hexsha
stringlengths
40
40
size
int64
2
1.02M
ext
stringclasses
10 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
4
245
max_stars_repo_name
stringlengths
6
130
max_stars_repo_head_hexsha
stringlengths
40
40
max_stars_repo_licenses
listlengths
1
10
max_stars_count
int64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
4
245
max_issues_repo_name
stringlengths
6
130
max_issues_repo_head_hexsha
stringlengths
40
40
max_issues_repo_licenses
listlengths
1
10
max_issues_count
int64
1
67k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
4
245
max_forks_repo_name
stringlengths
6
130
max_forks_repo_head_hexsha
stringlengths
40
40
max_forks_repo_licenses
listlengths
1
10
max_forks_count
int64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
2
1.02M
avg_line_length
float64
1
417k
max_line_length
int64
1
987k
alphanum_fraction
float64
0
1
content_no_comment
stringlengths
0
1.01M
is_comment_constant_removed
bool
1 class
is_sharp_comment_removed
bool
1 class
1c3901ca5ab816802d479374ebb2045f07d00596
2,584
py
Python
whyis_classifier/test_whyis_classifier.py
roryschadler/whyis_classifier
e0c41fb2b01311c40979764265b79fd7bd771794
[ "MIT" ]
null
null
null
whyis_classifier/test_whyis_classifier.py
roryschadler/whyis_classifier
e0c41fb2b01311c40979764265b79fd7bd771794
[ "MIT" ]
null
null
null
whyis_classifier/test_whyis_classifier.py
roryschadler/whyis_classifier
e0c41fb2b01311c40979764265b79fd7bd771794
[ "MIT" ]
null
null
null
""" Provides a testing framework for the Classifier Agent.""" from rdflib import * from rdflib.namespace import RDF from whyis_classifier import classifier_agent as ca from whyis_classifier import testclassifier from whyis_classifier import whyisclassifier from whyis import nanopub from whyis.test.agent_unit_test_case import AgentUnitTestCase from whyis.namespace import sio class ClassifierAgentTestCase(AgentUnitTestCase): def test_positive_classifier(self): np = nanopub.Nanopublication() np.assertion.parse(data='''{ "@id": "http://test.org/test_data", "@type": [ "http://nanomine.org/ns/PolymerNanocomposite", "http://test.org/PNC" ] }''', format="json-ld") # print(np.serialize(format="trig")) agent = ca.Classifier() # replace any user-defined classifiers with test classifier agent.classifiers = {'test_classifier': testclassifier.TestClassifier()} results = self.run_agent(agent, nanopublication=np) self.assertEquals(len(results), 1) # print(results[0].serialize(format='trig')) labeled_correctly = False confidence = None if results[0].resource(URIRef("http://test.org/test_data"))[RDF.type : URIRef("http://test.org/ItsAPNC")]: labeled_correctly = True for conf in results[0].objects(subject=None, predicate=sio.SIO_000638): confidence = conf.value self.assertEquals(confidence, 1) self.assertTrue(labeled_correctly) def test_negative_classifier(self): np = nanopub.Nanopublication() np.assertion.parse(data='''{ "@id": "http://test.org/test_data", "@type": [ "http://nanomine.org/ns/PolymerNanocomposite" ] }''', format="json-ld") # print(np.serialize(format="trig")) agent = ca.Classifier() # replace any user-defined classifiers with test classifier agent.classifiers = {'test_classifier': testclassifier.TestClassifier()} results = self.run_agent(agent, nanopublication=np) self.assertEquals(len(results), 1) # print(results[0].serialize(format='trig')) labeled_correctly = False confidence = None if results[0].resource(URIRef("http://test.org/test_data"))[RDF.type : URIRef("http://test.org/NotAPNC")]: labeled_correctly = True for conf in results[0].objects(subject=None, predicate=sio.SIO_000638): confidence = conf.value self.assertIsNone(confidence) self.assertTrue(labeled_correctly)
39.151515
114
0.664861
from rdflib import * from rdflib.namespace import RDF from whyis_classifier import classifier_agent as ca from whyis_classifier import testclassifier from whyis_classifier import whyisclassifier from whyis import nanopub from whyis.test.agent_unit_test_case import AgentUnitTestCase from whyis.namespace import sio class ClassifierAgentTestCase(AgentUnitTestCase): def test_positive_classifier(self): np = nanopub.Nanopublication() np.assertion.parse(data='''{ "@id": "http://test.org/test_data", "@type": [ "http://nanomine.org/ns/PolymerNanocomposite", "http://test.org/PNC" ] }''', format="json-ld") agent = ca.Classifier() agent.classifiers = {'test_classifier': testclassifier.TestClassifier()} results = self.run_agent(agent, nanopublication=np) self.assertEquals(len(results), 1) labeled_correctly = False confidence = None if results[0].resource(URIRef("http://test.org/test_data"))[RDF.type : URIRef("http://test.org/ItsAPNC")]: labeled_correctly = True for conf in results[0].objects(subject=None, predicate=sio.SIO_000638): confidence = conf.value self.assertEquals(confidence, 1) self.assertTrue(labeled_correctly) def test_negative_classifier(self): np = nanopub.Nanopublication() np.assertion.parse(data='''{ "@id": "http://test.org/test_data", "@type": [ "http://nanomine.org/ns/PolymerNanocomposite" ] }''', format="json-ld") agent = ca.Classifier() agent.classifiers = {'test_classifier': testclassifier.TestClassifier()} results = self.run_agent(agent, nanopublication=np) self.assertEquals(len(results), 1) labeled_correctly = False confidence = None if results[0].resource(URIRef("http://test.org/test_data"))[RDF.type : URIRef("http://test.org/NotAPNC")]: labeled_correctly = True for conf in results[0].objects(subject=None, predicate=sio.SIO_000638): confidence = conf.value self.assertIsNone(confidence) self.assertTrue(labeled_correctly)
true
true
1c3902c997e7058ff982752470db9ce9e18556b9
21,647
py
Python
cirq/sim/simulator.py
davemc84/Cirq
713e016d32be99efb0fd4d3e6dbe6d9ca8421271
[ "Apache-2.0" ]
2
2019-04-02T09:16:28.000Z
2019-05-25T18:35:19.000Z
cirq/sim/simulator.py
babbush/Cirq
447b2c762cc2820dd28abb3bd2bc785d36bae39a
[ "Apache-2.0" ]
null
null
null
cirq/sim/simulator.py
babbush/Cirq
447b2c762cc2820dd28abb3bd2bc785d36bae39a
[ "Apache-2.0" ]
null
null
null
# Copyright 2018 The Cirq Developers # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Abstract base classes for different types of simulators. Simulator types include: SimulatesSamples: mimics the interface of quantum hardware. SimulatesFinalState: allows access to the final state of the simulation. SimulatesIntermediateState: allows for access to the state of the simulation as the simulation iterates through the moments of a cirq. """ from typing import ( Any, Dict, Hashable, Iterator, List, Tuple, Union, Optional) import abc import collections import numpy as np from cirq import circuits, ops, protocols, schedules, study, value from cirq.sim import sampler class SimulatesSamples(sampler.Sampler, metaclass=abc.ABCMeta): """Simulator that mimics running on quantum hardware. Implementors of this interface should implement the _run method. """ def run_sweep( self, program: Union[circuits.Circuit, schedules.Schedule], params: study.Sweepable, repetitions: int = 1, ) -> List[study.TrialResult]: """Runs the supplied Circuit or Schedule, mimicking quantum hardware. In contrast to run, this allows for sweeping over different parameter values. Args: program: The circuit or schedule to simulate. params: Parameters to run with the program. repetitions: The number of repetitions to simulate. Returns: TrialResult list for this run; one for each possible parameter resolver. """ circuit = (program if isinstance(program, circuits.Circuit) else program.to_circuit()) param_resolvers = study.to_resolvers(params) trial_results = [] # type: List[study.TrialResult] for param_resolver in param_resolvers: measurements = self._run(circuit=circuit, param_resolver=param_resolver, repetitions=repetitions) trial_results.append(study.TrialResult(params=param_resolver, repetitions=repetitions, measurements=measurements)) return trial_results @abc.abstractmethod def _run( self, circuit: circuits.Circuit, param_resolver: study.ParamResolver, repetitions: int ) -> Dict[str, np.ndarray]: """Run a simulation, mimicking quantum hardware. Args: circuit: The circuit to simulate. param_resolver: Parameters to run with the program. repetitions: Number of times to repeat the run. Returns: A dictionary from measurement gate key to measurement results. Measurement results are stored in a 2-dimensional numpy array, the first dimension corresponding to the repetition and the second to the actual boolean measurement results (ordered by the qubits being measured.) """ raise NotImplementedError() def compute_samples_displays( self, program: Union[circuits.Circuit, schedules.Schedule], param_resolver: 'study.ParamResolverOrSimilarType' = None, ) -> study.ComputeDisplaysResult: """Computes SamplesDisplays in the supplied Circuit or Schedule. Args: program: The circuit or schedule to simulate. param_resolver: Parameters to run with the program. Returns: ComputeDisplaysResult for the simulation. """ return self.compute_samples_displays_sweep( program, study.ParamResolver(param_resolver))[0] def compute_samples_displays_sweep( self, program: Union[circuits.Circuit, schedules.Schedule], params: Optional[study.Sweepable] = None ) -> List[study.ComputeDisplaysResult]: """Computes SamplesDisplays in the supplied Circuit or Schedule. In contrast to `compute_displays`, this allows for sweeping over different parameter values. Args: program: The circuit or schedule to simulate. params: Parameters to run with the program. Returns: List of ComputeDisplaysResults for this run, one for each possible parameter resolver. """ circuit = (program if isinstance(program, circuits.Circuit) else program.to_circuit()) param_resolvers = study.to_resolvers(params or study.ParamResolver({})) compute_displays_results = [] # type: List[study.ComputeDisplaysResult] for param_resolver in param_resolvers: display_values = {} # type: Dict[Hashable, Any] preceding_circuit = circuits.Circuit() for i, moment in enumerate(circuit): displays = (op for op in moment if isinstance(op, ops.SamplesDisplay)) for display in displays: measurement_key = str(display.key) measurement_circuit = circuits.Circuit.from_ops( display.measurement_basis_change(), ops.measure(*display.qubits, key=measurement_key) ) measurements = self._run( preceding_circuit + measurement_circuit, param_resolver, display.num_samples) display_values[display.key] = ( display.value_derived_from_samples( measurements[measurement_key])) preceding_circuit.append(circuit[i]) compute_displays_results.append(study.ComputeDisplaysResult( params=param_resolver, display_values=display_values)) return compute_displays_results class SimulatesFinalState(metaclass=abc.ABCMeta): """Simulator that allows access to a quantum computer's final state. Implementors of this interface should implement the simulate_sweep method. This simulator only returns the state of the quantum system for the final step of a simulation. This simulator state may be a wave function, the density matrix, or another representation, depending on the implementation. For simulators that also allow stepping through a circuit see `SimulatesIntermediateState`. """ def simulate( self, program: Union[circuits.Circuit, schedules.Schedule], param_resolver: 'study.ParamResolverOrSimilarType' = None, qubit_order: ops.QubitOrderOrList = ops.QubitOrder.DEFAULT, initial_state: Any = None, ) -> 'SimulationTrialResult': """Simulates the supplied Circuit or Schedule. This method returns a result which allows access to the entire wave function. Args: program: The circuit or schedule to simulate. param_resolver: Parameters to run with the program. qubit_order: Determines the canonical ordering of the qubits. This is often used in specifying the initial state, i.e. the ordering of the computational basis states. initial_state: The initial state for the simulation. The form of this state depends on the simulation implementation. See documentation of the implementing class for details. Returns: SimulationTrialResults for the simulation. Includes the final state. """ return self.simulate_sweep( program, study.ParamResolver(param_resolver), qubit_order, initial_state)[0] @abc.abstractmethod def simulate_sweep( self, program: Union[circuits.Circuit, schedules.Schedule], params: study.Sweepable, qubit_order: ops.QubitOrderOrList = ops.QubitOrder.DEFAULT, initial_state: Any = None, ) -> List['SimulationTrialResult']: """Simulates the supplied Circuit or Schedule. This method returns a result which allows access to the entire wave function. In contrast to simulate, this allows for sweeping over different parameter values. Args: program: The circuit or schedule to simulate. params: Parameters to run with the program. qubit_order: Determines the canonical ordering of the qubits. This is often used in specifying the initial state, i.e. the ordering of the computational basis states. initial_state: The initial state for the simulation. The form of this state depends on the simulation implementation. See documentation of the implementing class for details. Returns: List of SimulationTrialResults for this run, one for each possible parameter resolver. """ raise NotImplementedError() class SimulatesIntermediateState(SimulatesFinalState, metaclass=abc.ABCMeta): """A SimulatesFinalState that simulates a circuit by moments. Whereas a general SimulatesFinalState may return the entire wave function at the end of a circuit, a SimulatesIntermediateState can simulate stepping through the moments of a circuit. Implementors of this interface should implement the _simulator_iterator method. """ def simulate_sweep( self, program: Union[circuits.Circuit, schedules.Schedule], params: study.Sweepable, qubit_order: ops.QubitOrderOrList = ops.QubitOrder.DEFAULT, initial_state: Any = None, ) -> List['SimulationTrialResult']: """Simulates the supplied Circuit or Schedule. This method returns a result which allows access to the entire wave function. In contrast to simulate, this allows for sweeping over different parameter values. Args: program: The circuit or schedule to simulate. params: Parameters to run with the program. qubit_order: Determines the canonical ordering of the qubits. This is often used in specifying the initial state, i.e. the ordering of the computational basis states. initial_state: The initial state for the simulation. The form of this state depends on the simulation implementation. See documentation of the implementing class for details. Returns: List of SimulationTrialResults for this run, one for each possible parameter resolver. """ circuit = (program if isinstance(program, circuits.Circuit) else program.to_circuit()) param_resolvers = study.to_resolvers(params) trial_results = [] qubit_order = ops.QubitOrder.as_qubit_order(qubit_order) for param_resolver in param_resolvers: all_step_results = self.simulate_moment_steps(circuit, param_resolver, qubit_order, initial_state) measurements = {} # type: Dict[str, np.ndarray] for step_result in all_step_results: for k, v in step_result.measurements.items(): measurements[k] = np.array(v, dtype=bool) trial_results.append( self._create_simulator_trial_result( params=param_resolver, measurements=measurements, final_simulator_state=step_result.simulator_state())) return trial_results def simulate_moment_steps( self, circuit: circuits.Circuit, param_resolver: 'study.ParamResolverOrSimilarType' = None, qubit_order: ops.QubitOrderOrList = ops.QubitOrder.DEFAULT, initial_state: Any = None ) -> Iterator: """Returns an iterator of StepResults for each moment simulated. If the circuit being simulated is empty, a single step result should be returned with the state being set to the initial state. Args: circuit: The Circuit to simulate. param_resolver: A ParamResolver for determining values of Symbols. qubit_order: Determines the canonical ordering of the qubits. This is often used in specifying the initial state, i.e. the ordering of the computational basis states. initial_state: The initial state for the simulation. The form of this state depends on the simulation implementation. See documentation of the implementing class for details. Returns: Iterator that steps through the simulation, simulating each moment and returning a StepResult for each moment. """ return self._simulator_iterator( circuit, study.ParamResolver(param_resolver), qubit_order, initial_state) @abc.abstractmethod def _simulator_iterator( self, circuit: circuits.Circuit, param_resolver: study.ParamResolver, qubit_order: ops.QubitOrderOrList, initial_state: Any, ) -> Iterator: """Iterator over StepResult from Moments of a Circuit. Args: circuit: The circuit to simulate. param_resolver: A ParamResolver for determining values of Symbols. qubit_order: Determines the canonical ordering of the qubits. This is often used in specifying the initial state, i.e. the ordering of the computational basis states. initial_state: The initial state for the simulation. The form of this state depends on the simulation implementation. See documentation of the implementing class for details. Yields: StepResults from simulating a Moment of the Circuit. """ raise NotImplementedError() def _create_simulator_trial_result(self, params: study.ParamResolver, measurements: Dict[str, np.ndarray], final_simulator_state: Any) \ -> 'SimulationTrialResult': """This method can be overridden to creation of a trial result. Args: params: The ParamResolver for this trial. measurements: The measurement results for this trial. final_simulator_state: The final state of the simulator for the StepResult. Returns: The SimulationTrialResult. """ return SimulationTrialResult( params=params, measurements=measurements, final_simulator_state=final_simulator_state) class StepResult(metaclass=abc.ABCMeta): """Results of a step of a SimulatesIntermediateState. Attributes: measurements: A dictionary from measurement gate key to measurement results, ordered by the qubits that the measurement operates on. """ def __init__(self, measurements: Optional[Dict[str, List[bool]]] = None) -> None: self.measurements = measurements or collections.defaultdict(list) @abc.abstractmethod def simulator_state(self) -> Any: """Returns the simulator_state of the simulator after this step. The form of the simulator_state depends on the implementation of the simulation,see documentation for the implementing class for the form of details. """ @abc.abstractmethod def sample(self, qubits: List[ops.Qid], repetitions: int = 1) -> np.ndarray: """Samples from the system at this point in the computation. Note that this does not collapse the wave function. Args: qubits: The qubits to be sampled in an order that influence the returned measurement results. repetitions: The number of samples to take. Returns: Measurement results with True corresponding to the ``|1⟩`` state. The outer list is for repetitions, and the inner corresponds to measurements ordered by the supplied qubits. These lists are wrapped as an numpy ndarray. """ raise NotImplementedError() def sample_measurement_ops( self, measurement_ops: List[ops.GateOperation], repetitions: int = 1) -> Dict[str, np.ndarray]: """Samples from the system at this point in the computation. Note that this does not collapse the wave function. In contrast to `sample` which samples qubits, this takes a list of `cirq.GateOperation` instances whose gates are `cirq.MeasurementGate` instances and then returns a mapping from the key in the measurement gate to the resulting bit strings. Different measurement operations must not act on the same qubits. Args: measurement_ops: `GateOperation` instances whose gates are `MeasurementGate` instances to be sampled form. repetitions: The number of samples to take. Returns: A dictionary from measurement gate key to measurement results. Measurement results are stored in a 2-dimensional numpy array, the first dimension corresponding to the repetition and the second to the actual boolean measurement results (ordered by the qubits being measured.) Raises: ValueError: If the operation's gates are not `MeasurementGate` instances or a qubit is acted upon multiple times by different operations from `measurement_ops`. """ bounds = {} # type: Dict[str, Tuple] all_qubits = [] # type: List[ops.Qid] current_index = 0 for op in measurement_ops: gate = op.gate if not isinstance(gate, ops.MeasurementGate): raise ValueError('{} was not a MeasurementGate'.format(gate)) key = protocols.measurement_key(gate) if key in bounds: raise ValueError( 'Duplicate MeasurementGate with key {}'.format(key)) bounds[key] = (current_index, current_index + len(op.qubits)) all_qubits.extend(op.qubits) current_index += len(op.qubits) indexed_sample = self.sample(all_qubits, repetitions) return {k: np.array([x[s:e] for x in indexed_sample]) for k, (s, e) in bounds.items()} @value.value_equality(unhashable=True) class SimulationTrialResult: """Results of a simulation by a SimulatesFinalState. Unlike TrialResult these results contain the final simulator_state of the system. This simulator_state is dependent on the simulation implementation and may be, for example, the wave function of the system or the density matrix of the system. Attributes: params: A ParamResolver of settings used for this result. measurements: A dictionary from measurement gate key to measurement results. Measurement results are a numpy ndarray of actual boolean measurement results (ordered by the qubits acted on by the measurement gate.) final_simulator_state: The final simulator state of the system after the trial finishes. """ def __init__(self, params: study.ParamResolver, measurements: Dict[str, np.ndarray], final_simulator_state: Any) -> None: self.params = params self.measurements = measurements self.final_simulator_state = final_simulator_state def __repr__(self): return ( 'cirq.SimulationTrialResult(params={!r}, ' 'measurements={!r}, ' 'final_simulator_state={!r})').format( self.params, self.measurements, self.final_simulator_state) def __str__(self): def bitstring(vals): return ''.join('1' if v else '0' for v in vals) results = sorted( [(key, bitstring(val)) for key, val in self.measurements.items()]) if not results: return '(no measurements)' return ' '.join( ['{}={}'.format(key, val) for key, val in results]) def _repr_pretty_(self, p: Any, cycle: bool) -> None: """Text output in Jupyter.""" if cycle: # There should never be a cycle. This is just in case. p.text('SimulationTrialResult(...)') else: p.text(str(self)) def _value_equality_values_(self): measurements = {k: v.tolist() for k, v in sorted(self.measurements.items())} return (self.params, measurements, self.final_simulator_state)
40.613508
80
0.633714
from typing import ( Any, Dict, Hashable, Iterator, List, Tuple, Union, Optional) import abc import collections import numpy as np from cirq import circuits, ops, protocols, schedules, study, value from cirq.sim import sampler class SimulatesSamples(sampler.Sampler, metaclass=abc.ABCMeta): def run_sweep( self, program: Union[circuits.Circuit, schedules.Schedule], params: study.Sweepable, repetitions: int = 1, ) -> List[study.TrialResult]: circuit = (program if isinstance(program, circuits.Circuit) else program.to_circuit()) param_resolvers = study.to_resolvers(params) trial_results = [] for param_resolver in param_resolvers: measurements = self._run(circuit=circuit, param_resolver=param_resolver, repetitions=repetitions) trial_results.append(study.TrialResult(params=param_resolver, repetitions=repetitions, measurements=measurements)) return trial_results @abc.abstractmethod def _run( self, circuit: circuits.Circuit, param_resolver: study.ParamResolver, repetitions: int ) -> Dict[str, np.ndarray]: raise NotImplementedError() def compute_samples_displays( self, program: Union[circuits.Circuit, schedules.Schedule], param_resolver: 'study.ParamResolverOrSimilarType' = None, ) -> study.ComputeDisplaysResult: return self.compute_samples_displays_sweep( program, study.ParamResolver(param_resolver))[0] def compute_samples_displays_sweep( self, program: Union[circuits.Circuit, schedules.Schedule], params: Optional[study.Sweepable] = None ) -> List[study.ComputeDisplaysResult]: circuit = (program if isinstance(program, circuits.Circuit) else program.to_circuit()) param_resolvers = study.to_resolvers(params or study.ParamResolver({})) compute_displays_results = [] for param_resolver in param_resolvers: display_values = {} preceding_circuit = circuits.Circuit() for i, moment in enumerate(circuit): displays = (op for op in moment if isinstance(op, ops.SamplesDisplay)) for display in displays: measurement_key = str(display.key) measurement_circuit = circuits.Circuit.from_ops( display.measurement_basis_change(), ops.measure(*display.qubits, key=measurement_key) ) measurements = self._run( preceding_circuit + measurement_circuit, param_resolver, display.num_samples) display_values[display.key] = ( display.value_derived_from_samples( measurements[measurement_key])) preceding_circuit.append(circuit[i]) compute_displays_results.append(study.ComputeDisplaysResult( params=param_resolver, display_values=display_values)) return compute_displays_results class SimulatesFinalState(metaclass=abc.ABCMeta): def simulate( self, program: Union[circuits.Circuit, schedules.Schedule], param_resolver: 'study.ParamResolverOrSimilarType' = None, qubit_order: ops.QubitOrderOrList = ops.QubitOrder.DEFAULT, initial_state: Any = None, ) -> 'SimulationTrialResult': return self.simulate_sweep( program, study.ParamResolver(param_resolver), qubit_order, initial_state)[0] @abc.abstractmethod def simulate_sweep( self, program: Union[circuits.Circuit, schedules.Schedule], params: study.Sweepable, qubit_order: ops.QubitOrderOrList = ops.QubitOrder.DEFAULT, initial_state: Any = None, ) -> List['SimulationTrialResult']: raise NotImplementedError() class SimulatesIntermediateState(SimulatesFinalState, metaclass=abc.ABCMeta): def simulate_sweep( self, program: Union[circuits.Circuit, schedules.Schedule], params: study.Sweepable, qubit_order: ops.QubitOrderOrList = ops.QubitOrder.DEFAULT, initial_state: Any = None, ) -> List['SimulationTrialResult']: circuit = (program if isinstance(program, circuits.Circuit) else program.to_circuit()) param_resolvers = study.to_resolvers(params) trial_results = [] qubit_order = ops.QubitOrder.as_qubit_order(qubit_order) for param_resolver in param_resolvers: all_step_results = self.simulate_moment_steps(circuit, param_resolver, qubit_order, initial_state) measurements = {} for step_result in all_step_results: for k, v in step_result.measurements.items(): measurements[k] = np.array(v, dtype=bool) trial_results.append( self._create_simulator_trial_result( params=param_resolver, measurements=measurements, final_simulator_state=step_result.simulator_state())) return trial_results def simulate_moment_steps( self, circuit: circuits.Circuit, param_resolver: 'study.ParamResolverOrSimilarType' = None, qubit_order: ops.QubitOrderOrList = ops.QubitOrder.DEFAULT, initial_state: Any = None ) -> Iterator: return self._simulator_iterator( circuit, study.ParamResolver(param_resolver), qubit_order, initial_state) @abc.abstractmethod def _simulator_iterator( self, circuit: circuits.Circuit, param_resolver: study.ParamResolver, qubit_order: ops.QubitOrderOrList, initial_state: Any, ) -> Iterator: raise NotImplementedError() def _create_simulator_trial_result(self, params: study.ParamResolver, measurements: Dict[str, np.ndarray], final_simulator_state: Any) \ -> 'SimulationTrialResult': return SimulationTrialResult( params=params, measurements=measurements, final_simulator_state=final_simulator_state) class StepResult(metaclass=abc.ABCMeta): def __init__(self, measurements: Optional[Dict[str, List[bool]]] = None) -> None: self.measurements = measurements or collections.defaultdict(list) @abc.abstractmethod def simulator_state(self) -> Any: @abc.abstractmethod def sample(self, qubits: List[ops.Qid], repetitions: int = 1) -> np.ndarray: raise NotImplementedError() def sample_measurement_ops( self, measurement_ops: List[ops.GateOperation], repetitions: int = 1) -> Dict[str, np.ndarray]: bounds = {} all_qubits = [] current_index = 0 for op in measurement_ops: gate = op.gate if not isinstance(gate, ops.MeasurementGate): raise ValueError('{} was not a MeasurementGate'.format(gate)) key = protocols.measurement_key(gate) if key in bounds: raise ValueError( 'Duplicate MeasurementGate with key {}'.format(key)) bounds[key] = (current_index, current_index + len(op.qubits)) all_qubits.extend(op.qubits) current_index += len(op.qubits) indexed_sample = self.sample(all_qubits, repetitions) return {k: np.array([x[s:e] for x in indexed_sample]) for k, (s, e) in bounds.items()} @value.value_equality(unhashable=True) class SimulationTrialResult: def __init__(self, params: study.ParamResolver, measurements: Dict[str, np.ndarray], final_simulator_state: Any) -> None: self.params = params self.measurements = measurements self.final_simulator_state = final_simulator_state def __repr__(self): return ( 'cirq.SimulationTrialResult(params={!r}, ' 'measurements={!r}, ' 'final_simulator_state={!r})').format( self.params, self.measurements, self.final_simulator_state) def __str__(self): def bitstring(vals): return ''.join('1' if v else '0' for v in vals) results = sorted( [(key, bitstring(val)) for key, val in self.measurements.items()]) if not results: return '(no measurements)' return ' '.join( ['{}={}'.format(key, val) for key, val in results]) def _repr_pretty_(self, p: Any, cycle: bool) -> None: if cycle: p.text('SimulationTrialResult(...)') else: p.text(str(self)) def _value_equality_values_(self): measurements = {k: v.tolist() for k, v in sorted(self.measurements.items())} return (self.params, measurements, self.final_simulator_state)
true
true
1c3903d9c614c2f662c464f37994e6c31336906e
167
py
Python
python/8kyu/opposites_attracks.py
Sigmanificient/codewars
b34df4bf55460d312b7ddf121b46a707b549387a
[ "MIT" ]
3
2021-06-08T01:57:13.000Z
2021-06-26T10:52:47.000Z
python/8kyu/opposites_attracks.py
Sigmanificient/codewars
b34df4bf55460d312b7ddf121b46a707b549387a
[ "MIT" ]
null
null
null
python/8kyu/opposites_attracks.py
Sigmanificient/codewars
b34df4bf55460d312b7ddf121b46a707b549387a
[ "MIT" ]
2
2021-06-10T21:20:13.000Z
2021-06-30T10:13:26.000Z
"""Kata url: https://www.codewars.com/kata/555086d53eac039a2a000083.""" def lovefunc(flower1: int, flower2: int) -> bool: return bool(flower1 % 2 - flower2 % 2)
27.833333
71
0.688623
def lovefunc(flower1: int, flower2: int) -> bool: return bool(flower1 % 2 - flower2 % 2)
true
true
1c3903ef11cf30ab618c0f857e68e2d515607a88
11,794
py
Python
matched_markets_fixed/utils.py
ntellakula/fixed_matched_markets
187827e614f398d414019a68ec093a39ca8fadfd
[ "MIT" ]
null
null
null
matched_markets_fixed/utils.py
ntellakula/fixed_matched_markets
187827e614f398d414019a68ec093a39ca8fadfd
[ "MIT" ]
null
null
null
matched_markets_fixed/utils.py
ntellakula/fixed_matched_markets
187827e614f398d414019a68ec093a39ca8fadfd
[ "MIT" ]
null
null
null
# Copyright 2020 Google LLC. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================ """Generic utility functions.""" import random import re from typing import List import altair as alt from matched_markets_fixed.methodology import common_classes import numpy as np import pandas as pd from pandas.api.types import is_numeric_dtype TimeWindow = common_classes.TimeWindow def kwarg_subdict(prefix, **kwargs): """Extract sub dict of `kwargs` prefixed by `prefix`, stripping `prefix`. E.g. kwarg_subdict('a', a_x=1, a_y=2, b_z=3) # returns {x:1, y:2} Args: prefix: a string specifying the prefix to search for in the kwarg names. **kwargs: any number of named arguments. Returns: A subset of the supplied kwargs in the form of a dictionary. """ # Define a regex to match the prefix. rgx = re.compile(r'%s(.*)' % prefix) # Extract the kwargs which match the regex. sub_kwargs = [k for k in kwargs.keys() if rgx.search(k)] # Return the matched kwargs, stripping off prefix. return {rgx.match(k).group(1): kwargs[k] for k in sub_kwargs} def float_order(x): """Calculates the order of magnitude of x.""" abs_x = np.abs(x) if abs_x > 0: return np.floor(np.log10(abs_x)) else: return -np.inf def randomize_strata(n_items, group_ids, seed=None): """Perform stratified randomization. Maps a number of items into group ids by dividing the items into strata of length equal to the number of groups, then assigning the group ids randomly within each strata. If the number of items do not divide the number of groups equally, the remaining items are assigned to groups randomly (with equal probability of assignment in each group). Example: randomize_strata(12, [1, 2, 3]) yields a list of 12 group ids, each 1, 2, or 3. There are (3!)^4 = 6^4 = 1296 possible outcomes as there are 12 / 3 = 4 strata, and within each strata there are 3! = 6 different ways to assign the items into groups. Therefore, the first 3 items of the list (that is, positions 0, 1, and 2) can be mapped only to the 3!=6 different mappings: [1, 2, 3], [1, 3, 2], [2, 1, 3], [2, 3, 1], [3, 1, 2] or [3, 2, 1]. Args: n_items: (int) Number of items to assign to groups. group_ids: A list of group ids that are typically integers or strings, but can be of any type. seed: (int) Random seed, applied to a local instance of class random.Random; if not specified, the global random instance is used instead. Returns: A list of length n_items, consisting of the group ids whose positions in the list correspond to the items. """ if seed is None: random_sampler = random.sample else: random_sampler = random.Random(seed).sample n_groups = len(group_ids) n_strata = n_items // n_groups groups = [] for _ in range(n_strata): groups.extend(random_sampler(group_ids, n_groups)) remaining = n_items - len(groups) if remaining > 0: groups.extend(random_sampler(group_ids, remaining)) return groups def brownian_bridge_bounds(n, sd_bound_multiplier): """Obtain bounds of cumulative residuals from Brownian Bridge process. The bounds for variance are proportional to t * (n - t) / n for residuals t = 1 .. n (for residual n, the bound is zero as the sum of residuals is always zero). This function returns the bounds for the standard deviation. Args: n: (int >= 1) Length of the time series of the cumulative residuals following a Brownian Bridge process. sd_bound_multiplier: (numeric > 0) Multiplier for bounds on cumulative standardized residuals. Returns: A list of length n, of the Brownian Bridge process bounds in absolute values (if n == 1, returns [0]). """ if n < 1: raise ValueError('n must be >= 1') if sd_bound_multiplier <= 0: raise ValueError('sd_bound_multiplier must be > 0') n_range = np.arange(1, n + 1) # 1, ..., n. bounds = sd_bound_multiplier * np.sqrt(n_range * (1.0 - n_range / float(n))) return bounds.tolist() def credible_interval(simulations, level): """Construct the (1 - level, 0.5, level) central interval from simulations. Args: simulations: numeric arraylike. The simulations. level: float in (0, 1). The mass of the desired interval. Returns: An np.array representing the central credible interval at the given level. Raises: ValueError: if the requested level is too large (< 1/ len(sims)). """ alpha = (1 - level)/2.0 nvals = len(simulations) if alpha < 1.0/nvals: raise ValueError('Too few values to provide requested quantiles.') sims_sort = np.sort(np.copy(simulations)) frac = nvals * np.array([alpha, 0.5, 1.0 - alpha]) - 1.0 low = np.floor(frac).astype(np.int64) return sims_sort[low] + (frac - low)*(sims_sort[low + 1] - sims_sort[low]) def find_days_to_exclude( dates_to_exclude: List[str]) -> List[TimeWindow]: """Returns a list of time windows to exclude from a list of days and periods. Args: dates_to_exclude: a List of strings with format indicating a single day as '2020/01/01' (YYYY/MM/DD) or an entire time period as '2020/01/01 - 2020/02/01' (indicating start and end date of the time period) Returns: days_exclude: a List of TimeWindows obtained from the list in input. """ days_exclude = [] for x in dates_to_exclude: tmp = x.split('-') if len(tmp) == 1: try: days_exclude.append( TimeWindow(pd.Timestamp(tmp[0]), pd.Timestamp(tmp[0]))) except ValueError: raise ValueError(f'Cannot convert the string {tmp[0]} to a valid date.') elif len(tmp) == 2: try: days_exclude.append( TimeWindow(pd.Timestamp(tmp[0]), pd.Timestamp(tmp[1]))) except ValueError: raise ValueError( f'Cannot convert the strings in {tmp} to a valid date.') else: raise ValueError(f'The input {tmp} cannot be interpreted as a single' + ' day or a time window') return days_exclude def expand_time_windows(periods: List[TimeWindow]) -> List[pd.Timestamp]: """Return a list of days to exclude from a list of TimeWindows. Args: periods: List of time windows (first day, last day). Returns: days_exclude: a List of obtained by expanding the list in input. """ days_exclude = [] for window in periods: days_exclude += pd.date_range(window.first_day, window.last_day, freq='D') return list(set(days_exclude)) def human_readable_number(number: float) -> str: """Print a large number in a readable format. Return a readable format for a number, e.g. 123 milions becomes 123M. Args: number: a float to be printed in human readable format. Returns: readable_number: a string containing the formatted number. """ number = float('{:.3g}'.format(number)) magnitude = 0 while abs(number) >= 1000 and magnitude < 4: magnitude += 1 number /= 1000.0 readable_number = '{}{}'.format('{:f}'.format(number).rstrip('0').rstrip('.'), ['', 'K', 'M', 'B', 'tn'][magnitude]) return readable_number def default_geo_assignment(geo_level_time_series: pd.DataFrame, geo_eligibility: pd.DataFrame) -> pd.DataFrame: """Set the default assignment eligibility for missing geos. Geos missing in the geo assignment table but present in the geo level time series are considered unconstrained. So, they can be assigned to either treatment, control, or excluded. Args: geo_level_time_series: table containing the response time series at geo level. geo_eligibility: table containing the possible assignments for some of the geos. Returns: a table containing the possible assignments for all geos in geo_level_time_series. """ if not is_numeric_dtype(geo_level_time_series['geo']): geo_level_time_series['geo'] = pd.to_numeric(geo_level_time_series['geo']) if not is_numeric_dtype(geo_eligibility['geo']): geo_eligibility['geo'] = pd.to_numeric(geo_eligibility['geo']) missing_geos = list( set(geo_level_time_series['geo']) - set(geo_eligibility['geo'])) return geo_eligibility.append( pd.DataFrame({ 'geo': missing_geos, 'control': 1, 'treatment': 1, 'exclude': 1 })).sort_values(by='geo').reset_index(drop=True) def plot_iroas_over_time(iroas_df: pd.DataFrame, experiment_dates: pd.DataFrame, cooldown_date: pd.DataFrame): """Returns a chart of the iROAS estimate over time with confidence bands. This function provides a visualization of the evolution of the iROAS estimate over the duration of the experiment and cooldown, together with confidence bands. Args: iroas_df: a dataframe with columns: date, lower, mean, upper experiment_dates: dataframe with columns (date, color) which contains two dates for each period (start, end), and the column color is the label used in the chart to refer to the corresponding period, e.g. "Experiment period" or "Pretes period". cooldown_date: dataframe with column (date, color) with only one entry, where date indicates the last day in the cooldown period, and color is the label used in the plot legend, e.g. "End of cooldown period". Returns: iroas_chart: Chart containing the plot. """ iroas_base = alt.Chart(iroas_df).mark_line().encode( x=alt.X('date:T', axis=alt.Axis(title='', format=('%b %e')))) iroas_selection = alt.selection_single( fields=['date'], nearest=True, on='mouseover', empty='none', clear='mouseout') iroas_lines = iroas_base.mark_line().encode( y=alt.Y('mean:Q', axis=alt.Axis(title=' ', format='.3'))) iroas_points = iroas_lines.mark_point().transform_filter(iroas_selection) iroas_rule1 = iroas_base.mark_rule().encode( tooltip=['date:T', 'mean:Q', 'lower:Q', 'upper:Q']) iroas_rule = iroas_rule1.encode( opacity=alt.condition(iroas_selection, alt.value(0.3), alt.value( 0))).add_selection(iroas_selection) iroas_ci_bands_rule = alt.Chart(iroas_df).mark_area(color='gray').encode( alt.X('date:T'), y='lower:Q', y2='upper:Q', opacity=alt.value(0.5)) date_rule = alt.Chart( experiment_dates[experiment_dates['color'] == 'Experiment period']).mark_rule(strokeWidth=2).encode( x='date:T', color=alt.Color( 'color', scale=alt.Scale( domain=[ 'Experiment period', 'End of cooldown period', 'iROAS estimate' ], range=['black', 'black', '#1f77b4']))) cooldown_date_rule = alt.Chart(cooldown_date).mark_rule( strokeWidth=2, strokeDash=[5, 2], color='black').encode( x='date:T', color='color:N') # Compile chart iroas_chart = alt.layer(iroas_lines, iroas_rule, iroas_points, date_rule, cooldown_date_rule, iroas_ci_bands_rule) return iroas_chart
38.292208
80
0.664151
import random import re from typing import List import altair as alt from matched_markets_fixed.methodology import common_classes import numpy as np import pandas as pd from pandas.api.types import is_numeric_dtype TimeWindow = common_classes.TimeWindow def kwarg_subdict(prefix, **kwargs): rgx = re.compile(r'%s(.*)' % prefix) sub_kwargs = [k for k in kwargs.keys() if rgx.search(k)] return {rgx.match(k).group(1): kwargs[k] for k in sub_kwargs} def float_order(x): abs_x = np.abs(x) if abs_x > 0: return np.floor(np.log10(abs_x)) else: return -np.inf def randomize_strata(n_items, group_ids, seed=None): if seed is None: random_sampler = random.sample else: random_sampler = random.Random(seed).sample n_groups = len(group_ids) n_strata = n_items // n_groups groups = [] for _ in range(n_strata): groups.extend(random_sampler(group_ids, n_groups)) remaining = n_items - len(groups) if remaining > 0: groups.extend(random_sampler(group_ids, remaining)) return groups def brownian_bridge_bounds(n, sd_bound_multiplier): if n < 1: raise ValueError('n must be >= 1') if sd_bound_multiplier <= 0: raise ValueError('sd_bound_multiplier must be > 0') n_range = np.arange(1, n + 1) bounds = sd_bound_multiplier * np.sqrt(n_range * (1.0 - n_range / float(n))) return bounds.tolist() def credible_interval(simulations, level): alpha = (1 - level)/2.0 nvals = len(simulations) if alpha < 1.0/nvals: raise ValueError('Too few values to provide requested quantiles.') sims_sort = np.sort(np.copy(simulations)) frac = nvals * np.array([alpha, 0.5, 1.0 - alpha]) - 1.0 low = np.floor(frac).astype(np.int64) return sims_sort[low] + (frac - low)*(sims_sort[low + 1] - sims_sort[low]) def find_days_to_exclude( dates_to_exclude: List[str]) -> List[TimeWindow]: days_exclude = [] for x in dates_to_exclude: tmp = x.split('-') if len(tmp) == 1: try: days_exclude.append( TimeWindow(pd.Timestamp(tmp[0]), pd.Timestamp(tmp[0]))) except ValueError: raise ValueError(f'Cannot convert the string {tmp[0]} to a valid date.') elif len(tmp) == 2: try: days_exclude.append( TimeWindow(pd.Timestamp(tmp[0]), pd.Timestamp(tmp[1]))) except ValueError: raise ValueError( f'Cannot convert the strings in {tmp} to a valid date.') else: raise ValueError(f'The input {tmp} cannot be interpreted as a single' + ' day or a time window') return days_exclude def expand_time_windows(periods: List[TimeWindow]) -> List[pd.Timestamp]: days_exclude = [] for window in periods: days_exclude += pd.date_range(window.first_day, window.last_day, freq='D') return list(set(days_exclude)) def human_readable_number(number: float) -> str: number = float('{:.3g}'.format(number)) magnitude = 0 while abs(number) >= 1000 and magnitude < 4: magnitude += 1 number /= 1000.0 readable_number = '{}{}'.format('{:f}'.format(number).rstrip('0').rstrip('.'), ['', 'K', 'M', 'B', 'tn'][magnitude]) return readable_number def default_geo_assignment(geo_level_time_series: pd.DataFrame, geo_eligibility: pd.DataFrame) -> pd.DataFrame: if not is_numeric_dtype(geo_level_time_series['geo']): geo_level_time_series['geo'] = pd.to_numeric(geo_level_time_series['geo']) if not is_numeric_dtype(geo_eligibility['geo']): geo_eligibility['geo'] = pd.to_numeric(geo_eligibility['geo']) missing_geos = list( set(geo_level_time_series['geo']) - set(geo_eligibility['geo'])) return geo_eligibility.append( pd.DataFrame({ 'geo': missing_geos, 'control': 1, 'treatment': 1, 'exclude': 1 })).sort_values(by='geo').reset_index(drop=True) def plot_iroas_over_time(iroas_df: pd.DataFrame, experiment_dates: pd.DataFrame, cooldown_date: pd.DataFrame): iroas_base = alt.Chart(iroas_df).mark_line().encode( x=alt.X('date:T', axis=alt.Axis(title='', format=('%b %e')))) iroas_selection = alt.selection_single( fields=['date'], nearest=True, on='mouseover', empty='none', clear='mouseout') iroas_lines = iroas_base.mark_line().encode( y=alt.Y('mean:Q', axis=alt.Axis(title=' ', format='.3'))) iroas_points = iroas_lines.mark_point().transform_filter(iroas_selection) iroas_rule1 = iroas_base.mark_rule().encode( tooltip=['date:T', 'mean:Q', 'lower:Q', 'upper:Q']) iroas_rule = iroas_rule1.encode( opacity=alt.condition(iroas_selection, alt.value(0.3), alt.value( 0))).add_selection(iroas_selection) iroas_ci_bands_rule = alt.Chart(iroas_df).mark_area(color='gray').encode( alt.X('date:T'), y='lower:Q', y2='upper:Q', opacity=alt.value(0.5)) date_rule = alt.Chart( experiment_dates[experiment_dates['color'] == 'Experiment period']).mark_rule(strokeWidth=2).encode( x='date:T', color=alt.Color( 'color', scale=alt.Scale( domain=[ 'Experiment period', 'End of cooldown period', 'iROAS estimate' ], range=['black', 'black', '#1f77b4']))) cooldown_date_rule = alt.Chart(cooldown_date).mark_rule( strokeWidth=2, strokeDash=[5, 2], color='black').encode( x='date:T', color='color:N') iroas_chart = alt.layer(iroas_lines, iroas_rule, iroas_points, date_rule, cooldown_date_rule, iroas_ci_bands_rule) return iroas_chart
true
true
1c3905c8a414bd1df7bcaf0c0e38c79c313ebff3
18,262
py
Python
tests/test_main.py
dstathis/charmcraft
d892b3f301dfeef8a9ba597be30d521a1f29a30e
[ "Apache-2.0" ]
null
null
null
tests/test_main.py
dstathis/charmcraft
d892b3f301dfeef8a9ba597be30d521a1f29a30e
[ "Apache-2.0" ]
null
null
null
tests/test_main.py
dstathis/charmcraft
d892b3f301dfeef8a9ba597be30d521a1f29a30e
[ "Apache-2.0" ]
null
null
null
# Copyright 2020-2021 Canonical 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. # # For further info, check https://github.com/canonical/charmcraft import argparse import io import os import pathlib import subprocess import sys from unittest.mock import patch from charmcraft import __version__, logsetup from charmcraft.main import Dispatcher, main, COMMAND_GROUPS from charmcraft.cmdbase import BaseCommand, CommandError from tests.factory import create_command import pytest @pytest.fixture(autouse=True) def mock_is_charmcraft_running_in_supported_environment(monkeypatch): """Bypass entry point check for running as snap.""" with patch( "charmcraft.env.is_charmcraft_running_in_supported_environment", return_value=True, ) as mock_supported: yield mock_supported # --- Tests for the Dispatcher def test_dispatcher_command_execution_ok(): """Command execution depends of the indicated name in command line, return code ok.""" class MyCommandControl(BaseCommand): help_msg = "some help" def run(self, parsed_args): self._executed.append(parsed_args) class MyCommand1(MyCommandControl): name = "name1" _executed = [] class MyCommand2(MyCommandControl): name = "name2" _executed = [] groups = [("test-group", "title", [MyCommand1, MyCommand2])] dispatcher = Dispatcher(["name2"], groups) dispatcher.run() assert MyCommand1._executed == [] assert isinstance(MyCommand2._executed[0], argparse.Namespace) def test_dispatcher_command_return_code(): """Command ends indicating the return code to be used.""" class MyCommand(BaseCommand): help_msg = "some help" name = "cmdname" def run(self, parsed_args): return 17 groups = [("test-group", "title", [MyCommand])] dispatcher = Dispatcher(["cmdname"], groups) retcode = dispatcher.run() assert retcode == 17 def test_dispatcher_command_execution_crash(): """Command crashing doesn't pass through, we inform nicely.""" class MyCommand(BaseCommand): help_msg = "some help" name = "cmdname" def run(self, parsed_args): raise ValueError() groups = [("test-group", "title", [MyCommand])] dispatcher = Dispatcher(["cmdname"], groups) with pytest.raises(ValueError): dispatcher.run() def test_dispatcher_config_needed_ok(tmp_path): """Command needs a config, which is provided ok.""" class MyCommand(BaseCommand): help_msg = "some help" name = "cmdname" needs_config = True def run(self, parsed_args): pass # put the config in place test_file = tmp_path / "charmcraft.yaml" test_file.write_text( """ type: charm """ ) groups = [("test-group", "title", [MyCommand])] dispatcher = Dispatcher(["cmdname", "--project-dir", tmp_path], groups) dispatcher.run() def test_dispatcher_config_needed_problem(tmp_path): """Command needs a config, which is not there.""" class MyCommand(BaseCommand): help_msg = "some help" name = "cmdname" needs_config = True def run(self, parsed_args): pass groups = [("test-group", "title", [MyCommand])] dispatcher = Dispatcher(["cmdname", "--project-dir", tmp_path], groups) with pytest.raises(CommandError) as err: dispatcher.run() assert str(err.value) == ( "The specified command needs a valid 'charmcraft.yaml' configuration file (in the " "current directory or where specified with --project-dir option); see the reference: " "https://discourse.charmhub.io/t/charmcraft-configuration/4138" ) def test_dispatcher_config_not_needed(): """Command does not needs a config.""" class MyCommand(BaseCommand): help_msg = "some help" name = "cmdname" def run(self, parsed_args): pass groups = [("test-group", "title", [MyCommand])] dispatcher = Dispatcher(["cmdname"], groups) dispatcher.run() def test_dispatcher_generic_setup_default(): """Generic parameter handling for default values.""" cmd = create_command("somecommand") groups = [("test-group", "title", [cmd])] logsetup.message_handler.mode = None with patch("charmcraft.config.load") as config_mock: Dispatcher(["somecommand"], groups) assert logsetup.message_handler.mode is None config_mock.assert_called_once_with(None) @pytest.mark.parametrize( "options", [ ["somecommand", "--verbose"], ["somecommand", "-v"], ["-v", "somecommand"], ["--verbose", "somecommand"], ["--verbose", "somecommand", "-v"], ], ) def test_dispatcher_generic_setup_verbose(options): """Generic parameter handling for verbose log setup, directly or after the command.""" cmd = create_command("somecommand") groups = [("test-group", "title", [cmd])] logsetup.message_handler.mode = None Dispatcher(options, groups) assert logsetup.message_handler.mode == logsetup.message_handler.VERBOSE @pytest.mark.parametrize( "options", [ ["somecommand", "--quiet"], ["somecommand", "-q"], ["-q", "somecommand"], ["--quiet", "somecommand"], ["--quiet", "somecommand", "-q"], ], ) def test_dispatcher_generic_setup_quiet(options): """Generic parameter handling for quiet log setup, directly or after the command.""" cmd = create_command("somecommand") groups = [("test-group", "title", [cmd])] logsetup.message_handler.mode = None Dispatcher(options, groups) assert logsetup.message_handler.mode == logsetup.message_handler.QUIET @pytest.mark.parametrize( "options", [ ["--quiet", "--verbose", "somecommand"], ["-v", "-q", "somecommand"], ["somecommand", "--quiet", "--verbose"], ["somecommand", "-v", "-q"], ["--verbose", "somecommand", "--quiet"], ["-q", "somecommand", "-v"], ], ) def test_dispatcher_generic_setup_mutually_exclusive(options): """Disallow mutually exclusive generic options.""" cmd = create_command("somecommand") groups = [("test-group", "title", [cmd])] # test the system exit, which is done automatically by argparse with pytest.raises(CommandError) as err: Dispatcher(options, groups) assert str(err.value) == "The 'verbose' and 'quiet' options are mutually exclusive." @pytest.mark.parametrize( "options", [ ["somecommand", "--project-dir", "foobar"], ["somecommand", "--project-dir=foobar"], ["somecommand", "-p", "foobar"], ["-p", "foobar", "somecommand"], ["--project-dir", "foobar", "somecommand"], ["--project-dir=foobar", "somecommand"], ], ) def test_dispatcher_generic_setup_projectdir_with_param(options): """Generic parameter handling for 'project dir' with the param, directly or after the cmd.""" cmd = create_command("somecommand") groups = [("test-group", "title", [cmd])] with patch("charmcraft.config.load") as config_mock: Dispatcher(options, groups) config_mock.assert_called_once_with("foobar") @pytest.mark.parametrize( "options", [ ["somecommand", "--project-dir"], ["somecommand", "--project-dir="], ["somecommand", "-p"], ["--project-dir=", "somecommand"], ], ) def test_dispatcher_generic_setup_projectdir_without_param_simple(options): """Generic parameter handling for 'project dir' without the requested parameter.""" cmd = create_command("somecommand") groups = [("test-group", "title", [cmd])] with pytest.raises(CommandError) as err: Dispatcher(options, groups) assert str(err.value) == "The 'project-dir' option expects one argument." @pytest.mark.parametrize( "options", [ ["-p", "somecommand"], ["--project-dir", "somecommand"], ], ) def test_dispatcher_generic_setup_projectdir_without_param_confusing(options): """Generic parameter handling for 'project dir' taking confusingly the command as the arg.""" cmd = create_command("somecommand") groups = [("test-group", "title", [cmd])] with pytest.raises(CommandError) as err: Dispatcher(options, groups) # generic usage message because "no command" (as 'somecommand' was consumed by --project-dir) assert "Usage" in str(err.value) def test_dispatcher_build_commands_ok(): """Correct command loading.""" cmd0, cmd1, cmd2 = [create_command("cmd-name-{}".format(n), "cmd help") for n in range(3)] groups = [ ("test-group-A", "whatever title", [cmd0]), ("test-group-B", "other title", [cmd1, cmd2]), ] dispatcher = Dispatcher([cmd0.name], groups) assert len(dispatcher.commands) == 3 for cmd, group in [ (cmd0, "test-group-A"), (cmd1, "test-group-B"), (cmd2, "test-group-B"), ]: expected_class, expected_group = dispatcher.commands[cmd.name] assert expected_class == cmd assert expected_group == group def test_dispatcher_build_commands_repeated(): """Error while loading commands with repeated name.""" class Foo(BaseCommand): help_msg = "some help" name = "repeated" class Bar(BaseCommand): help_msg = "some help" name = "cool" class Baz(BaseCommand): help_msg = "some help" name = "repeated" groups = [ ("test-group-1", "whatever title", [Foo, Bar]), ("test-group-2", "other title", [Baz]), ] expected_msg = "Multiple commands with same name: (Foo|Baz) and (Baz|Foo)" with pytest.raises(RuntimeError, match=expected_msg): Dispatcher([], groups) def test_dispatcher_commands_are_not_loaded_if_not_needed(): class MyCommand1(BaseCommand): """Expected to be executed.""" name = "command1" help_msg = "some help" _executed = [] def run(self, parsed_args): self._executed.append(parsed_args) class MyCommand2(BaseCommand): """Expected to not be instantiated, or parse args, or run.""" name = "command2" help_msg = "some help" def __init__(self, *args): raise AssertionError def fill_parser(self, parser): raise AssertionError def run(self, parsed_args): raise AssertionError groups = [("test-group", "title", [MyCommand1, MyCommand2])] dispatcher = Dispatcher(["command1"], groups) dispatcher.run() assert isinstance(MyCommand1._executed[0], argparse.Namespace) # --- Tests for the main entry point # In all the test methods below we patch Dispatcher.run so we don't really exercise any # command machinery, even if we call to main using a real command (which is to just # make argument parsing system happy). def test_main_ok(): """Work ended ok: message handler notified properly, return code in 0.""" with patch("charmcraft.main.message_handler") as mh_mock: with patch("charmcraft.main.Dispatcher.run") as d_mock: d_mock.return_value = None retcode = main(["charmcraft", "version"]) assert retcode == 0 mh_mock.ended_ok.assert_called_once_with() def test_main_no_args(): """The setup.py entry_point function needs to work with no arguments.""" with patch("sys.argv", ["charmcraft"]): with patch("charmcraft.main.message_handler") as mh_mock: retcode = main() assert retcode == 1 assert mh_mock.ended_cmderror.call_count == 1 def test_main_controlled_error(): """Work raised CommandError: message handler notified properly, use indicated return code.""" simulated_exception = CommandError("boom", retcode=33) with patch("charmcraft.main.message_handler") as mh_mock: with patch("charmcraft.main.Dispatcher.run") as d_mock: d_mock.side_effect = simulated_exception retcode = main(["charmcraft", "version"]) assert retcode == 33 mh_mock.ended_cmderror.assert_called_once_with(simulated_exception) def test_main_controlled_return_code(): """Work ended ok, and the command indicated the return code.""" with patch("charmcraft.main.message_handler") as mh_mock: with patch("charmcraft.main.Dispatcher.run") as d_mock: d_mock.return_value = 9 retcode = main(["charmcraft", "version"]) assert retcode == 9 mh_mock.ended_ok.assert_called_once_with() def test_main_environment_is_supported_error( mock_is_charmcraft_running_in_supported_environment, ): mock_is_charmcraft_running_in_supported_environment.return_value = False with patch("charmcraft.main.message_handler") as mh_mock: with patch("charmcraft.main.Dispatcher.run") as d_mock: d_mock.return_value = None retcode = main(["charmcraft", "version"]) assert retcode == 1 assert mh_mock.ended_cmderror.call_count == 1 def test_main_crash(): """Work crashed: message handler notified properly, return code in 1.""" simulated_exception = ValueError("boom") with patch("charmcraft.main.message_handler") as mh_mock: with patch("charmcraft.main.Dispatcher.run") as d_mock: d_mock.side_effect = simulated_exception retcode = main(["charmcraft", "version"]) assert retcode == 1 mh_mock.ended_crash.assert_called_once_with(simulated_exception) def test_main_interrupted(): """Work interrupted: message handler notified properly, return code in 1.""" with patch("charmcraft.main.message_handler") as mh_mock: with patch("charmcraft.main.Dispatcher.run") as d_mock: d_mock.side_effect = KeyboardInterrupt retcode = main(["charmcraft", "version"]) assert retcode == 1 assert mh_mock.ended_interrupt.call_count == 1 # --- Tests for the bootstrap version message def test_initmsg_default(): """Without any option, the init msg only goes to disk.""" cmd = create_command("somecommand") fake_stream = io.StringIO() with patch("charmcraft.main.COMMAND_GROUPS", [("test-group", "whatever title", [cmd])]): with patch.object(logsetup.message_handler, "ended_ok") as ended_ok_mock: with patch.object(logsetup.message_handler._stderr_handler, "stream", fake_stream): main(["charmcraft", "somecommand"]) # get the logfile first line before removing it ended_ok_mock.assert_called_once_with() logged_to_file = pathlib.Path(logsetup.message_handler._log_filepath).read_text() file_first_line = logged_to_file.split("\n")[0] logsetup.message_handler.ended_ok() # get the terminal first line captured = fake_stream.getvalue() terminal_first_line = captured.split("\n")[0] expected = "Starting charmcraft version " + __version__ assert expected in file_first_line assert expected not in terminal_first_line def test_initmsg_quiet(): """In quiet mode, the init msg only goes to disk.""" cmd = create_command("somecommand") fake_stream = io.StringIO() with patch("charmcraft.main.COMMAND_GROUPS", [("test-group", "whatever title", [cmd])]): with patch.object(logsetup.message_handler, "ended_ok") as ended_ok_mock: with patch.object(logsetup.message_handler._stderr_handler, "stream", fake_stream): main(["charmcraft", "--quiet", "somecommand"]) # get the logfile first line before removing it ended_ok_mock.assert_called_once_with() logged_to_file = pathlib.Path(logsetup.message_handler._log_filepath).read_text() file_first_line = logged_to_file.split("\n")[0] logsetup.message_handler.ended_ok() # get the terminal first line captured = fake_stream.getvalue() terminal_first_line = captured.split("\n")[0] expected = "Starting charmcraft version " + __version__ assert expected in file_first_line assert expected not in terminal_first_line def test_initmsg_verbose(): """In verbose mode, the init msg goes both to disk and terminal.""" cmd = create_command("somecommand") fake_stream = io.StringIO() with patch("charmcraft.main.COMMAND_GROUPS", [("test-group", "whatever title", [cmd])]): with patch.object(logsetup.message_handler, "ended_ok") as ended_ok_mock: with patch.object(logsetup.message_handler._stderr_handler, "stream", fake_stream): main(["charmcraft", "--verbose", "somecommand"]) # get the logfile first line before removing it ended_ok_mock.assert_called_once_with() logged_to_file = pathlib.Path(logsetup.message_handler._log_filepath).read_text() file_first_line = logged_to_file.split("\n")[0] logsetup.message_handler.ended_ok() # get the terminal first line captured = fake_stream.getvalue() terminal_first_line = captured.split("\n")[0] expected = "Starting charmcraft version " + __version__ assert expected in file_first_line assert expected in terminal_first_line def test_commands(): cmds = [cmd.name for _, _, cmds in COMMAND_GROUPS for cmd in cmds] env = os.environ.copy() # Bypass unsupported environment error. env["CHARMCRAFT_DEVELOPER"] = "1" env_paths = [p for p in sys.path if "env/lib/python" in p] if env_paths: if "PYTHONPATH" in env: env["PYTHONPATH"] += ":" + ":".join(env_paths) else: env["PYTHONPATH"] = ":".join(env_paths) for cmd in cmds: subprocess.run( [sys.executable, "-m", "charmcraft", cmd, "-h"], check=True, env=env, stdout=subprocess.DEVNULL, )
33.324818
97
0.664604
import argparse import io import os import pathlib import subprocess import sys from unittest.mock import patch from charmcraft import __version__, logsetup from charmcraft.main import Dispatcher, main, COMMAND_GROUPS from charmcraft.cmdbase import BaseCommand, CommandError from tests.factory import create_command import pytest @pytest.fixture(autouse=True) def mock_is_charmcraft_running_in_supported_environment(monkeypatch): with patch( "charmcraft.env.is_charmcraft_running_in_supported_environment", return_value=True, ) as mock_supported: yield mock_supported def test_dispatcher_command_execution_ok(): class MyCommandControl(BaseCommand): help_msg = "some help" def run(self, parsed_args): self._executed.append(parsed_args) class MyCommand1(MyCommandControl): name = "name1" _executed = [] class MyCommand2(MyCommandControl): name = "name2" _executed = [] groups = [("test-group", "title", [MyCommand1, MyCommand2])] dispatcher = Dispatcher(["name2"], groups) dispatcher.run() assert MyCommand1._executed == [] assert isinstance(MyCommand2._executed[0], argparse.Namespace) def test_dispatcher_command_return_code(): class MyCommand(BaseCommand): help_msg = "some help" name = "cmdname" def run(self, parsed_args): return 17 groups = [("test-group", "title", [MyCommand])] dispatcher = Dispatcher(["cmdname"], groups) retcode = dispatcher.run() assert retcode == 17 def test_dispatcher_command_execution_crash(): class MyCommand(BaseCommand): help_msg = "some help" name = "cmdname" def run(self, parsed_args): raise ValueError() groups = [("test-group", "title", [MyCommand])] dispatcher = Dispatcher(["cmdname"], groups) with pytest.raises(ValueError): dispatcher.run() def test_dispatcher_config_needed_ok(tmp_path): class MyCommand(BaseCommand): help_msg = "some help" name = "cmdname" needs_config = True def run(self, parsed_args): pass test_file = tmp_path / "charmcraft.yaml" test_file.write_text( """ type: charm """ ) groups = [("test-group", "title", [MyCommand])] dispatcher = Dispatcher(["cmdname", "--project-dir", tmp_path], groups) dispatcher.run() def test_dispatcher_config_needed_problem(tmp_path): class MyCommand(BaseCommand): help_msg = "some help" name = "cmdname" needs_config = True def run(self, parsed_args): pass groups = [("test-group", "title", [MyCommand])] dispatcher = Dispatcher(["cmdname", "--project-dir", tmp_path], groups) with pytest.raises(CommandError) as err: dispatcher.run() assert str(err.value) == ( "The specified command needs a valid 'charmcraft.yaml' configuration file (in the " "current directory or where specified with --project-dir option); see the reference: " "https://discourse.charmhub.io/t/charmcraft-configuration/4138" ) def test_dispatcher_config_not_needed(): class MyCommand(BaseCommand): help_msg = "some help" name = "cmdname" def run(self, parsed_args): pass groups = [("test-group", "title", [MyCommand])] dispatcher = Dispatcher(["cmdname"], groups) dispatcher.run() def test_dispatcher_generic_setup_default(): cmd = create_command("somecommand") groups = [("test-group", "title", [cmd])] logsetup.message_handler.mode = None with patch("charmcraft.config.load") as config_mock: Dispatcher(["somecommand"], groups) assert logsetup.message_handler.mode is None config_mock.assert_called_once_with(None) @pytest.mark.parametrize( "options", [ ["somecommand", "--verbose"], ["somecommand", "-v"], ["-v", "somecommand"], ["--verbose", "somecommand"], ["--verbose", "somecommand", "-v"], ], ) def test_dispatcher_generic_setup_verbose(options): cmd = create_command("somecommand") groups = [("test-group", "title", [cmd])] logsetup.message_handler.mode = None Dispatcher(options, groups) assert logsetup.message_handler.mode == logsetup.message_handler.VERBOSE @pytest.mark.parametrize( "options", [ ["somecommand", "--quiet"], ["somecommand", "-q"], ["-q", "somecommand"], ["--quiet", "somecommand"], ["--quiet", "somecommand", "-q"], ], ) def test_dispatcher_generic_setup_quiet(options): cmd = create_command("somecommand") groups = [("test-group", "title", [cmd])] logsetup.message_handler.mode = None Dispatcher(options, groups) assert logsetup.message_handler.mode == logsetup.message_handler.QUIET @pytest.mark.parametrize( "options", [ ["--quiet", "--verbose", "somecommand"], ["-v", "-q", "somecommand"], ["somecommand", "--quiet", "--verbose"], ["somecommand", "-v", "-q"], ["--verbose", "somecommand", "--quiet"], ["-q", "somecommand", "-v"], ], ) def test_dispatcher_generic_setup_mutually_exclusive(options): cmd = create_command("somecommand") groups = [("test-group", "title", [cmd])] with pytest.raises(CommandError) as err: Dispatcher(options, groups) assert str(err.value) == "The 'verbose' and 'quiet' options are mutually exclusive." @pytest.mark.parametrize( "options", [ ["somecommand", "--project-dir", "foobar"], ["somecommand", "--project-dir=foobar"], ["somecommand", "-p", "foobar"], ["-p", "foobar", "somecommand"], ["--project-dir", "foobar", "somecommand"], ["--project-dir=foobar", "somecommand"], ], ) def test_dispatcher_generic_setup_projectdir_with_param(options): cmd = create_command("somecommand") groups = [("test-group", "title", [cmd])] with patch("charmcraft.config.load") as config_mock: Dispatcher(options, groups) config_mock.assert_called_once_with("foobar") @pytest.mark.parametrize( "options", [ ["somecommand", "--project-dir"], ["somecommand", "--project-dir="], ["somecommand", "-p"], ["--project-dir=", "somecommand"], ], ) def test_dispatcher_generic_setup_projectdir_without_param_simple(options): cmd = create_command("somecommand") groups = [("test-group", "title", [cmd])] with pytest.raises(CommandError) as err: Dispatcher(options, groups) assert str(err.value) == "The 'project-dir' option expects one argument." @pytest.mark.parametrize( "options", [ ["-p", "somecommand"], ["--project-dir", "somecommand"], ], ) def test_dispatcher_generic_setup_projectdir_without_param_confusing(options): cmd = create_command("somecommand") groups = [("test-group", "title", [cmd])] with pytest.raises(CommandError) as err: Dispatcher(options, groups) assert "Usage" in str(err.value) def test_dispatcher_build_commands_ok(): cmd0, cmd1, cmd2 = [create_command("cmd-name-{}".format(n), "cmd help") for n in range(3)] groups = [ ("test-group-A", "whatever title", [cmd0]), ("test-group-B", "other title", [cmd1, cmd2]), ] dispatcher = Dispatcher([cmd0.name], groups) assert len(dispatcher.commands) == 3 for cmd, group in [ (cmd0, "test-group-A"), (cmd1, "test-group-B"), (cmd2, "test-group-B"), ]: expected_class, expected_group = dispatcher.commands[cmd.name] assert expected_class == cmd assert expected_group == group def test_dispatcher_build_commands_repeated(): class Foo(BaseCommand): help_msg = "some help" name = "repeated" class Bar(BaseCommand): help_msg = "some help" name = "cool" class Baz(BaseCommand): help_msg = "some help" name = "repeated" groups = [ ("test-group-1", "whatever title", [Foo, Bar]), ("test-group-2", "other title", [Baz]), ] expected_msg = "Multiple commands with same name: (Foo|Baz) and (Baz|Foo)" with pytest.raises(RuntimeError, match=expected_msg): Dispatcher([], groups) def test_dispatcher_commands_are_not_loaded_if_not_needed(): class MyCommand1(BaseCommand): name = "command1" help_msg = "some help" _executed = [] def run(self, parsed_args): self._executed.append(parsed_args) class MyCommand2(BaseCommand): name = "command2" help_msg = "some help" def __init__(self, *args): raise AssertionError def fill_parser(self, parser): raise AssertionError def run(self, parsed_args): raise AssertionError groups = [("test-group", "title", [MyCommand1, MyCommand2])] dispatcher = Dispatcher(["command1"], groups) dispatcher.run() assert isinstance(MyCommand1._executed[0], argparse.Namespace) # command machinery, even if we call to main using a real command (which is to just # make argument parsing system happy). def test_main_ok(): with patch("charmcraft.main.message_handler") as mh_mock: with patch("charmcraft.main.Dispatcher.run") as d_mock: d_mock.return_value = None retcode = main(["charmcraft", "version"]) assert retcode == 0 mh_mock.ended_ok.assert_called_once_with() def test_main_no_args(): with patch("sys.argv", ["charmcraft"]): with patch("charmcraft.main.message_handler") as mh_mock: retcode = main() assert retcode == 1 assert mh_mock.ended_cmderror.call_count == 1 def test_main_controlled_error(): simulated_exception = CommandError("boom", retcode=33) with patch("charmcraft.main.message_handler") as mh_mock: with patch("charmcraft.main.Dispatcher.run") as d_mock: d_mock.side_effect = simulated_exception retcode = main(["charmcraft", "version"]) assert retcode == 33 mh_mock.ended_cmderror.assert_called_once_with(simulated_exception) def test_main_controlled_return_code(): with patch("charmcraft.main.message_handler") as mh_mock: with patch("charmcraft.main.Dispatcher.run") as d_mock: d_mock.return_value = 9 retcode = main(["charmcraft", "version"]) assert retcode == 9 mh_mock.ended_ok.assert_called_once_with() def test_main_environment_is_supported_error( mock_is_charmcraft_running_in_supported_environment, ): mock_is_charmcraft_running_in_supported_environment.return_value = False with patch("charmcraft.main.message_handler") as mh_mock: with patch("charmcraft.main.Dispatcher.run") as d_mock: d_mock.return_value = None retcode = main(["charmcraft", "version"]) assert retcode == 1 assert mh_mock.ended_cmderror.call_count == 1 def test_main_crash(): simulated_exception = ValueError("boom") with patch("charmcraft.main.message_handler") as mh_mock: with patch("charmcraft.main.Dispatcher.run") as d_mock: d_mock.side_effect = simulated_exception retcode = main(["charmcraft", "version"]) assert retcode == 1 mh_mock.ended_crash.assert_called_once_with(simulated_exception) def test_main_interrupted(): with patch("charmcraft.main.message_handler") as mh_mock: with patch("charmcraft.main.Dispatcher.run") as d_mock: d_mock.side_effect = KeyboardInterrupt retcode = main(["charmcraft", "version"]) assert retcode == 1 assert mh_mock.ended_interrupt.call_count == 1 # --- Tests for the bootstrap version message def test_initmsg_default(): cmd = create_command("somecommand") fake_stream = io.StringIO() with patch("charmcraft.main.COMMAND_GROUPS", [("test-group", "whatever title", [cmd])]): with patch.object(logsetup.message_handler, "ended_ok") as ended_ok_mock: with patch.object(logsetup.message_handler._stderr_handler, "stream", fake_stream): main(["charmcraft", "somecommand"]) # get the logfile first line before removing it ended_ok_mock.assert_called_once_with() logged_to_file = pathlib.Path(logsetup.message_handler._log_filepath).read_text() file_first_line = logged_to_file.split("\n")[0] logsetup.message_handler.ended_ok() # get the terminal first line captured = fake_stream.getvalue() terminal_first_line = captured.split("\n")[0] expected = "Starting charmcraft version " + __version__ assert expected in file_first_line assert expected not in terminal_first_line def test_initmsg_quiet(): cmd = create_command("somecommand") fake_stream = io.StringIO() with patch("charmcraft.main.COMMAND_GROUPS", [("test-group", "whatever title", [cmd])]): with patch.object(logsetup.message_handler, "ended_ok") as ended_ok_mock: with patch.object(logsetup.message_handler._stderr_handler, "stream", fake_stream): main(["charmcraft", "--quiet", "somecommand"]) # get the logfile first line before removing it ended_ok_mock.assert_called_once_with() logged_to_file = pathlib.Path(logsetup.message_handler._log_filepath).read_text() file_first_line = logged_to_file.split("\n")[0] logsetup.message_handler.ended_ok() # get the terminal first line captured = fake_stream.getvalue() terminal_first_line = captured.split("\n")[0] expected = "Starting charmcraft version " + __version__ assert expected in file_first_line assert expected not in terminal_first_line def test_initmsg_verbose(): cmd = create_command("somecommand") fake_stream = io.StringIO() with patch("charmcraft.main.COMMAND_GROUPS", [("test-group", "whatever title", [cmd])]): with patch.object(logsetup.message_handler, "ended_ok") as ended_ok_mock: with patch.object(logsetup.message_handler._stderr_handler, "stream", fake_stream): main(["charmcraft", "--verbose", "somecommand"]) # get the logfile first line before removing it ended_ok_mock.assert_called_once_with() logged_to_file = pathlib.Path(logsetup.message_handler._log_filepath).read_text() file_first_line = logged_to_file.split("\n")[0] logsetup.message_handler.ended_ok() # get the terminal first line captured = fake_stream.getvalue() terminal_first_line = captured.split("\n")[0] expected = "Starting charmcraft version " + __version__ assert expected in file_first_line assert expected in terminal_first_line def test_commands(): cmds = [cmd.name for _, _, cmds in COMMAND_GROUPS for cmd in cmds] env = os.environ.copy() # Bypass unsupported environment error. env["CHARMCRAFT_DEVELOPER"] = "1" env_paths = [p for p in sys.path if "env/lib/python" in p] if env_paths: if "PYTHONPATH" in env: env["PYTHONPATH"] += ":" + ":".join(env_paths) else: env["PYTHONPATH"] = ":".join(env_paths) for cmd in cmds: subprocess.run( [sys.executable, "-m", "charmcraft", cmd, "-h"], check=True, env=env, stdout=subprocess.DEVNULL, )
true
true
1c3905ddf3a4668d405567ec585b908595c453dc
1,824
py
Python
gym_minigrid/envs/distshift.py
HelgeS/gym-minigrid
af7f0e9473d9ef1365779e27af3143c40dda07e0
[ "BSD-3-Clause" ]
2
2021-12-06T20:45:55.000Z
2022-03-15T21:09:15.000Z
gym_minigrid/envs/distshift.py
HelgeS/gym-minigrid
af7f0e9473d9ef1365779e27af3143c40dda07e0
[ "BSD-3-Clause" ]
null
null
null
gym_minigrid/envs/distshift.py
HelgeS/gym-minigrid
af7f0e9473d9ef1365779e27af3143c40dda07e0
[ "BSD-3-Clause" ]
1
2022-01-11T21:04:37.000Z
2022-01-11T21:04:37.000Z
from gym_minigrid.minigrid import * from gym_minigrid.register import register class DistShiftEnv(MiniGridEnv): """ Distributional shift environment. """ def __init__( self, width=9, height=7, agent_start_pos=(1,1), agent_start_dir=0, strip2_row=2 ): self.agent_start_pos = agent_start_pos self.agent_start_dir = agent_start_dir self.goal_pos=(width-2, 1) self.strip2_row = strip2_row super().__init__( width=width, height=height, max_steps=4*width*height, # Set this to True for maximum speed see_through_walls=True ) def _gen_grid(self, width, height): # Create an empty grid self.grid = Grid(width, height) # Generate the surrounding walls self.grid.wall_rect(0, 0, width, height) # Place a goal square in the bottom-right corner self.grid.set(*self.goal_pos, Goal()) # Place the lava rows for i in range(self.width - 6): self.grid.set(3+i, 1, Lava()) self.grid.set(3+i, self.strip2_row, Lava()) # Place the agent if self.agent_start_pos is not None: self.start_pos = self.agent_start_pos self.start_dir = self.agent_start_dir else: self.place_agent() self.mission = "get to the green goal square" class DistShift1(DistShiftEnv): def __init__(self): super().__init__(strip2_row=2) class DistShift2(DistShiftEnv): def __init__(self): super().__init__(strip2_row=5) register( id='MiniGrid-DistShift1-v0', entry_point='gym_minigrid.envs:DistShift1' ) register( id='MiniGrid-DistShift2-v0', entry_point='gym_minigrid.envs:DistShift2' )
25.690141
56
0.611294
from gym_minigrid.minigrid import * from gym_minigrid.register import register class DistShiftEnv(MiniGridEnv): def __init__( self, width=9, height=7, agent_start_pos=(1,1), agent_start_dir=0, strip2_row=2 ): self.agent_start_pos = agent_start_pos self.agent_start_dir = agent_start_dir self.goal_pos=(width-2, 1) self.strip2_row = strip2_row super().__init__( width=width, height=height, max_steps=4*width*height, see_through_walls=True ) def _gen_grid(self, width, height): self.grid = Grid(width, height) self.grid.wall_rect(0, 0, width, height) self.grid.set(*self.goal_pos, Goal()) for i in range(self.width - 6): self.grid.set(3+i, 1, Lava()) self.grid.set(3+i, self.strip2_row, Lava()) if self.agent_start_pos is not None: self.start_pos = self.agent_start_pos self.start_dir = self.agent_start_dir else: self.place_agent() self.mission = "get to the green goal square" class DistShift1(DistShiftEnv): def __init__(self): super().__init__(strip2_row=2) class DistShift2(DistShiftEnv): def __init__(self): super().__init__(strip2_row=5) register( id='MiniGrid-DistShift1-v0', entry_point='gym_minigrid.envs:DistShift1' ) register( id='MiniGrid-DistShift2-v0', entry_point='gym_minigrid.envs:DistShift2' )
true
true
1c3906b61a2bdcb4997a349270dd185d2a2fab40
5,883
py
Python
catkin_ws/src/ros_pa3/scripts/markers_example.py
SwellMai/Terminator-800
df7b31780aa950e407d4f50fbbfb150959ec4192
[ "MIT" ]
null
null
null
catkin_ws/src/ros_pa3/scripts/markers_example.py
SwellMai/Terminator-800
df7b31780aa950e407d4f50fbbfb150959ec4192
[ "MIT" ]
null
null
null
catkin_ws/src/ros_pa3/scripts/markers_example.py
SwellMai/Terminator-800
df7b31780aa950e407d4f50fbbfb150959ec4192
[ "MIT" ]
null
null
null
#!/usr/bin/env python # Ref 1: http://wiki.ros.org/rviz/DisplayTypes/Marker # Ref 2: https://answers.ros.org/question/203782/rviz-marker-line_strip-is-not-displayed/ import rospy from visualization_msgs.msg import Marker from geometry_msgs.msg import Point rospy.loginfo('Rviz example') def display_line_list(points, publisher): """ A function that publishes a set of points as marker line list to Rviz. It will draw a line between each pair of points, so 0-1, 2-3, 4-5, ... Parameters: points (list): Each item in the list is a tuple (x, y) representing a point in xy space. publisher (rospy.Publisher): A publisher object used to pubish the marker Returns: None """ marker = Marker() # The coordinate frame in which the marker is publsihed. # Make sure "Fixed Frame" under "Global Options" in the Display panel # in rviz is "/map" marker.header.frame_id = "/map" # Mark type (http://wiki.ros.org/rviz/DisplayTypes/Marker) # LINE_LIST: It will draw a line between each pair of points, so 0-1, 2-3, 4-5, ... marker.type = marker.LINE_LIST # Marker action (Set this as ADD) marker.action = marker.ADD # Marker scale marker.scale.x = 0.01 marker.scale.y = 0.01 marker.scale.z = 0.01 # Marker color (Make sure a=1.0 which sets the opacity) marker.color.a = 1.0 marker.color.r = 1.0 marker.color.g = 1.0 marker.color.b = 0.0 # Marker orientaiton (Set it as default orientation in quaternion) marker.pose.orientation.x = 0.0 marker.pose.orientation.y = 0.0 marker.pose.orientation.z = 0.0 marker.pose.orientation.w = 1.0 # Marker position # The position of the marker. In this case it the COM of all the points # Set this as 0,0,0 marker.pose.position.x = 0.0 marker.pose.position.y = 0.0 marker.pose.position.z = 0.0 # Marker line points marker.points = [] for point in points: marker_point = Point() # Create a new Point() marker_point.x = point[0] marker_point.y = point[1] marker_point.z = 0.0 marker.points.append(marker_point) # Append the marker_point to the marker.points list # Publish the Marker using the appropirate publisher publisher.publish(marker) def display_cube_list(points, publisher): """ A function that publishes a set of points as marker cubes in Rviz. Each point represents the COM of the cube to be displayed. Parameters: points (list): Each item in the list is a tuple (x, y) representing a point in xy space for the COM of the cube. publisher (rospy.Publisher): A publisher object used to pubish the marker Returns: None """ marker = Marker() # The coordinate frame in which the marker is published. # Make sure "Fixed Frame" under "Global Options" in the Display panel # in rviz is "/map" marker.header.frame_id = "/map" # Mark type (http://wiki.ros.org/rviz/DisplayTypes/Marker) # CUBE_LIST marker.type = marker.CUBE_LIST # Marker action (Set this as ADD) marker.action = marker.ADD # Marker scale (Size of the cube) marker.scale.x = 0.1 marker.scale.y = 0.1 marker.scale.z = 0.1 # Marker color (Make sure a=1.0 which sets the opacity) marker.color.a = 1.0 marker.color.r = 0.0 marker.color.g = 1.0 marker.color.b = 0.0 # Marker orientation (Set it as default orientation in quaternion) marker.pose.orientation.x = 0.0 marker.pose.orientation.y = 0.0 marker.pose.orientation.z = 0.0 marker.pose.orientation.w = 1.0 # Marker position # The position of the marker. In this case it the COM of all the cubes # Set this as 0,0,0 marker.pose.position.x = 0.0 marker.pose.position.y = 0.0 marker.pose.position.z = 0.0 # Marker line points marker.points = [] for point in points: marker_point = Point() # Create a new Point() marker_point.x = point[0] marker_point.y = point[1] marker_point.z = 0.0 marker.points.append(marker_point) # Append the marker_point to the marker.points list # Publish the Marker using the apporopriate publisher publisher.publish(marker) def display_line(line_points): rospy.init_node('rviz_pub') pub_line_list = rospy.Publisher('line_list', Marker, queue_size=1) while not rospy.is_shutdown(): display_line_list(line_points, pub_line_list) if __name__ == "__main__": rospy.init_node('rviz_pub_example') # Rviz is a node that can subscribe to topics of certain message types. # Here we use the Marker message type and create two publishers # to display the robot trejectory as a list of lines(MARKER.LINE_LIST) # and display the landmarks as a list of cubes (MARKER.CUBE_LIST) # Make sure you in rviz you subsribe to these topics in rviz by clicking # on Add in the display panel, selecting by topic and choosing the # appropraite topic. # Initilize a publisher for LINE_LIST makers pub_line_list = rospy.Publisher('line_list', Marker, queue_size=1) # Initilize a publisher for CUBE_LIST makers pub_cube_list = rospy.Publisher('cube_list', Marker, queue_size=1) # Example Input: Set of points to draw a square line_points = [(0,0), (0,0.5), (0,0.5), (0.5,0.5), (0.5,0.5), (0.5,0), (0.5,0), (0,0)] # Example Input: Set of cubes at four positions cube_points = [(0,0), (0,1), (1,0), (1,1)] # Call the display functions in a loop to see the markers on rviz over time while not rospy.is_shutdown(): display_line_list(line_points, pub_line_list) display_cube_list(cube_points, pub_cube_list)
33.050562
95
0.654088
import rospy from visualization_msgs.msg import Marker from geometry_msgs.msg import Point rospy.loginfo('Rviz example') def display_line_list(points, publisher): marker = Marker() marker.header.frame_id = "/map" marker.type = marker.LINE_LIST marker.action = marker.ADD marker.scale.x = 0.01 marker.scale.y = 0.01 marker.scale.z = 0.01 marker.color.a = 1.0 marker.color.r = 1.0 marker.color.g = 1.0 marker.color.b = 0.0 marker.pose.orientation.x = 0.0 marker.pose.orientation.y = 0.0 marker.pose.orientation.z = 0.0 marker.pose.orientation.w = 1.0 marker.pose.position.x = 0.0 marker.pose.position.y = 0.0 marker.pose.position.z = 0.0 marker.points = [] for point in points: marker_point = Point() marker_point.x = point[0] marker_point.y = point[1] marker_point.z = 0.0 marker.points.append(marker_point) publisher.publish(marker) def display_cube_list(points, publisher): marker = Marker() marker.header.frame_id = "/map" marker.type = marker.CUBE_LIST marker.action = marker.ADD marker.scale.x = 0.1 marker.scale.y = 0.1 marker.scale.z = 0.1 marker.color.a = 1.0 marker.color.r = 0.0 marker.color.g = 1.0 marker.color.b = 0.0 marker.pose.orientation.x = 0.0 marker.pose.orientation.y = 0.0 marker.pose.orientation.z = 0.0 marker.pose.orientation.w = 1.0 marker.pose.position.x = 0.0 marker.pose.position.y = 0.0 marker.pose.position.z = 0.0 marker.points = [] for point in points: marker_point = Point() marker_point.x = point[0] marker_point.y = point[1] marker_point.z = 0.0 marker.points.append(marker_point) publisher.publish(marker) def display_line(line_points): rospy.init_node('rviz_pub') pub_line_list = rospy.Publisher('line_list', Marker, queue_size=1) while not rospy.is_shutdown(): display_line_list(line_points, pub_line_list) if __name__ == "__main__": rospy.init_node('rviz_pub_example') pub_line_list = rospy.Publisher('line_list', Marker, queue_size=1) pub_cube_list = rospy.Publisher('cube_list', Marker, queue_size=1) line_points = [(0,0), (0,0.5), (0,0.5), (0.5,0.5), (0.5,0.5), (0.5,0), (0.5,0), (0,0)] cube_points = [(0,0), (0,1), (1,0), (1,1)] while not rospy.is_shutdown(): display_line_list(line_points, pub_line_list) display_cube_list(cube_points, pub_cube_list)
true
true
1c39089dece05e9048b900f460e1e2cfed1a3266
3,404
py
Python
pcg_libraries/src/pcg_gazebo/task_manager/simulation_timer.py
boschresearch/pcg_gazebo_pkgs
1c112d01847ca4f8da61ce9b273e13d13bc7eb73
[ "Apache-2.0", "BSD-3-Clause" ]
42
2019-06-26T09:46:03.000Z
2022-03-18T17:56:26.000Z
pcg_libraries/src/pcg_gazebo/task_manager/simulation_timer.py
boschresearch/pcg_gazebo_pkgs
1c112d01847ca4f8da61ce9b273e13d13bc7eb73
[ "Apache-2.0", "BSD-3-Clause" ]
9
2019-07-18T10:36:05.000Z
2020-10-02T15:26:32.000Z
pcg_libraries/src/pcg_gazebo/task_manager/simulation_timer.py
boschresearch/pcg_gazebo_pkgs
1c112d01847ca4f8da61ce9b273e13d13bc7eb73
[ "Apache-2.0", "BSD-3-Clause" ]
2
2019-11-01T03:20:11.000Z
2020-10-15T23:23:44.000Z
# Copyright (c) 2019 - The Procedural Generation for Gazebo authors # For information on the respective copyright owner see the NOTICE file # # 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 time import time, sleep from threading import Thread from rosgraph_msgs.msg import Clock import rospy from ..log import create_logger class SimulationTimer(Thread): def __init__(self, simulation_timeout=0, start_gazebo_timeout=60, ros_config=None, output_log_dir=None, callback=None): Thread.__init__(self) assert ros_config is not None, 'ROS network configuration cannot' \ ' be null' assert start_gazebo_timeout >= 0, 'Start Gazebo timeout must be ' \ 'equal or greater than zero' assert simulation_timeout >= 0, 'Simulation timeout must be equal' \ ' or greater than zero' if callback is not None: assert callable(callback), 'Invalid callback function' self._logger = create_logger(name='simulation_timeout', output_dir=output_log_dir) self._gazebo_clock = 0 self._simulation_timeout = simulation_timeout self._start_gazebo_timeout = start_gazebo_timeout self._ros_config = ros_config self._success = True self._callback = callback rospy.init_node('simulation_timer', anonymous=True) self._sim_time_sub = rospy.Subscriber( 'clock', Clock, self._clock_callback) self._logger.info('Simulation timeout configured, ' 'simulation_timeout={}, ' 'start_gazebo_timeout={}'.format(self._simulation_timeout, self._start_gazebo_timeout)) def _clock_callback(self, msg): self._gazebo_clock = rospy.Time(msg.clock.secs, msg.clock.nsecs).to_sec() def run(self): self._logger.info('Starting simulation timer - Timeout = {} s'.format(self._simulation_timeout)) rate = rospy.Rate(100) start_process_timeout = time() while self._gazebo_clock < self._simulation_timeout: rate.sleep() if self._gazebo_clock == 0: if time() - start_process_timeout > self._start_gazebo_timeout: self._logger.error('Clock was not initialized for {} seconds'.format(self._start_gazebo_timeout)) self._success = False break if rospy.is_shutdown(): self._logger.error('ROS master was killed!') self._success = False break if self._success: self._logger.info('Simulation timeout was triggered!') else: self._logger.error('Simulation timeout encountered an error') if self._callback is not None: self._logger.info('Calling simulation timeout callback') self._callback()
40.52381
117
0.65658
from time import time, sleep from threading import Thread from rosgraph_msgs.msg import Clock import rospy from ..log import create_logger class SimulationTimer(Thread): def __init__(self, simulation_timeout=0, start_gazebo_timeout=60, ros_config=None, output_log_dir=None, callback=None): Thread.__init__(self) assert ros_config is not None, 'ROS network configuration cannot' \ ' be null' assert start_gazebo_timeout >= 0, 'Start Gazebo timeout must be ' \ 'equal or greater than zero' assert simulation_timeout >= 0, 'Simulation timeout must be equal' \ ' or greater than zero' if callback is not None: assert callable(callback), 'Invalid callback function' self._logger = create_logger(name='simulation_timeout', output_dir=output_log_dir) self._gazebo_clock = 0 self._simulation_timeout = simulation_timeout self._start_gazebo_timeout = start_gazebo_timeout self._ros_config = ros_config self._success = True self._callback = callback rospy.init_node('simulation_timer', anonymous=True) self._sim_time_sub = rospy.Subscriber( 'clock', Clock, self._clock_callback) self._logger.info('Simulation timeout configured, ' 'simulation_timeout={}, ' 'start_gazebo_timeout={}'.format(self._simulation_timeout, self._start_gazebo_timeout)) def _clock_callback(self, msg): self._gazebo_clock = rospy.Time(msg.clock.secs, msg.clock.nsecs).to_sec() def run(self): self._logger.info('Starting simulation timer - Timeout = {} s'.format(self._simulation_timeout)) rate = rospy.Rate(100) start_process_timeout = time() while self._gazebo_clock < self._simulation_timeout: rate.sleep() if self._gazebo_clock == 0: if time() - start_process_timeout > self._start_gazebo_timeout: self._logger.error('Clock was not initialized for {} seconds'.format(self._start_gazebo_timeout)) self._success = False break if rospy.is_shutdown(): self._logger.error('ROS master was killed!') self._success = False break if self._success: self._logger.info('Simulation timeout was triggered!') else: self._logger.error('Simulation timeout encountered an error') if self._callback is not None: self._logger.info('Calling simulation timeout callback') self._callback()
true
true
1c390924433878cc4300f06e61fa07ebe7d9ea64
5,040
py
Python
d3mdm/__main__.py
HDI-Project/d3m-dataset-manager
fdba854cd88a5731dae5213b6c32874a50610e7b
[ "MIT" ]
3
2021-09-27T00:53:54.000Z
2022-02-26T09:06:48.000Z
d3mdm/__main__.py
HDI-Project/d3m-dataset-manager
fdba854cd88a5731dae5213b6c32874a50610e7b
[ "MIT" ]
null
null
null
d3mdm/__main__.py
HDI-Project/d3m-dataset-manager
fdba854cd88a5731dae5213b6c32874a50610e7b
[ "MIT" ]
2
2019-12-07T17:59:35.000Z
2021-09-27T00:53:55.000Z
# -*- coding: utf-8 -*- import gc import logging import os from getpass import getpass from d3mdm import d3m, local, s3 from d3mdm.splitter import add_dataset_splits LOGGER = logging.getLogger(__name__) def logging_setup(verbosity=1): logger = logging.getLogger() log_level = (3 - verbosity) * 10 fmt = '%(levelname)s - %(message)s' formatter = logging.Formatter(fmt) logger.setLevel(log_level) logger.propagate = False console_handler = logging.StreamHandler() console_handler.setLevel(log_level) console_handler.setFormatter(formatter) logger.addHandler(console_handler) def parse_s3_path(path): parts = path[5:].split('/', 1) bucket = parts[0] folder = parts[1] if len(parts) > 1 else 'datasets' return bucket, folder def get_input_manager(args): if args.input.startswith('d3m:'): input_args = args.input[4:].split(':') username = input_args[0] password = input_args[1:] if not username: username = input('Username: ') if password: password = password[0] if not password: password = getpass() return d3m.D3MManager(username, password, skip_sublevels=args.skip_sublevels) elif args.input.startswith('ipfs'): return d3m.IPFSManager(skip_sublevels=args.skip_sublevels) elif args.input.startswith('s3://'): bucket, folder = parse_s3_path(args.input) return s3.S3Manager(bucket, folder, skip_sublevels=args.skip_sublevels) elif os.path.isdir(args.input): return local.LocalManager(args.input, args.skip_sublevels) else: raise Exception('Invalid Input: {}'.format(args.input)) def get_output_manager(args): if args.output.startswith('s3://'): bucket, folder = parse_s3_path(args.output) return s3.S3Manager(bucket, folder) elif os.path.isdir(args.output): return local.LocalManager(args.output) else: raise Exception('Invalid Output: {}'.format(args.output)) def process_dataset(dataset_name, input_manager, output_manager, split, raw): raw = raw or split dataset = input_manager.load(dataset_name, raw=raw) if split: add_dataset_splits(dataset, dataset_name) output_manager.write(dataset, dataset_name) def main(): from argparse import ArgumentParser parser = ArgumentParser(description='D3M dataset manager') # Logging parser.add_argument('-v', '--verbose', action='count', default=0) # Input parser.add_argument('-i', '--input', required=True, help='Local folder, s3:bucket or d3m:username:password.') # Output output_or_list = parser.add_mutually_exclusive_group() output_or_list.add_argument('-o', '--output', help='Local folder or s3:bucket:folder') output_or_list.add_argument('-l', '--list', action='store_true', help='List all datasets found in input') # Process options parser.add_argument('-a', '--all', action='store_true', help='Process all datasets from Input') parser.add_argument('-s', '--split', action='store_true', help='Compute and store the dataset splits.') parser.add_argument('-r', '--raw', action='store_true', help='Do not download the dataset splits.') parser.add_argument('-S', '--skip-sublevels', action='store_true', help='Skip dataset sublevels. For debug purposes') parser.add_argument('-f', '--force', action='store_true', help='Overwrite previously downloaded datasets') parser.add_argument('-d', '--dry-run', action='store_true', help='Do not perform any real action. Only name them.') # TODO: add cleanup option: Delete the dataset before saving parser.add_argument('dataset', type=str, nargs='*', help='Datasets to process.') args = parser.parse_args() logging_setup(args.verbose) input_manager = get_input_manager(args) if args.list: for dataset in input_manager.datasets(): print(dataset) else: if args.all: datasets = input_manager.datasets() else: datasets = args.dataset if not datasets: print('Please provide at least a dataset name') else: output_manager = get_output_manager(args) for dataset in datasets: if args.force or not output_manager.exists(dataset): print('Copying dataset {} from {} to {}'.format( dataset, args.input, args.output)) if not args.dry_run: process_dataset( dataset, input_manager, output_manager, args.split, args.raw) gc.collect() else: print('Dataset {} already exists. Use --force to overwrite.'.format(dataset)) if __name__ == '__main__': main()
31.698113
97
0.624405
import gc import logging import os from getpass import getpass from d3mdm import d3m, local, s3 from d3mdm.splitter import add_dataset_splits LOGGER = logging.getLogger(__name__) def logging_setup(verbosity=1): logger = logging.getLogger() log_level = (3 - verbosity) * 10 fmt = '%(levelname)s - %(message)s' formatter = logging.Formatter(fmt) logger.setLevel(log_level) logger.propagate = False console_handler = logging.StreamHandler() console_handler.setLevel(log_level) console_handler.setFormatter(formatter) logger.addHandler(console_handler) def parse_s3_path(path): parts = path[5:].split('/', 1) bucket = parts[0] folder = parts[1] if len(parts) > 1 else 'datasets' return bucket, folder def get_input_manager(args): if args.input.startswith('d3m:'): input_args = args.input[4:].split(':') username = input_args[0] password = input_args[1:] if not username: username = input('Username: ') if password: password = password[0] if not password: password = getpass() return d3m.D3MManager(username, password, skip_sublevels=args.skip_sublevels) elif args.input.startswith('ipfs'): return d3m.IPFSManager(skip_sublevels=args.skip_sublevels) elif args.input.startswith('s3://'): bucket, folder = parse_s3_path(args.input) return s3.S3Manager(bucket, folder, skip_sublevels=args.skip_sublevels) elif os.path.isdir(args.input): return local.LocalManager(args.input, args.skip_sublevels) else: raise Exception('Invalid Input: {}'.format(args.input)) def get_output_manager(args): if args.output.startswith('s3://'): bucket, folder = parse_s3_path(args.output) return s3.S3Manager(bucket, folder) elif os.path.isdir(args.output): return local.LocalManager(args.output) else: raise Exception('Invalid Output: {}'.format(args.output)) def process_dataset(dataset_name, input_manager, output_manager, split, raw): raw = raw or split dataset = input_manager.load(dataset_name, raw=raw) if split: add_dataset_splits(dataset, dataset_name) output_manager.write(dataset, dataset_name) def main(): from argparse import ArgumentParser parser = ArgumentParser(description='D3M dataset manager') parser.add_argument('-v', '--verbose', action='count', default=0) parser.add_argument('-i', '--input', required=True, help='Local folder, s3:bucket or d3m:username:password.') output_or_list = parser.add_mutually_exclusive_group() output_or_list.add_argument('-o', '--output', help='Local folder or s3:bucket:folder') output_or_list.add_argument('-l', '--list', action='store_true', help='List all datasets found in input') parser.add_argument('-a', '--all', action='store_true', help='Process all datasets from Input') parser.add_argument('-s', '--split', action='store_true', help='Compute and store the dataset splits.') parser.add_argument('-r', '--raw', action='store_true', help='Do not download the dataset splits.') parser.add_argument('-S', '--skip-sublevels', action='store_true', help='Skip dataset sublevels. For debug purposes') parser.add_argument('-f', '--force', action='store_true', help='Overwrite previously downloaded datasets') parser.add_argument('-d', '--dry-run', action='store_true', help='Do not perform any real action. Only name them.') parser.add_argument('dataset', type=str, nargs='*', help='Datasets to process.') args = parser.parse_args() logging_setup(args.verbose) input_manager = get_input_manager(args) if args.list: for dataset in input_manager.datasets(): print(dataset) else: if args.all: datasets = input_manager.datasets() else: datasets = args.dataset if not datasets: print('Please provide at least a dataset name') else: output_manager = get_output_manager(args) for dataset in datasets: if args.force or not output_manager.exists(dataset): print('Copying dataset {} from {} to {}'.format( dataset, args.input, args.output)) if not args.dry_run: process_dataset( dataset, input_manager, output_manager, args.split, args.raw) gc.collect() else: print('Dataset {} already exists. Use --force to overwrite.'.format(dataset)) if __name__ == '__main__': main()
true
true
1c39094515abba4603acfc585af47cc40b45b3eb
3,265
py
Python
2_structures_lineaires/liste.py
efloti/cours-nsi-terminale
091df5518c25b50ef523a803ac747c63be76f670
[ "CC0-1.0" ]
null
null
null
2_structures_lineaires/liste.py
efloti/cours-nsi-terminale
091df5518c25b50ef523a803ac747c63be76f670
[ "CC0-1.0" ]
null
null
null
2_structures_lineaires/liste.py
efloti/cours-nsi-terminale
091df5518c25b50ef523a803ac747c63be76f670
[ "CC0-1.0" ]
null
null
null
class Cellule: """Fondation du type ListeSimple""" def __init__(self, valeur, suivante=None): self.valeur = valeur self._suivante = suivante # éviter de jouer avec ce pointeur... @property def suivante(self): return self._suivante def __str__(self): if self._suivante is None: return f"{self.valeur}" return f"{self.valeur} → {self._suivante}" class Liste: """Une liste chaînée simple - utilise Cellule""" def __init__(self): """Crée une liste chaînée vide""" self._tete = None self._queue = None self._taille = 0 @property def tete(self): return self._tete @property def queue(self): return self._queue def __len__(self): return self._taille def __str__(self): if self._tete is None: return "None" else: return str(self._tete) def inserer_apres(self, valeur, cellule=None): """ Insère valeur juste après cellule. Si cellule n'est pas précisée, l'insertion se fait en tête. """ self._taille += 1 cell = Cellule(valeur) # insertion en tête if cellule is None: cell._suivante = self._tete self._tete = cell # si la cellule est seule, elle est aussi la queue! if self._tete._suivante is None: self._queue = cell return # insertion queue if cellule._suivante is None: cellule._suivante = cell self._queue = cell return # insertion ailleurs cell._suivante = cellule._suivante cellule._suivante = cell def supprimer_apres(self, cellule=None): """ Supprime et renvoie la valeur située dans la cellule qui suit celle fournie. Si aucune cellule n'est précisée, supprimer la cellule de tête. """ # la liste est vide ou cellule n'a pas de suivante if self._tete is None or (cellule is not None and cellule._suivante is None): raise IndexError("Liste vide!") self._taille -= 1 # supprimer en tête if cellule is None: v = self.tete.valeur if self._tete._suivante is None: self._queue = None self._tete = self.tete._suivante return v # ailleurs v = cellule._suivante.valeur # mais peut-être la queue if cellule._suivante is self._queue: self._queue = cellule cellule._suivante = cellule._suivante._suivante # penser à renvoyer la valeur effectivement supprimée return v if __name__ == "__main__": test = Cellule(1, Cellule(2)) assert str(test) == "1 → 2" l = Liste() assert str(l) == "None" l.inserer_apres(1) l.inserer_apres(2) assert str(l) == "2 → 1" assert len(l) == 2 assert l.tete.valeur == 2 assert l.tete.suivante.valeur == 1 l.inserer_apres(3) l.supprimer_apres() assert l.tete.valeur == 2 l.inserer_apres(3) l.supprimer_apres(l.tete) assert l.tete.valeur == 3 and l.tete.suivante.valeur == 1 l.supprimer_apres(l.tete) assert l.queue is l.tete
28.391304
108
0.583155
class Cellule: def __init__(self, valeur, suivante=None): self.valeur = valeur self._suivante = suivante @property def suivante(self): return self._suivante def __str__(self): if self._suivante is None: return f"{self.valeur}" return f"{self.valeur} → {self._suivante}" class Liste: def __init__(self): self._tete = None self._queue = None self._taille = 0 @property def tete(self): return self._tete @property def queue(self): return self._queue def __len__(self): return self._taille def __str__(self): if self._tete is None: return "None" else: return str(self._tete) def inserer_apres(self, valeur, cellule=None): self._taille += 1 cell = Cellule(valeur) if cellule is None: cell._suivante = self._tete self._tete = cell if self._tete._suivante is None: self._queue = cell return if cellule._suivante is None: cellule._suivante = cell self._queue = cell return cell._suivante = cellule._suivante cellule._suivante = cell def supprimer_apres(self, cellule=None): if self._tete is None or (cellule is not None and cellule._suivante is None): raise IndexError("Liste vide!") self._taille -= 1 # supprimer en tête if cellule is None: v = self.tete.valeur if self._tete._suivante is None: self._queue = None self._tete = self.tete._suivante return v # ailleurs v = cellule._suivante.valeur # mais peut-être la queue if cellule._suivante is self._queue: self._queue = cellule cellule._suivante = cellule._suivante._suivante # penser à renvoyer la valeur effectivement supprimée return v if __name__ == "__main__": test = Cellule(1, Cellule(2)) assert str(test) == "1 → 2" l = Liste() assert str(l) == "None" l.inserer_apres(1) l.inserer_apres(2) assert str(l) == "2 → 1" assert len(l) == 2 assert l.tete.valeur == 2 assert l.tete.suivante.valeur == 1 l.inserer_apres(3) l.supprimer_apres() assert l.tete.valeur == 2 l.inserer_apres(3) l.supprimer_apres(l.tete) assert l.tete.valeur == 3 and l.tete.suivante.valeur == 1 l.supprimer_apres(l.tete) assert l.queue is l.tete
true
true
1c3909bc4bd933e38f38b04f0fc61f7b50cb080d
227
py
Python
helper.py
mohammadjafri1992/simple_py_cli
a77b5fc27813b4b1572613d6ffb5f8b2d7647a55
[ "MIT" ]
null
null
null
helper.py
mohammadjafri1992/simple_py_cli
a77b5fc27813b4b1572613d6ffb5f8b2d7647a55
[ "MIT" ]
1
2020-08-07T03:13:08.000Z
2020-08-07T03:13:08.000Z
helper.py
mohammadjafri1992/simple_py_cli
a77b5fc27813b4b1572613d6ffb5f8b2d7647a55
[ "MIT" ]
null
null
null
def _greet_user(user): print("Hello, ", user) def get_user(): user = input("What is your name?") return user def interface_with_user(user): _greet_user(user) # Test# 11: This is another test for GitKraken. Not merging.
17.461538
60
0.713656
def _greet_user(user): print("Hello, ", user) def get_user(): user = input("What is your name?") return user def interface_with_user(user): _greet_user(user)
true
true
1c390a4922c1bec8289b04732867bd2ca4a2da77
3,674
py
Python
UNIOA/optimizer_running.py
Huilin-Li/UNIOA
0f2527eac955a7193406775e5b71fab35f064422
[ "MIT" ]
null
null
null
UNIOA/optimizer_running.py
Huilin-Li/UNIOA
0f2527eac955a7193406775e5b71fab35f064422
[ "MIT" ]
null
null
null
UNIOA/optimizer_running.py
Huilin-Li/UNIOA
0f2527eac955a7193406775e5b71fab35f064422
[ "MIT" ]
null
null
null
import time import ioh from datetime import datetime from .algs import * import sys, os from pydoc import locate # def optimizer_running(problems, instances, dimensions, num_runs, paras_set, optimizer_name, output_name): # Which_alg = output_name.split("_")[1] # folder_name = Which_alg + '_folder' # data_name = output_name # st = time.time() # print('---> ' + output_name + ' is optmizting', flush=True) # logger = ioh.logger.Analyzer(folder_name='DataFiles/'+folder_name+'/'+data_name, algorithm_name=output_name) # for p_id in problems: # print('P-id={}'.format(p_id), end=":", flush=True) # for d in dimensions: # print('d-{}'.format(d), end=":", flush=True) # for i_id in instances: # print('{}'.format(i_id), end="", flush=True) # func = ioh.get_problem(fid=p_id, dim=d, iid=i_id) # print('', end='(', flush=True) # for rep in range(num_runs): # #func.attach_logger(logger) # print('{}'.format(rep), end="", flush=True) # func.attach_logger(logger) # opt = eval(optimizer_name)(func, paras_set) # opt() # func.reset() # print('', end=')', flush=True) # # print('costs', round((time.time() - st) / 60, 2), 'minutes') # with open("DataFiles/runningtime_" + Which_alg + ".txt", "a+") as text_file: # date = datetime.now().strftime("%m/%d/%Y, %H:%M:%S") # runningtime = round((time.time() - st) / 60, 2) # print("{} | {}: {} minutes.".format(date, output_name, runningtime), file=text_file) # def optimizer_running(problems, instances, dimensions, num_runs, paras_set, optimizer_name): t = 0 optimizer_name_temp = optimizer_name UNIOA_algs = ['BA_UNIOA', 'CSA_UNIOA', 'MFO_UNIOA', 'PSO_UNIOA', 'GOA_UNIOA', 'MBO_UNIOA', 'BOA_UNIOA'] if optimizer_name not in UNIOA_algs: t = 1 file_name = os.path.basename(sys.argv[0])[:-2] your_optimizer_name = locate(file_name + optimizer_name) folder_name = optimizer_name_temp + '_folder' data_name = optimizer_name_temp st = time.time() print('----- ' + optimizer_name_temp + ' is optmizting your problem -----', flush=True) logger = ioh.logger.Analyzer(folder_name='DataFiles/'+folder_name+'/'+data_name, algorithm_name=optimizer_name_temp) for p_id in problems: print('P-id={}'.format(p_id), end=":", flush=True) for d in dimensions: print('d-{}'.format(d), end=":", flush=True) for i_id in instances: print('{}'.format(i_id), end="", flush=True) func = ioh.get_problem(fid=p_id, dim=d, iid=i_id) # func.attach_logger(logger) print('', end='(', flush=True) for rep in range(num_runs): func.attach_logger(logger) print('{}'.format(rep), end="", flush=True) if t == 1 : opt = your_optimizer_name(func, paras_set) else: opt = eval(optimizer_name)(func, paras_set) opt() func.reset() print('', end=')', flush=True) print('costs', round((time.time() - st) / 60, 2), 'minutes') with open("DataFiles/runningtime.txt", "a+") as text_file: date = datetime.now().strftime("%m/%d/%Y, %H:%M:%S") runningtime = round((time.time() - st) / 60, 2) print("{} | {}: {} minutes.".format(date, optimizer_name, runningtime), file=text_file)
44.26506
120
0.555253
import time import ioh from datetime import datetime from .algs import * import sys, os from pydoc import locate er_running(problems, instances, dimensions, num_runs, paras_set, optimizer_name): t = 0 optimizer_name_temp = optimizer_name UNIOA_algs = ['BA_UNIOA', 'CSA_UNIOA', 'MFO_UNIOA', 'PSO_UNIOA', 'GOA_UNIOA', 'MBO_UNIOA', 'BOA_UNIOA'] if optimizer_name not in UNIOA_algs: t = 1 file_name = os.path.basename(sys.argv[0])[:-2] your_optimizer_name = locate(file_name + optimizer_name) folder_name = optimizer_name_temp + '_folder' data_name = optimizer_name_temp st = time.time() print('----- ' + optimizer_name_temp + ' is optmizting your problem -----', flush=True) logger = ioh.logger.Analyzer(folder_name='DataFiles/'+folder_name+'/'+data_name, algorithm_name=optimizer_name_temp) for p_id in problems: print('P-id={}'.format(p_id), end=":", flush=True) for d in dimensions: print('d-{}'.format(d), end=":", flush=True) for i_id in instances: print('{}'.format(i_id), end="", flush=True) func = ioh.get_problem(fid=p_id, dim=d, iid=i_id) print('', end='(', flush=True) for rep in range(num_runs): func.attach_logger(logger) print('{}'.format(rep), end="", flush=True) if t == 1 : opt = your_optimizer_name(func, paras_set) else: opt = eval(optimizer_name)(func, paras_set) opt() func.reset() print('', end=')', flush=True) print('costs', round((time.time() - st) / 60, 2), 'minutes') with open("DataFiles/runningtime.txt", "a+") as text_file: date = datetime.now().strftime("%m/%d/%Y, %H:%M:%S") runningtime = round((time.time() - st) / 60, 2) print("{} | {}: {} minutes.".format(date, optimizer_name, runningtime), file=text_file)
true
true
1c390c681c2d3660293795ee39f4549157cbf995
3,947
py
Python
tests/unit/viz/test_legend.py
manmorjim/cartoframes
4172e3dcdaedf207c10772a6dffe4f43b1993230
[ "BSD-3-Clause" ]
null
null
null
tests/unit/viz/test_legend.py
manmorjim/cartoframes
4172e3dcdaedf207c10772a6dffe4f43b1993230
[ "BSD-3-Clause" ]
null
null
null
tests/unit/viz/test_legend.py
manmorjim/cartoframes
4172e3dcdaedf207c10772a6dffe4f43b1993230
[ "BSD-3-Clause" ]
null
null
null
import pytest from cartoframes.viz import Legend class TestLegend(object): def test_is_legend_defined(self): """Legend""" assert Legend is not None def test_legend_init_dict(self): """Legend should be properly initialized when passing a dict""" legend = Legend({ 'type': 'color-category', 'prop': 'strokeColor', 'title': '[TITLE]', 'description': '[description]', 'footer': '[footer]' }) assert legend._type == 'color-category' assert legend._prop == 'strokeColor' assert legend._title == '[TITLE]' assert legend._description == '[description]' assert legend._footer == '[footer]' assert legend._dynamic is True def test_legend_init_properties(self): """Legend should be properly initialized when passing properties""" legend = Legend('color-category', prop='strokeColor', title='[TITLE]', description='[description]', footer='[footer]', dynamic=False) assert legend._type == 'color-category' assert legend._prop == 'strokeColor' assert legend._title == '[TITLE]' assert legend._description == '[description]' assert legend._footer == '[footer]' assert legend._dynamic is False def test_legend_info(self): """Legend should return a proper information object""" legend = Legend({ 'type': 'color-category', 'title': '[TITLE]', 'description': '[description]', 'footer': '[footer]' }) assert legend.get_info() == { 'type': 'color-category', 'prop': 'color', 'title': '[TITLE]', 'description': '[description]', 'footer': '[footer]', 'dynamic': True, 'variable': '' } legend = Legend({ 'type': { 'point': 'color-category-point', 'line': 'color-category-line', 'polygon': 'color-category-polygon' } }) assert legend.get_info('line') == { 'type': 'color-category-line', 'prop': 'color', 'title': '', 'description': '', 'footer': '', 'dynamic': True, 'variable': '' } def test_wrong_input(self): """Legend should raise an error if legend input is not valid""" msg = 'Wrong legend input.' with pytest.raises(ValueError) as e: Legend(1234) assert str(e.value) == msg def test_wrong_type(self): """Legend should raise an error if legend type is not valid""" msg = 'Legend type "xxx" is not valid. Valid legend types are: default, ' +\ 'color-bins, color-bins-line, color-bins-point, color-bins-polygon, ' + \ 'color-category, color-category-line, color-category-point, color-category-polygon, ' + \ 'color-continuous, color-continuous-line, color-continuous-point, color-continuous-polygon, ' + \ 'size-bins, size-bins-line, size-bins-point, ' + \ 'size-category, size-category-line, size-category-point, ' + \ 'size-continuous, size-continuous-line, size-continuous-point.' with pytest.raises(ValueError) as e: Legend({'type': 'xxx'}).get_info() assert str(e.value) == msg def test_wrong_prop(self): """Legend should raise an error if legend prop is not valid""" msg = 'Legend property "xxx" is not valid. Valid legend properties are: ' + \ 'color, strokeColor, width, strokeWidth.' with pytest.raises(ValueError) as e: Legend({'type': 'color-category', 'prop': 'xxx'}).get_info() assert str(e.value) == msg
36.546296
109
0.53965
import pytest from cartoframes.viz import Legend class TestLegend(object): def test_is_legend_defined(self): assert Legend is not None def test_legend_init_dict(self): legend = Legend({ 'type': 'color-category', 'prop': 'strokeColor', 'title': '[TITLE]', 'description': '[description]', 'footer': '[footer]' }) assert legend._type == 'color-category' assert legend._prop == 'strokeColor' assert legend._title == '[TITLE]' assert legend._description == '[description]' assert legend._footer == '[footer]' assert legend._dynamic is True def test_legend_init_properties(self): legend = Legend('color-category', prop='strokeColor', title='[TITLE]', description='[description]', footer='[footer]', dynamic=False) assert legend._type == 'color-category' assert legend._prop == 'strokeColor' assert legend._title == '[TITLE]' assert legend._description == '[description]' assert legend._footer == '[footer]' assert legend._dynamic is False def test_legend_info(self): legend = Legend({ 'type': 'color-category', 'title': '[TITLE]', 'description': '[description]', 'footer': '[footer]' }) assert legend.get_info() == { 'type': 'color-category', 'prop': 'color', 'title': '[TITLE]', 'description': '[description]', 'footer': '[footer]', 'dynamic': True, 'variable': '' } legend = Legend({ 'type': { 'point': 'color-category-point', 'line': 'color-category-line', 'polygon': 'color-category-polygon' } }) assert legend.get_info('line') == { 'type': 'color-category-line', 'prop': 'color', 'title': '', 'description': '', 'footer': '', 'dynamic': True, 'variable': '' } def test_wrong_input(self): msg = 'Wrong legend input.' with pytest.raises(ValueError) as e: Legend(1234) assert str(e.value) == msg def test_wrong_type(self): msg = 'Legend type "xxx" is not valid. Valid legend types are: default, ' +\ 'color-bins, color-bins-line, color-bins-point, color-bins-polygon, ' + \ 'color-category, color-category-line, color-category-point, color-category-polygon, ' + \ 'color-continuous, color-continuous-line, color-continuous-point, color-continuous-polygon, ' + \ 'size-bins, size-bins-line, size-bins-point, ' + \ 'size-category, size-category-line, size-category-point, ' + \ 'size-continuous, size-continuous-line, size-continuous-point.' with pytest.raises(ValueError) as e: Legend({'type': 'xxx'}).get_info() assert str(e.value) == msg def test_wrong_prop(self): msg = 'Legend property "xxx" is not valid. Valid legend properties are: ' + \ 'color, strokeColor, width, strokeWidth.' with pytest.raises(ValueError) as e: Legend({'type': 'color-category', 'prop': 'xxx'}).get_info() assert str(e.value) == msg
true
true
1c390d3b6b3f17050b35232ecaab5093ede0711c
336
py
Python
helpline/qpanel/rq_worker.py
mbai93/myhelpline-1
8c6130ad7ce9637565e83988a45c0b2ff9c5d698
[ "BSD-3-Clause" ]
1
2018-07-15T13:13:43.000Z
2018-07-15T13:13:43.000Z
helpline/qpanel/rq_worker.py
mbai93/myhelpline-1
8c6130ad7ce9637565e83988a45c0b2ff9c5d698
[ "BSD-3-Clause" ]
14
2018-07-10T12:48:46.000Z
2022-03-11T23:24:51.000Z
helpline/qpanel/rq_worker.py
mbai93/myhelpline-1
8c6130ad7ce9637565e83988a45c0b2ff9c5d698
[ "BSD-3-Clause" ]
5
2018-07-04T07:59:14.000Z
2020-01-28T07:50:18.000Z
from panel.qpanel.job import start_process from multiprocessing import Process from rq_scheduler.scripts.rqscheduler import main def start_jobs(): p = Process(target=start_process) p.start() start_scheduler() def start_scheduler(): p = Process(target=main) p.start() if __name__ == '__main__': start_jobs()
18.666667
49
0.72619
from panel.qpanel.job import start_process from multiprocessing import Process from rq_scheduler.scripts.rqscheduler import main def start_jobs(): p = Process(target=start_process) p.start() start_scheduler() def start_scheduler(): p = Process(target=main) p.start() if __name__ == '__main__': start_jobs()
true
true
1c390e23f28cb806d6b057d3dc02d45614c84697
996
py
Python
account/urls.py
zerolfx/eoj3
156060399d1c3e5f7bcdbf34eaffbe2be66e1b20
[ "MIT" ]
1
2020-11-17T13:08:07.000Z
2020-11-17T13:08:07.000Z
account/urls.py
zerolfx/eoj3
156060399d1c3e5f7bcdbf34eaffbe2be66e1b20
[ "MIT" ]
null
null
null
account/urls.py
zerolfx/eoj3
156060399d1c3e5f7bcdbf34eaffbe2be66e1b20
[ "MIT" ]
null
null
null
from django.conf.urls import url from utils.site_settings import force_closed from . import views app_name = "account" urlpatterns = [ url(r'^settings/profile/$', views.UpdateProfileView.as_view(), name='profile', kwargs=force_closed()), url(r'^settings/security/$', views.my_password_change, name='security', kwargs=force_closed()), url(r'^settings/preference/$', views.UpdatePreferencesView.as_view(), name='preference', kwargs=force_closed()), url(r'^settings/username/update/$', views.ChangeUsernameView.as_view(), name='change_username'), url(r'^password_reset/$', views.my_password_reset, name='reset_password'), url(r'^password_reset_done/$', views.my_password_reset_done, name='password_reset_done'), url(r'^reset/(?P<uidb64>[0-9A-Za-z_\-]+)/(?P<token>[0-9A-Za-z]{1,13}-[0-9A-Za-z]{1,20})/$', views.my_password_reset_confirm, name='password_reset_confirm'), url(r'^ban/(?P<user_id>[0-9]+)/$', views.BanAccount.as_view(), name='ban_account'), ]
49.8
116
0.710843
from django.conf.urls import url from utils.site_settings import force_closed from . import views app_name = "account" urlpatterns = [ url(r'^settings/profile/$', views.UpdateProfileView.as_view(), name='profile', kwargs=force_closed()), url(r'^settings/security/$', views.my_password_change, name='security', kwargs=force_closed()), url(r'^settings/preference/$', views.UpdatePreferencesView.as_view(), name='preference', kwargs=force_closed()), url(r'^settings/username/update/$', views.ChangeUsernameView.as_view(), name='change_username'), url(r'^password_reset/$', views.my_password_reset, name='reset_password'), url(r'^password_reset_done/$', views.my_password_reset_done, name='password_reset_done'), url(r'^reset/(?P<uidb64>[0-9A-Za-z_\-]+)/(?P<token>[0-9A-Za-z]{1,13}-[0-9A-Za-z]{1,20})/$', views.my_password_reset_confirm, name='password_reset_confirm'), url(r'^ban/(?P<user_id>[0-9]+)/$', views.BanAccount.as_view(), name='ban_account'), ]
true
true
1c390f513174f38db1d3c2c1982522569666ed0f
4,592
py
Python
abusehelper/core/handlers.py
AbuseSA/abusehelper
3e953632d20317c6bfe7eeb987ea9104d8f2a957
[ "MIT" ]
117
2015-11-30T09:52:52.000Z
2021-11-24T23:58:13.000Z
abusehelper/core/handlers.py
AbuseSA/abusehelper
3e953632d20317c6bfe7eeb987ea9104d8f2a957
[ "MIT" ]
57
2015-12-08T10:06:57.000Z
2018-03-28T11:13:11.000Z
abusehelper/core/handlers.py
AbuseSA/abusehelper
3e953632d20317c6bfe7eeb987ea9104d8f2a957
[ "MIT" ]
29
2016-02-08T08:24:30.000Z
2022-03-31T13:53:15.000Z
import json import collections from . import bot, utils class HandlerParam(bot.Param): def parse(self, value): try: return json.loads(value) except ValueError: return value def load_handler(handler_spec): """ >>> import logging >>> log = logging.getLogger("dummy") >>> handler = load_handler({ ... "type": "abusehelper.core.mail.Handler" ... }) >>> type(handler(log=log)) <class 'abusehelper.core.mail.Handler'> >>> handler(log=log).log is log True Extra keys in aside from "type" will be given as keyword arguments when instantiating the handler. The arguments given to load_handler take priority over overlapping keyword arguments given at instantiation. >>> handler = load_handler({ ... "type": "abusehelper.core.mail.Handler", ... "log": log ... }) >>> handler().log is log True >>> other_log = logging.getLogger("other") >>> other_log is not log True >>> handler(log=other_log).log is log True Instead of a string the "type" key can contain a Handler type object. >>> from abusehelper.core.mail import Handler >>> handler = load_handler({ ... "type": Handler, ... "log": log ... }) >>> type(handler()) <class 'abusehelper.core.mail.Handler'> A plain string is a shorthand for {"type": <string>}, and a plain Handler type object is a shorthand for {"type": <object>}. >>> handler = load_handler("abusehelper.core.mail.Handler") >>> type(handler(log=log)) <class 'abusehelper.core.mail.Handler'> >>> handler = load_handler(Handler) >>> type(handler(log=log)) <class 'abusehelper.core.mail.Handler'> ValueError will be raised when there is no "type" key and the argument is not a shorthand. >>> load_handler({}) Traceback (most recent call last): ... ValueError: missing key 'type' """ if isinstance(handler_spec, collections.Mapping): handler_dict = dict(handler_spec) try: type_path = handler_dict.pop("type") except KeyError: raise ValueError("missing key 'type'") type_ = _load_callable(type_path) return _wrap_handler(type_, **handler_dict) # Wrap with anyway to force all arguments to be given as keyword arguments. type_ = _load_callable(handler_spec) return _wrap_handler(type_) def _wrap_handler(type_, **fixed): def _wrapper(**defaults): kwargs = dict(defaults) kwargs.update(fixed) return type_(**kwargs) return _wrapper def _load_callable(value): r""" Load and return a callable. >>> import uuid >>> _load_callable("uuid.UUID") == uuid.UUID True If the value is not a string but a callable object then return it as-is. >>> _load_callable(uuid.UUID) == uuid.UUID True if the value is neither a string nor a callable then raise TypeError. >>> _load_callable(2) Traceback (most recent call last): ... TypeError: expected a string or a callable, got int If the value is a string but points to a non-callable then raise TypeError. >>> _load_callable("uuid.NAMESPACE_DNS") Traceback (most recent call last): ... TypeError: expected a string or a callable, got uuid.UUID Raise ValueError if the path is not valid. >>> _load_callable("SomeClass") Traceback (most recent call last): ... ValueError: missing module name Raise ImportError if the callable cannot be loaded. >>> _load_callable("abusehelper.nonexisting.SomeClass") Traceback (most recent call last): ... ImportError: no module named 'abusehelper.nonexisting' >>> _load_callable("abusehelper.NonExistingClass") Traceback (most recent call last): ... ImportError: module 'abusehelper' has no attribute 'NonExistingClass' """ if isinstance(value, basestring): module, _, name = value.rpartition(".") if not module: raise ValueError("missing module name") try: mod = __import__(module, fromlist=[name]) except ImportError: raise ImportError("no module named '{0}'".format(module)) try: value = getattr(mod, name) except AttributeError: raise ImportError("module '{0}' has no attribute '{1}'".format(module, name)) if not callable(value): raise TypeError("expected a string or a callable, got {0}".format(utils.format_type(value))) return value
28.521739
100
0.633493
import json import collections from . import bot, utils class HandlerParam(bot.Param): def parse(self, value): try: return json.loads(value) except ValueError: return value def load_handler(handler_spec): if isinstance(handler_spec, collections.Mapping): handler_dict = dict(handler_spec) try: type_path = handler_dict.pop("type") except KeyError: raise ValueError("missing key 'type'") type_ = _load_callable(type_path) return _wrap_handler(type_, **handler_dict) type_ = _load_callable(handler_spec) return _wrap_handler(type_) def _wrap_handler(type_, **fixed): def _wrapper(**defaults): kwargs = dict(defaults) kwargs.update(fixed) return type_(**kwargs) return _wrapper def _load_callable(value): if isinstance(value, basestring): module, _, name = value.rpartition(".") if not module: raise ValueError("missing module name") try: mod = __import__(module, fromlist=[name]) except ImportError: raise ImportError("no module named '{0}'".format(module)) try: value = getattr(mod, name) except AttributeError: raise ImportError("module '{0}' has no attribute '{1}'".format(module, name)) if not callable(value): raise TypeError("expected a string or a callable, got {0}".format(utils.format_type(value))) return value
true
true
1c39104a082000a3ca295c53bab812baf8df9962
1,656
py
Python
app/tool_results/microbe_directory/tests/factory.py
MetaGenScope/metagenscope-server
609cd57c626c857c8efde8237a1f22f4d1e6065d
[ "MIT" ]
null
null
null
app/tool_results/microbe_directory/tests/factory.py
MetaGenScope/metagenscope-server
609cd57c626c857c8efde8237a1f22f4d1e6065d
[ "MIT" ]
null
null
null
app/tool_results/microbe_directory/tests/factory.py
MetaGenScope/metagenscope-server
609cd57c626c857c8efde8237a1f22f4d1e6065d
[ "MIT" ]
null
null
null
"""Factory for generating Kraken result models for testing.""" from random import random from app.tool_results.microbe_directory import MicrobeDirectoryToolResult def create_values(): """Create microbe directory values.""" return { 'gram_stain': { 'gram_positive': random(), 'gram_negative': random(), 'unknown': random(), }, 'microbiome_location': { 'human': random(), 'non_human': random(), 'unknown': random(), }, 'antimicrobial_susceptibility': { 'known_abx': random(), 'unknown': random(), }, 'optimal_temperature': { '37c': random(), 'unknown': random(), }, 'extreme_environment': { 'mesophile': random(), 'unknown': random(), }, 'biofilm_forming': { 'yes': random(), 'unknown': random(), }, 'optimal_ph': { 'unknown': random(), }, 'animal_pathogen': { 'unknown': random(), }, 'spore_forming': { 'no': random(), 'unknown': random(), }, 'pathogenicity': { 'cogem_1': random(), 'cogem_2': random(), 'unknown': random(), }, 'plant_pathogen': { 'no': random(), 'unknown': random(), } } def create_microbe_directory(): """Create MicrobeDirectoryToolResult with randomized field data.""" packed_data = create_values() return MicrobeDirectoryToolResult(**packed_data).save()
26.285714
73
0.490942
from random import random from app.tool_results.microbe_directory import MicrobeDirectoryToolResult def create_values(): return { 'gram_stain': { 'gram_positive': random(), 'gram_negative': random(), 'unknown': random(), }, 'microbiome_location': { 'human': random(), 'non_human': random(), 'unknown': random(), }, 'antimicrobial_susceptibility': { 'known_abx': random(), 'unknown': random(), }, 'optimal_temperature': { '37c': random(), 'unknown': random(), }, 'extreme_environment': { 'mesophile': random(), 'unknown': random(), }, 'biofilm_forming': { 'yes': random(), 'unknown': random(), }, 'optimal_ph': { 'unknown': random(), }, 'animal_pathogen': { 'unknown': random(), }, 'spore_forming': { 'no': random(), 'unknown': random(), }, 'pathogenicity': { 'cogem_1': random(), 'cogem_2': random(), 'unknown': random(), }, 'plant_pathogen': { 'no': random(), 'unknown': random(), } } def create_microbe_directory(): packed_data = create_values() return MicrobeDirectoryToolResult(**packed_data).save()
true
true
1c391078e21a3e42bb1c73182f9827a91c3d06ee
16,562
py
Python
bird/_bird.py
wavelets/bird
ae0fe470a6517e34bfe8713fe389f0a2dd223afe
[ "BSD-3-Clause" ]
1
2017-05-05T20:15:44.000Z
2017-05-05T20:15:44.000Z
bird/_bird.py
wavelets/bird
ae0fe470a6517e34bfe8713fe389f0a2dd223afe
[ "BSD-3-Clause" ]
null
null
null
bird/_bird.py
wavelets/bird
ae0fe470a6517e34bfe8713fe389f0a2dd223afe
[ "BSD-3-Clause" ]
null
null
null
# -*- coding: utf-8 -*- # Authors: Alexandre Gramfort <alexandre.gramfort@telecom-paristech.fr> # Manuel Moussallam <manuel.moussallam@gmail.com> # # Algorithm presented here are described in: # Blind Denoising with Random Greedy Pursuits. # Moussallam, M., Gramfort, A., Daudet, L., & Richard, G. (2014). # IEEE Signal Processing Letters, 21(11), 1341�1345 # # License: BSD (3-clause) from math import sqrt import multiprocessing from functools import partial import numpy as np from scipy.special import erfinv from scipy import linalg from joblib import Parallel, delayed, Memory from mdct_tools import mdct_waveform, mdct, MDCT def check_random_state(seed): """Turn seed into a np.random.RandomState instance If seed is None, return the RandomState singleton used by np.random. If seed is an int, return a new RandomState instance seeded with seed. If seed is already a RandomState instance, return it. Otherwise raise ValueError. """ if seed is None or seed is np.random: return np.random.mtrand._rand if isinstance(seed, (int, np.integer)): return np.random.RandomState(seed) if isinstance(seed, np.random.RandomState): return seed raise ValueError('%r cannot be used to seed a numpy.random.RandomState' ' instance' % seed) def _single_mp_run(x, Phi, bound, max_iter, verbose=False, pad=0, random_state=None, memory=Memory(None)): """ run of the RSSMP algorithm """ rng = check_random_state(random_state) pad = int(pad) x = np.concatenate((np.zeros(pad), x, np.zeros(pad))) n = x.size m = Phi.doth(x).size err_mse = [] # Initialisation residual = np.concatenate((x.copy(), np.zeros(max(Phi.sizes) / 2))) s = np.zeros(m) x_est = np.zeros(n) # Main algorithm coeffs = np.zeros(m) it_number = 0 current_lambda = 1 err_mse.append(linalg.norm(residual)) # Decomposition loop: stopping criteria is either SNR or iteration number while (current_lambda > bound) & (it_number < max_iter): # pick a shift at random : in each size rndshifts = [] for scale_idx, size in enumerate(Phi.sizes): shift = rng.randint(low=0, high=size / 4) coeffs[scale_idx * n:(scale_idx + 1) * n] = mdct( residual[shift:shift + n], size).ravel() rndshifts.append(shift) # Select a new element idx = np.argmax(np.abs(coeffs)) # Update coefficients s[idx] += coeffs[idx] # Only one method now : local update via a cached waveform # find scale and frequency bin of selected atom mdct_wf = memory.cache(mdct_waveform) scale_idx = idx // n size = Phi.sizes[scale_idx] F = n // (size // 2) frame = (idx - (scale_idx * n)) % F freq_bin = ((idx - (scale_idx * n))) // F pos = (frame * size / 2) - size / 4 + rndshifts[scale_idx] residual[pos:pos + size] -= coeffs[idx] * mdct_wf(size, freq_bin) # also add it to the reconstruction x_est[pos:pos + size] += coeffs[idx] * mdct_wf(size, freq_bin) # error computation (err_mse) err_mse.append(linalg.norm(residual)) current_lambda = np.sqrt(1 - err_mse[-1] / err_mse[-2]) if current_lambda <= bound: x_est[pos:pos + size] -= coeffs[idx] * mdct_wf(size, freq_bin) if verbose: print("Iteration %d : Current lambda of %1.4f" % ( it_number, current_lambda)) it_number += 1 return x_est, err_mse def _single_multichannel_mp_run(X, Phi, bound, selection_rule, stop_crit, max_iter, verbose=False, pad=0, random_state=None, memory=Memory(None)): """ run of the structured variant of the RSSMP algorithm """ rng = check_random_state(random_state) # padding as v stak pad = int(pad) n_channels = X.shape[0] X = np.hstack((np.zeros((n_channels, pad)), X, np.zeros((n_channels, pad)))) n_samples = X.shape[1] n_projs = Phi.doth(X).shape[1] err_mse = {} # Initialisation residual = np.hstack((X.copy(), np.zeros((n_channels, max(Phi.sizes) / 2)))) s_rep = np.zeros((n_channels, n_projs)) X_est = np.zeros((n_channels, n_samples)) # Main algorithm coeffs = np.zeros((n_channels, n_projs)) it_number = 0 current_lambda = 1 for c_idx in range(n_channels): err_mse[c_idx] = [] err_mse[c_idx].append(linalg.norm(residual[c_idx, :])) # Decomposition loop: stopping criteria is either SNR or iteration number while (current_lambda > bound) & (it_number < max_iter): # pick a shift at random : in each size rndshifts = {} for c_idx in range(n_channels): rndshifts[c_idx] = [] for s_idx, L in enumerate(Phi.sizes): shift = rng.randint(low=0, high=L / 4) for c_idx in range(n_channels): coeffs[c_idx, s_idx * n_samples:(s_idx + 1) * n_samples] = \ mdct(residual[c_idx, shift:shift + n_samples], L).ravel() rndshifts[c_idx].append(shift) # Multichannel mode : we combine projections combined = selection_rule(coeffs ** 2) # Select a new element idx = np.argmax(np.abs(combined)) # find scale and frequency bin of selected atom s_idx = idx // n_samples L = Phi.sizes[s_idx] F = n_samples // (L // 2) frame = (idx - (s_idx * n_samples)) % F freq_bin = ((idx - (s_idx * n_samples))) // F mdct_wf = memory.cache(mdct_waveform) # Update coefficients and residual current_lambda_array = np.zeros(n_channels) for c_idx in range(n_channels): s_rep[c_idx, idx] += coeffs[c_idx, idx] # Only one method now : local update via a cached waveform pos = (frame * L / 2) - L / 4 + rndshifts[c_idx][s_idx] residual[c_idx, pos:pos + L] -= coeffs[c_idx, idx] * \ mdct_wf(L, freq_bin) # also add it to the reconstruction X_est[c_idx, pos:pos + L] += coeffs[c_idx, idx] * \ mdct_wf(L, freq_bin) # error computation (err_mse) err_mse[c_idx].append(linalg.norm(residual[c_idx, :])) current_lambda_array[c_idx] = np.sqrt( 1. - err_mse[c_idx][-1] / err_mse[c_idx][-2]) current_lambda = stop_crit(current_lambda_array) if verbose: print("Iteration %d : Current lambda of %1.4f" % ( it_number, current_lambda)) it_number += 1 return X_est[:, pad: -pad], err_mse def _pad(X): """ add zeroes on the border to make sure the signal length is a power of two """ p_above = int(np.floor(np.log2(X.shape[1]))) M = 2 ** (p_above + 1) - X.shape[1] X = np.hstack((np.zeros((X.shape[0], M)), X)) return X, M def _denoise(seeds, x, dico, sup_bound, n_atoms, verbose=False, indep=True, stop_crit=None, selection_rule=None, pad=0, memory=Memory(None)): """ multiple rssmp runs with a smart stopping criterion using the convergence decay monitoring """ approx = [] for seed in seeds: if verbose > 0: print("Run seed %d" % seed) if indep: approx.append(_single_mp_run(x, dico, sup_bound, n_atoms, verbose=verbose, pad=pad, random_state=seed, memory=memory)[0]) else: approx.append(_single_multichannel_mp_run(x, dico, sup_bound, selection_rule, stop_crit, n_atoms, verbose=verbose, pad=pad, random_state=seed, memory=memory)[0]) return approx def _bird_core(X, scales, n_runs, Lambda_W, max_iter=100, stop_crit=np.mean, selection_rule=np.sum, n_jobs=1, indep=True, random_state=None, memory=Memory(None), verbose=False): """Automatically detect when noise zone has been reached and stop MP at this point Parameters ---------- X : array, shape (n_channels, n_times) The numpy n_channels-vy-N array to be denoised where n_channels is number of sensors and N the dimension scales : list The list of MDCT scales that will be used to built the dictionary Phi n_runs : int the number of runs (n_runs in the paper) Lambda_W : float bound for lambda under which a run will be stopped max_iter : int Maximum number of iterations (serves as alternate stopping criterion) stop_crit : function controls the calculation of Lambda selection_rule : callable controls the way multiple channel projections are combined for atom selection only used if indep=False n_jobs : int number of jobs to run in parallel indep : bool True for BIRD (independent processing of each channel, False for S-BIRD (structured sparsity seeked) random_state : None | int | np.random.RandomState To specify the random generator state (seed). memory : instance of Memory The object to use to cache some computations. If cachedir is None, no caching is performed. verbose : bool verbose mode Returns ------- X_denoise : array, shape (n_channels, n_times) denoised array of same shape as X """ Phi = MDCT(scales) pad = int(1.5 * max(scales)) X_denoise = np.zeros_like(X) approx = [] rng = check_random_state(random_state) seeds = rng.randint(4294967295, size=n_runs) # < max seed value if n_jobs <= 0: n_cores = multiprocessing.cpu_count() n_jobs = min(n_cores + n_jobs + 1, n_cores) if indep: # Independent treat of each channel (plain BIRD) for r, x in zip(X_denoise, X): this_approx = Parallel(n_jobs=n_jobs)( delayed(_denoise)(this_seeds, x, Phi, Lambda_W, max_iter, pad=pad, verbose=verbose, indep=True, memory=memory) for this_seeds in np.array_split(seeds, n_jobs)) this_approx = sum(this_approx[1:], this_approx[0]) r[:] = sum([a[pad:-pad] for a in this_approx]) approx.append(this_approx) else: # data need to be processed jointly this_approx = Parallel(n_jobs=n_jobs)( delayed(_denoise)(this_seeds, X, Phi, Lambda_W, max_iter, pad=pad, verbose=verbose, selection_rule=selection_rule, indep=False, memory=memory, stop_crit=stop_crit) for this_seeds in np.array_split(seeds, n_jobs)) # reconstruction by averaging for jidx in range(len(this_approx)): for ridx in range(len(this_approx[jidx])): X_denoise += this_approx[jidx][ridx] X_denoise /= float(n_runs) return X_denoise def bird(X, scales, n_runs, p_above, max_iter=100, random_state=None, n_jobs=1, memory=Memory(None), verbose=False): """ The BIRD algorithm as described in the paper Parameters ---------- X : array, shape (n_channels, n_times) The numpy n_channels-vy-N array to be X_denoised where n_channels is number of sensors and n_times the dimension scales : list The list of MDCT scales that will be used to built the dictionary Phi n_runs : int the number of runs (n_runs in the paper) p_above : float probability of appearance of the max above which the noise hypothesis is considered false max_iter : int The maximum number of iterations in one pursuit. random_state : None | int | np.random.RandomState To specify the random generator state (seed). max_iter : int The maximum number of iterations in one pursuit. n_jobs : int The number of jobs to run in parallel. memory : instance of Memory The object to use to cache some computations. If cachedir is None, no caching is performed. verbose : bool verbose mode Returns ------- X_denoise : array, shape (n_channels, n_times) The X_denoised data. """ X, prepad = _pad(X) # Computing Lambda_W(Phi, p_above) N = float(X.shape[1]) # size of the full shift-invariant dictionary M = np.sum(np.array(scales) / 2) * N sigma = sqrt((1.0 - (2.0 / np.pi)) / float(N)) Lambda_W = sigma * sqrt(2.0) * erfinv((1.0 - p_above) ** (1.0 / float(M))) print("Starting BIRD with MDCT dictionary of %d Atoms. " "Lambda_W=%1.3f, n_runs=%d" % (M, Lambda_W, n_runs)) X_denoised = _bird_core(X, scales, n_runs, Lambda_W, verbose=verbose, max_iter=max_iter, indep=True, n_jobs=n_jobs, random_state=random_state, memory=memory) return X_denoised[:, prepad:] # the stopping criterion is determined by the p_active parameter def stop_crit(lambda_array, lint): lambda_array.sort() return np.mean(lambda_array[-int(lint):]) def selection_rule(projections_matrix, lint): sorted_projs = np.sort(projections_matrix ** 2, axis=0) return np.mean(sorted_projs[-lint:, :], axis=0) def s_bird(X, scales, n_runs, p_above, p_active=1, max_iter=100, random_state=None, n_jobs=1, memory=Memory(None), verbose=False): """ Multichannel version of BIRD (S-BIRD) seeking Structured Sparsity Parameters ---------- X : array, shape (n_channels, n_times) The numpy n_channels-vy-n_samples array to be denoised where n_channels is the number of sensors and n_samples the dimension scales : list of int The list of MDCT scales that will be used to built the dictionary Phi n_runs : int the number of runs (n_runs in the paper) p_above : float probability of appearance of the max above which the noise hypothesis is considered false p_active : float proportion of active channels (l in the paper) max_iter : int The maximum number of iterations in one pursuit. random_state : None | int | np.random.RandomState To specify the random generator state (seed). n_jobs : int The number of jobs to run in parallel. memory : instance of Memory The object to use to cache some computations. If cachedir is None, no caching is performed. verbose : bool verbose mode Returns ------- X_denoise : array, shape (n_channels, n_times) The denoised data. """ X, prepad = _pad(X) # Computing Lambda_W(Phi, p_above) n_channels = X.shape[0] n_samples = float(X.shape[1]) # size of the full shift-invariant dictionary M = np.sum(np.array(scales) / 2) * n_samples sigma = sqrt((1.0 - (2.0 / np.pi)) / float(n_samples)) Lambda_W = sigma * sqrt(2.0) * erfinv((1.0 - p_above) ** (1.0 / float(M))) lint = int(n_channels * p_active) this_stop_crit = partial(stop_crit, lint=lint) # XXX : check lint here this_selection_rule = partial(selection_rule, lint=lint) print("Starting S-BIRD with MDCT dictionary of %d Atoms." " Lambda_W=%1.3f, n_runs=%d, p_active=%1.1f" % (M, Lambda_W, n_runs, p_active)) denoised = _bird_core(X, scales, n_runs, Lambda_W, verbose=verbose, stop_crit=this_stop_crit, n_jobs=n_jobs, selection_rule=this_selection_rule, max_iter=max_iter, indep=False, memory=memory) return denoised[:, prepad:]
37.134529
79
0.586282
from math import sqrt import multiprocessing from functools import partial import numpy as np from scipy.special import erfinv from scipy import linalg from joblib import Parallel, delayed, Memory from mdct_tools import mdct_waveform, mdct, MDCT def check_random_state(seed): if seed is None or seed is np.random: return np.random.mtrand._rand if isinstance(seed, (int, np.integer)): return np.random.RandomState(seed) if isinstance(seed, np.random.RandomState): return seed raise ValueError('%r cannot be used to seed a numpy.random.RandomState' ' instance' % seed) def _single_mp_run(x, Phi, bound, max_iter, verbose=False, pad=0, random_state=None, memory=Memory(None)): rng = check_random_state(random_state) pad = int(pad) x = np.concatenate((np.zeros(pad), x, np.zeros(pad))) n = x.size m = Phi.doth(x).size err_mse = [] residual = np.concatenate((x.copy(), np.zeros(max(Phi.sizes) / 2))) s = np.zeros(m) x_est = np.zeros(n) coeffs = np.zeros(m) it_number = 0 current_lambda = 1 err_mse.append(linalg.norm(residual)) while (current_lambda > bound) & (it_number < max_iter): rndshifts = [] for scale_idx, size in enumerate(Phi.sizes): shift = rng.randint(low=0, high=size / 4) coeffs[scale_idx * n:(scale_idx + 1) * n] = mdct( residual[shift:shift + n], size).ravel() rndshifts.append(shift) idx = np.argmax(np.abs(coeffs)) s[idx] += coeffs[idx] mdct_wf = memory.cache(mdct_waveform) scale_idx = idx // n size = Phi.sizes[scale_idx] F = n // (size // 2) frame = (idx - (scale_idx * n)) % F freq_bin = ((idx - (scale_idx * n))) // F pos = (frame * size / 2) - size / 4 + rndshifts[scale_idx] residual[pos:pos + size] -= coeffs[idx] * mdct_wf(size, freq_bin) x_est[pos:pos + size] += coeffs[idx] * mdct_wf(size, freq_bin) err_mse.append(linalg.norm(residual)) current_lambda = np.sqrt(1 - err_mse[-1] / err_mse[-2]) if current_lambda <= bound: x_est[pos:pos + size] -= coeffs[idx] * mdct_wf(size, freq_bin) if verbose: print("Iteration %d : Current lambda of %1.4f" % ( it_number, current_lambda)) it_number += 1 return x_est, err_mse def _single_multichannel_mp_run(X, Phi, bound, selection_rule, stop_crit, max_iter, verbose=False, pad=0, random_state=None, memory=Memory(None)): rng = check_random_state(random_state) pad = int(pad) n_channels = X.shape[0] X = np.hstack((np.zeros((n_channels, pad)), X, np.zeros((n_channels, pad)))) n_samples = X.shape[1] n_projs = Phi.doth(X).shape[1] err_mse = {} residual = np.hstack((X.copy(), np.zeros((n_channels, max(Phi.sizes) / 2)))) s_rep = np.zeros((n_channels, n_projs)) X_est = np.zeros((n_channels, n_samples)) coeffs = np.zeros((n_channels, n_projs)) it_number = 0 current_lambda = 1 for c_idx in range(n_channels): err_mse[c_idx] = [] err_mse[c_idx].append(linalg.norm(residual[c_idx, :])) while (current_lambda > bound) & (it_number < max_iter): rndshifts = {} for c_idx in range(n_channels): rndshifts[c_idx] = [] for s_idx, L in enumerate(Phi.sizes): shift = rng.randint(low=0, high=L / 4) for c_idx in range(n_channels): coeffs[c_idx, s_idx * n_samples:(s_idx + 1) * n_samples] = \ mdct(residual[c_idx, shift:shift + n_samples], L).ravel() rndshifts[c_idx].append(shift) combined = selection_rule(coeffs ** 2) idx = np.argmax(np.abs(combined)) s_idx = idx // n_samples L = Phi.sizes[s_idx] F = n_samples // (L // 2) frame = (idx - (s_idx * n_samples)) % F freq_bin = ((idx - (s_idx * n_samples))) // F mdct_wf = memory.cache(mdct_waveform) current_lambda_array = np.zeros(n_channels) for c_idx in range(n_channels): s_rep[c_idx, idx] += coeffs[c_idx, idx] pos = (frame * L / 2) - L / 4 + rndshifts[c_idx][s_idx] residual[c_idx, pos:pos + L] -= coeffs[c_idx, idx] * \ mdct_wf(L, freq_bin) X_est[c_idx, pos:pos + L] += coeffs[c_idx, idx] * \ mdct_wf(L, freq_bin) err_mse[c_idx].append(linalg.norm(residual[c_idx, :])) current_lambda_array[c_idx] = np.sqrt( 1. - err_mse[c_idx][-1] / err_mse[c_idx][-2]) current_lambda = stop_crit(current_lambda_array) if verbose: print("Iteration %d : Current lambda of %1.4f" % ( it_number, current_lambda)) it_number += 1 return X_est[:, pad: -pad], err_mse def _pad(X): p_above = int(np.floor(np.log2(X.shape[1]))) M = 2 ** (p_above + 1) - X.shape[1] X = np.hstack((np.zeros((X.shape[0], M)), X)) return X, M def _denoise(seeds, x, dico, sup_bound, n_atoms, verbose=False, indep=True, stop_crit=None, selection_rule=None, pad=0, memory=Memory(None)): approx = [] for seed in seeds: if verbose > 0: print("Run seed %d" % seed) if indep: approx.append(_single_mp_run(x, dico, sup_bound, n_atoms, verbose=verbose, pad=pad, random_state=seed, memory=memory)[0]) else: approx.append(_single_multichannel_mp_run(x, dico, sup_bound, selection_rule, stop_crit, n_atoms, verbose=verbose, pad=pad, random_state=seed, memory=memory)[0]) return approx def _bird_core(X, scales, n_runs, Lambda_W, max_iter=100, stop_crit=np.mean, selection_rule=np.sum, n_jobs=1, indep=True, random_state=None, memory=Memory(None), verbose=False): Phi = MDCT(scales) pad = int(1.5 * max(scales)) X_denoise = np.zeros_like(X) approx = [] rng = check_random_state(random_state) seeds = rng.randint(4294967295, size=n_runs) if n_jobs <= 0: n_cores = multiprocessing.cpu_count() n_jobs = min(n_cores + n_jobs + 1, n_cores) if indep: for r, x in zip(X_denoise, X): this_approx = Parallel(n_jobs=n_jobs)( delayed(_denoise)(this_seeds, x, Phi, Lambda_W, max_iter, pad=pad, verbose=verbose, indep=True, memory=memory) for this_seeds in np.array_split(seeds, n_jobs)) this_approx = sum(this_approx[1:], this_approx[0]) r[:] = sum([a[pad:-pad] for a in this_approx]) approx.append(this_approx) else: this_approx = Parallel(n_jobs=n_jobs)( delayed(_denoise)(this_seeds, X, Phi, Lambda_W, max_iter, pad=pad, verbose=verbose, selection_rule=selection_rule, indep=False, memory=memory, stop_crit=stop_crit) for this_seeds in np.array_split(seeds, n_jobs)) for jidx in range(len(this_approx)): for ridx in range(len(this_approx[jidx])): X_denoise += this_approx[jidx][ridx] X_denoise /= float(n_runs) return X_denoise def bird(X, scales, n_runs, p_above, max_iter=100, random_state=None, n_jobs=1, memory=Memory(None), verbose=False): X, prepad = _pad(X) N = float(X.shape[1]) M = np.sum(np.array(scales) / 2) * N sigma = sqrt((1.0 - (2.0 / np.pi)) / float(N)) Lambda_W = sigma * sqrt(2.0) * erfinv((1.0 - p_above) ** (1.0 / float(M))) print("Starting BIRD with MDCT dictionary of %d Atoms. " "Lambda_W=%1.3f, n_runs=%d" % (M, Lambda_W, n_runs)) X_denoised = _bird_core(X, scales, n_runs, Lambda_W, verbose=verbose, max_iter=max_iter, indep=True, n_jobs=n_jobs, random_state=random_state, memory=memory) return X_denoised[:, prepad:] def stop_crit(lambda_array, lint): lambda_array.sort() return np.mean(lambda_array[-int(lint):]) def selection_rule(projections_matrix, lint): sorted_projs = np.sort(projections_matrix ** 2, axis=0) return np.mean(sorted_projs[-lint:, :], axis=0) def s_bird(X, scales, n_runs, p_above, p_active=1, max_iter=100, random_state=None, n_jobs=1, memory=Memory(None), verbose=False): X, prepad = _pad(X) n_channels = X.shape[0] n_samples = float(X.shape[1]) M = np.sum(np.array(scales) / 2) * n_samples sigma = sqrt((1.0 - (2.0 / np.pi)) / float(n_samples)) Lambda_W = sigma * sqrt(2.0) * erfinv((1.0 - p_above) ** (1.0 / float(M))) lint = int(n_channels * p_active) this_stop_crit = partial(stop_crit, lint=lint) this_selection_rule = partial(selection_rule, lint=lint) print("Starting S-BIRD with MDCT dictionary of %d Atoms." " Lambda_W=%1.3f, n_runs=%d, p_active=%1.1f" % (M, Lambda_W, n_runs, p_active)) denoised = _bird_core(X, scales, n_runs, Lambda_W, verbose=verbose, stop_crit=this_stop_crit, n_jobs=n_jobs, selection_rule=this_selection_rule, max_iter=max_iter, indep=False, memory=memory) return denoised[:, prepad:]
true
true
1c3910cf551f794e5779d21ed10f3b3bae511add
7,975
py
Python
lib/galaxy/workflow/resources/__init__.py
rikeshi/galaxy
c536a877e4a9b3d12aa0d00fd4d5e705109a0d0a
[ "CC-BY-3.0" ]
4
2015-05-12T20:36:41.000Z
2017-06-26T15:34:02.000Z
lib/galaxy/workflow/resources/__init__.py
rikeshi/galaxy
c536a877e4a9b3d12aa0d00fd4d5e705109a0d0a
[ "CC-BY-3.0" ]
52
2015-03-16T14:02:14.000Z
2021-12-24T09:50:23.000Z
lib/galaxy/workflow/resources/__init__.py
rikeshi/galaxy
c536a877e4a9b3d12aa0d00fd4d5e705109a0d0a
[ "CC-BY-3.0" ]
1
2016-03-21T12:54:06.000Z
2016-03-21T12:54:06.000Z
"""This package is something a placeholder for workflow resource parameters. This file defines the baked in resource mapper types, and this package contains an example of a more open, pluggable approach with greater control. """ import functools import logging import os import sys from copy import deepcopy import yaml import galaxy.util log = logging.getLogger(__name__) def get_resource_mapper_function(app): config = app.config mapper = getattr(config, "workflow_resource_params_mapper", None) if mapper is None: return _null_mapper_function elif ":" in mapper: raw_function = _import_resource_mapping_function(mapper) # Bind resource parameters here just to not re-parse over and over. workflow_resource_params = _read_defined_parameter_definitions(config) return functools.partial(raw_function, workflow_resource_params=workflow_resource_params) else: workflow_resource_params = _read_defined_parameter_definitions(config) with open(mapper) as f: mapper_definition = yaml.safe_load(f) if "by_group" in mapper_definition: by_group = mapper_definition["by_group"] return functools.partial(_resource_parameters_by_group, by_group=by_group, workflow_resource_params=workflow_resource_params) else: raise Exception("Currently workflow parameter mapper definitions require a by_group definition.") def _read_defined_parameter_definitions(config): params_file = getattr(config, "workflow_resource_params_file", None) if not params_file or not os.path.exists(params_file): # Just re-use job resource parameters. params_file = getattr(config, "job_resource_params_file", None) if not params_file or not os.path.exists(params_file): params_file = None log.debug("Loading workflow resource parameter definitions from %s" % params_file) if params_file: return galaxy.util.parse_resource_parameters(params_file) else: return {} def _resource_parameters_by_group(trans, **kwds): user = trans.user by_group = kwds["by_group"] workflow_resource_params = kwds["workflow_resource_params"] params = [] if validate_by_group_workflow_parameters_mapper(by_group, workflow_resource_params): user_permissions = {} user_groups = [] for g in user.groups: user_groups.append(g.group.name) default_group = by_group.get('default', None) for group_name, group_def in by_group.get("groups", {}).items(): if group_name == default_group or group_name in user_groups: for tag in group_def: if type(tag) is dict: if tag.get('name') not in user_permissions: user_permissions[tag.get('name')] = {} for option in tag.get('options'): user_permissions[tag.get('name')][option] = {} else: if tag not in user_permissions: user_permissions[tag] = {} # user_permissions is now set. params = get_workflow_parameter_list(workflow_resource_params, user_permissions) return params # returns an array of parameters that a users set of permissions can access. def get_workflow_parameter_list(params, user_permissions): param_list = [] for param_name, param_elem in params.items(): attr = deepcopy(param_elem.attrib) if attr['name'] in user_permissions: # Allow 'select' type parameters to be used if attr['type'] == 'select': option_data = [] reject_list = [] for option_elem in param_elem.findall("option"): if option_elem.attrib['value'] in user_permissions[attr['name']]: option_data.append({ 'label': option_elem.attrib['label'], 'value': option_elem.attrib['value'] }) else: reject_list.append(option_elem.attrib['label']) attr['data'] = option_data attr_help = "" if 'help' in attr: attr_help = attr['help'] if reject_list: attr_help += "<br/><br/>The following options are available but disabled.<br/>" + \ str(reject_list) + \ "<br/>If you believe this is a mistake, please contact your Galaxy admin." attr['help'] = attr_help param_list.append(attr) return param_list def validate_by_group_workflow_parameters_mapper(by_group, workflow_resource_params): valid = True try: if 'default' not in by_group: raise Exception("'workflow_resource_params_mapper' YAML file is malformed, 'default' attribute not found!") default_group = by_group['default'] if 'groups' not in by_group: raise Exception("'workflow_resource_params_mapper' YAML file is malformed, 'groups' attribute not found!") if default_group not in by_group['groups']: raise Exception("'workflow_resource_params_mapper' YAML file is malformed, default group with title '" + default_group + "' not found in 'groups'!") for group in by_group['groups']: for attrib in by_group['groups'][group]: if type(attrib) is dict: if 'name' not in attrib: raise Exception("'workflow_resource_params_mapper' YAML file is malformed, " "'name' attribute not found in attribute of group '" + group + "'!") if attrib['name'] not in workflow_resource_params: raise Exception("'workflow_resource_params_mapper' YAML file is malformed, group with name '" + attrib['name'] + "' not found in 'workflow_resource_params'!") if 'options' not in attrib: raise Exception("'workflow_resource_params_mapper' YAML file is malformed, " "'options' attribute not found in attribute of group '" + group + "'!") valid_options = [] for param_option in workflow_resource_params[attrib['name']]: valid_options.append(param_option.attrib['value']) for option in attrib['options']: if option not in valid_options: raise Exception("'workflow_resource_params_mapper' YAML file is malformed, '" + option + "' in 'options' of '" + attrib['name'] + "' not found in attribute of group '" + group + "'!") else: if attrib not in workflow_resource_params: raise Exception("'workflow_resource_params_mapper' YAML file is malformed, attribute with name " "'" + attrib + "' not found in 'workflow_resource_params'!") except Exception as e: log.exception(e) valid = False return valid def _import_resource_mapping_function(qualified_function_path): full_module_name, function_name = qualified_function_path.split(":", 1) try: __import__(full_module_name) except ImportError: raise Exception("Failed to find workflow resource mapper module %s" % full_module_name) module = sys.modules[full_module_name] if hasattr(module, function_name): return getattr(module, function_name) else: raise Exception(f"Failed to find workflow resource mapper function {full_module_name}.{function_name}") def _null_mapper_function(*args, **kwds): return None
45.3125
138
0.61442
import functools import logging import os import sys from copy import deepcopy import yaml import galaxy.util log = logging.getLogger(__name__) def get_resource_mapper_function(app): config = app.config mapper = getattr(config, "workflow_resource_params_mapper", None) if mapper is None: return _null_mapper_function elif ":" in mapper: raw_function = _import_resource_mapping_function(mapper) workflow_resource_params = _read_defined_parameter_definitions(config) return functools.partial(raw_function, workflow_resource_params=workflow_resource_params) else: workflow_resource_params = _read_defined_parameter_definitions(config) with open(mapper) as f: mapper_definition = yaml.safe_load(f) if "by_group" in mapper_definition: by_group = mapper_definition["by_group"] return functools.partial(_resource_parameters_by_group, by_group=by_group, workflow_resource_params=workflow_resource_params) else: raise Exception("Currently workflow parameter mapper definitions require a by_group definition.") def _read_defined_parameter_definitions(config): params_file = getattr(config, "workflow_resource_params_file", None) if not params_file or not os.path.exists(params_file): params_file = getattr(config, "job_resource_params_file", None) if not params_file or not os.path.exists(params_file): params_file = None log.debug("Loading workflow resource parameter definitions from %s" % params_file) if params_file: return galaxy.util.parse_resource_parameters(params_file) else: return {} def _resource_parameters_by_group(trans, **kwds): user = trans.user by_group = kwds["by_group"] workflow_resource_params = kwds["workflow_resource_params"] params = [] if validate_by_group_workflow_parameters_mapper(by_group, workflow_resource_params): user_permissions = {} user_groups = [] for g in user.groups: user_groups.append(g.group.name) default_group = by_group.get('default', None) for group_name, group_def in by_group.get("groups", {}).items(): if group_name == default_group or group_name in user_groups: for tag in group_def: if type(tag) is dict: if tag.get('name') not in user_permissions: user_permissions[tag.get('name')] = {} for option in tag.get('options'): user_permissions[tag.get('name')][option] = {} else: if tag not in user_permissions: user_permissions[tag] = {} params = get_workflow_parameter_list(workflow_resource_params, user_permissions) return params def get_workflow_parameter_list(params, user_permissions): param_list = [] for param_name, param_elem in params.items(): attr = deepcopy(param_elem.attrib) if attr['name'] in user_permissions: if attr['type'] == 'select': option_data = [] reject_list = [] for option_elem in param_elem.findall("option"): if option_elem.attrib['value'] in user_permissions[attr['name']]: option_data.append({ 'label': option_elem.attrib['label'], 'value': option_elem.attrib['value'] }) else: reject_list.append(option_elem.attrib['label']) attr['data'] = option_data attr_help = "" if 'help' in attr: attr_help = attr['help'] if reject_list: attr_help += "<br/><br/>The following options are available but disabled.<br/>" + \ str(reject_list) + \ "<br/>If you believe this is a mistake, please contact your Galaxy admin." attr['help'] = attr_help param_list.append(attr) return param_list def validate_by_group_workflow_parameters_mapper(by_group, workflow_resource_params): valid = True try: if 'default' not in by_group: raise Exception("'workflow_resource_params_mapper' YAML file is malformed, 'default' attribute not found!") default_group = by_group['default'] if 'groups' not in by_group: raise Exception("'workflow_resource_params_mapper' YAML file is malformed, 'groups' attribute not found!") if default_group not in by_group['groups']: raise Exception("'workflow_resource_params_mapper' YAML file is malformed, default group with title '" + default_group + "' not found in 'groups'!") for group in by_group['groups']: for attrib in by_group['groups'][group]: if type(attrib) is dict: if 'name' not in attrib: raise Exception("'workflow_resource_params_mapper' YAML file is malformed, " "'name' attribute not found in attribute of group '" + group + "'!") if attrib['name'] not in workflow_resource_params: raise Exception("'workflow_resource_params_mapper' YAML file is malformed, group with name '" + attrib['name'] + "' not found in 'workflow_resource_params'!") if 'options' not in attrib: raise Exception("'workflow_resource_params_mapper' YAML file is malformed, " "'options' attribute not found in attribute of group '" + group + "'!") valid_options = [] for param_option in workflow_resource_params[attrib['name']]: valid_options.append(param_option.attrib['value']) for option in attrib['options']: if option not in valid_options: raise Exception("'workflow_resource_params_mapper' YAML file is malformed, '" + option + "' in 'options' of '" + attrib['name'] + "' not found in attribute of group '" + group + "'!") else: if attrib not in workflow_resource_params: raise Exception("'workflow_resource_params_mapper' YAML file is malformed, attribute with name " "'" + attrib + "' not found in 'workflow_resource_params'!") except Exception as e: log.exception(e) valid = False return valid def _import_resource_mapping_function(qualified_function_path): full_module_name, function_name = qualified_function_path.split(":", 1) try: __import__(full_module_name) except ImportError: raise Exception("Failed to find workflow resource mapper module %s" % full_module_name) module = sys.modules[full_module_name] if hasattr(module, function_name): return getattr(module, function_name) else: raise Exception(f"Failed to find workflow resource mapper function {full_module_name}.{function_name}") def _null_mapper_function(*args, **kwds): return None
true
true
1c391150740bb4b197ee22feca4f17cc88087007
579
py
Python
hellowebapp/settings_production.py
cesmus/hellowebapp
83a1a0018d4ba3fffb6e4fc78d5502bffcd3ec50
[ "MIT" ]
49
2015-03-16T16:17:33.000Z
2017-08-18T16:24:51.000Z
hellowebapp/settings_production.py
cesmus/hellowebapp
83a1a0018d4ba3fffb6e4fc78d5502bffcd3ec50
[ "MIT" ]
1
2015-07-23T16:41:07.000Z
2015-07-25T15:14:34.000Z
hellowebapp/settings_production.py
cesmus/hellowebapp
83a1a0018d4ba3fffb6e4fc78d5502bffcd3ec50
[ "MIT" ]
16
2017-10-20T19:51:26.000Z
2021-05-13T05:12:33.000Z
# Inherit from standard settings file for defaults from hellowebapp.settings import * # Everything below will override our standard settings: # Parse database configuration from $DATABASE_URL import dj_database_url DATABASES['default'] = dj_database_url.config() # Honor the 'X-Forwarded-Proto' header for request.is_secure() SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https') # Allow all host headers ALLOWED_HOSTS = ['*'] # Set debug to False DEBUG = False # Static asset configuration STATICFILES_STORAGE = 'whitenoise.django.GzipManifestStaticFilesStorage'
28.95
72
0.7962
from hellowebapp.settings import * import dj_database_url DATABASES['default'] = dj_database_url.config() SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https') ALLOWED_HOSTS = ['*'] DEBUG = False STATICFILES_STORAGE = 'whitenoise.django.GzipManifestStaticFilesStorage'
true
true
1c39140645f257e2db64c393e1af682f66d7985f
60,018
py
Python
test/onnx/test_utility_funs.py
wayi1/pytorch
e832ff58bf93fb1bcb2292219f6c98ab3c842484
[ "Intel" ]
2
2020-03-13T06:57:49.000Z
2020-05-17T04:18:14.000Z
test/onnx/test_utility_funs.py
wayi1/pytorch
e832ff58bf93fb1bcb2292219f6c98ab3c842484
[ "Intel" ]
null
null
null
test/onnx/test_utility_funs.py
wayi1/pytorch
e832ff58bf93fb1bcb2292219f6c98ab3c842484
[ "Intel" ]
null
null
null
# Owner(s): ["module: onnx"] import copy import io import unittest import onnx import torchvision from autograd_helper import CustomFunction as CustomFunction2 from test_pytorch_common import ( TestCase, run_tests, skipIfNoCuda, skipIfUnsupportedMaxOpsetVersion, skipIfUnsupportedMinOpsetVersion, ) from verify import verify import torch import torch.onnx import torch.utils.cpp_extension from torch.onnx import ( OperatorExportTypes, TrainingMode, register_custom_op_symbolic, unregister_custom_op_symbolic, utils, ) from torch.onnx.symbolic_helper import ( _set_onnx_shape_inference, _set_operator_export_type, _set_opset_version, _unpack_list, parse_args, ) skip = unittest.skip class _BaseTestCase(TestCase): def setUp(self): torch.manual_seed(0) if torch.cuda.is_available(): torch.cuda.manual_seed_all(0) def _model_to_graph( self, model, input, do_constant_folding=True, training=TrainingMode.EVAL, operator_export_type=OperatorExportTypes.ONNX, input_names=None, dynamic_axes=None, ): if training == torch.onnx.TrainingMode.TRAINING: model.train() elif training == torch.onnx.TrainingMode.EVAL: model.eval() # Need disable onnx_shape_inference for this test because it puts const node to initializers. _set_onnx_shape_inference(False) utils._validate_dynamic_axes(dynamic_axes, model, None, None) graph, params_dict, torch_out = utils._model_to_graph( model, input, do_constant_folding=do_constant_folding, _disable_torch_constant_prop=True, operator_export_type=operator_export_type, training=training, input_names=input_names, dynamic_axes=dynamic_axes, ) _set_onnx_shape_inference(True) return graph, params_dict, torch_out class TestUtilityFuns_opset_independent(_BaseTestCase): def test_unconvertible_ops(self): class MyModule(torch.nn.Module): def forward(self, x): return torch.cumsum(x, dim=0) model = MyModule() x = torch.randn(2, 3, 4) graph, unconvertible_ops = utils.unconvertible_ops(model, (x,), opset_version=9) iter = graph.nodes() self.assertEqual(next(iter).kind(), "onnx::Constant") self.assertEqual(next(iter).kind(), "prim::Constant") self.assertEqual(next(iter).kind(), "aten::cumsum") self.assertEqual(len(unconvertible_ops), 1) self.assertEqual(unconvertible_ops, ["aten::cumsum"]) class TestUtilityFuns_opset9(_BaseTestCase): opset_version = 9 def test_is_in_onnx_export(self): test_self = self class MyModule(torch.nn.Module): def forward(self, x): test_self.assertTrue(torch.onnx.is_in_onnx_export()) raise ValueError return x + 1 x = torch.randn(3, 4) f = io.BytesIO() try: torch.onnx.export(MyModule(), x, f, opset_version=self.opset_version) except ValueError: self.assertFalse(torch.onnx.is_in_onnx_export()) def test_validate_dynamic_axes_invalid_input_output_name(self): import warnings with warnings.catch_warnings(record=True) as w: warnings.simplefilter("always") utils._validate_dynamic_axes( {"input1": {}, "output": {}, "invalid_name1": {}, "invalid_name2": {}}, None, ["input1", "input2"], ["output"], ) messages = [str(warning.message) for warning in w] self.assertIn( "Provided key invalid_name1 for dynamic axes is not a valid input/output name", messages, ) self.assertIn( "Provided key invalid_name2 for dynamic axes is not a valid input/output name", messages, ) self.assertEqual(len(messages), 2) @skipIfUnsupportedMinOpsetVersion(11) def test_split_to_slice(self): class SplitModule(torch.nn.Module): def forward(self, x, y, t): splits = (x.size(1), y.size(1)) out, out2 = torch.split(t, splits, dim=1) return out, out2 _set_opset_version(self.opset_version) _set_operator_export_type(OperatorExportTypes.ONNX) x = torch.randn(2, 3) y = torch.randn(2, 4) t = torch.randn(2, 7) graph, _, _ = self._model_to_graph( SplitModule(), (x, y, t), input_names=["x", "y", "t"], dynamic_axes={"x": [0, 1], "y": [0, 1], "t": [0, 1]}, ) for node in graph.nodes(): self.assertNotEqual(node.kind(), "onnx::SplitToSequence") def test_constant_fold_transpose(self): class TransposeModule(torch.nn.Module): def forward(self, x): a = torch.tensor([[1.0, 2.0, 3.0], [4.0, 5.0, 6.0]]) b = torch.transpose(a, 1, 0) return b + x _set_opset_version(self.opset_version) _set_operator_export_type(OperatorExportTypes.ONNX) x = torch.ones(3, 2) graph, _, __ = self._model_to_graph( TransposeModule(), (x,), input_names=["x"], dynamic_axes={"x": [0, 1]} ) for node in graph.nodes(): self.assertNotEqual(node.kind(), "onnx::Transpose") self.assertNotEqual(node.kind(), "onnx::Cast") self.assertNotEqual(node.kind(), "onnx::Constant") self.assertEqual(len(list(graph.nodes())), 1) def test_constant_fold_reduceL2(self): class ReduceModule(torch.nn.Module): def forward(self, x): a = torch.tensor([[1.0, 2.0, 3.0], [4.0, 5.0, 6.0]]) b = torch.norm(a, p=2, dim=-2, keepdim=False) return b + x _set_opset_version(self.opset_version) _set_operator_export_type(OperatorExportTypes.ONNX) x = torch.ones(2, 3) graph, _, __ = self._model_to_graph( ReduceModule(), (x,), input_names=["x"], dynamic_axes={"x": [0, 1]} ) for node in graph.nodes(): self.assertNotEqual(node.kind(), "onnx::ReduceL2") self.assertEqual(len(list(graph.nodes())), 1) def test_constant_fold_reduceL1(self): class NormModule(torch.nn.Module): def forward(self, x): a = torch.tensor([[1.0, 2.0, 3.0], [4.0, 5.0, 6.0]]) b = torch.norm(a, p=1, dim=-2) return b + x _set_opset_version(self.opset_version) _set_operator_export_type(OperatorExportTypes.ONNX) x = torch.ones(2, 3) graph, _, __ = self._model_to_graph( NormModule(), (x,), input_names=["x"], dynamic_axes={"x": [0, 1]} ) for node in graph.nodes(): self.assertNotEqual(node.kind(), "onnx::ReduceL1") self.assertEqual(len(list(graph.nodes())), 1) def test_constant_fold_slice(self): class NarrowModule(torch.nn.Module): def forward(self, x): a = torch.tensor([[1.0, 2.0, 3.0], [4.0, 5.0, 6.0]]) b = torch.narrow(a, 0, 0, 1) return b + x _set_opset_version(self.opset_version) _set_operator_export_type(OperatorExportTypes.ONNX) x = torch.ones(1, 3) graph, _, __ = self._model_to_graph( NarrowModule(), (x,), input_names=["x"], dynamic_axes={"x": [0, 1]} ) for node in graph.nodes(): self.assertNotEqual(node.kind(), "onnx::Slice") self.assertNotEqual(node.kind(), "onnx::Cast") self.assertNotEqual(node.kind(), "onnx::Constant") self.assertEqual(len(list(graph.nodes())), 1) def test_constant_fold_slice_index_exceeds_dim(self): class SliceIndexExceedsDimModule(torch.nn.Module): def forward(self, x): a = torch.tensor([[1.0, 2.0, 3.0], [4.0, 5.0, 6.0]]) b = a[1:10] # index exceeds dimension return b + x _set_opset_version(self.opset_version) _set_operator_export_type(OperatorExportTypes.ONNX) x = torch.ones(1, 3) graph, _, __ = self._model_to_graph( SliceIndexExceedsDimModule(), (x,), input_names=["x"], dynamic_axes={"x": [0, 1]}, ) for node in graph.nodes(): self.assertNotEqual(node.kind(), "onnx::Slice") self.assertNotEqual(node.kind(), "onnx::Cast") self.assertNotEqual(node.kind(), "onnx::Constant") self.assertEqual(len(list(graph.nodes())), 1) def test_constant_fold_slice_negative_index(self): class SliceNegativeIndexModule(torch.nn.Module): def forward(self, x): a = torch.tensor([[1.0, 2.0, 3.0], [4.0, 5.0, 6.0]]) b = a[0:-1] # index relative to the end c = torch.select(a, dim=-1, index=-2) d = torch.select(a, dim=1, index=0) return b + x, c + d _set_opset_version(self.opset_version) _set_operator_export_type(OperatorExportTypes.ONNX) x = torch.ones(1, 3) graph, _, __ = self._model_to_graph( SliceNegativeIndexModule(), (x,), input_names=["x"], dynamic_axes={"x": [0, 1]}, ) for node in graph.nodes(): self.assertNotEqual(node.kind(), "onnx::Slice") self.assertNotEqual(node.kind(), "onnx::Cast") self.assertNotEqual(node.kind(), "onnx::Constant") def test_constant_fold_gather(self): class GatherModule(torch.nn.Module): def forward(self, x): a = torch.tensor([[1.0, 2.0, 3.0], [4.0, 5.0, 6.0]]) b = torch.select(a, dim=1, index=-2) c = torch.index_select(a, dim=-2, index=torch.tensor([0, 1])) return b + 1, c + x _set_opset_version(self.opset_version) _set_operator_export_type(OperatorExportTypes.ONNX) x = torch.ones(1, 3) model = GatherModule() model(x) graph, _, __ = self._model_to_graph( GatherModule(), (x,), input_names=["x"], dynamic_axes={"x": [0, 1]} ) for node in graph.nodes(): self.assertNotEqual(node.kind(), "onnx::Gather") def test_constant_fold_unsqueeze(self): class UnsqueezeModule(torch.nn.Module): def forward(self, x): a = torch.tensor([[1.0, 2.0, 3.0], [4.0, 5.0, 6.0]]) b = torch.unsqueeze(a, -2) return b + x _set_opset_version(self.opset_version) _set_operator_export_type(OperatorExportTypes.ONNX) x = torch.ones(1, 2, 3) graph, _, __ = self._model_to_graph( UnsqueezeModule(), (x,), input_names=["x"], dynamic_axes={"x": [0, 1, 2]} ) for node in graph.nodes(): self.assertNotEqual(node.kind(), "onnx::Unsqueeze") self.assertNotEqual(node.kind(), "onnx::Cast") self.assertNotEqual(node.kind(), "onnx::Constant") self.assertEqual(len(list(graph.nodes())), 1) def test_constant_fold_unsqueeze_multi_axies(self): class PReluModel(torch.nn.Module): def __init__(self): super(PReluModel, self).__init__() self.prelu = torch.nn.PReLU() def forward(self, x): a = torch.randn(2, 3, 4, 5, 8, 7) return self.prelu(x) + a _set_opset_version(self.opset_version) _set_operator_export_type(OperatorExportTypes.ONNX) x = torch.randn(2, 3, 4, 5, 8, 7) graph, _, __ = self._model_to_graph( PReluModel(), x, input_names=["x"], dynamic_axes={"x": [0, 1, 2, 3, 4, 5]} ) for node in graph.nodes(): self.assertNotEqual(node.kind(), "onnx::Unsqueeze") self.assertNotEqual(node.kind(), "onnx::Cast") self.assertNotEqual(node.kind(), "onnx::Constant") self.assertEqual(len(list(graph.nodes())), 4) def test_constant_fold_squeeze_without_axes(self): class SqueezeModule(torch.nn.Module): def forward(self, x): a = torch.tensor([[[1.0, 2.0, 3.0], [4.0, 5.0, 6.0]]]) return torch.squeeze(a) + x + torch.squeeze(a) _set_opset_version(self.opset_version) _set_operator_export_type(OperatorExportTypes.ONNX) x = torch.ones(2, 3) graph, _, __ = self._model_to_graph( SqueezeModule(), (x,), input_names=["x"], dynamic_axes={"x": [0, 1]} ) for node in graph.nodes(): self.assertNotEqual(node.kind(), "onnx::Squeeze") self.assertNotEqual(node.kind(), "onnx::Cast") self.assertNotEqual(node.kind(), "onnx::Constant") self.assertEqual(len(list(graph.nodes())), 2) def test_constant_fold_squeeze_with_axes(self): class SqueezeAxesModule(torch.nn.Module): def forward(self, x): a = torch.tensor([[[1.0, 2.0, 3.0], [4.0, 5.0, 6.0]]]) return torch.squeeze(a, dim=-3) + x _set_opset_version(self.opset_version) _set_operator_export_type(OperatorExportTypes.ONNX) x = torch.ones(2, 3) graph, _, __ = self._model_to_graph( SqueezeAxesModule(), (x,), input_names=["x"], dynamic_axes={"x": [0, 1]} ) for node in graph.nodes(): self.assertNotEqual(node.kind(), "onnx::Squeeze") self.assertNotEqual(node.kind(), "onnx::Cast") self.assertNotEqual(node.kind(), "onnx::Constant") self.assertEqual(len(list(graph.nodes())), 1) def test_constant_fold_concat(self): class ConcatModule(torch.nn.Module): def forward(self, x): # Why did I insert a Cast here? There appears to be intentional # behavior in ONNX constant folding where constant tensors which # are not attached to any known to be foldable onnx # operations don't get extracted into the initializer graph. So # without these casts, we will actually fail to pull out one of # the constants, thus failing constant folding. I think the # test is wrong but I don't have time to write a more correct # test (I think the right way to go about the test is to setup # a predicate for what invariant graphs should hold after # constant folding, and then verify this predicate holds. # I think the asserts below are an attempt at this predicate, # but it is not right!) # # More commentary at # https://github.com/pytorch/pytorch/pull/18698/files#r340107552 a = torch.tensor([[1.0, 2.0, 3.0]]).to(torch.float) b = torch.tensor([[4.0, 5.0, 6.0]]).to(torch.float) c = torch.cat((a, b), 0) d = b + c return x + d _set_opset_version(self.opset_version) _set_operator_export_type(OperatorExportTypes.ONNX) x = torch.ones(2, 3) graph, _, __ = self._model_to_graph( ConcatModule(), (x,), input_names=["x"], dynamic_axes={"x": [0, 1]} ) for node in graph.nodes(): self.assertNotEqual(node.kind(), "onnx::Concat") self.assertNotEqual(node.kind(), "onnx::Cast") self.assertNotEqual(node.kind(), "onnx::Constant") self.assertEqual(len(list(graph.nodes())), 1) def test_constant_fold_lstm(self): class GruNet(torch.nn.Module): def __init__(self): super(GruNet, self).__init__() self.mygru = torch.nn.GRU(7, 3, 1, bidirectional=False) def forward(self, input, initial_state): return self.mygru(input, initial_state) _set_opset_version(self.opset_version) _set_operator_export_type(OperatorExportTypes.ONNX) input = torch.randn(5, 3, 7) h0 = torch.randn(1, 3, 3) graph, _, __ = self._model_to_graph( GruNet(), (input, h0), input_names=["input", "h0"], dynamic_axes={"input": [0, 1, 2], "h0": [0, 1, 2]}, ) for node in graph.nodes(): self.assertNotEqual(node.kind(), "onnx::Slice") self.assertNotEqual(node.kind(), "onnx::Concat") self.assertNotEqual(node.kind(), "onnx::Unsqueeze") if self.opset_version <= 12: self.assertEqual(len(list(graph.nodes())), 3) else: # Unsqueeze op parameter "axes" as an input instead of as an attribute when opset version >= 13 self.assertEqual(len(list(graph.nodes())), 4) def test_constant_fold_transpose_matmul(self): class MatMulNet(torch.nn.Module): def __init__(self): super(MatMulNet, self).__init__() self.B = torch.nn.Parameter(torch.ones(5, 3)) def forward(self, A): return torch.matmul(A, torch.transpose(self.B, -1, -2)) _set_opset_version(self.opset_version) _set_operator_export_type(OperatorExportTypes.ONNX) A = torch.randn(2, 3) graph, _, __ = self._model_to_graph( MatMulNet(), (A,), input_names=["A"], dynamic_axes={"A": [0, 1]} ) for node in graph.nodes(): self.assertNotEqual(node.kind(), "onnx::Transpose") self.assertEqual(len(list(graph.nodes())), 1) def test_constant_fold_reshape(self): class ReshapeModule(torch.nn.Module): def __init__( self, ): super(ReshapeModule, self).__init__() self.register_buffer("weight", torch.ones(5)) def forward(self, x): b = self.weight.reshape(1, -1, 1, 1) return x * b _set_opset_version(self.opset_version) _set_operator_export_type(OperatorExportTypes.ONNX) x = torch.randn(4, 5) graph, _, __ = self._model_to_graph( ReshapeModule(), (x,), input_names=["x"], dynamic_axes={"x": [0, 1]} ) for node in graph.nodes(): self.assertNotEqual(node.kind(), "onnx::Reshape") self.assertEqual(len(list(graph.nodes())), 1) def test_constant_fold_div(self): class Module(torch.nn.Module): def __init__( self, ): super(Module, self).__init__() self.register_buffer("weight", torch.ones(5)) def forward(self, x): div = self.weight.div(torch.tensor([1, 2, 3, 4, 5])) return div * x x = torch.randn(2, 5) _set_opset_version(self.opset_version) _set_operator_export_type(OperatorExportTypes.ONNX) graph, _, __ = self._model_to_graph( Module(), (x,), input_names=["x"], dynamic_axes={"x": [0, 1]} ) for node in graph.nodes(): self.assertNotEqual(node.kind(), "onnx::Div") self.assertEqual(len(list(graph.nodes())), 1) def test_constant_fold_mul(self): class Module(torch.nn.Module): def __init__( self, ): super(Module, self).__init__() self.register_buffer("weight", torch.ones(5)) def forward(self, x): mul = self.weight.mul(torch.tensor([1, 2, 3, 4, 5])) return mul / x x = torch.randn(2, 5) _set_opset_version(self.opset_version) _set_operator_export_type(OperatorExportTypes.ONNX) graph, _, __ = self._model_to_graph( Module(), (x,), input_names=["x"], dynamic_axes={"x": [0, 1]} ) for node in graph.nodes(): self.assertNotEqual(node.kind(), "onnx::Mul") self.assertEqual(len(list(graph.nodes())), 1) def test_constant_fold_add(self): class Module(torch.nn.Module): def __init__( self, ): super(Module, self).__init__() self.register_buffer("weight", torch.ones(5)) def forward(self, x): add = self.weight + torch.tensor([1, 2, 3, 4, 5]) return add - x x = torch.randn(2, 5) _set_opset_version(self.opset_version) _set_operator_export_type(OperatorExportTypes.ONNX) graph, params_dict, __ = self._model_to_graph( Module(), (x,), do_constant_folding=True, operator_export_type=OperatorExportTypes.ONNX, input_names=["x"], dynamic_axes={"x": [0, 1]}, ) for node in graph.nodes(): self.assertTrue(node.kind() != "onnx::Add") self.assertEqual(len(list(graph.nodes())), 1) params = list(params_dict.values()) self.assertEqual(len(params), 1) weight = params[0] # TODO(#38095): Replace assertEqualIgnoreType. See issue #38095 self.assertEqualIgnoreType(weight, torch.tensor([2, 3, 4, 5, 6])) def test_constant_fold_sub(self): class Module(torch.nn.Module): def __init__( self, ): super(Module, self).__init__() self.register_buffer("weight", torch.ones(5)) def forward(self, x): sub = self.weight - torch.tensor([1, 2, 3, 4, 5]) return sub + x x = torch.randn(2, 5) _set_opset_version(self.opset_version) _set_operator_export_type(OperatorExportTypes.ONNX) graph, params_dict, __ = self._model_to_graph( Module(), (x,), do_constant_folding=True, operator_export_type=OperatorExportTypes.ONNX, input_names=["x"], dynamic_axes={"x": [0, 1]}, ) for node in graph.nodes(): self.assertNotEqual(node.kind(), "onnx::Sub") self.assertEqual(len(list(graph.nodes())), 1) params = list(params_dict.values()) self.assertEqual(len(params), 1) weight = params[0] # TODO(#38095): Replace assertEqualIgnoreType. See issue #38095 self.assertEqualIgnoreType(weight, torch.tensor([0, -1, -2, -3, -4])) def test_constant_fold_sqrt(self): class Module(torch.nn.Module): def __init__( self, ): super(Module, self).__init__() self.register_buffer("weight", torch.ones(5)) def forward(self, x): sqrt = torch.sqrt(self.weight) return sqrt / x x = torch.randn(2, 5) _set_opset_version(self.opset_version) _set_operator_export_type(OperatorExportTypes.ONNX) graph, _, __ = self._model_to_graph( Module(), (x,), input_names=["x"], dynamic_axes={"x": [0, 1]} ) for node in graph.nodes(): self.assertNotEqual(node.kind(), "onnx::Sqrt") self.assertEqual(len(list(graph.nodes())), 1) def test_constant_fold_shape(self): class ShapeModule(torch.nn.Module): def __init__(self): super(ShapeModule, self).__init__() self.register_buffer("weight", torch.ones(5)) def forward(self, x): shape = self.weight.shape[0] return x + shape x = torch.randn(2, 5) _set_opset_version(self.opset_version) _set_operator_export_type(OperatorExportTypes.ONNX) graph, _, __ = self._model_to_graph( ShapeModule(), (x,), input_names=["x"], dynamic_axes={"x": [0, 1]} ) for node in graph.nodes(): self.assertNotEqual(node.kind(), "onnx::Shape") self.assertEqual(len(list(graph.nodes())), 1) def test_verbose(self): class MyModule(torch.nn.Module): def forward(self, input): return torch.exp(input) x = torch.randn(3, 4) def is_model_stripped(f, verbose=None): if verbose is None: torch.onnx.export(MyModule(), x, f, opset_version=self.opset_version) else: torch.onnx.export( MyModule(), x, f, verbose=verbose, opset_version=self.opset_version ) model = onnx.load(io.BytesIO(f.getvalue())) model_strip = copy.copy(model) onnx.helper.strip_doc_string(model_strip) return model == model_strip # test verbose=False (default) self.assertTrue(is_model_stripped(io.BytesIO())) # test verbose=True self.assertFalse(is_model_stripped(io.BytesIO(), True)) # NB: remove this test once DataParallel can be correctly handled def test_error_on_data_parallel(self): model = torch.nn.DataParallel(torch.nn.ReflectionPad2d((1, 2, 3, 4))) x = torch.randn(1, 2, 3, 4) f = io.BytesIO() with self.assertRaisesRegex( ValueError, "torch.nn.DataParallel is not supported by ONNX " "exporter, please use 'attribute' module to " "unwrap model from torch.nn.DataParallel. Try ", ): torch.onnx.export(model, x, f, opset_version=self.opset_version) @skipIfUnsupportedMinOpsetVersion(11) def test_sequence_dim(self): class Module(torch.nn.Module): def forward(self, x, y): return [x, y] model = Module() # Export with scripting to keep output as Sequence type. # Tracing unpacks the list. script_model = torch.jit.script(model) x = torch.randn(2, 3) # Case 1: dynamic axis f = io.BytesIO() y = torch.randn(2, 3) torch.onnx.export( script_model, (x, y), f, opset_version=self.opset_version, input_names=["x", "y"], dynamic_axes={"y": [1]}, ) onnx_model = onnx.load(io.BytesIO(f.getvalue())) loop_output_value_info_proto = onnx_model.graph.output[0] ref_value_info_proto = onnx.helper.make_tensor_sequence_value_info( loop_output_value_info_proto.name, 1, [2, None] ) self.assertEqual(loop_output_value_info_proto, ref_value_info_proto) # Case 2: no dynamic axes. f = io.BytesIO() y = torch.randn(2, 3) torch.onnx.export(script_model, (x, y), f, opset_version=self.opset_version) onnx_model = onnx.load(io.BytesIO(f.getvalue())) loop_output_value_info_proto = onnx_model.graph.output[0] ref_value_info_proto = onnx.helper.make_tensor_sequence_value_info( loop_output_value_info_proto.name, 1, [2, 3] ) self.assertEqual(loop_output_value_info_proto, ref_value_info_proto) def test_export_mode(self): class MyModule(torch.nn.Module): def forward(self, x): y = x + 1 return y model = MyModule() x = torch.randn(10, 3, 128, 128) f = io.BytesIO() # set mode to in inference mode and export in training mode model.eval() old_state = model.training torch.onnx.export( model, (x,), f, opset_version=self.opset_version, training=torch.onnx.TrainingMode.TRAINING, ) # verify that the model state is preserved self.assertEqual(model.training, old_state) # set mode to training mode and export in inference mode model.train() old_state = model.training torch.onnx.export( model, (x,), f, opset_version=self.opset_version, training=torch.onnx.TrainingMode.EVAL, ) # verify that the model state is preserved self.assertEqual(model.training, old_state) @skipIfUnsupportedMinOpsetVersion(15) def test_local_function(self): class N(torch.nn.Module): def __init__(self, prob): super().__init__() self.dropout = torch.nn.Dropout(prob) def forward(self, x): return self.dropout(x) class M(torch.nn.Module): def __init__(self, num_layers): super().__init__() self.num_layers = num_layers self.lns = torch.nn.ModuleList( [torch.nn.LayerNorm(3, eps=i) for i in range(num_layers)] ) self.celu1 = torch.nn.CELU(1.0) self.celu2 = torch.nn.CELU(2.0) self.dropout = N(0.5) def forward(self, x, y, z): res1 = self.celu1(x) res2 = self.celu2(y) for ln in self.lns: z = ln(z) return res1 + res2, self.dropout(z) x = torch.randn(2, 3) y = torch.randn(2, 3) z = torch.randn(2, 3) # Export specified modules. Test against specifying modules that won't # exist in the exported model. # Model export in inference mode will remove dropout node, # thus the dropout module no longer exist in graph. f = io.BytesIO() torch.onnx.export( M(3), (x, y, z), f, opset_version=self.opset_version, export_modules_as_functions={ torch.nn.CELU, torch.nn.Dropout, torch.nn.LayerNorm, }, ) onnx_model = onnx.load(io.BytesIO(f.getvalue())) # Check function definition funcs = onnx_model.functions celu_funcs = [f for f in funcs if f.name == "CELU"] self.assertEqual(len(celu_funcs), 1) self.assertEqual(celu_funcs[0].domain, "torch.nn.modules.activation") self.assertEqual(len(celu_funcs[0].attribute), 3) ln_funcs = [f for f in funcs if f.name == "LayerNorm"] self.assertEqual(len(ln_funcs), 1) self.assertEqual(ln_funcs[0].domain, "torch.nn.modules.normalization") self.assertEqual(len(ln_funcs[0].attribute), 3) # Check local function nodes nodes = onnx_model.graph.node celu_ns = [n for n in nodes if n.op_type == "CELU"] ln_ns = [n for n in nodes if n.op_type == "LayerNorm"] self.assertEqual(len(celu_ns), 2) self.assertEqual(celu_ns[0].domain, "torch.nn.modules.activation") self.assertEqual(len(celu_ns[0].attribute), 3) self.assertEqual(len(ln_ns), 3) self.assertEqual(ln_ns[0].domain, "torch.nn.modules.normalization") self.assertEqual(len(ln_ns[0].attribute), 3) # Export specified modules. f = io.BytesIO() torch.onnx.export( M(3), (x, y, z), f, opset_version=self.opset_version, export_modules_as_functions={torch.nn.CELU}, ) onnx_model = onnx.load(io.BytesIO(f.getvalue())) funcs = onnx_model.functions self.assertEqual(len(funcs), 1) self.assertEqual(funcs[0].name, "CELU") # Export with empty specified modules. Normal export. f = io.BytesIO() torch.onnx.export( M(3), (x, y, z), f, opset_version=self.opset_version, export_modules_as_functions=set(), ) onnx_model = onnx.load(io.BytesIO(f.getvalue())) funcs = onnx_model.functions self.assertEqual(len(funcs), 0) # Export all modules. Should contain {M, CELU, LayerNorm}. f = io.BytesIO() torch.onnx.export( M(3), (x, y, z), f, opset_version=self.opset_version, export_modules_as_functions=True, ) onnx_model = onnx.load(io.BytesIO(f.getvalue())) funcs = onnx_model.functions self.assertEqual(len(funcs), 3) @skipIfUnsupportedMinOpsetVersion(15) def test_local_function_overloads(self): class NWithOverloads(torch.nn.Module): def forward(self, x, y=None, z=None): if y is None: return x + 1 elif z is None: return x + y else: return x + y, x + z class M(torch.nn.Module): def __init__(self, num_layers): super().__init__() self.n = NWithOverloads() def forward(self, x, y, z): return self.n(x), self.n(x, y), self.n(x, y, z) x = torch.randn(2, 3) y = torch.randn(2, 3) z = torch.randn(2, 3) f = io.BytesIO() torch.onnx.export( M(3), (x, y, z), f, opset_version=self.opset_version, export_modules_as_functions={NWithOverloads}, ) onnx_model = onnx.load(io.BytesIO(f.getvalue())) funcs = onnx_model.functions self.assertEqual(len(funcs), 3) func_names = [f.name for f in funcs] self.assertIn("NWithOverloads", func_names) self.assertIn("NWithOverloads.1", func_names) self.assertIn("NWithOverloads.2", func_names) @skipIfUnsupportedMinOpsetVersion(15) def test_local_function_infer_scopes(self): class M(torch.nn.Module): def forward(self, x): # Concatenation of scalars inserts unscoped tensors in IR graph. new_tensor_shape = x.size()[:-1] + (1, 1, -1) tensor = x.view(*new_tensor_shape) return tensor x = torch.randn(4, 5) f = io.BytesIO() torch.onnx.export( M(), (x,), f, export_modules_as_functions=True, opset_version=self.opset_version, do_constant_folding=False, ) onnx_model = onnx.load(io.BytesIO(f.getvalue())) funcs = onnx_model.functions self.assertIn("M", [f.name for f in funcs]) @skipIfUnsupportedMinOpsetVersion(15) def test_local_function_predefined_attributes(self): class M(torch.nn.Module): num_layers: int def __init__(self, num_layers): super().__init__() self.num_layers = num_layers self.lns = torch.nn.ModuleList( [torch.nn.LayerNorm(3, eps=1e-4) for _ in range(num_layers)] ) def forward(self, x): for ln in self.lns: x = ln(x) return x x = torch.randn(2, 3) f = io.BytesIO() model = M(3) torch.onnx.export( model, (x,), f, export_modules_as_functions=True, opset_version=self.opset_version, ) onnx_model = onnx.load(io.BytesIO(f.getvalue())) funcs = onnx_model.functions m_funcs = [fn for fn in funcs if fn.name == "M"] self.assertEqual(m_funcs[0].attribute, ["num_layers"]) ln_funcs = [fn for fn in funcs if fn.name == "LayerNorm"] self.assertEqual(ln_funcs[0].attribute, ["eps", "elementwise_affine"]) from onnx import helper m_node = [n for n in onnx_model.graph.node if n.op_type == "M"] self.assertEqual( m_node[0].attribute[0], helper.make_attribute("num_layers", model.num_layers), ) ln_nodes = [n for n in m_funcs[0].node if n.op_type == "LayerNorm"] expected_ln_attrs = [ helper.make_attribute( "elementwise_affine", model.lns[0].elementwise_affine ), helper.make_attribute("eps", model.lns[0].eps), ] for ln_node in ln_nodes: self.assertIn(ln_node.attribute[0], expected_ln_attrs) self.assertIn(ln_node.attribute[1], expected_ln_attrs) def test_aten_fallthrough(self): # Test aten export of op with no symbolic class Module(torch.nn.Module): def forward(self, x): return torch.erfc(x) x = torch.randn(2, 3, 4) _set_opset_version(self.opset_version) graph, _, __ = self._model_to_graph( Module(), (x,), operator_export_type=OperatorExportTypes.ONNX_FALLTHROUGH, input_names=["x"], dynamic_axes={"x": [0, 1, 2]}, ) iter = graph.nodes() self.assertEqual(next(iter).kind(), "aten::erfc") def test_custom_op_fallthrough(self): # Test custom op op_source = """ #include <torch/script.h> torch::Tensor custom_add(torch::Tensor self, torch::Tensor other) { return self + other; } static auto registry = torch::RegisterOperators("custom_namespace::custom_op", &custom_add); """ torch.utils.cpp_extension.load_inline( name="custom_add", cpp_sources=op_source, is_python_module=False, verbose=True, ) class FooModel(torch.nn.Module): def forward(self, input, other): # Calling custom op return torch.ops.custom_namespace.custom_op(input, other) x = torch.randn(2, 3, 4, requires_grad=False) y = torch.randn(2, 3, 4, requires_grad=False) model = FooModel() graph, _, __ = self._model_to_graph( model, (x, y), operator_export_type=torch.onnx.OperatorExportTypes.ONNX_FALLTHROUGH, input_names=["x", "y"], dynamic_axes={"x": [0, 1, 2], "y": [0, 1, 2]}, ) iter = graph.nodes() self.assertEqual(next(iter).kind(), "custom_namespace::custom_op") def test_custom_opsets_gelu(self): self.addCleanup(unregister_custom_op_symbolic, "::gelu", 1) def gelu(g, self, approximate): return g.op("com.microsoft::Gelu", self).setType(self.type()) register_custom_op_symbolic("::gelu", gelu, 1) model = torch.nn.GELU(approximate="none") x = torch.randn(3, 3) f = io.BytesIO() torch.onnx.export( model, (x,), f, opset_version=self.opset_version, custom_opsets={"com.microsoft": 1}, ) graph = onnx.load(io.BytesIO(f.getvalue())) self.assertEqual(graph.graph.node[0].op_type, "Gelu") self.assertEqual(graph.opset_import[0].version, self.opset_version) self.assertEqual(graph.opset_import[1].domain, "com.microsoft") self.assertEqual(graph.opset_import[1].version, 1) def test_register_aten_custom_op_symbolic(self): self.addCleanup(unregister_custom_op_symbolic, "aten::gelu", 1) def gelu(g, self, approximate): return g.op("com.microsoft::Gelu", self).setType(self.type()) register_custom_op_symbolic("aten::gelu", gelu, 1) model = torch.nn.GELU(approximate="none") x = torch.randn(3, 3) f = io.BytesIO() torch.onnx.export(model, (x,), f, opset_version=self.opset_version) graph = onnx.load(io.BytesIO(f.getvalue())) self.assertEqual(graph.graph.node[0].op_type, "Gelu") self.assertEqual(graph.opset_import[1].domain, "com.microsoft") def test_custom_opsets_inverse(self): class CustomInverse(torch.nn.Module): def forward(self, x): return torch.inverse(x) + x def inverse(g, self): return g.op("com.microsoft::Inverse", self).setType(self.type()) register_custom_op_symbolic("::inverse", inverse, 1) model = CustomInverse() x = torch.randn(2, 3, 3) f = io.BytesIO() torch.onnx.export( model, (x,), f, opset_version=self.opset_version, custom_opsets={"com.microsoft": 1}, ) graph = onnx.load(io.BytesIO(f.getvalue())) self.assertEqual(graph.graph.node[0].op_type, "Inverse") self.assertEqual(graph.opset_import[0].version, self.opset_version) self.assertEqual(graph.opset_import[1].domain, "com.microsoft") self.assertEqual(graph.opset_import[1].version, 1) def test_onnx_fallthrough(self): # Test aten export of op with symbolic for aten class Module(torch.nn.Module): def forward(self, x): return torch.digamma(x) x = torch.randn(100, 128) graph, _, __ = self._model_to_graph( Module(), (x,), operator_export_type=OperatorExportTypes.ONNX_FALLTHROUGH, input_names=["x"], dynamic_axes={"x": [0, 1]}, ) iter = graph.nodes() self.assertEqual(next(iter).kind(), "aten::digamma") # prim::ListConstruct is exported as onnx::SequenceConstruct for opset >= 11 @skipIfUnsupportedMaxOpsetVersion(10) def test_prim_fallthrough(self): # Test prim op class PrimModule(torch.jit.ScriptModule): @torch.jit.script_method def forward(self, x): if isinstance(x, list): y = x else: y = [x] return y x = torch.tensor([2]) model = PrimModule() model.eval() graph, _, __ = self._model_to_graph( model, (x,), operator_export_type=OperatorExportTypes.ONNX_FALLTHROUGH, input_names=["x"], dynamic_axes={"x": [0]}, ) iter = graph.nodes() self.assertEqual(next(iter).kind(), "prim::ListConstruct") def test_custom_layer_tuple(self): class CustomFunction(torch.autograd.Function): @staticmethod def symbolic(g, input): return g.op("CustomNamespace::Custom", input, outputs=2) @staticmethod def forward(ctx, input): return input, input class Custom(torch.nn.Module): def forward(self, input): return CustomFunction.apply(input) model = Custom() batch = torch.FloatTensor(1, 3) graph, _, _ = self._model_to_graph( model, batch, input_names=["batch"], dynamic_axes={"batch": [0, 1]} ) iter = graph.nodes() self.assertEqual(next(iter).kind(), "CustomNamespace::Custom") def test_autograd_onnx_fallthrough(self): class CustomFunction(torch.autograd.Function): @staticmethod def forward(ctx, input): ctx.save_for_backward(input) return input.clamp(min=0) @staticmethod def backward(ctx, grad_output): (input,) = ctx.saved_tensors grad_input = grad_output.clone() grad_input[input < 0] = 0 return grad_input class Custom(torch.nn.Module): def forward(self, input): return CustomFunction.apply(input) model = Custom() batch = torch.FloatTensor(1, 3) graph, _, _ = self._model_to_graph( model, batch, operator_export_type=OperatorExportTypes.ONNX_FALLTHROUGH, input_names=["batch"], dynamic_axes={"batch": [0, 1]}, ) iter = graph.nodes() self.assertEqual(next(iter).kind(), "prim::PythonOp") def test_autograd_module_name(self): class CustomFunction(torch.autograd.Function): @staticmethod def forward(ctx, input): ctx.save_for_backward(input) return input.clamp(min=0) @staticmethod def backward(ctx, grad_output): (input,) = ctx.saved_tensors grad_input = grad_output.clone() grad_input[input < 0] = 0 return grad_input class Custom(torch.nn.Module): def forward(self, input): return CustomFunction.apply(input) + CustomFunction2.apply(input) model = Custom() batch = torch.FloatTensor(1, 3) graph, _, _ = self._model_to_graph( model, batch, input_names=["batch"], dynamic_axes={"batch": [0, 1]} ) iter = graph.nodes() autograd1 = next(iter) autograd2 = next(iter) self.assertEqual(autograd1.kind(), "prim::PythonOp") self.assertEqual(autograd2.kind(), "prim::PythonOp") self.assertNotEqual(autograd1.s("module"), autograd2.s("module")) def test_unused_initializers(self): class Model(torch.nn.Module): def __init__(self): super(Model, self).__init__() self.conv2 = torch.nn.ConvTranspose2d( 16, 33, (3, 5), stride=(2, 1), padding=(4, 2), dilation=(1, 1) ) self.k_proj = torch.nn.Linear(5, 5, bias=True) def forward(self, x): x = self.conv2(x) return x x = torch.randn(20, 16, 50, 100) _set_opset_version(self.opset_version) _set_operator_export_type(OperatorExportTypes.ONNX) _, params_dict, __ = self._model_to_graph( Model(), (x,), do_constant_folding=False, operator_export_type=OperatorExportTypes.ONNX, input_names=["x"], dynamic_axes={"x": [0, 1, 2, 3]}, ) self.assertEqual(len(params_dict), 2) def test_scripting_param(self): class MyModule(torch.nn.Module): def __init__(self): super(MyModule, self).__init__() self.conv = torch.nn.Conv2d( 3, 16, kernel_size=1, stride=2, padding=3, bias=True ) self.bn = torch.nn.BatchNorm2d(16, affine=True) def forward(self, x): x = self.conv(x) bn = self.bn(x) return bn model = torch.jit.script(MyModule()) x = torch.randn(10, 3, 128, 128) _set_opset_version(self.opset_version) _set_operator_export_type(OperatorExportTypes.ONNX) graph, _, __ = self._model_to_graph( model, (x,), do_constant_folding=True, operator_export_type=OperatorExportTypes.ONNX, training=torch.onnx.TrainingMode.TRAINING, input_names=["x"], dynamic_axes={"x": [0, 1, 2, 3]}, ) graph_input_params = [param.debugName() for param in graph.inputs()] for item in dict(model.named_parameters()): self.assertIn( item, graph_input_params, "Graph parameter names does not match model parameters.", ) def test_modifying_params(self): class MyModel(torch.nn.Module): def __init__(self): super(MyModel, self).__init__() self.param = torch.nn.Parameter(torch.tensor([2.0])) def forward(self, x): y = x * x self.param.data.add_(1.0) return y x = torch.tensor([1, 2]) # Move import to local as caffe2 backend requires additional build flag, # and is only used in this test case. import caffe2.python.onnx.backend as backend verify(MyModel(), x, backend, do_constant_folding=False) def test_fuse_conv_bn(self): class Fuse(torch.nn.Module): def __init__(self): super(Fuse, self).__init__() self.conv = torch.nn.Conv2d( 3, 2, kernel_size=1, stride=2, padding=3, bias=True ) self.bn = torch.nn.BatchNorm2d(2) def forward(self, x): out = self.conv(x) return self.bn(out) x = torch.randn(2, 3, 2, 2, requires_grad=True) graph, _, __ = self._model_to_graph( Fuse(), (x,), training=TrainingMode.EVAL, input_names=["x"], dynamic_axes={"x": [0, 1, 2, 3]}, ) for node in graph.nodes(): self.assertNotEqual(node.kind(), "onnx::BatchNormalization") self.assertEqual(node.kind(), "onnx::Conv") self.assertEqual(len(list(graph.nodes())), 1) def test_fuse_resnet18(self): model = torchvision.models.resnet18(pretrained=False) x = torch.randn(2, 3, 224, 224, requires_grad=True) graph, _, __ = self._model_to_graph( model, (x,), training=TrainingMode.EVAL, input_names=["x"], dynamic_axes={"x": [0, 1, 2, 3]}, ) for node in graph.nodes(): self.assertNotEqual(node.kind(), "onnx::BatchNormalization") def test_onnx_function_substitution_pass(self): @torch.jit.script def f(x: torch.Tensor, y: torch.Tensor): z = x - y return x + z class MyModule(torch.nn.Module): def __init__(self): super(MyModule, self).__init__() def forward(self, x, y): return f(x, y) input_1 = torch.tensor(11) input_2 = torch.tensor(12) _set_opset_version(self.opset_version) _set_operator_export_type(OperatorExportTypes.ONNX) graph, _, __ = self._model_to_graph( MyModule(), (input_1, input_2), do_constant_folding=True, operator_export_type=OperatorExportTypes.ONNX, input_names=["input_1", "input_2"], dynamic_axes={"input_1": [0], "input_2": [0]}, ) # Check that the prim::Constant node in the graph for representing the # scripted function `f` is removed and the following prim::CallFunction # is replced by inline graph, with onnx::Sub and onnx::Add nodes. for node in graph.nodes(): self.assertNotEqual(node.kind(), "prim::Constant") self.assertEqual( len(list(graph.nodes())), 2 ) # onnx::Sub and onnx::Add nodes only. def test_onnx_value_name(self): class MyModule(torch.nn.Module): def __init__(self): super().__init__() self.in_weight = torch.nn.Parameter(torch.Tensor(3, 3)) self.in_bias = torch.nn.Parameter(torch.Tensor(3)) def forward(self, x): start = 0 end = None weight = self.in_weight bias = self.in_bias weight = weight[start:end, :] if bias is not None: bias = bias[start:end] return torch.nn.functional.linear(x, weight, bias) model = MyModule() x = torch.randn(3, 3) f = io.BytesIO() model.eval() torch.onnx.export( model, (x,), f, opset_version=self.opset_version, keep_initializers_as_inputs=True, ) graph = onnx.load(io.BytesIO(f.getvalue())) self.assertEqual(graph.graph.input[1].name, "in_weight") self.assertEqual(graph.graph.input[2].name, "in_bias") def test_onnx_intermediate_renaming(self): class RenamedIntermediateModule(torch.nn.Module): def __init__(self): super().__init__() self._module_1 = torch.nn.Linear(10, 10) self._module_2 = torch.nn.Linear(10, 10) self._module_3 = torch.nn.Linear(10, 10) self._module_4 = torch.nn.Linear(10, 10) def forward(self, x): y = self._module_1(x) z = self._module_2(y) z = self._module_3(y * z) z = self._module_4(y * z) return z module = RenamedIntermediateModule() g, p, o = utils._model_to_graph(module, torch.ones(1, 10), output_names=["y"]) renamed_intermediate = 0 for n in g.nodes(): for v in n.inputs(): if v.debugName().startswith("onnx::Mul_"): renamed_intermediate += 1 self.assertEqual(renamed_intermediate, 2) def _test_deduplicate_initializers(self, torchscript=False): class MyModule(torch.nn.Module): def __init__(self): super().__init__() self.layer1 = torch.nn.Linear(3, 3) self.layer2 = torch.nn.Linear(3, 3) # Reusing layers. self.layer3 = self.layer1 # Reusing parameters. self.layer2.weight = self.layer1.weight self.layer1.bias = self.layer2.bias # Parameter with different tensors equal in value. self.param1 = torch.nn.Parameter(torch.tensor([1.0, 2.0, 3.0])) self.param2 = torch.nn.Parameter(torch.tensor([1.0, 2.0, 3.0])) def forward(self, x): return ( self.layer3(self.layer2(self.layer1(x))) + self.param1 + self.param2 ) model = torch.jit.script(MyModule()) if torchscript else MyModule() x = torch.randn(3, 3) param_name_set = set([k for k, _ in model.named_parameters()]) # Test training mode. model.train() f = io.BytesIO() torch.onnx.export( model, (x,), f, training=TrainingMode.TRAINING, opset_version=self.opset_version, ) graph = onnx.load(io.BytesIO(f.getvalue())) self.assertSetEqual( set([i.name for i in graph.graph.initializer]), param_name_set ) model.train() f = io.BytesIO() torch.onnx.export( model, (x,), f, training=TrainingMode.PRESERVE, opset_version=self.opset_version, ) graph = onnx.load(io.BytesIO(f.getvalue())) self.assertSetEqual( set([i.name for i in graph.graph.initializer]), param_name_set ) # Test eval mode. model.eval() f = io.BytesIO() torch.onnx.export(model, (x,), f, opset_version=self.opset_version) graph = onnx.load(io.BytesIO(f.getvalue())) param_name_set.remove("param2") self.assertSetEqual( set([i.name for i in graph.graph.initializer]), param_name_set ) def test_deduplicate_initializers(self): self._test_deduplicate_initializers(torchscript=False) def test_deduplicate_initializers_torchscript(self): self._test_deduplicate_initializers(torchscript=True) @skipIfNoCuda def test_deduplicate_initializers_diff_devices(self): class Model(torch.nn.Module): def __init__(self): super().__init__() self.w_cpu = torch.nn.Parameter( torch.ones(3, device=torch.device("cpu")) ) self.w_cuda = torch.nn.Parameter( torch.ones(3, device=torch.device("cuda")) ) def forward(self, x, y): return x + self.w_cpu, y + self.w_cuda x = torch.randn(3, 3, device=torch.device("cpu")) y = torch.randn(3, 3, device=torch.device("cuda")) f = io.BytesIO() torch.onnx.export(Model(), (x, y), f, opset_version=self.opset_version) graph = onnx.load(io.BytesIO(f.getvalue())) self.assertSetEqual(set([i.name for i in graph.graph.initializer]), {"w_cpu"}) def test_duplicated_output_node(self): class DuplicatedOutputNet(torch.nn.Module): def __init__(self, input_size, num_classes): super(DuplicatedOutputNet, self).__init__() self.fc1 = torch.nn.Linear(input_size, num_classes) def forward(self, input0, input1): out1 = self.fc1(input0) out2 = self.fc1(input1) return out1, out1, out2, out1, out2 N, D_in, H, D_out = 64, 784, 500, 10 pt_model = DuplicatedOutputNet(D_in, D_out) f = io.BytesIO() x = torch.randn(N, D_in) dynamic_axes = { "input0": {0: "input0_dim0", 1: "input0_dim1"}, "input1": {0: "input1_dim0", 1: "input1_dim1"}, "output-0": {0: "output-0_dim0", 1: "output-0_dim1"}, "output-1": {0: "output-1_dim0", 1: "output-1_dim1"}, "output-2": {0: "output-2_dim0", 1: "output-2_dim1"}, "output-3": {0: "output-3_dim0", 1: "output-3_dim1"}, "output-4": {0: "output-4_dim0", 1: "output-4_dim1"}, } torch.onnx.export( pt_model, (x, x), f, input_names=["input0", "input1"], output_names=["output-0", "output-1", "output-2", "output-3", "output-4"], do_constant_folding=False, training=torch.onnx.TrainingMode.TRAINING, dynamic_axes=dynamic_axes, verbose=True, keep_initializers_as_inputs=True, ) graph = onnx.load(io.BytesIO(f.getvalue())) self.assertEqual(graph.graph.input[0].name, "input0") self.assertEqual(graph.graph.input[1].name, "input1") for i in range(5): self.assertEqual(graph.graph.output[i].name, f"output-{i}") self.assertEqual(graph.graph.node[0].op_type, "Gemm") self.assertEqual(graph.graph.node[1].op_type, "Identity") self.assertEqual(graph.graph.node[2].op_type, "Identity") self.assertEqual(graph.graph.node[3].op_type, "Gemm") self.assertEqual(graph.graph.node[4].op_type, "Identity") def test_bad_symbolic_registration(self): _onnx_opset_version = 9 @parse_args("v") def cat(g, tensor_list, dim): tensors = _unpack_list(tensor_list) return g.op("Concat", *tensors, axis_i=dim) register_custom_op_symbolic("::cat", cat, _onnx_opset_version) class CatModel(torch.nn.Module): def forward(self, x): return torch.cat((x, x, x), 0) model = CatModel() x = torch.randn(2, 3) f = io.BytesIO() self.assertExpectedRaisesInline( AssertionError, lambda: torch.onnx.export( model, (x,), f, opset_version=_onnx_opset_version ), ( "A mismatch between the number of arguments (2) and their descriptors (1) was found at symbolic function " "'cat'. If you believe this is not due to custom symbolic implementation within your code or an external " "library, please file an issue at https://github.com/pytorch/pytorch/issues/new?template=bug-report.yml to " "report this bug." ), ) unregister_custom_op_symbolic("::cat", _onnx_opset_version) class TestUtilityFuns_opset10(TestUtilityFuns_opset9): opset_version = 10 class TestUtilityFuns_opset11(TestUtilityFuns_opset9): opset_version = 11 class TestUtilityFuns_opset12(TestUtilityFuns_opset9): opset_version = 12 class TestUtilityFuns_opset13(TestUtilityFuns_opset9): opset_version = 13 class TestUtilityFuns_opset14(TestUtilityFuns_opset9): opset_version = 14 class TestUtilityFuns_opset15(TestUtilityFuns_opset9): opset_version = 15 if __name__ == "__main__": run_tests()
36.133654
124
0.561915
import copy import io import unittest import onnx import torchvision from autograd_helper import CustomFunction as CustomFunction2 from test_pytorch_common import ( TestCase, run_tests, skipIfNoCuda, skipIfUnsupportedMaxOpsetVersion, skipIfUnsupportedMinOpsetVersion, ) from verify import verify import torch import torch.onnx import torch.utils.cpp_extension from torch.onnx import ( OperatorExportTypes, TrainingMode, register_custom_op_symbolic, unregister_custom_op_symbolic, utils, ) from torch.onnx.symbolic_helper import ( _set_onnx_shape_inference, _set_operator_export_type, _set_opset_version, _unpack_list, parse_args, ) skip = unittest.skip class _BaseTestCase(TestCase): def setUp(self): torch.manual_seed(0) if torch.cuda.is_available(): torch.cuda.manual_seed_all(0) def _model_to_graph( self, model, input, do_constant_folding=True, training=TrainingMode.EVAL, operator_export_type=OperatorExportTypes.ONNX, input_names=None, dynamic_axes=None, ): if training == torch.onnx.TrainingMode.TRAINING: model.train() elif training == torch.onnx.TrainingMode.EVAL: model.eval() _set_onnx_shape_inference(False) utils._validate_dynamic_axes(dynamic_axes, model, None, None) graph, params_dict, torch_out = utils._model_to_graph( model, input, do_constant_folding=do_constant_folding, _disable_torch_constant_prop=True, operator_export_type=operator_export_type, training=training, input_names=input_names, dynamic_axes=dynamic_axes, ) _set_onnx_shape_inference(True) return graph, params_dict, torch_out class TestUtilityFuns_opset_independent(_BaseTestCase): def test_unconvertible_ops(self): class MyModule(torch.nn.Module): def forward(self, x): return torch.cumsum(x, dim=0) model = MyModule() x = torch.randn(2, 3, 4) graph, unconvertible_ops = utils.unconvertible_ops(model, (x,), opset_version=9) iter = graph.nodes() self.assertEqual(next(iter).kind(), "onnx::Constant") self.assertEqual(next(iter).kind(), "prim::Constant") self.assertEqual(next(iter).kind(), "aten::cumsum") self.assertEqual(len(unconvertible_ops), 1) self.assertEqual(unconvertible_ops, ["aten::cumsum"]) class TestUtilityFuns_opset9(_BaseTestCase): opset_version = 9 def test_is_in_onnx_export(self): test_self = self class MyModule(torch.nn.Module): def forward(self, x): test_self.assertTrue(torch.onnx.is_in_onnx_export()) raise ValueError return x + 1 x = torch.randn(3, 4) f = io.BytesIO() try: torch.onnx.export(MyModule(), x, f, opset_version=self.opset_version) except ValueError: self.assertFalse(torch.onnx.is_in_onnx_export()) def test_validate_dynamic_axes_invalid_input_output_name(self): import warnings with warnings.catch_warnings(record=True) as w: warnings.simplefilter("always") utils._validate_dynamic_axes( {"input1": {}, "output": {}, "invalid_name1": {}, "invalid_name2": {}}, None, ["input1", "input2"], ["output"], ) messages = [str(warning.message) for warning in w] self.assertIn( "Provided key invalid_name1 for dynamic axes is not a valid input/output name", messages, ) self.assertIn( "Provided key invalid_name2 for dynamic axes is not a valid input/output name", messages, ) self.assertEqual(len(messages), 2) @skipIfUnsupportedMinOpsetVersion(11) def test_split_to_slice(self): class SplitModule(torch.nn.Module): def forward(self, x, y, t): splits = (x.size(1), y.size(1)) out, out2 = torch.split(t, splits, dim=1) return out, out2 _set_opset_version(self.opset_version) _set_operator_export_type(OperatorExportTypes.ONNX) x = torch.randn(2, 3) y = torch.randn(2, 4) t = torch.randn(2, 7) graph, _, _ = self._model_to_graph( SplitModule(), (x, y, t), input_names=["x", "y", "t"], dynamic_axes={"x": [0, 1], "y": [0, 1], "t": [0, 1]}, ) for node in graph.nodes(): self.assertNotEqual(node.kind(), "onnx::SplitToSequence") def test_constant_fold_transpose(self): class TransposeModule(torch.nn.Module): def forward(self, x): a = torch.tensor([[1.0, 2.0, 3.0], [4.0, 5.0, 6.0]]) b = torch.transpose(a, 1, 0) return b + x _set_opset_version(self.opset_version) _set_operator_export_type(OperatorExportTypes.ONNX) x = torch.ones(3, 2) graph, _, __ = self._model_to_graph( TransposeModule(), (x,), input_names=["x"], dynamic_axes={"x": [0, 1]} ) for node in graph.nodes(): self.assertNotEqual(node.kind(), "onnx::Transpose") self.assertNotEqual(node.kind(), "onnx::Cast") self.assertNotEqual(node.kind(), "onnx::Constant") self.assertEqual(len(list(graph.nodes())), 1) def test_constant_fold_reduceL2(self): class ReduceModule(torch.nn.Module): def forward(self, x): a = torch.tensor([[1.0, 2.0, 3.0], [4.0, 5.0, 6.0]]) b = torch.norm(a, p=2, dim=-2, keepdim=False) return b + x _set_opset_version(self.opset_version) _set_operator_export_type(OperatorExportTypes.ONNX) x = torch.ones(2, 3) graph, _, __ = self._model_to_graph( ReduceModule(), (x,), input_names=["x"], dynamic_axes={"x": [0, 1]} ) for node in graph.nodes(): self.assertNotEqual(node.kind(), "onnx::ReduceL2") self.assertEqual(len(list(graph.nodes())), 1) def test_constant_fold_reduceL1(self): class NormModule(torch.nn.Module): def forward(self, x): a = torch.tensor([[1.0, 2.0, 3.0], [4.0, 5.0, 6.0]]) b = torch.norm(a, p=1, dim=-2) return b + x _set_opset_version(self.opset_version) _set_operator_export_type(OperatorExportTypes.ONNX) x = torch.ones(2, 3) graph, _, __ = self._model_to_graph( NormModule(), (x,), input_names=["x"], dynamic_axes={"x": [0, 1]} ) for node in graph.nodes(): self.assertNotEqual(node.kind(), "onnx::ReduceL1") self.assertEqual(len(list(graph.nodes())), 1) def test_constant_fold_slice(self): class NarrowModule(torch.nn.Module): def forward(self, x): a = torch.tensor([[1.0, 2.0, 3.0], [4.0, 5.0, 6.0]]) b = torch.narrow(a, 0, 0, 1) return b + x _set_opset_version(self.opset_version) _set_operator_export_type(OperatorExportTypes.ONNX) x = torch.ones(1, 3) graph, _, __ = self._model_to_graph( NarrowModule(), (x,), input_names=["x"], dynamic_axes={"x": [0, 1]} ) for node in graph.nodes(): self.assertNotEqual(node.kind(), "onnx::Slice") self.assertNotEqual(node.kind(), "onnx::Cast") self.assertNotEqual(node.kind(), "onnx::Constant") self.assertEqual(len(list(graph.nodes())), 1) def test_constant_fold_slice_index_exceeds_dim(self): class SliceIndexExceedsDimModule(torch.nn.Module): def forward(self, x): a = torch.tensor([[1.0, 2.0, 3.0], [4.0, 5.0, 6.0]]) b = a[1:10] return b + x _set_opset_version(self.opset_version) _set_operator_export_type(OperatorExportTypes.ONNX) x = torch.ones(1, 3) graph, _, __ = self._model_to_graph( SliceIndexExceedsDimModule(), (x,), input_names=["x"], dynamic_axes={"x": [0, 1]}, ) for node in graph.nodes(): self.assertNotEqual(node.kind(), "onnx::Slice") self.assertNotEqual(node.kind(), "onnx::Cast") self.assertNotEqual(node.kind(), "onnx::Constant") self.assertEqual(len(list(graph.nodes())), 1) def test_constant_fold_slice_negative_index(self): class SliceNegativeIndexModule(torch.nn.Module): def forward(self, x): a = torch.tensor([[1.0, 2.0, 3.0], [4.0, 5.0, 6.0]]) b = a[0:-1] c = torch.select(a, dim=-1, index=-2) d = torch.select(a, dim=1, index=0) return b + x, c + d _set_opset_version(self.opset_version) _set_operator_export_type(OperatorExportTypes.ONNX) x = torch.ones(1, 3) graph, _, __ = self._model_to_graph( SliceNegativeIndexModule(), (x,), input_names=["x"], dynamic_axes={"x": [0, 1]}, ) for node in graph.nodes(): self.assertNotEqual(node.kind(), "onnx::Slice") self.assertNotEqual(node.kind(), "onnx::Cast") self.assertNotEqual(node.kind(), "onnx::Constant") def test_constant_fold_gather(self): class GatherModule(torch.nn.Module): def forward(self, x): a = torch.tensor([[1.0, 2.0, 3.0], [4.0, 5.0, 6.0]]) b = torch.select(a, dim=1, index=-2) c = torch.index_select(a, dim=-2, index=torch.tensor([0, 1])) return b + 1, c + x _set_opset_version(self.opset_version) _set_operator_export_type(OperatorExportTypes.ONNX) x = torch.ones(1, 3) model = GatherModule() model(x) graph, _, __ = self._model_to_graph( GatherModule(), (x,), input_names=["x"], dynamic_axes={"x": [0, 1]} ) for node in graph.nodes(): self.assertNotEqual(node.kind(), "onnx::Gather") def test_constant_fold_unsqueeze(self): class UnsqueezeModule(torch.nn.Module): def forward(self, x): a = torch.tensor([[1.0, 2.0, 3.0], [4.0, 5.0, 6.0]]) b = torch.unsqueeze(a, -2) return b + x _set_opset_version(self.opset_version) _set_operator_export_type(OperatorExportTypes.ONNX) x = torch.ones(1, 2, 3) graph, _, __ = self._model_to_graph( UnsqueezeModule(), (x,), input_names=["x"], dynamic_axes={"x": [0, 1, 2]} ) for node in graph.nodes(): self.assertNotEqual(node.kind(), "onnx::Unsqueeze") self.assertNotEqual(node.kind(), "onnx::Cast") self.assertNotEqual(node.kind(), "onnx::Constant") self.assertEqual(len(list(graph.nodes())), 1) def test_constant_fold_unsqueeze_multi_axies(self): class PReluModel(torch.nn.Module): def __init__(self): super(PReluModel, self).__init__() self.prelu = torch.nn.PReLU() def forward(self, x): a = torch.randn(2, 3, 4, 5, 8, 7) return self.prelu(x) + a _set_opset_version(self.opset_version) _set_operator_export_type(OperatorExportTypes.ONNX) x = torch.randn(2, 3, 4, 5, 8, 7) graph, _, __ = self._model_to_graph( PReluModel(), x, input_names=["x"], dynamic_axes={"x": [0, 1, 2, 3, 4, 5]} ) for node in graph.nodes(): self.assertNotEqual(node.kind(), "onnx::Unsqueeze") self.assertNotEqual(node.kind(), "onnx::Cast") self.assertNotEqual(node.kind(), "onnx::Constant") self.assertEqual(len(list(graph.nodes())), 4) def test_constant_fold_squeeze_without_axes(self): class SqueezeModule(torch.nn.Module): def forward(self, x): a = torch.tensor([[[1.0, 2.0, 3.0], [4.0, 5.0, 6.0]]]) return torch.squeeze(a) + x + torch.squeeze(a) _set_opset_version(self.opset_version) _set_operator_export_type(OperatorExportTypes.ONNX) x = torch.ones(2, 3) graph, _, __ = self._model_to_graph( SqueezeModule(), (x,), input_names=["x"], dynamic_axes={"x": [0, 1]} ) for node in graph.nodes(): self.assertNotEqual(node.kind(), "onnx::Squeeze") self.assertNotEqual(node.kind(), "onnx::Cast") self.assertNotEqual(node.kind(), "onnx::Constant") self.assertEqual(len(list(graph.nodes())), 2) def test_constant_fold_squeeze_with_axes(self): class SqueezeAxesModule(torch.nn.Module): def forward(self, x): a = torch.tensor([[[1.0, 2.0, 3.0], [4.0, 5.0, 6.0]]]) return torch.squeeze(a, dim=-3) + x _set_opset_version(self.opset_version) _set_operator_export_type(OperatorExportTypes.ONNX) x = torch.ones(2, 3) graph, _, __ = self._model_to_graph( SqueezeAxesModule(), (x,), input_names=["x"], dynamic_axes={"x": [0, 1]} ) for node in graph.nodes(): self.assertNotEqual(node.kind(), "onnx::Squeeze") self.assertNotEqual(node.kind(), "onnx::Cast") self.assertNotEqual(node.kind(), "onnx::Constant") self.assertEqual(len(list(graph.nodes())), 1) def test_constant_fold_concat(self): class ConcatModule(torch.nn.Module): def forward(self, x): # without these casts, we will actually fail to pull out one of # the constants, thus failing constant folding. I think the # test is wrong but I don't have time to write a more correct a = torch.tensor([[1.0, 2.0, 3.0]]).to(torch.float) b = torch.tensor([[4.0, 5.0, 6.0]]).to(torch.float) c = torch.cat((a, b), 0) d = b + c return x + d _set_opset_version(self.opset_version) _set_operator_export_type(OperatorExportTypes.ONNX) x = torch.ones(2, 3) graph, _, __ = self._model_to_graph( ConcatModule(), (x,), input_names=["x"], dynamic_axes={"x": [0, 1]} ) for node in graph.nodes(): self.assertNotEqual(node.kind(), "onnx::Concat") self.assertNotEqual(node.kind(), "onnx::Cast") self.assertNotEqual(node.kind(), "onnx::Constant") self.assertEqual(len(list(graph.nodes())), 1) def test_constant_fold_lstm(self): class GruNet(torch.nn.Module): def __init__(self): super(GruNet, self).__init__() self.mygru = torch.nn.GRU(7, 3, 1, bidirectional=False) def forward(self, input, initial_state): return self.mygru(input, initial_state) _set_opset_version(self.opset_version) _set_operator_export_type(OperatorExportTypes.ONNX) input = torch.randn(5, 3, 7) h0 = torch.randn(1, 3, 3) graph, _, __ = self._model_to_graph( GruNet(), (input, h0), input_names=["input", "h0"], dynamic_axes={"input": [0, 1, 2], "h0": [0, 1, 2]}, ) for node in graph.nodes(): self.assertNotEqual(node.kind(), "onnx::Slice") self.assertNotEqual(node.kind(), "onnx::Concat") self.assertNotEqual(node.kind(), "onnx::Unsqueeze") if self.opset_version <= 12: self.assertEqual(len(list(graph.nodes())), 3) else: self.assertEqual(len(list(graph.nodes())), 4) def test_constant_fold_transpose_matmul(self): class MatMulNet(torch.nn.Module): def __init__(self): super(MatMulNet, self).__init__() self.B = torch.nn.Parameter(torch.ones(5, 3)) def forward(self, A): return torch.matmul(A, torch.transpose(self.B, -1, -2)) _set_opset_version(self.opset_version) _set_operator_export_type(OperatorExportTypes.ONNX) A = torch.randn(2, 3) graph, _, __ = self._model_to_graph( MatMulNet(), (A,), input_names=["A"], dynamic_axes={"A": [0, 1]} ) for node in graph.nodes(): self.assertNotEqual(node.kind(), "onnx::Transpose") self.assertEqual(len(list(graph.nodes())), 1) def test_constant_fold_reshape(self): class ReshapeModule(torch.nn.Module): def __init__( self, ): super(ReshapeModule, self).__init__() self.register_buffer("weight", torch.ones(5)) def forward(self, x): b = self.weight.reshape(1, -1, 1, 1) return x * b _set_opset_version(self.opset_version) _set_operator_export_type(OperatorExportTypes.ONNX) x = torch.randn(4, 5) graph, _, __ = self._model_to_graph( ReshapeModule(), (x,), input_names=["x"], dynamic_axes={"x": [0, 1]} ) for node in graph.nodes(): self.assertNotEqual(node.kind(), "onnx::Reshape") self.assertEqual(len(list(graph.nodes())), 1) def test_constant_fold_div(self): class Module(torch.nn.Module): def __init__( self, ): super(Module, self).__init__() self.register_buffer("weight", torch.ones(5)) def forward(self, x): div = self.weight.div(torch.tensor([1, 2, 3, 4, 5])) return div * x x = torch.randn(2, 5) _set_opset_version(self.opset_version) _set_operator_export_type(OperatorExportTypes.ONNX) graph, _, __ = self._model_to_graph( Module(), (x,), input_names=["x"], dynamic_axes={"x": [0, 1]} ) for node in graph.nodes(): self.assertNotEqual(node.kind(), "onnx::Div") self.assertEqual(len(list(graph.nodes())), 1) def test_constant_fold_mul(self): class Module(torch.nn.Module): def __init__( self, ): super(Module, self).__init__() self.register_buffer("weight", torch.ones(5)) def forward(self, x): mul = self.weight.mul(torch.tensor([1, 2, 3, 4, 5])) return mul / x x = torch.randn(2, 5) _set_opset_version(self.opset_version) _set_operator_export_type(OperatorExportTypes.ONNX) graph, _, __ = self._model_to_graph( Module(), (x,), input_names=["x"], dynamic_axes={"x": [0, 1]} ) for node in graph.nodes(): self.assertNotEqual(node.kind(), "onnx::Mul") self.assertEqual(len(list(graph.nodes())), 1) def test_constant_fold_add(self): class Module(torch.nn.Module): def __init__( self, ): super(Module, self).__init__() self.register_buffer("weight", torch.ones(5)) def forward(self, x): add = self.weight + torch.tensor([1, 2, 3, 4, 5]) return add - x x = torch.randn(2, 5) _set_opset_version(self.opset_version) _set_operator_export_type(OperatorExportTypes.ONNX) graph, params_dict, __ = self._model_to_graph( Module(), (x,), do_constant_folding=True, operator_export_type=OperatorExportTypes.ONNX, input_names=["x"], dynamic_axes={"x": [0, 1]}, ) for node in graph.nodes(): self.assertTrue(node.kind() != "onnx::Add") self.assertEqual(len(list(graph.nodes())), 1) params = list(params_dict.values()) self.assertEqual(len(params), 1) weight = params[0] , 4, 5, 6])) def test_constant_fold_sub(self): class Module(torch.nn.Module): def __init__( self, ): super(Module, self).__init__() self.register_buffer("weight", torch.ones(5)) def forward(self, x): sub = self.weight - torch.tensor([1, 2, 3, 4, 5]) return sub + x x = torch.randn(2, 5) _set_opset_version(self.opset_version) _set_operator_export_type(OperatorExportTypes.ONNX) graph, params_dict, __ = self._model_to_graph( Module(), (x,), do_constant_folding=True, operator_export_type=OperatorExportTypes.ONNX, input_names=["x"], dynamic_axes={"x": [0, 1]}, ) for node in graph.nodes(): self.assertNotEqual(node.kind(), "onnx::Sub") self.assertEqual(len(list(graph.nodes())), 1) params = list(params_dict.values()) self.assertEqual(len(params), 1) weight = params[0] 1, -2, -3, -4])) def test_constant_fold_sqrt(self): class Module(torch.nn.Module): def __init__( self, ): super(Module, self).__init__() self.register_buffer("weight", torch.ones(5)) def forward(self, x): sqrt = torch.sqrt(self.weight) return sqrt / x x = torch.randn(2, 5) _set_opset_version(self.opset_version) _set_operator_export_type(OperatorExportTypes.ONNX) graph, _, __ = self._model_to_graph( Module(), (x,), input_names=["x"], dynamic_axes={"x": [0, 1]} ) for node in graph.nodes(): self.assertNotEqual(node.kind(), "onnx::Sqrt") self.assertEqual(len(list(graph.nodes())), 1) def test_constant_fold_shape(self): class ShapeModule(torch.nn.Module): def __init__(self): super(ShapeModule, self).__init__() self.register_buffer("weight", torch.ones(5)) def forward(self, x): shape = self.weight.shape[0] return x + shape x = torch.randn(2, 5) _set_opset_version(self.opset_version) _set_operator_export_type(OperatorExportTypes.ONNX) graph, _, __ = self._model_to_graph( ShapeModule(), (x,), input_names=["x"], dynamic_axes={"x": [0, 1]} ) for node in graph.nodes(): self.assertNotEqual(node.kind(), "onnx::Shape") self.assertEqual(len(list(graph.nodes())), 1) def test_verbose(self): class MyModule(torch.nn.Module): def forward(self, input): return torch.exp(input) x = torch.randn(3, 4) def is_model_stripped(f, verbose=None): if verbose is None: torch.onnx.export(MyModule(), x, f, opset_version=self.opset_version) else: torch.onnx.export( MyModule(), x, f, verbose=verbose, opset_version=self.opset_version ) model = onnx.load(io.BytesIO(f.getvalue())) model_strip = copy.copy(model) onnx.helper.strip_doc_string(model_strip) return model == model_strip self.assertTrue(is_model_stripped(io.BytesIO())) self.assertFalse(is_model_stripped(io.BytesIO(), True)) def test_error_on_data_parallel(self): model = torch.nn.DataParallel(torch.nn.ReflectionPad2d((1, 2, 3, 4))) x = torch.randn(1, 2, 3, 4) f = io.BytesIO() with self.assertRaisesRegex( ValueError, "torch.nn.DataParallel is not supported by ONNX " "exporter, please use 'attribute' module to " "unwrap model from torch.nn.DataParallel. Try ", ): torch.onnx.export(model, x, f, opset_version=self.opset_version) @skipIfUnsupportedMinOpsetVersion(11) def test_sequence_dim(self): class Module(torch.nn.Module): def forward(self, x, y): return [x, y] model = Module() script_model = torch.jit.script(model) x = torch.randn(2, 3) f = io.BytesIO() y = torch.randn(2, 3) torch.onnx.export( script_model, (x, y), f, opset_version=self.opset_version, input_names=["x", "y"], dynamic_axes={"y": [1]}, ) onnx_model = onnx.load(io.BytesIO(f.getvalue())) loop_output_value_info_proto = onnx_model.graph.output[0] ref_value_info_proto = onnx.helper.make_tensor_sequence_value_info( loop_output_value_info_proto.name, 1, [2, None] ) self.assertEqual(loop_output_value_info_proto, ref_value_info_proto) f = io.BytesIO() y = torch.randn(2, 3) torch.onnx.export(script_model, (x, y), f, opset_version=self.opset_version) onnx_model = onnx.load(io.BytesIO(f.getvalue())) loop_output_value_info_proto = onnx_model.graph.output[0] ref_value_info_proto = onnx.helper.make_tensor_sequence_value_info( loop_output_value_info_proto.name, 1, [2, 3] ) self.assertEqual(loop_output_value_info_proto, ref_value_info_proto) def test_export_mode(self): class MyModule(torch.nn.Module): def forward(self, x): y = x + 1 return y model = MyModule() x = torch.randn(10, 3, 128, 128) f = io.BytesIO() model.eval() old_state = model.training torch.onnx.export( model, (x,), f, opset_version=self.opset_version, training=torch.onnx.TrainingMode.TRAINING, ) self.assertEqual(model.training, old_state) model.train() old_state = model.training torch.onnx.export( model, (x,), f, opset_version=self.opset_version, training=torch.onnx.TrainingMode.EVAL, ) self.assertEqual(model.training, old_state) @skipIfUnsupportedMinOpsetVersion(15) def test_local_function(self): class N(torch.nn.Module): def __init__(self, prob): super().__init__() self.dropout = torch.nn.Dropout(prob) def forward(self, x): return self.dropout(x) class M(torch.nn.Module): def __init__(self, num_layers): super().__init__() self.num_layers = num_layers self.lns = torch.nn.ModuleList( [torch.nn.LayerNorm(3, eps=i) for i in range(num_layers)] ) self.celu1 = torch.nn.CELU(1.0) self.celu2 = torch.nn.CELU(2.0) self.dropout = N(0.5) def forward(self, x, y, z): res1 = self.celu1(x) res2 = self.celu2(y) for ln in self.lns: z = ln(z) return res1 + res2, self.dropout(z) x = torch.randn(2, 3) y = torch.randn(2, 3) z = torch.randn(2, 3) # exist in the exported model. # Model export in inference mode will remove dropout node, # thus the dropout module no longer exist in graph. f = io.BytesIO() torch.onnx.export( M(3), (x, y, z), f, opset_version=self.opset_version, export_modules_as_functions={ torch.nn.CELU, torch.nn.Dropout, torch.nn.LayerNorm, }, ) onnx_model = onnx.load(io.BytesIO(f.getvalue())) # Check function definition funcs = onnx_model.functions celu_funcs = [f for f in funcs if f.name == "CELU"] self.assertEqual(len(celu_funcs), 1) self.assertEqual(celu_funcs[0].domain, "torch.nn.modules.activation") self.assertEqual(len(celu_funcs[0].attribute), 3) ln_funcs = [f for f in funcs if f.name == "LayerNorm"] self.assertEqual(len(ln_funcs), 1) self.assertEqual(ln_funcs[0].domain, "torch.nn.modules.normalization") self.assertEqual(len(ln_funcs[0].attribute), 3) # Check local function nodes nodes = onnx_model.graph.node celu_ns = [n for n in nodes if n.op_type == "CELU"] ln_ns = [n for n in nodes if n.op_type == "LayerNorm"] self.assertEqual(len(celu_ns), 2) self.assertEqual(celu_ns[0].domain, "torch.nn.modules.activation") self.assertEqual(len(celu_ns[0].attribute), 3) self.assertEqual(len(ln_ns), 3) self.assertEqual(ln_ns[0].domain, "torch.nn.modules.normalization") self.assertEqual(len(ln_ns[0].attribute), 3) # Export specified modules. f = io.BytesIO() torch.onnx.export( M(3), (x, y, z), f, opset_version=self.opset_version, export_modules_as_functions={torch.nn.CELU}, ) onnx_model = onnx.load(io.BytesIO(f.getvalue())) funcs = onnx_model.functions self.assertEqual(len(funcs), 1) self.assertEqual(funcs[0].name, "CELU") # Export with empty specified modules. Normal export. f = io.BytesIO() torch.onnx.export( M(3), (x, y, z), f, opset_version=self.opset_version, export_modules_as_functions=set(), ) onnx_model = onnx.load(io.BytesIO(f.getvalue())) funcs = onnx_model.functions self.assertEqual(len(funcs), 0) # Export all modules. Should contain {M, CELU, LayerNorm}. f = io.BytesIO() torch.onnx.export( M(3), (x, y, z), f, opset_version=self.opset_version, export_modules_as_functions=True, ) onnx_model = onnx.load(io.BytesIO(f.getvalue())) funcs = onnx_model.functions self.assertEqual(len(funcs), 3) @skipIfUnsupportedMinOpsetVersion(15) def test_local_function_overloads(self): class NWithOverloads(torch.nn.Module): def forward(self, x, y=None, z=None): if y is None: return x + 1 elif z is None: return x + y else: return x + y, x + z class M(torch.nn.Module): def __init__(self, num_layers): super().__init__() self.n = NWithOverloads() def forward(self, x, y, z): return self.n(x), self.n(x, y), self.n(x, y, z) x = torch.randn(2, 3) y = torch.randn(2, 3) z = torch.randn(2, 3) f = io.BytesIO() torch.onnx.export( M(3), (x, y, z), f, opset_version=self.opset_version, export_modules_as_functions={NWithOverloads}, ) onnx_model = onnx.load(io.BytesIO(f.getvalue())) funcs = onnx_model.functions self.assertEqual(len(funcs), 3) func_names = [f.name for f in funcs] self.assertIn("NWithOverloads", func_names) self.assertIn("NWithOverloads.1", func_names) self.assertIn("NWithOverloads.2", func_names) @skipIfUnsupportedMinOpsetVersion(15) def test_local_function_infer_scopes(self): class M(torch.nn.Module): def forward(self, x): # Concatenation of scalars inserts unscoped tensors in IR graph. new_tensor_shape = x.size()[:-1] + (1, 1, -1) tensor = x.view(*new_tensor_shape) return tensor x = torch.randn(4, 5) f = io.BytesIO() torch.onnx.export( M(), (x,), f, export_modules_as_functions=True, opset_version=self.opset_version, do_constant_folding=False, ) onnx_model = onnx.load(io.BytesIO(f.getvalue())) funcs = onnx_model.functions self.assertIn("M", [f.name for f in funcs]) @skipIfUnsupportedMinOpsetVersion(15) def test_local_function_predefined_attributes(self): class M(torch.nn.Module): num_layers: int def __init__(self, num_layers): super().__init__() self.num_layers = num_layers self.lns = torch.nn.ModuleList( [torch.nn.LayerNorm(3, eps=1e-4) for _ in range(num_layers)] ) def forward(self, x): for ln in self.lns: x = ln(x) return x x = torch.randn(2, 3) f = io.BytesIO() model = M(3) torch.onnx.export( model, (x,), f, export_modules_as_functions=True, opset_version=self.opset_version, ) onnx_model = onnx.load(io.BytesIO(f.getvalue())) funcs = onnx_model.functions m_funcs = [fn for fn in funcs if fn.name == "M"] self.assertEqual(m_funcs[0].attribute, ["num_layers"]) ln_funcs = [fn for fn in funcs if fn.name == "LayerNorm"] self.assertEqual(ln_funcs[0].attribute, ["eps", "elementwise_affine"]) from onnx import helper m_node = [n for n in onnx_model.graph.node if n.op_type == "M"] self.assertEqual( m_node[0].attribute[0], helper.make_attribute("num_layers", model.num_layers), ) ln_nodes = [n for n in m_funcs[0].node if n.op_type == "LayerNorm"] expected_ln_attrs = [ helper.make_attribute( "elementwise_affine", model.lns[0].elementwise_affine ), helper.make_attribute("eps", model.lns[0].eps), ] for ln_node in ln_nodes: self.assertIn(ln_node.attribute[0], expected_ln_attrs) self.assertIn(ln_node.attribute[1], expected_ln_attrs) def test_aten_fallthrough(self): # Test aten export of op with no symbolic class Module(torch.nn.Module): def forward(self, x): return torch.erfc(x) x = torch.randn(2, 3, 4) _set_opset_version(self.opset_version) graph, _, __ = self._model_to_graph( Module(), (x,), operator_export_type=OperatorExportTypes.ONNX_FALLTHROUGH, input_names=["x"], dynamic_axes={"x": [0, 1, 2]}, ) iter = graph.nodes() self.assertEqual(next(iter).kind(), "aten::erfc") def test_custom_op_fallthrough(self): # Test custom op op_source = """ #include <torch/script.h> torch::Tensor custom_add(torch::Tensor self, torch::Tensor other) { return self + other; } static auto registry = torch::RegisterOperators("custom_namespace::custom_op", &custom_add); """ torch.utils.cpp_extension.load_inline( name="custom_add", cpp_sources=op_source, is_python_module=False, verbose=True, ) class FooModel(torch.nn.Module): def forward(self, input, other): # Calling custom op return torch.ops.custom_namespace.custom_op(input, other) x = torch.randn(2, 3, 4, requires_grad=False) y = torch.randn(2, 3, 4, requires_grad=False) model = FooModel() graph, _, __ = self._model_to_graph( model, (x, y), operator_export_type=torch.onnx.OperatorExportTypes.ONNX_FALLTHROUGH, input_names=["x", "y"], dynamic_axes={"x": [0, 1, 2], "y": [0, 1, 2]}, ) iter = graph.nodes() self.assertEqual(next(iter).kind(), "custom_namespace::custom_op") def test_custom_opsets_gelu(self): self.addCleanup(unregister_custom_op_symbolic, "::gelu", 1) def gelu(g, self, approximate): return g.op("com.microsoft::Gelu", self).setType(self.type()) register_custom_op_symbolic("::gelu", gelu, 1) model = torch.nn.GELU(approximate="none") x = torch.randn(3, 3) f = io.BytesIO() torch.onnx.export( model, (x,), f, opset_version=self.opset_version, custom_opsets={"com.microsoft": 1}, ) graph = onnx.load(io.BytesIO(f.getvalue())) self.assertEqual(graph.graph.node[0].op_type, "Gelu") self.assertEqual(graph.opset_import[0].version, self.opset_version) self.assertEqual(graph.opset_import[1].domain, "com.microsoft") self.assertEqual(graph.opset_import[1].version, 1) def test_register_aten_custom_op_symbolic(self): self.addCleanup(unregister_custom_op_symbolic, "aten::gelu", 1) def gelu(g, self, approximate): return g.op("com.microsoft::Gelu", self).setType(self.type()) register_custom_op_symbolic("aten::gelu", gelu, 1) model = torch.nn.GELU(approximate="none") x = torch.randn(3, 3) f = io.BytesIO() torch.onnx.export(model, (x,), f, opset_version=self.opset_version) graph = onnx.load(io.BytesIO(f.getvalue())) self.assertEqual(graph.graph.node[0].op_type, "Gelu") self.assertEqual(graph.opset_import[1].domain, "com.microsoft") def test_custom_opsets_inverse(self): class CustomInverse(torch.nn.Module): def forward(self, x): return torch.inverse(x) + x def inverse(g, self): return g.op("com.microsoft::Inverse", self).setType(self.type()) register_custom_op_symbolic("::inverse", inverse, 1) model = CustomInverse() x = torch.randn(2, 3, 3) f = io.BytesIO() torch.onnx.export( model, (x,), f, opset_version=self.opset_version, custom_opsets={"com.microsoft": 1}, ) graph = onnx.load(io.BytesIO(f.getvalue())) self.assertEqual(graph.graph.node[0].op_type, "Inverse") self.assertEqual(graph.opset_import[0].version, self.opset_version) self.assertEqual(graph.opset_import[1].domain, "com.microsoft") self.assertEqual(graph.opset_import[1].version, 1) def test_onnx_fallthrough(self): # Test aten export of op with symbolic for aten class Module(torch.nn.Module): def forward(self, x): return torch.digamma(x) x = torch.randn(100, 128) graph, _, __ = self._model_to_graph( Module(), (x,), operator_export_type=OperatorExportTypes.ONNX_FALLTHROUGH, input_names=["x"], dynamic_axes={"x": [0, 1]}, ) iter = graph.nodes() self.assertEqual(next(iter).kind(), "aten::digamma") # prim::ListConstruct is exported as onnx::SequenceConstruct for opset >= 11 @skipIfUnsupportedMaxOpsetVersion(10) def test_prim_fallthrough(self): # Test prim op class PrimModule(torch.jit.ScriptModule): @torch.jit.script_method def forward(self, x): if isinstance(x, list): y = x else: y = [x] return y x = torch.tensor([2]) model = PrimModule() model.eval() graph, _, __ = self._model_to_graph( model, (x,), operator_export_type=OperatorExportTypes.ONNX_FALLTHROUGH, input_names=["x"], dynamic_axes={"x": [0]}, ) iter = graph.nodes() self.assertEqual(next(iter).kind(), "prim::ListConstruct") def test_custom_layer_tuple(self): class CustomFunction(torch.autograd.Function): @staticmethod def symbolic(g, input): return g.op("CustomNamespace::Custom", input, outputs=2) @staticmethod def forward(ctx, input): return input, input class Custom(torch.nn.Module): def forward(self, input): return CustomFunction.apply(input) model = Custom() batch = torch.FloatTensor(1, 3) graph, _, _ = self._model_to_graph( model, batch, input_names=["batch"], dynamic_axes={"batch": [0, 1]} ) iter = graph.nodes() self.assertEqual(next(iter).kind(), "CustomNamespace::Custom") def test_autograd_onnx_fallthrough(self): class CustomFunction(torch.autograd.Function): @staticmethod def forward(ctx, input): ctx.save_for_backward(input) return input.clamp(min=0) @staticmethod def backward(ctx, grad_output): (input,) = ctx.saved_tensors grad_input = grad_output.clone() grad_input[input < 0] = 0 return grad_input class Custom(torch.nn.Module): def forward(self, input): return CustomFunction.apply(input) model = Custom() batch = torch.FloatTensor(1, 3) graph, _, _ = self._model_to_graph( model, batch, operator_export_type=OperatorExportTypes.ONNX_FALLTHROUGH, input_names=["batch"], dynamic_axes={"batch": [0, 1]}, ) iter = graph.nodes() self.assertEqual(next(iter).kind(), "prim::PythonOp") def test_autograd_module_name(self): class CustomFunction(torch.autograd.Function): @staticmethod def forward(ctx, input): ctx.save_for_backward(input) return input.clamp(min=0) @staticmethod def backward(ctx, grad_output): (input,) = ctx.saved_tensors grad_input = grad_output.clone() grad_input[input < 0] = 0 return grad_input class Custom(torch.nn.Module): def forward(self, input): return CustomFunction.apply(input) + CustomFunction2.apply(input) model = Custom() batch = torch.FloatTensor(1, 3) graph, _, _ = self._model_to_graph( model, batch, input_names=["batch"], dynamic_axes={"batch": [0, 1]} ) iter = graph.nodes() autograd1 = next(iter) autograd2 = next(iter) self.assertEqual(autograd1.kind(), "prim::PythonOp") self.assertEqual(autograd2.kind(), "prim::PythonOp") self.assertNotEqual(autograd1.s("module"), autograd2.s("module")) def test_unused_initializers(self): class Model(torch.nn.Module): def __init__(self): super(Model, self).__init__() self.conv2 = torch.nn.ConvTranspose2d( 16, 33, (3, 5), stride=(2, 1), padding=(4, 2), dilation=(1, 1) ) self.k_proj = torch.nn.Linear(5, 5, bias=True) def forward(self, x): x = self.conv2(x) return x x = torch.randn(20, 16, 50, 100) _set_opset_version(self.opset_version) _set_operator_export_type(OperatorExportTypes.ONNX) _, params_dict, __ = self._model_to_graph( Model(), (x,), do_constant_folding=False, operator_export_type=OperatorExportTypes.ONNX, input_names=["x"], dynamic_axes={"x": [0, 1, 2, 3]}, ) self.assertEqual(len(params_dict), 2) def test_scripting_param(self): class MyModule(torch.nn.Module): def __init__(self): super(MyModule, self).__init__() self.conv = torch.nn.Conv2d( 3, 16, kernel_size=1, stride=2, padding=3, bias=True ) self.bn = torch.nn.BatchNorm2d(16, affine=True) def forward(self, x): x = self.conv(x) bn = self.bn(x) return bn model = torch.jit.script(MyModule()) x = torch.randn(10, 3, 128, 128) _set_opset_version(self.opset_version) _set_operator_export_type(OperatorExportTypes.ONNX) graph, _, __ = self._model_to_graph( model, (x,), do_constant_folding=True, operator_export_type=OperatorExportTypes.ONNX, training=torch.onnx.TrainingMode.TRAINING, input_names=["x"], dynamic_axes={"x": [0, 1, 2, 3]}, ) graph_input_params = [param.debugName() for param in graph.inputs()] for item in dict(model.named_parameters()): self.assertIn( item, graph_input_params, "Graph parameter names does not match model parameters.", ) def test_modifying_params(self): class MyModel(torch.nn.Module): def __init__(self): super(MyModel, self).__init__() self.param = torch.nn.Parameter(torch.tensor([2.0])) def forward(self, x): y = x * x self.param.data.add_(1.0) return y x = torch.tensor([1, 2]) # Move import to local as caffe2 backend requires additional build flag, # and is only used in this test case. import caffe2.python.onnx.backend as backend verify(MyModel(), x, backend, do_constant_folding=False) def test_fuse_conv_bn(self): class Fuse(torch.nn.Module): def __init__(self): super(Fuse, self).__init__() self.conv = torch.nn.Conv2d( 3, 2, kernel_size=1, stride=2, padding=3, bias=True ) self.bn = torch.nn.BatchNorm2d(2) def forward(self, x): out = self.conv(x) return self.bn(out) x = torch.randn(2, 3, 2, 2, requires_grad=True) graph, _, __ = self._model_to_graph( Fuse(), (x,), training=TrainingMode.EVAL, input_names=["x"], dynamic_axes={"x": [0, 1, 2, 3]}, ) for node in graph.nodes(): self.assertNotEqual(node.kind(), "onnx::BatchNormalization") self.assertEqual(node.kind(), "onnx::Conv") self.assertEqual(len(list(graph.nodes())), 1) def test_fuse_resnet18(self): model = torchvision.models.resnet18(pretrained=False) x = torch.randn(2, 3, 224, 224, requires_grad=True) graph, _, __ = self._model_to_graph( model, (x,), training=TrainingMode.EVAL, input_names=["x"], dynamic_axes={"x": [0, 1, 2, 3]}, ) for node in graph.nodes(): self.assertNotEqual(node.kind(), "onnx::BatchNormalization") def test_onnx_function_substitution_pass(self): @torch.jit.script def f(x: torch.Tensor, y: torch.Tensor): z = x - y return x + z class MyModule(torch.nn.Module): def __init__(self): super(MyModule, self).__init__() def forward(self, x, y): return f(x, y) input_1 = torch.tensor(11) input_2 = torch.tensor(12) _set_opset_version(self.opset_version) _set_operator_export_type(OperatorExportTypes.ONNX) graph, _, __ = self._model_to_graph( MyModule(), (input_1, input_2), do_constant_folding=True, operator_export_type=OperatorExportTypes.ONNX, input_names=["input_1", "input_2"], dynamic_axes={"input_1": [0], "input_2": [0]}, ) # Check that the prim::Constant node in the graph for representing the # scripted function `f` is removed and the following prim::CallFunction # is replced by inline graph, with onnx::Sub and onnx::Add nodes. for node in graph.nodes(): self.assertNotEqual(node.kind(), "prim::Constant") self.assertEqual( len(list(graph.nodes())), 2 ) # onnx::Sub and onnx::Add nodes only. def test_onnx_value_name(self): class MyModule(torch.nn.Module): def __init__(self): super().__init__() self.in_weight = torch.nn.Parameter(torch.Tensor(3, 3)) self.in_bias = torch.nn.Parameter(torch.Tensor(3)) def forward(self, x): start = 0 end = None weight = self.in_weight bias = self.in_bias weight = weight[start:end, :] if bias is not None: bias = bias[start:end] return torch.nn.functional.linear(x, weight, bias) model = MyModule() x = torch.randn(3, 3) f = io.BytesIO() model.eval() torch.onnx.export( model, (x,), f, opset_version=self.opset_version, keep_initializers_as_inputs=True, ) graph = onnx.load(io.BytesIO(f.getvalue())) self.assertEqual(graph.graph.input[1].name, "in_weight") self.assertEqual(graph.graph.input[2].name, "in_bias") def test_onnx_intermediate_renaming(self): class RenamedIntermediateModule(torch.nn.Module): def __init__(self): super().__init__() self._module_1 = torch.nn.Linear(10, 10) self._module_2 = torch.nn.Linear(10, 10) self._module_3 = torch.nn.Linear(10, 10) self._module_4 = torch.nn.Linear(10, 10) def forward(self, x): y = self._module_1(x) z = self._module_2(y) z = self._module_3(y * z) z = self._module_4(y * z) return z module = RenamedIntermediateModule() g, p, o = utils._model_to_graph(module, torch.ones(1, 10), output_names=["y"]) renamed_intermediate = 0 for n in g.nodes(): for v in n.inputs(): if v.debugName().startswith("onnx::Mul_"): renamed_intermediate += 1 self.assertEqual(renamed_intermediate, 2) def _test_deduplicate_initializers(self, torchscript=False): class MyModule(torch.nn.Module): def __init__(self): super().__init__() self.layer1 = torch.nn.Linear(3, 3) self.layer2 = torch.nn.Linear(3, 3) # Reusing layers. self.layer3 = self.layer1 # Reusing parameters. self.layer2.weight = self.layer1.weight self.layer1.bias = self.layer2.bias # Parameter with different tensors equal in value. self.param1 = torch.nn.Parameter(torch.tensor([1.0, 2.0, 3.0])) self.param2 = torch.nn.Parameter(torch.tensor([1.0, 2.0, 3.0])) def forward(self, x): return ( self.layer3(self.layer2(self.layer1(x))) + self.param1 + self.param2 ) model = torch.jit.script(MyModule()) if torchscript else MyModule() x = torch.randn(3, 3) param_name_set = set([k for k, _ in model.named_parameters()]) # Test training mode. model.train() f = io.BytesIO() torch.onnx.export( model, (x,), f, training=TrainingMode.TRAINING, opset_version=self.opset_version, ) graph = onnx.load(io.BytesIO(f.getvalue())) self.assertSetEqual( set([i.name for i in graph.graph.initializer]), param_name_set ) model.train() f = io.BytesIO() torch.onnx.export( model, (x,), f, training=TrainingMode.PRESERVE, opset_version=self.opset_version, ) graph = onnx.load(io.BytesIO(f.getvalue())) self.assertSetEqual( set([i.name for i in graph.graph.initializer]), param_name_set ) # Test eval mode. model.eval() f = io.BytesIO() torch.onnx.export(model, (x,), f, opset_version=self.opset_version) graph = onnx.load(io.BytesIO(f.getvalue())) param_name_set.remove("param2") self.assertSetEqual( set([i.name for i in graph.graph.initializer]), param_name_set ) def test_deduplicate_initializers(self): self._test_deduplicate_initializers(torchscript=False) def test_deduplicate_initializers_torchscript(self): self._test_deduplicate_initializers(torchscript=True) @skipIfNoCuda def test_deduplicate_initializers_diff_devices(self): class Model(torch.nn.Module): def __init__(self): super().__init__() self.w_cpu = torch.nn.Parameter( torch.ones(3, device=torch.device("cpu")) ) self.w_cuda = torch.nn.Parameter( torch.ones(3, device=torch.device("cuda")) ) def forward(self, x, y): return x + self.w_cpu, y + self.w_cuda x = torch.randn(3, 3, device=torch.device("cpu")) y = torch.randn(3, 3, device=torch.device("cuda")) f = io.BytesIO() torch.onnx.export(Model(), (x, y), f, opset_version=self.opset_version) graph = onnx.load(io.BytesIO(f.getvalue())) self.assertSetEqual(set([i.name for i in graph.graph.initializer]), {"w_cpu"}) def test_duplicated_output_node(self): class DuplicatedOutputNet(torch.nn.Module): def __init__(self, input_size, num_classes): super(DuplicatedOutputNet, self).__init__() self.fc1 = torch.nn.Linear(input_size, num_classes) def forward(self, input0, input1): out1 = self.fc1(input0) out2 = self.fc1(input1) return out1, out1, out2, out1, out2 N, D_in, H, D_out = 64, 784, 500, 10 pt_model = DuplicatedOutputNet(D_in, D_out) f = io.BytesIO() x = torch.randn(N, D_in) dynamic_axes = { "input0": {0: "input0_dim0", 1: "input0_dim1"}, "input1": {0: "input1_dim0", 1: "input1_dim1"}, "output-0": {0: "output-0_dim0", 1: "output-0_dim1"}, "output-1": {0: "output-1_dim0", 1: "output-1_dim1"}, "output-2": {0: "output-2_dim0", 1: "output-2_dim1"}, "output-3": {0: "output-3_dim0", 1: "output-3_dim1"}, "output-4": {0: "output-4_dim0", 1: "output-4_dim1"}, } torch.onnx.export( pt_model, (x, x), f, input_names=["input0", "input1"], output_names=["output-0", "output-1", "output-2", "output-3", "output-4"], do_constant_folding=False, training=torch.onnx.TrainingMode.TRAINING, dynamic_axes=dynamic_axes, verbose=True, keep_initializers_as_inputs=True, ) graph = onnx.load(io.BytesIO(f.getvalue())) self.assertEqual(graph.graph.input[0].name, "input0") self.assertEqual(graph.graph.input[1].name, "input1") for i in range(5): self.assertEqual(graph.graph.output[i].name, f"output-{i}") self.assertEqual(graph.graph.node[0].op_type, "Gemm") self.assertEqual(graph.graph.node[1].op_type, "Identity") self.assertEqual(graph.graph.node[2].op_type, "Identity") self.assertEqual(graph.graph.node[3].op_type, "Gemm") self.assertEqual(graph.graph.node[4].op_type, "Identity") def test_bad_symbolic_registration(self): _onnx_opset_version = 9 @parse_args("v") def cat(g, tensor_list, dim): tensors = _unpack_list(tensor_list) return g.op("Concat", *tensors, axis_i=dim) register_custom_op_symbolic("::cat", cat, _onnx_opset_version) class CatModel(torch.nn.Module): def forward(self, x): return torch.cat((x, x, x), 0) model = CatModel() x = torch.randn(2, 3) f = io.BytesIO() self.assertExpectedRaisesInline( AssertionError, lambda: torch.onnx.export( model, (x,), f, opset_version=_onnx_opset_version ), ( "A mismatch between the number of arguments (2) and their descriptors (1) was found at symbolic function " "'cat'. If you believe this is not due to custom symbolic implementation within your code or an external " "library, please file an issue at https://github.com/pytorch/pytorch/issues/new?template=bug-report.yml to " "report this bug." ), ) unregister_custom_op_symbolic("::cat", _onnx_opset_version) class TestUtilityFuns_opset10(TestUtilityFuns_opset9): opset_version = 10 class TestUtilityFuns_opset11(TestUtilityFuns_opset9): opset_version = 11 class TestUtilityFuns_opset12(TestUtilityFuns_opset9): opset_version = 12 class TestUtilityFuns_opset13(TestUtilityFuns_opset9): opset_version = 13 class TestUtilityFuns_opset14(TestUtilityFuns_opset9): opset_version = 14 class TestUtilityFuns_opset15(TestUtilityFuns_opset9): opset_version = 15 if __name__ == "__main__": run_tests()
true
true
1c3914fede50b34f4b2f062825b934eb1dadb5ab
1,545
py
Python
setup.py
akalex/aiohttp_prometheus_exporter
d6e80e86a63bf568d175929e7a7d9ee039af5a68
[ "MIT" ]
null
null
null
setup.py
akalex/aiohttp_prometheus_exporter
d6e80e86a63bf568d175929e7a7d9ee039af5a68
[ "MIT" ]
null
null
null
setup.py
akalex/aiohttp_prometheus_exporter
d6e80e86a63bf568d175929e7a7d9ee039af5a68
[ "MIT" ]
null
null
null
#!/usr/bin/env python """The setup script.""" from setuptools import setup, find_packages with open('README.rst') as readme_file: readme = readme_file.read() with open('HISTORY.rst') as history_file: history = history_file.read() requirements = ['aiohttp>=3', 'prometheus_client>=0.6', ] setup_requirements = ['pytest-runner', ] test_requirements = ['pytest>=3', ] setup( author="Adrian Krupa", author_email='adrian.krupa91@gmail.com', python_requires='>=3.6', classifiers=[ 'Development Status :: 2 - Pre-Alpha', 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Natural Language :: English', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.6', 'Programming Language :: Python :: 3.7', 'Programming Language :: Python :: 3.8', ], description="Prometheus exporter for aiohttp server and client.", install_requires=requirements, license="MIT license", long_description=readme + '\n\n' + history, long_description_content_type='text/x-rst', include_package_data=True, keywords='aiohttp_prometheus_exporter', name='aiohttp_prometheus_exporter', packages=find_packages(include=['aiohttp_prometheus_exporter', 'aiohttp_prometheus_exporter.*']), setup_requires=setup_requirements, test_suite='tests', tests_require=test_requirements, url='https://github.com/adriankrupa/aiohttp_prometheus_exporter', version='0.2.4', zip_safe=False, )
31.530612
101
0.680906
from setuptools import setup, find_packages with open('README.rst') as readme_file: readme = readme_file.read() with open('HISTORY.rst') as history_file: history = history_file.read() requirements = ['aiohttp>=3', 'prometheus_client>=0.6', ] setup_requirements = ['pytest-runner', ] test_requirements = ['pytest>=3', ] setup( author="Adrian Krupa", author_email='adrian.krupa91@gmail.com', python_requires='>=3.6', classifiers=[ 'Development Status :: 2 - Pre-Alpha', 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Natural Language :: English', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.6', 'Programming Language :: Python :: 3.7', 'Programming Language :: Python :: 3.8', ], description="Prometheus exporter for aiohttp server and client.", install_requires=requirements, license="MIT license", long_description=readme + '\n\n' + history, long_description_content_type='text/x-rst', include_package_data=True, keywords='aiohttp_prometheus_exporter', name='aiohttp_prometheus_exporter', packages=find_packages(include=['aiohttp_prometheus_exporter', 'aiohttp_prometheus_exporter.*']), setup_requires=setup_requirements, test_suite='tests', tests_require=test_requirements, url='https://github.com/adriankrupa/aiohttp_prometheus_exporter', version='0.2.4', zip_safe=False, )
true
true
1c391551e0a5354e37d07670d112ae687c8b0879
4,663
py
Python
python/zephyr/constants.py
r-pad/zephyr
c8f45e207c11bfc2b21df169db65a7df892d2848
[ "MIT" ]
18
2021-05-27T04:40:38.000Z
2022-02-08T19:46:31.000Z
python/zephyr/constants.py
r-pad/zephyr
c8f45e207c11bfc2b21df169db65a7df892d2848
[ "MIT" ]
null
null
null
python/zephyr/constants.py
r-pad/zephyr
c8f45e207c11bfc2b21df169db65a7df892d2848
[ "MIT" ]
2
2021-11-07T12:42:00.000Z
2022-03-01T12:51:54.000Z
FEATURE_MEAN = [491.3183898925781, 445.4370422363281, 104.46714782714844, -9.33281421661377, -0.3871251940727234, 15.277295112609863, 96.35192108154297, -21.257665634155273, 244.6168975830078, 454.5150146484375, 452.712890625, 93.33969116210938, 96.92170715332031, 0.4305391013622284, 0.39397644996643066, 0.10189277678728104, 0.2605348229408264, -0.016525093466043472, -0.0010204192949458957, 0.029299981892108917, 0.2030143290758133, -0.03813593089580536, 0.5364543795585632, 0.9343518018722534, 0.9338011741638184, 0.8567478060722351, 0.856406033039093, 14.381174087524414, 39.7275505065918, 0.19100581109523773, 0.2816426157951355, 0.29801905155181885, 32.04430389404297, 15.896907806396484, 0.03398795798420906, 6.787647724151611, 0.43156930804252625, 0.22434939444065094, 0.0131981261074543] FEATURE_VAR = [104024.1953125, 84253.234375, 10451.4873046875, 7728.88623046875, 0.6716803908348083, 3666.609619140625, 23751.6484375, 3180.625244140625, 57259.7109375, 140852.34375, 82354.09375, 9427.083984375, 9033.4541015625, 0.009170586243271828, 0.009593164548277855, 0.00744457496330142, 0.042461588978767395, 0.015770280733704567, 4.10813800044707e-06, 0.008367528207600117, 0.06150421127676964, 0.004480129573494196, 0.09543216973543167, 0.21136140823364258, 0.005510418675839901, 0.29657745361328125, 0.0726594552397728, 819.4340209960938, 1027.7301025390625, 0.015476326458156109, 0.02970016933977604, 0.036495599895715714, 1238.669677734375, 234.83010864257812, 0.0009443855960853398, 44.11335754394531, 0.014797595329582691, 0.048345230519771576, 9.701783710625023e-06] FEATURE_LIST = [ "Number of visible points", "Number of points with depth", "Number of points close to observed depth", "Sum of depth error", "Sum of close error", "Sum of freespace error", "Number of points with freespace error", "Sum of occlusion error", "Number of points occluded", "Sum of L2 color error", "Sum of cosine color error", "Sum of L2 color error with close depth", "Sum of cosine color error with close depth", "Percent of model points points visible", "Percent of model points with depth", "Percent of model points close to observed depth", "Percent of model points with depth close to observed depth", "Mean of depth error", "Mean of close error", "Mean of freespace error", "Percent of visible points violating freespace", "Mean of occlusion error", "Percent of visible points occluded", "Mean of L2 color error", "Mean of cosine color error", "Mean of L2 color error with close depth", "Mean of cosine color error with close depth ", ] FEATURE_LIST += [ "RGB edge score", "Depth edge score" ] FEATURE_LIST += [ "Mean of Hue Error", "Mean of Saturation Error", "Mean of Value Error", ] FEATURE_LIST += [ "Number of feature matches that are inliers", "Number of s features matched to m feature closely", "Ratio of s features matched to m feature closely", "Sum of feature distances of inlier features", "Mean of feature distances of inlier features", "Sum of Euclidean distances of inlier features", "Mean of Euclidean distances of inlier features", ] YCBV_TRAIN_SCENE = [ 0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23, 24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,41,42,43,44,45,46,47,60, 61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84, 86 ] YCBV_VALID_SCENE = [40, 85, 87, 88, 89, 90, 91] YCBV_BOPTEST_SCENE = [48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59] OBJECT_DIAMETERES = { "ycbv":{ 1: 0.172063, 2: 0.26957299999999995, 3: 0.198377, 4: 0.12054300000000001, 5: 0.196463, 6: 0.089797, 7: 0.142543, 8: 0.114053, 9: 0.12954, 10: 0.197796, 11: 0.259534, 12: 0.25956599999999996, 13: 0.161922, 14: 0.12498999999999999, 15: 0.22616999999999998, 16: 0.237299, 17: 0.20397300000000002, 18: 0.121365, 19: 0.174746, 20: 0.21709399999999998, 21: 0.10290300000000001, }, "lmo": { 1: 0.10209900000000001, 2: 0.247506, 3: 0.16735499999999998, 4: 0.17249199999999998, 5: 0.201404, 6: 0.154546, 7: 0.124264, 8: 0.261472, 9: 0.108999, 10: 0.164628, 11: 0.17588900000000002, 12: 0.145543, 13: 0.278078, 14: 0.282601, 15: 0.212358, } }
43.175926
798
0.668239
FEATURE_MEAN = [491.3183898925781, 445.4370422363281, 104.46714782714844, -9.33281421661377, -0.3871251940727234, 15.277295112609863, 96.35192108154297, -21.257665634155273, 244.6168975830078, 454.5150146484375, 452.712890625, 93.33969116210938, 96.92170715332031, 0.4305391013622284, 0.39397644996643066, 0.10189277678728104, 0.2605348229408264, -0.016525093466043472, -0.0010204192949458957, 0.029299981892108917, 0.2030143290758133, -0.03813593089580536, 0.5364543795585632, 0.9343518018722534, 0.9338011741638184, 0.8567478060722351, 0.856406033039093, 14.381174087524414, 39.7275505065918, 0.19100581109523773, 0.2816426157951355, 0.29801905155181885, 32.04430389404297, 15.896907806396484, 0.03398795798420906, 6.787647724151611, 0.43156930804252625, 0.22434939444065094, 0.0131981261074543] FEATURE_VAR = [104024.1953125, 84253.234375, 10451.4873046875, 7728.88623046875, 0.6716803908348083, 3666.609619140625, 23751.6484375, 3180.625244140625, 57259.7109375, 140852.34375, 82354.09375, 9427.083984375, 9033.4541015625, 0.009170586243271828, 0.009593164548277855, 0.00744457496330142, 0.042461588978767395, 0.015770280733704567, 4.10813800044707e-06, 0.008367528207600117, 0.06150421127676964, 0.004480129573494196, 0.09543216973543167, 0.21136140823364258, 0.005510418675839901, 0.29657745361328125, 0.0726594552397728, 819.4340209960938, 1027.7301025390625, 0.015476326458156109, 0.02970016933977604, 0.036495599895715714, 1238.669677734375, 234.83010864257812, 0.0009443855960853398, 44.11335754394531, 0.014797595329582691, 0.048345230519771576, 9.701783710625023e-06] FEATURE_LIST = [ "Number of visible points", "Number of points with depth", "Number of points close to observed depth", "Sum of depth error", "Sum of close error", "Sum of freespace error", "Number of points with freespace error", "Sum of occlusion error", "Number of points occluded", "Sum of L2 color error", "Sum of cosine color error", "Sum of L2 color error with close depth", "Sum of cosine color error with close depth", "Percent of model points points visible", "Percent of model points with depth", "Percent of model points close to observed depth", "Percent of model points with depth close to observed depth", "Mean of depth error", "Mean of close error", "Mean of freespace error", "Percent of visible points violating freespace", "Mean of occlusion error", "Percent of visible points occluded", "Mean of L2 color error", "Mean of cosine color error", "Mean of L2 color error with close depth", "Mean of cosine color error with close depth ", ] FEATURE_LIST += [ "RGB edge score", "Depth edge score" ] FEATURE_LIST += [ "Mean of Hue Error", "Mean of Saturation Error", "Mean of Value Error", ] FEATURE_LIST += [ "Number of feature matches that are inliers", "Number of s features matched to m feature closely", "Ratio of s features matched to m feature closely", "Sum of feature distances of inlier features", "Mean of feature distances of inlier features", "Sum of Euclidean distances of inlier features", "Mean of Euclidean distances of inlier features", ] YCBV_TRAIN_SCENE = [ 0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23, 24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,41,42,43,44,45,46,47,60, 61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84, 86 ] YCBV_VALID_SCENE = [40, 85, 87, 88, 89, 90, 91] YCBV_BOPTEST_SCENE = [48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59] OBJECT_DIAMETERES = { "ycbv":{ 1: 0.172063, 2: 0.26957299999999995, 3: 0.198377, 4: 0.12054300000000001, 5: 0.196463, 6: 0.089797, 7: 0.142543, 8: 0.114053, 9: 0.12954, 10: 0.197796, 11: 0.259534, 12: 0.25956599999999996, 13: 0.161922, 14: 0.12498999999999999, 15: 0.22616999999999998, 16: 0.237299, 17: 0.20397300000000002, 18: 0.121365, 19: 0.174746, 20: 0.21709399999999998, 21: 0.10290300000000001, }, "lmo": { 1: 0.10209900000000001, 2: 0.247506, 3: 0.16735499999999998, 4: 0.17249199999999998, 5: 0.201404, 6: 0.154546, 7: 0.124264, 8: 0.261472, 9: 0.108999, 10: 0.164628, 11: 0.17588900000000002, 12: 0.145543, 13: 0.278078, 14: 0.282601, 15: 0.212358, } }
true
true
1c3915f44fe7d8202f20a3318d5e5194a160286a
2,067
py
Python
UiMainWindowLoginByFaceID.py
kyvipro113/FaceID_Realtime_Detect
b4942091ade34b38b761808386991b919d29c1d3
[ "MIT" ]
1
2021-07-01T10:25:14.000Z
2021-07-01T10:25:14.000Z
Ui_MainWindowLoginByFaceID.py
kyvipro113/FaceID_Realtime_Detect
b4942091ade34b38b761808386991b919d29c1d3
[ "MIT" ]
null
null
null
Ui_MainWindowLoginByFaceID.py
kyvipro113/FaceID_Realtime_Detect
b4942091ade34b38b761808386991b919d29c1d3
[ "MIT" ]
null
null
null
# -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'Ui_MainWindowLoginByFaceID.ui' # # Created by: PyQt5 UI code generator 5.15.2 # # WARNING: Any manual changes made to this file will be lost when pyuic5 is # run again. Do not edit this file unless you know what you are doing. from PyQt5 import QtCore, QtGui, QtWidgets class Ui_MainWindowLoginByFaceID(object): def setupUi(self, MainWindowLoginByFaceID): MainWindowLoginByFaceID.setObjectName("MainWindowLoginByFaceID") MainWindowLoginByFaceID.resize(640, 497) self.centralwidget = QtWidgets.QWidget(MainWindowLoginByFaceID) self.centralwidget.setObjectName("centralwidget") self.lbImg = QtWidgets.QLabel(self.centralwidget) self.lbImg.setGeometry(QtCore.QRect(0, 0, 640, 480)) self.lbImg.setText("") self.lbImg.setPixmap(QtGui.QPixmap("Logo/imgNone.png")) self.lbImg.setObjectName("lbImg") MainWindowLoginByFaceID.setCentralWidget(self.centralwidget) self.menubar = QtWidgets.QMenuBar(MainWindowLoginByFaceID) self.menubar.setGeometry(QtCore.QRect(0, 0, 640, 21)) self.menubar.setObjectName("menubar") MainWindowLoginByFaceID.setMenuBar(self.menubar) self.statusbar = QtWidgets.QStatusBar(MainWindowLoginByFaceID) self.statusbar.setObjectName("statusbar") MainWindowLoginByFaceID.setStatusBar(self.statusbar) self.retranslateUi(MainWindowLoginByFaceID) QtCore.QMetaObject.connectSlotsByName(MainWindowLoginByFaceID) def retranslateUi(self, MainWindowLoginByFaceID): _translate = QtCore.QCoreApplication.translate MainWindowLoginByFaceID.setWindowTitle(_translate("MainWindowLoginByFaceID", "Face Recognition version 1.0")) if __name__ == "__main__": import sys app = QtWidgets.QApplication(sys.argv) MainWindowLoginByFaceID = QtWidgets.QMainWindow() ui = Ui_MainWindowLoginByFaceID() ui.setupUi(MainWindowLoginByFaceID) MainWindowLoginByFaceID.show() sys.exit(app.exec_())
41.34
117
0.742622
from PyQt5 import QtCore, QtGui, QtWidgets class Ui_MainWindowLoginByFaceID(object): def setupUi(self, MainWindowLoginByFaceID): MainWindowLoginByFaceID.setObjectName("MainWindowLoginByFaceID") MainWindowLoginByFaceID.resize(640, 497) self.centralwidget = QtWidgets.QWidget(MainWindowLoginByFaceID) self.centralwidget.setObjectName("centralwidget") self.lbImg = QtWidgets.QLabel(self.centralwidget) self.lbImg.setGeometry(QtCore.QRect(0, 0, 640, 480)) self.lbImg.setText("") self.lbImg.setPixmap(QtGui.QPixmap("Logo/imgNone.png")) self.lbImg.setObjectName("lbImg") MainWindowLoginByFaceID.setCentralWidget(self.centralwidget) self.menubar = QtWidgets.QMenuBar(MainWindowLoginByFaceID) self.menubar.setGeometry(QtCore.QRect(0, 0, 640, 21)) self.menubar.setObjectName("menubar") MainWindowLoginByFaceID.setMenuBar(self.menubar) self.statusbar = QtWidgets.QStatusBar(MainWindowLoginByFaceID) self.statusbar.setObjectName("statusbar") MainWindowLoginByFaceID.setStatusBar(self.statusbar) self.retranslateUi(MainWindowLoginByFaceID) QtCore.QMetaObject.connectSlotsByName(MainWindowLoginByFaceID) def retranslateUi(self, MainWindowLoginByFaceID): _translate = QtCore.QCoreApplication.translate MainWindowLoginByFaceID.setWindowTitle(_translate("MainWindowLoginByFaceID", "Face Recognition version 1.0")) if __name__ == "__main__": import sys app = QtWidgets.QApplication(sys.argv) MainWindowLoginByFaceID = QtWidgets.QMainWindow() ui = Ui_MainWindowLoginByFaceID() ui.setupUi(MainWindowLoginByFaceID) MainWindowLoginByFaceID.show() sys.exit(app.exec_())
true
true
1c3916a50958fbd9772e08319d3a2903ea41a9cc
4,057
py
Python
hublib/rappture/test/test_number.py
hzclarksm/hublib
e8f2168d80464b6343b980e30fdd552d1b0c2479
[ "MIT" ]
6
2017-05-23T19:17:29.000Z
2022-02-24T00:36:46.000Z
hublib/rappture/test/test_number.py
hzclarksm/hublib
e8f2168d80464b6343b980e30fdd552d1b0c2479
[ "MIT" ]
1
2019-02-13T13:35:57.000Z
2019-02-13T13:35:57.000Z
hublib/rappture/test/test_number.py
hzclarksm/hublib
e8f2168d80464b6343b980e30fdd552d1b0c2479
[ "MIT" ]
6
2017-09-12T19:51:12.000Z
2021-01-13T23:43:57.000Z
from __future__ import print_function import pytest import os, sys import numpy as np sys.path.insert(0, os.path.abspath('../../..')) import hublib.rappture as rappture from hublib import ureg, Q_ class TestNumber: @classmethod def setup_class(cls): print("cls", cls) cls.io = rappture.RapXML('number.xml') def test_input_list(self): inputs = str(self.io.inputs()) expected = """input.number(temperature)\t"Ambient temperature" input.number(temperature2)\t"Ambient Temperature Celsius" input.number(temperature3)\t"Ambient Temperature Current No Units" input.number(temperature4)\t"Ambient Temperature Unitless" input.number(vsweep)\t"Voltage Sweep +/-" """ assert expected == inputs def test_output_list(self): outputs = str(self.io.outputs()) expected = """output.number(outt)\t"Ambient temperature" output.number(outv)\t"Voltage Sweep +/-" """ assert expected == outputs def test_read_value1(self): val = self.io['input.number(temperature)'].value assert val.m == 300 assert val.u == ureg.kelvin assert '{:~}'.format(val) == '300 K' assert self.io['input.number(temperature)'].rvalue == '300K' def test_read_value2(self): val = self.io['input.number(temperature2)'].value assert np.isclose(val.m, 26.85) assert val.u == ureg.degC assert self.io['input.number(temperature2)'].rvalue == '300K' assert self.io['input.number(temperature2).units'].rvalue == 'C' def test_read_value3(self): val = self.io['input.number(temperature3)'].value assert val.m == 300 assert val.u == ureg.degC assert '{:~}'.format(val) == '300 celsius' assert self.io['input.number(temperature3)'].rvalue == '300' assert self.io['input.number(temperature3).units'].rvalue == 'C' def test_read_value4(self): assert self.io['input.number(temperature4)'].value == 300.0 assert self.io['input.number(temperature4)'].rvalue == '300' def test_write_value1(self): # set without units self.io['input.number(temperature)'] = 270 val = self.io['input.number(temperature)'].value assert val.m == 270 assert val.u == ureg.kelvin def test_write_value1b(self): # set with units self.io['input.number(temperature)'] = "260 K" val = self.io['input.number(temperature)'].value assert val.m == 260 assert val.u == ureg.kelvin def test_write_value1c(self): # Set default and check that current is not affected self.io['input.number(temperature).default'] = "305 K" val = self.io['input.number(temperature).default'].value assert val.m == 305 assert val.u == ureg.kelvin val = self.io['input.number(temperature)'].value assert val.m == 260 assert val.u == ureg.kelvin def test_write_value2(self): # set without units self.io['input.number(temperature2)'] = 270 val = self.io['input.number(temperature2)'].value assert val.m == 270 assert val.u == ureg.degC def test_write_value2b(self): # set without units self.io['input.number(temperature2)'] = "270 K" val = self.io['input.number(temperature2)'].value assert np.allclose(val.m, -3.15) assert val.u == ureg.degC def test_write_value2c(self): # change units self.io['input.number(temperature2).units'] = 'K' val = self.io['input.number(temperature2)'].value assert val.m == 270 assert val.u == ureg.kelvin def test_write_value4(self): # set without units self.io['input.number(temperature4)'] = 270 val = self.io['input.number(temperature4)'].value assert val == 270 def test_write_value4b(self): # set without units self.io['input.number(temperature4)'] = '270' val = self.io['input.number(temperature4)'].value assert val == 270
33.808333
72
0.624846
from __future__ import print_function import pytest import os, sys import numpy as np sys.path.insert(0, os.path.abspath('../../..')) import hublib.rappture as rappture from hublib import ureg, Q_ class TestNumber: @classmethod def setup_class(cls): print("cls", cls) cls.io = rappture.RapXML('number.xml') def test_input_list(self): inputs = str(self.io.inputs()) expected = """input.number(temperature)\t"Ambient temperature" input.number(temperature2)\t"Ambient Temperature Celsius" input.number(temperature3)\t"Ambient Temperature Current No Units" input.number(temperature4)\t"Ambient Temperature Unitless" input.number(vsweep)\t"Voltage Sweep +/-" """ assert expected == inputs def test_output_list(self): outputs = str(self.io.outputs()) expected = """output.number(outt)\t"Ambient temperature" output.number(outv)\t"Voltage Sweep +/-" """ assert expected == outputs def test_read_value1(self): val = self.io['input.number(temperature)'].value assert val.m == 300 assert val.u == ureg.kelvin assert '{:~}'.format(val) == '300 K' assert self.io['input.number(temperature)'].rvalue == '300K' def test_read_value2(self): val = self.io['input.number(temperature2)'].value assert np.isclose(val.m, 26.85) assert val.u == ureg.degC assert self.io['input.number(temperature2)'].rvalue == '300K' assert self.io['input.number(temperature2).units'].rvalue == 'C' def test_read_value3(self): val = self.io['input.number(temperature3)'].value assert val.m == 300 assert val.u == ureg.degC assert '{:~}'.format(val) == '300 celsius' assert self.io['input.number(temperature3)'].rvalue == '300' assert self.io['input.number(temperature3).units'].rvalue == 'C' def test_read_value4(self): assert self.io['input.number(temperature4)'].value == 300.0 assert self.io['input.number(temperature4)'].rvalue == '300' def test_write_value1(self): self.io['input.number(temperature)'] = 270 val = self.io['input.number(temperature)'].value assert val.m == 270 assert val.u == ureg.kelvin def test_write_value1b(self): self.io['input.number(temperature)'] = "260 K" val = self.io['input.number(temperature)'].value assert val.m == 260 assert val.u == ureg.kelvin def test_write_value1c(self): self.io['input.number(temperature).default'] = "305 K" val = self.io['input.number(temperature).default'].value assert val.m == 305 assert val.u == ureg.kelvin val = self.io['input.number(temperature)'].value assert val.m == 260 assert val.u == ureg.kelvin def test_write_value2(self): self.io['input.number(temperature2)'] = 270 val = self.io['input.number(temperature2)'].value assert val.m == 270 assert val.u == ureg.degC def test_write_value2b(self): self.io['input.number(temperature2)'] = "270 K" val = self.io['input.number(temperature2)'].value assert np.allclose(val.m, -3.15) assert val.u == ureg.degC def test_write_value2c(self): self.io['input.number(temperature2).units'] = 'K' val = self.io['input.number(temperature2)'].value assert val.m == 270 assert val.u == ureg.kelvin def test_write_value4(self): self.io['input.number(temperature4)'] = 270 val = self.io['input.number(temperature4)'].value assert val == 270 def test_write_value4b(self): self.io['input.number(temperature4)'] = '270' val = self.io['input.number(temperature4)'].value assert val == 270
true
true
1c3916bec016c984790c755d9995f06946dcc489
2,686
py
Python
Banking-Inference/code.py
Shubham-0212/ga-learner-dsmp-repo
ed2ebf13fb959746be3b97a6ece0a1784ebb0166
[ "MIT" ]
null
null
null
Banking-Inference/code.py
Shubham-0212/ga-learner-dsmp-repo
ed2ebf13fb959746be3b97a6ece0a1784ebb0166
[ "MIT" ]
null
null
null
Banking-Inference/code.py
Shubham-0212/ga-learner-dsmp-repo
ed2ebf13fb959746be3b97a6ece0a1784ebb0166
[ "MIT" ]
null
null
null
# -------------- import pandas as pd import scipy.stats as stats import math import numpy as np import warnings warnings.filterwarnings('ignore') #Sample_Size sample_size=2000 #Z_Critical Score z_critical = stats.norm.ppf(q = 0.95) # path [File location variable] data=pd.read_csv(path) data_sample=data.sample(n=sample_size,random_state=0) sample_mean=data_sample.installment.mean() sample_std=data_sample.installment.std() margin_of_error=z_critical*sample_std/np.sqrt(sample_size) confidence_interval=[] confidence_interval.append(sample_mean-margin_of_error) confidence_interval.append(sample_mean+margin_of_error) true_mean=data.installment.mean() if true_mean>confidence_interval[0] and true_mean<confidence_interval[1]: print('true',true_mean) else: print('false')#Code starts here # -------------- import matplotlib.pyplot as plt import numpy as np #Different sample sizes to take sample_size=np.array([20,50,100]) #Code starts here fig, axes = plt.subplots(3,1, figsize=(20,10)) for i in range(len(sample_size)): m=[] for j in range(1000): m.append(data['installment'].sample(n=sample_size[i]).mean()) mean_series=pd.Series(m) print(mean_series) # -------------- #Importing header files from statsmodels.stats.weightstats import ztest #Code starts here data['int.rate']=data['int.rate'].str.replace('%','').astype(float)/100 print(data['int.rate'].head()) z_statistic, p_value = ztest(data[data['purpose']=='small_business']['int.rate'],value=data['int.rate'].mean(),alternative='larger') print(z_statistic, p_value) if p_value<0.05: print('reject') else: print('accept') # -------------- #Importing header files from statsmodels.stats.weightstats import ztest #Code starts here z_statistic, p_value=ztest(data[data['paid.back.loan']=='No']['installment'],data[data['paid.back.loan']=='Yes']['installment']) print(z_statistic,p_value) if p_value<0.05: print('reject') else: print('accept') # -------------- from scipy.stats import chi2_contingency #Critical value critical_value = stats.chi2.ppf(q = 0.95, # Find the critical value for 95% confidence* df = 6) # Df = number of variable categories(in purpose) - 1 #Code starts here yes=data[data['paid.back.loan']=='Yes']['purpose'].value_counts() #print(yes) no=data[data['paid.back.loan']=='No']['purpose'].value_counts() observed=pd.concat([yes.transpose(),no.transpose()],keys=['Yes','No'],axis=1) print(observed) chi2, p, dof, ex = stats.chi2_contingency(observed) if chi2>critical_value: print('reject') else: print('accept')
26.333333
133
0.686895
import pandas as pd import scipy.stats as stats import math import numpy as np import warnings warnings.filterwarnings('ignore') sample_size=2000 z_critical = stats.norm.ppf(q = 0.95) data=pd.read_csv(path) data_sample=data.sample(n=sample_size,random_state=0) sample_mean=data_sample.installment.mean() sample_std=data_sample.installment.std() margin_of_error=z_critical*sample_std/np.sqrt(sample_size) confidence_interval=[] confidence_interval.append(sample_mean-margin_of_error) confidence_interval.append(sample_mean+margin_of_error) true_mean=data.installment.mean() if true_mean>confidence_interval[0] and true_mean<confidence_interval[1]: print('true',true_mean) else: print('false') import matplotlib.pyplot as plt import numpy as np sample_size=np.array([20,50,100]) fig, axes = plt.subplots(3,1, figsize=(20,10)) for i in range(len(sample_size)): m=[] for j in range(1000): m.append(data['installment'].sample(n=sample_size[i]).mean()) mean_series=pd.Series(m) print(mean_series) from statsmodels.stats.weightstats import ztest data['int.rate']=data['int.rate'].str.replace('%','').astype(float)/100 print(data['int.rate'].head()) z_statistic, p_value = ztest(data[data['purpose']=='small_business']['int.rate'],value=data['int.rate'].mean(),alternative='larger') print(z_statistic, p_value) if p_value<0.05: print('reject') else: print('accept') from statsmodels.stats.weightstats import ztest z_statistic, p_value=ztest(data[data['paid.back.loan']=='No']['installment'],data[data['paid.back.loan']=='Yes']['installment']) print(z_statistic,p_value) if p_value<0.05: print('reject') else: print('accept') from scipy.stats import chi2_contingency critical_value = stats.chi2.ppf(q = 0.95, df = 6) yes=data[data['paid.back.loan']=='Yes']['purpose'].value_counts() no=data[data['paid.back.loan']=='No']['purpose'].value_counts() observed=pd.concat([yes.transpose(),no.transpose()],keys=['Yes','No'],axis=1) print(observed) chi2, p, dof, ex = stats.chi2_contingency(observed) if chi2>critical_value: print('reject') else: print('accept')
true
true
1c3917526a4c1ededdf3dc3e73ebc732d89b14e3
232
py
Python
source/py/cmd/osclient.py
shakfu/pymax
67dca5990581d91ffcedf800e585e87646ab94d4
[ "CC0-1.0" ]
25
2020-08-06T12:38:07.000Z
2022-03-23T17:35:09.000Z
source/py/cmd/osclient.py
shakfu/pymax
67dca5990581d91ffcedf800e585e87646ab94d4
[ "CC0-1.0" ]
7
2021-04-02T02:58:56.000Z
2022-03-31T22:58:19.000Z
source/py/cmd/osclient.py
shakfu/pymax
67dca5990581d91ffcedf800e585e87646ab94d4
[ "CC0-1.0" ]
3
2021-04-04T05:47:07.000Z
2021-06-26T03:30:02.000Z
#!/usr/bin/env python3 from pythonosc import udp_client client = udp_client.SimpleUDPClient('127.0.0.1', 7000) while True: data = input(">>> ") #client.send_message("/py", data) client.send_message("/eval", data)
15.466667
54
0.663793
from pythonosc import udp_client client = udp_client.SimpleUDPClient('127.0.0.1', 7000) while True: data = input(">>> ") client.send_message("/eval", data)
true
true
1c391a12cc5d4d5f2963496063d83640b2a90b80
2,250
py
Python
qa/rpc-tests/forknotify.py
jwflame/nyancoin-client-1
6bc7686edf8bc4b058d504ce0ab40b7cd2a0597b
[ "MIT" ]
21
2021-11-13T17:36:02.000Z
2022-03-02T15:11:57.000Z
qa/rpc-tests/forknotify.py
jwflame/nyancoin-client-1
6bc7686edf8bc4b058d504ce0ab40b7cd2a0597b
[ "MIT" ]
3
2021-07-07T13:55:07.000Z
2021-11-29T21:05:11.000Z
qa/rpc-tests/forknotify.py
BillionaerCoin/BillionaerCoin
0e11b0b1fec56191b4ca93496d1881648498cb84
[ "MIT" ]
3
2021-11-19T23:50:41.000Z
2021-12-06T23:20:26.000Z
#!/usr/bin/env python3 # Copyright (c) 2014-2021 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 -alertnotify # from test_framework.test_framework import BitcoinTestFramework from test_framework.util import * class ForkNotifyTest(BitcoinTestFramework): def __init__(self): super().__init__() self.num_nodes = 2 self.setup_clean_chain = False alert_filename = None # Set by setup_network def setup_network(self): self.nodes = [] self.alert_filename = os.path.join(self.options.tmpdir, "alert.txt") with open(self.alert_filename, 'w', encoding='utf8'): pass # Just open then close to create zero-length file self.nodes.append(start_node(0, self.options.tmpdir, ["-blockversion=2", "-alertnotify=echo %s >> \"" + self.alert_filename + "\""])) # Node1 mines block.version=211 blocks self.nodes.append(start_node(1, self.options.tmpdir, ["-blockversion=211"])) connect_nodes(self.nodes[1], 0) self.is_network_split = False self.sync_all() def run_test(self): # Mine 51 up-version blocks self.nodes[1].generate(51) self.sync_all() # -alertnotify should trigger on the 51'st, # but mine and sync another to give # -alertnotify time to write self.nodes[1].generate(1) self.sync_all() with open(self.alert_filename, 'r', encoding='utf8') as f: alert_text = f.read() if len(alert_text) == 0: raise AssertionError("-alertnotify did not warn of up-version blocks") # Mine more up-version blocks, should not get more alerts: self.nodes[1].generate(1) self.sync_all() self.nodes[1].generate(1) self.sync_all() with open(self.alert_filename, 'r', encoding='utf8') as f: alert_text2 = f.read() if alert_text != alert_text2: raise AssertionError("-alertnotify excessive warning of up-version blocks") if __name__ == '__main__': ForkNotifyTest().main()
33.58209
108
0.628
from test_framework.test_framework import BitcoinTestFramework from test_framework.util import * class ForkNotifyTest(BitcoinTestFramework): def __init__(self): super().__init__() self.num_nodes = 2 self.setup_clean_chain = False alert_filename = None def setup_network(self): self.nodes = [] self.alert_filename = os.path.join(self.options.tmpdir, "alert.txt") with open(self.alert_filename, 'w', encoding='utf8'): pass self.nodes.append(start_node(0, self.options.tmpdir, ["-blockversion=2", "-alertnotify=echo %s >> \"" + self.alert_filename + "\""])) self.nodes.append(start_node(1, self.options.tmpdir, ["-blockversion=211"])) connect_nodes(self.nodes[1], 0) self.is_network_split = False self.sync_all() def run_test(self): self.nodes[1].generate(51) self.sync_all() # but mine and sync another to give # -alertnotify time to write self.nodes[1].generate(1) self.sync_all() with open(self.alert_filename, 'r', encoding='utf8') as f: alert_text = f.read() if len(alert_text) == 0: raise AssertionError("-alertnotify did not warn of up-version blocks") # Mine more up-version blocks, should not get more alerts: self.nodes[1].generate(1) self.sync_all() self.nodes[1].generate(1) self.sync_all() with open(self.alert_filename, 'r', encoding='utf8') as f: alert_text2 = f.read() if alert_text != alert_text2: raise AssertionError("-alertnotify excessive warning of up-version blocks") if __name__ == '__main__': ForkNotifyTest().main()
true
true
1c391b33607695b408094e1bb3752379aca6ea4e
9,199
py
Python
asposecellscloud/models/name.py
aspose-cells-cloud/aspose-cells-cloud-python
0189236d38053dc67f7edc754b5101f17262cee8
[ "MIT" ]
3
2018-05-23T03:16:26.000Z
2020-11-07T11:42:41.000Z
asposecellscloud/models/name.py
aspose-cells-cloud/aspose-cells-cloud-python
0189236d38053dc67f7edc754b5101f17262cee8
[ "MIT" ]
null
null
null
asposecellscloud/models/name.py
aspose-cells-cloud/aspose-cells-cloud-python
0189236d38053dc67f7edc754b5101f17262cee8
[ "MIT" ]
4
2018-08-29T18:45:05.000Z
2021-03-25T07:59:56.000Z
# coding: utf-8 """ Copyright (c) 2021 Aspose.Cells Cloud 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 """ from pprint import pformat from six import iteritems import re class Name(object): """ NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually. """ """ 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 = { 'link': 'Link', 'comment': 'str', 'text': 'str', 'worksheet_index': 'int', 'r1_c1_refers_to': 'str', 'refers_to': 'str', 'is_referred': 'bool', 'is_visible': 'bool' } attribute_map = { 'link': 'link', 'comment': 'Comment', 'text': 'Text', 'worksheet_index': 'WorksheetIndex', 'r1_c1_refers_to': 'R1C1RefersTo', 'refers_to': 'RefersTo', 'is_referred': 'IsReferred', 'is_visible': 'IsVisible' } @staticmethod def get_swagger_types(): return Name.swagger_types @staticmethod def get_attribute_map(): return Name.attribute_map def get_from_container(self, attr): if attr in self.container: return self.container[attr] return None def __init__(self, link=None, comment=None, text=None, worksheet_index=None, r1_c1_refers_to=None, refers_to=None, is_referred=None, is_visible=None, **kw): """ Associative dict for storing property values """ self.container = {} """ Name - a model defined in Swagger """ self.container['link'] = None self.container['comment'] = None self.container['text'] = None self.container['worksheet_index'] = None self.container['r1_c1_refers_to'] = None self.container['refers_to'] = None self.container['is_referred'] = None self.container['is_visible'] = None if link is not None: self.link = link if comment is not None: self.comment = comment if text is not None: self.text = text self.worksheet_index = worksheet_index if r1_c1_refers_to is not None: self.r1_c1_refers_to = r1_c1_refers_to if refers_to is not None: self.refers_to = refers_to self.is_referred = is_referred self.is_visible = is_visible @property def link(self): """ Gets the link of this Name. :return: The link of this Name. :rtype: Link """ return self.container['link'] @link.setter def link(self, link): """ Sets the link of this Name. :param link: The link of this Name. :type: Link """ self.container['link'] = link @property def comment(self): """ Gets the comment of this Name. :return: The comment of this Name. :rtype: str """ return self.container['comment'] @comment.setter def comment(self, comment): """ Sets the comment of this Name. :param comment: The comment of this Name. :type: str """ self.container['comment'] = comment @property def text(self): """ Gets the text of this Name. :return: The text of this Name. :rtype: str """ return self.container['text'] @text.setter def text(self, text): """ Sets the text of this Name. :param text: The text of this Name. :type: str """ self.container['text'] = text @property def worksheet_index(self): """ Gets the worksheet_index of this Name. :return: The worksheet_index of this Name. :rtype: int """ return self.container['worksheet_index'] @worksheet_index.setter def worksheet_index(self, worksheet_index): """ Sets the worksheet_index of this Name. :param worksheet_index: The worksheet_index of this Name. :type: int """ """ if worksheet_index is None: raise ValueError("Invalid value for `worksheet_index`, must not be `None`") """ self.container['worksheet_index'] = worksheet_index @property def r1_c1_refers_to(self): """ Gets the r1_c1_refers_to of this Name. :return: The r1_c1_refers_to of this Name. :rtype: str """ return self.container['r1_c1_refers_to'] @r1_c1_refers_to.setter def r1_c1_refers_to(self, r1_c1_refers_to): """ Sets the r1_c1_refers_to of this Name. :param r1_c1_refers_to: The r1_c1_refers_to of this Name. :type: str """ self.container['r1_c1_refers_to'] = r1_c1_refers_to @property def refers_to(self): """ Gets the refers_to of this Name. :return: The refers_to of this Name. :rtype: str """ return self.container['refers_to'] @refers_to.setter def refers_to(self, refers_to): """ Sets the refers_to of this Name. :param refers_to: The refers_to of this Name. :type: str """ self.container['refers_to'] = refers_to @property def is_referred(self): """ Gets the is_referred of this Name. :return: The is_referred of this Name. :rtype: bool """ return self.container['is_referred'] @is_referred.setter def is_referred(self, is_referred): """ Sets the is_referred of this Name. :param is_referred: The is_referred of this Name. :type: bool """ """ if is_referred is None: raise ValueError("Invalid value for `is_referred`, must not be `None`") """ self.container['is_referred'] = is_referred @property def is_visible(self): """ Gets the is_visible of this Name. :return: The is_visible of this Name. :rtype: bool """ return self.container['is_visible'] @is_visible.setter def is_visible(self, is_visible): """ Sets the is_visible of this Name. :param is_visible: The is_visible of this Name. :type: bool """ """ if is_visible is None: raise ValueError("Invalid value for `is_visible`, must not be `None`") """ self.container['is_visible'] = is_visible def to_dict(self): """ Returns the model properties as a dict """ result = {} for attr, _ in iteritems(self.get_swagger_types()): value = self.get_from_container(attr) if isinstance(value, list): result[attr] = list(map( lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value )) elif hasattr(value, "to_dict"): result[attr] = value.to_dict() elif isinstance(value, dict): result[attr] = dict(map( lambda item: (item[0], item[1].to_dict()) if hasattr(item[1], "to_dict") else item, value.items() )) else: result[attr] = value return result def to_str(self): """ Returns the string representation of the model """ return pformat(self.to_dict()) def __repr__(self): """ For `print` and `pprint` """ return self.to_str() def __eq__(self, other): """ Returns true if both objects are equal """ if not isinstance(other, Name): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """ Returns true if both objects are not equal """ return not self == other
26.819242
160
0.576584
from pprint import pformat from six import iteritems import re class Name(object): swagger_types = { 'link': 'Link', 'comment': 'str', 'text': 'str', 'worksheet_index': 'int', 'r1_c1_refers_to': 'str', 'refers_to': 'str', 'is_referred': 'bool', 'is_visible': 'bool' } attribute_map = { 'link': 'link', 'comment': 'Comment', 'text': 'Text', 'worksheet_index': 'WorksheetIndex', 'r1_c1_refers_to': 'R1C1RefersTo', 'refers_to': 'RefersTo', 'is_referred': 'IsReferred', 'is_visible': 'IsVisible' } @staticmethod def get_swagger_types(): return Name.swagger_types @staticmethod def get_attribute_map(): return Name.attribute_map def get_from_container(self, attr): if attr in self.container: return self.container[attr] return None def __init__(self, link=None, comment=None, text=None, worksheet_index=None, r1_c1_refers_to=None, refers_to=None, is_referred=None, is_visible=None, **kw): self.container = {} self.container['link'] = None self.container['comment'] = None self.container['text'] = None self.container['worksheet_index'] = None self.container['r1_c1_refers_to'] = None self.container['refers_to'] = None self.container['is_referred'] = None self.container['is_visible'] = None if link is not None: self.link = link if comment is not None: self.comment = comment if text is not None: self.text = text self.worksheet_index = worksheet_index if r1_c1_refers_to is not None: self.r1_c1_refers_to = r1_c1_refers_to if refers_to is not None: self.refers_to = refers_to self.is_referred = is_referred self.is_visible = is_visible @property def link(self): return self.container['link'] @link.setter def link(self, link): self.container['link'] = link @property def comment(self): return self.container['comment'] @comment.setter def comment(self, comment): self.container['comment'] = comment @property def text(self): return self.container['text'] @text.setter def text(self, text): self.container['text'] = text @property def worksheet_index(self): return self.container['worksheet_index'] @worksheet_index.setter def worksheet_index(self, worksheet_index): self.container['worksheet_index'] = worksheet_index @property def r1_c1_refers_to(self): return self.container['r1_c1_refers_to'] @r1_c1_refers_to.setter def r1_c1_refers_to(self, r1_c1_refers_to): self.container['r1_c1_refers_to'] = r1_c1_refers_to @property def refers_to(self): return self.container['refers_to'] @refers_to.setter def refers_to(self, refers_to): self.container['refers_to'] = refers_to @property def is_referred(self): return self.container['is_referred'] @is_referred.setter def is_referred(self, is_referred): self.container['is_referred'] = is_referred @property def is_visible(self): return self.container['is_visible'] @is_visible.setter def is_visible(self, is_visible): self.container['is_visible'] = is_visible def to_dict(self): result = {} for attr, _ in iteritems(self.get_swagger_types()): value = self.get_from_container(attr) if isinstance(value, list): result[attr] = list(map( lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value )) elif hasattr(value, "to_dict"): result[attr] = value.to_dict() elif isinstance(value, dict): result[attr] = dict(map( lambda item: (item[0], item[1].to_dict()) if hasattr(item[1], "to_dict") else item, value.items() )) else: result[attr] = value return result def to_str(self): return pformat(self.to_dict()) def __repr__(self): return self.to_str() def __eq__(self, other): if not isinstance(other, Name): return False return self.__dict__ == other.__dict__ def __ne__(self, other): return not self == other
true
true
1c391b51a86d75659c38a1a5c1fac94f650f2f1e
463
py
Python
accounts/migrations/0033_auto_20210130_1852.py
noelsj007/ecommerceweb
e00edfe9110d2cc54deebd97043e0aa152c8afd4
[ "Unlicense" ]
null
null
null
accounts/migrations/0033_auto_20210130_1852.py
noelsj007/ecommerceweb
e00edfe9110d2cc54deebd97043e0aa152c8afd4
[ "Unlicense" ]
null
null
null
accounts/migrations/0033_auto_20210130_1852.py
noelsj007/ecommerceweb
e00edfe9110d2cc54deebd97043e0aa152c8afd4
[ "Unlicense" ]
null
null
null
# Generated by Django 3.1.5 on 2021-01-30 13:22 import datetime from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('accounts', '0032_auto_20210130_1852'), ] operations = [ migrations.AlterField( model_name='order', name='order_ordered_date', field=models.DateTimeField(default=datetime.datetime(2021, 1, 30, 18, 52, 22, 193660)), ), ]
23.15
99
0.62851
import datetime from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('accounts', '0032_auto_20210130_1852'), ] operations = [ migrations.AlterField( model_name='order', name='order_ordered_date', field=models.DateTimeField(default=datetime.datetime(2021, 1, 30, 18, 52, 22, 193660)), ), ]
true
true
1c391b838cbaebe0ca5300f1f7adc660e5fbd8a6
5,058
py
Python
earth/weather/observations.py
justquick/python-earth
ced0d1fff7c2de77df5b51ea490137b0d84d1d96
[ "MIT" ]
2
2017-12-18T13:12:48.000Z
2020-01-21T04:18:03.000Z
earth/weather/observations.py
justquick/python-earth
ced0d1fff7c2de77df5b51ea490137b0d84d1d96
[ "MIT" ]
null
null
null
earth/weather/observations.py
justquick/python-earth
ced0d1fff7c2de77df5b51ea490137b0d84d1d96
[ "MIT" ]
null
null
null
import os,sys import zipfile from xml.parsers.expat import ParserCreate from datetime import datetime from urllib import urlretrieve from earth.core.config import conf from earth.geo import Location URL = 'http://www.weather.gov/data/current_obs/all_xml.zip' URI = os.path.join(conf.data_root, 'observations', 'all_xml.zip') conf.mkdirs('observations') def fetch(): urlretrieve(URL,URI) def parse(): for station in get_weather_observations(): station = Station(station) conf.dump('observations',dict(station),station.id) yield station def cron(): fetch() [x for x in parse()] def get_weather_observations(): vs = {'tagdata':{},'tag':None,'data':[]} def start(tag, attrs): if not tag == 'image': vs['tag'] = tag.lower() vs['tagdata'][vs['tag']] = None def dodata(text): text = text.strip() if vs['tag'] and text: if text in ('None','NA') or not text: del vs['tagdata'][vs['tag']] else: try: vs['tagdata'][vs['tag']] = int(text) except ValueError: try: vs['tagdata'][vs['tag']] = float(text) except ValueError: vs['tagdata'][vs['tag']] = str(text) def feed(text): vs['tagdata'],vs['tag'] = {},None if text: parser = ParserCreate() parser.StartElementHandler = start parser.CharacterDataHandler = dodata parser.Parse(text, 1) vs['data'].append(Station(vs['tagdata'])) if not os.path.isfile(URI): fetch() zfile = zipfile.ZipFile(URI,'r') for name in zfile.namelist(): if name.endswith('.xml') and not name.endswith('index.xml'): feed(zfile.read(name).strip()) return vs['data'] class Station(dict): def __init__(self, data): if isinstance(data, basestring) and conf.resource_exists('observations',data): dict.__init__(self, conf.load('observations',data)) else: dict.__init__(self, data) @property def datetime(self): if 'observation_time_rfc822' in self \ and self['observation_time_rfc822']: return datetime.strptime( ' '.join(self['observation_time_rfc822'].split(' ')[:-2]), '%a, %d %b %Y %H:%M:%S' ) elif 'observation_time' in self: return datetime.strptime( '%s %s' % (self['observation_time'], datetime.now().year), 'Last Updated on %b %d, %H:%M %p %Z %Y' ) @property def icon(self): return '%s%s' % ( self.get('icon_url_base',''), self.get('icon_url_name','') ) @property def point(self): return self.get('latitude',None),self.get('longitude',None) @property def location(self): if 'location' in self and self['location']: if self['location'].find(' - ')>-1: return self['location'].split(' - ')[1] return self['location'] elif 'station_name' in self and self['station_name']: return self['station_name'] @property def geo(self): if self.point: return Location(*self.point,**{'live':True}) if self.location: return Location(self.location,**{'live':True}) @property def id(self): return self.get('station_id',None) def __repr__(self): return '<Station %s>'%self.id def stations(force_parse=False): files = [] if os.path.isdir(os.path.join(conf.data_root, 'observations')): files = [os.path.splitext(file)[0] for file in \ os.listdir(os.path.join(conf.data_root, 'observations')) \ if file.endswith('.obj')] if not files or force_parse: for station in parse(): yield station else: for file in files: yield Station(conf.load('observations',file)) def location2station(location): """ Translate full location into Station tuple by closest match Locations can be in any Google friendly form like "State St, Troy, NY", "2nd st & State St, Troy, NY" & "7 State St, Troy, NY" """ point = Location(location).point best,result = 99999999,None for station in stations(): tpoint = station.point distance = ((tpoint[0]-point[0])**2 + (tpoint[1]-point[1])**2)**.5 if distance < best: best,result = distance,station return result def test(unit): for station in stations(True): unit.assertNotEqual(station.icon, '') unit.assertNotEqual(station.point, (None,None)) unit.assertNotEqual(dict(station), {})
32.216561
87
0.536576
import os,sys import zipfile from xml.parsers.expat import ParserCreate from datetime import datetime from urllib import urlretrieve from earth.core.config import conf from earth.geo import Location URL = 'http://www.weather.gov/data/current_obs/all_xml.zip' URI = os.path.join(conf.data_root, 'observations', 'all_xml.zip') conf.mkdirs('observations') def fetch(): urlretrieve(URL,URI) def parse(): for station in get_weather_observations(): station = Station(station) conf.dump('observations',dict(station),station.id) yield station def cron(): fetch() [x for x in parse()] def get_weather_observations(): vs = {'tagdata':{},'tag':None,'data':[]} def start(tag, attrs): if not tag == 'image': vs['tag'] = tag.lower() vs['tagdata'][vs['tag']] = None def dodata(text): text = text.strip() if vs['tag'] and text: if text in ('None','NA') or not text: del vs['tagdata'][vs['tag']] else: try: vs['tagdata'][vs['tag']] = int(text) except ValueError: try: vs['tagdata'][vs['tag']] = float(text) except ValueError: vs['tagdata'][vs['tag']] = str(text) def feed(text): vs['tagdata'],vs['tag'] = {},None if text: parser = ParserCreate() parser.StartElementHandler = start parser.CharacterDataHandler = dodata parser.Parse(text, 1) vs['data'].append(Station(vs['tagdata'])) if not os.path.isfile(URI): fetch() zfile = zipfile.ZipFile(URI,'r') for name in zfile.namelist(): if name.endswith('.xml') and not name.endswith('index.xml'): feed(zfile.read(name).strip()) return vs['data'] class Station(dict): def __init__(self, data): if isinstance(data, basestring) and conf.resource_exists('observations',data): dict.__init__(self, conf.load('observations',data)) else: dict.__init__(self, data) @property def datetime(self): if 'observation_time_rfc822' in self \ and self['observation_time_rfc822']: return datetime.strptime( ' '.join(self['observation_time_rfc822'].split(' ')[:-2]), '%a, %d %b %Y %H:%M:%S' ) elif 'observation_time' in self: return datetime.strptime( '%s %s' % (self['observation_time'], datetime.now().year), 'Last Updated on %b %d, %H:%M %p %Z %Y' ) @property def icon(self): return '%s%s' % ( self.get('icon_url_base',''), self.get('icon_url_name','') ) @property def point(self): return self.get('latitude',None),self.get('longitude',None) @property def location(self): if 'location' in self and self['location']: if self['location'].find(' - ')>-1: return self['location'].split(' - ')[1] return self['location'] elif 'station_name' in self and self['station_name']: return self['station_name'] @property def geo(self): if self.point: return Location(*self.point,**{'live':True}) if self.location: return Location(self.location,**{'live':True}) @property def id(self): return self.get('station_id',None) def __repr__(self): return '<Station %s>'%self.id def stations(force_parse=False): files = [] if os.path.isdir(os.path.join(conf.data_root, 'observations')): files = [os.path.splitext(file)[0] for file in \ os.listdir(os.path.join(conf.data_root, 'observations')) \ if file.endswith('.obj')] if not files or force_parse: for station in parse(): yield station else: for file in files: yield Station(conf.load('observations',file)) def location2station(location): point = Location(location).point best,result = 99999999,None for station in stations(): tpoint = station.point distance = ((tpoint[0]-point[0])**2 + (tpoint[1]-point[1])**2)**.5 if distance < best: best,result = distance,station return result def test(unit): for station in stations(True): unit.assertNotEqual(station.icon, '') unit.assertNotEqual(station.point, (None,None)) unit.assertNotEqual(dict(station), {})
true
true
1c391bf60123cd731b897495b6cd872ba6fb0af6
36,120
py
Python
mrcnn/utils.py
HuchieWuchie/Mask_RCNN
93f74c5fae72852563b1d3e0e22428d6abf86dc2
[ "MIT" ]
null
null
null
mrcnn/utils.py
HuchieWuchie/Mask_RCNN
93f74c5fae72852563b1d3e0e22428d6abf86dc2
[ "MIT" ]
null
null
null
mrcnn/utils.py
HuchieWuchie/Mask_RCNN
93f74c5fae72852563b1d3e0e22428d6abf86dc2
[ "MIT" ]
null
null
null
""" Mask R-CNN Common utility functions and classes. Copyright (c) 2017 Matterport, Inc. Licensed under the MIT License (see LICENSE for details) Written by Waleed Abdulla """ import sys import os import logging import math import random import numpy as np import tensorflow as tf import scipy import skimage.color import skimage.io import skimage.transform import urllib.request import shutil import warnings from distutils.version import LooseVersion # URL from which to download the latest COCO trained weights COCO_MODEL_URL = "https://github.com/matterport/Mask_RCNN/releases/download/v2.0/mask_rcnn_coco.h5" ############################################################ # Bounding Boxes ############################################################ def extract_bboxes(mask): """Compute bounding boxes from masks. mask: [num_instances, height, width, num_affordances]. Mask pixels are either 1 or 0. Returns: bbox array [num_instances, (y1, x1, y2, x2)]. """ # Albert was here boxes = np.zeros([mask.shape[0], 4], dtype=np.int32) for i in range(mask.shape[0]): m = mask[i, :, :, 1:] #m_viz = np.zeros((m.shape[0], m.shape[1])) # Bounding box. #for i in range(m.shape[-1]): # m_viz[m[:,:, i] == 1] = 255 #cv2.imwrite(os.path.join("mask_gt", str(np.random.randint(10000, size=1)[0]) + ".png"), m_viz) horizontal_indicies = np.where(np.any(m, axis=0))[0] vertical_indicies = np.where(np.any(m, axis=1))[0] if horizontal_indicies.shape[0]: x1, x2 = horizontal_indicies[[0, -1]] y1, y2 = vertical_indicies[[0, -1]] # x2 and y2 should not be part of the box. Increment by 1. x2 += 1 y2 += 1 else: # No mask for this instance. Might happen due to # resizing or cropping. Set bbox to zeros x1, x2, y1, y2 = 0, 0, 0, 0 boxes[i] = np.array([y1, x1, y2, x2]) return boxes.astype(np.int32) def compute_iou(box, boxes, box_area, boxes_area): """Calculates IoU of the given box with the array of the given boxes. box: 1D vector [y1, x1, y2, x2] boxes: [boxes_count, (y1, x1, y2, x2)] box_area: float. the area of 'box' boxes_area: array of length boxes_count. Note: the areas are passed in rather than calculated here for efficiency. Calculate once in the caller to avoid duplicate work. """ # Calculate intersection areas y1 = np.maximum(box[0], boxes[:, 0]) y2 = np.minimum(box[2], boxes[:, 2]) x1 = np.maximum(box[1], boxes[:, 1]) x2 = np.minimum(box[3], boxes[:, 3]) intersection = np.maximum(x2 - x1, 0) * np.maximum(y2 - y1, 0) union = box_area + boxes_area[:] - intersection[:] iou = intersection / union return iou def compute_overlaps(boxes1, boxes2): """Computes IoU overlaps between two sets of boxes. boxes1, boxes2: [N, (y1, x1, y2, x2)]. For better performance, pass the largest set first and the smaller second. """ # Areas of anchors and GT boxes area1 = (boxes1[:, 2] - boxes1[:, 0]) * (boxes1[:, 3] - boxes1[:, 1]) area2 = (boxes2[:, 2] - boxes2[:, 0]) * (boxes2[:, 3] - boxes2[:, 1]) # Compute overlaps to generate matrix [boxes1 count, boxes2 count] # Each cell contains the IoU value. overlaps = np.zeros((boxes1.shape[0], boxes2.shape[0])) for i in range(overlaps.shape[1]): box2 = boxes2[i] overlaps[:, i] = compute_iou(box2, boxes1, area2[i], area1) return overlaps def compute_overlaps_masks(masks1, masks2): """Computes IoU overlaps between two sets of masks. masks1, masks2: [Height, Width, instances] """ # If either set of masks is empty return empty result #if masks1.shape[-1] == 0 or masks2.shape[-1] == 0: # return np.zeros((masks1.shape[-1], masks2.shape[-1])) if np.sum(masks1.shape[:,:, 1:]) == 0 or np.sum(masks2.shape[:,:, 1:]) == 0: return np.zeros((masks1.shape[-1], masks2.shape[-1])) # flatten masks and compute their areas masks1 = np.reshape(masks1 > .5, (-1, masks1.shape[-1])).astype(np.float32) masks2 = np.reshape(masks2 > .5, (-1, masks2.shape[-1])).astype(np.float32) area1 = np.sum(masks1, axis=0) area2 = np.sum(masks2, axis=0) # intersections and union intersections = np.dot(masks1.T, masks2) union = area1[:, None] + area2[None, :] - intersections overlaps = intersections / union return overlaps def non_max_suppression(boxes, scores, threshold): """Performs non-maximum suppression and returns indices of kept boxes. boxes: [N, (y1, x1, y2, x2)]. Notice that (y2, x2) lays outside the box. scores: 1-D array of box scores. threshold: Float. IoU threshold to use for filtering. """ assert boxes.shape[0] > 0 if boxes.dtype.kind != "f": boxes = boxes.astype(np.float32) # Compute box areas y1 = boxes[:, 0] x1 = boxes[:, 1] y2 = boxes[:, 2] x2 = boxes[:, 3] area = (y2 - y1) * (x2 - x1) # Get indicies of boxes sorted by scores (highest first) ixs = scores.argsort()[::-1] pick = [] while len(ixs) > 0: # Pick top box and add its index to the list i = ixs[0] pick.append(i) # Compute IoU of the picked box with the rest iou = compute_iou(boxes[i], boxes[ixs[1:]], area[i], area[ixs[1:]]) # Identify boxes with IoU over the threshold. This # returns indices into ixs[1:], so add 1 to get # indices into ixs. remove_ixs = np.where(iou > threshold)[0] + 1 # Remove indices of the picked and overlapped boxes. ixs = np.delete(ixs, remove_ixs) ixs = np.delete(ixs, 0) return np.array(pick, dtype=np.int32) def apply_box_deltas(boxes, deltas): """Applies the given deltas to the given boxes. boxes: [N, (y1, x1, y2, x2)]. Note that (y2, x2) is outside the box. deltas: [N, (dy, dx, log(dh), log(dw))] """ boxes = boxes.astype(np.float32) # Convert to y, x, h, w height = boxes[:, 2] - boxes[:, 0] width = boxes[:, 3] - boxes[:, 1] center_y = boxes[:, 0] + 0.5 * height center_x = boxes[:, 1] + 0.5 * width # Apply deltas center_y += deltas[:, 0] * height center_x += deltas[:, 1] * width height *= np.exp(deltas[:, 2]) width *= np.exp(deltas[:, 3]) # Convert back to y1, x1, y2, x2 y1 = center_y - 0.5 * height x1 = center_x - 0.5 * width y2 = y1 + height x2 = x1 + width return np.stack([y1, x1, y2, x2], axis=1) def box_refinement_graph(box, gt_box): """Compute refinement needed to transform box to gt_box. box and gt_box are [N, (y1, x1, y2, x2)] """ box = tf.cast(box, tf.float32) gt_box = tf.cast(gt_box, tf.float32) height = box[:, 2] - box[:, 0] width = box[:, 3] - box[:, 1] center_y = box[:, 0] + 0.5 * height center_x = box[:, 1] + 0.5 * width gt_height = gt_box[:, 2] - gt_box[:, 0] gt_width = gt_box[:, 3] - gt_box[:, 1] gt_center_y = gt_box[:, 0] + 0.5 * gt_height gt_center_x = gt_box[:, 1] + 0.5 * gt_width dy = (gt_center_y - center_y) / height dx = (gt_center_x - center_x) / width dh = tf.log(gt_height / height) dw = tf.log(gt_width / width) result = tf.stack([dy, dx, dh, dw], axis=1) return result def box_refinement(box, gt_box): """Compute refinement needed to transform box to gt_box. box and gt_box are [N, (y1, x1, y2, x2)]. (y2, x2) is assumed to be outside the box. """ box = box.astype(np.float32) gt_box = gt_box.astype(np.float32) height = box[:, 2] - box[:, 0] width = box[:, 3] - box[:, 1] center_y = box[:, 0] + 0.5 * height center_x = box[:, 1] + 0.5 * width gt_height = gt_box[:, 2] - gt_box[:, 0] gt_width = gt_box[:, 3] - gt_box[:, 1] gt_center_y = gt_box[:, 0] + 0.5 * gt_height gt_center_x = gt_box[:, 1] + 0.5 * gt_width dy = (gt_center_y - center_y) / height dx = (gt_center_x - center_x) / width dh = np.log(gt_height / height) dw = np.log(gt_width / width) return np.stack([dy, dx, dh, dw], axis=1) ############################################################ # Dataset ############################################################ class Dataset(object): """The base class for dataset classes. To use it, create a new class that adds functions specific to the dataset you want to use. For example: class CatsAndDogsDataset(Dataset): def load_cats_and_dogs(self): ... def load_mask(self, image_id): ... def image_reference(self, image_id): ... See COCODataset and ShapesDataset as examples. """ def __init__(self, class_map=None): self._image_ids = [] self.image_info = [] #CHANGE # Background is always the first class #self.class_info = [{"source": "", "id": 0, "name": "BG"}] # outcommented since there should be no background self.class_info = [] self.affordance_info = [] # new self.source_class_ids = {} def add_affordance(self, source, affordance_id, affordance_name): assert "." not in source, "Source name cannot contain a dot" # Does the class exist already? for info in self.affordance_info: if info['source'] == source and info["id"] == affordance_id: # source.class_id combination already available, skip return # Add the class self.affordance_info.append({ "source": source, "id": affordance_id, "name": affordance_name, }) def add_class(self, source, class_id, class_name): assert "." not in source, "Source name cannot contain a dot" # Does the class exist already? for info in self.class_info: if info['source'] == source and info["id"] == class_id: # source.class_id combination already available, skip return # Add the class self.class_info.append({ "source": source, "id": class_id, "name": class_name, }) def add_image(self, source, image_id, path, **kwargs): image_info = { "id": image_id, "source": source, "path": path, } image_info.update(kwargs) self.image_info.append(image_info) def image_reference(self, image_id): """Return a link to the image in its source Website or details about the image that help looking it up or debugging it. Override for your dataset, but pass to this function if you encounter images not in your dataset. """ return "" def prepare(self, class_map=None): """Prepares the Dataset class for use. TODO: class map is not supported yet. When done, it should handle mapping classes from different datasets to the same class ID. """ def clean_name(name): """Returns a shorter version of object names for cleaner display.""" return ",".join(name.split(",")[:1]) # Build (or rebuild) everything else from the info dicts. self.num_classes = len(self.class_info) self.class_ids = np.arange(self.num_classes) self.class_names = [clean_name(c["name"]) for c in self.class_info] self.num_affordances = len(self.affordance_info) self.affordance_ids = np.arange(self.num_affordances) self.affordances_names = [clean_name(c["name"]) for c in self.affordance_info] self.num_images = len(self.image_info) self._image_ids = np.arange(self.num_images) # Mapping from source class and image IDs to internal IDs # ALBERT: Maybe there is something to do here self.class_from_source_map = {"{}.{}".format(info['source'], info['id']): id for info, id in zip(self.class_info, self.class_ids)} self.image_from_source_map = {"{}.{}".format(info['source'], info['id']): id for info, id in zip(self.image_info, self.image_ids)} # Map sources to class_ids they support self.sources = list(set([i['source'] for i in self.class_info])) self.source_class_ids = {} # Loop over datasets for source in self.sources: self.source_class_ids[source] = [] # Find classes that belong to this dataset for i, info in enumerate(self.class_info): # Include BG class in all datasets if i == 0 or source == info['source']: # ALBERT: Maybe there is something to do here self.source_class_ids[source].append(i) def map_source_class_id(self, source_class_id): """Takes a source class ID and returns the int class ID assigned to it. For example: dataset.map_source_class_id("coco.12") -> 23 """ return self.class_from_source_map[source_class_id] def get_source_class_id(self, class_id, source): """Map an internal class ID to the corresponding class ID in the source dataset.""" info = self.class_info[class_id] assert info['source'] == source return info['id'] @property def image_ids(self): return self._image_ids def source_image_link(self, image_id): """Returns the path or URL to the image. Override this to return a URL to the image if it's available online for easy debugging. """ return self.image_info[image_id]["path"] def load_image(self, image_id): """Load the specified image and return a [H,W,3] Numpy array. """ # Load image image = skimage.io.imread(self.image_info[image_id]['path']) # If grayscale. Convert to RGB for consistency. if image.ndim != 3: image = skimage.color.gray2rgb(image) # If has an alpha channel, remove it for consistency if image.shape[-1] == 4: image = image[..., :3] return image def load_mask(self, image_id): """Load instance masks for the given image. Different datasets use different ways to store masks. Override this method to load instance masks and return them in the form of am array of binary masks of shape [height, width, instances]. Returns: masks: A bool array of shape [height, width, instance count] with a binary mask per instance. class_ids: a 1D array of class IDs of the instance masks. """ # Override this function to load a mask from your dataset. # Otherwise, it returns an empty mask. logging.warning("You are using the default load_mask(), maybe you need to define your own one.") mask = np.empty([0, 0, 0]) class_ids = np.empty([0], np.int32) return mask, class_ids def resize_image(image, min_dim=None, max_dim=None, min_scale=None, mode="square"): """Resizes an image keeping the aspect ratio unchanged. min_dim: if provided, resizes the image such that it's smaller dimension == min_dim max_dim: if provided, ensures that the image longest side doesn't exceed this value. min_scale: if provided, ensure that the image is scaled up by at least this percent even if min_dim doesn't require it. mode: Resizing mode. none: No resizing. Return the image unchanged. square: Resize and pad with zeros to get a square image of size [max_dim, max_dim]. pad64: Pads width and height with zeros to make them multiples of 64. If min_dim or min_scale are provided, it scales the image up before padding. max_dim is ignored in this mode. The multiple of 64 is needed to ensure smooth scaling of feature maps up and down the 6 levels of the FPN pyramid (2**6=64). crop: Picks random crops from the image. First, scales the image based on min_dim and min_scale, then picks a random crop of size min_dim x min_dim. Can be used in training only. max_dim is not used in this mode. Returns: image: the resized image window: (y1, x1, y2, x2). If max_dim is provided, padding might be inserted in the returned image. If so, this window is the coordinates of the image part of the full image (excluding the padding). The x2, y2 pixels are not included. scale: The scale factor used to resize the image padding: Padding added to the image [(top, bottom), (left, right), (0, 0)] """ # Keep track of image dtype and return results in the same dtype image_dtype = image.dtype # Default window (y1, x1, y2, x2) and default scale == 1. h, w = image.shape[:2] window = (0, 0, h, w) scale = 1 padding = [(0, 0), (0, 0), (0, 0)] crop = None if mode == "none": return image, window, scale, padding, crop # Scale? if min_dim: # Scale up but not down scale = max(1, min_dim / min(h, w)) if min_scale and scale < min_scale: scale = min_scale # Does it exceed max dim? if max_dim and mode == "square": image_max = max(h, w) if round(image_max * scale) > max_dim: scale = max_dim / image_max # Resize image using bilinear interpolation if scale != 1: image = resize(image, (round(h * scale), round(w * scale)), preserve_range=True) # Need padding or cropping? if mode == "square": # Get new height and width h, w = image.shape[:2] top_pad = (max_dim - h) // 2 bottom_pad = max_dim - h - top_pad left_pad = (max_dim - w) // 2 right_pad = max_dim - w - left_pad padding = [(top_pad, bottom_pad), (left_pad, right_pad), (0, 0)] image = np.pad(image, padding, mode='constant', constant_values=0) window = (top_pad, left_pad, h + top_pad, w + left_pad) elif mode == "pad64": h, w = image.shape[:2] # Both sides must be divisible by 64 assert min_dim % 64 == 0, "Minimum dimension must be a multiple of 64" # Height if h % 64 > 0: max_h = h - (h % 64) + 64 top_pad = (max_h - h) // 2 bottom_pad = max_h - h - top_pad else: top_pad = bottom_pad = 0 # Width if w % 64 > 0: max_w = w - (w % 64) + 64 left_pad = (max_w - w) // 2 right_pad = max_w - w - left_pad else: left_pad = right_pad = 0 padding = [(top_pad, bottom_pad), (left_pad, right_pad), (0, 0)] image = np.pad(image, padding, mode='constant', constant_values=0) window = (top_pad, left_pad, h + top_pad, w + left_pad) elif mode == "crop": # Pick a random crop h, w = image.shape[:2] y = random.randint(0, (h - min_dim)) x = random.randint(0, (w - min_dim)) crop = (y, x, min_dim, min_dim) image = image[y:y + min_dim, x:x + min_dim] window = (0, 0, min_dim, min_dim) else: raise Exception("Mode {} not supported".format(mode)) return image.astype(image_dtype), window, scale, padding, crop def resize_mask(mask, scale, padding, crop=None): """Resizes a mask using the given scale and padding. Typically, you get the scale and padding from resize_image() to ensure both, the image and the mask, are resized consistently. scale: mask scaling factor padding: Padding to add to the mask in the form [(top, bottom), (left, right), (0, 0)] """ # Suppress warning from scipy 0.13.0, the output shape of zoom() is # calculated with round() instead of int() with warnings.catch_warnings(): warnings.simplefilter("ignore") # mask [instance, height, width, affordance] # only scale height and width mask = scipy.ndimage.zoom(mask, zoom=[1, scale, scale, 1], order=0) if crop is not None: y, x, h, w = crop mask = mask[:, y:y + h, x:x + w] else: mask = np.pad(mask, padding, mode='constant', constant_values=0) return mask def minimize_mask(bbox, mask, mini_shape): """Resize masks to a smaller version to reduce memory load. Mini-masks can be resized back to image scale using expand_masks() See inspect_data.ipynb notebook for more details. """ mini_mask = np.zeros((mask.shape[0],) + mini_shape + (mask.shape[-1],), dtype=bool) for i in range(mask.shape[0]): # Pick slice and cast to bool in case load_mask() returned wrong dtype m = mask[i, :, :, :].astype(bool) y1, x1, y2, x2 = bbox[i][:4] m = m[y1:y2, x1:x2] if m.size == 0: raise Exception("Invalid bounding box with area of zero") # Resize with bilinear interpolation m = resize(m, mini_shape) mini_mask[i, :, :, :] = np.around(m).astype(np.bool) return mini_mask def expand_mask(bbox, mini_mask, image_shape): """Resizes mini masks back to image size. Reverses the change of minimize_mask(). See inspect_data.ipynb notebook for more details. """ mask = np.zeros(image_shape[:2] + (mini_mask.shape[-1],), dtype=bool) for i in range(mask.shape[-1]): m = mini_mask[:, :, i] y1, x1, y2, x2 = bbox[i][:4] h = y2 - y1 w = x2 - x1 # Resize with bilinear interpolation m = resize(m, (h, w)) mask[y1:y2, x1:x2, i] = np.around(m).astype(np.bool) return mask # TODO: Build and use this function to reduce code duplication def mold_mask(mask, config): pass def unmold_mask(mask, bbox, image_shape): """Converts a mask generated by the neural network to a format similar to its original shape. original: mask: [height, width] of type float. A small, typically 28x28 mask. new: mask: [height, width, NUM_AFFORDANCES] of type float. A small, typically 28x28 mask. bbox: [y1, x1, y2, x2]. The box to fit the mask in. Returns a binary mask with the same size as the original image. """ #threshold = 0.1 threshold = 0.05 y1, x1, y2, x2 = bbox mask = resize(mask, (y2 - y1, x2 - x1)) print(mask) print(mask.shape) #mask = mask * 255 #mask = np.where(mask >= threshold, 1, 0).astype(np.bool) # Put the mask in the right location. full_mask = np.zeros(image_shape[:2] + (mask.shape[-1],), dtype=np.float) #full_mask = np.zeros(image_shape[:2] + (mask.shape[-1],), dtype=np.bool) full_mask[y1:y2, x1:x2] = mask return full_mask ############################################################ # Anchors ############################################################ def generate_anchors(scales, ratios, shape, feature_stride, anchor_stride): """ scales: 1D array of anchor sizes in pixels. Example: [32, 64, 128] ratios: 1D array of anchor ratios of width/height. Example: [0.5, 1, 2] shape: [height, width] spatial shape of the feature map over which to generate anchors. feature_stride: Stride of the feature map relative to the image in pixels. anchor_stride: Stride of anchors on the feature map. For example, if the value is 2 then generate anchors for every other feature map pixel. """ # Get all combinations of scales and ratios scales, ratios = np.meshgrid(np.array(scales), np.array(ratios)) scales = scales.flatten() ratios = ratios.flatten() # Enumerate heights and widths from scales and ratios heights = scales / np.sqrt(ratios) widths = scales * np.sqrt(ratios) # Enumerate shifts in feature space shifts_y = np.arange(0, shape[0], anchor_stride) * feature_stride shifts_x = np.arange(0, shape[1], anchor_stride) * feature_stride shifts_x, shifts_y = np.meshgrid(shifts_x, shifts_y) # Enumerate combinations of shifts, widths, and heights box_widths, box_centers_x = np.meshgrid(widths, shifts_x) box_heights, box_centers_y = np.meshgrid(heights, shifts_y) # Reshape to get a list of (y, x) and a list of (h, w) box_centers = np.stack( [box_centers_y, box_centers_x], axis=2).reshape([-1, 2]) box_sizes = np.stack([box_heights, box_widths], axis=2).reshape([-1, 2]) # Convert to corner coordinates (y1, x1, y2, x2) boxes = np.concatenate([box_centers - 0.5 * box_sizes, box_centers + 0.5 * box_sizes], axis=1) return boxes def generate_pyramid_anchors(scales, ratios, feature_shapes, feature_strides, anchor_stride): """Generate anchors at different levels of a feature pyramid. Each scale is associated with a level of the pyramid, but each ratio is used in all levels of the pyramid. Returns: anchors: [N, (y1, x1, y2, x2)]. All generated anchors in one array. Sorted with the same order of the given scales. So, anchors of scale[0] come first, then anchors of scale[1], and so on. """ # Anchors # [anchor_count, (y1, x1, y2, x2)] anchors = [] for i in range(len(scales)): anchors.append(generate_anchors(scales[i], ratios, feature_shapes[i], feature_strides[i], anchor_stride)) return np.concatenate(anchors, axis=0) ############################################################ # Miscellaneous ############################################################ def trim_zeros(x): """It's common to have tensors larger than the available data and pad with zeros. This function removes rows that are all zeros. x: [rows, columns]. """ assert len(x.shape) == 2 return x[~np.all(x == 0, axis=1)] def compute_matches(gt_boxes, gt_class_ids, gt_masks, pred_boxes, pred_class_ids, pred_scores, pred_masks, iou_threshold=0.5, score_threshold=0.0): """Finds matches between prediction and ground truth instances. Returns: gt_match: 1-D array. For each GT box it has the index of the matched predicted box. pred_match: 1-D array. For each predicted box, it has the index of the matched ground truth box. overlaps: [pred_boxes, gt_boxes] IoU overlaps. """ # Trim zero padding # TODO: cleaner to do zero unpadding upstream gt_boxes = trim_zeros(gt_boxes) gt_masks = gt_masks[:gt_boxes.shape[0], :, :, :] pred_boxes = trim_zeros(pred_boxes) pred_scores = pred_scores[:pred_boxes.shape[0]] # Sort predictions by score from high to low indices = np.argsort(pred_scores)[::-1] pred_boxes = pred_boxes[indices] pred_class_ids = pred_class_ids[indices] pred_scores = pred_scores[indices] pred_masks = pred_masks[indices] # Compute IoU overlaps [pred_masks, gt_masks] overlaps = compute_overlaps_masks(pred_masks, gt_masks) # Loop through predictions and find matching ground truth boxes match_count = 0 pred_match = -1 * np.ones([pred_boxes.shape[0]]) gt_match = -1 * np.ones([gt_boxes.shape[0]]) for i in range(len(pred_boxes)): # Find best matching ground truth box # 1. Sort matches by score sorted_ixs = np.argsort(overlaps[i])[::-1] # 2. Remove low scores low_score_idx = np.where(overlaps[i, sorted_ixs] < score_threshold)[0] if low_score_idx.size > 0: sorted_ixs = sorted_ixs[:low_score_idx[0]] # 3. Find the match for j in sorted_ixs: # If ground truth box is already matched, go to next one if gt_match[j] > -1: continue # If we reach IoU smaller than the threshold, end the loop iou = overlaps[i, j] if iou < iou_threshold: break # Do we have a match? if pred_class_ids[i] == gt_class_ids[j]: match_count += 1 gt_match[j] = i pred_match[i] = j break return gt_match, pred_match, overlaps def compute_ap(gt_boxes, gt_class_ids, gt_masks, pred_boxes, pred_class_ids, pred_scores, pred_masks, iou_threshold=0.5): """Compute Average Precision at a set IoU threshold (default 0.5). Returns: mAP: Mean Average Precision precisions: List of precisions at different class score thresholds. recalls: List of recall values at different class score thresholds. overlaps: [pred_boxes, gt_boxes] IoU overlaps. """ # Get matches and overlaps gt_match, pred_match, overlaps = compute_matches( gt_boxes, gt_class_ids, gt_masks, pred_boxes, pred_class_ids, pred_scores, pred_masks, iou_threshold) # Compute precision and recall at each prediction box step precisions = np.cumsum(pred_match > -1) / (np.arange(len(pred_match)) + 1) recalls = np.cumsum(pred_match > -1).astype(np.float32) / len(gt_match) # Pad with start and end values to simplify the math precisions = np.concatenate([[0], precisions, [0]]) recalls = np.concatenate([[0], recalls, [1]]) # Ensure precision values decrease but don't increase. This way, the # precision value at each recall threshold is the maximum it can be # for all following recall thresholds, as specified by the VOC paper. for i in range(len(precisions) - 2, -1, -1): precisions[i] = np.maximum(precisions[i], precisions[i + 1]) # Compute mean AP over recall range indices = np.where(recalls[:-1] != recalls[1:])[0] + 1 mAP = np.sum((recalls[indices] - recalls[indices - 1]) * precisions[indices]) return mAP, precisions, recalls, overlaps def compute_ap_range(gt_box, gt_class_id, gt_mask, pred_box, pred_class_id, pred_score, pred_mask, iou_thresholds=None, verbose=1): """Compute AP over a range or IoU thresholds. Default range is 0.5-0.95.""" # Default is 0.5 to 0.95 with increments of 0.05 iou_thresholds = iou_thresholds or np.arange(0.5, 1.0, 0.05) # Compute AP over range of IoU thresholds AP = [] for iou_threshold in iou_thresholds: ap, precisions, recalls, overlaps =\ compute_ap(gt_box, gt_class_id, gt_mask, pred_box, pred_class_id, pred_score, pred_mask, iou_threshold=iou_threshold) if verbose: print("AP @{:.2f}:\t {:.3f}".format(iou_threshold, ap)) AP.append(ap) AP = np.array(AP).mean() if verbose: print("AP @{:.2f}-{:.2f}:\t {:.3f}".format( iou_thresholds[0], iou_thresholds[-1], AP)) return AP def compute_recall(pred_boxes, gt_boxes, iou): """Compute the recall at the given IoU threshold. It's an indication of how many GT boxes were found by the given prediction boxes. pred_boxes: [N, (y1, x1, y2, x2)] in image coordinates gt_boxes: [N, (y1, x1, y2, x2)] in image coordinates """ # Measure overlaps overlaps = compute_overlaps(pred_boxes, gt_boxes) iou_max = np.max(overlaps, axis=1) iou_argmax = np.argmax(overlaps, axis=1) positive_ids = np.where(iou_max >= iou)[0] matched_gt_boxes = iou_argmax[positive_ids] recall = len(set(matched_gt_boxes)) / gt_boxes.shape[0] return recall, positive_ids # ## Batch Slicing # Some custom layers support a batch size of 1 only, and require a lot of work # to support batches greater than 1. This function slices an input tensor # across the batch dimension and feeds batches of size 1. Effectively, # an easy way to support batches > 1 quickly with little code modification. # In the long run, it's more efficient to modify the code to support large # batches and getting rid of this function. Consider this a temporary solution def batch_slice(inputs, graph_fn, batch_size, names=None): """Splits inputs into slices and feeds each slice to a copy of the given computation graph and then combines the results. It allows you to run a graph on a batch of inputs even if the graph is written to support one instance only. inputs: list of tensors. All must have the same first dimension length graph_fn: A function that returns a TF tensor that's part of a graph. batch_size: number of slices to divide the data into. names: If provided, assigns names to the resulting tensors. """ if not isinstance(inputs, list): inputs = [inputs] outputs = [] for i in range(batch_size): inputs_slice = [x[i] for x in inputs] output_slice = graph_fn(*inputs_slice) if not isinstance(output_slice, (tuple, list)): output_slice = [output_slice] outputs.append(output_slice) # Change outputs from a list of slices where each is # a list of outputs to a list of outputs and each has # a list of slices outputs = list(zip(*outputs)) if names is None: names = [None] * len(outputs) result = [tf.stack(o, axis=0, name=n) for o, n in zip(outputs, names)] if len(result) == 1: result = result[0] return result def download_trained_weights(coco_model_path, verbose=1): """Download COCO trained weights from Releases. coco_model_path: local path of COCO trained weights """ if verbose > 0: print("Downloading pretrained model to " + coco_model_path + " ...") with urllib.request.urlopen(COCO_MODEL_URL) as resp, open(coco_model_path, 'wb') as out: shutil.copyfileobj(resp, out) if verbose > 0: print("... done downloading pretrained model!") def norm_boxes(boxes, shape): """Converts boxes from pixel coordinates to normalized coordinates. boxes: [N, (y1, x1, y2, x2)] in pixel coordinates shape: [..., (height, width)] in pixels Note: In pixel coordinates (y2, x2) is outside the box. But in normalized coordinates it's inside the box. Returns: [N, (y1, x1, y2, x2)] in normalized coordinates """ h, w = shape scale = np.array([h - 1, w - 1, h - 1, w - 1]) shift = np.array([0, 0, 1, 1]) return np.divide((boxes - shift), scale).astype(np.float32) def denorm_boxes(boxes, shape): """Converts boxes from normalized coordinates to pixel coordinates. boxes: [N, (y1, x1, y2, x2)] in normalized coordinates shape: [..., (height, width)] in pixels Note: In pixel coordinates (y2, x2) is outside the box. But in normalized coordinates it's inside the box. Returns: [N, (y1, x1, y2, x2)] in pixel coordinates """ h, w = shape scale = np.array([h - 1, w - 1, h - 1, w - 1]) shift = np.array([0, 0, 1, 1]) return np.around(np.multiply(boxes, scale) + shift).astype(np.int32) def resize(image, output_shape, order=1, mode='constant', cval=0, clip=True, preserve_range=False, anti_aliasing=False, anti_aliasing_sigma=None): """A wrapper for Scikit-Image resize(). Scikit-Image generates warnings on every call to resize() if it doesn't receive the right parameters. The right parameters depend on the version of skimage. This solves the problem by using different parameters per version. And it provides a central place to control resizing defaults. """ if LooseVersion(skimage.__version__) >= LooseVersion("0.14"): # New in 0.14: anti_aliasing. Default it to False for backward # compatibility with skimage 0.13. return skimage.transform.resize( image, output_shape, order=order, mode=mode, cval=cval, clip=clip, preserve_range=preserve_range, anti_aliasing=anti_aliasing, anti_aliasing_sigma=anti_aliasing_sigma) else: return skimage.transform.resize( image, output_shape, order=order, mode=mode, cval=cval, clip=clip, preserve_range=preserve_range)
38.101266
117
0.612846
import sys import os import logging import math import random import numpy as np import tensorflow as tf import scipy import skimage.color import skimage.io import skimage.transform import urllib.request import shutil import warnings from distutils.version import LooseVersion COCO_MODEL_URL = "https://github.com/matterport/Mask_RCNN/releases/download/v2.0/mask_rcnn_coco.h5" _y = box[:, 0] + 0.5 * height center_x = box[:, 1] + 0.5 * width gt_height = gt_box[:, 2] - gt_box[:, 0] gt_width = gt_box[:, 3] - gt_box[:, 1] gt_center_y = gt_box[:, 0] + 0.5 * gt_height gt_center_x = gt_box[:, 1] + 0.5 * gt_width dy = (gt_center_y - center_y) / height dx = (gt_center_x - center_x) / width dh = tf.log(gt_height / height) dw = tf.log(gt_width / width) result = tf.stack([dy, dx, dh, dw], axis=1) return result def box_refinement(box, gt_box): box = box.astype(np.float32) gt_box = gt_box.astype(np.float32) height = box[:, 2] - box[:, 0] width = box[:, 3] - box[:, 1] center_y = box[:, 0] + 0.5 * height center_x = box[:, 1] + 0.5 * width gt_height = gt_box[:, 2] - gt_box[:, 0] gt_width = gt_box[:, 3] - gt_box[:, 1] gt_center_y = gt_box[:, 0] + 0.5 * gt_height gt_center_x = gt_box[:, 1] + 0.5 * gt_width dy = (gt_center_y - center_y) / height dx = (gt_center_x - center_x) / width dh = np.log(gt_height / height) dw = np.log(gt_width / width) return np.stack([dy, dx, dh, dw], axis=1) return image def load_mask(self, image_id): logging.warning("You are using the default load_mask(), maybe you need to define your own one.") mask = np.empty([0, 0, 0]) class_ids = np.empty([0], np.int32) return mask, class_ids def resize_image(image, min_dim=None, max_dim=None, min_scale=None, mode="square"): image_dtype = image.dtype h, w = image.shape[:2] window = (0, 0, h, w) scale = 1 padding = [(0, 0), (0, 0), (0, 0)] crop = None if mode == "none": return image, window, scale, padding, crop if min_dim: scale = max(1, min_dim / min(h, w)) if min_scale and scale < min_scale: scale = min_scale if max_dim and mode == "square": image_max = max(h, w) if round(image_max * scale) > max_dim: scale = max_dim / image_max if scale != 1: image = resize(image, (round(h * scale), round(w * scale)), preserve_range=True) if mode == "square": h, w = image.shape[:2] top_pad = (max_dim - h) // 2 bottom_pad = max_dim - h - top_pad left_pad = (max_dim - w) // 2 right_pad = max_dim - w - left_pad padding = [(top_pad, bottom_pad), (left_pad, right_pad), (0, 0)] image = np.pad(image, padding, mode='constant', constant_values=0) window = (top_pad, left_pad, h + top_pad, w + left_pad) elif mode == "pad64": h, w = image.shape[:2] assert min_dim % 64 == 0, "Minimum dimension must be a multiple of 64" if h % 64 > 0: max_h = h - (h % 64) + 64 top_pad = (max_h - h) // 2 bottom_pad = max_h - h - top_pad else: top_pad = bottom_pad = 0 if w % 64 > 0: max_w = w - (w % 64) + 64 left_pad = (max_w - w) // 2 right_pad = max_w - w - left_pad else: left_pad = right_pad = 0 padding = [(top_pad, bottom_pad), (left_pad, right_pad), (0, 0)] image = np.pad(image, padding, mode='constant', constant_values=0) window = (top_pad, left_pad, h + top_pad, w + left_pad) elif mode == "crop": h, w = image.shape[:2] y = random.randint(0, (h - min_dim)) x = random.randint(0, (w - min_dim)) crop = (y, x, min_dim, min_dim) image = image[y:y + min_dim, x:x + min_dim] window = (0, 0, min_dim, min_dim) else: raise Exception("Mode {} not supported".format(mode)) return image.astype(image_dtype), window, scale, padding, crop def resize_mask(mask, scale, padding, crop=None): with warnings.catch_warnings(): warnings.simplefilter("ignore") mask = scipy.ndimage.zoom(mask, zoom=[1, scale, scale, 1], order=0) if crop is not None: y, x, h, w = crop mask = mask[:, y:y + h, x:x + w] else: mask = np.pad(mask, padding, mode='constant', constant_values=0) return mask def minimize_mask(bbox, mask, mini_shape): mini_mask = np.zeros((mask.shape[0],) + mini_shape + (mask.shape[-1],), dtype=bool) for i in range(mask.shape[0]): m = mask[i, :, :, :].astype(bool) y1, x1, y2, x2 = bbox[i][:4] m = m[y1:y2, x1:x2] if m.size == 0: raise Exception("Invalid bounding box with area of zero") m = resize(m, mini_shape) mini_mask[i, :, :, :] = np.around(m).astype(np.bool) return mini_mask def expand_mask(bbox, mini_mask, image_shape): mask = np.zeros(image_shape[:2] + (mini_mask.shape[-1],), dtype=bool) for i in range(mask.shape[-1]): m = mini_mask[:, :, i] y1, x1, y2, x2 = bbox[i][:4] h = y2 - y1 w = x2 - x1 m = resize(m, (h, w)) mask[y1:y2, x1:x2, i] = np.around(m).astype(np.bool) return mask def mold_mask(mask, config): pass def unmold_mask(mask, bbox, image_shape): threshold = 0.05 y1, x1, y2, x2 = bbox mask = resize(mask, (y2 - y1, x2 - x1)) print(mask) print(mask.shape) full_mask = np.zeros(image_shape[:2] + (mask.shape[-1],), dtype=np.float) full_mask[y1:y2, x1:x2] = mask return full_mask - 1, w - 1]) shift = np.array([0, 0, 1, 1]) return np.around(np.multiply(boxes, scale) + shift).astype(np.int32) def resize(image, output_shape, order=1, mode='constant', cval=0, clip=True, preserve_range=False, anti_aliasing=False, anti_aliasing_sigma=None): if LooseVersion(skimage.__version__) >= LooseVersion("0.14"): return skimage.transform.resize( image, output_shape, order=order, mode=mode, cval=cval, clip=clip, preserve_range=preserve_range, anti_aliasing=anti_aliasing, anti_aliasing_sigma=anti_aliasing_sigma) else: return skimage.transform.resize( image, output_shape, order=order, mode=mode, cval=cval, clip=clip, preserve_range=preserve_range)
true
true
1c391d1d141f20c8bb8ed6f008fe68893348f80f
3,342
py
Python
alipay/aop/api/domain/ExtendParams.py
snowxmas/alipay-sdk-python-all
96870ced60facd96c5bce18d19371720cbda3317
[ "Apache-2.0" ]
32
2018-05-24T08:40:15.000Z
2019-04-04T20:54:55.000Z
alipay/aop/api/domain/ExtendParams.py
snowxmas/alipay-sdk-python-all
96870ced60facd96c5bce18d19371720cbda3317
[ "Apache-2.0" ]
7
2018-05-24T08:42:59.000Z
2020-09-06T23:18:46.000Z
alipay/aop/api/domain/ExtendParams.py
snowxmas/alipay-sdk-python-all
96870ced60facd96c5bce18d19371720cbda3317
[ "Apache-2.0" ]
13
2018-04-25T11:27:58.000Z
2021-03-15T12:22:21.000Z
#!/usr/bin/env python # -*- coding: utf-8 -*- import json from alipay.aop.api.constant.ParamConstants import * class ExtendParams(object): def __init__(self): self._card_type = None self._hb_fq_num = None self._hb_fq_seller_percent = None self._industry_reflux_info = None self._sys_service_provider_id = None @property def card_type(self): return self._card_type @card_type.setter def card_type(self, value): self._card_type = value @property def hb_fq_num(self): return self._hb_fq_num @hb_fq_num.setter def hb_fq_num(self, value): self._hb_fq_num = value @property def hb_fq_seller_percent(self): return self._hb_fq_seller_percent @hb_fq_seller_percent.setter def hb_fq_seller_percent(self, value): self._hb_fq_seller_percent = value @property def industry_reflux_info(self): return self._industry_reflux_info @industry_reflux_info.setter def industry_reflux_info(self, value): self._industry_reflux_info = value @property def sys_service_provider_id(self): return self._sys_service_provider_id @sys_service_provider_id.setter def sys_service_provider_id(self, value): self._sys_service_provider_id = value def to_alipay_dict(self): params = dict() if self.card_type: if hasattr(self.card_type, 'to_alipay_dict'): params['card_type'] = self.card_type.to_alipay_dict() else: params['card_type'] = self.card_type if self.hb_fq_num: if hasattr(self.hb_fq_num, 'to_alipay_dict'): params['hb_fq_num'] = self.hb_fq_num.to_alipay_dict() else: params['hb_fq_num'] = self.hb_fq_num if self.hb_fq_seller_percent: if hasattr(self.hb_fq_seller_percent, 'to_alipay_dict'): params['hb_fq_seller_percent'] = self.hb_fq_seller_percent.to_alipay_dict() else: params['hb_fq_seller_percent'] = self.hb_fq_seller_percent if self.industry_reflux_info: if hasattr(self.industry_reflux_info, 'to_alipay_dict'): params['industry_reflux_info'] = self.industry_reflux_info.to_alipay_dict() else: params['industry_reflux_info'] = self.industry_reflux_info if self.sys_service_provider_id: if hasattr(self.sys_service_provider_id, 'to_alipay_dict'): params['sys_service_provider_id'] = self.sys_service_provider_id.to_alipay_dict() else: params['sys_service_provider_id'] = self.sys_service_provider_id return params @staticmethod def from_alipay_dict(d): if not d: return None o = ExtendParams() if 'card_type' in d: o.card_type = d['card_type'] if 'hb_fq_num' in d: o.hb_fq_num = d['hb_fq_num'] if 'hb_fq_seller_percent' in d: o.hb_fq_seller_percent = d['hb_fq_seller_percent'] if 'industry_reflux_info' in d: o.industry_reflux_info = d['industry_reflux_info'] if 'sys_service_provider_id' in d: o.sys_service_provider_id = d['sys_service_provider_id'] return o
33.089109
97
0.642729
import json from alipay.aop.api.constant.ParamConstants import * class ExtendParams(object): def __init__(self): self._card_type = None self._hb_fq_num = None self._hb_fq_seller_percent = None self._industry_reflux_info = None self._sys_service_provider_id = None @property def card_type(self): return self._card_type @card_type.setter def card_type(self, value): self._card_type = value @property def hb_fq_num(self): return self._hb_fq_num @hb_fq_num.setter def hb_fq_num(self, value): self._hb_fq_num = value @property def hb_fq_seller_percent(self): return self._hb_fq_seller_percent @hb_fq_seller_percent.setter def hb_fq_seller_percent(self, value): self._hb_fq_seller_percent = value @property def industry_reflux_info(self): return self._industry_reflux_info @industry_reflux_info.setter def industry_reflux_info(self, value): self._industry_reflux_info = value @property def sys_service_provider_id(self): return self._sys_service_provider_id @sys_service_provider_id.setter def sys_service_provider_id(self, value): self._sys_service_provider_id = value def to_alipay_dict(self): params = dict() if self.card_type: if hasattr(self.card_type, 'to_alipay_dict'): params['card_type'] = self.card_type.to_alipay_dict() else: params['card_type'] = self.card_type if self.hb_fq_num: if hasattr(self.hb_fq_num, 'to_alipay_dict'): params['hb_fq_num'] = self.hb_fq_num.to_alipay_dict() else: params['hb_fq_num'] = self.hb_fq_num if self.hb_fq_seller_percent: if hasattr(self.hb_fq_seller_percent, 'to_alipay_dict'): params['hb_fq_seller_percent'] = self.hb_fq_seller_percent.to_alipay_dict() else: params['hb_fq_seller_percent'] = self.hb_fq_seller_percent if self.industry_reflux_info: if hasattr(self.industry_reflux_info, 'to_alipay_dict'): params['industry_reflux_info'] = self.industry_reflux_info.to_alipay_dict() else: params['industry_reflux_info'] = self.industry_reflux_info if self.sys_service_provider_id: if hasattr(self.sys_service_provider_id, 'to_alipay_dict'): params['sys_service_provider_id'] = self.sys_service_provider_id.to_alipay_dict() else: params['sys_service_provider_id'] = self.sys_service_provider_id return params @staticmethod def from_alipay_dict(d): if not d: return None o = ExtendParams() if 'card_type' in d: o.card_type = d['card_type'] if 'hb_fq_num' in d: o.hb_fq_num = d['hb_fq_num'] if 'hb_fq_seller_percent' in d: o.hb_fq_seller_percent = d['hb_fq_seller_percent'] if 'industry_reflux_info' in d: o.industry_reflux_info = d['industry_reflux_info'] if 'sys_service_provider_id' in d: o.sys_service_provider_id = d['sys_service_provider_id'] return o
true
true
1c391d5749ac5da2b4e8d01b62d28ba30433503f
2,530
py
Python
attacks/single_key/z3_solver.py
Marius-Sheppard/RsaCtfTool
c6b8e00d54d56e9bcbf0a324e90ecd9446aef839
[ "Beerware" ]
null
null
null
attacks/single_key/z3_solver.py
Marius-Sheppard/RsaCtfTool
c6b8e00d54d56e9bcbf0a324e90ecd9446aef839
[ "Beerware" ]
null
null
null
attacks/single_key/z3_solver.py
Marius-Sheppard/RsaCtfTool
c6b8e00d54d56e9bcbf0a324e90ecd9446aef839
[ "Beerware" ]
1
2021-12-13T15:58:47.000Z
2021-12-13T15:58:47.000Z
#!/usr/bin/env python3 # -*- coding: utf-8 -*- from z3 import Solver, Int ,set_param from attacks.abstract_attack import AbstractAttack from gmpy2 import isqrt from lib.utils import timeout, TimeoutError from lib.keys_wrapper import PrivateKey set_param('parallel.enable', True) class Attack(AbstractAttack): def __init__(self, timeout=60): super().__init__(timeout) self.speed = AbstractAttack.speed_enum["medium"] def z3_solve(self, n, timeout_amount): s = Solver() s.set("timeout", timeout_amount * 1000) p = Int("x") q = Int("y") i = int(isqrt(n)) if i**2 == n: # check if we are dealing with a perfect square otherwise try to SMT. return i,i s.add(p * q == n, p > 1, q > i, q > p) # In every composite n=pq,there exists a p>sqrt(n) and q<sqrt(n). try: s_check_output = s.check() res = s.model() return res[p], res[q] except: return None, None def attack(self, publickey, cipher=[], progress=True): if not hasattr(publickey, "p"): publickey.p = None if not hasattr(publickey, "q"): publickey.q = None # solve with z3 theorem prover with timeout(self.timeout): try: try: z3_res = self.z3_solve(publickey.n, self.timeout) except: self.logger.warning("[!] z3: Internal Error.") return (None, None) if z3_res and len(z3_res) > 1: p, q = z3_res try: publickey.p = p.as_long() publickey.q = q.as_long() except AttributeError: return (None, None) if publickey.q is not None: priv_key = PrivateKey( int(publickey.p), int(publickey.q), int(publickey.e), int(publickey.n), ) return (priv_key, None) except TimeoutError: return (None, None) return (None, None) def test(self): from lib.keys_wrapper import PublicKey key_data = """-----BEGIN PUBLIC KEY----- MBowDQYJKoZIhvcNAQEBBQADCQAwBgIBDwIBAw== -----END PUBLIC KEY-----""" result = self.attack(PublicKey(key_data), progress=False) return result != (None, None)
32.857143
112
0.514625
from z3 import Solver, Int ,set_param from attacks.abstract_attack import AbstractAttack from gmpy2 import isqrt from lib.utils import timeout, TimeoutError from lib.keys_wrapper import PrivateKey set_param('parallel.enable', True) class Attack(AbstractAttack): def __init__(self, timeout=60): super().__init__(timeout) self.speed = AbstractAttack.speed_enum["medium"] def z3_solve(self, n, timeout_amount): s = Solver() s.set("timeout", timeout_amount * 1000) p = Int("x") q = Int("y") i = int(isqrt(n)) if i**2 == n: return i,i s.add(p * q == n, p > 1, q > i, q > p) try: s_check_output = s.check() res = s.model() return res[p], res[q] except: return None, None def attack(self, publickey, cipher=[], progress=True): if not hasattr(publickey, "p"): publickey.p = None if not hasattr(publickey, "q"): publickey.q = None with timeout(self.timeout): try: try: z3_res = self.z3_solve(publickey.n, self.timeout) except: self.logger.warning("[!] z3: Internal Error.") return (None, None) if z3_res and len(z3_res) > 1: p, q = z3_res try: publickey.p = p.as_long() publickey.q = q.as_long() except AttributeError: return (None, None) if publickey.q is not None: priv_key = PrivateKey( int(publickey.p), int(publickey.q), int(publickey.e), int(publickey.n), ) return (priv_key, None) except TimeoutError: return (None, None) return (None, None) def test(self): from lib.keys_wrapper import PublicKey key_data = """-----BEGIN PUBLIC KEY----- MBowDQYJKoZIhvcNAQEBBQADCQAwBgIBDwIBAw== -----END PUBLIC KEY-----""" result = self.attack(PublicKey(key_data), progress=False) return result != (None, None)
true
true
1c391d5ed05feb1b0e23072fa66197a57a837bf5
2,565
py
Python
quartical/apps/backup.py
JSKenyon/QuartiCal
2113855b080cfecc4a1c77cc9dad346ef3619716
[ "MIT" ]
null
null
null
quartical/apps/backup.py
JSKenyon/QuartiCal
2113855b080cfecc4a1c77cc9dad346ef3619716
[ "MIT" ]
null
null
null
quartical/apps/backup.py
JSKenyon/QuartiCal
2113855b080cfecc4a1c77cc9dad346ef3619716
[ "MIT" ]
1
2022-03-18T14:30:04.000Z
2022-03-18T14:30:04.000Z
import argparse from daskms import xds_from_ms, xds_to_table from daskms.experimental.zarr import xds_to_zarr, xds_from_zarr from pathlib import Path import time import dask def backup(): parser = argparse.ArgumentParser( description='Backup any Measurement Set column to zarr. Backups will ' 'be labelled automatically using the current datetime, ' 'the Measurement Set name and the column name.' ) parser.add_argument( 'ms_path', type=Path, help='Path to input measurement set, e.g. path/to/dir/foo.MS.' ) parser.add_argument( 'zarr_dir', type=Path, help='Path to desired backup location. Note that this only allows ' 'the user to specify a directory and not the name of the backup ' 'zarr that will be created, e.g. path/to/dir.' ) parser.add_argument('column', type=str, help='Name of column to be backed up.') args = parser.parse_args() ms_path = args.ms_path.resolve() zarr_dir = args.zarr_dir.resolve() ms_name = ms_path.name timestamp = time.strftime("%Y%m%d-%H%M%S") data_xds_list = xds_from_ms( ms_path, columns=args.column, index_cols=("TIME",), group_cols=("DATA_DESC_ID",)) bkp_xds_list = xds_to_zarr( data_xds_list, f"{zarr_dir}::{timestamp}-{ms_name}-{args.column}.bkp.qc", ) dask.compute(bkp_xds_list) def restore(): parser = argparse.ArgumentParser( description='Restore a zarr column backup to a Measurement Set.' ) parser.add_argument( 'zarr_path', type=Path, help='Path to backup zarr column e.g. ' 'path/to/dir/20211201-154457-foo.MS-FLAG.bkp.qc.' ) parser.add_argument( 'ms_path', type=Path, help='Path to measurement set, e.g. path/to/dir/foo.MS.' ) parser.add_argument( 'column', type=str, help='Name of column to populate using the backup. Note that this ' 'does not have to be the same column as was used to create the ' 'backup.' ) args = parser.parse_args() zarr_path = args.zarr_path.resolve() ms_path = args.ms_path.resolve() zarr_xds_list = xds_from_zarr( f"{zarr_path.parent}::{zarr_path.name}", ) restored_xds_list = xds_to_table( zarr_xds_list, str(ms_path), columns=(args.column,) ) dask.compute(restored_xds_list)
27
78
0.607797
import argparse from daskms import xds_from_ms, xds_to_table from daskms.experimental.zarr import xds_to_zarr, xds_from_zarr from pathlib import Path import time import dask def backup(): parser = argparse.ArgumentParser( description='Backup any Measurement Set column to zarr. Backups will ' 'be labelled automatically using the current datetime, ' 'the Measurement Set name and the column name.' ) parser.add_argument( 'ms_path', type=Path, help='Path to input measurement set, e.g. path/to/dir/foo.MS.' ) parser.add_argument( 'zarr_dir', type=Path, help='Path to desired backup location. Note that this only allows ' 'the user to specify a directory and not the name of the backup ' 'zarr that will be created, e.g. path/to/dir.' ) parser.add_argument('column', type=str, help='Name of column to be backed up.') args = parser.parse_args() ms_path = args.ms_path.resolve() zarr_dir = args.zarr_dir.resolve() ms_name = ms_path.name timestamp = time.strftime("%Y%m%d-%H%M%S") data_xds_list = xds_from_ms( ms_path, columns=args.column, index_cols=("TIME",), group_cols=("DATA_DESC_ID",)) bkp_xds_list = xds_to_zarr( data_xds_list, f"{zarr_dir}::{timestamp}-{ms_name}-{args.column}.bkp.qc", ) dask.compute(bkp_xds_list) def restore(): parser = argparse.ArgumentParser( description='Restore a zarr column backup to a Measurement Set.' ) parser.add_argument( 'zarr_path', type=Path, help='Path to backup zarr column e.g. ' 'path/to/dir/20211201-154457-foo.MS-FLAG.bkp.qc.' ) parser.add_argument( 'ms_path', type=Path, help='Path to measurement set, e.g. path/to/dir/foo.MS.' ) parser.add_argument( 'column', type=str, help='Name of column to populate using the backup. Note that this ' 'does not have to be the same column as was used to create the ' 'backup.' ) args = parser.parse_args() zarr_path = args.zarr_path.resolve() ms_path = args.ms_path.resolve() zarr_xds_list = xds_from_zarr( f"{zarr_path.parent}::{zarr_path.name}", ) restored_xds_list = xds_to_table( zarr_xds_list, str(ms_path), columns=(args.column,) ) dask.compute(restored_xds_list)
true
true
1c391df30f14ef0733bb52c2cdf6a72596913d64
3,649
py
Python
esm/pretrained.py
konstin/esm
a39894c079ce314e1c0aaa607e8ae498111910a0
[ "MIT" ]
null
null
null
esm/pretrained.py
konstin/esm
a39894c079ce314e1c0aaa607e8ae498111910a0
[ "MIT" ]
null
null
null
esm/pretrained.py
konstin/esm
a39894c079ce314e1c0aaa607e8ae498111910a0
[ "MIT" ]
null
null
null
# Copyright (c) Facebook, Inc. and its affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. import esm import torch from argparse import Namespace from .constants import proteinseq_toks def load_model_and_alphabet(model_name): if model_name.endswith(".pt"): # treat as filepath return load_model_and_alphabet_local(model_name) else: return load_model_and_alphabet_hub(model_name) def load_model_and_alphabet_hub(model_name): alphabet = esm.Alphabet.from_dict(proteinseq_toks) url = f"https://dl.fbaipublicfiles.com/fair-esm/models/{model_name}.pt" if torch.cuda.is_available(): model_data = torch.hub.load_state_dict_from_url(url, progress=False) else: model_data = torch.hub.load_state_dict_from_url(url, progress=False, map_location=torch.device('cpu')) # upgrade state dict pra = lambda s: ''.join(s.split('decoder_')[1:] if 'decoder' in s else s) prs = lambda s: ''.join(s.split('decoder.')[1:] if 'decoder' in s else s) model_args = {pra(arg[0]): arg[1] for arg in vars(model_data["args"]).items()} model_state = {prs(arg[0]): arg[1] for arg in model_data["model"].items()} model = esm.ProteinBertModel( Namespace(**model_args), len(alphabet), padding_idx=alphabet.padding_idx ) model.load_state_dict(model_state) return model, alphabet def load_model_and_alphabet_local(model_location): alphabet = esm.Alphabet.from_dict(proteinseq_toks) model_data = torch.load(model_location) # upgrade state dict pra = lambda s: ''.join(s.split('decoder_')[1:] if 'decoder' in s else s) prs = lambda s: ''.join(s.split('decoder.')[1:] if 'decoder' in s else s) model_args = {pra(arg[0]): arg[1] for arg in vars(model_data["args"]).items()} model_state = {prs(arg[0]): arg[1] for arg in model_data["model"].items()} model = esm.ProteinBertModel( Namespace(**model_args), len(alphabet), padding_idx=alphabet.padding_idx ) model.load_state_dict(model_state) return model, alphabet def esm1_t34_670M_UR50S_local(): model_location = '/checkpoint/bioseq_nonsecure/br2020/br4/checkpoint94.pt' model, alphabet = load_model_and_alphabet_local(model_location) return model, alphabet def esm1_t34_670M_UR50S_hub(): return load_model_and_alphabet_hub("esm1_t34_670M_UR50S") def esm1_t34_670M_UR50S(): """ 34 layer transformer model with 670M params, trained on Uniref50 Sparse. Returns a tuple of (ProteinBertModel, Alphabet). """ #return esm1_t34_670M_UR50S_hub() #return esm1_t34_670M_UR50S_local() return load_model_and_alphabet_hub("esm1_t34_670M_UR50S") def esm1_t34_670M_UR50D(): """ 34 layer transformer model with 670M params, trained on Uniref50 Dense. Returns a tuple of (ProteinBertModel, Alphabet). """ return load_model_and_alphabet_hub("esm1_t34_670M_UR50D") def esm1_t34_670M_UR100(): """ 34 layer transformer model with 670M params, trained on Uniref100. Returns a tuple of (ProteinBertModel, Alphabet). """ return load_model_and_alphabet_hub("esm1_t34_670M_UR100") def esm1_t12_85M_UR50S(): """ 12 layer transformer model with 85M params, trained on Uniref50 Sparse. Returns a tuple of (ProteinBertModel, Alphabet). """ return load_model_and_alphabet_hub("esm1_t12_85M_UR50S") def esm1_t6_43M_UR50S(): """ 6 layer transformer model with 43M params, trained on Uniref50 Sparse. Returns a tuple of (ProteinBertModel, Alphabet). """ return load_model_and_alphabet_hub("esm1_t6_43M_UR50S")
36.128713
110
0.725678
import esm import torch from argparse import Namespace from .constants import proteinseq_toks def load_model_and_alphabet(model_name): if model_name.endswith(".pt"): return load_model_and_alphabet_local(model_name) else: return load_model_and_alphabet_hub(model_name) def load_model_and_alphabet_hub(model_name): alphabet = esm.Alphabet.from_dict(proteinseq_toks) url = f"https://dl.fbaipublicfiles.com/fair-esm/models/{model_name}.pt" if torch.cuda.is_available(): model_data = torch.hub.load_state_dict_from_url(url, progress=False) else: model_data = torch.hub.load_state_dict_from_url(url, progress=False, map_location=torch.device('cpu')) pra = lambda s: ''.join(s.split('decoder_')[1:] if 'decoder' in s else s) prs = lambda s: ''.join(s.split('decoder.')[1:] if 'decoder' in s else s) model_args = {pra(arg[0]): arg[1] for arg in vars(model_data["args"]).items()} model_state = {prs(arg[0]): arg[1] for arg in model_data["model"].items()} model = esm.ProteinBertModel( Namespace(**model_args), len(alphabet), padding_idx=alphabet.padding_idx ) model.load_state_dict(model_state) return model, alphabet def load_model_and_alphabet_local(model_location): alphabet = esm.Alphabet.from_dict(proteinseq_toks) model_data = torch.load(model_location) pra = lambda s: ''.join(s.split('decoder_')[1:] if 'decoder' in s else s) prs = lambda s: ''.join(s.split('decoder.')[1:] if 'decoder' in s else s) model_args = {pra(arg[0]): arg[1] for arg in vars(model_data["args"]).items()} model_state = {prs(arg[0]): arg[1] for arg in model_data["model"].items()} model = esm.ProteinBertModel( Namespace(**model_args), len(alphabet), padding_idx=alphabet.padding_idx ) model.load_state_dict(model_state) return model, alphabet def esm1_t34_670M_UR50S_local(): model_location = '/checkpoint/bioseq_nonsecure/br2020/br4/checkpoint94.pt' model, alphabet = load_model_and_alphabet_local(model_location) return model, alphabet def esm1_t34_670M_UR50S_hub(): return load_model_and_alphabet_hub("esm1_t34_670M_UR50S") def esm1_t34_670M_UR50S(): return load_model_and_alphabet_hub("esm1_t34_670M_UR50S") def esm1_t34_670M_UR50D(): return load_model_and_alphabet_hub("esm1_t34_670M_UR50D") def esm1_t34_670M_UR100(): return load_model_and_alphabet_hub("esm1_t34_670M_UR100") def esm1_t12_85M_UR50S(): return load_model_and_alphabet_hub("esm1_t12_85M_UR50S") def esm1_t6_43M_UR50S(): return load_model_and_alphabet_hub("esm1_t6_43M_UR50S")
true
true
1c391e377f29162aac3ee75ece710cd23fd7e65e
799
py
Python
ds2bim2-Adrian/usuariodao.py
adrianpastore/trabds2bim2
72232dfb27cdaf3d8ff99fccabf8612a803d4903
[ "MIT" ]
null
null
null
ds2bim2-Adrian/usuariodao.py
adrianpastore/trabds2bim2
72232dfb27cdaf3d8ff99fccabf8612a803d4903
[ "MIT" ]
null
null
null
ds2bim2-Adrian/usuariodao.py
adrianpastore/trabds2bim2
72232dfb27cdaf3d8ff99fccabf8612a803d4903
[ "MIT" ]
null
null
null
from usuario import Usuario from psycopg2 import connect from dao import DAO class UsuarioDao(DAO): def __init__(self): super().__init__() def buscar(self, usuario): with connect(self._dados_con) as conn: cur = conn.cursor() cur.execute('SELECT * from "usuario" WHERE senha = md5(%s) AND login = %s',[usuario.senha,usuario.login]) linha = cur.fetchone() if(linha == None): return None else: User = Usuario(cod = linha[0], nome = linha[1], login =linha[2], senha = linha[3]) return User conn.commit() cur.close() #dao = UsuarioDao() #usuario = Usuario(cod = 1, login = "perdeCarros", senha="vouDeMoto") #b = dao.buscar(usuario) #print(b)
31.96
117
0.56821
from usuario import Usuario from psycopg2 import connect from dao import DAO class UsuarioDao(DAO): def __init__(self): super().__init__() def buscar(self, usuario): with connect(self._dados_con) as conn: cur = conn.cursor() cur.execute('SELECT * from "usuario" WHERE senha = md5(%s) AND login = %s',[usuario.senha,usuario.login]) linha = cur.fetchone() if(linha == None): return None else: User = Usuario(cod = linha[0], nome = linha[1], login =linha[2], senha = linha[3]) return User conn.commit() cur.close()
true
true
1c391e3c0170ee0db296746981821f8c2c9b4e91
4,200
py
Python
pypureclient/flashblade/FB_2_3/models/session_get_response.py
Flav-STOR-WL/py-pure-client
03b889c997d90380ac5d6380ca5d5432792d3e89
[ "BSD-2-Clause" ]
14
2018-12-07T18:30:27.000Z
2022-02-22T09:12:33.000Z
pypureclient/flashblade/FB_2_3/models/session_get_response.py
Flav-STOR-WL/py-pure-client
03b889c997d90380ac5d6380ca5d5432792d3e89
[ "BSD-2-Clause" ]
28
2019-09-17T21:03:52.000Z
2022-03-29T22:07:35.000Z
pypureclient/flashblade/FB_2_3/models/session_get_response.py
Flav-STOR-WL/py-pure-client
03b889c997d90380ac5d6380ca5d5432792d3e89
[ "BSD-2-Clause" ]
15
2020-06-11T15:50:08.000Z
2022-03-21T09:27:25.000Z
# coding: utf-8 """ FlashBlade REST API A lightweight client for FlashBlade REST API 2.3, developed by Pure Storage, Inc. (http://www.purestorage.com/). OpenAPI spec version: 2.3 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.flashblade.FB_2_3 import models class SessionGetResponse(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 = { 'continuation_token': 'str', 'total_item_count': 'int', 'items': 'list[Session]' } attribute_map = { 'continuation_token': 'continuation_token', 'total_item_count': 'total_item_count', 'items': 'items' } required_args = { } def __init__( self, continuation_token=None, # type: str total_item_count=None, # type: int items=None, # type: List[models.Session] ): """ Keyword args: continuation_token (str): Continuation token that can be provided in the `continuation_token` query param to get the next page of data. If you use the `continuation_token` to page through data you are guaranteed to get all items exactly once regardless of how items are modified. If an item is added or deleted during the pagination then it may or may not be returned. The `continuation_token` is generated if the `limit` is less than the remaining number of items, and the default sort is used (no sort is specified). total_item_count (int): Total number of items after applying `filter` params. items (list[Session]) """ if continuation_token is not None: self.continuation_token = continuation_token if total_item_count is not None: self.total_item_count = total_item_count if items is not None: self.items = items def __setattr__(self, key, value): if key not in self.attribute_map: raise KeyError("Invalid key `{}` for `SessionGetResponse`".format(key)) self.__dict__[key] = value def __getattribute__(self, item): value = object.__getattribute__(self, item) if isinstance(value, Property): return None 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(SessionGetResponse, 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, SessionGetResponse): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Returns true if both objects are not equal""" return not self == other
33.870968
530
0.585952
import pprint import re import six import typing from ....properties import Property if typing.TYPE_CHECKING: from pypureclient.flashblade.FB_2_3 import models class SessionGetResponse(object): swagger_types = { 'continuation_token': 'str', 'total_item_count': 'int', 'items': 'list[Session]' } attribute_map = { 'continuation_token': 'continuation_token', 'total_item_count': 'total_item_count', 'items': 'items' } required_args = { } def __init__( self, continuation_token=None, total_item_count=None, items=None, ): if continuation_token is not None: self.continuation_token = continuation_token if total_item_count is not None: self.total_item_count = total_item_count if items is not None: self.items = items def __setattr__(self, key, value): if key not in self.attribute_map: raise KeyError("Invalid key `{}` for `SessionGetResponse`".format(key)) self.__dict__[key] = value def __getattribute__(self, item): value = object.__getattribute__(self, item) if isinstance(value, Property): return None else: return value def to_dict(self): 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(SessionGetResponse, dict): for key, value in self.items(): result[key] = value return result def to_str(self): return pprint.pformat(self.to_dict()) def __repr__(self): return self.to_str() def __eq__(self, other): if not isinstance(other, SessionGetResponse): return False return self.__dict__ == other.__dict__ def __ne__(self, other): return not self == other
true
true
1c391e5facf5849bcd0968b6857debfbf9b22501
9,328
py
Python
bincrafters/build_shared.py
rockdreamer/bincrafters-package-tools
75781ef72e756888dd6f1dc48ae8bb3c97afb5ea
[ "MIT" ]
null
null
null
bincrafters/build_shared.py
rockdreamer/bincrafters-package-tools
75781ef72e756888dd6f1dc48ae8bb3c97afb5ea
[ "MIT" ]
null
null
null
bincrafters/build_shared.py
rockdreamer/bincrafters-package-tools
75781ef72e756888dd6f1dc48ae8bb3c97afb5ea
[ "MIT" ]
null
null
null
import os import re import platform from conans.client import conan_api from cpt.packager import ConanMultiPackager from cpt.tools import split_colon_env from cpt.remotes import RemotesManager # from cpt.ci_manager import * from cpt.printer import Printer from bincrafters.build_paths import BINCRAFTERS_REPO_URL, BINCRAFTERS_LOGIN_USERNAME, BINCRAFTERS_USERNAME, BINCRAFTERS_REPO_NAME printer = Printer() # ci_manager = CIManager(printer=printer) def get_recipe_path(cwd=None): cwd = os.getenv("BPT_CWD", cwd) conanfile = os.getenv("CONAN_CONANFILE", "conanfile.py") if cwd is None: return os.path.abspath(conanfile) else: return os.path.abspath(os.path.join(cwd, conanfile)) def get_bool_from_env(var_name, default="1"): val = os.getenv(var_name, default) return str(val).lower() in ("1", "true", "yes", "y") def get_value_from_recipe(search_string, recipe=None): if recipe is None: recipe = get_recipe_path() with open(recipe, "r") as conanfile: contents = conanfile.read() result = re.search(search_string, contents) return result def inspect_value_from_recipe(attribute, recipe_path): cwd = os.getcwd() result = None try: dir_name = os.path.dirname(recipe_path) conanfile_name = os.path.basename(recipe_path) if dir_name == "": dir_name = "./" os.chdir(dir_name) conan_instance, _, _ = conan_api.Conan.factory() inspect_result = conan_instance.inspect(path=conanfile_name, attributes=[attribute]) result = inspect_result.get(attribute) except: pass os.chdir(cwd) return result def get_name_from_recipe(recipe=None): name = inspect_value_from_recipe(attribute="name", recipe_path=recipe) return name or get_value_from_recipe(r'''name\s*=\s*["'](\S*)["']''', recipe=recipe).groups()[0] def get_version_from_recipe(recipe=None): version = inspect_value_from_recipe(attribute="version", recipe_path=recipe) return version or get_value_from_recipe(r'''version\s*=\s*["'](\S*)["']''', recipe=recipe).groups()[0] def is_shared(recipe=None): options = inspect_value_from_recipe(attribute="options", recipe_path=recipe) if options: return "shared" in options match = get_value_from_recipe(r'''options.*=([\s\S]*?)(?=}|$)''', recipe=recipe) if match is None: return False return "shared" in match.groups()[0] def get_repo_name_from_ci(): reponame_a = os.getenv("APPVEYOR_REPO_NAME", "") reponame_t = os.getenv("TRAVIS_REPO_SLUG", "") reponame_c = "%s/%s" % (os.getenv("CIRCLE_PROJECT_USERNAME", ""), os.getenv("CIRCLE_PROJECT_REPONAME", "")) reponame_azp = os.getenv("BUILD_REPOSITORY_NAME", "") reponame_g = os.getenv("GITHUB_REPOSITORY", "") return reponame_a or reponame_t or reponame_c or reponame_azp or reponame_g def get_repo_branch_from_ci(): # TODO: Try one day again to migrate this to CPTs CI Manager # Since CPTs CI Managers varies in logic this break to much of the existing behaviour # in a first attempt (Croydon) # ~~Remove GHA special handling after CPT 0.32.0 is released~~ repobranch_a = os.getenv("APPVEYOR_REPO_BRANCH", "") repobranch_t = os.getenv("TRAVIS_BRANCH", "") repobranch_c = os.getenv("CIRCLE_BRANCH", "") repobranch_azp = os.getenv("BUILD_SOURCEBRANCH", "") if repobranch_azp.startswith("refs/pull/"): repobranch_azp = os.getenv("SYSTEM_PULLREQUEST_TARGETBRANCH", "") def _clean_branch(branch): return branch[11:] if branch.startswith("refs/heads/") else branch repobranch_azp = _clean_branch(repobranch_azp) repobranch_g = _clean_branch(os.getenv("GITHUB_REF", "")) if os.getenv("GITHUB_EVENT_NAME", "") == "pull_request": repobranch_g = os.getenv("GITHUB_BASE_REF", "") return repobranch_a or repobranch_t or repobranch_c or repobranch_azp or repobranch_g def get_ci_vars(): reponame = get_repo_name_from_ci() reponame_split = reponame.split("/") repobranch = get_repo_branch_from_ci() repobranch_split = repobranch.split("/") username, _ = reponame_split if len(reponame_split) == 2 else ["", ""] channel, version = repobranch_split if len(repobranch_split) == 2 else ["", ""] return username, channel, version def get_username_from_ci(): username, _, _ = get_ci_vars() return username def get_channel_from_ci(): _, channel, _ = get_ci_vars() return channel def get_version_from_ci(): _, _, version = get_ci_vars() return version def get_version(recipe=None): env_ver = os.getenv("CONAN_VERSION", None) ci_ver = get_version_from_ci() if env_ver: return env_ver elif ci_ver: return ci_ver else: return get_version_from_recipe(recipe=recipe) def get_conan_vars(recipe=None, kwargs={}): # these fallbacks have to handle empty environment variables too! # this is the case for e.g. external pull request (i.e. no secrets available) # This combined with versioned branches, lead to the error # that the channel is defined but not the username and CPT fails if "CONAN_USERNAME" in os.environ and os.getenv("CONAN_USERNAME") != "": username_fallback = os.getenv("CONAN_USERNAME") else: username_fallback = get_username_from_ci() or BINCRAFTERS_USERNAME if "CONAN_LOGIN_USERNAME" in os.environ and os.getenv("CONAN_LOGIN_USERNAME") != "": login_username_fallback = os.getenv("CONAN_LOGIN_USERNAME") else: login_username_fallback = BINCRAFTERS_LOGIN_USERNAME username = kwargs.get("username", username_fallback) kwargs["channel"] = kwargs.get("channel", os.getenv("CONAN_CHANNEL", get_channel_from_ci())) version = get_version(recipe=recipe) kwargs["login_username"] = kwargs.get("login_username", login_username_fallback) kwargs["username"] = username return username, version, kwargs def get_user_repository(username, repository_name): return "https://api.bintray.com/conan/{0}/{1}".format(username.lower(), repository_name) def get_conan_upload(username): upload = os.getenv("CONAN_UPLOAD") if upload: return upload.split('@') if '@' in upload else upload repository_name = os.getenv("BINTRAY_REPOSITORY", BINCRAFTERS_REPO_NAME) return get_user_repository(username, repository_name) def get_conan_upload_param(username, kwargs): if "upload" not in kwargs: kwargs["upload"] = get_conan_upload(username) return kwargs def get_conan_remotes(username, kwargs): remotes = None if "remotes" not in kwargs: remotes = os.getenv("CONAN_REMOTES") if remotes: remotes = remotes.split(',') for remote in reversed(remotes): if '@' in remote: remote = RemotesManager._get_remote_from_str(remote, var_name=remote) else: # While redundant, this moves upload remote to position 0. remotes = [get_conan_upload(username)] # Add bincrafters repository for other users, e.g. if the package would # require other packages from the bincrafters repo. bincrafters_user = BINCRAFTERS_USERNAME if username != bincrafters_user: remotes.append(get_conan_upload(bincrafters_user)) # Force Bincrafters repo on remotes if BINCRAFTERS_REPO_URL not in remotes: remotes.append(BINCRAFTERS_REPO_URL) kwargs["remotes"] = remotes return kwargs def get_upload_when_stable(kwargs): upload_when_stable = kwargs.get('upload_only_when_stable') if upload_when_stable is None: kwargs['upload_only_when_stable'] = get_bool_from_env("CONAN_UPLOAD_ONLY_WHEN_STABLE") return kwargs def get_os(): return platform.system().replace("Darwin", "Macos") def get_archs(kwargs): if "archs" not in kwargs: archs = os.getenv("CONAN_ARCHS", None) if archs is None: # Per default only build 64-bit artifacts kwargs["archs"] = ["x86_64"] else: kwargs["archs"] = split_colon_env("CONAN_ARCHS") if archs else None return kwargs def get_stable_branch_pattern(kwargs): if "stable_branch_pattern" not in kwargs: kwargs["stable_branch_pattern"] = os.getenv("CONAN_STABLE_BRANCH_PATTERN", "stable/*") return kwargs def get_reference(name, version, kwargs): if "reference" not in kwargs: kwargs["reference"] = "{0}/{1}".format(name, version) return kwargs def get_builder(build_policy=None, cwd=None, **kwargs): recipe = get_recipe_path(cwd) cwd = os.path.dirname(recipe) name = get_name_from_recipe(recipe=recipe) username, version, kwargs = get_conan_vars(recipe=recipe, kwargs=kwargs) kwargs = get_reference(name, version, kwargs) kwargs = get_conan_upload_param(username, kwargs) kwargs = get_conan_remotes(username, kwargs) kwargs = get_upload_when_stable(kwargs) kwargs = get_stable_branch_pattern(kwargs) kwargs = get_archs(kwargs) build_policy = os.getenv("CONAN_BUILD_POLICY", build_policy) builder = ConanMultiPackager( build_policy=build_policy, cwd=cwd, **kwargs) return builder
34.168498
129
0.690609
import os import re import platform from conans.client import conan_api from cpt.packager import ConanMultiPackager from cpt.tools import split_colon_env from cpt.remotes import RemotesManager from cpt.printer import Printer from bincrafters.build_paths import BINCRAFTERS_REPO_URL, BINCRAFTERS_LOGIN_USERNAME, BINCRAFTERS_USERNAME, BINCRAFTERS_REPO_NAME printer = Printer() def get_recipe_path(cwd=None): cwd = os.getenv("BPT_CWD", cwd) conanfile = os.getenv("CONAN_CONANFILE", "conanfile.py") if cwd is None: return os.path.abspath(conanfile) else: return os.path.abspath(os.path.join(cwd, conanfile)) def get_bool_from_env(var_name, default="1"): val = os.getenv(var_name, default) return str(val).lower() in ("1", "true", "yes", "y") def get_value_from_recipe(search_string, recipe=None): if recipe is None: recipe = get_recipe_path() with open(recipe, "r") as conanfile: contents = conanfile.read() result = re.search(search_string, contents) return result def inspect_value_from_recipe(attribute, recipe_path): cwd = os.getcwd() result = None try: dir_name = os.path.dirname(recipe_path) conanfile_name = os.path.basename(recipe_path) if dir_name == "": dir_name = "./" os.chdir(dir_name) conan_instance, _, _ = conan_api.Conan.factory() inspect_result = conan_instance.inspect(path=conanfile_name, attributes=[attribute]) result = inspect_result.get(attribute) except: pass os.chdir(cwd) return result def get_name_from_recipe(recipe=None): name = inspect_value_from_recipe(attribute="name", recipe_path=recipe) return name or get_value_from_recipe(r'''name\s*=\s*["'](\S*)["']''', recipe=recipe).groups()[0] def get_version_from_recipe(recipe=None): version = inspect_value_from_recipe(attribute="version", recipe_path=recipe) return version or get_value_from_recipe(r'''version\s*=\s*["'](\S*)["']''', recipe=recipe).groups()[0] def is_shared(recipe=None): options = inspect_value_from_recipe(attribute="options", recipe_path=recipe) if options: return "shared" in options match = get_value_from_recipe(r'''options.*=([\s\S]*?)(?=}|$)''', recipe=recipe) if match is None: return False return "shared" in match.groups()[0] def get_repo_name_from_ci(): reponame_a = os.getenv("APPVEYOR_REPO_NAME", "") reponame_t = os.getenv("TRAVIS_REPO_SLUG", "") reponame_c = "%s/%s" % (os.getenv("CIRCLE_PROJECT_USERNAME", ""), os.getenv("CIRCLE_PROJECT_REPONAME", "")) reponame_azp = os.getenv("BUILD_REPOSITORY_NAME", "") reponame_g = os.getenv("GITHUB_REPOSITORY", "") return reponame_a or reponame_t or reponame_c or reponame_azp or reponame_g def get_repo_branch_from_ci(): repobranch_a = os.getenv("APPVEYOR_REPO_BRANCH", "") repobranch_t = os.getenv("TRAVIS_BRANCH", "") repobranch_c = os.getenv("CIRCLE_BRANCH", "") repobranch_azp = os.getenv("BUILD_SOURCEBRANCH", "") if repobranch_azp.startswith("refs/pull/"): repobranch_azp = os.getenv("SYSTEM_PULLREQUEST_TARGETBRANCH", "") def _clean_branch(branch): return branch[11:] if branch.startswith("refs/heads/") else branch repobranch_azp = _clean_branch(repobranch_azp) repobranch_g = _clean_branch(os.getenv("GITHUB_REF", "")) if os.getenv("GITHUB_EVENT_NAME", "") == "pull_request": repobranch_g = os.getenv("GITHUB_BASE_REF", "") return repobranch_a or repobranch_t or repobranch_c or repobranch_azp or repobranch_g def get_ci_vars(): reponame = get_repo_name_from_ci() reponame_split = reponame.split("/") repobranch = get_repo_branch_from_ci() repobranch_split = repobranch.split("/") username, _ = reponame_split if len(reponame_split) == 2 else ["", ""] channel, version = repobranch_split if len(repobranch_split) == 2 else ["", ""] return username, channel, version def get_username_from_ci(): username, _, _ = get_ci_vars() return username def get_channel_from_ci(): _, channel, _ = get_ci_vars() return channel def get_version_from_ci(): _, _, version = get_ci_vars() return version def get_version(recipe=None): env_ver = os.getenv("CONAN_VERSION", None) ci_ver = get_version_from_ci() if env_ver: return env_ver elif ci_ver: return ci_ver else: return get_version_from_recipe(recipe=recipe) def get_conan_vars(recipe=None, kwargs={}): if "CONAN_USERNAME" in os.environ and os.getenv("CONAN_USERNAME") != "": username_fallback = os.getenv("CONAN_USERNAME") else: username_fallback = get_username_from_ci() or BINCRAFTERS_USERNAME if "CONAN_LOGIN_USERNAME" in os.environ and os.getenv("CONAN_LOGIN_USERNAME") != "": login_username_fallback = os.getenv("CONAN_LOGIN_USERNAME") else: login_username_fallback = BINCRAFTERS_LOGIN_USERNAME username = kwargs.get("username", username_fallback) kwargs["channel"] = kwargs.get("channel", os.getenv("CONAN_CHANNEL", get_channel_from_ci())) version = get_version(recipe=recipe) kwargs["login_username"] = kwargs.get("login_username", login_username_fallback) kwargs["username"] = username return username, version, kwargs def get_user_repository(username, repository_name): return "https://api.bintray.com/conan/{0}/{1}".format(username.lower(), repository_name) def get_conan_upload(username): upload = os.getenv("CONAN_UPLOAD") if upload: return upload.split('@') if '@' in upload else upload repository_name = os.getenv("BINTRAY_REPOSITORY", BINCRAFTERS_REPO_NAME) return get_user_repository(username, repository_name) def get_conan_upload_param(username, kwargs): if "upload" not in kwargs: kwargs["upload"] = get_conan_upload(username) return kwargs def get_conan_remotes(username, kwargs): remotes = None if "remotes" not in kwargs: remotes = os.getenv("CONAN_REMOTES") if remotes: remotes = remotes.split(',') for remote in reversed(remotes): if '@' in remote: remote = RemotesManager._get_remote_from_str(remote, var_name=remote) else: remotes = [get_conan_upload(username)] bincrafters_user = BINCRAFTERS_USERNAME if username != bincrafters_user: remotes.append(get_conan_upload(bincrafters_user)) if BINCRAFTERS_REPO_URL not in remotes: remotes.append(BINCRAFTERS_REPO_URL) kwargs["remotes"] = remotes return kwargs def get_upload_when_stable(kwargs): upload_when_stable = kwargs.get('upload_only_when_stable') if upload_when_stable is None: kwargs['upload_only_when_stable'] = get_bool_from_env("CONAN_UPLOAD_ONLY_WHEN_STABLE") return kwargs def get_os(): return platform.system().replace("Darwin", "Macos") def get_archs(kwargs): if "archs" not in kwargs: archs = os.getenv("CONAN_ARCHS", None) if archs is None: kwargs["archs"] = ["x86_64"] else: kwargs["archs"] = split_colon_env("CONAN_ARCHS") if archs else None return kwargs def get_stable_branch_pattern(kwargs): if "stable_branch_pattern" not in kwargs: kwargs["stable_branch_pattern"] = os.getenv("CONAN_STABLE_BRANCH_PATTERN", "stable/*") return kwargs def get_reference(name, version, kwargs): if "reference" not in kwargs: kwargs["reference"] = "{0}/{1}".format(name, version) return kwargs def get_builder(build_policy=None, cwd=None, **kwargs): recipe = get_recipe_path(cwd) cwd = os.path.dirname(recipe) name = get_name_from_recipe(recipe=recipe) username, version, kwargs = get_conan_vars(recipe=recipe, kwargs=kwargs) kwargs = get_reference(name, version, kwargs) kwargs = get_conan_upload_param(username, kwargs) kwargs = get_conan_remotes(username, kwargs) kwargs = get_upload_when_stable(kwargs) kwargs = get_stable_branch_pattern(kwargs) kwargs = get_archs(kwargs) build_policy = os.getenv("CONAN_BUILD_POLICY", build_policy) builder = ConanMultiPackager( build_policy=build_policy, cwd=cwd, **kwargs) return builder
true
true
1c391f6ada311b0f09e8e8fff75fe6bb1938ca33
12,918
py
Python
chap11/cuppa4_interp/cuppa4_fe.py
lutzhamel/plipy-code
b4f8c465cddbc0b51d6d6487535d3171ce4f13ee
[ "BSD-2-Clause" ]
1
2021-09-17T15:27:53.000Z
2021-09-17T15:27:53.000Z
chap11/cuppa4/cuppa4_fe.py
lutzhamel/plipy-code
b4f8c465cddbc0b51d6d6487535d3171ce4f13ee
[ "BSD-2-Clause" ]
null
null
null
chap11/cuppa4/cuppa4_fe.py
lutzhamel/plipy-code
b4f8c465cddbc0b51d6d6487535d3171ce4f13ee
[ "BSD-2-Clause" ]
4
2021-09-17T15:27:58.000Z
2021-11-17T01:18:37.000Z
''' Frontend for our Cuppa4 language - builds an AST where each node is of the shape, (TYPE, [arg1, arg2, arg3,...]) here TYPE is a string describing the node type. ''' # helper function to compute the type of a function def formalargs_type(args): output_list = list() for a in args[1]: (FORMALARG, type, id) = a output_list.append(type) return ('LIST', output_list) # stmt_list : ({VOID_TYPE,INTEGER_TYPE,FLOAT_TYPE,STRING_TYPE,ID,GET,PUT,RETURN,WHILE,IF,LCURLY} stmt)* stmt_lookahead = [ 'VOID_TYPE', 'INTEGER_TYPE', 'FLOAT_TYPE', 'STRING_TYPE', 'ID', 'GET', 'PUT', 'RETURN', 'WHILE', 'IF', 'LCURLY', ] def stmt_list(stream): lst = [] while stream.pointer().type in stmt_lookahead: s = stmt(stream) lst.append(s) return ('STMTLIST', lst) # stmt : {VOID_TYPE} VOID_TYPE ID LPAREN ({INTEGER_TYPE,FLOAT_TYPE,STRING_TYPE} formal_args)? RPAREN stmt # | {INTEGER_TYPE,FLOAT_TYPE,STRING_TYPE} data_type ID decl_suffix # | {ID} ID id_suffix # | {GET} GET ID ({SEMI} SEMI)? # | {PUT} PUT exp ({SEMI} SEMI)? # | {RETURN} RETURN ({INTEGER,ID,LPAREN,MINUS,NOT} exp)? ({SEMI} SEMI)? # | {WHILE} WHILE LPAREN exp RPAREN stmt # | {IF} IF LPAREN exp RPAREN stmt ({ELSE} ELSE stmt)? # | {LCURLY} LCURLY stmt_list RCURLY def stmt(stream): if stream.pointer().type in ['VOID_TYPE']: stream.match('VOID_TYPE') ret_type = ('VOID_TYPE',) id_tok = stream.match('ID') stream.match('LPAREN') args = ('NIL',) if stream.pointer().type in ['INTEGER_TYPE','FLOAT_TYPE','STRING_TYPE']: args = formal_args(stream) stream.match('RPAREN') arg_types = formalargs_type(args) body = stmt(stream) return ('FUNDECL', ('ID', id_tok.value), ('FUNCTION_TYPE', ret_type, arg_types), args, body) elif stream.pointer().type in ['INTEGER_TYPE','FLOAT_TYPE','STRING_TYPE']: type = data_type(stream) id_tok = stream.match('ID') e = decl_suffix(stream) if e[0] == 'FUNCTION': (FUNCTION, args, body) = e arg_types = formalargs_type(args) return ('FUNDECL', ('ID', id_tok.value), ('FUNCTION_TYPE', type, arg_types), args, body) else: return ('VARDECL', ('ID', id_tok.value), type, e) elif stream.pointer().type in ['ID']: id_tok = stream.match('ID') e = id_suffix(stream) if e[0] == 'LIST': return ('CALLSTMT', ('ID', id_tok.value), e) else: return ('ASSIGN', ('ID', id_tok.value), e) elif stream.pointer().type in ['GET']: stream.match('GET') id_tk = stream.match('ID') if stream.pointer().type in ['SEMI']: stream.match('SEMI') return ('GET', ('ID', id_tk.value)) elif stream.pointer().type in ['PUT']: stream.match('PUT') e = exp(stream) if stream.pointer().type in ['SEMI']: stream.match('SEMI') return ('PUT', e) elif stream.pointer().type in ['RETURN']: stream.match('RETURN') if stream.pointer().type in exp_lookahead: e = exp(stream) else: e = ('NIL',) if stream.pointer().type in ['SEMI']: stream.match('SEMI') return ('RETURN', e) elif stream.pointer().type in ['WHILE']: stream.match('WHILE') stream.match('LPAREN') e = exp(stream) stream.match('RPAREN') s = stmt(stream) return ('WHILE', e, s) elif stream.pointer().type in ['IF']: stream.match('IF') stream.match('LPAREN') e = exp(stream) stream.match('RPAREN') s1 = stmt(stream) if stream.pointer().type in ['ELSE']: stream.match('ELSE') s2 = stmt(stream) return ('IF', e, s1, s2) else: return ('IF', e, s1, ('NIL',)) elif stream.pointer().type in ['LCURLY']: stream.match('LCURLY') sl = stmt_list(stream) stream.match('RCURLY') return ('BLOCK', sl) else: raise SyntaxError("stmt: syntax error at {}" .format(stream.pointer().value)) # data_type : {INTEGER_TYPE} INTEGER_TYPE # | {FLOAT_TYPE} FLOAT_TYPE # | {STRING_TYPE} STRING_TYPE def data_type(stream): if stream.pointer().type in ['INTEGER_TYPE']: stream.match('INTEGER_TYPE') return ('INTEGER_TYPE',) elif stream.pointer().type in ['FLOAT_TYPE']: stream.match('FLOAT_TYPE') return ('FLOAT_TYPE',) elif stream.pointer().type in ['STRING_TYPE']: stream.match('STRING_TYPE') return ('STRING_TYPE',) else: raise SyntaxError("data_type: syntax error at {}" .format(stream.pointer().value)) # decl_suffix : {LPAREN} LPAREN ({INTEGER_TYPE,FLOAT_TYPE,STRING_TYPE} formal_args)? RPAREN stmt # | {ASSIGN} ASSIGN exp ({SEMI} SEMI)? # | ({SEMI} SEMI)? def decl_suffix(stream): if stream.pointer().type in ['LPAREN']: stream.match('LPAREN') if stream.pointer().type in ['INTEGER_TYPE','FLOAT_TYPE','STRING_TYPE']: args = formal_args(stream) else: args = ('LIST', []) stream.match('RPAREN') body = stmt(stream) return ('FUNCTION', args, body ) elif stream.pointer().type in ['ASSIGN']: stream.match('ASSIGN') e = exp(stream) if stream.pointer().type in ['SEMI']: stream.match('SEMI') return e else: if stream.pointer().type in ['SEMI']: stream.match('SEMI') return ('CONST',('INTEGER_TYPE',), ('VALUE', 0)) # id_suffix : {LPAREN} LPAREN ({INTEGER,FLOAT,STRING,ID,LPAREN,MINUS,NOT} actual_args)? # RPAREN ({SEMI} SEMI)? # | {ASSIGN} ASSIGN exp ({SEMI} SEMI)? def id_suffix(stream): if stream.pointer().type in ['LPAREN']: stream.match('LPAREN') if stream.pointer().type in exp_lookahead: args = actual_args(stream) stream.match('RPAREN') if stream.pointer().type in ['SEMI']: stream.match('SEMI') return args elif stream.pointer().type in ['ASSIGN']: stream.match('ASSIGN') e = exp(stream) if stream.pointer().type in ['SEMI']: stream.match('SEMI') return e else: raise SyntaxError("id_suffix: syntax error at {}" .format(stream.pointer().value)) # exp : {INTEGER,FLOAT,STRING,ID,LPAREN,MINUS,NOT} exp_low # exp_lookahead # == exp_low_lookahead # == exp_med_lookahead # == exp_high_lookahead # == primary_lookahead exp_lookahead = [ 'INTEGER', 'FLOAT', 'STRING', 'ID', 'LPAREN', 'MINUS', 'NOT', ] def exp(stream): if stream.pointer().type in exp_lookahead: e = exp_low(stream) return e else: raise SyntaxError("exp: syntax error at {}" .format(stream.pointer().value)) # exp_low : {INTEGER,FLOAT,STRING,ID,LPAREN,MINUS,NOT} exp_med ({EQ,LE} (EQ|LE) exp_med)* def exp_low(stream): if stream.pointer().type in exp_lookahead: e = exp_med(stream) while stream.pointer().type in ['EQ','LE']: if stream.pointer().type == 'EQ': op_tk = stream.match('EQ') else: op_tk = stream.match('LE') tmp = exp_med(stream) e = (op_tk.type, e, tmp) return e else: raise SyntaxError("exp_low: syntax error at {}" .format(stream.pointer().value)) # exp_med : {INTEGER,FLOAT,STRING,ID,LPAREN,MINUS,NOT} exp_high ({PLUS,MINUS} (PLUS|MINUS) exp_high)* def exp_med(stream): if stream.pointer().type in exp_lookahead: e = exp_high(stream) while stream.pointer().type in ['PLUS','MINUS']: if stream.pointer().type == 'PLUS': op_tk = stream.match('PLUS') else: op_tk = stream.match('MINUS') tmp = exp_high(stream) e = (op_tk.type, e, tmp) return e else: raise SyntaxError("exp_med: syntax error at {}" .format(stream.pointer().value)) # exp_high : {INTEGER,FLOAT,STRING,ID,LPAREN,MINUS,NOT} primary ({MUL,DIV} (MUL|DIV) primary)* def exp_high(stream): if stream.pointer().type in exp_lookahead: e = primary(stream) while stream.pointer().type in ['MUL','DIV']: if stream.pointer().type == 'MUL': op_tk = stream.match('MUL') else: op_tk = stream.match('DIV') tmp = primary(stream) e = (op_tk.type, e, tmp) return e else: raise SyntaxError("exp_high: syntax error at {}" .format(stream.pointer().value)) # primary : {INTEGER} INTEGER # | {FLOAT} FLOAT # | {STRING} STRING # | {ID} ID ({LPAREN} LPAREN ({INTEGER,FLOAT,STRING,ID,LPAREN,MINUS,NOT} actual_args)? RPAREN)? # | {LPAREN} LPAREN exp RPAREN # | {MINUS} MINUS primary # | {NOT} NOT primary def primary(stream): if stream.pointer().type in ['INTEGER']: tk = stream.match('INTEGER') return ('CONST', ('INTEGER_TYPE',), ('VALUE', int(tk.value))) elif stream.pointer().type in ['FLOAT']: tk = stream.match('FLOAT') return ('CONST', ('FLOAT_TYPE',), ('VALUE', float(tk.value))) elif stream.pointer().type in ['STRING']: tk = stream.match('STRING') return ('CONST', ('STRING_TYPE',), ('VALUE', str(tk.value))) elif stream.pointer().type in ['ID']: id_tk = stream.match('ID') if stream.pointer().type in ['LPAREN']: stream.match('LPAREN') if stream.pointer().type in exp_lookahead: args = actual_args(stream) else: args = ('LIST', []) stream.match('RPAREN') return ('CALLEXP', ('ID', id_tk.value), args) else: return ('ID', id_tk.value) elif stream.pointer().type in ['LPAREN']: stream.match('LPAREN') e = exp(stream) stream.match('RPAREN') return e elif stream.pointer().type in ['MINUS']: stream.match('MINUS') e = primary(stream) if e[0] == 'CONST' and e[1][0] in ['INTEGER_TYPE', 'FLOAT_TYPE']: return ('CONST', e[1], -e[2]) else: return ('UMINUS', e) elif stream.pointer().type in ['NOT']: stream.match('NOT') e = primary(stream) # (CONST, TYPE, VAL) if e[0] == 'CONST' and e[1][0] == 'INTEGER_TYPE': return ('CONST', ('INTEGER_TYPE',), 0 if e[2] else 1) else: return ('NOT', e) else: raise SyntaxError("primary: syntax error at {}" .format(stream.pointer().value)) # formal_args : {INTEGER_TYPE,FLOAT_TYPE,STRING_TYPE} data_type ID ({COMMA} COMMA data_type ID)* def formal_args(stream): if stream.pointer().type in ['INTEGER_TYPE','FLOAT_TYPE','STRING_TYPE']: type = data_type(stream) id_tok = stream.match('ID') ll = [('FORMALARG', type, ('ID', id_tok.value))] while stream.pointer().type in ['COMMA']: stream.match('COMMA') type = data_type(stream) id_tok = stream.match('ID') ll.append(('FORMALARG', type, ('ID', id_tok.value))) return ('LIST', ll) else: raise SyntaxError("formal_args: syntax error at {}" .format(stream.pointer().value)) # actual_args : {INTEGER,FLOAT,STRING,ID,LPAREN,MINUS,NOT} exp ({COMMA} COMMA exp)* def actual_args(stream): if stream.pointer().type in exp_lookahead: e = exp(stream) ll = [e] while stream.pointer().type in ['COMMA']: stream.match('COMMA') e = exp(stream) ll.append(e) return ('LIST', ll) else: raise SyntaxError("actual_args: syntax error at {}" .format(stream.pointer().value)) # frontend top-level driver def parse(stream): from cuppa4_lexer import Lexer token_stream = Lexer(stream) sl = stmt_list(token_stream) # call the parser function for start symbol if not token_stream.end_of_file(): raise SyntaxError("parse: syntax error at {}" .format(token_stream.pointer().value)) else: return sl if __name__ == "__main__": from sys import stdin from dumpast import dumpast char_stream = stdin.read() # read from stdin dumpast(parse(char_stream))
35.00813
105
0.549466
def formalargs_type(args): output_list = list() for a in args[1]: (FORMALARG, type, id) = a output_list.append(type) return ('LIST', output_list) stmt_lookahead = [ 'VOID_TYPE', 'INTEGER_TYPE', 'FLOAT_TYPE', 'STRING_TYPE', 'ID', 'GET', 'PUT', 'RETURN', 'WHILE', 'IF', 'LCURLY', ] def stmt_list(stream): lst = [] while stream.pointer().type in stmt_lookahead: s = stmt(stream) lst.append(s) return ('STMTLIST', lst) def stmt(stream): if stream.pointer().type in ['VOID_TYPE']: stream.match('VOID_TYPE') ret_type = ('VOID_TYPE',) id_tok = stream.match('ID') stream.match('LPAREN') args = ('NIL',) if stream.pointer().type in ['INTEGER_TYPE','FLOAT_TYPE','STRING_TYPE']: args = formal_args(stream) stream.match('RPAREN') arg_types = formalargs_type(args) body = stmt(stream) return ('FUNDECL', ('ID', id_tok.value), ('FUNCTION_TYPE', ret_type, arg_types), args, body) elif stream.pointer().type in ['INTEGER_TYPE','FLOAT_TYPE','STRING_TYPE']: type = data_type(stream) id_tok = stream.match('ID') e = decl_suffix(stream) if e[0] == 'FUNCTION': (FUNCTION, args, body) = e arg_types = formalargs_type(args) return ('FUNDECL', ('ID', id_tok.value), ('FUNCTION_TYPE', type, arg_types), args, body) else: return ('VARDECL', ('ID', id_tok.value), type, e) elif stream.pointer().type in ['ID']: id_tok = stream.match('ID') e = id_suffix(stream) if e[0] == 'LIST': return ('CALLSTMT', ('ID', id_tok.value), e) else: return ('ASSIGN', ('ID', id_tok.value), e) elif stream.pointer().type in ['GET']: stream.match('GET') id_tk = stream.match('ID') if stream.pointer().type in ['SEMI']: stream.match('SEMI') return ('GET', ('ID', id_tk.value)) elif stream.pointer().type in ['PUT']: stream.match('PUT') e = exp(stream) if stream.pointer().type in ['SEMI']: stream.match('SEMI') return ('PUT', e) elif stream.pointer().type in ['RETURN']: stream.match('RETURN') if stream.pointer().type in exp_lookahead: e = exp(stream) else: e = ('NIL',) if stream.pointer().type in ['SEMI']: stream.match('SEMI') return ('RETURN', e) elif stream.pointer().type in ['WHILE']: stream.match('WHILE') stream.match('LPAREN') e = exp(stream) stream.match('RPAREN') s = stmt(stream) return ('WHILE', e, s) elif stream.pointer().type in ['IF']: stream.match('IF') stream.match('LPAREN') e = exp(stream) stream.match('RPAREN') s1 = stmt(stream) if stream.pointer().type in ['ELSE']: stream.match('ELSE') s2 = stmt(stream) return ('IF', e, s1, s2) else: return ('IF', e, s1, ('NIL',)) elif stream.pointer().type in ['LCURLY']: stream.match('LCURLY') sl = stmt_list(stream) stream.match('RCURLY') return ('BLOCK', sl) else: raise SyntaxError("stmt: syntax error at {}" .format(stream.pointer().value)) def data_type(stream): if stream.pointer().type in ['INTEGER_TYPE']: stream.match('INTEGER_TYPE') return ('INTEGER_TYPE',) elif stream.pointer().type in ['FLOAT_TYPE']: stream.match('FLOAT_TYPE') return ('FLOAT_TYPE',) elif stream.pointer().type in ['STRING_TYPE']: stream.match('STRING_TYPE') return ('STRING_TYPE',) else: raise SyntaxError("data_type: syntax error at {}" .format(stream.pointer().value)) def decl_suffix(stream): if stream.pointer().type in ['LPAREN']: stream.match('LPAREN') if stream.pointer().type in ['INTEGER_TYPE','FLOAT_TYPE','STRING_TYPE']: args = formal_args(stream) else: args = ('LIST', []) stream.match('RPAREN') body = stmt(stream) return ('FUNCTION', args, body ) elif stream.pointer().type in ['ASSIGN']: stream.match('ASSIGN') e = exp(stream) if stream.pointer().type in ['SEMI']: stream.match('SEMI') return e else: if stream.pointer().type in ['SEMI']: stream.match('SEMI') return ('CONST',('INTEGER_TYPE',), ('VALUE', 0)) def id_suffix(stream): if stream.pointer().type in ['LPAREN']: stream.match('LPAREN') if stream.pointer().type in exp_lookahead: args = actual_args(stream) stream.match('RPAREN') if stream.pointer().type in ['SEMI']: stream.match('SEMI') return args elif stream.pointer().type in ['ASSIGN']: stream.match('ASSIGN') e = exp(stream) if stream.pointer().type in ['SEMI']: stream.match('SEMI') return e else: raise SyntaxError("id_suffix: syntax error at {}" .format(stream.pointer().value)) exp_lookahead = [ 'INTEGER', 'FLOAT', 'STRING', 'ID', 'LPAREN', 'MINUS', 'NOT', ] def exp(stream): if stream.pointer().type in exp_lookahead: e = exp_low(stream) return e else: raise SyntaxError("exp: syntax error at {}" .format(stream.pointer().value)) def exp_low(stream): if stream.pointer().type in exp_lookahead: e = exp_med(stream) while stream.pointer().type in ['EQ','LE']: if stream.pointer().type == 'EQ': op_tk = stream.match('EQ') else: op_tk = stream.match('LE') tmp = exp_med(stream) e = (op_tk.type, e, tmp) return e else: raise SyntaxError("exp_low: syntax error at {}" .format(stream.pointer().value)) def exp_med(stream): if stream.pointer().type in exp_lookahead: e = exp_high(stream) while stream.pointer().type in ['PLUS','MINUS']: if stream.pointer().type == 'PLUS': op_tk = stream.match('PLUS') else: op_tk = stream.match('MINUS') tmp = exp_high(stream) e = (op_tk.type, e, tmp) return e else: raise SyntaxError("exp_med: syntax error at {}" .format(stream.pointer().value)) def exp_high(stream): if stream.pointer().type in exp_lookahead: e = primary(stream) while stream.pointer().type in ['MUL','DIV']: if stream.pointer().type == 'MUL': op_tk = stream.match('MUL') else: op_tk = stream.match('DIV') tmp = primary(stream) e = (op_tk.type, e, tmp) return e else: raise SyntaxError("exp_high: syntax error at {}" .format(stream.pointer().value)) def primary(stream): if stream.pointer().type in ['INTEGER']: tk = stream.match('INTEGER') return ('CONST', ('INTEGER_TYPE',), ('VALUE', int(tk.value))) elif stream.pointer().type in ['FLOAT']: tk = stream.match('FLOAT') return ('CONST', ('FLOAT_TYPE',), ('VALUE', float(tk.value))) elif stream.pointer().type in ['STRING']: tk = stream.match('STRING') return ('CONST', ('STRING_TYPE',), ('VALUE', str(tk.value))) elif stream.pointer().type in ['ID']: id_tk = stream.match('ID') if stream.pointer().type in ['LPAREN']: stream.match('LPAREN') if stream.pointer().type in exp_lookahead: args = actual_args(stream) else: args = ('LIST', []) stream.match('RPAREN') return ('CALLEXP', ('ID', id_tk.value), args) else: return ('ID', id_tk.value) elif stream.pointer().type in ['LPAREN']: stream.match('LPAREN') e = exp(stream) stream.match('RPAREN') return e elif stream.pointer().type in ['MINUS']: stream.match('MINUS') e = primary(stream) if e[0] == 'CONST' and e[1][0] in ['INTEGER_TYPE', 'FLOAT_TYPE']: return ('CONST', e[1], -e[2]) else: return ('UMINUS', e) elif stream.pointer().type in ['NOT']: stream.match('NOT') e = primary(stream) if e[0] == 'CONST' and e[1][0] == 'INTEGER_TYPE': return ('CONST', ('INTEGER_TYPE',), 0 if e[2] else 1) else: return ('NOT', e) else: raise SyntaxError("primary: syntax error at {}" .format(stream.pointer().value)) def formal_args(stream): if stream.pointer().type in ['INTEGER_TYPE','FLOAT_TYPE','STRING_TYPE']: type = data_type(stream) id_tok = stream.match('ID') ll = [('FORMALARG', type, ('ID', id_tok.value))] while stream.pointer().type in ['COMMA']: stream.match('COMMA') type = data_type(stream) id_tok = stream.match('ID') ll.append(('FORMALARG', type, ('ID', id_tok.value))) return ('LIST', ll) else: raise SyntaxError("formal_args: syntax error at {}" .format(stream.pointer().value)) def actual_args(stream): if stream.pointer().type in exp_lookahead: e = exp(stream) ll = [e] while stream.pointer().type in ['COMMA']: stream.match('COMMA') e = exp(stream) ll.append(e) return ('LIST', ll) else: raise SyntaxError("actual_args: syntax error at {}" .format(stream.pointer().value)) def parse(stream): from cuppa4_lexer import Lexer token_stream = Lexer(stream) sl = stmt_list(token_stream) if not token_stream.end_of_file(): raise SyntaxError("parse: syntax error at {}" .format(token_stream.pointer().value)) else: return sl if __name__ == "__main__": from sys import stdin from dumpast import dumpast char_stream = stdin.read() dumpast(parse(char_stream))
true
true
1c39203f14a1c227593183bf54901f5572687633
7,062
py
Python
packages/python/plotly/plotly/tests/test_io/test_to_from_json.py
astafan8/plotly.py
c67f80067210d66e61c2f8f5e3b746a9a6c739a0
[ "MIT" ]
1
2022-01-22T04:10:29.000Z
2022-01-22T04:10:29.000Z
packages/python/plotly/plotly/tests/test_io/test_to_from_json.py
astafan8/plotly.py
c67f80067210d66e61c2f8f5e3b746a9a6c739a0
[ "MIT" ]
null
null
null
packages/python/plotly/plotly/tests/test_io/test_to_from_json.py
astafan8/plotly.py
c67f80067210d66e61c2f8f5e3b746a9a6c739a0
[ "MIT" ]
1
2022-02-07T14:42:35.000Z
2022-02-07T14:42:35.000Z
import plotly.graph_objs as go import plotly.io as pio import pytest import plotly import json import os import tempfile from unittest.mock import MagicMock from pathlib import Path # fixtures # -------- @pytest.fixture def fig1(request): return go.Figure( data=[ {"type": "scattergl", "marker": {"color": "green"}}, { "type": "parcoords", "dimensions": [{"values": [1, 2, 3]}, {"values": [3, 2, 1]}], "line": {"color": "blue"}, }, ], layout={"title": "Figure title"}, ) opts = { "separators": (",", ":"), "cls": plotly.utils.PlotlyJSONEncoder, "sort_keys": True, } pretty_opts = {"indent": 2, "cls": plotly.utils.PlotlyJSONEncoder, "sort_keys": True} # to_json # ------- def test_to_json(fig1): assert pio.to_json(fig1, remove_uids=False) == json.dumps(fig1, **opts) def test_to_json_remove_uids(fig1): dict1 = fig1.to_dict() for trace in dict1["data"]: trace.pop("uid", None) assert pio.to_json(fig1) == json.dumps(dict1, **opts) def test_to_json_validate(fig1): dict1 = fig1.to_dict() dict1["layout"]["bogus"] = 37 with pytest.raises(ValueError): pio.to_json(dict1) def test_to_json_validate_false(fig1): dict1 = fig1.to_dict() dict1["layout"]["bogus"] = 37 assert pio.to_json(dict1, validate=False) == json.dumps(dict1, **opts) def test_to_json_pretty_print(fig1): assert pio.to_json(fig1, remove_uids=False, pretty=True) == json.dumps( fig1, **pretty_opts ) # from_json # --------- def test_from_json(fig1): fig1_json = json.dumps(fig1, **opts) fig1_loaded = pio.from_json(fig1_json) # Check return type assert isinstance(fig1_loaded, go.Figure) # Check return json assert pio.to_json(fig1_loaded) == pio.to_json(fig1.to_dict()) @pytest.mark.parametrize( "fig_type_spec,fig_type", [ ("Figure", go.Figure), (go.Figure, go.Figure), ("FigureWidget", go.FigureWidget), (go.FigureWidget, go.FigureWidget), ], ) def test_from_json_output_type(fig1, fig_type_spec, fig_type): fig1_json = json.dumps(fig1, **opts) fig1_loaded = pio.from_json(fig1_json, output_type=fig_type_spec) # Check return type assert isinstance(fig1_loaded, fig_type) # Check return json assert pio.to_json(fig1_loaded) == pio.to_json(fig1.to_dict()) def test_from_json_invalid(fig1): dict1 = fig1.to_dict() # Set bad property name dict1["data"][0]["marker"]["bogus"] = 123 # Set property with bad value dict1["data"][0]["marker"]["size"] = -1 # Serialize to json bad_json = json.dumps(dict1, **opts) with pytest.raises(ValueError): pio.from_json(bad_json) def test_from_json_skip_invalid(fig1): dict1 = fig1.to_dict() # Set bad property name dict1["data"][0]["marker"]["bogus"] = 123 # Set property with bad value dict1["data"][0]["marker"]["size"] = -1 # Serialize to json bad_json = json.dumps(dict1, **opts) fig1_loaded = pio.from_json(bad_json, skip_invalid=True) # Check loaded figure assert pio.to_json(fig1_loaded) == pio.to_json(fig1.to_dict()) # read_json # --------- @pytest.mark.parametrize( "fig_type_spec,fig_type", [ ("Figure", go.Figure), (go.Figure, go.Figure), ("FigureWidget", go.FigureWidget), (go.FigureWidget, go.FigureWidget), ], ) def test_read_json_from_filelike(fig1, fig_type_spec, fig_type): # Configure file-like mock filemock = MagicMock() del filemock.read_text filemock.read.return_value = pio.to_json(fig1) # read_json on mock file fig1_loaded = pio.read_json(filemock, output_type=fig_type_spec) # Check return type assert isinstance(fig1_loaded, fig_type) # Check loaded figure assert pio.to_json(fig1_loaded) == pio.to_json(fig1.to_dict()) @pytest.mark.parametrize( "fig_type_spec,fig_type", [ ("Figure", go.Figure), (go.Figure, go.Figure), ("FigureWidget", go.FigureWidget), (go.FigureWidget, go.FigureWidget), ], ) def test_read_json_from_pathlib(fig1, fig_type_spec, fig_type): # Configure pathlib.Path-like mock filemock = MagicMock(spec=Path) filemock.read_text.return_value = pio.to_json(fig1) # read_json on mock file fig1_loaded = pio.read_json(filemock, output_type=fig_type_spec) # Check return type assert isinstance(fig1_loaded, fig_type) # Check loaded figure assert pio.to_json(fig1_loaded) == pio.to_json(fig1.to_dict()) @pytest.mark.parametrize( "fig_type_spec,fig_type", [ ("Figure", go.Figure), (go.Figure, go.Figure), ("FigureWidget", go.FigureWidget), (go.FigureWidget, go.FigureWidget), ], ) def test_read_json_from_file_string(fig1, fig_type_spec, fig_type): with tempfile.TemporaryDirectory() as dir_name: # Write json file path = os.path.join(dir_name, "fig1.json") with open(path, "w") as f: f.write(pio.to_json(fig1)) # read json from file as string fig1_loaded = pio.read_json(path, output_type=fig_type_spec) # Check return type assert isinstance(fig1_loaded, fig_type) # Check loaded figure assert pio.to_json(fig1_loaded) == pio.to_json(fig1.to_dict()) # write_json # ---------- @pytest.mark.parametrize("pretty", [True, False]) @pytest.mark.parametrize("remove_uids", [True, False]) def test_write_json_filelike(fig1, pretty, remove_uids): # Configure file-like mock filemock = MagicMock() del filemock.write_text # write_json to mock file pio.write_json(fig1, filemock, pretty=pretty, remove_uids=remove_uids) # check write contents expected = pio.to_json(fig1, pretty=pretty, remove_uids=remove_uids) filemock.write.assert_called_once_with(expected) @pytest.mark.parametrize("pretty", [True, False]) @pytest.mark.parametrize("remove_uids", [True, False]) def test_write_json_pathlib(fig1, pretty, remove_uids): # Configure file-like mock filemock = MagicMock(spec=Path) # write_json to mock file pio.write_json(fig1, filemock, pretty=pretty, remove_uids=remove_uids) # check write contents expected = pio.to_json(fig1, pretty=pretty, remove_uids=remove_uids) filemock.write_text.assert_called_once_with(expected) @pytest.mark.parametrize("pretty", [True, False]) @pytest.mark.parametrize("remove_uids", [True, False]) def test_write_json_from_file_string(fig1, pretty, remove_uids): with tempfile.TemporaryDirectory() as dir_name: # Write json path = os.path.join(dir_name, "fig1.json") pio.write_json(fig1, path, pretty=pretty, remove_uids=remove_uids) # Open as text file with open(path, "r") as f: result = f.read() # Check contents that were written expected = pio.to_json(fig1, pretty=pretty, remove_uids=remove_uids) assert result == expected
26.851711
85
0.65817
import plotly.graph_objs as go import plotly.io as pio import pytest import plotly import json import os import tempfile from unittest.mock import MagicMock from pathlib import Path @pytest.fixture def fig1(request): return go.Figure( data=[ {"type": "scattergl", "marker": {"color": "green"}}, { "type": "parcoords", "dimensions": [{"values": [1, 2, 3]}, {"values": [3, 2, 1]}], "line": {"color": "blue"}, }, ], layout={"title": "Figure title"}, ) opts = { "separators": (",", ":"), "cls": plotly.utils.PlotlyJSONEncoder, "sort_keys": True, } pretty_opts = {"indent": 2, "cls": plotly.utils.PlotlyJSONEncoder, "sort_keys": True} def test_to_json(fig1): assert pio.to_json(fig1, remove_uids=False) == json.dumps(fig1, **opts) def test_to_json_remove_uids(fig1): dict1 = fig1.to_dict() for trace in dict1["data"]: trace.pop("uid", None) assert pio.to_json(fig1) == json.dumps(dict1, **opts) def test_to_json_validate(fig1): dict1 = fig1.to_dict() dict1["layout"]["bogus"] = 37 with pytest.raises(ValueError): pio.to_json(dict1) def test_to_json_validate_false(fig1): dict1 = fig1.to_dict() dict1["layout"]["bogus"] = 37 assert pio.to_json(dict1, validate=False) == json.dumps(dict1, **opts) def test_to_json_pretty_print(fig1): assert pio.to_json(fig1, remove_uids=False, pretty=True) == json.dumps( fig1, **pretty_opts ) def test_from_json(fig1): fig1_json = json.dumps(fig1, **opts) fig1_loaded = pio.from_json(fig1_json) assert isinstance(fig1_loaded, go.Figure) assert pio.to_json(fig1_loaded) == pio.to_json(fig1.to_dict()) @pytest.mark.parametrize( "fig_type_spec,fig_type", [ ("Figure", go.Figure), (go.Figure, go.Figure), ("FigureWidget", go.FigureWidget), (go.FigureWidget, go.FigureWidget), ], ) def test_from_json_output_type(fig1, fig_type_spec, fig_type): fig1_json = json.dumps(fig1, **opts) fig1_loaded = pio.from_json(fig1_json, output_type=fig_type_spec) assert isinstance(fig1_loaded, fig_type) assert pio.to_json(fig1_loaded) == pio.to_json(fig1.to_dict()) def test_from_json_invalid(fig1): dict1 = fig1.to_dict() dict1["data"][0]["marker"]["bogus"] = 123 dict1["data"][0]["marker"]["size"] = -1 bad_json = json.dumps(dict1, **opts) with pytest.raises(ValueError): pio.from_json(bad_json) def test_from_json_skip_invalid(fig1): dict1 = fig1.to_dict() dict1["data"][0]["marker"]["bogus"] = 123 dict1["data"][0]["marker"]["size"] = -1 bad_json = json.dumps(dict1, **opts) fig1_loaded = pio.from_json(bad_json, skip_invalid=True) assert pio.to_json(fig1_loaded) == pio.to_json(fig1.to_dict()) @pytest.mark.parametrize( "fig_type_spec,fig_type", [ ("Figure", go.Figure), (go.Figure, go.Figure), ("FigureWidget", go.FigureWidget), (go.FigureWidget, go.FigureWidget), ], ) def test_read_json_from_filelike(fig1, fig_type_spec, fig_type): filemock = MagicMock() del filemock.read_text filemock.read.return_value = pio.to_json(fig1) fig1_loaded = pio.read_json(filemock, output_type=fig_type_spec) assert isinstance(fig1_loaded, fig_type) assert pio.to_json(fig1_loaded) == pio.to_json(fig1.to_dict()) @pytest.mark.parametrize( "fig_type_spec,fig_type", [ ("Figure", go.Figure), (go.Figure, go.Figure), ("FigureWidget", go.FigureWidget), (go.FigureWidget, go.FigureWidget), ], ) def test_read_json_from_pathlib(fig1, fig_type_spec, fig_type): filemock = MagicMock(spec=Path) filemock.read_text.return_value = pio.to_json(fig1) fig1_loaded = pio.read_json(filemock, output_type=fig_type_spec) assert isinstance(fig1_loaded, fig_type) assert pio.to_json(fig1_loaded) == pio.to_json(fig1.to_dict()) @pytest.mark.parametrize( "fig_type_spec,fig_type", [ ("Figure", go.Figure), (go.Figure, go.Figure), ("FigureWidget", go.FigureWidget), (go.FigureWidget, go.FigureWidget), ], ) def test_read_json_from_file_string(fig1, fig_type_spec, fig_type): with tempfile.TemporaryDirectory() as dir_name: path = os.path.join(dir_name, "fig1.json") with open(path, "w") as f: f.write(pio.to_json(fig1)) fig1_loaded = pio.read_json(path, output_type=fig_type_spec) assert isinstance(fig1_loaded, fig_type) assert pio.to_json(fig1_loaded) == pio.to_json(fig1.to_dict()) @pytest.mark.parametrize("pretty", [True, False]) @pytest.mark.parametrize("remove_uids", [True, False]) def test_write_json_filelike(fig1, pretty, remove_uids): filemock = MagicMock() del filemock.write_text pio.write_json(fig1, filemock, pretty=pretty, remove_uids=remove_uids) expected = pio.to_json(fig1, pretty=pretty, remove_uids=remove_uids) filemock.write.assert_called_once_with(expected) @pytest.mark.parametrize("pretty", [True, False]) @pytest.mark.parametrize("remove_uids", [True, False]) def test_write_json_pathlib(fig1, pretty, remove_uids): filemock = MagicMock(spec=Path) pio.write_json(fig1, filemock, pretty=pretty, remove_uids=remove_uids) expected = pio.to_json(fig1, pretty=pretty, remove_uids=remove_uids) filemock.write_text.assert_called_once_with(expected) @pytest.mark.parametrize("pretty", [True, False]) @pytest.mark.parametrize("remove_uids", [True, False]) def test_write_json_from_file_string(fig1, pretty, remove_uids): with tempfile.TemporaryDirectory() as dir_name: path = os.path.join(dir_name, "fig1.json") pio.write_json(fig1, path, pretty=pretty, remove_uids=remove_uids) with open(path, "r") as f: result = f.read() expected = pio.to_json(fig1, pretty=pretty, remove_uids=remove_uids) assert result == expected
true
true
1c39218de99cf3055114621cc77d6dfaa98a58d0
3,699
py
Python
flask_apispec/apidoc.py
henryfjordan/flask-apispec
a643f15586f4fdc16372e939805d00a0b23eafe3
[ "MIT" ]
null
null
null
flask_apispec/apidoc.py
henryfjordan/flask-apispec
a643f15586f4fdc16372e939805d00a0b23eafe3
[ "MIT" ]
null
null
null
flask_apispec/apidoc.py
henryfjordan/flask-apispec
a643f15586f4fdc16372e939805d00a0b23eafe3
[ "MIT" ]
null
null
null
# -*- coding: utf-8 -*- import copy import six from pkg_resources import parse_version import apispec from apispec.core import VALID_METHODS from apispec.ext.marshmallow import swagger from marshmallow import Schema from marshmallow.utils import is_instance_or_subclass from flask_apispec.paths import rule_to_path, rule_to_params from flask_apispec.utils import resolve_resource, resolve_annotations, merge_recursive class Converter(object): def __init__(self, app): self.app = app def convert(self, target, endpoint=None, blueprint=None, **kwargs): endpoint = endpoint or target.__name__.lower() if blueprint: endpoint = '{}.{}'.format(blueprint, endpoint) rules = self.app.url_map._rules_by_endpoint[endpoint] return [self.get_path(rule, target, **kwargs) for rule in rules] def get_path(self, rule, target, **kwargs): operations = self.get_operations(rule, target) parent = self.get_parent(target, **kwargs) return { 'view': target, 'path': rule_to_path(rule), 'operations': { method.lower(): self.get_operation(rule, view, parent=parent) for method, view in six.iteritems(operations) if method.lower() in (set(VALID_METHODS) - {'head'}) }, } def get_operations(self, rule, target): return {} def get_operation(self, rule, view, parent=None): annotation = resolve_annotations(view, 'docs', parent) docs = merge_recursive(annotation.options) operation = { 'responses': self.get_responses(view, parent), 'parameters': self.get_parameters(rule, view, docs, parent), } docs.pop('params', None) return merge_recursive([operation, docs]) def get_parent(self, view): return None def get_parameters(self, rule, view, docs, parent=None): annotation = resolve_annotations(view, 'args', parent) args = merge_recursive(annotation.options) schema = args.get('args', {}) if is_instance_or_subclass(schema, Schema): converter = swagger.schema2parameters elif callable(schema): schema = schema(request=None) if is_instance_or_subclass(schema, Schema): converter = swagger.schema2parameters else: converter = swagger.fields2parameters else: converter = swagger.fields2parameters options = copy.copy(args.get('kwargs', {})) locations = options.pop('locations', None) if locations: options['default_in'] = locations[0] if parse_version(apispec.__version__) < parse_version('0.20.0'): options['dump'] = False options['spec'] = self.app.config.get('APISPEC_SPEC', None) rule_params = rule_to_params(rule, docs.get('params')) or [] extra_params = converter(schema, **options) if args else [] return extra_params + rule_params def get_responses(self, view, parent=None): annotation = resolve_annotations(view, 'schemas', parent) return merge_recursive(annotation.options) class ViewConverter(Converter): def get_operations(self, rule, view): return {method: view for method in rule.methods} class ResourceConverter(Converter): def get_operations(self, rule, resource): return { method: getattr(resource, method.lower()) for method in rule.methods if hasattr(resource, method.lower()) } def get_parent(self, resource, **kwargs): return resolve_resource(resource, **kwargs)
34.570093
86
0.641254
import copy import six from pkg_resources import parse_version import apispec from apispec.core import VALID_METHODS from apispec.ext.marshmallow import swagger from marshmallow import Schema from marshmallow.utils import is_instance_or_subclass from flask_apispec.paths import rule_to_path, rule_to_params from flask_apispec.utils import resolve_resource, resolve_annotations, merge_recursive class Converter(object): def __init__(self, app): self.app = app def convert(self, target, endpoint=None, blueprint=None, **kwargs): endpoint = endpoint or target.__name__.lower() if blueprint: endpoint = '{}.{}'.format(blueprint, endpoint) rules = self.app.url_map._rules_by_endpoint[endpoint] return [self.get_path(rule, target, **kwargs) for rule in rules] def get_path(self, rule, target, **kwargs): operations = self.get_operations(rule, target) parent = self.get_parent(target, **kwargs) return { 'view': target, 'path': rule_to_path(rule), 'operations': { method.lower(): self.get_operation(rule, view, parent=parent) for method, view in six.iteritems(operations) if method.lower() in (set(VALID_METHODS) - {'head'}) }, } def get_operations(self, rule, target): return {} def get_operation(self, rule, view, parent=None): annotation = resolve_annotations(view, 'docs', parent) docs = merge_recursive(annotation.options) operation = { 'responses': self.get_responses(view, parent), 'parameters': self.get_parameters(rule, view, docs, parent), } docs.pop('params', None) return merge_recursive([operation, docs]) def get_parent(self, view): return None def get_parameters(self, rule, view, docs, parent=None): annotation = resolve_annotations(view, 'args', parent) args = merge_recursive(annotation.options) schema = args.get('args', {}) if is_instance_or_subclass(schema, Schema): converter = swagger.schema2parameters elif callable(schema): schema = schema(request=None) if is_instance_or_subclass(schema, Schema): converter = swagger.schema2parameters else: converter = swagger.fields2parameters else: converter = swagger.fields2parameters options = copy.copy(args.get('kwargs', {})) locations = options.pop('locations', None) if locations: options['default_in'] = locations[0] if parse_version(apispec.__version__) < parse_version('0.20.0'): options['dump'] = False options['spec'] = self.app.config.get('APISPEC_SPEC', None) rule_params = rule_to_params(rule, docs.get('params')) or [] extra_params = converter(schema, **options) if args else [] return extra_params + rule_params def get_responses(self, view, parent=None): annotation = resolve_annotations(view, 'schemas', parent) return merge_recursive(annotation.options) class ViewConverter(Converter): def get_operations(self, rule, view): return {method: view for method in rule.methods} class ResourceConverter(Converter): def get_operations(self, rule, resource): return { method: getattr(resource, method.lower()) for method in rule.methods if hasattr(resource, method.lower()) } def get_parent(self, resource, **kwargs): return resolve_resource(resource, **kwargs)
true
true
1c3926366b55551ae92b5873afdccbfc3221ebce
4,769
py
Python
src/main/python/main.py
sterzy/rc-snitch
0e6889e1797c3eae2e5f502f7f01cfee7e1bfa20
[ "MIT" ]
null
null
null
src/main/python/main.py
sterzy/rc-snitch
0e6889e1797c3eae2e5f502f7f01cfee7e1bfa20
[ "MIT" ]
null
null
null
src/main/python/main.py
sterzy/rc-snitch
0e6889e1797c3eae2e5f502f7f01cfee7e1bfa20
[ "MIT" ]
null
null
null
#!/usr/bin/env python3 # -*- coding: utf-8 -*- from commands import block, send, sniff, profile from pathlib import Path from util import check_binary, check_tri_state, check_tri_state_pair import argparse def main(): parser = argparse.ArgumentParser(description='''A utility to sniff and \ transmit with a 433MHz transceiver using an Arduino.''') subparsers = parser.add_subparsers(title='sub-commands', metavar='COMMAND', help='') subparsers.required = True parser.add_argument('-p', '--port', metavar='PORT', type=str, default='/dev/ttyACM0', help='''port the Arduino is connected to, defaults \ to "/dev/ttyACM0"''') parser.add_argument('-b', '--baud-rate', metavar='BAUDRATE', type=int, default=9600, help='''baud rate that the Arduino uses, defaults to \ 9600''') parser.add_argument('-t', '--timeout', metavar='TIMEOUT', type=int, default=5, help='''timeout used for the connection to the \ arduino, defaults to 5 seconds''') send_parser = subparsers.add_parser('send', help='''send either a \ tri-state, binary or decimal value''') send_group = send_parser.add_mutually_exclusive_group(required=True) send_group.add_argument('-b', '--binary', metavar="BINARY", type=check_binary, help='the binary code to send') send_group.add_argument('-t', '--tri-state', metavar="TRISTATE", type=check_tri_state, help='the tri-state code to send') send_group.add_argument('-d', '--decimal', metavar="NUMBER", type=int, nargs=2, help='the decimal code and length to send') send_parser.set_defaults(func=send.Send().execute) sniff_parser = subparsers.add_parser('sniff', help='''use the receiver to \ sniff for events''') sniff_parser.add_argument('-o', '--out', metavar='OUTFILE', type=Path, help='''write events to a file in addition to the \ terminal, data will be in a csv format''') sniff_parser.add_argument('-a', '--allowed', metavar='ALLOW', type=check_tri_state, nargs='+', help='''a list of allowed codes that will be \ logged, only accepts tri-state codes''') sniff_parser.set_defaults(func=sniff.Sniff().execute) block_parser = subparsers.add_parser('block', help='''block a switch either \ reactively or aggressively, only accepts tri-state codes''') block_group = block_parser.add_mutually_exclusive_group(required=True) block_group.add_argument('-r', '--reactive', metavar='ON:SEND', type=check_tri_state_pair, nargs='+', help='''reactively block a switch, when the code ON is \ detected SEND will be transmitted''') block_group.add_argument('-a', '--aggressive', metavar='CODE', type=check_tri_state, nargs='+', help='''aggressively block a switch i.e. send the \ provided code continously''') block_parser.set_defaults(func=block.Block().execute) profile_parser = subparsers.add_parser('profile', help='''take a csv file \ create by the "sniff" sub-command and create a nice overview''') profile_parser.add_argument('data', metavar='CSVFILE', type=Path, help='''the file containing the sniffing data''') profile_parser.set_defaults(func=profile.Profile().execute) args = parser.parse_args() args.func(args) if __name__ == '__main__': main()
37.551181
82
0.477039
from commands import block, send, sniff, profile from pathlib import Path from util import check_binary, check_tri_state, check_tri_state_pair import argparse def main(): parser = argparse.ArgumentParser(description='''A utility to sniff and \ transmit with a 433MHz transceiver using an Arduino.''') subparsers = parser.add_subparsers(title='sub-commands', metavar='COMMAND', help='') subparsers.required = True parser.add_argument('-p', '--port', metavar='PORT', type=str, default='/dev/ttyACM0', help='''port the Arduino is connected to, defaults \ to "/dev/ttyACM0"''') parser.add_argument('-b', '--baud-rate', metavar='BAUDRATE', type=int, default=9600, help='''baud rate that the Arduino uses, defaults to \ 9600''') parser.add_argument('-t', '--timeout', metavar='TIMEOUT', type=int, default=5, help='''timeout used for the connection to the \ arduino, defaults to 5 seconds''') send_parser = subparsers.add_parser('send', help='''send either a \ tri-state, binary or decimal value''') send_group = send_parser.add_mutually_exclusive_group(required=True) send_group.add_argument('-b', '--binary', metavar="BINARY", type=check_binary, help='the binary code to send') send_group.add_argument('-t', '--tri-state', metavar="TRISTATE", type=check_tri_state, help='the tri-state code to send') send_group.add_argument('-d', '--decimal', metavar="NUMBER", type=int, nargs=2, help='the decimal code and length to send') send_parser.set_defaults(func=send.Send().execute) sniff_parser = subparsers.add_parser('sniff', help='''use the receiver to \ sniff for events''') sniff_parser.add_argument('-o', '--out', metavar='OUTFILE', type=Path, help='''write events to a file in addition to the \ terminal, data will be in a csv format''') sniff_parser.add_argument('-a', '--allowed', metavar='ALLOW', type=check_tri_state, nargs='+', help='''a list of allowed codes that will be \ logged, only accepts tri-state codes''') sniff_parser.set_defaults(func=sniff.Sniff().execute) block_parser = subparsers.add_parser('block', help='''block a switch either \ reactively or aggressively, only accepts tri-state codes''') block_group = block_parser.add_mutually_exclusive_group(required=True) block_group.add_argument('-r', '--reactive', metavar='ON:SEND', type=check_tri_state_pair, nargs='+', help='''reactively block a switch, when the code ON is \ detected SEND will be transmitted''') block_group.add_argument('-a', '--aggressive', metavar='CODE', type=check_tri_state, nargs='+', help='''aggressively block a switch i.e. send the \ provided code continously''') block_parser.set_defaults(func=block.Block().execute) profile_parser = subparsers.add_parser('profile', help='''take a csv file \ create by the "sniff" sub-command and create a nice overview''') profile_parser.add_argument('data', metavar='CSVFILE', type=Path, help='''the file containing the sniffing data''') profile_parser.set_defaults(func=profile.Profile().execute) args = parser.parse_args() args.func(args) if __name__ == '__main__': main()
true
true
1c39284718027a242c5b3d74f179ac8b43a95aed
9,481
py
Python
tests/test_miso_helper.py
ferrumnet/MISO
d1698e1819d7cacbddb7fb979dc0c9a613d55cc9
[ "Apache-2.0" ]
80
2020-11-30T00:25:51.000Z
2022-03-15T12:02:37.000Z
brownie/tests/test_miso_helper.py
Certora/miso
9575fdf8aeccf1d97ba389b8428194e66187b6c1
[ "Apache-2.0" ]
8
2021-09-01T17:33:57.000Z
2022-02-25T20:11:27.000Z
brownie/tests/test_miso_helper.py
Certora/miso
9575fdf8aeccf1d97ba389b8428194e66187b6c1
[ "Apache-2.0" ]
30
2020-11-30T00:25:57.000Z
2022-01-09T06:01:27.000Z
from brownie import accounts, web3, Wei, reverts, chain from brownie.network.transaction import TransactionReceipt from brownie.convert import to_address import pytest from brownie import Contract from settings import * from test_token_factory import _create_token # reset the chain after every test case @pytest.fixture(autouse=True) def isolation(fn_isolation): pass # Crowdsale with a simple operator @pytest.fixture(scope='module', autouse=True) def crowdsale(Crowdsale, mintable_token): crowdsale = Crowdsale.deploy({"from": accounts[0]}) mintable_token.mint(accounts[0], AUCTION_TOKENS, {"from": accounts[0]}) assert mintable_token.balanceOf(accounts[0]) == AUCTION_TOKENS start_time = chain.time() + 10 end_time = start_time + CROWDSALE_TIME wallet = accounts[4] operator = accounts[0] mintable_token.approve(crowdsale, AUCTION_TOKENS, {"from": accounts[0]}) crowdsale.initCrowdsale( accounts[0], mintable_token, ETH_ADDRESS, CROWDSALE_TOKENS, start_time, end_time, CROWDSALE_RATE, CROWDSALE_GOAL, operator, ZERO_ADDRESS, wallet, {"from": accounts[0]} ) assert mintable_token.balanceOf(crowdsale) == AUCTION_TOKENS chain.sleep(10) return crowdsale @pytest.fixture(scope='function') def miso_helper(MISOHelper, miso_access_controls, token_factory, auction_factory, launcher, farm_factory): miso_helper = MISOHelper.deploy(miso_access_controls, token_factory, auction_factory, launcher, farm_factory, {"from": accounts[0]}) return miso_helper def test_getTokens(miso_helper, token_factory, fixed_token_template): name = "Helper Token" symbol = "HP" template_id = 1 # Fixed Token Template total_supply = 100 * TENPOW18 integrator_account = accounts[1] _create_token( token_factory, fixed_token_template, name, symbol, total_supply, template_id, integrator_account, accounts[0] ) _create_token( token_factory, fixed_token_template, name, symbol, total_supply, template_id, integrator_account, accounts[1] ) tokens = miso_helper.getTokens() print("tokens:", tokens) def test_getCrowdsaleInfo(miso_helper, crowdsale): crowdsale_info = miso_helper.getCrowdsaleInfo(crowdsale) print("crowdsale_info:", crowdsale_info) print("totalTokens:", crowdsale.marketInfo()[2]) @pytest.fixture(scope='function') def fixed_token_cal(FixedToken): fixed_token_cal = FixedToken.deploy({'from': accounts[0]}) name = "Fixed Token Cal" symbol = "CAL" owner = accounts[0] fixed_token_cal.initToken(name, symbol, owner,AUCTION_TOKENS, {'from': owner}) assert fixed_token_cal.name() == name assert fixed_token_cal.symbol() == symbol # assert fixed_token_cal.owner() == owner # changed to access controls assert fixed_token_cal.totalSupply() == AUCTION_TOKENS assert fixed_token_cal.balanceOf(owner) == AUCTION_TOKENS return fixed_token_cal def test_getMarkets(miso_helper, auction_factory, dutch_auction_template, fixed_token_cal): assert fixed_token_cal.balanceOf(accounts[0]) == AUCTION_TOKENS template_id = auction_factory.getTemplateId(dutch_auction_template) minimum_fee = 0.1 * TENPOW18 integrator_fee_percent = 10 ETH_TO_FEE = 1 * TENPOW18 auction_factory.setMinimumFee(minimum_fee,{"from":accounts[0]}) auction_factory.setIntegratorFeePct(integrator_fee_percent, {"from":accounts[0]}) start_date = chain.time() + 20 end_date = start_date + AUCTION_TIME operator = accounts[0] wallet = accounts[1] chain.sleep(10) fixed_token_cal.approve(auction_factory, AUCTION_TOKENS, {"from": accounts[0]}) _data = dutch_auction_template.getAuctionInitData( auction_factory, fixed_token_cal, AUCTION_TOKENS, start_date, end_date, ETH_ADDRESS, AUCTION_START_PRICE, AUCTION_RESERVE, operator, ZERO_ADDRESS, wallet, {"from": accounts[0]} ) tx = auction_factory.createMarket(template_id,fixed_token_cal,AUCTION_TOKENS,wallet, _data,{"from":accounts[0],"value": ETH_TO_FEE}) markets = miso_helper.getMarkets() print("markets:", markets) def test_getDutchAuctionInfo(miso_helper, dutch_auction): dutch_auction_info = miso_helper.getDutchAuctionInfo(dutch_auction) print("dutch_auction_info:", dutch_auction_info) def test_getBatchAuctionInfo(miso_helper, batch_auction): batch_auction_info = miso_helper.getBatchAuctionInfo(batch_auction) print("batch_auction_info:", batch_auction_info) def test_getHyperbolicAuctionInfo(miso_helper, hyperbolic_auction): hyperbolic_auction_info = miso_helper.getHyperbolicAuctionInfo(hyperbolic_auction) print("hyperbolic_auction_info:", hyperbolic_auction_info) def test_getFarms(miso_helper, create_farm): farms = miso_helper.getFarms() print("farms:", farms) def test_getFarmDetail(miso_helper, create_farm): farm_info_user_0 = miso_helper.getFarmDetail(create_farm, accounts[0]) farm_info_user_1 = miso_helper.getFarmDetail(create_farm, accounts[1]) print("farm_info_user_0:", farm_info_user_0) print("farm_info_user_1:", farm_info_user_1) def test_getUserPoolsInfos(miso_helper): user_pool_infos = miso_helper.getUserPoolsInfos(accounts[0]) print("user_pools_infos:", user_pool_infos) def test_getUserMarketInfo(miso_helper, crowdsale): crowdsale.commitEth(accounts[0], True, {"from": accounts[0], "value": 2*TENPOW18}) user_info = miso_helper.getUserMarketInfo(crowdsale, accounts[0]) print("user_info:", user_info) @pytest.fixture(scope='function') def create_farm(MISOMasterChef, farm_factory, farm_template, fixed_token_cal, miso_access_controls, staking_token): rewards_per_block = 1 * TENPOW18 # Define the start time relative to sales start_block = len(chain) + 10 wallet = accounts[4] dev_addr = wallet fixed_token_cal.approve(farm_factory, AUCTION_TOKENS, {"from": accounts[0]}) integratorFeeAccount = accounts[6] miso_dev = accounts[5] integratorFeeAccount = accounts[6] before_deploy_balance_miso_dev = miso_dev.balance() before_deploy_balance_integrator = integratorFeeAccount.balance() data = farm_template.getInitData(fixed_token_cal, rewards_per_block, start_block, dev_addr, accounts[0]) tx = farm_factory.createFarm(1,wallet, data,{"from":accounts[0]}) master_chef = MISOMasterChef.at(tx.return_value) assert "FarmCreated" in tx.events assert farm_factory.numberOfFarms() == 1 master_chef.addToken(150, staking_token, True, {'from': accounts[0]}) staking_token.approve(master_chef, 100*TENPOW18, {'from': accounts[1]}) master_chef.deposit(0, 100*TENPOW18, {'from': accounts[1]}) staking_token.approve(master_chef, 200*TENPOW18, {'from': accounts[2]}) master_chef.deposit(0, 200*TENPOW18, {'from': accounts[2]}) assert master_chef.poolLength() == 1 after_deploy_balance_miso_dev = miso_dev.balance() after_deploy_balance_integrator = integratorFeeAccount.balance() assert before_deploy_balance_miso_dev==after_deploy_balance_miso_dev assert before_deploy_balance_integrator == after_deploy_balance_integrator return master_chef ##################################### # Reward Token ###################################### @pytest.fixture(scope='module', autouse=True) def reward_token(FixedToken): reward_token = FixedToken.deploy({'from': accounts[0]}) name = "Reward Token" symbol = "RWD" owner = accounts[1] initial_supply = 100000 * TENPOW18 reward_token.initToken(name, symbol, owner, initial_supply, {'from': owner}) return reward_token ##################################### # Staking Token ###################################### @pytest.fixture(scope='module', autouse=True) def staking_token(MintableToken): staking_token = MintableToken.deploy({'from': accounts[0]}) name = "Staking Token" symbol = "STAKE" owner = accounts[0] staking_token.initToken(name, symbol, owner, 1000 * TENPOW18, {'from': owner}) assert staking_token.name() == name assert staking_token.symbol() == symbol staking_token.mint(accounts[1], 1000 * TENPOW18, {'from': owner}) assert staking_token.balanceOf(accounts[1]) == 1000 * TENPOW18 staking_token.mint(accounts[2], 200 * TENPOW18, {'from': owner}) assert staking_token.balanceOf(accounts[2]) == 200 * TENPOW18 return staking_token ##################################### # LP Token ###################################### @pytest.fixture(scope='module', autouse=True) def lp_token(UniswapV2Pair, uniswap_factory, weth_token, reward_token): # lp_token = UniswapV2Pair.deploy({"from": accounts[0]}) # lp_token.initialize(weth_token, reward_token, {"from": accounts[0]}) tx = uniswap_factory.createPair(weth_token, reward_token, {"from": accounts[0]}) lp_token = UniswapV2Pair.at(tx.return_value) weth_token.deposit({'from': accounts[1], 'value': 1 * TENPOW18}) reward_token.transfer(lp_token, 100000 * TENPOW18, {'from':accounts[1]}) weth_token.transfer(lp_token, 1 * TENPOW18, {'from':accounts[1]}) lp_token.mint(accounts[1], {'from': accounts[1]}) return lp_token
32.693103
136
0.702141
from brownie import accounts, web3, Wei, reverts, chain from brownie.network.transaction import TransactionReceipt from brownie.convert import to_address import pytest from brownie import Contract from settings import * from test_token_factory import _create_token @pytest.fixture(autouse=True) def isolation(fn_isolation): pass @pytest.fixture(scope='module', autouse=True) def crowdsale(Crowdsale, mintable_token): crowdsale = Crowdsale.deploy({"from": accounts[0]}) mintable_token.mint(accounts[0], AUCTION_TOKENS, {"from": accounts[0]}) assert mintable_token.balanceOf(accounts[0]) == AUCTION_TOKENS start_time = chain.time() + 10 end_time = start_time + CROWDSALE_TIME wallet = accounts[4] operator = accounts[0] mintable_token.approve(crowdsale, AUCTION_TOKENS, {"from": accounts[0]}) crowdsale.initCrowdsale( accounts[0], mintable_token, ETH_ADDRESS, CROWDSALE_TOKENS, start_time, end_time, CROWDSALE_RATE, CROWDSALE_GOAL, operator, ZERO_ADDRESS, wallet, {"from": accounts[0]} ) assert mintable_token.balanceOf(crowdsale) == AUCTION_TOKENS chain.sleep(10) return crowdsale @pytest.fixture(scope='function') def miso_helper(MISOHelper, miso_access_controls, token_factory, auction_factory, launcher, farm_factory): miso_helper = MISOHelper.deploy(miso_access_controls, token_factory, auction_factory, launcher, farm_factory, {"from": accounts[0]}) return miso_helper def test_getTokens(miso_helper, token_factory, fixed_token_template): name = "Helper Token" symbol = "HP" template_id = 1 total_supply = 100 * TENPOW18 integrator_account = accounts[1] _create_token( token_factory, fixed_token_template, name, symbol, total_supply, template_id, integrator_account, accounts[0] ) _create_token( token_factory, fixed_token_template, name, symbol, total_supply, template_id, integrator_account, accounts[1] ) tokens = miso_helper.getTokens() print("tokens:", tokens) def test_getCrowdsaleInfo(miso_helper, crowdsale): crowdsale_info = miso_helper.getCrowdsaleInfo(crowdsale) print("crowdsale_info:", crowdsale_info) print("totalTokens:", crowdsale.marketInfo()[2]) @pytest.fixture(scope='function') def fixed_token_cal(FixedToken): fixed_token_cal = FixedToken.deploy({'from': accounts[0]}) name = "Fixed Token Cal" symbol = "CAL" owner = accounts[0] fixed_token_cal.initToken(name, symbol, owner,AUCTION_TOKENS, {'from': owner}) assert fixed_token_cal.name() == name assert fixed_token_cal.symbol() == symbol assert fixed_token_cal.totalSupply() == AUCTION_TOKENS assert fixed_token_cal.balanceOf(owner) == AUCTION_TOKENS return fixed_token_cal def test_getMarkets(miso_helper, auction_factory, dutch_auction_template, fixed_token_cal): assert fixed_token_cal.balanceOf(accounts[0]) == AUCTION_TOKENS template_id = auction_factory.getTemplateId(dutch_auction_template) minimum_fee = 0.1 * TENPOW18 integrator_fee_percent = 10 ETH_TO_FEE = 1 * TENPOW18 auction_factory.setMinimumFee(minimum_fee,{"from":accounts[0]}) auction_factory.setIntegratorFeePct(integrator_fee_percent, {"from":accounts[0]}) start_date = chain.time() + 20 end_date = start_date + AUCTION_TIME operator = accounts[0] wallet = accounts[1] chain.sleep(10) fixed_token_cal.approve(auction_factory, AUCTION_TOKENS, {"from": accounts[0]}) _data = dutch_auction_template.getAuctionInitData( auction_factory, fixed_token_cal, AUCTION_TOKENS, start_date, end_date, ETH_ADDRESS, AUCTION_START_PRICE, AUCTION_RESERVE, operator, ZERO_ADDRESS, wallet, {"from": accounts[0]} ) tx = auction_factory.createMarket(template_id,fixed_token_cal,AUCTION_TOKENS,wallet, _data,{"from":accounts[0],"value": ETH_TO_FEE}) markets = miso_helper.getMarkets() print("markets:", markets) def test_getDutchAuctionInfo(miso_helper, dutch_auction): dutch_auction_info = miso_helper.getDutchAuctionInfo(dutch_auction) print("dutch_auction_info:", dutch_auction_info) def test_getBatchAuctionInfo(miso_helper, batch_auction): batch_auction_info = miso_helper.getBatchAuctionInfo(batch_auction) print("batch_auction_info:", batch_auction_info) def test_getHyperbolicAuctionInfo(miso_helper, hyperbolic_auction): hyperbolic_auction_info = miso_helper.getHyperbolicAuctionInfo(hyperbolic_auction) print("hyperbolic_auction_info:", hyperbolic_auction_info) def test_getFarms(miso_helper, create_farm): farms = miso_helper.getFarms() print("farms:", farms) def test_getFarmDetail(miso_helper, create_farm): farm_info_user_0 = miso_helper.getFarmDetail(create_farm, accounts[0]) farm_info_user_1 = miso_helper.getFarmDetail(create_farm, accounts[1]) print("farm_info_user_0:", farm_info_user_0) print("farm_info_user_1:", farm_info_user_1) def test_getUserPoolsInfos(miso_helper): user_pool_infos = miso_helper.getUserPoolsInfos(accounts[0]) print("user_pools_infos:", user_pool_infos) def test_getUserMarketInfo(miso_helper, crowdsale): crowdsale.commitEth(accounts[0], True, {"from": accounts[0], "value": 2*TENPOW18}) user_info = miso_helper.getUserMarketInfo(crowdsale, accounts[0]) print("user_info:", user_info) @pytest.fixture(scope='function') def create_farm(MISOMasterChef, farm_factory, farm_template, fixed_token_cal, miso_access_controls, staking_token): rewards_per_block = 1 * TENPOW18 start_block = len(chain) + 10 wallet = accounts[4] dev_addr = wallet fixed_token_cal.approve(farm_factory, AUCTION_TOKENS, {"from": accounts[0]}) integratorFeeAccount = accounts[6] miso_dev = accounts[5] integratorFeeAccount = accounts[6] before_deploy_balance_miso_dev = miso_dev.balance() before_deploy_balance_integrator = integratorFeeAccount.balance() data = farm_template.getInitData(fixed_token_cal, rewards_per_block, start_block, dev_addr, accounts[0]) tx = farm_factory.createFarm(1,wallet, data,{"from":accounts[0]}) master_chef = MISOMasterChef.at(tx.return_value) assert "FarmCreated" in tx.events assert farm_factory.numberOfFarms() == 1 master_chef.addToken(150, staking_token, True, {'from': accounts[0]}) staking_token.approve(master_chef, 100*TENPOW18, {'from': accounts[1]}) master_chef.deposit(0, 100*TENPOW18, {'from': accounts[1]}) staking_token.approve(master_chef, 200*TENPOW18, {'from': accounts[2]}) master_chef.deposit(0, 200*TENPOW18, {'from': accounts[2]}) assert master_chef.poolLength() == 1 after_deploy_balance_miso_dev = miso_dev.balance() after_deploy_balance_integrator = integratorFeeAccount.balance() assert before_deploy_balance_miso_dev==after_deploy_balance_miso_dev assert before_deploy_balance_integrator == after_deploy_balance_integrator return master_chef
true
true
1c392b3f62972fca6f39a129839f79d030fd890e
6,362
py
Python
test/functional/feature_dersig.py
knotcoin/knotcoin
3f4ade4e2cabf94acd80bc043deec3d9a4209938
[ "MIT" ]
null
null
null
test/functional/feature_dersig.py
knotcoin/knotcoin
3f4ade4e2cabf94acd80bc043deec3d9a4209938
[ "MIT" ]
null
null
null
test/functional/feature_dersig.py
knotcoin/knotcoin
3f4ade4e2cabf94acd80bc043deec3d9a4209938
[ "MIT" ]
null
null
null
#!/usr/bin/env python3 # Copyright (c) 2015-2017 The Knotcoin Core developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. """Test BIP66 (DER SIG). Test that the DERSIG soft-fork activates at (regtest) height 1251. """ from test_framework.test_framework import KnotcoinTestFramework from test_framework.util import * from test_framework.mininode import * from test_framework.blocktools import create_coinbase, create_block from test_framework.script import CScript from io import BytesIO DERSIG_HEIGHT = 1251 # Reject codes that we might receive in this test REJECT_INVALID = 16 REJECT_OBSOLETE = 17 REJECT_NONSTANDARD = 64 # A canonical signature consists of: # <30> <total len> <02> <len R> <R> <02> <len S> <S> <hashtype> def unDERify(tx): """ Make the signature in vin 0 of a tx non-DER-compliant, by adding padding after the S-value. """ scriptSig = CScript(tx.vin[0].scriptSig) newscript = [] for i in scriptSig: if (len(newscript) == 0): newscript.append(i[0:-1] + b'\0' + i[-1:]) else: newscript.append(i) tx.vin[0].scriptSig = CScript(newscript) def create_transaction(node, coinbase, to_address, amount): from_txid = node.getblock(coinbase)['tx'][0] inputs = [{ "txid" : from_txid, "vout" : 0}] outputs = { to_address : amount } rawtx = node.createrawtransaction(inputs, outputs) signresult = node.signrawtransaction(rawtx) tx = CTransaction() tx.deserialize(BytesIO(hex_str_to_bytes(signresult['hex']))) return tx class BIP66Test(KnotcoinTestFramework): def set_test_params(self): self.num_nodes = 1 self.extra_args = [['-promiscuousmempoolflags=1', '-whitelist=127.0.0.1']] self.setup_clean_chain = True def run_test(self): self.nodes[0].add_p2p_connection(P2PInterface()) network_thread_start() # wait_for_verack ensures that the P2P connection is fully up. self.nodes[0].p2p.wait_for_verack() self.log.info("Mining %d blocks", DERSIG_HEIGHT - 2) self.coinbase_blocks = self.nodes[0].generate(DERSIG_HEIGHT - 2) self.nodeaddress = self.nodes[0].getnewaddress() self.log.info("Test that a transaction with non-DER signature can still appear in a block") spendtx = create_transaction(self.nodes[0], self.coinbase_blocks[0], self.nodeaddress, 1.0) unDERify(spendtx) spendtx.rehash() tip = self.nodes[0].getbestblockhash() block_time = self.nodes[0].getblockheader(tip)['mediantime'] + 1 block = create_block(int(tip, 16), create_coinbase(DERSIG_HEIGHT - 1), block_time) block.nVersion = 2 block.vtx.append(spendtx) block.hashMerkleRoot = block.calc_merkle_root() block.rehash() block.solve() self.nodes[0].p2p.send_and_ping(msg_block(block)) assert_equal(self.nodes[0].getbestblockhash(), block.hash) self.log.info("Test that blocks must now be at least version 3") tip = block.sha256 block_time += 1 block = create_block(tip, create_coinbase(DERSIG_HEIGHT), block_time) block.nVersion = 2 block.rehash() block.solve() self.nodes[0].p2p.send_and_ping(msg_block(block)) assert_equal(int(self.nodes[0].getbestblockhash(), 16), tip) wait_until(lambda: "reject" in self.nodes[0].p2p.last_message.keys(), lock=mininode_lock) with mininode_lock: assert_equal(self.nodes[0].p2p.last_message["reject"].code, REJECT_OBSOLETE) assert_equal(self.nodes[0].p2p.last_message["reject"].reason, b'bad-version(0x00000002)') assert_equal(self.nodes[0].p2p.last_message["reject"].data, block.sha256) del self.nodes[0].p2p.last_message["reject"] self.log.info("Test that transactions with non-DER signatures cannot appear in a block") block.nVersion = 3 spendtx = create_transaction(self.nodes[0], self.coinbase_blocks[1], self.nodeaddress, 1.0) unDERify(spendtx) spendtx.rehash() # First we show that this tx is valid except for DERSIG by getting it # accepted to the mempool (which we can achieve with # -promiscuousmempoolflags). self.nodes[0].p2p.send_and_ping(msg_tx(spendtx)) assert spendtx.hash in self.nodes[0].getrawmempool() # Now we verify that a block with this transaction is invalid. block.vtx.append(spendtx) block.hashMerkleRoot = block.calc_merkle_root() block.rehash() block.solve() self.nodes[0].p2p.send_and_ping(msg_block(block)) assert_equal(int(self.nodes[0].getbestblockhash(), 16), tip) wait_until(lambda: "reject" in self.nodes[0].p2p.last_message.keys(), lock=mininode_lock) with mininode_lock: # We can receive different reject messages depending on whether # knotcoind is running with multiple script check threads. If script # check threads are not in use, then transaction script validation # happens sequentially, and knotcoind produces more specific reject # reasons. assert self.nodes[0].p2p.last_message["reject"].code in [REJECT_INVALID, REJECT_NONSTANDARD] assert_equal(self.nodes[0].p2p.last_message["reject"].data, block.sha256) if self.nodes[0].p2p.last_message["reject"].code == REJECT_INVALID: # Generic rejection when a block is invalid assert_equal(self.nodes[0].p2p.last_message["reject"].reason, b'block-validation-failed') else: assert b'Non-canonical DER signature' in self.nodes[0].p2p.last_message["reject"].reason self.log.info("Test that a version 3 block with a DERSIG-compliant transaction is accepted") block.vtx[1] = create_transaction(self.nodes[0], self.coinbase_blocks[1], self.nodeaddress, 1.0) block.hashMerkleRoot = block.calc_merkle_root() block.rehash() block.solve() self.nodes[0].p2p.send_and_ping(msg_block(block)) assert_equal(int(self.nodes[0].getbestblockhash(), 16), block.sha256) if __name__ == '__main__': BIP66Test().main()
41.311688
105
0.668029
from test_framework.test_framework import KnotcoinTestFramework from test_framework.util import * from test_framework.mininode import * from test_framework.blocktools import create_coinbase, create_block from test_framework.script import CScript from io import BytesIO DERSIG_HEIGHT = 1251 REJECT_INVALID = 16 REJECT_OBSOLETE = 17 REJECT_NONSTANDARD = 64 def unDERify(tx): scriptSig = CScript(tx.vin[0].scriptSig) newscript = [] for i in scriptSig: if (len(newscript) == 0): newscript.append(i[0:-1] + b'\0' + i[-1:]) else: newscript.append(i) tx.vin[0].scriptSig = CScript(newscript) def create_transaction(node, coinbase, to_address, amount): from_txid = node.getblock(coinbase)['tx'][0] inputs = [{ "txid" : from_txid, "vout" : 0}] outputs = { to_address : amount } rawtx = node.createrawtransaction(inputs, outputs) signresult = node.signrawtransaction(rawtx) tx = CTransaction() tx.deserialize(BytesIO(hex_str_to_bytes(signresult['hex']))) return tx class BIP66Test(KnotcoinTestFramework): def set_test_params(self): self.num_nodes = 1 self.extra_args = [['-promiscuousmempoolflags=1', '-whitelist=127.0.0.1']] self.setup_clean_chain = True def run_test(self): self.nodes[0].add_p2p_connection(P2PInterface()) network_thread_start() self.nodes[0].p2p.wait_for_verack() self.log.info("Mining %d blocks", DERSIG_HEIGHT - 2) self.coinbase_blocks = self.nodes[0].generate(DERSIG_HEIGHT - 2) self.nodeaddress = self.nodes[0].getnewaddress() self.log.info("Test that a transaction with non-DER signature can still appear in a block") spendtx = create_transaction(self.nodes[0], self.coinbase_blocks[0], self.nodeaddress, 1.0) unDERify(spendtx) spendtx.rehash() tip = self.nodes[0].getbestblockhash() block_time = self.nodes[0].getblockheader(tip)['mediantime'] + 1 block = create_block(int(tip, 16), create_coinbase(DERSIG_HEIGHT - 1), block_time) block.nVersion = 2 block.vtx.append(spendtx) block.hashMerkleRoot = block.calc_merkle_root() block.rehash() block.solve() self.nodes[0].p2p.send_and_ping(msg_block(block)) assert_equal(self.nodes[0].getbestblockhash(), block.hash) self.log.info("Test that blocks must now be at least version 3") tip = block.sha256 block_time += 1 block = create_block(tip, create_coinbase(DERSIG_HEIGHT), block_time) block.nVersion = 2 block.rehash() block.solve() self.nodes[0].p2p.send_and_ping(msg_block(block)) assert_equal(int(self.nodes[0].getbestblockhash(), 16), tip) wait_until(lambda: "reject" in self.nodes[0].p2p.last_message.keys(), lock=mininode_lock) with mininode_lock: assert_equal(self.nodes[0].p2p.last_message["reject"].code, REJECT_OBSOLETE) assert_equal(self.nodes[0].p2p.last_message["reject"].reason, b'bad-version(0x00000002)') assert_equal(self.nodes[0].p2p.last_message["reject"].data, block.sha256) del self.nodes[0].p2p.last_message["reject"] self.log.info("Test that transactions with non-DER signatures cannot appear in a block") block.nVersion = 3 spendtx = create_transaction(self.nodes[0], self.coinbase_blocks[1], self.nodeaddress, 1.0) unDERify(spendtx) spendtx.rehash() self.nodes[0].p2p.send_and_ping(msg_tx(spendtx)) assert spendtx.hash in self.nodes[0].getrawmempool() block.vtx.append(spendtx) block.hashMerkleRoot = block.calc_merkle_root() block.rehash() block.solve() self.nodes[0].p2p.send_and_ping(msg_block(block)) assert_equal(int(self.nodes[0].getbestblockhash(), 16), tip) wait_until(lambda: "reject" in self.nodes[0].p2p.last_message.keys(), lock=mininode_lock) with mininode_lock: assert self.nodes[0].p2p.last_message["reject"].code in [REJECT_INVALID, REJECT_NONSTANDARD] assert_equal(self.nodes[0].p2p.last_message["reject"].data, block.sha256) if self.nodes[0].p2p.last_message["reject"].code == REJECT_INVALID: assert_equal(self.nodes[0].p2p.last_message["reject"].reason, b'block-validation-failed') else: assert b'Non-canonical DER signature' in self.nodes[0].p2p.last_message["reject"].reason self.log.info("Test that a version 3 block with a DERSIG-compliant transaction is accepted") block.vtx[1] = create_transaction(self.nodes[0], self.coinbase_blocks[1], self.nodeaddress, 1.0) block.hashMerkleRoot = block.calc_merkle_root() block.rehash() block.solve() self.nodes[0].p2p.send_and_ping(msg_block(block)) assert_equal(int(self.nodes[0].getbestblockhash(), 16), block.sha256) if __name__ == '__main__': BIP66Test().main()
true
true
1c392d05cd539b3dbedd2273b39a258c3a351840
513
py
Python
setup.py
robert-pathy/graphite-cleaner
fc6e59cf25307cad532c4323fb8d62372e7bffbd
[ "MIT" ]
null
null
null
setup.py
robert-pathy/graphite-cleaner
fc6e59cf25307cad532c4323fb8d62372e7bffbd
[ "MIT" ]
null
null
null
setup.py
robert-pathy/graphite-cleaner
fc6e59cf25307cad532c4323fb8d62372e7bffbd
[ "MIT" ]
null
null
null
#!/usr/bin/env python from setuptools import setup, find_packages setup( name='graphite-cleaner', version='0.1.3', description='Graphite Whisper stale database files remover', author='Services Wroclaw Team', author_email='svc-code@opera.com', url='https://github.com/operasoftware/graphite-cleaner', packages=find_packages(), entry_points={'console_scripts': [ 'graphite-cleaner = graphite_cleaner.main:main'] }, install_requires=[ 'argh==0.26.2' ] )
25.65
64
0.674464
from setuptools import setup, find_packages setup( name='graphite-cleaner', version='0.1.3', description='Graphite Whisper stale database files remover', author='Services Wroclaw Team', author_email='svc-code@opera.com', url='https://github.com/operasoftware/graphite-cleaner', packages=find_packages(), entry_points={'console_scripts': [ 'graphite-cleaner = graphite_cleaner.main:main'] }, install_requires=[ 'argh==0.26.2' ] )
true
true
1c3930693a5c124be3065fafbd3e7b798d91134e
2,211
py
Python
tools/utils.py
mpfeppat/mpfeppat
85ecf09a3d8c33177967ea404b2274b0d4f2d2df
[ "Apache-2.0" ]
1
2016-02-10T10:41:27.000Z
2016-02-10T10:41:27.000Z
tools/utils.py
mpfeppat/mpfeppat
85ecf09a3d8c33177967ea404b2274b0d4f2d2df
[ "Apache-2.0" ]
null
null
null
tools/utils.py
mpfeppat/mpfeppat
85ecf09a3d8c33177967ea404b2274b0d4f2d2df
[ "Apache-2.0" ]
null
null
null
"""Some format conversion tools. """ from base64 import b64encode from gmpy import mpz from re import sub # from gmpy2 import mpz, bit_length, f_divmod_2exp ALPHABET = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=" b64toOct = {} i = 0 for key in "ABCDEFGH": b64toOct[key] = "0" + str(i) i += 1 for key in "IJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=": b64toOct[key] = oct(i)[1:] i+= 1 #COUNTER = 0 #def crypthash(m): # global COUNTER # COUNTER += 1 # print "counting:", COUNTER # return sha256(m) def mpztob64(mpzval): """ converts an mpz integer into a base64 string """ # convert to octal string and pad with 0's to have 2k symbols # (octal conversion appears to be 3 times faster than binary) octal = mpzval.digits(8) octal = "0" * (len(octal) % 2) + octal # build resulting base64 string b64string = "" #print "octal: ", octal for i in xrange(0, len(octal), 2): b64string += ALPHABET[int(octal[i:i+2], 8)] return b64string def b64tompz(b64string): """ converts a base64 string into an mpz integer """ octal = "" for c in b64string: octal += b64toOct[c] return mpz(octal, 8) #def mpztob64(n): # '''Attempt at more efficient solution, but would require gmpy2 ''' # l = bit_length(n) # s = "" # for i in xrange(6*(l/6), -1, -6): # v, n = f_divmod_2exp(n, i) # s += ALPHABET[v] # return s def captounder(s): r = s[0].lower() r += sub(r'([A-Z])', lambda pat: '_' + pat.group(1).lower(), s[1:]) return r def undertocap(s): r = s[0].upper() r += sub('_'+r'([a-z])', lambda pat: pat.group(1).upper(), s[1:]) return r def binn(x): b = bin(x) s = b[2:] return s def decompBin(x,d,m): ''' x is an integer m is the possible total lenght of x d is the length of the words ''' b = binn(x) assert len(b)<=m if len(b)<m : t = '0'*(m-len(b)) b = t+b k = len(b)%d if not k == 0 : t = '0'*(d-k) b = t+b tu = () while not b == '' : fi = b[:d] la = b[d:] b = la tu = tu+(fi,) return tu
22.793814
78
0.561284
from base64 import b64encode from gmpy import mpz from re import sub ALPHABET = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=" b64toOct = {} i = 0 for key in "ABCDEFGH": b64toOct[key] = "0" + str(i) i += 1 for key in "IJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=": b64toOct[key] = oct(i)[1:] i+= 1 def mpztob64(mpzval): # (octal conversion appears to be 3 times faster than binary) octal = mpzval.digits(8) octal = "0" * (len(octal) % 2) + octal # build resulting base64 string b64string = "" #print "octal: ", octal for i in xrange(0, len(octal), 2): b64string += ALPHABET[int(octal[i:i+2], 8)] return b64string def b64tompz(b64string): octal = "" for c in b64string: octal += b64toOct[c] return mpz(octal, 8) #def mpztob64(n): # '''Attempt at more efficient solution, but would require gmpy2 ''' # l = bit_length(n) # s = "" # for i in xrange(6*(l/6), -1, -6): # v, n = f_divmod_2exp(n, i) # s += ALPHABET[v] # return s def captounder(s): r = s[0].lower() r += sub(r'([A-Z])', lambda pat: '_' + pat.group(1).lower(), s[1:]) return r def undertocap(s): r = s[0].upper() r += sub('_'+r'([a-z])', lambda pat: pat.group(1).upper(), s[1:]) return r def binn(x): b = bin(x) s = b[2:] return s def decompBin(x,d,m): b = binn(x) assert len(b)<=m if len(b)<m : t = '0'*(m-len(b)) b = t+b k = len(b)%d if not k == 0 : t = '0'*(d-k) b = t+b tu = () while not b == '' : fi = b[:d] la = b[d:] b = la tu = tu+(fi,) return tu
true
true
1c393135d2924153274c5bf9832e7a13fb57ac31
751
py
Python
app/core/tests/test_utils.py
PragmaticCoder/Linkedin-Analytics
a990b5cae02f0d758bc3123bde643d13a439efa3
[ "MIT" ]
13
2018-07-31T15:37:47.000Z
2021-12-20T04:48:13.000Z
app/core/tests/test_utils.py
PragmaticCoder/Linkedin-Analytics
a990b5cae02f0d758bc3123bde643d13a439efa3
[ "MIT" ]
25
2019-12-10T20:03:48.000Z
2022-03-11T23:26:11.000Z
app/core/tests/test_utils.py
PragmaticCoder/Linkedin-Analytics
a990b5cae02f0d758bc3123bde643d13a439efa3
[ "MIT" ]
4
2020-03-24T20:13:50.000Z
2022-02-05T20:40:48.000Z
from django.contrib.auth import get_user_model from django.test import TestCase from core.models import MyProfile from core.utils import content_file_name class ContentFileTests(TestCase): def setUp(self): self.user = get_user_model().objects.create_user( email="test@gmail.com", password="test1234", name="Test User" ) self.my_profile = MyProfile.objects.filter(owner__email="test@gmail.com").first() self.filename = content_file_name(self.my_profile, "C:/Images/test_image.jpg") def tearDown(self): self.user.delete() self.my_profile.delete() def test_content_file_name(self): self.assertEqual(str(self.filename)[10:], "1-portrait.jpg")
27.814815
89
0.679095
from django.contrib.auth import get_user_model from django.test import TestCase from core.models import MyProfile from core.utils import content_file_name class ContentFileTests(TestCase): def setUp(self): self.user = get_user_model().objects.create_user( email="test@gmail.com", password="test1234", name="Test User" ) self.my_profile = MyProfile.objects.filter(owner__email="test@gmail.com").first() self.filename = content_file_name(self.my_profile, "C:/Images/test_image.jpg") def tearDown(self): self.user.delete() self.my_profile.delete() def test_content_file_name(self): self.assertEqual(str(self.filename)[10:], "1-portrait.jpg")
true
true
1c393157c4d04005e6e3d429b955d205cafcbc5c
2,939
py
Python
code/utils/bbox_helper.py
cruiseresearchgroup/DroTrack
d2adb8d8ee6d142f89c16cd906c848903ba1617b
[ "MIT" ]
13
2020-08-19T14:33:04.000Z
2021-11-29T05:43:45.000Z
code/utils/bbox_helper.py
cruiseresearchgroup/DroTrack
d2adb8d8ee6d142f89c16cd906c848903ba1617b
[ "MIT" ]
1
2021-06-12T04:51:17.000Z
2022-02-22T09:43:17.000Z
code/utils/bbox_helper.py
cruiseresearchgroup/DroTrack
d2adb8d8ee6d142f89c16cd906c848903ba1617b
[ "MIT" ]
1
2021-06-23T07:06:07.000Z
2021-06-23T07:06:07.000Z
# -*- coding: utf-8 -*- """ Created on Tue Jul 14 13:37:39 2020 @author: Ali Hamdi; ali.ali@rmit.edu.au """ from collections import OrderedDict import cv2 import numpy as np from scipy.spatial import distance def intersection_over_union(boxA, boxB): # determine the (x, y)-coordinates of the intersection rectangle xA = max(boxA[0], boxB[0]) yA = max(boxA[1], boxB[1]) xB = min(boxA[2], boxB[2]) yB = min(boxA[3], boxB[3]) # compute the area of intersection rectangle interArea = max(0, xB - xA + 1) * max(0, yB - yA + 1) # compute the area of both the prediction and ground-truth # rectangles boxAArea = (boxA[2] - boxA[0] + 1) * (boxA[3] - boxA[1] + 1) boxBArea = (boxB[2] - boxB[0] + 1) * (boxB[3] - boxB[1] + 1) # compute the intersection over union by taking the intersection # area and dividing it by the sum of prediction + ground-truth # areas - the interesection area iou = interArea / float(boxAArea + boxBArea - interArea) # return the intersection over union value return iou def data2bboxes(data): boxes = {} for title, dataset in data.items(): boxes.update({title:{}}) for class_dir in dataset['dirs']: with open(dataset['url']+class_dir+'/groundtruth_rect.txt') as f: first_line = f.readline() points = [] try: for point in first_line.split(','): points.append(int(point)) except: for point in first_line.split('\t'): points.append(int(point)) bbox = tuple(points) boxes[title][class_dir] = bbox return OrderedDict(sorted(boxes.items())) def get_all_bboxes(filename): f = open(filename, 'r') lines = f.readlines() all_boxes = [] for line in lines: box = [] for point in line.split(','): try: box.append(float(point)) except: box.append(np.nan) all_boxes.append(box) return all_boxes def get_bbox_points(bbox): y1 = int(bbox[1]) y2 = int(bbox[1])+int(bbox[3]) x1 = int(bbox[0]) x2 = int(bbox[0])+int(bbox[2]) return x1, y1, x2, y2 def visualise_bbox(bbox, file, class_dir, s, dataset): frame_color = cv2.imread(dataset+class_dir+"/img/"+file) x1, y1, x2, y2 = get_bbox_points(bbox) x1, y1, x2, y2 = x1*s, y1*s, x2*s, y2*s cv2.rectangle(frame_color, (x1,y1), (x2,y2), (0,255,255), 1) cv2.imshow(class_dir, frame_color) def get_bbox_center(bbox): bbox_center_x = int(bbox[0]+(bbox[2]/2)) bbox_center_y = int(bbox[1]+(bbox[3]/2)) bc_point = (bbox_center_x, bbox_center_y) return bc_point # Calculate the difference between two points; ex: orginal center point and tracked point def complement_point(point, ppoint): return point[0]-ppoint[0], point[1]-ppoint[1]
31.945652
89
0.595781
from collections import OrderedDict import cv2 import numpy as np from scipy.spatial import distance def intersection_over_union(boxA, boxB): xA = max(boxA[0], boxB[0]) yA = max(boxA[1], boxB[1]) xB = min(boxA[2], boxB[2]) yB = min(boxA[3], boxB[3]) interArea = max(0, xB - xA + 1) * max(0, yB - yA + 1) boxAArea = (boxA[2] - boxA[0] + 1) * (boxA[3] - boxA[1] + 1) boxBArea = (boxB[2] - boxB[0] + 1) * (boxB[3] - boxB[1] + 1) iou = interArea / float(boxAArea + boxBArea - interArea) return iou def data2bboxes(data): boxes = {} for title, dataset in data.items(): boxes.update({title:{}}) for class_dir in dataset['dirs']: with open(dataset['url']+class_dir+'/groundtruth_rect.txt') as f: first_line = f.readline() points = [] try: for point in first_line.split(','): points.append(int(point)) except: for point in first_line.split('\t'): points.append(int(point)) bbox = tuple(points) boxes[title][class_dir] = bbox return OrderedDict(sorted(boxes.items())) def get_all_bboxes(filename): f = open(filename, 'r') lines = f.readlines() all_boxes = [] for line in lines: box = [] for point in line.split(','): try: box.append(float(point)) except: box.append(np.nan) all_boxes.append(box) return all_boxes def get_bbox_points(bbox): y1 = int(bbox[1]) y2 = int(bbox[1])+int(bbox[3]) x1 = int(bbox[0]) x2 = int(bbox[0])+int(bbox[2]) return x1, y1, x2, y2 def visualise_bbox(bbox, file, class_dir, s, dataset): frame_color = cv2.imread(dataset+class_dir+"/img/"+file) x1, y1, x2, y2 = get_bbox_points(bbox) x1, y1, x2, y2 = x1*s, y1*s, x2*s, y2*s cv2.rectangle(frame_color, (x1,y1), (x2,y2), (0,255,255), 1) cv2.imshow(class_dir, frame_color) def get_bbox_center(bbox): bbox_center_x = int(bbox[0]+(bbox[2]/2)) bbox_center_y = int(bbox[1]+(bbox[3]/2)) bc_point = (bbox_center_x, bbox_center_y) return bc_point def complement_point(point, ppoint): return point[0]-ppoint[0], point[1]-ppoint[1]
true
true
1c393288d85c3a10aa4301a9be8d466f103489b4
9,643
py
Python
tests/api/test_datafeed.py
sirjamesmeddel-gitty/intuition
cd517e6b3b315a743eb4d0d0dc294e264ab913ce
[ "Apache-2.0" ]
81
2015-01-13T15:16:43.000Z
2021-11-12T20:51:56.000Z
tests/api/test_datafeed.py
sirjamesmeddel-gitty/intuition
cd517e6b3b315a743eb4d0d0dc294e264ab913ce
[ "Apache-2.0" ]
1
2015-07-30T06:17:55.000Z
2015-07-30T08:09:14.000Z
tests/api/test_datafeed.py
sirjamesmeddel-gitty/intuition
cd517e6b3b315a743eb4d0d0dc294e264ab913ce
[ "Apache-2.0" ]
30
2015-03-26T11:55:46.000Z
2021-07-22T22:16:39.000Z
''' Tests for intuition.api.datafeed ''' import unittest from nose.tools import raises, ok_, eq_, nottest import random import pytz import datetime as dt import pandas as pd import intuition.api.datafeed as datafeed from intuition.data.universe import Market from intuition.errors import InvalidDatafeed import dna.test_utils class FakeBacktestDatasource(object): def __init__(self, sids, properties): pass @property def mapping(self): return { 'backtest': (lambda x: True, 'sid'), 'dt': (lambda x: x, 'dt'), 'sid': (lambda x: x, 'sid'), 'price': (float, 'price'), 'volume': (int, 'volume'), } def get_data(self, sids, start, end): index = pd.date_range(start, end, tz=pytz.utc) return pd.DataFrame({sid: [random.random()] * len(index) for sid in sids}, index=index) class FakePanelBacktestDatasource(object): def __init__(self, sids, properties): pass @property def mapping(self): return { 'backtest': (lambda x: True, 'sid'), 'dt': (lambda x: x, 'dt'), 'sid': (lambda x: x, 'sid'), 'price': (float, 'price'), 'low': (float, 'low'), 'high': (float, 'high'), 'volume': (int, 'volume'), } def get_data(self, sids, start, end): index = pd.date_range(start, end, tz=pytz.utc) fake_data = {} for sid in sids: fake_data[sid] = pd.DataFrame( {field: [random.random()] * len(index) for field in ['price', 'low', 'high', 'volume']}, index=index) return pd.Panel(fake_data) class FakePanelWithoutVolumeBacktestDatasource(object): def __init__(self, sids, properties): pass def get_data(self, sids, start, end): index = pd.date_range(start, end, tz=pytz.utc) fake_data = {} for sid in sids: fake_data[sid] = pd.DataFrame( {field: [random.random()] * len(index) for field in ['price', 'low', 'high']}, index=index) return pd.Panel(fake_data) class FakeLiveDatasource(object): def __init__(self, sids, properties): pass @property def mapping(self): return { 'live': True } def get_data(self, sids, start, end): return pd.DataFrame() class DatafeedUtilsTestCase(unittest.TestCase): def setUp(self): dna.test_utils.setup_logger(self) self.fake_sid = 'fake_sid' self.fake_one_sid_series = pd.Series( {key: random.random() for key in ['low', 'close']}) self.fake_multiple_sids_series = pd.Series( {key: random.random() for key in ['goog', 'fake_sid']}) self.fake_multiple_sids_df = pd.DataFrame( {key: {'price': random.random(), 'close': 0.3} for key in ['goog', 'fake_sid']}) self.fake_date = dt.datetime(2013, 1, 1) def tearDown(self): dna.test_utils.teardown_logger(self) @nottest def _check_event(self, event): self.assertIsInstance(event, dict) self.assertIn('volume', event) self.assertIn('dt', event) eq_(event['dt'], self.fake_date) eq_(event['sid'], self.fake_sid) def test_build_safe_event_without_volume(self): partial_event = self.fake_one_sid_series.to_dict() event = datafeed._build_safe_event( partial_event, self.fake_date, self.fake_sid) self._check_event(event) for field in self.fake_one_sid_series.index: self.assertIn(field, event.keys()) def test_build_safe_event_with_volume(self): partial_event = self.fake_one_sid_series.to_dict() partial_event.update({'volume': 12034}) event = datafeed._build_safe_event( partial_event, self.fake_date, self.fake_sid) self._check_event(event) for field in self.fake_one_sid_series.index: self.assertIn(field, event.keys()) @raises(AttributeError) def test_wrong_data_type(self): wrong_type = bool datafeed._build_safe_event(wrong_type, self.fake_date, self.fake_sid) def test_check_data_modules(self): end = self.fake_date + pd.datetools.MonthBegin(6) ok_(datafeed._check_data_modules( 'backtest.module', None, self.fake_date, end)) @raises(InvalidDatafeed) def test_check_data_modules_all_nones(self): end = self.fake_date + pd.datetools.MonthBegin(6) datafeed._check_data_modules(None, None, self.fake_date, end) class HybridDataFactoryTestCase(unittest.TestCase): def setUp(self): dna.test_utils.setup_logger(self) self.test_index = pd.date_range( '2012/01/01', '2012/01/7', tz=pytz.utc) self.test_universe = 'forex,5' self.market = Market() self.market.parse_universe_description(self.test_universe) self.test_sids = self.market.sids def tearDown(self): dna.test_utils.teardown_logger(self) @nottest def _check_datasource(self, source): ok_((source.index == self.test_index).all()) eq_(source.start, self.test_index[0]) eq_(source.end, self.test_index[-1]) eq_(source.sids, self.test_sids) self.assertIsNone(source._raw_data) eq_(source.arg_string, source.instance_hash) eq_(source.event_type, 4) ok_(hasattr(source, 'log')) self.assertFalse(source._is_live) @raises(InvalidDatafeed) def test_data_source_without_modules(self): config = { 'sids': self.test_sids, 'index': self.test_index } datafeed.HybridDataFactory(**config) @raises(InvalidDatafeed) def test_data_source_invalid_index(self): config = { 'sids': self.test_sids, 'index': bool } datafeed.HybridDataFactory(**config) def test_minimal_data_source(self): source = datafeed.HybridDataFactory( universe=self.market, index=self.test_index, backtest=FakeBacktestDatasource) self._check_datasource(source) def test_hybrid_mapping(self): source = datafeed.HybridDataFactory( universe=self.market, index=self.test_index, backtest=FakeBacktestDatasource, live=FakeLiveDatasource) self.assertIn('backtest', source.mapping) source._is_live = True self.assertIn('live', source.mapping) # TODO Test Live data sources class SpecificMarketDataFactoryTestCase(unittest.TestCase): def setUp(self): dna.test_utils.setup_logger(self) self.test_index = pd.date_range( '2012/01/01', '2012/01/7', tz=pytz.utc) def tearDown(self): dna.test_utils.teardown_logger(self) def test_dataframe_forex_backtest_data_generation(self): test_universe = 'forex,5' market = Market() market.parse_universe_description(test_universe) source = datafeed.HybridDataFactory( universe=market, index=self.test_index, backtest=FakeBacktestDatasource) total_rows = 0 for row in source.raw_data: if not total_rows: self.assertListEqual( sorted(row.keys()), sorted(['dt', 'price', 'sid', 'volume'])) total_rows += 1 eq_(total_rows, 2 * len(self.test_index) * len(market.sids)) def test_dataframe_cac40_backtest_data_generation(self): test_universe = 'stocks:paris:cac40' market = Market() market.parse_universe_description(test_universe) source = datafeed.HybridDataFactory( universe=market, index=self.test_index, backtest=FakeBacktestDatasource) total_rows = 0 for row in source.raw_data: if not total_rows: self.assertListEqual( sorted(row.keys()), sorted(['dt', 'price', 'sid', 'volume'])) total_rows += 1 eq_(total_rows, len(self.test_index) * len(market.sids)) def test_panel_cac40_backtest_data_generation(self): test_universe = 'stocks:paris:cac40' market = Market() market.parse_universe_description(test_universe) source = datafeed.HybridDataFactory( universe=market, index=self.test_index, backtest=FakePanelBacktestDatasource) total_rows = 0 for row in source.raw_data: if not total_rows: self.assertListEqual( sorted(row.keys()), sorted(['dt', 'price', 'low', 'high', 'sid', 'volume'])) total_rows += 1 eq_(total_rows, len(self.test_index) * len(market.sids)) def test_panel_without_volume_cac40_backtest_data_generation(self): test_universe = 'stocks:paris:cac40,5' market = Market() market.parse_universe_description(test_universe) source = datafeed.HybridDataFactory( universe=market, index=self.test_index, backtest=FakePanelWithoutVolumeBacktestDatasource) total_rows = 0 for row in source.raw_data: if not total_rows: self.assertListEqual( sorted(row.keys()), sorted(['dt', 'price', 'low', 'high', 'sid', 'volume'])) total_rows += 1 eq_(total_rows, len(self.test_index) * len(market.sids))
33.023973
79
0.606139
import unittest from nose.tools import raises, ok_, eq_, nottest import random import pytz import datetime as dt import pandas as pd import intuition.api.datafeed as datafeed from intuition.data.universe import Market from intuition.errors import InvalidDatafeed import dna.test_utils class FakeBacktestDatasource(object): def __init__(self, sids, properties): pass @property def mapping(self): return { 'backtest': (lambda x: True, 'sid'), 'dt': (lambda x: x, 'dt'), 'sid': (lambda x: x, 'sid'), 'price': (float, 'price'), 'volume': (int, 'volume'), } def get_data(self, sids, start, end): index = pd.date_range(start, end, tz=pytz.utc) return pd.DataFrame({sid: [random.random()] * len(index) for sid in sids}, index=index) class FakePanelBacktestDatasource(object): def __init__(self, sids, properties): pass @property def mapping(self): return { 'backtest': (lambda x: True, 'sid'), 'dt': (lambda x: x, 'dt'), 'sid': (lambda x: x, 'sid'), 'price': (float, 'price'), 'low': (float, 'low'), 'high': (float, 'high'), 'volume': (int, 'volume'), } def get_data(self, sids, start, end): index = pd.date_range(start, end, tz=pytz.utc) fake_data = {} for sid in sids: fake_data[sid] = pd.DataFrame( {field: [random.random()] * len(index) for field in ['price', 'low', 'high', 'volume']}, index=index) return pd.Panel(fake_data) class FakePanelWithoutVolumeBacktestDatasource(object): def __init__(self, sids, properties): pass def get_data(self, sids, start, end): index = pd.date_range(start, end, tz=pytz.utc) fake_data = {} for sid in sids: fake_data[sid] = pd.DataFrame( {field: [random.random()] * len(index) for field in ['price', 'low', 'high']}, index=index) return pd.Panel(fake_data) class FakeLiveDatasource(object): def __init__(self, sids, properties): pass @property def mapping(self): return { 'live': True } def get_data(self, sids, start, end): return pd.DataFrame() class DatafeedUtilsTestCase(unittest.TestCase): def setUp(self): dna.test_utils.setup_logger(self) self.fake_sid = 'fake_sid' self.fake_one_sid_series = pd.Series( {key: random.random() for key in ['low', 'close']}) self.fake_multiple_sids_series = pd.Series( {key: random.random() for key in ['goog', 'fake_sid']}) self.fake_multiple_sids_df = pd.DataFrame( {key: {'price': random.random(), 'close': 0.3} for key in ['goog', 'fake_sid']}) self.fake_date = dt.datetime(2013, 1, 1) def tearDown(self): dna.test_utils.teardown_logger(self) @nottest def _check_event(self, event): self.assertIsInstance(event, dict) self.assertIn('volume', event) self.assertIn('dt', event) eq_(event['dt'], self.fake_date) eq_(event['sid'], self.fake_sid) def test_build_safe_event_without_volume(self): partial_event = self.fake_one_sid_series.to_dict() event = datafeed._build_safe_event( partial_event, self.fake_date, self.fake_sid) self._check_event(event) for field in self.fake_one_sid_series.index: self.assertIn(field, event.keys()) def test_build_safe_event_with_volume(self): partial_event = self.fake_one_sid_series.to_dict() partial_event.update({'volume': 12034}) event = datafeed._build_safe_event( partial_event, self.fake_date, self.fake_sid) self._check_event(event) for field in self.fake_one_sid_series.index: self.assertIn(field, event.keys()) @raises(AttributeError) def test_wrong_data_type(self): wrong_type = bool datafeed._build_safe_event(wrong_type, self.fake_date, self.fake_sid) def test_check_data_modules(self): end = self.fake_date + pd.datetools.MonthBegin(6) ok_(datafeed._check_data_modules( 'backtest.module', None, self.fake_date, end)) @raises(InvalidDatafeed) def test_check_data_modules_all_nones(self): end = self.fake_date + pd.datetools.MonthBegin(6) datafeed._check_data_modules(None, None, self.fake_date, end) class HybridDataFactoryTestCase(unittest.TestCase): def setUp(self): dna.test_utils.setup_logger(self) self.test_index = pd.date_range( '2012/01/01', '2012/01/7', tz=pytz.utc) self.test_universe = 'forex,5' self.market = Market() self.market.parse_universe_description(self.test_universe) self.test_sids = self.market.sids def tearDown(self): dna.test_utils.teardown_logger(self) @nottest def _check_datasource(self, source): ok_((source.index == self.test_index).all()) eq_(source.start, self.test_index[0]) eq_(source.end, self.test_index[-1]) eq_(source.sids, self.test_sids) self.assertIsNone(source._raw_data) eq_(source.arg_string, source.instance_hash) eq_(source.event_type, 4) ok_(hasattr(source, 'log')) self.assertFalse(source._is_live) @raises(InvalidDatafeed) def test_data_source_without_modules(self): config = { 'sids': self.test_sids, 'index': self.test_index } datafeed.HybridDataFactory(**config) @raises(InvalidDatafeed) def test_data_source_invalid_index(self): config = { 'sids': self.test_sids, 'index': bool } datafeed.HybridDataFactory(**config) def test_minimal_data_source(self): source = datafeed.HybridDataFactory( universe=self.market, index=self.test_index, backtest=FakeBacktestDatasource) self._check_datasource(source) def test_hybrid_mapping(self): source = datafeed.HybridDataFactory( universe=self.market, index=self.test_index, backtest=FakeBacktestDatasource, live=FakeLiveDatasource) self.assertIn('backtest', source.mapping) source._is_live = True self.assertIn('live', source.mapping) class SpecificMarketDataFactoryTestCase(unittest.TestCase): def setUp(self): dna.test_utils.setup_logger(self) self.test_index = pd.date_range( '2012/01/01', '2012/01/7', tz=pytz.utc) def tearDown(self): dna.test_utils.teardown_logger(self) def test_dataframe_forex_backtest_data_generation(self): test_universe = 'forex,5' market = Market() market.parse_universe_description(test_universe) source = datafeed.HybridDataFactory( universe=market, index=self.test_index, backtest=FakeBacktestDatasource) total_rows = 0 for row in source.raw_data: if not total_rows: self.assertListEqual( sorted(row.keys()), sorted(['dt', 'price', 'sid', 'volume'])) total_rows += 1 eq_(total_rows, 2 * len(self.test_index) * len(market.sids)) def test_dataframe_cac40_backtest_data_generation(self): test_universe = 'stocks:paris:cac40' market = Market() market.parse_universe_description(test_universe) source = datafeed.HybridDataFactory( universe=market, index=self.test_index, backtest=FakeBacktestDatasource) total_rows = 0 for row in source.raw_data: if not total_rows: self.assertListEqual( sorted(row.keys()), sorted(['dt', 'price', 'sid', 'volume'])) total_rows += 1 eq_(total_rows, len(self.test_index) * len(market.sids)) def test_panel_cac40_backtest_data_generation(self): test_universe = 'stocks:paris:cac40' market = Market() market.parse_universe_description(test_universe) source = datafeed.HybridDataFactory( universe=market, index=self.test_index, backtest=FakePanelBacktestDatasource) total_rows = 0 for row in source.raw_data: if not total_rows: self.assertListEqual( sorted(row.keys()), sorted(['dt', 'price', 'low', 'high', 'sid', 'volume'])) total_rows += 1 eq_(total_rows, len(self.test_index) * len(market.sids)) def test_panel_without_volume_cac40_backtest_data_generation(self): test_universe = 'stocks:paris:cac40,5' market = Market() market.parse_universe_description(test_universe) source = datafeed.HybridDataFactory( universe=market, index=self.test_index, backtest=FakePanelWithoutVolumeBacktestDatasource) total_rows = 0 for row in source.raw_data: if not total_rows: self.assertListEqual( sorted(row.keys()), sorted(['dt', 'price', 'low', 'high', 'sid', 'volume'])) total_rows += 1 eq_(total_rows, len(self.test_index) * len(market.sids))
true
true
1c3933380f57420b969ba2aa01d1a27d4b57408a
7,501
py
Python
synapse/rest/client/v1/directory.py
TheJJ/synapse
1032393dfb0c865fc540539dfe649e7b1a32037a
[ "Apache-2.0" ]
2
2021-05-14T19:05:03.000Z
2021-05-26T23:00:43.000Z
synapse/rest/client/v1/directory.py
TheJJ/synapse
1032393dfb0c865fc540539dfe649e7b1a32037a
[ "Apache-2.0" ]
null
null
null
synapse/rest/client/v1/directory.py
TheJJ/synapse
1032393dfb0c865fc540539dfe649e7b1a32037a
[ "Apache-2.0" ]
null
null
null
# -*- coding: utf-8 -*- # Copyright 2014-2016 OpenMarket 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. from twisted.internet import defer from synapse.api.errors import AuthError, SynapseError, Codes from synapse.types import RoomAlias from synapse.http.servlet import parse_json_object_from_request from .base import ClientV1RestServlet, client_path_patterns import logging logger = logging.getLogger(__name__) def register_servlets(hs, http_server): ClientDirectoryServer(hs).register(http_server) ClientDirectoryListServer(hs).register(http_server) ClientAppserviceDirectoryListServer(hs).register(http_server) class ClientDirectoryServer(ClientV1RestServlet): PATTERNS = client_path_patterns("/directory/room/(?P<room_alias>[^/]*)$") def __init__(self, hs): super(ClientDirectoryServer, self).__init__(hs) self.store = hs.get_datastore() self.handlers = hs.get_handlers() @defer.inlineCallbacks def on_GET(self, request, room_alias): room_alias = RoomAlias.from_string(room_alias) dir_handler = self.handlers.directory_handler res = yield dir_handler.get_association(room_alias) defer.returnValue((200, res)) @defer.inlineCallbacks def on_PUT(self, request, room_alias): content = parse_json_object_from_request(request) if "room_id" not in content: raise SynapseError(400, "Missing room_id key", errcode=Codes.BAD_JSON) logger.debug("Got content: %s", content) room_alias = RoomAlias.from_string(room_alias) logger.debug("Got room name: %s", room_alias.to_string()) room_id = content["room_id"] servers = content["servers"] if "servers" in content else None logger.debug("Got room_id: %s", room_id) logger.debug("Got servers: %s", servers) # TODO(erikj): Check types. room = yield self.store.get_room(room_id) if room is None: raise SynapseError(400, "Room does not exist") dir_handler = self.handlers.directory_handler try: # try to auth as a user requester = yield self.auth.get_user_by_req(request) try: user_id = requester.user.to_string() yield dir_handler.create_association( user_id, room_alias, room_id, servers ) yield dir_handler.send_room_alias_update_event( requester, user_id, room_id ) except SynapseError as e: raise e except Exception: logger.exception("Failed to create association") raise except AuthError: # try to auth as an application service service = yield self.auth.get_appservice_by_req(request) yield dir_handler.create_appservice_association( service, room_alias, room_id, servers ) logger.info( "Application service at %s created alias %s pointing to %s", service.url, room_alias.to_string(), room_id ) defer.returnValue((200, {})) @defer.inlineCallbacks def on_DELETE(self, request, room_alias): dir_handler = self.handlers.directory_handler try: service = yield self.auth.get_appservice_by_req(request) room_alias = RoomAlias.from_string(room_alias) yield dir_handler.delete_appservice_association( service, room_alias ) logger.info( "Application service at %s deleted alias %s", service.url, room_alias.to_string() ) defer.returnValue((200, {})) except AuthError: # fallback to default user behaviour if they aren't an AS pass requester = yield self.auth.get_user_by_req(request) user = requester.user room_alias = RoomAlias.from_string(room_alias) yield dir_handler.delete_association( requester, user.to_string(), room_alias ) logger.info( "User %s deleted alias %s", user.to_string(), room_alias.to_string() ) defer.returnValue((200, {})) class ClientDirectoryListServer(ClientV1RestServlet): PATTERNS = client_path_patterns("/directory/list/room/(?P<room_id>[^/]*)$") def __init__(self, hs): super(ClientDirectoryListServer, self).__init__(hs) self.store = hs.get_datastore() self.handlers = hs.get_handlers() @defer.inlineCallbacks def on_GET(self, request, room_id): room = yield self.store.get_room(room_id) if room is None: raise SynapseError(400, "Unknown room") defer.returnValue((200, { "visibility": "public" if room["is_public"] else "private" })) @defer.inlineCallbacks def on_PUT(self, request, room_id): requester = yield self.auth.get_user_by_req(request) content = parse_json_object_from_request(request) visibility = content.get("visibility", "public") yield self.handlers.directory_handler.edit_published_room_list( requester, room_id, visibility, ) defer.returnValue((200, {})) @defer.inlineCallbacks def on_DELETE(self, request, room_id): requester = yield self.auth.get_user_by_req(request) yield self.handlers.directory_handler.edit_published_room_list( requester, room_id, "private", ) defer.returnValue((200, {})) class ClientAppserviceDirectoryListServer(ClientV1RestServlet): PATTERNS = client_path_patterns( "/directory/list/appservice/(?P<network_id>[^/]*)/(?P<room_id>[^/]*)$" ) def __init__(self, hs): super(ClientAppserviceDirectoryListServer, self).__init__(hs) self.store = hs.get_datastore() self.handlers = hs.get_handlers() def on_PUT(self, request, network_id, room_id): content = parse_json_object_from_request(request) visibility = content.get("visibility", "public") return self._edit(request, network_id, room_id, visibility) def on_DELETE(self, request, network_id, room_id): return self._edit(request, network_id, room_id, "private") @defer.inlineCallbacks def _edit(self, request, network_id, room_id, visibility): requester = yield self.auth.get_user_by_req(request) if not requester.app_service: raise AuthError( 403, "Only appservices can edit the appservice published room list" ) yield self.handlers.directory_handler.edit_published_appservice_room_list( requester.app_service.id, network_id, room_id, visibility, ) defer.returnValue((200, {}))
33.337778
83
0.639781
from twisted.internet import defer from synapse.api.errors import AuthError, SynapseError, Codes from synapse.types import RoomAlias from synapse.http.servlet import parse_json_object_from_request from .base import ClientV1RestServlet, client_path_patterns import logging logger = logging.getLogger(__name__) def register_servlets(hs, http_server): ClientDirectoryServer(hs).register(http_server) ClientDirectoryListServer(hs).register(http_server) ClientAppserviceDirectoryListServer(hs).register(http_server) class ClientDirectoryServer(ClientV1RestServlet): PATTERNS = client_path_patterns("/directory/room/(?P<room_alias>[^/]*)$") def __init__(self, hs): super(ClientDirectoryServer, self).__init__(hs) self.store = hs.get_datastore() self.handlers = hs.get_handlers() @defer.inlineCallbacks def on_GET(self, request, room_alias): room_alias = RoomAlias.from_string(room_alias) dir_handler = self.handlers.directory_handler res = yield dir_handler.get_association(room_alias) defer.returnValue((200, res)) @defer.inlineCallbacks def on_PUT(self, request, room_alias): content = parse_json_object_from_request(request) if "room_id" not in content: raise SynapseError(400, "Missing room_id key", errcode=Codes.BAD_JSON) logger.debug("Got content: %s", content) room_alias = RoomAlias.from_string(room_alias) logger.debug("Got room name: %s", room_alias.to_string()) room_id = content["room_id"] servers = content["servers"] if "servers" in content else None logger.debug("Got room_id: %s", room_id) logger.debug("Got servers: %s", servers) room = yield self.store.get_room(room_id) if room is None: raise SynapseError(400, "Room does not exist") dir_handler = self.handlers.directory_handler try: requester = yield self.auth.get_user_by_req(request) try: user_id = requester.user.to_string() yield dir_handler.create_association( user_id, room_alias, room_id, servers ) yield dir_handler.send_room_alias_update_event( requester, user_id, room_id ) except SynapseError as e: raise e except Exception: logger.exception("Failed to create association") raise except AuthError: service = yield self.auth.get_appservice_by_req(request) yield dir_handler.create_appservice_association( service, room_alias, room_id, servers ) logger.info( "Application service at %s created alias %s pointing to %s", service.url, room_alias.to_string(), room_id ) defer.returnValue((200, {})) @defer.inlineCallbacks def on_DELETE(self, request, room_alias): dir_handler = self.handlers.directory_handler try: service = yield self.auth.get_appservice_by_req(request) room_alias = RoomAlias.from_string(room_alias) yield dir_handler.delete_appservice_association( service, room_alias ) logger.info( "Application service at %s deleted alias %s", service.url, room_alias.to_string() ) defer.returnValue((200, {})) except AuthError: pass requester = yield self.auth.get_user_by_req(request) user = requester.user room_alias = RoomAlias.from_string(room_alias) yield dir_handler.delete_association( requester, user.to_string(), room_alias ) logger.info( "User %s deleted alias %s", user.to_string(), room_alias.to_string() ) defer.returnValue((200, {})) class ClientDirectoryListServer(ClientV1RestServlet): PATTERNS = client_path_patterns("/directory/list/room/(?P<room_id>[^/]*)$") def __init__(self, hs): super(ClientDirectoryListServer, self).__init__(hs) self.store = hs.get_datastore() self.handlers = hs.get_handlers() @defer.inlineCallbacks def on_GET(self, request, room_id): room = yield self.store.get_room(room_id) if room is None: raise SynapseError(400, "Unknown room") defer.returnValue((200, { "visibility": "public" if room["is_public"] else "private" })) @defer.inlineCallbacks def on_PUT(self, request, room_id): requester = yield self.auth.get_user_by_req(request) content = parse_json_object_from_request(request) visibility = content.get("visibility", "public") yield self.handlers.directory_handler.edit_published_room_list( requester, room_id, visibility, ) defer.returnValue((200, {})) @defer.inlineCallbacks def on_DELETE(self, request, room_id): requester = yield self.auth.get_user_by_req(request) yield self.handlers.directory_handler.edit_published_room_list( requester, room_id, "private", ) defer.returnValue((200, {})) class ClientAppserviceDirectoryListServer(ClientV1RestServlet): PATTERNS = client_path_patterns( "/directory/list/appservice/(?P<network_id>[^/]*)/(?P<room_id>[^/]*)$" ) def __init__(self, hs): super(ClientAppserviceDirectoryListServer, self).__init__(hs) self.store = hs.get_datastore() self.handlers = hs.get_handlers() def on_PUT(self, request, network_id, room_id): content = parse_json_object_from_request(request) visibility = content.get("visibility", "public") return self._edit(request, network_id, room_id, visibility) def on_DELETE(self, request, network_id, room_id): return self._edit(request, network_id, room_id, "private") @defer.inlineCallbacks def _edit(self, request, network_id, room_id, visibility): requester = yield self.auth.get_user_by_req(request) if not requester.app_service: raise AuthError( 403, "Only appservices can edit the appservice published room list" ) yield self.handlers.directory_handler.edit_published_appservice_room_list( requester.app_service.id, network_id, room_id, visibility, ) defer.returnValue((200, {}))
true
true
1c39336bd345b134235dc43a104eb61b2d17024f
2,809
py
Python
keystone/contrib/endpoint_filter/backends/catalog_sql.py
ISCAS-VDI/keystone
11af181c06d78026c89a873f62931558e80f3192
[ "Apache-2.0" ]
null
null
null
keystone/contrib/endpoint_filter/backends/catalog_sql.py
ISCAS-VDI/keystone
11af181c06d78026c89a873f62931558e80f3192
[ "Apache-2.0" ]
null
null
null
keystone/contrib/endpoint_filter/backends/catalog_sql.py
ISCAS-VDI/keystone
11af181c06d78026c89a873f62931558e80f3192
[ "Apache-2.0" ]
null
null
null
# Copyright 2013 OpenStack Foundation # # 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 oslo_config import cfg from keystone.catalog.backends import sql from keystone.common import dependency from keystone.common import utils CONF = cfg.CONF @dependency.requires('catalog_api') class EndpointFilterCatalog(sql.Catalog): def get_v3_catalog(self, user_id, project_id): substitutions = dict(CONF.items()) substitutions.update({ 'tenant_id': project_id, 'project_id': project_id, 'user_id': user_id, }) services = {} dict_of_endpoint_refs = (self.catalog_api. list_endpoints_for_project(project_id)) if (not dict_of_endpoint_refs and CONF.endpoint_filter.return_all_endpoints_if_no_filter): return super(EndpointFilterCatalog, self).get_v3_catalog( user_id, project_id) for endpoint_id, endpoint in dict_of_endpoint_refs.items(): if not endpoint['enabled']: # Skip disabled endpoints. continue service_id = endpoint['service_id'] services.setdefault( service_id, self.get_service(service_id)) service = services[service_id] del endpoint['service_id'] del endpoint['enabled'] del endpoint['legacy_endpoint_id'] # Include deprecated region for backwards compatibility endpoint['region'] = endpoint['region_id'] endpoint['url'] = utils.format_url( endpoint['url'], substitutions) # populate filtered endpoints if 'endpoints' in services[service_id]: service['endpoints'].append(endpoint) else: service['endpoints'] = [endpoint] # format catalog catalog = [] for service_id, service in services.items(): formatted_service = {} formatted_service['id'] = service['id'] formatted_service['type'] = service['type'] formatted_service['name'] = service['name'] formatted_service['endpoints'] = service['endpoints'] catalog.append(formatted_service) return catalog
36.012821
75
0.632253
from oslo_config import cfg from keystone.catalog.backends import sql from keystone.common import dependency from keystone.common import utils CONF = cfg.CONF @dependency.requires('catalog_api') class EndpointFilterCatalog(sql.Catalog): def get_v3_catalog(self, user_id, project_id): substitutions = dict(CONF.items()) substitutions.update({ 'tenant_id': project_id, 'project_id': project_id, 'user_id': user_id, }) services = {} dict_of_endpoint_refs = (self.catalog_api. list_endpoints_for_project(project_id)) if (not dict_of_endpoint_refs and CONF.endpoint_filter.return_all_endpoints_if_no_filter): return super(EndpointFilterCatalog, self).get_v3_catalog( user_id, project_id) for endpoint_id, endpoint in dict_of_endpoint_refs.items(): if not endpoint['enabled']: continue service_id = endpoint['service_id'] services.setdefault( service_id, self.get_service(service_id)) service = services[service_id] del endpoint['service_id'] del endpoint['enabled'] del endpoint['legacy_endpoint_id'] endpoint['region'] = endpoint['region_id'] endpoint['url'] = utils.format_url( endpoint['url'], substitutions) if 'endpoints' in services[service_id]: service['endpoints'].append(endpoint) else: service['endpoints'] = [endpoint] catalog = [] for service_id, service in services.items(): formatted_service = {} formatted_service['id'] = service['id'] formatted_service['type'] = service['type'] formatted_service['name'] = service['name'] formatted_service['endpoints'] = service['endpoints'] catalog.append(formatted_service) return catalog
true
true
1c3933738fb207211f83be29cc0b87ab51a2cb7f
133
py
Python
001-simple-tr/reahl/simple-tr/etc/web.config.py
craig-reahl/python-web-framework-comparison
30c9d08f5c87b5b12bda7158108398092d6cad31
[ "Apache-2.0" ]
null
null
null
001-simple-tr/reahl/simple-tr/etc/web.config.py
craig-reahl/python-web-framework-comparison
30c9d08f5c87b5b12bda7158108398092d6cad31
[ "Apache-2.0" ]
null
null
null
001-simple-tr/reahl/simple-tr/etc/web.config.py
craig-reahl/python-web-framework-comparison
30c9d08f5c87b5b12bda7158108398092d6cad31
[ "Apache-2.0" ]
1
2018-10-23T07:46:51.000Z
2018-10-23T07:46:51.000Z
from __future__ import print_function, unicode_literals, absolute_import, division from simple_tr import MyUI web.site_root = MyUI
22.166667
82
0.842105
from __future__ import print_function, unicode_literals, absolute_import, division from simple_tr import MyUI web.site_root = MyUI
true
true
1c39356ff5ad1145eb7a03dbf131079e7de162ec
907
py
Python
taotao-cloud-python/taotao-cloud-oldboy/day59-student-manager-system-form/day59 - 1/day59/urls.py
shuigedeng/taotao-cloud-paren
3d281b919490f7cbee4520211e2eee5da7387564
[ "Apache-2.0" ]
47
2021-04-13T10:32:13.000Z
2022-03-31T10:30:30.000Z
taotao-cloud-python/taotao-cloud-oldboy/day59-student-manager-system-form/day59 - 1/day59/urls.py
shuigedeng/taotao-cloud-paren
3d281b919490f7cbee4520211e2eee5da7387564
[ "Apache-2.0" ]
1
2021-11-01T07:41:04.000Z
2021-11-01T07:41:10.000Z
taotao-cloud-python/taotao-cloud-oldboy/day59-student-manager-system-form/day59 - 1/day59/urls.py
shuigedeng/taotao-cloud-paren
3d281b919490f7cbee4520211e2eee5da7387564
[ "Apache-2.0" ]
21
2021-04-13T10:32:17.000Z
2022-03-26T07:43:22.000Z
"""day59 URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/1.10/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: url(r'^$', views.home, name='home') Class-based views 1. Add an import: from other_app.views import Home 2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home') Including another URLconf 1. Import the include() function: from django.conf.urls import url, include 2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls')) """ from django.conf.urls import url from django.contrib import admin from app01 import views urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^users/', views.users), url(r'^add_user/', views.add_user), url(r'^edit_user-(\d+)/', views.edit_user), ]
36.28
79
0.692393
from django.conf.urls import url from django.contrib import admin from app01 import views urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^users/', views.users), url(r'^add_user/', views.add_user), url(r'^edit_user-(\d+)/', views.edit_user), ]
true
true
1c3935bd382124999fb78f579dec7c4c42f6c9cd
685
py
Python
pysparktest/test_data_frame.py
Joe-Heffer-Shef/pyspark-bessemer
ab78a96fd7fc607824a95a0b502d4ffa1bcc1899
[ "MIT" ]
null
null
null
pysparktest/test_data_frame.py
Joe-Heffer-Shef/pyspark-bessemer
ab78a96fd7fc607824a95a0b502d4ffa1bcc1899
[ "MIT" ]
4
2021-04-08T09:38:59.000Z
2021-04-08T10:03:27.000Z
pysparktest/test_data_frame.py
Joe-Heffer-Shef/pyspark-bessemer
ab78a96fd7fc607824a95a0b502d4ffa1bcc1899
[ "MIT" ]
null
null
null
""" PySpark "Hello World" example Based on the quick-start guide in the docs https://spark.apache.org/docs/latest/api/python/getting_started/quickstart.html """ import datetime import random import uuid from pyspark.sql import SparkSession def test_data_frame(session: SparkSession): # Create data frame df = session.createDataFrame([ # Generate some random data (i, random.random(), uuid.uuid4().hex, datetime.date(1970, 1, 1) + datetime.timedelta(days=i), datetime.datetime(1970, 1, 1, 12) + datetime.timedelta(hours=i)) for i in range(1000)], schema='a long, b double, c string, d date, e timestamp') df.collect()
26.346154
79
0.681752
import datetime import random import uuid from pyspark.sql import SparkSession def test_data_frame(session: SparkSession): df = session.createDataFrame([ (i, random.random(), uuid.uuid4().hex, datetime.date(1970, 1, 1) + datetime.timedelta(days=i), datetime.datetime(1970, 1, 1, 12) + datetime.timedelta(hours=i)) for i in range(1000)], schema='a long, b double, c string, d date, e timestamp') df.collect()
true
true
1c3939db7a445b27d04bce0f50544a42aa0b8875
1,881
py
Python
stanford_postagger/java.py
banyh/PyStanfordSegmenter
2165a218df87f00f84c461a41ca77a86eb85687b
[ "MIT" ]
16
2017-03-25T07:42:51.000Z
2022-03-12T09:33:50.000Z
stanford_postagger/java.py
banyh/PyStanfordSegmenter
2165a218df87f00f84c461a41ca77a86eb85687b
[ "MIT" ]
1
2017-09-06T02:46:29.000Z
2017-09-21T01:56:11.000Z
stanford_postagger/java.py
banyh/PyStanfordSegmenter
2165a218df87f00f84c461a41ca77a86eb85687b
[ "MIT" ]
5
2017-04-13T04:32:53.000Z
2018-03-17T06:09:27.000Z
from jpype import startJVM, getDefaultJVMPath, shutdownJVM, java, JPackage, isJVMStarted from os.path import join, dirname from platform import system class Postagger(object): def __init__(self, lang='zh'): if system() == 'Linux': sep = ':' else: sep = ';' # Windows pwd = dirname(__file__) main_dir = join(pwd, 'pos') if not isJVMStarted(): startJVM(getDefaultJVMPath(), "-ea", "-Djava.class.path=" + sep.join([main_dir, join(main_dir, 'stanford-postagger.jar'), join(pwd, '..', 'stanford_segmenter', 'seg'), join(pwd, '..', 'stanford_segmenter', 'seg', 'stanford-segmenter-3.6.0.jar'), join(main_dir, 'lib', 'slf4j-api.jar'), join(main_dir, 'lib', 'slf4j-simple.jar')])) # --------- for debugging ----------- print('JVM classpath:') cl = java.lang.ClassLoader.getSystemClassLoader() for url in cl.getURLs(): print(url.getFile()) # --------- end debugging ----------- maxent = JPackage('edu').stanford.nlp.tagger.maxent if lang == 'zh': self.postagger = maxent.MaxentTagger('models/chinese-distsim.tagger') elif lang == 'en': self.postagger = maxent.MaxentTagger('models/english-bidirectional-distsim.tagger') elif lang == 'fr': self.postagger = maxent.MaxentTagger('models/french.tagger') elif lang == 'de': self.postagger = maxent.MaxentTagger('models/german-dewac.tagger') elif lang == 'es': self.postagger = maxent.MaxentTagger('models/spanish-distsim.tagger') else: raise ValueError('Not Support Language: {}'.format(lang)) def postag(self, segmented_sent): return self.postagger.tagTokenizedString(segmented_sent)
44.785714
105
0.577352
from jpype import startJVM, getDefaultJVMPath, shutdownJVM, java, JPackage, isJVMStarted from os.path import join, dirname from platform import system class Postagger(object): def __init__(self, lang='zh'): if system() == 'Linux': sep = ':' else: sep = ';' pwd = dirname(__file__) main_dir = join(pwd, 'pos') if not isJVMStarted(): startJVM(getDefaultJVMPath(), "-ea", "-Djava.class.path=" + sep.join([main_dir, join(main_dir, 'stanford-postagger.jar'), join(pwd, '..', 'stanford_segmenter', 'seg'), join(pwd, '..', 'stanford_segmenter', 'seg', 'stanford-segmenter-3.6.0.jar'), join(main_dir, 'lib', 'slf4j-api.jar'), join(main_dir, 'lib', 'slf4j-simple.jar')])) print('JVM classpath:') cl = java.lang.ClassLoader.getSystemClassLoader() for url in cl.getURLs(): print(url.getFile()) maxent = JPackage('edu').stanford.nlp.tagger.maxent if lang == 'zh': self.postagger = maxent.MaxentTagger('models/chinese-distsim.tagger') elif lang == 'en': self.postagger = maxent.MaxentTagger('models/english-bidirectional-distsim.tagger') elif lang == 'fr': self.postagger = maxent.MaxentTagger('models/french.tagger') elif lang == 'de': self.postagger = maxent.MaxentTagger('models/german-dewac.tagger') elif lang == 'es': self.postagger = maxent.MaxentTagger('models/spanish-distsim.tagger') else: raise ValueError('Not Support Language: {}'.format(lang)) def postag(self, segmented_sent): return self.postagger.tagTokenizedString(segmented_sent)
true
true
1c393ad1a362a095cadd38c4c328787fc28e2873
5,994
py
Python
stuff7/utils/parsers/tests.py
Stuff7/stuff7
c4210ad99c7d745ded3742a645cc9173243946b1
[ "MIT" ]
null
null
null
stuff7/utils/parsers/tests.py
Stuff7/stuff7
c4210ad99c7d745ded3742a645cc9173243946b1
[ "MIT" ]
null
null
null
stuff7/utils/parsers/tests.py
Stuff7/stuff7
c4210ad99c7d745ded3742a645cc9173243946b1
[ "MIT" ]
null
null
null
from datetime import datetime as dt from datetime import timezone as tz from datetime import timedelta as td from calendar import isleap from unittest import TestCase from pytz import timezone from . import TimeDeltaParser, TimezoneParser class TimeDeltaParserTestCase(TestCase): def setUp(self): self.delta = TimeDeltaParser() self.timeunits = ("years", "months", "days", "hours", "minutes", "seconds", "microseconds") self.now = dt.now(tz.utc) self.msg = ( "{channel} <{years} year{years(s)}>, " "<{months} month{months(s)}>, <{days} day{days(s)}>, " "<{hours} hour{hours(s)}>, <{minutes} minute{minutes(s)}> " "and <{seconds} second{seconds(s)}>" ) self.date = self.now - td(days=self.leap(777), hours=15, minutes=24, seconds=33) self.strid = "someID" def test_parse_ok(self): parsedresult = self.delta.parse(self.msg, self.now, self.date) self.assertEqual(parsedresult, "{channel} 2 years, 1 month, 16 days, 15 hours, 24 minutes and 33 seconds") parsedresult = self.delta.parse(self.msg, self.now, self.now-td(days=self.leap(365), seconds=33)) self.assertEqual(parsedresult, "{channel} 1 year and 33 seconds") parsedresult = self.delta.parse(( "{channel} <{years} year{years(s)}>, " "<{months} month{months(s)}>, " "<{days} day{days(s)}> and " "[{hours:02d}:{minutes:02d}:{seconds:02d} hours]"), self.now, self.now-td(days=self.leap(365), seconds=33) ) self.assertEqual(parsedresult, "{channel} 1 year and 00:00:33 hours") parsedresult = self.delta.parse(f"Escape \<block\> identifiers like \[this\].", self.now, self.date) self.assertEqual(parsedresult, "Escape <block> identifiers like [this].") def test_parse_invalid_format(self): parsedresult = self.delta.parse("Can't use single {", self.now, self.date) self.assertIn("Invalid string", parsedresult) parsedresult = self.delta.parse("Can't use single } either", self.now, self.date) self.assertIn("Invalid string", parsedresult) def test_parse_parser_error(self): parsedresult = self.delta.parse("[You should close your blocks..", self.now, self.date) self.assertIn("Expecting ].", parsedresult) parsedresult = self.delta.parse("Closing inexistent blocks isn't allowed..>", self.now, self.date) self.assertIn("Single > is not allowed.", parsedresult) def test_timediff(self): parsedobj = self.delta.timediff(self.now, self.date) self.assertEqual(tuple(parsedobj), self.timeunits) self.assertEqual(tuple(parsedobj.values()), (2, 1, 16, 15, 24, 33, 0)) def test_loop(self): self.assertEqual(len(tuple(x for x in self.delta.loop("Some string without any blocks."))), 2, msg="Beginning and end of string are always shown after parsed is done.") parsed = tuple(x for x in self.delta.loop(self.msg)) self.assertTrue(all(type(obj) is self.delta.Block for obj in parsed[1:-1]), msg="Anything in between the parsed result is a block.") def test_split_ok(self): parts = self.delta.split("<Some block [inner [blocks]] and an \[escaped block> and <\<another> [block\>]") self.assertEqual(len(parts), 7, msg="Returns 3 blocks with connectors 3*2=6. And a string. So 3*2+1=7 total parts.") self.assertEqual(parts[1], "<Some block [inner [blocks]] and an [escaped block>") self.assertEqual(parts[3], "<<another>") self.assertEqual(parts[5], "[block>]") def test_split_error(self): with self.assertRaises(ValueError) as e: self.delta.split("<Some invalid block>>") self.assertEqual("Single > is not allowed.", str(e.exception)) with self.assertRaises(ValueError) as e: self.delta.split("[Some invalid block") self.assertEqual("Expecting ].", str(e.exception)) def leap(self, number): return number+1 if isleap(self.now.year) else number class TimezoneParserTestCase(TestCase): def setUp(self): self.tz = TimezoneParser() self.utc = dt.now(tz.utc) self.common_tzones = { "gmt": self.tzone("iceland"), "aoe": self.tzone("Etc/GMT+12"), "pst_us": self.tzone("America/Los_Angeles"), "pdt_us": self.tzone("America/Los_Angeles"), "cst": self.tzone("America/Chicago"), "cdt": self.tzone("America/Chicago"), "ast": self.tzone("America/Halifax"), "adt": self.tzone("America/Halifax"), "est": self.tzone("America/New_York"), "edt": self.tzone("America/New_York"), "mst": self.tzone("America/Edmonton"), "mdt": self.tzone("America/Edmonton"), "akst": self.tzone("America/Anchorage"), "akdt": self.tzone("America/Anchorage"), "aest": self.tzone("Australia/Sydney"), "acst": self.tzone("Australia/Adelaide"), "acdt": self.tzone("Australia/Adelaide"), "awst": self.tzone("Australia/Perth"), "bst": self.tzone("Europe/London"), "ist": self.tzone("Europe/Dublin"), "wet": self.tzone("Europe/Lisbon"), "west": self.tzone("Europe/Lisbon"), "cet": self.tzone("Europe/Brussels"), "cest": self.tzone("Europe/Brussels"), "eet": self.tzone("Europe/Bucharest"), "eest": self.tzone("Europe/Bucharest"), } self.tzoffsets = { **{ str(offset*-1): self.tzone(f"Etc/GMT{offset}") for offset in range(-14, 0) }, **{ str(offset*-1): self.tzone(f"Etc/GMT+{offset}") for offset in range(0, 12+1) }, } def test_parse_common_timezones(self): for abbv, date in self.common_tzones.items(): guess_tzone = self.tz.parsetz(*abbv.split("_")[:2]) guess_date = self.utc.astimezone(guess_tzone) self.assertEqual(guess_date, date, msg="Parses common timezone correctly.") def test_find_by_offset(self): for offset, date in self.tzoffsets.items(): self.tz.timezone = offset guess_date = self.tzone(self.tz.find_by_offset()) self.assertEqual(guess_date, date, msg="Parses all timezone offsets.") def tzone(self, tz): return self.utc.astimezone(timezone(tz))
43.434783
110
0.66016
from datetime import datetime as dt from datetime import timezone as tz from datetime import timedelta as td from calendar import isleap from unittest import TestCase from pytz import timezone from . import TimeDeltaParser, TimezoneParser class TimeDeltaParserTestCase(TestCase): def setUp(self): self.delta = TimeDeltaParser() self.timeunits = ("years", "months", "days", "hours", "minutes", "seconds", "microseconds") self.now = dt.now(tz.utc) self.msg = ( "{channel} <{years} year{years(s)}>, " "<{months} month{months(s)}>, <{days} day{days(s)}>, " "<{hours} hour{hours(s)}>, <{minutes} minute{minutes(s)}> " "and <{seconds} second{seconds(s)}>" ) self.date = self.now - td(days=self.leap(777), hours=15, minutes=24, seconds=33) self.strid = "someID" def test_parse_ok(self): parsedresult = self.delta.parse(self.msg, self.now, self.date) self.assertEqual(parsedresult, "{channel} 2 years, 1 month, 16 days, 15 hours, 24 minutes and 33 seconds") parsedresult = self.delta.parse(self.msg, self.now, self.now-td(days=self.leap(365), seconds=33)) self.assertEqual(parsedresult, "{channel} 1 year and 33 seconds") parsedresult = self.delta.parse(( "{channel} <{years} year{years(s)}>, " "<{months} month{months(s)}>, " "<{days} day{days(s)}> and " "[{hours:02d}:{minutes:02d}:{seconds:02d} hours]"), self.now, self.now-td(days=self.leap(365), seconds=33) ) self.assertEqual(parsedresult, "{channel} 1 year and 00:00:33 hours") parsedresult = self.delta.parse(f"Escape \<block\> identifiers like \[this\].", self.now, self.date) self.assertEqual(parsedresult, "Escape <block> identifiers like [this].") def test_parse_invalid_format(self): parsedresult = self.delta.parse("Can't use single {", self.now, self.date) self.assertIn("Invalid string", parsedresult) parsedresult = self.delta.parse("Can't use single } either", self.now, self.date) self.assertIn("Invalid string", parsedresult) def test_parse_parser_error(self): parsedresult = self.delta.parse("[You should close your blocks..", self.now, self.date) self.assertIn("Expecting ].", parsedresult) parsedresult = self.delta.parse("Closing inexistent blocks isn't allowed..>", self.now, self.date) self.assertIn("Single > is not allowed.", parsedresult) def test_timediff(self): parsedobj = self.delta.timediff(self.now, self.date) self.assertEqual(tuple(parsedobj), self.timeunits) self.assertEqual(tuple(parsedobj.values()), (2, 1, 16, 15, 24, 33, 0)) def test_loop(self): self.assertEqual(len(tuple(x for x in self.delta.loop("Some string without any blocks."))), 2, msg="Beginning and end of string are always shown after parsed is done.") parsed = tuple(x for x in self.delta.loop(self.msg)) self.assertTrue(all(type(obj) is self.delta.Block for obj in parsed[1:-1]), msg="Anything in between the parsed result is a block.") def test_split_ok(self): parts = self.delta.split("<Some block [inner [blocks]] and an \[escaped block> and <\<another> [block\>]") self.assertEqual(len(parts), 7, msg="Returns 3 blocks with connectors 3*2=6. And a string. So 3*2+1=7 total parts.") self.assertEqual(parts[1], "<Some block [inner [blocks]] and an [escaped block>") self.assertEqual(parts[3], "<<another>") self.assertEqual(parts[5], "[block>]") def test_split_error(self): with self.assertRaises(ValueError) as e: self.delta.split("<Some invalid block>>") self.assertEqual("Single > is not allowed.", str(e.exception)) with self.assertRaises(ValueError) as e: self.delta.split("[Some invalid block") self.assertEqual("Expecting ].", str(e.exception)) def leap(self, number): return number+1 if isleap(self.now.year) else number class TimezoneParserTestCase(TestCase): def setUp(self): self.tz = TimezoneParser() self.utc = dt.now(tz.utc) self.common_tzones = { "gmt": self.tzone("iceland"), "aoe": self.tzone("Etc/GMT+12"), "pst_us": self.tzone("America/Los_Angeles"), "pdt_us": self.tzone("America/Los_Angeles"), "cst": self.tzone("America/Chicago"), "cdt": self.tzone("America/Chicago"), "ast": self.tzone("America/Halifax"), "adt": self.tzone("America/Halifax"), "est": self.tzone("America/New_York"), "edt": self.tzone("America/New_York"), "mst": self.tzone("America/Edmonton"), "mdt": self.tzone("America/Edmonton"), "akst": self.tzone("America/Anchorage"), "akdt": self.tzone("America/Anchorage"), "aest": self.tzone("Australia/Sydney"), "acst": self.tzone("Australia/Adelaide"), "acdt": self.tzone("Australia/Adelaide"), "awst": self.tzone("Australia/Perth"), "bst": self.tzone("Europe/London"), "ist": self.tzone("Europe/Dublin"), "wet": self.tzone("Europe/Lisbon"), "west": self.tzone("Europe/Lisbon"), "cet": self.tzone("Europe/Brussels"), "cest": self.tzone("Europe/Brussels"), "eet": self.tzone("Europe/Bucharest"), "eest": self.tzone("Europe/Bucharest"), } self.tzoffsets = { **{ str(offset*-1): self.tzone(f"Etc/GMT{offset}") for offset in range(-14, 0) }, **{ str(offset*-1): self.tzone(f"Etc/GMT+{offset}") for offset in range(0, 12+1) }, } def test_parse_common_timezones(self): for abbv, date in self.common_tzones.items(): guess_tzone = self.tz.parsetz(*abbv.split("_")[:2]) guess_date = self.utc.astimezone(guess_tzone) self.assertEqual(guess_date, date, msg="Parses common timezone correctly.") def test_find_by_offset(self): for offset, date in self.tzoffsets.items(): self.tz.timezone = offset guess_date = self.tzone(self.tz.find_by_offset()) self.assertEqual(guess_date, date, msg="Parses all timezone offsets.") def tzone(self, tz): return self.utc.astimezone(timezone(tz))
true
true
1c393cccf5d22a80a4b220c3f9f9f8cbfaeb97cf
15,241
py
Python
api/authority/digicert.py
ziegeer/autocert
285df181508573918e280948e51cdd7c65743281
[ "MIT" ]
null
null
null
api/authority/digicert.py
ziegeer/autocert
285df181508573918e280948e51cdd7c65743281
[ "MIT" ]
null
null
null
api/authority/digicert.py
ziegeer/autocert
285df181508573918e280948e51cdd7c65743281
[ "MIT" ]
null
null
null
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import io import zipfile from attrdict import AttrDict from pprint import pprint, pformat from fnmatch import fnmatch from datetime import timedelta #FIXME: do we import this here? from whois import whois from tld import get_tld from authority.base import AuthorityBase from utils.dictionary import merge, body from utils.format import fmt, pfmt from utils.newline import windows2unix from utils.exceptions import AutocertError from app import app def not_200(call): return call.recv.status != 200 class OrderCertificateError(AutocertError): def __init__(self, call): message = fmt('order certificate error call={0}', call) super(OrderCertificateError, self).__init__(message) class RevokeCertificateError(AutocertError): def __init__(self, call): message = fmt('revoke certificate error call={0}', call) super(RevokeCertificateError, self).__init__(message) class ApproveCertificateError(AutocertError): def __init__(self, call): message = fmt('approve certificate error call={0}', call) super(ApproveCertificateError, self).__init__(message) class DownloadCertificateError(AutocertError): def __init__(self, call): message = fmt('download certificate error call={0}', call) super(DownloadCertificateError, self).__init__(message) class OrganizationNameNotFoundError(AutocertError): def __init__(self, organization_name): message = fmt('organization name {organization_name} not found') super(OrganizationNameNotFoundError, self).__init__(message) class NotValidatedDomainError(AutocertError): def __init__(self, denied_domains, active_domains): message = fmt('these denied_domains: {denied_domains} were not found in these active_domains: {active_domains}') super(NotValidatedDomainError, self).__init__(message) class WhoisDoesntMatchError(AutocertError): def __init__(self, domains): domains = ', '.join(domains) message = fmt('list of domains with whois emails not matching hostmaster@mozilla.com: {domains}') super(WhoisDoesntMatchError, self).__init__(message) class DigicertError(AutocertError): def __init__(self, call): message = 'digicert error without errors field' if 'errors' in call.recv.json: message = call.recv.json['errors'][0]['message'] super(DigicertError, self).__init__(message) def expiryify(call): from utils.timestamp import string2datetime if call.recv.status != 200: raise DigicertError(call) try: valid_till = call.recv.json.certificate.valid_till if valid_till and valid_till != 'null': return string2datetime(valid_till) except AttributeError as ae: raise DigicertError(call) def combine_sans(sans1, sans2): if sans1 is None: return list(sans2) elif sans2 is None: return list(sans1) return list(set(list(sans1) + list(sans2))) class DigicertAuthority(AuthorityBase): def __init__(self, ar, cfg, verbosity): super(DigicertAuthority, self).__init__(ar, cfg, verbosity) def has_connectivity(self): call = self.get('user/me') if call.recv.status != 200: raise AuthorityConnectivityError(call) return True def display_certificates(self, certs, repeat_delta=None): app.logger.info(fmt('display_certificates:\n{locals}')) order_ids = [cert.authority['digicert']['order_id'] for cert in certs] calls = self._get_certificate_order_detail(order_ids) certificate_ids = [call.recv.json.certificate.id for call in calls] crts = self._download_certificates(certificate_ids, repeat_delta=repeat_delta) expiries = [expiryify(call) for call in calls] csrs = [windows2unix(call.recv.json.certificate.csr) for call in calls] for expiry, csr, crt, cert in zip(expiries, csrs, crts, certs): matched = csr.strip() == cert.csr.strip() and crt.strip() == cert.crt.strip() cert.authority['digicert']['matched'] = matched return certs def create_certificate(self, organization_name, common_name, validity_years, csr, bug, sans=None, repeat_delta=None, whois_check=False): app.logger.info(fmt('create_certificate:\n{locals}')) if not sans: sans = [] organization_id, container_id = self._get_organization_container_ids(organization_name) path, json = self._prepare_path_json( organization_id, container_id, common_name, validity_years, csr, bug, sans=sans, whois_check=whois_check) crts, expiries, order_ids = self._create_certificates([path], [json], bug, repeat_delta) authority = dict(digicert=dict(order_id=order_ids[0])) return crts[0], expiries[0], authority def renew_certificates(self, certs, organization_name, validity_years, bug, sans=None, repeat_delta=None, whois_check=False): app.logger.info(fmt('renew_certificates:\n{locals}')) if not sans: sans = [] organization_id, container_id = self._get_organization_container_ids(organization_name) paths, jsons = self._prepare_paths_jsons_for_renewals( certs, organization_id, container_id, bug, validity_years, sans, whois_check) crts, expiries, order_ids = self._create_certificates(paths, jsons, bug, repeat_delta) authorities = [dict(digicert=dict(order_id=order_id)) for order_id in order_ids] return crts, expiries, authorities def revoke_certificates(self, certs, bug): app.logger.info(fmt('revoke_certificates:\n{locals}')) paths, jsons = self._prepare_paths_jsons_for_revocations(certs, bug) self._revoke_certificates(paths, jsons, bug) return certs def _get_organization_container_ids(self, organization_name): app.logger.debug(fmt('_get_organization_container_ids:\n{locals}')) path = 'organization' call = self.get(path) if call.recv.status != 200: raise DigicertError(call) for organization in call.recv.json.organizations: if organization.name == organization_name: return organization.id, organization.container.id raise OrganizationNameNotFoundError(organization_name) def _get_domains(self, organization_id, container_id): app.logger.debug(fmt('_get_domains:\n{locals}')) call = self.get(fmt('domain?container_id={container_id}')) if call.recv.status != 200: raise DigicertError(call) return [domain for domain in call.recv.json.domains if domain.is_active and domain.organization.id == organization_id] def _validate_domains(self, organization_id, container_id, domains, whois_check=False): app.logger.debug(fmt('_validate_domains:\n{locals}')) active_domains = self._get_domains(organization_id, container_id) active_domains = [ad.name for ad in active_domains] def _is_validated(domain_to_check): matched_domains = [ad for ad in active_domains if domain_to_check == ad] if matched_domains: domain = matched_domains[0] else: matched_subdomains = [ad for ad in active_domains if domain_to_check.endswith('.'+ad)] if matched_subdomains: domain = matched_subdomains[0] else: return False return True def _whois_email(domain_to_check): app.logger.debug(fmt('_whois_email:\n{locals}')) try: emails = whois(domain_to_check)['emails'] app.logger.debug(fmt('emails={emails}')) return 'hostmaster@mozilla.com' in emails except Exception as ex: app.logger.debug('WHOIS_ERROR') app.logger.debug(ex) return False return False app.logger.debug(fmt('domains={domains}')) domains = list(set([get_tld('http://'+domain) for domain in domains])) app.logger.debug(fmt('domains={domains}')) not_whois_domains = [] if whois_check: app.logger.info('the whois check was enabled with --whois-check flag for this run') not_whois_domains = [domain for domain in domains if not _whois_email(domain)] if not_whois_domains: raise WhoisDoesntMatchError(not_whois_domains) denied_domains = [domain for domain in domains if not _is_validated(domain)] if denied_domains: raise NotValidatedDomainError(denied_domains, active_domains) return True def _domains_to_check(self, common_name, sans): app.logger.debug(fmt('_domains_to_check:\n{locals}')) domains_to_check = [(common_name[2:] if common_name.startswith('*.') else common_name)] domains_to_check += sans if sans else [] return list(set(domains_to_check)) def _prepare_path_json(self, organization_id, container_id, common_name, validity_years, csr, bug, sans=None, whois_check=False, renewal_of_order_id=None): app.logger.debug(fmt('_prepare_path_json:\n{locals}')) domains_to_check = self._domains_to_check(common_name, sans) self._validate_domains(organization_id, container_id, domains_to_check, whois_check) path = 'order/certificate/ssl_plus' json = merge(self.cfg.template, dict( validity_years=validity_years, certificate=dict( common_name=common_name, csr=csr), organization=dict( id=organization_id), comments=bug)) if common_name.startswith('*.'): path = 'order/certificate/ssl_wildcard' elif sans: path = 'order/certificate/ssl_multi_domain' json = merge(json, dict( certificate=dict( dns_names=sans))) if renewal_of_order_id: json = merge(json, dict( renewal_of_order_id=renewal_of_order_id)) return path, json def _prepare_paths_jsons_for_renewals(self, certs, organization_id, container_id, bug, validity_years, sans_to_add, whois_check=False): app.logger.debug(fmt('_prepare_paths_jsons_for_renewals:\n{locals}')) order_ids = [cert.authority['digicert']['order_id'] for cert in certs] calls = self._get_certificate_order_detail(order_ids) paths = [] jsons = [] for cert, call in zip(certs, calls): cert.sans=combine_sans(cert.sans, sans_to_add) path, json = self._prepare_path_json( organization_id, container_id, cert.common_name, validity_years, cert.csr, bug, sans=cert.sans, whois_check=whois_check, renewal_of_order_id=cert.authority['digicert']['order_id']) paths += [path] jsons += [json] return paths, jsons def _prepare_paths_jsons_for_revocations(self, certs, bug): app.logger.debug(fmt('_prepare_paths_jsons_for_revocations:\n{locals}')) order_ids = [cert.authority['digicert']['order_id'] for cert in certs] calls = self._get_certificate_order_detail(order_ids) certificate_ids = [call.recv.json.certificate.id for call in calls] paths = [fmt('certificate/{certificate_id}/revoke') for certificate_id in certificate_ids] jsons = [dict(comments=str(bug))] return paths, jsons def _create_certificates(self, paths, jsons, bug, repeat_delta): app.logger.debug(fmt('_create_certificates:\n{locals}')) order_ids, request_ids = self._order_certificates(paths, jsons) self._update_requests_status(request_ids, 'approved', bug) calls = self._get_certificate_order_detail(order_ids) certificate_ids = [call.recv.json.certificate.id for call in calls] try: crts = self._download_certificates(certificate_ids, repeat_delta=repeat_delta) calls = self._get_certificate_order_detail(order_ids) expiries = [expiryify(call) for call in calls] except DownloadCertificateError as dce: app.logger.warning(str(dce)) crts = [] expiries = [] return crts, expiries, order_ids def _revoke_certificates(self, paths, jsons, bug): app.logger.debug(fmt('_revoke_certificates:\n{locals}')) calls = self.puts(paths=paths, jsons=jsons) for call in calls: if call.recv.status != 201: raise RevokeCertificateError(call) request_ids = [call.recv.json.id for call in calls] self._update_requests_status(request_ids, 'approved', bug) def _order_certificates(self, paths, jsons): app.logger.debug(fmt('_order_certificates:\n{locals}')) calls = self.posts(paths=paths, jsons=jsons) for call in calls: if call.recv.status != 201: raise OrderCertificateError(call) return zip(*[(call.recv.json.id, call.recv.json.requests[0].id) for call in calls]) def _update_requests_status(self, request_ids, status,bug): app.logger.debug(fmt('_update_requests_status:\n{locals}')) paths = [fmt('request/{request_id}/status') for request_id in request_ids] jsons = [dict(status=status, processor_comment=bug)] app.logger.debug(fmt('calling digicert api with paths={paths} and jsons={jsons}')) calls = self.puts(paths=paths, jsons=jsons) for call in calls: if call.recv.status != 204: if call.recv.json.errors[0].code != 'request_already_processed': raise ApproveCertificateError(call) return True def _get_certificate_order_summary(self): app.logger.debug(fmt('_get_certificate_order_summary:\n{locals}')) call = self.get(path='order/certificate') return call def _get_certificate_order_detail(self, order_ids): app.logger.debug(fmt('_get_certificate_order_detail:\n{locals}')) paths = [fmt('order/certificate/{order_id}') for order_id in order_ids] calls = self.gets(paths=paths) return calls def _download_certificates(self, certificate_ids, format_type='pem_noroot', repeat_delta=None): app.logger.debug(fmt('_download_certificates:\n{locals}')) if repeat_delta is not None and isinstance(repeat_delta, int): repeat_delta = timedelta(seconds=repeat_delta) paths = [fmt('certificate/{certificate_id}/download/format/{format_type}') for certificate_id in certificate_ids] calls = self.gets(paths=paths, repeat_delta=repeat_delta, repeat_if=not_200) texts = [] for call in calls: if call.recv.status == 200: texts += [call.recv.text] else: raise DownloadCertificateError(call) return texts
44.826471
159
0.660127
import io import zipfile from attrdict import AttrDict from pprint import pprint, pformat from fnmatch import fnmatch from datetime import timedelta from whois import whois from tld import get_tld from authority.base import AuthorityBase from utils.dictionary import merge, body from utils.format import fmt, pfmt from utils.newline import windows2unix from utils.exceptions import AutocertError from app import app def not_200(call): return call.recv.status != 200 class OrderCertificateError(AutocertError): def __init__(self, call): message = fmt('order certificate error call={0}', call) super(OrderCertificateError, self).__init__(message) class RevokeCertificateError(AutocertError): def __init__(self, call): message = fmt('revoke certificate error call={0}', call) super(RevokeCertificateError, self).__init__(message) class ApproveCertificateError(AutocertError): def __init__(self, call): message = fmt('approve certificate error call={0}', call) super(ApproveCertificateError, self).__init__(message) class DownloadCertificateError(AutocertError): def __init__(self, call): message = fmt('download certificate error call={0}', call) super(DownloadCertificateError, self).__init__(message) class OrganizationNameNotFoundError(AutocertError): def __init__(self, organization_name): message = fmt('organization name {organization_name} not found') super(OrganizationNameNotFoundError, self).__init__(message) class NotValidatedDomainError(AutocertError): def __init__(self, denied_domains, active_domains): message = fmt('these denied_domains: {denied_domains} were not found in these active_domains: {active_domains}') super(NotValidatedDomainError, self).__init__(message) class WhoisDoesntMatchError(AutocertError): def __init__(self, domains): domains = ', '.join(domains) message = fmt('list of domains with whois emails not matching hostmaster@mozilla.com: {domains}') super(WhoisDoesntMatchError, self).__init__(message) class DigicertError(AutocertError): def __init__(self, call): message = 'digicert error without errors field' if 'errors' in call.recv.json: message = call.recv.json['errors'][0]['message'] super(DigicertError, self).__init__(message) def expiryify(call): from utils.timestamp import string2datetime if call.recv.status != 200: raise DigicertError(call) try: valid_till = call.recv.json.certificate.valid_till if valid_till and valid_till != 'null': return string2datetime(valid_till) except AttributeError as ae: raise DigicertError(call) def combine_sans(sans1, sans2): if sans1 is None: return list(sans2) elif sans2 is None: return list(sans1) return list(set(list(sans1) + list(sans2))) class DigicertAuthority(AuthorityBase): def __init__(self, ar, cfg, verbosity): super(DigicertAuthority, self).__init__(ar, cfg, verbosity) def has_connectivity(self): call = self.get('user/me') if call.recv.status != 200: raise AuthorityConnectivityError(call) return True def display_certificates(self, certs, repeat_delta=None): app.logger.info(fmt('display_certificates:\n{locals}')) order_ids = [cert.authority['digicert']['order_id'] for cert in certs] calls = self._get_certificate_order_detail(order_ids) certificate_ids = [call.recv.json.certificate.id for call in calls] crts = self._download_certificates(certificate_ids, repeat_delta=repeat_delta) expiries = [expiryify(call) for call in calls] csrs = [windows2unix(call.recv.json.certificate.csr) for call in calls] for expiry, csr, crt, cert in zip(expiries, csrs, crts, certs): matched = csr.strip() == cert.csr.strip() and crt.strip() == cert.crt.strip() cert.authority['digicert']['matched'] = matched return certs def create_certificate(self, organization_name, common_name, validity_years, csr, bug, sans=None, repeat_delta=None, whois_check=False): app.logger.info(fmt('create_certificate:\n{locals}')) if not sans: sans = [] organization_id, container_id = self._get_organization_container_ids(organization_name) path, json = self._prepare_path_json( organization_id, container_id, common_name, validity_years, csr, bug, sans=sans, whois_check=whois_check) crts, expiries, order_ids = self._create_certificates([path], [json], bug, repeat_delta) authority = dict(digicert=dict(order_id=order_ids[0])) return crts[0], expiries[0], authority def renew_certificates(self, certs, organization_name, validity_years, bug, sans=None, repeat_delta=None, whois_check=False): app.logger.info(fmt('renew_certificates:\n{locals}')) if not sans: sans = [] organization_id, container_id = self._get_organization_container_ids(organization_name) paths, jsons = self._prepare_paths_jsons_for_renewals( certs, organization_id, container_id, bug, validity_years, sans, whois_check) crts, expiries, order_ids = self._create_certificates(paths, jsons, bug, repeat_delta) authorities = [dict(digicert=dict(order_id=order_id)) for order_id in order_ids] return crts, expiries, authorities def revoke_certificates(self, certs, bug): app.logger.info(fmt('revoke_certificates:\n{locals}')) paths, jsons = self._prepare_paths_jsons_for_revocations(certs, bug) self._revoke_certificates(paths, jsons, bug) return certs def _get_organization_container_ids(self, organization_name): app.logger.debug(fmt('_get_organization_container_ids:\n{locals}')) path = 'organization' call = self.get(path) if call.recv.status != 200: raise DigicertError(call) for organization in call.recv.json.organizations: if organization.name == organization_name: return organization.id, organization.container.id raise OrganizationNameNotFoundError(organization_name) def _get_domains(self, organization_id, container_id): app.logger.debug(fmt('_get_domains:\n{locals}')) call = self.get(fmt('domain?container_id={container_id}')) if call.recv.status != 200: raise DigicertError(call) return [domain for domain in call.recv.json.domains if domain.is_active and domain.organization.id == organization_id] def _validate_domains(self, organization_id, container_id, domains, whois_check=False): app.logger.debug(fmt('_validate_domains:\n{locals}')) active_domains = self._get_domains(organization_id, container_id) active_domains = [ad.name for ad in active_domains] def _is_validated(domain_to_check): matched_domains = [ad for ad in active_domains if domain_to_check == ad] if matched_domains: domain = matched_domains[0] else: matched_subdomains = [ad for ad in active_domains if domain_to_check.endswith('.'+ad)] if matched_subdomains: domain = matched_subdomains[0] else: return False return True def _whois_email(domain_to_check): app.logger.debug(fmt('_whois_email:\n{locals}')) try: emails = whois(domain_to_check)['emails'] app.logger.debug(fmt('emails={emails}')) return 'hostmaster@mozilla.com' in emails except Exception as ex: app.logger.debug('WHOIS_ERROR') app.logger.debug(ex) return False return False app.logger.debug(fmt('domains={domains}')) domains = list(set([get_tld('http://'+domain) for domain in domains])) app.logger.debug(fmt('domains={domains}')) not_whois_domains = [] if whois_check: app.logger.info('the whois check was enabled with --whois-check flag for this run') not_whois_domains = [domain for domain in domains if not _whois_email(domain)] if not_whois_domains: raise WhoisDoesntMatchError(not_whois_domains) denied_domains = [domain for domain in domains if not _is_validated(domain)] if denied_domains: raise NotValidatedDomainError(denied_domains, active_domains) return True def _domains_to_check(self, common_name, sans): app.logger.debug(fmt('_domains_to_check:\n{locals}')) domains_to_check = [(common_name[2:] if common_name.startswith('*.') else common_name)] domains_to_check += sans if sans else [] return list(set(domains_to_check)) def _prepare_path_json(self, organization_id, container_id, common_name, validity_years, csr, bug, sans=None, whois_check=False, renewal_of_order_id=None): app.logger.debug(fmt('_prepare_path_json:\n{locals}')) domains_to_check = self._domains_to_check(common_name, sans) self._validate_domains(organization_id, container_id, domains_to_check, whois_check) path = 'order/certificate/ssl_plus' json = merge(self.cfg.template, dict( validity_years=validity_years, certificate=dict( common_name=common_name, csr=csr), organization=dict( id=organization_id), comments=bug)) if common_name.startswith('*.'): path = 'order/certificate/ssl_wildcard' elif sans: path = 'order/certificate/ssl_multi_domain' json = merge(json, dict( certificate=dict( dns_names=sans))) if renewal_of_order_id: json = merge(json, dict( renewal_of_order_id=renewal_of_order_id)) return path, json def _prepare_paths_jsons_for_renewals(self, certs, organization_id, container_id, bug, validity_years, sans_to_add, whois_check=False): app.logger.debug(fmt('_prepare_paths_jsons_for_renewals:\n{locals}')) order_ids = [cert.authority['digicert']['order_id'] for cert in certs] calls = self._get_certificate_order_detail(order_ids) paths = [] jsons = [] for cert, call in zip(certs, calls): cert.sans=combine_sans(cert.sans, sans_to_add) path, json = self._prepare_path_json( organization_id, container_id, cert.common_name, validity_years, cert.csr, bug, sans=cert.sans, whois_check=whois_check, renewal_of_order_id=cert.authority['digicert']['order_id']) paths += [path] jsons += [json] return paths, jsons def _prepare_paths_jsons_for_revocations(self, certs, bug): app.logger.debug(fmt('_prepare_paths_jsons_for_revocations:\n{locals}')) order_ids = [cert.authority['digicert']['order_id'] for cert in certs] calls = self._get_certificate_order_detail(order_ids) certificate_ids = [call.recv.json.certificate.id for call in calls] paths = [fmt('certificate/{certificate_id}/revoke') for certificate_id in certificate_ids] jsons = [dict(comments=str(bug))] return paths, jsons def _create_certificates(self, paths, jsons, bug, repeat_delta): app.logger.debug(fmt('_create_certificates:\n{locals}')) order_ids, request_ids = self._order_certificates(paths, jsons) self._update_requests_status(request_ids, 'approved', bug) calls = self._get_certificate_order_detail(order_ids) certificate_ids = [call.recv.json.certificate.id for call in calls] try: crts = self._download_certificates(certificate_ids, repeat_delta=repeat_delta) calls = self._get_certificate_order_detail(order_ids) expiries = [expiryify(call) for call in calls] except DownloadCertificateError as dce: app.logger.warning(str(dce)) crts = [] expiries = [] return crts, expiries, order_ids def _revoke_certificates(self, paths, jsons, bug): app.logger.debug(fmt('_revoke_certificates:\n{locals}')) calls = self.puts(paths=paths, jsons=jsons) for call in calls: if call.recv.status != 201: raise RevokeCertificateError(call) request_ids = [call.recv.json.id for call in calls] self._update_requests_status(request_ids, 'approved', bug) def _order_certificates(self, paths, jsons): app.logger.debug(fmt('_order_certificates:\n{locals}')) calls = self.posts(paths=paths, jsons=jsons) for call in calls: if call.recv.status != 201: raise OrderCertificateError(call) return zip(*[(call.recv.json.id, call.recv.json.requests[0].id) for call in calls]) def _update_requests_status(self, request_ids, status,bug): app.logger.debug(fmt('_update_requests_status:\n{locals}')) paths = [fmt('request/{request_id}/status') for request_id in request_ids] jsons = [dict(status=status, processor_comment=bug)] app.logger.debug(fmt('calling digicert api with paths={paths} and jsons={jsons}')) calls = self.puts(paths=paths, jsons=jsons) for call in calls: if call.recv.status != 204: if call.recv.json.errors[0].code != 'request_already_processed': raise ApproveCertificateError(call) return True def _get_certificate_order_summary(self): app.logger.debug(fmt('_get_certificate_order_summary:\n{locals}')) call = self.get(path='order/certificate') return call def _get_certificate_order_detail(self, order_ids): app.logger.debug(fmt('_get_certificate_order_detail:\n{locals}')) paths = [fmt('order/certificate/{order_id}') for order_id in order_ids] calls = self.gets(paths=paths) return calls def _download_certificates(self, certificate_ids, format_type='pem_noroot', repeat_delta=None): app.logger.debug(fmt('_download_certificates:\n{locals}')) if repeat_delta is not None and isinstance(repeat_delta, int): repeat_delta = timedelta(seconds=repeat_delta) paths = [fmt('certificate/{certificate_id}/download/format/{format_type}') for certificate_id in certificate_ids] calls = self.gets(paths=paths, repeat_delta=repeat_delta, repeat_if=not_200) texts = [] for call in calls: if call.recv.status == 200: texts += [call.recv.text] else: raise DownloadCertificateError(call) return texts
true
true
1c393d14ea8f30150efe552dc96b3b2564573ec3
1,489
py
Python
one_one.py
hduliufan/work
951a69aad5de3387c26fabe417a939349def3df6
[ "Apache-2.0" ]
null
null
null
one_one.py
hduliufan/work
951a69aad5de3387c26fabe417a939349def3df6
[ "Apache-2.0" ]
null
null
null
one_one.py
hduliufan/work
951a69aad5de3387c26fabe417a939349def3df6
[ "Apache-2.0" ]
null
null
null
import numpy as np import matplotlib.pyplot as plt from getlen_bit import getlen from begain import getbegain from x1x2 import x1_x2 from exchange_normal import variation from fitvalue import fitvalue #计算精度(人为设定)0.001 s=0.0001 a1=-3 a2=4.1 b1=12.1 b2=5.8 #种群规模 N=20 #-3<=x1<=12.1 4.1<=x2<=5.8 #二进制长度t1,t2 t1=getlen(a1,b1,s) t2=getlen(a2,b2,s) #print(t1,t2) t=t1+t2 #print(t) #二进制种群(N*t) pop=getbegain(N,t) #print(pop) x1,x2=x1_x2(pop,t,t1,t2,a1,b1,a2,b2) #print(x1,x2) def one_one(x1,x2,N): T=0 #记录变异前的最大适应值 fit1_=[] #记录变异后的最大适应值 fit2_=[] #记录最终的适应值 fit=[] while(T<10): #父本个体适应值(N*1) fit1=fitvalue(x1,x2) fit1_.append(np.max(fit1)) #变异采用高斯算子即N(0,1)标准正太分布 x11,x22=variation(N,x1,x2) #变异后个体适应值(N*1) fit2=fitvalue(x11,x22) fit2_.append(np.max(fit2)) #记录索引 i=0 for fit_1,fit_2 in zip(fit1,fit2): if fit_1<fit_2: #变异前与变异后交换 x1[i]=x11[i] x2[i]=x22[i] i=i+1 T=T+1 #输出最大适应值变化 for b,a in zip (fit1_,fit2_): fit.append(np.where(b>a,b,a)) #输出图形变异前后的最大适应值变化 plt.title('1+1') plt.subplot(111) plt.xlabel('T') plt.ylabel("fitvalue") plt.plot(range(1,T+1),fit1_,'b--',label='bef') plt.plot(range(1,T+1),fit2_,'g--',label='aft') plt.legend(loc='upper left') plt.plot(range(1,T+1),fit,'r-',label='maxfit') plt.show() one_one(x1,x2,N) #print(x1,x2)
21.271429
50
0.58227
import numpy as np import matplotlib.pyplot as plt from getlen_bit import getlen from begain import getbegain from x1x2 import x1_x2 from exchange_normal import variation from fitvalue import fitvalue s=0.0001 a1=-3 a2=4.1 b1=12.1 b2=5.8 N=20 t1=getlen(a1,b1,s) t2=getlen(a2,b2,s) t=t1+t2 pop=getbegain(N,t) x1,x2=x1_x2(pop,t,t1,t2,a1,b1,a2,b2) def one_one(x1,x2,N): T=0 fit1_=[] fit2_=[] fit=[] while(T<10): fit1=fitvalue(x1,x2) fit1_.append(np.max(fit1)) x11,x22=variation(N,x1,x2) fit2=fitvalue(x11,x22) fit2_.append(np.max(fit2)) i=0 for fit_1,fit_2 in zip(fit1,fit2): if fit_1<fit_2: x1[i]=x11[i] x2[i]=x22[i] i=i+1 T=T+1 for b,a in zip (fit1_,fit2_): fit.append(np.where(b>a,b,a)) plt.title('1+1') plt.subplot(111) plt.xlabel('T') plt.ylabel("fitvalue") plt.plot(range(1,T+1),fit1_,'b--',label='bef') plt.plot(range(1,T+1),fit2_,'g--',label='aft') plt.legend(loc='upper left') plt.plot(range(1,T+1),fit,'r-',label='maxfit') plt.show() one_one(x1,x2,N)
true
true
1c393e0e4e5cdb3c7b762f7c9e41dfc5893cdb33
4,396
py
Python
NLPCC_2018_TASK2_GEC/CS2S+BPE+Emb/software/nbest-reranker/log_utils.py
DCMMC/chineseocr
0b8772615239ea7f212b1ab5bc75183e7e9f16b0
[ "MIT" ]
null
null
null
NLPCC_2018_TASK2_GEC/CS2S+BPE+Emb/software/nbest-reranker/log_utils.py
DCMMC/chineseocr
0b8772615239ea7f212b1ab5bc75183e7e9f16b0
[ "MIT" ]
null
null
null
NLPCC_2018_TASK2_GEC/CS2S+BPE+Emb/software/nbest-reranker/log_utils.py
DCMMC/chineseocr
0b8772615239ea7f212b1ab5bc75183e7e9f16b0
[ "MIT" ]
null
null
null
import logging import sys #-----------------------------------------------------------------------------------------------------------# import re class BColors: HEADER = '\033[95m' OKBLUE = '\033[94m' OKGREEN = '\033[92m' WARNING = '\033[93m' FAIL = '\033[91m' ENDC = '\033[0m' BOLD = '\033[1m' UNDERLINE = '\033[4m' WHITE = '\033[37m' YELLOW = '\033[33m' GREEN = '\033[32m' BLUE = '\033[34m' CYAN = '\033[36m' RED = '\033[31m' MAGENTA = '\033[35m' BLACK = '\033[30m' BHEADER = BOLD + '\033[95m' BOKBLUE = BOLD + '\033[94m' BOKGREEN = BOLD + '\033[92m' BWARNING = BOLD + '\033[93m' BFAIL = BOLD + '\033[91m' BUNDERLINE = BOLD + '\033[4m' BWHITE = BOLD + '\033[37m' BYELLOW = BOLD + '\033[33m' BGREEN = BOLD + '\033[32m' BBLUE = BOLD + '\033[34m' BCYAN = BOLD + '\033[36m' BRED = BOLD + '\033[31m' BMAGENTA = BOLD + '\033[35m' BBLACK = BOLD + '\033[30m' @staticmethod def cleared(s): return re.sub("\033\[[0-9][0-9]?m", "", s) def red(message): return BColors.RED + str(message) + BColors.ENDC def b_red(message): return BColors.BRED + str(message) + BColors.ENDC def blue(message): return BColors.BLUE + str(message) + BColors.ENDC def yellow(message): return BColors.YELLOW + str(message) + BColors.ENDC def b_yellow(message): return BColors.BYELLOW + str(message) + BColors.ENDC def white(message): return BColors.WHITE + str(message) + BColors.ENDC def green(message): return BColors.GREEN + str(message) + BColors.ENDC def b_green(message): return BColors.BGREEN + str(message) + BColors.ENDC def b_okblue(message): return BColors.OKBLUE + str(message) + BColors.ENDC def b_fail(message): return BColors.BFAIL + str(message) + BColors.ENDC def b_warning(message): return BColors.WARNING + str(message) + BColors.ENDC def print_args(args, path=None): if path: output_file = open(path, 'w') logger = logging.getLogger(__name__) logger.info("Arguments:") args.command = ' '.join(sys.argv) items = vars(args) for key in sorted(items.keys(), key=lambda s: s.lower()): value = items[key] if not value: value = "None" logger.info(" " + key + ": " + str(items[key])) if path is not None: output_file.write(" " + key + ": " + str(items[key]) + "\n") if path: output_file.close() del args.command #-----------------------------------------------------------------------------------------------------------# #-----------------------------------------------------------------------------------------------------------# def set_logger(out_dir=None, log_file="log.txt"): #console_format = BColors.OKBLUE + '[%(levelname)s]' + BColors.ENDC + ' (%(name)s) %(message)s' #console_format = b_okblue('[%(levelname)s]') + b_okblue(' [%(asctime)s] ') + ' %(message)s ' datefmt='%d-%m-%Y %H:%M:%S' logger = logging.getLogger() logger.setLevel(logging.DEBUG) console = logging.StreamHandler() console.setLevel(logging.DEBUG) console.setFormatter(ColoredFormatter(datefmt=datefmt)) logger.addHandler(console) if out_dir: #file_format = '[%(levelname)s] (%(name)s) %(message)s' file_format = '[%(levelname)s] [%(asctime)s] %(message)s' log_file = logging.FileHandler(out_dir + '/' + log_file, mode='w') log_file.setLevel(logging.DEBUG) log_file.setFormatter(logging.Formatter(file_format, datefmt=datefmt)) logger.addHandler(log_file) #-----------------------------------------------------------------------------------------------------------# class ColoredFormatter(logging.Formatter): FORMATS = {logging.DEBUG :"DBG: %(module)s: %(lineno)d: %(message)s", logging.ERROR : b_fail('[%(levelname)s]') + b_fail(' [%(asctime)s] ') + ' %(message)s ', logging.INFO : b_okblue('[%(levelname)s]') + b_okblue(' [%(asctime)s] ') + ' %(message)s ', logging.WARNING : b_warning('[%(levelname)s]') + ' %(message)s', 'DEFAULT' : b_okblue('[%(levelname)s]') + b_okblue(' [%(asctime)s] ') + ' %(message)s '} def format(self, record): self._fmt = self.FORMATS.get(record.levelno, self.FORMATS['DEFAULT']) return logging.Formatter.format(self, record)
34.34375
109
0.541401
import logging import sys import re class BColors: HEADER = '\033[95m' OKBLUE = '\033[94m' OKGREEN = '\033[92m' WARNING = '\033[93m' FAIL = '\033[91m' ENDC = '\033[0m' BOLD = '\033[1m' UNDERLINE = '\033[4m' WHITE = '\033[37m' YELLOW = '\033[33m' GREEN = '\033[32m' BLUE = '\033[34m' CYAN = '\033[36m' RED = '\033[31m' MAGENTA = '\033[35m' BLACK = '\033[30m' BHEADER = BOLD + '\033[95m' BOKBLUE = BOLD + '\033[94m' BOKGREEN = BOLD + '\033[92m' BWARNING = BOLD + '\033[93m' BFAIL = BOLD + '\033[91m' BUNDERLINE = BOLD + '\033[4m' BWHITE = BOLD + '\033[37m' BYELLOW = BOLD + '\033[33m' BGREEN = BOLD + '\033[32m' BBLUE = BOLD + '\033[34m' BCYAN = BOLD + '\033[36m' BRED = BOLD + '\033[31m' BMAGENTA = BOLD + '\033[35m' BBLACK = BOLD + '\033[30m' @staticmethod def cleared(s): return re.sub("\033\[[0-9][0-9]?m", "", s) def red(message): return BColors.RED + str(message) + BColors.ENDC def b_red(message): return BColors.BRED + str(message) + BColors.ENDC def blue(message): return BColors.BLUE + str(message) + BColors.ENDC def yellow(message): return BColors.YELLOW + str(message) + BColors.ENDC def b_yellow(message): return BColors.BYELLOW + str(message) + BColors.ENDC def white(message): return BColors.WHITE + str(message) + BColors.ENDC def green(message): return BColors.GREEN + str(message) + BColors.ENDC def b_green(message): return BColors.BGREEN + str(message) + BColors.ENDC def b_okblue(message): return BColors.OKBLUE + str(message) + BColors.ENDC def b_fail(message): return BColors.BFAIL + str(message) + BColors.ENDC def b_warning(message): return BColors.WARNING + str(message) + BColors.ENDC def print_args(args, path=None): if path: output_file = open(path, 'w') logger = logging.getLogger(__name__) logger.info("Arguments:") args.command = ' '.join(sys.argv) items = vars(args) for key in sorted(items.keys(), key=lambda s: s.lower()): value = items[key] if not value: value = "None" logger.info(" " + key + ": " + str(items[key])) if path is not None: output_file.write(" " + key + ": " + str(items[key]) + "\n") if path: output_file.close() del args.command def set_logger(out_dir=None, log_file="log.txt"): datefmt='%d-%m-%Y %H:%M:%S' logger = logging.getLogger() logger.setLevel(logging.DEBUG) console = logging.StreamHandler() console.setLevel(logging.DEBUG) console.setFormatter(ColoredFormatter(datefmt=datefmt)) logger.addHandler(console) if out_dir: file_format = '[%(levelname)s] [%(asctime)s] %(message)s' log_file = logging.FileHandler(out_dir + '/' + log_file, mode='w') log_file.setLevel(logging.DEBUG) log_file.setFormatter(logging.Formatter(file_format, datefmt=datefmt)) logger.addHandler(log_file) class ColoredFormatter(logging.Formatter): FORMATS = {logging.DEBUG :"DBG: %(module)s: %(lineno)d: %(message)s", logging.ERROR : b_fail('[%(levelname)s]') + b_fail(' [%(asctime)s] ') + ' %(message)s ', logging.INFO : b_okblue('[%(levelname)s]') + b_okblue(' [%(asctime)s] ') + ' %(message)s ', logging.WARNING : b_warning('[%(levelname)s]') + ' %(message)s', 'DEFAULT' : b_okblue('[%(levelname)s]') + b_okblue(' [%(asctime)s] ') + ' %(message)s '} def format(self, record): self._fmt = self.FORMATS.get(record.levelno, self.FORMATS['DEFAULT']) return logging.Formatter.format(self, record)
true
true
1c393e1d3e1f2aa16049a35c535565eaac8e73ec
1,170
py
Python
checkov/cloudformation/checks/resource/aws/IAMPolicyAttachedToGroupOrRoles.py
peaudecastor/checkov
a4804b61c1b1390b7abd44ab53285fcbc3e7e80b
[ "Apache-2.0" ]
null
null
null
checkov/cloudformation/checks/resource/aws/IAMPolicyAttachedToGroupOrRoles.py
peaudecastor/checkov
a4804b61c1b1390b7abd44ab53285fcbc3e7e80b
[ "Apache-2.0" ]
null
null
null
checkov/cloudformation/checks/resource/aws/IAMPolicyAttachedToGroupOrRoles.py
peaudecastor/checkov
a4804b61c1b1390b7abd44ab53285fcbc3e7e80b
[ "Apache-2.0" ]
null
null
null
from typing import List, Any from checkov.cloudformation.checks.resource.base_resource_negative_value_check import BaseResourceNegativeValueCheck from checkov.common.models.consts import ANY_VALUE from checkov.common.models.enums import CheckCategories class IAMPolicyAttachedToGroupOrRoles(BaseResourceNegativeValueCheck): def __init__(self): name = "Ensure IAM policies are attached only to groups or roles (Reducing access management complexity may " \ "in-turn reduce opportunity for a principal to inadvertently receive or retain excessive privileges.)" id = "CKV_AWS_40" supported_resources = ['AWS::IAM::Policy'] categories = [CheckCategories.IAM] super().__init__(name=name, id=id, categories=categories, supported_resources=supported_resources) """ Looks for users attached to an IAM policy https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-iam-policy.html """ def get_inspected_key(self) -> str: return "Properties/Users" def get_forbidden_values(self) -> List[Any]: return [ANY_VALUE] check = IAMPolicyAttachedToGroupOrRoles()
40.344828
119
0.749573
from typing import List, Any from checkov.cloudformation.checks.resource.base_resource_negative_value_check import BaseResourceNegativeValueCheck from checkov.common.models.consts import ANY_VALUE from checkov.common.models.enums import CheckCategories class IAMPolicyAttachedToGroupOrRoles(BaseResourceNegativeValueCheck): def __init__(self): name = "Ensure IAM policies are attached only to groups or roles (Reducing access management complexity may " \ "in-turn reduce opportunity for a principal to inadvertently receive or retain excessive privileges.)" id = "CKV_AWS_40" supported_resources = ['AWS::IAM::Policy'] categories = [CheckCategories.IAM] super().__init__(name=name, id=id, categories=categories, supported_resources=supported_resources) def get_inspected_key(self) -> str: return "Properties/Users" def get_forbidden_values(self) -> List[Any]: return [ANY_VALUE] check = IAMPolicyAttachedToGroupOrRoles()
true
true
1c393e95a6ee0086c9f4971d40918cf5dc494fc7
8,021
py
Python
opendatatools/stock/stock_interface.py
buf1024/OpenData
6268a5f7bee88cc943b3a05858b8ab6f371e8e3b
[ "Apache-2.0" ]
null
null
null
opendatatools/stock/stock_interface.py
buf1024/OpenData
6268a5f7bee88cc943b3a05858b8ab6f371e8e3b
[ "Apache-2.0" ]
null
null
null
opendatatools/stock/stock_interface.py
buf1024/OpenData
6268a5f7bee88cc943b3a05858b8ab6f371e8e3b
[ "Apache-2.0" ]
null
null
null
# encoding: utf-8 import datetime from .stock_agent import SHExAgent, SZExAgent, CSIAgent, XueqiuAgent, SinaAgent, CNInfoAgent, EastMoneyAgent from opendatatools.common import get_current_day shex_agent = SHExAgent() szex_agent = SZExAgent() csi_agent = CSIAgent() xq_agent = XueqiuAgent() sina_agent = SinaAgent() cninfo_agent = CNInfoAgent() eastmoney_agent = EastMoneyAgent() xq_count_map = { '1m': -142, '5m': -142, '15m': -142, '30m': -142, '60m': -142, 'day' : -142, } bar_span_map = { '1m' : 1, '5m' : 5, '15m' : 15, '30m' : 30, '60m' : 60, 'day' : 1440, } def make_index(period, trade_date): bar_index = list() span = bar_span_map[period] dt = datetime.datetime.strptime(trade_date,'%Y-%m-%d') bar_index.extend(pd.DatetimeIndex(start="%s 09:30:00" % trade_date, end="%s 11:30:00" % trade_date, freq='%sT' % span)[1:]) bar_index.extend(pd.DatetimeIndex(start="%s 13:00:00" % trade_date, end="%s 15:00:00" % trade_date, freq='%sT' % span)[1:]) return bar_index def set_proxies(proxies): shex_agent.set_proxies(proxies) szex_agent.set_proxies(proxies) csi_agent.set_proxies(proxies) xq_agent.set_proxies(proxies) def get_index_list(market='SH'): if market == 'SH': return shex_agent.get_index_list() if market == 'SZ': return szex_agent.get_index_list() if market == 'CSI': return csi_agent.get_index_list() def get_index_component(symbol): temp = symbol.split(".") if len(temp) == 2: market = temp[1] index = temp[0] if market == 'SH': return shex_agent.get_index_component(index) elif market == 'SZ': return szex_agent.get_index_component(index) elif market == 'CSI': return csi_agent.get_index_component(index) else: return None else: return None def get_rzrq_info(market='SH', date = None): if date is None: date = get_current_day(format = '%Y-%m-%d') if market == 'SH': return shex_agent.get_rzrq_info(date) if market == 'SZ': return szex_agent.get_rzrq_info(date) return None, None def get_pledge_info(market='SH', date = None): if date is None: date = get_current_day(format = '%Y-%m-%d') if market == 'SH': return shex_agent.get_pledge_info(date) if market == 'SZ': return szex_agent.get_pledge_info(date) return None, None def get_dividend(symbol): temp = symbol.split(".") if len(temp) == 2: market = temp[1] code = temp[0] if market == 'SH': return shex_agent.get_dividend(code) if market == 'SZ': return cninfo_agent.get_dividend(code) def get_quote(symbols): return xq_agent.get_quote(symbols) def fill_df(df, period, trade_date, symbol): df.index = df['time'] index = make_index(period, trade_date) df_new = pd.DataFrame(index=index, columns=['last']) df_new['last'] = df['last'] df_new.fillna(method='ffill', inplace=True) df_new['high'] = df['high'] df_new['low'] = df['low'] df_new['open'] = df['open'] df_new.fillna(method='ffill', axis=1, inplace=True) df_new['change'] = df['change'] df_new['percent'] = df['percent'] df_new['symbol'] = symbol df_new['turnover_rate'] = df['turnover_rate'] df_new['volume'] = df['volume'] df_new['time'] = df_new.index df_new.fillna(0, inplace=True) return df_new # period 1m, 5m, 15m, 30m, 60m, day def get_kline(symbol, trade_date, period): curr_date = datetime.datetime.strptime(trade_date, '%Y-%m-%d') next_date = datetime.datetime.strptime(trade_date, '%Y-%m-%d') + datetime.timedelta(days=1) timestamp = next_date.timestamp() timestamp = int ( timestamp * 1000) df, msg = xq_agent.get_kline(symbol, timestamp, period, xq_count_map[period]) if len(df) == 0: return df, msg df = df[(df.time < next_date) & (df.time >= curr_date)] if len(df) < abs(xq_count_map[period]): df_new = fill_df(df, period, trade_date, symbol) return df_new, '' else: return df, '' def get_kline_multisymbol(symbols, trade_date, period): symbol_list = symbols.split(',') timestamp = datetime.datetime.strptime(trade_date, '%Y-%m-%d').timestamp() timestamp = int ( timestamp * 1000) df, msg = xq_agent.get_kline_multisymbol(symbol_list, timestamp, period, xq_count_map[period]) next_date = datetime.datetime.strptime(trade_date, '%Y-%m-%d') + datetime.timedelta(days=1) if df is None: return df, msg df = df[df.time < next_date] gp = df.groupby('symbol') df_list = list() for symbol, df_item in gp: if len(df_item) < xq_count_map[period]: df_list.append(fill_df(df_item, period, trade_date, symbol)) else: df_list(df_item) return pd.concat(df_list), '' def get_timestamp_list(start_date, end_date): timestamp_list = [] curr_date = start_date while curr_date <= end_date: curr_datetime = datetime.datetime.strptime(curr_date, '%Y-%m-%d') timestamp = curr_datetime.timestamp() timestamp_list.append(int(timestamp * 1000)) next_time = curr_datetime + datetime.timedelta(days=1) curr_date = datetime.datetime.strftime(next_time, '%Y-%m-%d') return timestamp_list def get_kline_multidate(symbol, start_date, end_date, period): timestamp_list = get_timestamp_list(start_date, end_date) return xq_agent.get_kline_multitimestamp(symbol, timestamp_list, period, xq_count_map[period]) import pandas as pd def get_daily(symbol, start_date, end_date): curr_date = start_date df_result = [] while curr_date <= end_date: curr_datetime = datetime.datetime.strptime(curr_date, '%Y-%m-%d') next_time = curr_datetime + datetime.timedelta(days=100) next_date = datetime.datetime.strftime(next_time, '%Y-%m-%d') timestamp = curr_datetime.timestamp() df, msg = xq_agent.get_kline(symbol, int(timestamp*1000), 'day', 100) if df is not None and len(df) != 0: df_result.append(df[df['time']<next_time]) curr_date = next_date if len(df_result) > 0: df = pd.concat(df_result) df = df[(df['time'] >= start_date) & (df['time'] <= end_date) ] return df, '' else: return None, '没有获取到数据' def get_adj_factor(symbol): return sina_agent.get_adj_factor(symbol) def get_trade_detail(symbol, trade_date): return sina_agent.get_trade_detail(symbol, trade_date) def get_report_data(symbol='600000.SH', type='资产负债表'): dict_type = { '利润表' : 'lrb', '资产负债表' : 'fzb', '现金流量表' : 'llb', } if type not in dict_type: return None, 'type输入错误,可以输入 %s' % dict_type.keys() data = symbol.split(sep='.') market = data[1].lower() code = data[0] return cninfo_agent.get_report_data(market, code, dict_type[type]) def get_shareholder_structure(symbol='600000.SH'): data = symbol.split(sep='.') market = data[1].lower() code = data[0] return cninfo_agent.get_shareholder_structure(market, code) # 单位:百万元 def get_hist_money_flow(symbol): data = symbol.split(sep='.') market = data[1] if market == 'SH': marketnum = '1' else: marketnum = '2' code = data[0]+marketnum return eastmoney_agent.get_hist_money_flow(code) # 单位:万元 def get_realtime_money_flow(symbol): data = symbol.split(sep='.') market = data[1] if market == 'SH': marketnum = '1' else: marketnum = '2' code = data[0]+marketnum return eastmoney_agent.get_realtime_money_flow(code) # 单位:亿元 def get_realtime_money_flow_market(): return eastmoney_agent.get_realtime_money_flow_market() def get_hist_money_flow_market(): return eastmoney_agent.get_hist_money_flow_market() def get_allstock_flow(): return eastmoney_agent.get_allstock_flow()
29.488971
127
0.642688
import datetime from .stock_agent import SHExAgent, SZExAgent, CSIAgent, XueqiuAgent, SinaAgent, CNInfoAgent, EastMoneyAgent from opendatatools.common import get_current_day shex_agent = SHExAgent() szex_agent = SZExAgent() csi_agent = CSIAgent() xq_agent = XueqiuAgent() sina_agent = SinaAgent() cninfo_agent = CNInfoAgent() eastmoney_agent = EastMoneyAgent() xq_count_map = { '1m': -142, '5m': -142, '15m': -142, '30m': -142, '60m': -142, 'day' : -142, } bar_span_map = { '1m' : 1, '5m' : 5, '15m' : 15, '30m' : 30, '60m' : 60, 'day' : 1440, } def make_index(period, trade_date): bar_index = list() span = bar_span_map[period] dt = datetime.datetime.strptime(trade_date,'%Y-%m-%d') bar_index.extend(pd.DatetimeIndex(start="%s 09:30:00" % trade_date, end="%s 11:30:00" % trade_date, freq='%sT' % span)[1:]) bar_index.extend(pd.DatetimeIndex(start="%s 13:00:00" % trade_date, end="%s 15:00:00" % trade_date, freq='%sT' % span)[1:]) return bar_index def set_proxies(proxies): shex_agent.set_proxies(proxies) szex_agent.set_proxies(proxies) csi_agent.set_proxies(proxies) xq_agent.set_proxies(proxies) def get_index_list(market='SH'): if market == 'SH': return shex_agent.get_index_list() if market == 'SZ': return szex_agent.get_index_list() if market == 'CSI': return csi_agent.get_index_list() def get_index_component(symbol): temp = symbol.split(".") if len(temp) == 2: market = temp[1] index = temp[0] if market == 'SH': return shex_agent.get_index_component(index) elif market == 'SZ': return szex_agent.get_index_component(index) elif market == 'CSI': return csi_agent.get_index_component(index) else: return None else: return None def get_rzrq_info(market='SH', date = None): if date is None: date = get_current_day(format = '%Y-%m-%d') if market == 'SH': return shex_agent.get_rzrq_info(date) if market == 'SZ': return szex_agent.get_rzrq_info(date) return None, None def get_pledge_info(market='SH', date = None): if date is None: date = get_current_day(format = '%Y-%m-%d') if market == 'SH': return shex_agent.get_pledge_info(date) if market == 'SZ': return szex_agent.get_pledge_info(date) return None, None def get_dividend(symbol): temp = symbol.split(".") if len(temp) == 2: market = temp[1] code = temp[0] if market == 'SH': return shex_agent.get_dividend(code) if market == 'SZ': return cninfo_agent.get_dividend(code) def get_quote(symbols): return xq_agent.get_quote(symbols) def fill_df(df, period, trade_date, symbol): df.index = df['time'] index = make_index(period, trade_date) df_new = pd.DataFrame(index=index, columns=['last']) df_new['last'] = df['last'] df_new.fillna(method='ffill', inplace=True) df_new['high'] = df['high'] df_new['low'] = df['low'] df_new['open'] = df['open'] df_new.fillna(method='ffill', axis=1, inplace=True) df_new['change'] = df['change'] df_new['percent'] = df['percent'] df_new['symbol'] = symbol df_new['turnover_rate'] = df['turnover_rate'] df_new['volume'] = df['volume'] df_new['time'] = df_new.index df_new.fillna(0, inplace=True) return df_new def get_kline(symbol, trade_date, period): curr_date = datetime.datetime.strptime(trade_date, '%Y-%m-%d') next_date = datetime.datetime.strptime(trade_date, '%Y-%m-%d') + datetime.timedelta(days=1) timestamp = next_date.timestamp() timestamp = int ( timestamp * 1000) df, msg = xq_agent.get_kline(symbol, timestamp, period, xq_count_map[period]) if len(df) == 0: return df, msg df = df[(df.time < next_date) & (df.time >= curr_date)] if len(df) < abs(xq_count_map[period]): df_new = fill_df(df, period, trade_date, symbol) return df_new, '' else: return df, '' def get_kline_multisymbol(symbols, trade_date, period): symbol_list = symbols.split(',') timestamp = datetime.datetime.strptime(trade_date, '%Y-%m-%d').timestamp() timestamp = int ( timestamp * 1000) df, msg = xq_agent.get_kline_multisymbol(symbol_list, timestamp, period, xq_count_map[period]) next_date = datetime.datetime.strptime(trade_date, '%Y-%m-%d') + datetime.timedelta(days=1) if df is None: return df, msg df = df[df.time < next_date] gp = df.groupby('symbol') df_list = list() for symbol, df_item in gp: if len(df_item) < xq_count_map[period]: df_list.append(fill_df(df_item, period, trade_date, symbol)) else: df_list(df_item) return pd.concat(df_list), '' def get_timestamp_list(start_date, end_date): timestamp_list = [] curr_date = start_date while curr_date <= end_date: curr_datetime = datetime.datetime.strptime(curr_date, '%Y-%m-%d') timestamp = curr_datetime.timestamp() timestamp_list.append(int(timestamp * 1000)) next_time = curr_datetime + datetime.timedelta(days=1) curr_date = datetime.datetime.strftime(next_time, '%Y-%m-%d') return timestamp_list def get_kline_multidate(symbol, start_date, end_date, period): timestamp_list = get_timestamp_list(start_date, end_date) return xq_agent.get_kline_multitimestamp(symbol, timestamp_list, period, xq_count_map[period]) import pandas as pd def get_daily(symbol, start_date, end_date): curr_date = start_date df_result = [] while curr_date <= end_date: curr_datetime = datetime.datetime.strptime(curr_date, '%Y-%m-%d') next_time = curr_datetime + datetime.timedelta(days=100) next_date = datetime.datetime.strftime(next_time, '%Y-%m-%d') timestamp = curr_datetime.timestamp() df, msg = xq_agent.get_kline(symbol, int(timestamp*1000), 'day', 100) if df is not None and len(df) != 0: df_result.append(df[df['time']<next_time]) curr_date = next_date if len(df_result) > 0: df = pd.concat(df_result) df = df[(df['time'] >= start_date) & (df['time'] <= end_date) ] return df, '' else: return None, '没有获取到数据' def get_adj_factor(symbol): return sina_agent.get_adj_factor(symbol) def get_trade_detail(symbol, trade_date): return sina_agent.get_trade_detail(symbol, trade_date) def get_report_data(symbol='600000.SH', type='资产负债表'): dict_type = { '利润表' : 'lrb', '资产负债表' : 'fzb', '现金流量表' : 'llb', } if type not in dict_type: return None, 'type输入错误,可以输入 %s' % dict_type.keys() data = symbol.split(sep='.') market = data[1].lower() code = data[0] return cninfo_agent.get_report_data(market, code, dict_type[type]) def get_shareholder_structure(symbol='600000.SH'): data = symbol.split(sep='.') market = data[1].lower() code = data[0] return cninfo_agent.get_shareholder_structure(market, code) def get_hist_money_flow(symbol): data = symbol.split(sep='.') market = data[1] if market == 'SH': marketnum = '1' else: marketnum = '2' code = data[0]+marketnum return eastmoney_agent.get_hist_money_flow(code) def get_realtime_money_flow(symbol): data = symbol.split(sep='.') market = data[1] if market == 'SH': marketnum = '1' else: marketnum = '2' code = data[0]+marketnum return eastmoney_agent.get_realtime_money_flow(code) def get_realtime_money_flow_market(): return eastmoney_agent.get_realtime_money_flow_market() def get_hist_money_flow_market(): return eastmoney_agent.get_hist_money_flow_market() def get_allstock_flow(): return eastmoney_agent.get_allstock_flow()
true
true
1c393f3ee967e72fff88acc2c2b88e798cda569b
62,343
py
Python
pypsg/psg.py
AWehrhahn/PyPSG
adaa1e50998b3366541e16143034d6acdc379bb3
[ "MIT" ]
null
null
null
pypsg/psg.py
AWehrhahn/PyPSG
adaa1e50998b3366541e16143034d6acdc379bb3
[ "MIT" ]
null
null
null
pypsg/psg.py
AWehrhahn/PyPSG
adaa1e50998b3366541e16143034d6acdc379bb3
[ "MIT" ]
null
null
null
# --------------------------------------------------- # Planet Spectrum Generator Interface # PSG multiple-scattering model: https://psg.gsfc.nasa.gov/helpmodel.php # PSG databases: https://psg.gsfc.nasa.gov/helpatm.php # PSG API driver: https://psg.gsfc.nasa.gov/helpapi.php # --------------------------------------------------- from io import StringIO from os.path import dirname, join import subprocess from datetime import datetime import re import hashlib from tempfile import NamedTemporaryFile import numpy as np from astropy.utils.data import ( import_file_to_cache, download_file, clear_download_cache, is_url_in_cache, ) from astropy import units as u # Add Atmosphere scale units ppb = u.def_unit( ["ppb", "ppbv"], 1e-9 * u.one, namespace=globals(), doc="Parts Per Billion" ) ppm = u.def_unit( ["ppm", "ppmv", "ppv"], 1e3 * ppb, namespace=globals(), doc="Parts Per Million Volume", ) ppt = u.def_unit( ["ppt", "pptv"], 1e6 * ppb, namespace=globals(), doc="Parts Per Thousand Volume" ) m2 = u.def_unit( ["m2", "m-2"], None, namespace=globals(), doc="Molecules per square meter" ) diameter = u.def_unit( ["diameter"], None, namespace=globals(), doc="Diameter of the telescope" ) diffrac = u.def_unit( ["diffrac"], None, namespace=globals(), doc="defined by the telescope diameter and center wavelength", ) scl = u.def_unit(["scl"], None, namespace=globals(), doc="Relative Scale") u.add_enabled_units([ppb, ppm, ppt, m2, scl, diameter, diffrac]) # Package Name for the Astropy cache PKGNAME = "planet-spectrum-generator" class PSG_Config: def __init__(self, config) -> None: # Store all the other atmosphere parameters self.other = {} for key, value in config.items(): self.other[key] = value @staticmethod def get_value(config, key, func=None): try: value = config[key] if func is not None: value = func(value) except KeyError: value = None return value def get_quantity(self, config, key, unit): return self.get_value(config, key, lambda x: float(x) * unit) def get_bool(self, config, key, true_value="Y"): return self.get_value(config, key, lambda x: x == true_value) def get_list(self, config, key, func=None, array=False, sep=","): value = self.get_value(config, key, lambda x: x.split(",")) if value is None: return None if func is not None: value = [func(v) for v in value] if array: value = np.array(value) return value @staticmethod def parse_units(unit, units, names): if unit is None: return None for u, n in zip(units, names): if unit == n: return u raise ValueError("Could not parse unit") @staticmethod def get_units(unit, units, names): if unit is None: return None, None for un, n in zip(units, names): if unit == un: return un, n for un, n in zip(units, names): try: unit.to(un) return un, n except u.core.UnitConversionError: continue raise ValueError("Could not determine units") def to_config(self): return self.other class PSG_Object(PSG_Config): def __init__(self, config) -> None: #:str: Object type (e.g., Exoplanet, Planet, Asteroid, Moon, Comet, Object) self.object = config.get("OBJECT") #:str: Object name self.name = config.get("OBJECT-NAME") # Datetime if "OBJECT-DATE" in config.keys(): match = re.match( r"(\d{4})/(\d{2})/(\d{2}) (\d{2}):(\d{2})", config["OBJECT-DATE"] ) date = datetime( int(match.group(1)), int(match.group(2)), int(match.group(3)), int(match.group(4)), int(match.group(5)), ) else: date = None #:datetime: Date of the observation (yyyy/mm/dd hh:mm) in Universal time [UT] self.date = date #:Quantity: Diameter of the object [km] self.diameter = self.get_quantity(config, "OBJECT-DIAMETER", u.km) # Gravity gravity_unit = config.get("OBJECT-GRAVITY-UNIT") if gravity_unit == "g": # Surface Gravity gravity_unit = u.m / u.s ** 2 elif gravity_unit == "rho": # Mean Density gravity_unit = u.g / u.cm ** 3 elif gravity_unit == "kg": # Total Mass gravity_unit = u.kg #:Quantity: Gravity/density/mass of the object self.gravity = self.get_quantity(config, "OBJECT-GRAVITY", gravity_unit) #:Quantity: Distance of the planet to the Sun [AU], and for exoplanets the semi-major axis [AU] self.star_distance = self.get_quantity(config, "OBJECT-STAR-DISTANCE", u.AU) #:Quantity: Velocity of the planet to the Sun [km/s], and for exoplanets the RV amplitude [km/s] self.star_velocity = self.get_quantity(config, "OBJECT-STAR-VELOCITY", (u.km / u.s)) #:Quantity: Sub-solar east longitude [degrees] self.solar_longitude = self.get_quantity(config, "OBJECT-SOLAR-LONGITUDE", u.deg) #:Quantity: Sub-solar latitude [degrees] self.solar_latitude = self.get_quantity(config, "OBJECT-SOLAR-LATITUDE", u.deg) #:Quantity: Angular parameter (season/phase) that defines the position of the planet moving along its Keplerian orbit. For exoplanets, 0:Secondary transit, 180:Primary transit, 90/270:Opposition. For solar-system bodies, 0:'N spring equinox', 90:'N summer solstice', 180:'N autumn equinox', 270:'N winter solstice' [degrees] self.season = self.get_quantity(config, "OBJECT-SEASON", u.deg) #:Quantity: Orbital inclination [degree], mainly relevant for exoplanets. Zero is phase on, 90 is a transiting orbit self.inclination = self.get_quantity(config, "OBJECT-INCLINATION", u.deg) #:float: Orbital eccentricity, mainly relevant for exoplanets self.eccentricity = self.get_value(config, "OBJECT-ECCENTRICITY", float) #:Quantity: Orbital longitude of periapse [degrees]. It indicates the phase at which the planet reaches periapsis self.periapsis = self.get_quantity(config, "OBJECT-PERIAPSIS", u.deg) #:str: Stellar type of the parent star [O/B/A/F/G/K/M] self.star_type = config.get("OBJECT-STAR-TYPE") #:Quantity: Temperature of the parent star [K] self.star_temperature = self.get_quantity(config, "OBJECT-STAR-TEMPERATURE", u.K) #:Quantity: Radius of the parent star [Rsun] self.star_radius = self.get_quantity(config, "OBJECT-STAR-RADIUS", u.Rsun) #:float: Metallicity of the parent star and object with respect to the Sun in log [dex] self.star_metallicity = self.get_value(config, "OBJECT-STAR-METALLICITY", float) #:Quantity: Sub-observer east longitude [degrees] self.obs_longitude = self.get_quantity(config, "OBJECT-OBS-LONGITUDE", u.deg) #:Quantity: Sub-observer latitude, for exoplanets inclination [degrees] self.obs_latitude = self.get_quantity(config, "OBJECT-OBS-LATITUDE", u.deg) #:Quantity: Relative velocity between the observer and the object [km/s] self.obs_velocity = self.get_quantity(config, "OBJECT-OBS-VELOCITY", u.km / u.s) #:Quantity: This field is computed by the geometry module - It is the apparent rotational period of the object as seen from the observer [days] self.period = self.get_quantity(config, "OBJECT-PERIOD", u.day) #:str: This field reports the orbital parameters for small bodies. It is only relevant for display purposes of the orbital diagram. self.orbit = config.get("OBJECT-ORBIT") @property def gravity_unit(self): """ Unit for the OBJECT-GRAVITY field, g:'Surface gravity [m/s2]', rho:'Mean density [g/cm3]', or kg:'Total mass [kg]' """ return self.gravity.unit def to_config(self): gravity_unit_loc, gravity_unit = self.get_units( self.gravity_unit, [u.m / u.s ** 2, u.g / u.cm ** 3, u.kg], ["g", "rho", "kg"], ) config = { "OBJECT": self.object, "OBJECT-NAME": self.name, "OBJECT-DATE": f"{self.date.year:04}/{self.date.month:02}/{self.date.day:02} {self.date.hour:02}:{self.date.minute:02}" if self.date is not None else None, "OBJECT-DIAMETER": self.diameter.to_value(u.km) if self.diameter is not None else None, "OBJECT-GRAVITY": self.gravity.to_value(gravity_unit_loc) if self.gravity is not None and gravity_unit_loc is not None else None, "OBJECT-GRAVITY-UNIT": gravity_unit, "OBJECT-STAR-DISTANCE": self.star_distance.to_value(u.AU) if self.star_distance is not None else None, "OBJECT-STAR-VELOCITY": self.star_velocity.to_value(u.km / u.s) if self.star_velocity is not None else None, "OBJECT-SOLAR-LONGITUDE": self.solar_longitude.to_value(u.deg) if self.solar_longitude is not None else None, "OBJECT-SOLAR-LATITUDE": self.solar_latitude.to_value(u.deg) if self.solar_latitude is not None else None, "OBJECT-SEASON": self.season.to_value(u.deg) if self.season is not None else None, "OBJECT-INCLINATION": self.inclination.to_value(u.deg) if self.inclination is not None else None, "OBJECT-ECCENTRICITY": self.eccentricity, "OBJECT-PERIAPSIS": self.periapsis.to_value(u.deg) if self.periapsis is not None else None, "OBJECT-STAR-TYPE": self.star_type, "OBJECT-STAR-TEMPERATURE": self.star_temperature.to_value(u.K) if self.star_temperature is not None else None, "OBJECT-STAR-RADIUS": self.star_radius.to_value(u.Rsun) if self.star_radius is not None else None, "OBJECT-STAR-METALLICITY": self.star_metallicity, "OBJECT-OBS-LONGITUDE": self.obs_longitude.to_value(u.deg) if self.obs_longitude is not None else None, "OBJECT-OBS-LATITUDE": self.obs_latitude.to_value(u.deg) if self.obs_latitude is not None else None, "OBJECT-OBS-VELOCITY": self.obs_velocity.to_value(u.km / u.s) if self.obs_velocity is not None else None, "OBJECT-PERIOD": self.period.to_value(u.day) if self.period is not None else None, "OBJECT-ORBIT": self.orbit, } config = {k: str(v) for k, v in config.items() if v is not None} return config class PSG_Geometry(PSG_Config): def __init__(self, config) -> None: #:str: Type of observing geometry self.geometry = config.get("GEOMETRY") #:str: Reference geometry (e.g., ExoMars, Maunakea), default is user defined or 'User' self.ref = config.get("GEOMETRY-REF") offset_unit = config.get("GEOMETRY-OFFSET-UNIT") offset_unit = self.parse_units(offset_unit, [u.arcsec, u.arcmin, u.deg, u.km, u.one], ["arcsec", "arcmin", "degree", "km", "diameter"],) #:quantity: Vertical offset with respect to the sub-observer location self.offset_ns = self.get_quantity(config, "GEOMETRY-OFFSET-NS", offset_unit) #:quantity: Horizontal offset with respect to the sub-observer location self.offset_ew = self.get_quantity(config, "GEOMETRY-OFFSET-EW", offset_unit) altitude_unit = config.get("GEOMETRY-ALTITUDE-UNIT") altitude_unit = self.parse_units(altitude_unit, [u.AU, u.km, u.one, u.pc], ["AU", "km", "diameter", "pc"]) #:quantity: Distance between the observer and the surface of the planet self.obs_altitude = self.get_quantity(config, "GEOMETRY-OBS-ALTITUDE", altitude_unit) #:quantity: The azimuth angle between the observational projected vector and the solar vector on the reference plane self.azimuth = self.get_quantity(config, "GEOMETRY-AZIMUTH", u.deg) #:float: Parameter for the selected geometry, for Nadir / Lookingup this field indicates the zenith angle [degrees], for limb / occultations this field indicates the atmospheric height [km] being sampled self.user_param = self.get_value(config, "GEOMETRY-USER-PARAM", float) #:str: For stellar occultations, this field indicates the type of the occultation star [O/B/A/F/G/K/M] self.stellar_type = config.get("GEOMETRY-STELLAR-TYPE") #:quantity: For stellar occultations, this field indicates the temperature [K] of the occultation star self.stellar_temperature = self.get_quantity(config, "GEOMETRY-STELLAR-TEMPERATURE", u.K) #:quantity: For stellar occultations, this field indicates the brightness [magnitude] of the occultation star self.stellar_magnitude = self.get_quantity(config, "GEOMETRY-STELLAR-MAGNITUDE", u.mag) #:str: This field is computed by the geometry module - It indicates the angle between the observer and the planetary surface self.obs_angle = config.get("GEOMETRY-OBS-ANGLE") #:str: This field is computed by the geometry module - It indicates the angle between the Sun and the planetary surface self.solar_angle = config.get("GEOMETRY-SOLAR-ANGLE") #:int: This field allows to divide the observable disk in finite rings so radiative-transfer calculations are performed with higher accuracy self.disk_angles = int(config.get("GEOMETRY-DISK-ANGLES")) #:quantity: This field is computed by the geometry module - It indicates the phase between the Sun and observer self.phase = self.get_quantity(config, "GEOMETRY-PHASE", u.deg) #:str: This field is computed by the geometry module - It indicates how much the beam fills the planetary area (1:maximum) self.planet_fraction = config.get("GEOMETRY-PLANET-FRACTION") #:float: This field is computed by the geometry module - It indicates how much the beam fills the parent star (1:maximum) self.star_fraction = self.get_value(config, "GEOMETRY-STAR-FRACTION", float) #:float: This field is computed by the geometry module - It indicates the projected distance between the beam and the parent star in arcsceconds self.star_distance = self.get_value(config, "GEOMETRY-STAR-DISTANCE", float) #:str: This field is computed by the geometry module - It indicates the rotational Doppler shift [km/s] affecting the spectra and the spread of rotational velocities [km/s] within the FOV self.rotation = config.get("GEOMETRY-ROTATION") #:str: This field is computed by the geometry module - It indicates the scaling factor between the integrated reflectance for the FOV with respect to the BRDF as computed using the geometry indidence/emission angles self.brdfscaler = config.get("GEOMETRY-BRDFSCALER") @property def offset_unit(self): """ Unit of the GEOMETRY-OFFSET field, arcsec / arcmin / degree / km / diameter """ return self.offset_ns.unit @property def altitude_unit(self): """ Unit of the GEOMETRY-OBS-ALTITUDE field, AU / km / diameter and pc:'parsec' """ return self.obs_altitude.unit def to_config(self): loc_offset_unit, offset_unit = self.get_units( self.offset_unit, [u.arcsec, u.arcmin, u.deg, u.km, u.one], ["arcsec", "arcmin", "degree", "km", "diameter"], ) loc_altitude_unit, altitude_unit = self.get_units( self.altitude_unit, [u.AU, u.km, u.pc, u.one], ["AU", "km", "pc", "diameter"], ) config = { "GEOMETRY": self.geometry, "GEOMETRY-REF": self.ref, "GEOMETRY-OFFSET-NS": self.offset_ns.to_value(loc_offset_unit) if self.offset_ns is not None and loc_offset_unit is not None else None, "GEOMETRY-OFFSET-EW": self.offset_ew.to_value(loc_offset_unit) if self.offset_ew is not None and loc_offset_unit is not None else None, "GEOMETRY-OFFSET-UNIT": offset_unit, "GEOMETRY-OBS-ALTITUDE": self.obs_altitude.to_value(loc_altitude_unit) if self.obs_altitude is not None and loc_altitude_unit is not None else None, "GEOMETRY-ALTITUDE-UNIT": altitude_unit, "GEOMETRY-AZIMUTH": self.azimuth.to_value(u.deg) if self.azimuth is not None else None, "GEOMETRY-USER-PARAM": self.user_param, "GEOMETRY-STELLAR-TYPE": self.stellar_type, "GEOMETRY-STELLAR-TEMPERATURE": self.stellar_temperature.to_value(u.K) if self.stellar_temperature is not None else None, "GEOMETRY-STELLAR-MAGNITUDE": self.stellar_magnitude.to_value(u.mag) if self.stellar_magnitude is not None else None, "GEOMETRY-OBS-ANGLE": self.obs_angle, "GEOMETRY-SOLAR-ANGLE": self.solar_angle, "GEOMETRY-DISK-ANGLES": self.disk_angles, "GEOMETRY-PHASE": self.phase.to_value(u.deg) if self.phase is not None else None, "GEOMETRY-PLANET-FRACTION": self.planet_fraction, "GEOMETRY-STAR-FRACTION": self.star_fraction, "GEOMETRY-STAR-DISTANCE": self.star_distance, "GEOMETRY-ROTATION": self.rotation, "GEOMETRY-BRDFSCALER": self.brdfscaler, } config = {k: str(v) for k, v in config.items() if v is not None} return config class PSG_Atmosphere(PSG_Config): # from https://hitran.org/docs/molec-meta/ hitran_molecule_id = { "H2O": 1, "CO2": 2, "O3": 3, "N2O": 4, "CO": 5, "CH4": 6, "O2": 7, "NO": 8, "SO2": 9, "NO2": 10, "NH3": 11, "HNO3": 12, "OH": 13, "HF": 14, "HCl": 15, "HBr": 16, "HI": 17, "ClO": 18, "OCS": 19, "H2CO": 20, "HOCl": 21, "N2": 22, "HCN": 23, "CH3Cl": 24, "H2O2": 25, "C2H2": 26, "C2H6": 27, "PH3": 28, "COF2": 29, "SF6": 30, "H2S": 31, "HCOOH": 32, "HO2": 33, "O": 34, "ClONO2": 35, "NO+": 36, "HOBr": 37, "C2H4": 38, "CH3OH": 39, "CH3Br": 40, "CH3CN": 41, "CF4": 42, "C4H2": 43, "HC3N": 44, "H2": 45, "CS": 46, "SO3": 47, "C2N2": 48, "COCl2": 49, "CS2": 53, "NF3": 55, } def __init__(self, config) -> None: # Handle the component molecules self._gas = self.get_list(config, "ATMOSPHERE-GAS") #:list(str): Sub-type of the gases, e.g. 'HIT[1], HIT[2]' self.type = self.get_list(config, "ATMOSPHERE-TYPE") abun = self.get_list(config, "ATMOSPHERE-ABUN", func=float) unit = self.get_list(config, "ATMOSPHERE-UNIT", func=u.Unit) #:list(quantity): Abundance of gases. The values can be assumed to be same across all altitudes/layers [%,ppmv,ppbv,pptv,m-2], or as a multiplier [scl] to the provided vertical profile self.abun = [a * u for a, u in zip(abun, unit)] if abun is not None and unit is not None else None # Handle the Aerosols self._aeros = self.get_list(config, "ATMOSPHERE-AEROS") #:list(str): Sub-type of the aerosols self.atype = self.get_list(config, "ATMOSPHERE-ATYPE") abun = self.get_list(config, "ATMOSPHERE-AABUN", func=float) unit = self.get_list(config, "ATMOSPHERE-AUNIT", func=u.Unit) #:list(quantity): Abundance of aerosols. The values can be assumed to be same across all altitudes/layers [%,ppm,ppb,ppt,Kg/m2], or as a multiplier [scaler] to the provided vertical profile self.aabun = [a * u for a, u in zip(abun, unit)] if abun is not None and unit is not None else None size = self.get_list(config, "ATMOSPHERE-ASIZE", func=float) unit = self.get_list(config, "ATMOSPHERE-ASUNI", func=float) #:list(quantity): Effective radius of the aerosol particles. The values can be assumed to be same across all layers [um, m, log(um)], or as a multiplier [scaler] to the provided size vertical profile self.asize = [a * u for a, u in zip(size, unit)] if size is not None and unit is not None else None # Handle the atmosphere layers #:list(str): Molecules quantified by the vertical profile self.layers_molecules = self.get_list(config, "ATMOSPHERE-LAYERS-MOLECULES") nlayers = self.get_value(config, "ATMOSPHERE-LAYERS", int) if nlayers is not None: try: layers = [config[f"ATMOSPHERE-LAYER-{i}"] for i in range(1, nlayers + 1)] layers = StringIO("\n".join(layers)) layers = np.genfromtxt(layers, delimiter=",") except KeyError: layers = None else: layers = None #:array: Values for that specific layer: Pressure[bar], Temperature[K], gases[mol/mol], aerosols [kg/kg] - Optional fields: Altitude[km], X_size[m, aerosol X particle size] self.layer = layers #:str: Parameters defining the 3D General Circulation Model grid: num_lons, num_lats, num_alts, lon0, lat0, delta_lon, delta_lat, variables (csv) self.gcm_parameters = config.get("ATMOSPHERE-GCM-PARAMETERS") #:str: The structure of the atmosphere, None / Equilibrium:'Hydrostatic equilibrium' / Coma:'Cometary expanding coma' self.structure = config.get("ATMOSPHERE-STRUCTURE") #:float: For equilibrium atmospheres, this field defines the surface pressure; while for cometary coma, this field indicates the gas production rate self.pressure = self.get_value(config, "ATMOSPHERE-PRESSURE", float) #:str: The unit of the ATMOSPHERE-PRESSURE field, Pa:Pascal / bar / kbar / mbar / ubar / at / atm / torr / psi / gas:'molecules / second' / gasau:'molecules / second at rh=1AU' self.punit = config.get("ATMOSPHERE-PUNIT") #:quantity: For atmospheres without a defined P/T profile, this field indicates the temperature across all altitudes self.temperature = self.get_quantity(config, "ATMOSPHERE-TEMPERATURE", u.K) #:float: Molecular weight of the atmosphere [g/mol] or expansion velocity [m/s] for expanding atmospheres self.weight = self.get_value(config, "ATMOSPHERE-WEIGHT", float) #:str: Continuum processes to be included in the calculation self.continuum = config.get("ATMOSPHERE-CONTINUUM") #:str: For expanding cometary coma, this field indicates the photodissociation lifetime of the molecules [s] self.tau = config.get("ATMOSPHERE-TAU") #:int: When performing scattering aerosols calculations, this parameter indicates the number of n-stream pairs - Use 0 for extinction calculations only (e.g. transit, occultation) self.nmax = self.get_value(config, "ATMOSPHERE-NMAX", int) #:int: When performing scattering aerosols calculations, this parameter indicates the number of scattering Legendre polynomials used for describing the phase function - Use 0 for extinction calculations only (e.g. transit, occultation) self.lmax = self.get_value(config, "ATMOSPHERE-LMAX", int) #:str: Description establishing the source/reference for the vertical profile self.description = config.get("ATMOSPHERE-DESCRIPTION") def to_config(self): config = { "ATMOSPHERE-NGAS": self.ngas, "ATMOSPHERE-GAS": ",".join([str(v) for v in self.gas]) if self.gas is not None else None, "ATMOSPHERE-TYPE": ",".join([str(v) for v in self.type]) if self.type is not None else None, "ATMOSPHERE-ABUN": ",".join([str(v.value) for v in self.abun]) if self.abun is not None else None, "ATMOSPHERE-UNIT": ",".join([str(v.unit) for v in self.abun]) if self.abun is not None else None, "ATMOSPHERE-NAERO": self.naero, "ATMOSPHERE-AEROS": ",".join([str(v) for v in self.aeros]) if self.aeros is not None else None, "ATMOSPHERE-ATYPE": ",".join([str(v) for v in self.atype]) if self.atype is not None else None, "ATMOSPHERE-AABUN": ",".join([str(v.value) for v in self.aabun]) if self.aabun is not None else None, "ATMOSPHERE-AUNIT": ",".join([str(v.unit) for v in self.aabun]) if self.aabun is not None else None, "ATMOSPHERE-ASIZE": ",".join([str(v.value) for v in self.asize]) if self.asize is not None else None, "ATMOSPHERE-ASUNI": ",".join([str(v.unit) for v in self.asize]) if self.asize is not None else None, "ATMOSPHERE-LAYERS-MOLECULES": ",".join( [str(v) for v in self.layers_molecules] ) if self.layers_molecules is not None else None, "ATMOSPHERE-LAYERS": self.layers , "ATMOSPHERE-STRUCTURE": self.structure, "ATMOSPHERE-PRESSURE": self.pressure, "ATMOSPHERE-PUNIT": self.punit, "ATMOSPHERE-TEMPERATURE": self.temperature.to_value(u.K) if self.temperature is not None else None, "ATMOSPHERE-WEIGHT": self.weight, "ATMOSPHERE-CONTINUUM": self.continuum, "ATMOSPHERE-TAU": self.tau, "ATMOSPHERE-NMAX": self.nmax, "ATMOSPHERE-LMAX": self.lmax, "ATMOSPHERE-DESCRIPTION": self.description, "ATMOSPHERE-GCM-PARAMETERS": self.gcm_parameters, } if self.layers is not None: for i in range(1, self.layers + 1): config[f"ATMOSPHERE-LAYER-{i}"] = np.array2string( self.layer[i - 1], separator=",", max_line_width=np.inf )[1:-1] config = {k: str(v) for k, v in config.items() if v is not None} return config @property def gas(self): #:list(str): Name of the gases to include in the simulation, e.g 'H2O, CO2'. Only these will considered for the radiative transfer return self._gas @gas.setter def gas(self, value): self._gas = value self.abun = [1 * scl] * len(value) self.type = [f"HIT[{self.hitran_molecule_id[v]}]" for v in self.gas] @property def unit(self): #:list(unit): Unit of the ATMOSPHERE-ABUN field, % / ppmv / ppbv / pptv / m2:'molecules/m2' / scl:'scaler of profile' return [a.unit for a in self.abun] @property def ngas(self): #:int: Number of gases to include in the simulation, maximum 20 return len(self.gas) @property def aeros(self): return self._aeros @aeros.setter def aeros(self, value): self._aeros = value self.aabun = [1 * scl] * len(value) self.atype = [""] * len(value) self.asize = [1 * scl] * len(value) @property def aunit(self): #:list(unit): Unit of the ATMOSPHERE-AABUN field, % / ppmv / ppbv / pptv / m2:'molecules/m2' / scl:'scaler of profile' return [a.unit for a in self.aabun] @property def asuni(self): #:list(init): Unit of the size of the aerosol particles if self.asize is None: return None return [a.unit for a in self.asize] @property def naero(self): #:int: Number of aerosols to include in the simulation, maximum 20 if self.aeros is None: return None return len(self.aeros) @property def layers(self): return self.layer.shape[0] class PSG_Surface(PSG_Config): def __init__(self, config) -> None: #:str: Type of scattering model describing the surface, and the model parameters self.model = self.get_value(config, "SURFACE-MODEL") #:quantity: Temperature of the surface [K] self.temperature = self.get_quantity(config, "SURFACE-TEMPERATURE", u.K) #:float: Albedo the surface [0:non-reflectance, 1:fully-reflective] self.albedo = self.get_value(config, "SURFACE-ALBEDO", float) #:float: Emissivity of the surface [0:non-emitting, 1:perfect-emitter] self.emissivity = self.get_value(config, "SURFACE-EMISSIVITY", float) #:float: For expanding cometary coma, this value indicates an scaling value for the dust in the coma self.gas_ratio = self.get_value(config, "SURFACE-GAS-RATIO", float) #:str: Unit of the dust abundance, [ratio] is dust/gas mass ratio, while [afrho] is the Afrho value and [lafrho] is log[Afrho/Q] self.gas_unit = config.get("SURFACE-GAS-UNIT") #:int: Number of components describing the surface properties [areal mixing] self.nsurf = self.get_value(config, "SURFACE-NSURF", int) #:str: Name of surface components to be included in the simulation self.surf = config.get("SURFACE-SURF") #:str: Sub-type of the surface components self.type = config.get("SURFACE-TYPE") #:str: Relative abundance of the surface components. For the remaining abundance, average surface albedo/emissivity will be considered self.abun = config.get("SURFACE-ABUN") #:Unit: Unit of the SURFACE-ABUN field, % / ppm / ppv self.unit = self.get_value(config, "SURFACE-UNIT", u.Unit) #:str: Thickness for each surface component [um] self.thick = self.get_quantity(config, "SURFACE-THICK", u.um) def to_config(self): config = { "SURFACE-MODEL": self.model, "SURFACE-TEMPERATURE": self.temperature.to_value(u.K) if self.temperature is not None else None, "SURFACE-ALBEDO": self.albedo, "SURFACE-EMISSIVITY": self.emissivity, "SURFACE-GAS-RATIO": self.gas_ratio, "SURFACE-GAS-UNIT": self.gas_unit, "SURFACE-NSURF": self.nsurf, "SURFACE-SURF": self.surf, "SURFACE-TYPE": self.type, "SURFACE-ABUN": self.abun, "SURFACE-UNIT": self.unit, "SURFACE-THICK": self.thick.to_value(u.um) if self.thick is not None else None, } config = {k: str(v) for k, v in config.items() if v is not None} return config class PSG_Generator(PSG_Config): def __init__(self, config) -> None: # Unit of the GENERATOR-RANGE fields, um / nm / mm / An:'Angstrom' / cm:'Wavenumber [cm-1]' / MHz / GHz / kHz range_unit = config.get("GENERATOR-RANGEUNIT") range_unit = self.parse_units(range_unit, [u.um, u.nm, u.mm, u.AA, 1 / u.cm, u.MHz, u.GHz, u.kHz], ["um", "nm", "An", "cm", "MHz", "GHz", "kHz"],) #:quantity: Lower spectral range for the simulation self.range1 = self.get_quantity(config, "GENERATOR-RANGE1", range_unit) #:quantity: Upper spectral range for the simulation self.range2 = self.get_quantity(config, "GENERATOR-RANGE2", range_unit) resolution_unit = config.get("GENERATOR-RESOLUTIONUNIT") resolution_unit = self.parse_units(resolution_unit, [u.one, u.um, u.nm, u.mm, u.AA, 1/u.cm, u.MHz, u.GHz, u.kHz], ["RP", "um", "nm", "mm", "An", "cm", "MHz", "GHz", "kHz"]) #:quantity: Spectral resolution for the simulation. PSG assumes that the sampling resolution is equal is to the instrumental resolution, yet radiative transfer resolutions are always performed at the necessary/higher resolutions in order to accurately describe the lineshapes self.resolution = self.get_quantity(config, "GENERATOR-RESOLUTION", resolution_unit) #:bool: Convolution kernel applied to the spectra, default is 'N' self.resolution_kernel = self.get_bool(config, "GENERATOR-RESOLUTIONKERNEL") #:bool: Flag indicating whether to include molecular signatures as generated with PUMAS or CEM [Y/N] self.gas_model = self.get_bool(config, "GENERATOR-GAS-MODEL") #:bool: Flag indicating whether to include continuum signatures as generated by the surface, the star (when in the field) and dust/nucleus (when synthesizing comets) [Y/N] self.cont_model = self.get_bool(config, "GENERATOR-CONT-MODEL") #:bool: Flag indicating whether to include stellar absorption signatures in the reflected sunlight / stellar spectra [Y/N] self.cont_stellar = self.get_bool(config, "GENERATOR-CONT-STELLAR") #:bool: Flag indicating whether we are synthesizing planetary spectra as observed with a ground-based telescope. This flag will ensure that the noise module properly includes telluric signatures self.trans_show = self.get_bool(config, "GENERATOR-TRANS-SHOW") #:bool: Flag indicating whether to show the spectra as observed and multiplied by the telluric transmittance [Y] self.trans_apply = self.get_bool(config, "GENERATOR-TRANS-APPLY") #:str: Keyword [SS-WW] indicating the site [SS] and water abundance [WW]. Values of SS are 00:'0m (sea level)', 01:'2,600m (8,500 feet)', 02:'4,200m (14,000 feet)', 03:'14,000m (46,000 feet)', 04:'35,000m (120,000 feet)'. Values of WW are 00:'10% tropical', 01:'30% tropical', 02:'70% tropical', 03:'100% tropical' self.trans = config.get("GENERATOR-TRANS") #:str: Radiation unit for the generated spectra, see full list of permitted keywords in the 'Modeling > Radiation Units' section self.rad_units = config.get("GENERATOR-RADUNITS") #:bool: Flag indicating whether to show the spectra employing a logarithmic scale self.lograd = self.get_bool(config, "GENERATOR-LOGRAD") #:str: Type of telescope, SINGLE:'single dish telescope or instrument', ARRAY:'Interferometric array', CORONA:'Coronagraph', AOTF or LIDAR self.telescope = config.get("GENERATOR-TELESCOPE") beam_unit = self.get_value(config, "GENERATOR-BEAM-UNIT", u.Unit) #:quantity: Full width half-maximum (FWHM) of the instrument's beam or field-of-view (FOV) self.beam = self.get_quantity(config, "GENERATOR-BEAM", beam_unit) #:quantity: Diameter of the main reflecting surface of the telescope or instrument [m] self.diam_tele = self.get_quantity(config, "GENERATOR-DIAMTELE", u.m) #:str: For interferometers, the number of telescopes; for coronagraphs, the instrument's contrast self.telescope1 = config.get("GENERATOR-TELESCOPE1") #:str: This field indicates the zodi-level (1.0:Ecliptic pole/minimum, 2.0:HST/JWST low values, 10.0:Normal values, 100.0:Close to ecliptic/Sun), or order number for the AOTF system. For coronagraphs, this field indicates allows two entries: the exozodi level and the local zodiacal dust level self.telescope2 = config.get("GENERATOR-TELESCOPE2") #:str: For coronagraphic observations, the inner working angle (IWA) in units of [L/D] self.telescope3 = config.get("GENERATOR-TELESCOPE3") #:str: Keyword identifying the noise model to consider, NO:'None', TRX:'Receiver temperature', RMS:'Constant noise in radiation units', BKG:'Constant noise with added background', NEP:'Power equivalent noise detector model', D*:'Detectability noise detector model', CCD:'Image sensor' self.noise = config.get("GENERATOR-NOISE") #:quantity: Exposure time per frame [sec] self.noise_time = self.get_quantity(config, "GENERATOR-NOISETIME", u.s) #:int: Number of exposures self.noise_frames = self.get_value(config, "GENERATOR-NOISEFRAMES", int) #:int: Total number of pixels that encompass the beam (GENERATOR-BEAM) and the spectral unit (GENERATOR-RESOLUTION) self.noise_pixels = self.get_value(config, "GENERATOR-NOISEPIXELS", int) #:str: First noise model parameter - For RMS, 1-sigma noise; for TRX, the receiver temperature; for BKG, the 1-sigma noise; for NEP, the sensitivity in W/sqrt(Hz); for DET, the sensitivity in cm.sqrt(Hz)/W; for CCD, the read noise [e-] self.noise1 = config.get("GENERATOR-NOISE1") #:str: Second noise model parameter - For RMS, not used; for TRX, the sideband g-factor; for BKG, the not used; for NEP, not used; for DET, the pixel size [um]; for CCD, the dark rate [e-/s] self.noise2 = config.get("GENERATOR-NOISE2") #:float: Total throughput of the telescope+instrument, from photons arriving to the main mirror to photons being quantified by the detector [0:none to 1:perfect]. The user can provide wavelength dependent values as neff@wavelength[um] (e.g., '0.087@2.28,0.089@2.30,0.092@2.31,0.094@2.32,...') self.noise_oeff = config.get("GENERATOR-NOISEOEFF") #:float: Emissivity of the telescope+instrument optics [0 to 1] self.noise_oemis = self.get_value(config, "GENERATOR-NOISEOEMIS", float) #:float: Temperature of the telescope+instrument optics [K] self.noise_otemp = self.get_quantity(config, "GENERATOR-NOISEOTEMP", u.K) #:str: Text describing if an instrument template was used to define the GENERATOR parameters self.instrument = config.get("GENERATOR-INSTRUMENT") #:float: Well depth [e-] of each pixel detector self.noise_well = self.get_value(config, "GENERATOR-NOISEWELL", float) #:float: Spatial binning applied to the GCM data when computing spectra. 1: Full resolution self.gcm_binning = self.get_value(config, "GENERATOR-GCM-BINNING", float) @property def range_unit(self): return self.range1.unit @property def resolution_unit(self): return self.resolution.unit @property def beam_unit(self): return self.beam.unit def to_config(self): range_unit_loc, range_unit = self.get_units( self.range_unit, [u.um, u.nm, u.mm, u.AA, 1 / u.cm, u.MHz, u.GHz, u.kHz], ["um", "nm", "An", "cm", "MHz", "GHz", "kHz"], ) resolution_unit_loc, resolution_unit = self.get_units( self.resolution_unit, [u.one, u.um, u.nm, u.mm, u.AA, 1 / u.cm, u.MHz, u.GHz, u.kHz], ["RP", "um", "nm", "mm", "An", "cm", "MHz", "GHz", "kHz"], ) beam_unit_loc, beam_unit = self.get_units( self.beam_unit, [u.arcsec, u.arcmin, u.deg, u.km, diameter, diffrac], ["arcsec", "arcmin", "degree", "km", "diameter", "diffrac"], ) config = { "GENERATOR-RANGE1": self.range1.to_value(range_unit_loc) if self.range1 is not None and range_unit_loc is not None else None, "GENERATOR-RANGE2": self.range2.to_value(range_unit_loc) if self.range2 is not None and range_unit_loc is not None else None, "GENERATOR-RANGEUNIT": range_unit, "GENERATOR-RESOLUTION": self.resolution.to_value(resolution_unit_loc) if self.resolution is not None and resolution_unit_loc is not None else None, "GENERATOR-RESOLUTIONUNIT": resolution_unit, "GENERATOR-RESOLUTIONKERNEL": "Y" if self.resolution_kernel else "N" if self.resolution_kernel is not None else None, "GENERATOR-GAS-MODEL": "Y" if self.gas_model else "N" if self.gas_model is not None else None, "GENERATOR-CONT-MODEL": "Y" if self.cont_model else "N" if self.cont_model is not None else None, "GENERATOR-CONT-STELLAR": "Y" if self.cont_stellar else "N" if self.cont_stellar is not None else None, "GENERATOR-TRANS-SHOW": "Y" if self.trans_show else "N" if self.trans_show is not None else None, "GENERATOR-TRANS-APPLY": "Y" if self.trans_apply else "N" if self.trans_apply is not None else None, "GENERATOR-TRANS": self.trans, "GENERATOR-RADUNITS": self.rad_units, "GENERATOR-LOGRAD": "Y" if self.lograd else "N" if self.lograd is not None else None, "GENERATOR-TELESCOPE": self.telescope, "GENERATOR-BEAM": self.beam.to_value(beam_unit_loc) if self.beam is not None and beam_unit_loc is not None else None, "GENERATOR-BEAM-UNIT": beam_unit, "GENERATOR-DIAMTELE": self.diam_tele.to_value(u.m) if self.diam_tele is not None else None, "GENERATOR-TELESCOPE1": self.telescope1, "GENERATOR-TELESCOPE2": self.telescope2, "GENERATOR-TELESCOPE3": self.telescope3, "GENERATOR-NOISE": self.noise, "GENERATOR-NOISETIME": self.noise_time.to_value(u.s) if self.noise_time is not None else None, "GENERATOR-NOISEFRAMES": self.noise_frames, "GENERATOR-NOISEPIXELS": self.noise_pixels, "GENERATOR-NOISE1": self.noise1, "GENERATOR-NOISE2": self.noise2, "GENERATOR-NOISEOEFF": self.noise_oeff, "GENERATOR-NOISEOEMIS": self.noise_oemis, "GENERATOR-NOISEOTEMP": self.noise_otemp.to_value(u.K) if self.noise_otemp is not None else None, "GENERATOR-INSTRUMENT": self.instrument, "GENERATOR-NOISEWELL": self.noise_well, "GENERATOR-GCM-BINNING": self.gcm_binning, } config = {k: str(v) for k, v in config.items() if v is not None} return config class PSG_Retrieval(PSG_Config): def __init__(self, config) -> None: #:float: The parameter Gamma (or Levenberg-Marquart parameter) is the extra regularization parameter (e.g., 0:Classic LM, 1:classic Rodgers' formalism, 10:Heavily tailored to the a-priori) self.gamma = self.get_value(config, "RETRIEVAL-GAMMA", float) #:str: Parameters for the nested sampling retrieval method self.nest = config.get("RETRIEVAL-NEST") range_unit = config.get("RETRIEVAL-RANGEUNIT") #:Unit: Spectral unit of the user-provided data for the retrieval, um / nm / mm / An:'Angstrom' / cm:'Wavenumber [cm-1]' / MHz / GHz / kHz self.range_unit = self.parse_units( range_unit, [u.um, u.nm, u.mm, u.AA, 1 / u.cm, u.MHz, u.GHz, u.kHz], ["um", "nm", "mm", "An", "cm", "MHz", "GHz", "kHz"], ) resolution_unit = config.get("RETRIEVAL-RESOLUTIONUNIT") resolution_unit = self.parse_units( resolution_unit, [u.one, u.um, u.nm, u.mm, u.AA, 1 / u.cm, u.MHz, u.GHz, u.kHz], ["RP", "um", "nm", "mm", "An", "cm", "MHz", "GHz", "kHz"], ) #:quantity: Instrument's spectral resolution [FWHM] of the user-provided data. This value is independent of the sampling rate of the data, and refers to the actual spectral resolution of the instrument self.resolution = self.get_quantity(config, "RETRIEVAL-RESOLUTION", resolution_unit) #:float: Scaling value to be applied to all fluxes of the user-provided data file self.flux_scaler = self.get_value(config, "RETRIEVAL-FLUXSCALER", float) #:str: Frequency/wavelength corrections (0th, 1st and 2nd orders) to be applied to the data self.freq_shift = config.get("RETRIEVAL-FREQSHIFT") #:str: Labels for the columns of the data file self.flux_labels = config.get("RETRIEVAL-FLUXLABELS") #:int: Polynomical degree of the instrument's gain function, -1:None, 0:Constant, 1:Sloped, 2:Quadratic, etc self.fit_gain = self.get_value(config, "RETRIEVAL-FITGAIN", int) #:bool: Flag indicating whether to preserve the photometric information of the data (zeroth order of gain fitting) [Y:Disable 0th order / N:Enable] self.fit_gain_photometric = self.get_bool(config, "RETRIEVAL-FITGAIN-PHOTOMETRIC") #:int: Polynomical degree of the residual offset, -1:None, 0:Constant, 1:Sloped, 2:Quadratic, etc self.remove_offset = self.get_value(config, "RETRIEVAL-REMOVEOFFSET", int) #:int: Maximum number of spectral fringes to be removed from the data self.remove_fringe = self.get_value(config, "RETRIEVAL-REMOVEFRINGE", int) #:bool: Flag indicating whether to fit the intensity of the solar/stellar features [Y/N] self.fit_stellar = self.get_bool(config, "RETRIEVAL-FITSTELLAR") #:bool: Flag indicating whether to refine the spectral calibration [Y/N] self.fit_freq = self.get_bool(config, "RETRIEVAL-FITFREQ") #:bool: Flag indicating whether to fit the spectral resolution [Y/N] self.fit_resolution = self.get_bool(config, "RETRIEVAL-FITRESOLUTION") #:bool: Flag indicating whether to fit the telluric features [Y/N]. This is done by perturbing the selected telluric column/water abundances self.fit_telluric = self.get_bool(config, "RETRIEVAL-FITTELLURIC") #:list: Name of the variables of the retrieval (comma separated) self.variables = self.get_list(config, "RETRIEVAL-VARIABLES") #:array: A-priori and resulting values of the retrieval parameters (comma separated) self.values = self.get_list(config, "RETRIEVAL-VALUES", func=float, array=True) #:array: Resulting 1-sigma uncertainties (corrected by chi-square) of the retrieval parameters (comma separated) self.sigmas = self.get_list(config, "RETRIEVAL-SIGMAS", func=float, array=True) #:array: Lower boundary permitted for each parameter (comma separated) self.min = self.get_list(config, "RETRIEVAL-MIN", func=float, array=True) #:array: Upper boundary permitted for each parameter (comma separated) self.max = self.get_list(config, "RETRIEVAL-MAX", func=float, array=True) #:list: Magnitude unit of the a-priori and boundary entries (comma separated) self.units = self.get_list(config, "RETRIEVAL-UNITS") #:str: Flag indicating the status of the retrieval suite (e.g., RUNNING, OK) self.status = self.get_bool(config, "RETRIEVAL-STATUS") @property def resolution_unit(self): if self.resolution is None: return None return self.resolution.unit @property def nvars(self): if self.variables is None: return None return len(self.variables) def to_config(self): range_unit_loc, range_unit = self.get_units( self.range_unit, [u.um, u.nm, u.mm, u.AA, 1 / u.cm, u.MHz, u.GHz, u.kHz], ["um", "nm", "mm", "An", "cm", "MHz", "GHz", "kHz"], ) resolution_unit_loc, resolution_unit = self.get_units( self.resolution_unit, [u.one, u.um, u.nm, u.mm, u.AA, 1 / u.cm, u.MHz, u.GHz, u.kHz], ["RP", "um", "nm", "mm", "An", "cm", "MHz", "GHz", "kHz"], ) config = { "RETRIEVAL-GAMMA": self.gamma, "RETRIEVAL-NEST": self.nest, "RETRIEVAL-RANGEUNIT": self.range_unit, "RETRIEVAL-RESOLUTION": self.resolution.to_value(resolution_unit_loc) if self.resolution is not None and resolution_unit_loc is not None else None, "RETRIEVAL-RESOLUTIONUNIT": resolution_unit, "RETRIEVAL-FLUXSCALER": self.flux_scaler, "RETRIEVAL-FREQSHIFT": self.freq_shift, "RETRIEVAL-FLUXLABELS": self.flux_labels, "RETRIEVAL-FITGAIN": self.fit_gain, "RETRIEVAL-FITGAIN-PHOTOMETRIC": "Y" if self.fit_gain_photometric else "N" if self.fit_gain_photometric is not None else None, "RETRIEVAL-REMOVEOFFSET": self.remove_offset, "RETRIEVAL-REMOVEFRINGE": self.remove_fringe, "RETRIEVAL-FITSTELLAR": "Y" if self.fit_stellar else "N" if self.fit_stellar is not None else None, "RETRIEVAL-FITFREQ": "Y" if self.fit_freq else "N" if self.fit_freq is not None else None, "RETRIEVAL-FITRESOLUTION": "Y" if self.fit_resolution else "N" if self.fit_resolution is not None else None, "RETRIEVAL-FITTELLURIC": "Y" if self.fit_telluric else "N" if self.fit_telluric is not None else None, "RETRIEVAL-NVARS": self.nvars, "RETRIEVAL-VARIABLES": ",".join(self.variables) if self.variables is not None else None, "RETRIEVAL-VALUES": ",".join([str(v) for v in self.values]) if self.values is not None else None, "RETRIEVAL-SIGMAS": ",".join([str(v) for v in self.sigmas]) if self.sigmas is not None else None, "RETRIEVAL-MIN": ",".join([str(v) for v in self.min]) if self.min is not None else None, "RETRIEVAL-MAX": ",".join([str(v) for v in self.max]) if self.max is not None else None, "RETRIEVAL-UNITS": ",".join(self.units) if self.units is not None else None, "RETRIEVAL-STATUS": self.status, } config = {k: str(v) for k, v in config.items() if v is not None} return config class PSG_Package: """ Abstract Class for a PSG package """ name = None def __init__(self, server, version=None) -> None: self.server = server if version is None: try: version = server.get_package_version(self.name) except: version = "" self.version = version def __str__(self): return f"{self.name.upper()} - version ({self.version})" def update(self): result = self.sever.update_package(self.name) self.version = server.get_package_version(self.name) return result def install(self): result = self.server.install_package(self.name) self.version = server.get_package_version(self.name) return result def remove(self): self.version = None return self.server.remove_package(self.name) def help(self): """ Return a formatted docstring """ return self.__doc__ class Programs_Package(PSG_Package): """ Operational software and programs required by PSG. This package includes all the necessary binaries to perform the radiative transfer calculations and retrievals, together with the PHP server interpreter modules. This package cannot be removed (it is fundamental for the operation of PSG), and it should be constantly updated to reflect the upgrades performed to the suite. """ name = "programs" class Base_Package(PSG_Package): """ This package includes the basic spectroscopic data for performing line-by-line calculations across a broad range of wavelengths and domains. It includes: - HITRAN line-by-line database formatted for PSG (binary) with collissional information for CO2, H2, He when available. - HITRAN Collission-Induced-Absorption (CIA) database for many species due to various collisionally interacting atoms or molecules. Some CIA spectra are given over an extended range of frequencies. - UV cross-sections database for a multiple species (ingested automatically by the RT modules when applicable). - Kurucz's stellar templates. - Scattering models for hundreds of optical constants (HRI, GSFC, Mie scattering), and for typical Mars aerosols (dust, water-ice, T-max based on Wolff et al.) """ name = "base" class Surfaces_Package(PSG_Package): """ The surface spectroscopic package includes the complete repository of optical constants and reflectances from all databases handled by PSG (e.g., RELAB, USGS, JENA). """ name = "surfaces" class Atmospheres_Package(PSG_Package): """ This package includes the climatological and atmospheric files needed by the 'atmosphere' module. Specifically, it includes: - Atmospheric templates for most Solar-System bodies. - Earth MERRA2 auxiliary data (e.g., topography), Mars-MCD, and Mars-GEM databases. - Exoplanet basic templates. - Exoplanet Parmentier T/P model and Kempton equilibrium chemistry modules. - Exoplanet Terrestrial LAPS model (Turbet+2015). """ name = "atmospheres" class Ephm_Package(PSG_Package): """ The ephemerides package includes orbital and geometric used by the 'geometry' module. Specifically, it includes: - Ephemerides information for hundreds of Solar-System bodies (1960-2050). - Ephemerides information for dozens of planetary missions (e.g., Cassini, MAVEN). """ name = "ephm" class Telluric_Package(PSG_Package): """ This package includes the database of telluric transmittances necessary when computing spectra as observed with ground-based observatories. It includes: - Database of telluric transmittances pre-computed for 5 altitudes and 4 columns of water for each case. - The altitudes include that of Mauna-Kea/Hawaii (4200 m), Paranal/Chile (2600 m), SOFIA (14,000 m) and balloon observatories (35,000 m). - The water vapor column was established by scaling the tropical water profile by a factor of 0.1, 0.3 and 0.7 and 1. """ name = "telluric" class Xcross_Package(PSG_Package): """ This package contains hundreds of absorption cross-sections for complex volatiles as reported by the latest HITRAN release. """ name = "xcross" class Lines_Package(PSG_Package): """ This package contains line-by-line spectroscopic information from several databases. - GEISA database. - JPL Molecular spectroscopy database. - CDMS molecular spectroscopy database. - CFA/Harvard Kurucz atomic database. """ name = "lines" class Fluor_Package(PSG_Package): """ This package contains non-LTE fluorescence efficiencies for dozens of species, suitable when synthesizing cometary spectra in the UV/optical/IR range. """ name = "fluor" class Exo_Package(PSG_Package): """ This package contains molecular and atomic cross-sections applicable for exoplanetary modeling, and it is based on the database employed by the open source 'Exo-Transmit' code (Kempton et al. 2017). """ name = "exo" class Mass_Package(PSG_Package): """ The mass spectrometry package provides access to the MS fragmentation pattern database for >20,000 species computed based on the NIST Standard Reference Database Number 69 library. """ name = "mass" class Corrklow_Package(PSG_Package): """ This package contains correlated-k tables for the main HITRAN species (H2O, CO2, O3, N2O, CO, CH4, O2, SO2, NO2, NH3, HCl, OCS, H2CO, N2, HCN, C2H2, C2H4, PH3, H2S, C2H4, H2), and for different collissional partners (e.g., CO2, H2, He) when available. The tables were computed with PUMAS assuming wings of 25 cm-1 and a fine core of 1 cm-1 where maximum resolution calculations are applied. This is the 'low' resolution package applicable to synthesis of spectra with a resolving power lower/equal than 500. """ name = "corrklow" class Corrkmed_Package(PSG_Package): """ This package contains correlated-k tables for the main HITRAN species (H2O, CO2, O3, N2O, CO, CH4, O2, SO2, NO2, NH3, HCl, OCS, H2CO, N2, HCN, C2H2, C2H4, PH3, H2S, C2H4, H2), and for different collissional partners (e.g., CO2, H2, He) when available. The tables were computed with PUMAS assuming wings of 25 cm-1 and a fine core of 1 cm-1 where maximum resolution calculations are applied. This is the 'med' resolution package applicable to synthesis of spectra with a resolving power greater than 500 and lower/equal to 5000. """ name = "corrkmed" class PSG: # Assign package names to package classes _packages = { "programs": Programs_Package, "base": Base_Package, "surfaces": Surfaces_Package, "atmospheres": Atmospheres_Package, "ephm": Ephm_Package, "telluric": Telluric_Package, "xcross": Xcross_Package, "lines": Lines_Package, "fluor": Fluor_Package, "exo": Exo_Package, "mass": Mass_Package, "corrklow": Corrklow_Package, "corrkmed": Corrkmed_Package, } def __init__(self, server=None, config=None) -> None: # self.server = 'https://psg.gsfc.nasa.gov' if server is None: server = "http://localhost:3000" self.server = server # Read configuration from file if config is None: config_file = join(dirname(__file__), "psg_cfg.txt") config = self.read_config(config_file) else: try: config = self.read_config(config) except FileNotFoundError: config = config self._config = config # Pass config to substructures self.object = PSG_Object(self._config) self.geometry = PSG_Geometry(self._config) self.atmosphere = PSG_Atmosphere(self._config) self.surface = PSG_Surface(self._config) self.generator = PSG_Generator(self._config) self.retrieval = PSG_Retrieval(self._config) # Load the individual packages for object oriented interface versions = self.get_package_version() self.packages = { name: cls(self, versions[name.upper()]) for name, cls in self._packages.items() if name.upper() in versions.keys() } @property def config(self): return self.to_config() @staticmethod def read_config(config_file): with open(config_file, "r") as f: lines = f.read() matches = re.findall(r"<(.*?)>(.*)\n", lines) config = {k: v for k, v in matches} return config def to_config(self): self._config.update(self.object.to_config()) self._config.update(self.geometry.to_config()) self._config.update(self.atmosphere.to_config()) self._config.update(self.surface.to_config()) self._config.update(self.generator.to_config()) self._config.update(self.retrieval.to_config()) return self._config def write_config(self, config_file=None): config = self.to_config() lines = [f"<{k}>{v}\n" for k, v in config.items()] text = "".join(lines) if config_file is not None: with open(config_file, "w") as f: f.write(text) f.flush() return text @staticmethod def read_datafile(datafile): # Read the header # and split into the seperate parts with open(datafile, "r") as f: columns = None for i, line in enumerate(f): if not line.startswith("#"): # Skip after the header break if line.startswith("# WARNING"): print(line[2:]) continue columns = line if columns is not None: columns = columns[2:-1].split(" ") # Read the data data = np.genfromtxt(datafile, names=columns) return data @staticmethod def download_file( server, config_text, psg_type="rad", wgeo="y", wephm="n", watm="n", cache=True ): hash = hashlib.sha256((psg_type + wephm + watm + config_text).encode("utf-8")) url = join(server, f"{hash.hexdigest()}.txt") if not is_url_in_cache(url, pkgname=PKGNAME) or not cache: with NamedTemporaryFile("w") as cf: cf.write(config_text) cf.flush() result = subprocess.run( f"curl -s -d type={psg_type} -d wgeo={wgeo} -d wephm={wephm} -d watm={watm} --data-urlencode file@{cf.name} {server}/api.php", capture_output=True, shell=True, ) text = result.stdout.decode() if text == "": raise RuntimeError("The PSG server did not return a result") with NamedTemporaryFile("w") as output: output.write(text) output.flush() import_file_to_cache(url, output.name, pkgname=PKGNAME) # Return the filename in the cache result = download_file(url, cache=True, pkgname=PKGNAME) return result @staticmethod def clear_cache(): clear_download_cache(pkgname=PKGNAME) @staticmethod def run_curl_command(server, page="index.php", command=None): call = f"curl {server}/index.php" if command is not None: call = f"{call}?{command}" result = subprocess.run(call, capture_output=True, shell=True,) text = result.stdout.decode() return text def get_info(self): return self.run_curl_command(self.server) def get_installed_packages(self): text = self.get_info() lines = text.splitlines() packages = [l.split("-", 1)[0].strip().lower() for l in lines] return packages def get_package_version(self, package=None): text = self.get_info() if package is not None: match = re.match( package.upper() + r" - .*version \((\d{4}-\d{2}-\d{2})\)", text ) version = match.group(1) return version else: match = re.findall(r"(\w*) - .*version \((\d{4}-\d{2}-\d{2})\)", text) version = {m[0]: m[1] for m in match} return version def install_package(self, package): text = self.run_curl_command(self.server, command=f"install={package}") # TODO: Check that the result is successful return text def update_package(self, package): text = self.run_curl_command(self.server, command=f"update={package}") # TODO: Check that the result is successful return text def remove_package(self, package): text = self.run_curl_command(self.server, command=f"remove={package}") # TODO: Check that the result is successful return text def update_all_packages(self): text = self.run_curl_command(self.server) lines = text.splitlines() lines = [l.split("-", 1) for l in lines] packages = [l[0].strip().lower() for l in lines if "Update available" in l[1]] for package in packages: self.update_package(package) return None def request(self, psg_type="rad", wgeo="y", wephm="n", watm="n"): # Create the configuration for the PSG config_text = self.write_config() # Get the filename from the cache output_name = self.download_file( self.server, config_text, psg_type=psg_type, wgeo=wgeo, wephm=wephm, watm=watm, ) # Read the results from file data = self.read_datafile(output_name) return data
50.480162
332
0.643055
from io import StringIO from os.path import dirname, join import subprocess from datetime import datetime import re import hashlib from tempfile import NamedTemporaryFile import numpy as np from astropy.utils.data import ( import_file_to_cache, download_file, clear_download_cache, is_url_in_cache, ) from astropy import units as u ppb = u.def_unit( ["ppb", "ppbv"], 1e-9 * u.one, namespace=globals(), doc="Parts Per Billion" ) ppm = u.def_unit( ["ppm", "ppmv", "ppv"], 1e3 * ppb, namespace=globals(), doc="Parts Per Million Volume", ) ppt = u.def_unit( ["ppt", "pptv"], 1e6 * ppb, namespace=globals(), doc="Parts Per Thousand Volume" ) m2 = u.def_unit( ["m2", "m-2"], None, namespace=globals(), doc="Molecules per square meter" ) diameter = u.def_unit( ["diameter"], None, namespace=globals(), doc="Diameter of the telescope" ) diffrac = u.def_unit( ["diffrac"], None, namespace=globals(), doc="defined by the telescope diameter and center wavelength", ) scl = u.def_unit(["scl"], None, namespace=globals(), doc="Relative Scale") u.add_enabled_units([ppb, ppm, ppt, m2, scl, diameter, diffrac]) PKGNAME = "planet-spectrum-generator" class PSG_Config: def __init__(self, config) -> None: self.other = {} for key, value in config.items(): self.other[key] = value @staticmethod def get_value(config, key, func=None): try: value = config[key] if func is not None: value = func(value) except KeyError: value = None return value def get_quantity(self, config, key, unit): return self.get_value(config, key, lambda x: float(x) * unit) def get_bool(self, config, key, true_value="Y"): return self.get_value(config, key, lambda x: x == true_value) def get_list(self, config, key, func=None, array=False, sep=","): value = self.get_value(config, key, lambda x: x.split(",")) if value is None: return None if func is not None: value = [func(v) for v in value] if array: value = np.array(value) return value @staticmethod def parse_units(unit, units, names): if unit is None: return None for u, n in zip(units, names): if unit == n: return u raise ValueError("Could not parse unit") @staticmethod def get_units(unit, units, names): if unit is None: return None, None for un, n in zip(units, names): if unit == un: return un, n for un, n in zip(units, names): try: unit.to(un) return un, n except u.core.UnitConversionError: continue raise ValueError("Could not determine units") def to_config(self): return self.other class PSG_Object(PSG_Config): def __init__(self, config) -> None: self.object = config.get("OBJECT") self.name = config.get("OBJECT-NAME") if "OBJECT-DATE" in config.keys(): match = re.match( r"(\d{4})/(\d{2})/(\d{2}) (\d{2}):(\d{2})", config["OBJECT-DATE"] ) date = datetime( int(match.group(1)), int(match.group(2)), int(match.group(3)), int(match.group(4)), int(match.group(5)), ) else: date = None self.date = date self.diameter = self.get_quantity(config, "OBJECT-DIAMETER", u.km) gravity_unit = config.get("OBJECT-GRAVITY-UNIT") if gravity_unit == "g": gravity_unit = u.m / u.s ** 2 elif gravity_unit == "rho": gravity_unit = u.g / u.cm ** 3 elif gravity_unit == "kg": gravity_unit = u.kg self.gravity = self.get_quantity(config, "OBJECT-GRAVITY", gravity_unit) self.star_distance = self.get_quantity(config, "OBJECT-STAR-DISTANCE", u.AU) self.star_velocity = self.get_quantity(config, "OBJECT-STAR-VELOCITY", (u.km / u.s)) self.solar_longitude = self.get_quantity(config, "OBJECT-SOLAR-LONGITUDE", u.deg) self.solar_latitude = self.get_quantity(config, "OBJECT-SOLAR-LATITUDE", u.deg) self.season = self.get_quantity(config, "OBJECT-SEASON", u.deg) self.inclination = self.get_quantity(config, "OBJECT-INCLINATION", u.deg) self.eccentricity = self.get_value(config, "OBJECT-ECCENTRICITY", float) self.periapsis = self.get_quantity(config, "OBJECT-PERIAPSIS", u.deg) self.star_type = config.get("OBJECT-STAR-TYPE") self.star_temperature = self.get_quantity(config, "OBJECT-STAR-TEMPERATURE", u.K) self.star_radius = self.get_quantity(config, "OBJECT-STAR-RADIUS", u.Rsun) self.star_metallicity = self.get_value(config, "OBJECT-STAR-METALLICITY", float) self.obs_longitude = self.get_quantity(config, "OBJECT-OBS-LONGITUDE", u.deg) self.obs_latitude = self.get_quantity(config, "OBJECT-OBS-LATITUDE", u.deg) self.obs_velocity = self.get_quantity(config, "OBJECT-OBS-VELOCITY", u.km / u.s) self.period = self.get_quantity(config, "OBJECT-PERIOD", u.day) self.orbit = config.get("OBJECT-ORBIT") @property def gravity_unit(self): return self.gravity.unit def to_config(self): gravity_unit_loc, gravity_unit = self.get_units( self.gravity_unit, [u.m / u.s ** 2, u.g / u.cm ** 3, u.kg], ["g", "rho", "kg"], ) config = { "OBJECT": self.object, "OBJECT-NAME": self.name, "OBJECT-DATE": f"{self.date.year:04}/{self.date.month:02}/{self.date.day:02} {self.date.hour:02}:{self.date.minute:02}" if self.date is not None else None, "OBJECT-DIAMETER": self.diameter.to_value(u.km) if self.diameter is not None else None, "OBJECT-GRAVITY": self.gravity.to_value(gravity_unit_loc) if self.gravity is not None and gravity_unit_loc is not None else None, "OBJECT-GRAVITY-UNIT": gravity_unit, "OBJECT-STAR-DISTANCE": self.star_distance.to_value(u.AU) if self.star_distance is not None else None, "OBJECT-STAR-VELOCITY": self.star_velocity.to_value(u.km / u.s) if self.star_velocity is not None else None, "OBJECT-SOLAR-LONGITUDE": self.solar_longitude.to_value(u.deg) if self.solar_longitude is not None else None, "OBJECT-SOLAR-LATITUDE": self.solar_latitude.to_value(u.deg) if self.solar_latitude is not None else None, "OBJECT-SEASON": self.season.to_value(u.deg) if self.season is not None else None, "OBJECT-INCLINATION": self.inclination.to_value(u.deg) if self.inclination is not None else None, "OBJECT-ECCENTRICITY": self.eccentricity, "OBJECT-PERIAPSIS": self.periapsis.to_value(u.deg) if self.periapsis is not None else None, "OBJECT-STAR-TYPE": self.star_type, "OBJECT-STAR-TEMPERATURE": self.star_temperature.to_value(u.K) if self.star_temperature is not None else None, "OBJECT-STAR-RADIUS": self.star_radius.to_value(u.Rsun) if self.star_radius is not None else None, "OBJECT-STAR-METALLICITY": self.star_metallicity, "OBJECT-OBS-LONGITUDE": self.obs_longitude.to_value(u.deg) if self.obs_longitude is not None else None, "OBJECT-OBS-LATITUDE": self.obs_latitude.to_value(u.deg) if self.obs_latitude is not None else None, "OBJECT-OBS-VELOCITY": self.obs_velocity.to_value(u.km / u.s) if self.obs_velocity is not None else None, "OBJECT-PERIOD": self.period.to_value(u.day) if self.period is not None else None, "OBJECT-ORBIT": self.orbit, } config = {k: str(v) for k, v in config.items() if v is not None} return config class PSG_Geometry(PSG_Config): def __init__(self, config) -> None: self.geometry = config.get("GEOMETRY") self.ref = config.get("GEOMETRY-REF") offset_unit = config.get("GEOMETRY-OFFSET-UNIT") offset_unit = self.parse_units(offset_unit, [u.arcsec, u.arcmin, u.deg, u.km, u.one], ["arcsec", "arcmin", "degree", "km", "diameter"],) self.offset_ns = self.get_quantity(config, "GEOMETRY-OFFSET-NS", offset_unit) self.offset_ew = self.get_quantity(config, "GEOMETRY-OFFSET-EW", offset_unit) altitude_unit = config.get("GEOMETRY-ALTITUDE-UNIT") altitude_unit = self.parse_units(altitude_unit, [u.AU, u.km, u.one, u.pc], ["AU", "km", "diameter", "pc"]) self.obs_altitude = self.get_quantity(config, "GEOMETRY-OBS-ALTITUDE", altitude_unit) self.azimuth = self.get_quantity(config, "GEOMETRY-AZIMUTH", u.deg) self.user_param = self.get_value(config, "GEOMETRY-USER-PARAM", float) self.stellar_type = config.get("GEOMETRY-STELLAR-TYPE") self.stellar_temperature = self.get_quantity(config, "GEOMETRY-STELLAR-TEMPERATURE", u.K) self.stellar_magnitude = self.get_quantity(config, "GEOMETRY-STELLAR-MAGNITUDE", u.mag) self.obs_angle = config.get("GEOMETRY-OBS-ANGLE") self.solar_angle = config.get("GEOMETRY-SOLAR-ANGLE") self.disk_angles = int(config.get("GEOMETRY-DISK-ANGLES")) self.phase = self.get_quantity(config, "GEOMETRY-PHASE", u.deg) self.planet_fraction = config.get("GEOMETRY-PLANET-FRACTION") self.star_fraction = self.get_value(config, "GEOMETRY-STAR-FRACTION", float) self.star_distance = self.get_value(config, "GEOMETRY-STAR-DISTANCE", float) self.rotation = config.get("GEOMETRY-ROTATION") self.brdfscaler = config.get("GEOMETRY-BRDFSCALER") @property def offset_unit(self): return self.offset_ns.unit @property def altitude_unit(self): return self.obs_altitude.unit def to_config(self): loc_offset_unit, offset_unit = self.get_units( self.offset_unit, [u.arcsec, u.arcmin, u.deg, u.km, u.one], ["arcsec", "arcmin", "degree", "km", "diameter"], ) loc_altitude_unit, altitude_unit = self.get_units( self.altitude_unit, [u.AU, u.km, u.pc, u.one], ["AU", "km", "pc", "diameter"], ) config = { "GEOMETRY": self.geometry, "GEOMETRY-REF": self.ref, "GEOMETRY-OFFSET-NS": self.offset_ns.to_value(loc_offset_unit) if self.offset_ns is not None and loc_offset_unit is not None else None, "GEOMETRY-OFFSET-EW": self.offset_ew.to_value(loc_offset_unit) if self.offset_ew is not None and loc_offset_unit is not None else None, "GEOMETRY-OFFSET-UNIT": offset_unit, "GEOMETRY-OBS-ALTITUDE": self.obs_altitude.to_value(loc_altitude_unit) if self.obs_altitude is not None and loc_altitude_unit is not None else None, "GEOMETRY-ALTITUDE-UNIT": altitude_unit, "GEOMETRY-AZIMUTH": self.azimuth.to_value(u.deg) if self.azimuth is not None else None, "GEOMETRY-USER-PARAM": self.user_param, "GEOMETRY-STELLAR-TYPE": self.stellar_type, "GEOMETRY-STELLAR-TEMPERATURE": self.stellar_temperature.to_value(u.K) if self.stellar_temperature is not None else None, "GEOMETRY-STELLAR-MAGNITUDE": self.stellar_magnitude.to_value(u.mag) if self.stellar_magnitude is not None else None, "GEOMETRY-OBS-ANGLE": self.obs_angle, "GEOMETRY-SOLAR-ANGLE": self.solar_angle, "GEOMETRY-DISK-ANGLES": self.disk_angles, "GEOMETRY-PHASE": self.phase.to_value(u.deg) if self.phase is not None else None, "GEOMETRY-PLANET-FRACTION": self.planet_fraction, "GEOMETRY-STAR-FRACTION": self.star_fraction, "GEOMETRY-STAR-DISTANCE": self.star_distance, "GEOMETRY-ROTATION": self.rotation, "GEOMETRY-BRDFSCALER": self.brdfscaler, } config = {k: str(v) for k, v in config.items() if v is not None} return config class PSG_Atmosphere(PSG_Config): hitran_molecule_id = { "H2O": 1, "CO2": 2, "O3": 3, "N2O": 4, "CO": 5, "CH4": 6, "O2": 7, "NO": 8, "SO2": 9, "NO2": 10, "NH3": 11, "HNO3": 12, "OH": 13, "HF": 14, "HCl": 15, "HBr": 16, "HI": 17, "ClO": 18, "OCS": 19, "H2CO": 20, "HOCl": 21, "N2": 22, "HCN": 23, "CH3Cl": 24, "H2O2": 25, "C2H2": 26, "C2H6": 27, "PH3": 28, "COF2": 29, "SF6": 30, "H2S": 31, "HCOOH": 32, "HO2": 33, "O": 34, "ClONO2": 35, "NO+": 36, "HOBr": 37, "C2H4": 38, "CH3OH": 39, "CH3Br": 40, "CH3CN": 41, "CF4": 42, "C4H2": 43, "HC3N": 44, "H2": 45, "CS": 46, "SO3": 47, "C2N2": 48, "COCl2": 49, "CS2": 53, "NF3": 55, } def __init__(self, config) -> None: self._gas = self.get_list(config, "ATMOSPHERE-GAS") self.type = self.get_list(config, "ATMOSPHERE-TYPE") abun = self.get_list(config, "ATMOSPHERE-ABUN", func=float) unit = self.get_list(config, "ATMOSPHERE-UNIT", func=u.Unit) self.abun = [a * u for a, u in zip(abun, unit)] if abun is not None and unit is not None else None self._aeros = self.get_list(config, "ATMOSPHERE-AEROS") self.atype = self.get_list(config, "ATMOSPHERE-ATYPE") abun = self.get_list(config, "ATMOSPHERE-AABUN", func=float) unit = self.get_list(config, "ATMOSPHERE-AUNIT", func=u.Unit) self.aabun = [a * u for a, u in zip(abun, unit)] if abun is not None and unit is not None else None size = self.get_list(config, "ATMOSPHERE-ASIZE", func=float) unit = self.get_list(config, "ATMOSPHERE-ASUNI", func=float) self.asize = [a * u for a, u in zip(size, unit)] if size is not None and unit is not None else None self.layers_molecules = self.get_list(config, "ATMOSPHERE-LAYERS-MOLECULES") nlayers = self.get_value(config, "ATMOSPHERE-LAYERS", int) if nlayers is not None: try: layers = [config[f"ATMOSPHERE-LAYER-{i}"] for i in range(1, nlayers + 1)] layers = StringIO("\n".join(layers)) layers = np.genfromtxt(layers, delimiter=",") except KeyError: layers = None else: layers = None self.layer = layers self.gcm_parameters = config.get("ATMOSPHERE-GCM-PARAMETERS") self.structure = config.get("ATMOSPHERE-STRUCTURE") self.pressure = self.get_value(config, "ATMOSPHERE-PRESSURE", float) self.punit = config.get("ATMOSPHERE-PUNIT") self.temperature = self.get_quantity(config, "ATMOSPHERE-TEMPERATURE", u.K) self.weight = self.get_value(config, "ATMOSPHERE-WEIGHT", float) self.continuum = config.get("ATMOSPHERE-CONTINUUM") self.tau = config.get("ATMOSPHERE-TAU") self.nmax = self.get_value(config, "ATMOSPHERE-NMAX", int) self.lmax = self.get_value(config, "ATMOSPHERE-LMAX", int) self.description = config.get("ATMOSPHERE-DESCRIPTION") def to_config(self): config = { "ATMOSPHERE-NGAS": self.ngas, "ATMOSPHERE-GAS": ",".join([str(v) for v in self.gas]) if self.gas is not None else None, "ATMOSPHERE-TYPE": ",".join([str(v) for v in self.type]) if self.type is not None else None, "ATMOSPHERE-ABUN": ",".join([str(v.value) for v in self.abun]) if self.abun is not None else None, "ATMOSPHERE-UNIT": ",".join([str(v.unit) for v in self.abun]) if self.abun is not None else None, "ATMOSPHERE-NAERO": self.naero, "ATMOSPHERE-AEROS": ",".join([str(v) for v in self.aeros]) if self.aeros is not None else None, "ATMOSPHERE-ATYPE": ",".join([str(v) for v in self.atype]) if self.atype is not None else None, "ATMOSPHERE-AABUN": ",".join([str(v.value) for v in self.aabun]) if self.aabun is not None else None, "ATMOSPHERE-AUNIT": ",".join([str(v.unit) for v in self.aabun]) if self.aabun is not None else None, "ATMOSPHERE-ASIZE": ",".join([str(v.value) for v in self.asize]) if self.asize is not None else None, "ATMOSPHERE-ASUNI": ",".join([str(v.unit) for v in self.asize]) if self.asize is not None else None, "ATMOSPHERE-LAYERS-MOLECULES": ",".join( [str(v) for v in self.layers_molecules] ) if self.layers_molecules is not None else None, "ATMOSPHERE-LAYERS": self.layers , "ATMOSPHERE-STRUCTURE": self.structure, "ATMOSPHERE-PRESSURE": self.pressure, "ATMOSPHERE-PUNIT": self.punit, "ATMOSPHERE-TEMPERATURE": self.temperature.to_value(u.K) if self.temperature is not None else None, "ATMOSPHERE-WEIGHT": self.weight, "ATMOSPHERE-CONTINUUM": self.continuum, "ATMOSPHERE-TAU": self.tau, "ATMOSPHERE-NMAX": self.nmax, "ATMOSPHERE-LMAX": self.lmax, "ATMOSPHERE-DESCRIPTION": self.description, "ATMOSPHERE-GCM-PARAMETERS": self.gcm_parameters, } if self.layers is not None: for i in range(1, self.layers + 1): config[f"ATMOSPHERE-LAYER-{i}"] = np.array2string( self.layer[i - 1], separator=",", max_line_width=np.inf )[1:-1] config = {k: str(v) for k, v in config.items() if v is not None} return config @property def gas(self): return self._gas @gas.setter def gas(self, value): self._gas = value self.abun = [1 * scl] * len(value) self.type = [f"HIT[{self.hitran_molecule_id[v]}]" for v in self.gas] @property def unit(self): return [a.unit for a in self.abun] @property def ngas(self): return len(self.gas) @property def aeros(self): return self._aeros @aeros.setter def aeros(self, value): self._aeros = value self.aabun = [1 * scl] * len(value) self.atype = [""] * len(value) self.asize = [1 * scl] * len(value) @property def aunit(self): return [a.unit for a in self.aabun] @property def asuni(self): if self.asize is None: return None return [a.unit for a in self.asize] @property def naero(self): if self.aeros is None: return None return len(self.aeros) @property def layers(self): return self.layer.shape[0] class PSG_Surface(PSG_Config): def __init__(self, config) -> None: self.model = self.get_value(config, "SURFACE-MODEL") self.temperature = self.get_quantity(config, "SURFACE-TEMPERATURE", u.K) self.albedo = self.get_value(config, "SURFACE-ALBEDO", float) self.emissivity = self.get_value(config, "SURFACE-EMISSIVITY", float) self.gas_ratio = self.get_value(config, "SURFACE-GAS-RATIO", float) self.gas_unit = config.get("SURFACE-GAS-UNIT") self.nsurf = self.get_value(config, "SURFACE-NSURF", int) self.surf = config.get("SURFACE-SURF") self.type = config.get("SURFACE-TYPE") self.abun = config.get("SURFACE-ABUN") self.unit = self.get_value(config, "SURFACE-UNIT", u.Unit) self.thick = self.get_quantity(config, "SURFACE-THICK", u.um) def to_config(self): config = { "SURFACE-MODEL": self.model, "SURFACE-TEMPERATURE": self.temperature.to_value(u.K) if self.temperature is not None else None, "SURFACE-ALBEDO": self.albedo, "SURFACE-EMISSIVITY": self.emissivity, "SURFACE-GAS-RATIO": self.gas_ratio, "SURFACE-GAS-UNIT": self.gas_unit, "SURFACE-NSURF": self.nsurf, "SURFACE-SURF": self.surf, "SURFACE-TYPE": self.type, "SURFACE-ABUN": self.abun, "SURFACE-UNIT": self.unit, "SURFACE-THICK": self.thick.to_value(u.um) if self.thick is not None else None, } config = {k: str(v) for k, v in config.items() if v is not None} return config class PSG_Generator(PSG_Config): def __init__(self, config) -> None: range_unit = config.get("GENERATOR-RANGEUNIT") range_unit = self.parse_units(range_unit, [u.um, u.nm, u.mm, u.AA, 1 / u.cm, u.MHz, u.GHz, u.kHz], ["um", "nm", "An", "cm", "MHz", "GHz", "kHz"],) self.range1 = self.get_quantity(config, "GENERATOR-RANGE1", range_unit) self.range2 = self.get_quantity(config, "GENERATOR-RANGE2", range_unit) resolution_unit = config.get("GENERATOR-RESOLUTIONUNIT") resolution_unit = self.parse_units(resolution_unit, [u.one, u.um, u.nm, u.mm, u.AA, 1/u.cm, u.MHz, u.GHz, u.kHz], ["RP", "um", "nm", "mm", "An", "cm", "MHz", "GHz", "kHz"]) self.resolution = self.get_quantity(config, "GENERATOR-RESOLUTION", resolution_unit) self.resolution_kernel = self.get_bool(config, "GENERATOR-RESOLUTIONKERNEL") self.gas_model = self.get_bool(config, "GENERATOR-GAS-MODEL") self.cont_model = self.get_bool(config, "GENERATOR-CONT-MODEL") self.cont_stellar = self.get_bool(config, "GENERATOR-CONT-STELLAR") self.trans_show = self.get_bool(config, "GENERATOR-TRANS-SHOW") self.trans_apply = self.get_bool(config, "GENERATOR-TRANS-APPLY") self.trans = config.get("GENERATOR-TRANS") self.rad_units = config.get("GENERATOR-RADUNITS") self.lograd = self.get_bool(config, "GENERATOR-LOGRAD") self.telescope = config.get("GENERATOR-TELESCOPE") beam_unit = self.get_value(config, "GENERATOR-BEAM-UNIT", u.Unit) self.beam = self.get_quantity(config, "GENERATOR-BEAM", beam_unit) #:quantity: Diameter of the main reflecting surface of the telescope or instrument [m] self.diam_tele = self.get_quantity(config, "GENERATOR-DIAMTELE", u.m) #:str: For interferometers, the number of telescopes; for coronagraphs, the instrument's contrast self.telescope1 = config.get("GENERATOR-TELESCOPE1") self.telescope2 = config.get("GENERATOR-TELESCOPE2") self.telescope3 = config.get("GENERATOR-TELESCOPE3") self.noise = config.get("GENERATOR-NOISE") self.noise_time = self.get_quantity(config, "GENERATOR-NOISETIME", u.s) self.noise_frames = self.get_value(config, "GENERATOR-NOISEFRAMES", int) self.noise_pixels = self.get_value(config, "GENERATOR-NOISEPIXELS", int) self.noise1 = config.get("GENERATOR-NOISE1") self.noise2 = config.get("GENERATOR-NOISE2") self.noise_oeff = config.get("GENERATOR-NOISEOEFF") self.noise_oemis = self.get_value(config, "GENERATOR-NOISEOEMIS", float) self.noise_otemp = self.get_quantity(config, "GENERATOR-NOISEOTEMP", u.K) self.instrument = config.get("GENERATOR-INSTRUMENT") self.noise_well = self.get_value(config, "GENERATOR-NOISEWELL", float) self.gcm_binning = self.get_value(config, "GENERATOR-GCM-BINNING", float) @property def range_unit(self): return self.range1.unit @property def resolution_unit(self): return self.resolution.unit @property def beam_unit(self): return self.beam.unit def to_config(self): range_unit_loc, range_unit = self.get_units( self.range_unit, [u.um, u.nm, u.mm, u.AA, 1 / u.cm, u.MHz, u.GHz, u.kHz], ["um", "nm", "An", "cm", "MHz", "GHz", "kHz"], ) resolution_unit_loc, resolution_unit = self.get_units( self.resolution_unit, [u.one, u.um, u.nm, u.mm, u.AA, 1 / u.cm, u.MHz, u.GHz, u.kHz], ["RP", "um", "nm", "mm", "An", "cm", "MHz", "GHz", "kHz"], ) beam_unit_loc, beam_unit = self.get_units( self.beam_unit, [u.arcsec, u.arcmin, u.deg, u.km, diameter, diffrac], ["arcsec", "arcmin", "degree", "km", "diameter", "diffrac"], ) config = { "GENERATOR-RANGE1": self.range1.to_value(range_unit_loc) if self.range1 is not None and range_unit_loc is not None else None, "GENERATOR-RANGE2": self.range2.to_value(range_unit_loc) if self.range2 is not None and range_unit_loc is not None else None, "GENERATOR-RANGEUNIT": range_unit, "GENERATOR-RESOLUTION": self.resolution.to_value(resolution_unit_loc) if self.resolution is not None and resolution_unit_loc is not None else None, "GENERATOR-RESOLUTIONUNIT": resolution_unit, "GENERATOR-RESOLUTIONKERNEL": "Y" if self.resolution_kernel else "N" if self.resolution_kernel is not None else None, "GENERATOR-GAS-MODEL": "Y" if self.gas_model else "N" if self.gas_model is not None else None, "GENERATOR-CONT-MODEL": "Y" if self.cont_model else "N" if self.cont_model is not None else None, "GENERATOR-CONT-STELLAR": "Y" if self.cont_stellar else "N" if self.cont_stellar is not None else None, "GENERATOR-TRANS-SHOW": "Y" if self.trans_show else "N" if self.trans_show is not None else None, "GENERATOR-TRANS-APPLY": "Y" if self.trans_apply else "N" if self.trans_apply is not None else None, "GENERATOR-TRANS": self.trans, "GENERATOR-RADUNITS": self.rad_units, "GENERATOR-LOGRAD": "Y" if self.lograd else "N" if self.lograd is not None else None, "GENERATOR-TELESCOPE": self.telescope, "GENERATOR-BEAM": self.beam.to_value(beam_unit_loc) if self.beam is not None and beam_unit_loc is not None else None, "GENERATOR-BEAM-UNIT": beam_unit, "GENERATOR-DIAMTELE": self.diam_tele.to_value(u.m) if self.diam_tele is not None else None, "GENERATOR-TELESCOPE1": self.telescope1, "GENERATOR-TELESCOPE2": self.telescope2, "GENERATOR-TELESCOPE3": self.telescope3, "GENERATOR-NOISE": self.noise, "GENERATOR-NOISETIME": self.noise_time.to_value(u.s) if self.noise_time is not None else None, "GENERATOR-NOISEFRAMES": self.noise_frames, "GENERATOR-NOISEPIXELS": self.noise_pixels, "GENERATOR-NOISE1": self.noise1, "GENERATOR-NOISE2": self.noise2, "GENERATOR-NOISEOEFF": self.noise_oeff, "GENERATOR-NOISEOEMIS": self.noise_oemis, "GENERATOR-NOISEOTEMP": self.noise_otemp.to_value(u.K) if self.noise_otemp is not None else None, "GENERATOR-INSTRUMENT": self.instrument, "GENERATOR-NOISEWELL": self.noise_well, "GENERATOR-GCM-BINNING": self.gcm_binning, } config = {k: str(v) for k, v in config.items() if v is not None} return config class PSG_Retrieval(PSG_Config): def __init__(self, config) -> None: self.gamma = self.get_value(config, "RETRIEVAL-GAMMA", float) #:str: Parameters for the nested sampling retrieval method self.nest = config.get("RETRIEVAL-NEST") range_unit = config.get("RETRIEVAL-RANGEUNIT") #:Unit: Spectral unit of the user-provided data for the retrieval, um / nm / mm / An:'Angstrom' / cm:'Wavenumber [cm-1]' / MHz / GHz / kHz self.range_unit = self.parse_units( range_unit, [u.um, u.nm, u.mm, u.AA, 1 / u.cm, u.MHz, u.GHz, u.kHz], ["um", "nm", "mm", "An", "cm", "MHz", "GHz", "kHz"], ) resolution_unit = config.get("RETRIEVAL-RESOLUTIONUNIT") resolution_unit = self.parse_units( resolution_unit, [u.one, u.um, u.nm, u.mm, u.AA, 1 / u.cm, u.MHz, u.GHz, u.kHz], ["RP", "um", "nm", "mm", "An", "cm", "MHz", "GHz", "kHz"], ) #:quantity: Instrument's spectral resolution [FWHM] of the user-provided data. This value is independent of the sampling rate of the data, and refers to the actual spectral resolution of the instrument self.resolution = self.get_quantity(config, "RETRIEVAL-RESOLUTION", resolution_unit) self.flux_scaler = self.get_value(config, "RETRIEVAL-FLUXSCALER", float) self.freq_shift = config.get("RETRIEVAL-FREQSHIFT") self.flux_labels = config.get("RETRIEVAL-FLUXLABELS") self.fit_gain = self.get_value(config, "RETRIEVAL-FITGAIN", int) #:bool: Flag indicating whether to preserve the photometric information of the data (zeroth order of gain fitting) [Y:Disable 0th order / N:Enable] self.fit_gain_photometric = self.get_bool(config, "RETRIEVAL-FITGAIN-PHOTOMETRIC") #:int: Polynomical degree of the residual offset, -1:None, 0:Constant, 1:Sloped, 2:Quadratic, etc self.remove_offset = self.get_value(config, "RETRIEVAL-REMOVEOFFSET", int) #:int: Maximum number of spectral fringes to be removed from the data self.remove_fringe = self.get_value(config, "RETRIEVAL-REMOVEFRINGE", int) #:bool: Flag indicating whether to fit the intensity of the solar/stellar features [Y/N] self.fit_stellar = self.get_bool(config, "RETRIEVAL-FITSTELLAR") #:bool: Flag indicating whether to refine the spectral calibration [Y/N] self.fit_freq = self.get_bool(config, "RETRIEVAL-FITFREQ") #:bool: Flag indicating whether to fit the spectral resolution [Y/N] self.fit_resolution = self.get_bool(config, "RETRIEVAL-FITRESOLUTION") #:bool: Flag indicating whether to fit the telluric features [Y/N]. This is done by perturbing the selected telluric column/water abundances self.fit_telluric = self.get_bool(config, "RETRIEVAL-FITTELLURIC") #:list: Name of the variables of the retrieval (comma separated) self.variables = self.get_list(config, "RETRIEVAL-VARIABLES") #:array: A-priori and resulting values of the retrieval parameters (comma separated) self.values = self.get_list(config, "RETRIEVAL-VALUES", func=float, array=True) #:array: Resulting 1-sigma uncertainties (corrected by chi-square) of the retrieval parameters (comma separated) self.sigmas = self.get_list(config, "RETRIEVAL-SIGMAS", func=float, array=True) #:array: Lower boundary permitted for each parameter (comma separated) self.min = self.get_list(config, "RETRIEVAL-MIN", func=float, array=True) #:array: Upper boundary permitted for each parameter (comma separated) self.max = self.get_list(config, "RETRIEVAL-MAX", func=float, array=True) #:list: Magnitude unit of the a-priori and boundary entries (comma separated) self.units = self.get_list(config, "RETRIEVAL-UNITS") #:str: Flag indicating the status of the retrieval suite (e.g., RUNNING, OK) self.status = self.get_bool(config, "RETRIEVAL-STATUS") @property def resolution_unit(self): if self.resolution is None: return None return self.resolution.unit @property def nvars(self): if self.variables is None: return None return len(self.variables) def to_config(self): range_unit_loc, range_unit = self.get_units( self.range_unit, [u.um, u.nm, u.mm, u.AA, 1 / u.cm, u.MHz, u.GHz, u.kHz], ["um", "nm", "mm", "An", "cm", "MHz", "GHz", "kHz"], ) resolution_unit_loc, resolution_unit = self.get_units( self.resolution_unit, [u.one, u.um, u.nm, u.mm, u.AA, 1 / u.cm, u.MHz, u.GHz, u.kHz], ["RP", "um", "nm", "mm", "An", "cm", "MHz", "GHz", "kHz"], ) config = { "RETRIEVAL-GAMMA": self.gamma, "RETRIEVAL-NEST": self.nest, "RETRIEVAL-RANGEUNIT": self.range_unit, "RETRIEVAL-RESOLUTION": self.resolution.to_value(resolution_unit_loc) if self.resolution is not None and resolution_unit_loc is not None else None, "RETRIEVAL-RESOLUTIONUNIT": resolution_unit, "RETRIEVAL-FLUXSCALER": self.flux_scaler, "RETRIEVAL-FREQSHIFT": self.freq_shift, "RETRIEVAL-FLUXLABELS": self.flux_labels, "RETRIEVAL-FITGAIN": self.fit_gain, "RETRIEVAL-FITGAIN-PHOTOMETRIC": "Y" if self.fit_gain_photometric else "N" if self.fit_gain_photometric is not None else None, "RETRIEVAL-REMOVEOFFSET": self.remove_offset, "RETRIEVAL-REMOVEFRINGE": self.remove_fringe, "RETRIEVAL-FITSTELLAR": "Y" if self.fit_stellar else "N" if self.fit_stellar is not None else None, "RETRIEVAL-FITFREQ": "Y" if self.fit_freq else "N" if self.fit_freq is not None else None, "RETRIEVAL-FITRESOLUTION": "Y" if self.fit_resolution else "N" if self.fit_resolution is not None else None, "RETRIEVAL-FITTELLURIC": "Y" if self.fit_telluric else "N" if self.fit_telluric is not None else None, "RETRIEVAL-NVARS": self.nvars, "RETRIEVAL-VARIABLES": ",".join(self.variables) if self.variables is not None else None, "RETRIEVAL-VALUES": ",".join([str(v) for v in self.values]) if self.values is not None else None, "RETRIEVAL-SIGMAS": ",".join([str(v) for v in self.sigmas]) if self.sigmas is not None else None, "RETRIEVAL-MIN": ",".join([str(v) for v in self.min]) if self.min is not None else None, "RETRIEVAL-MAX": ",".join([str(v) for v in self.max]) if self.max is not None else None, "RETRIEVAL-UNITS": ",".join(self.units) if self.units is not None else None, "RETRIEVAL-STATUS": self.status, } config = {k: str(v) for k, v in config.items() if v is not None} return config class PSG_Package: name = None def __init__(self, server, version=None) -> None: self.server = server if version is None: try: version = server.get_package_version(self.name) except: version = "" self.version = version def __str__(self): return f"{self.name.upper()} - version ({self.version})" def update(self): result = self.sever.update_package(self.name) self.version = server.get_package_version(self.name) return result def install(self): result = self.server.install_package(self.name) self.version = server.get_package_version(self.name) return result def remove(self): self.version = None return self.server.remove_package(self.name) def help(self): return self.__doc__ class Programs_Package(PSG_Package): name = "programs" class Base_Package(PSG_Package): name = "base" class Surfaces_Package(PSG_Package): name = "surfaces" class Atmospheres_Package(PSG_Package): name = "atmospheres" class Ephm_Package(PSG_Package): name = "ephm" class Telluric_Package(PSG_Package): name = "telluric" class Xcross_Package(PSG_Package): name = "xcross" class Lines_Package(PSG_Package): name = "lines" class Fluor_Package(PSG_Package): name = "fluor" class Exo_Package(PSG_Package): name = "exo" class Mass_Package(PSG_Package): name = "mass" class Corrklow_Package(PSG_Package): name = "corrklow" class Corrkmed_Package(PSG_Package): name = "corrkmed" class PSG: # Assign package names to package classes _packages = { "programs": Programs_Package, "base": Base_Package, "surfaces": Surfaces_Package, "atmospheres": Atmospheres_Package, "ephm": Ephm_Package, "telluric": Telluric_Package, "xcross": Xcross_Package, "lines": Lines_Package, "fluor": Fluor_Package, "exo": Exo_Package, "mass": Mass_Package, "corrklow": Corrklow_Package, "corrkmed": Corrkmed_Package, } def __init__(self, server=None, config=None) -> None: # self.server = 'https://psg.gsfc.nasa.gov' if server is None: server = "http://localhost:3000" self.server = server # Read configuration from file if config is None: config_file = join(dirname(__file__), "psg_cfg.txt") config = self.read_config(config_file) else: try: config = self.read_config(config) except FileNotFoundError: config = config self._config = config # Pass config to substructures self.object = PSG_Object(self._config) self.geometry = PSG_Geometry(self._config) self.atmosphere = PSG_Atmosphere(self._config) self.surface = PSG_Surface(self._config) self.generator = PSG_Generator(self._config) self.retrieval = PSG_Retrieval(self._config) # Load the individual packages for object oriented interface versions = self.get_package_version() self.packages = { name: cls(self, versions[name.upper()]) for name, cls in self._packages.items() if name.upper() in versions.keys() } @property def config(self): return self.to_config() @staticmethod def read_config(config_file): with open(config_file, "r") as f: lines = f.read() matches = re.findall(r"<(.*?)>(.*)\n", lines) config = {k: v for k, v in matches} return config def to_config(self): self._config.update(self.object.to_config()) self._config.update(self.geometry.to_config()) self._config.update(self.atmosphere.to_config()) self._config.update(self.surface.to_config()) self._config.update(self.generator.to_config()) self._config.update(self.retrieval.to_config()) return self._config def write_config(self, config_file=None): config = self.to_config() lines = [f"<{k}>{v}\n" for k, v in config.items()] text = "".join(lines) if config_file is not None: with open(config_file, "w") as f: f.write(text) f.flush() return text @staticmethod def read_datafile(datafile): # Read the header # and split into the seperate parts with open(datafile, "r") as f: columns = None for i, line in enumerate(f): if not line.startswith("#"): # Skip after the header break if line.startswith("# WARNING"): print(line[2:]) continue columns = line if columns is not None: columns = columns[2:-1].split(" ") # Read the data data = np.genfromtxt(datafile, names=columns) return data @staticmethod def download_file( server, config_text, psg_type="rad", wgeo="y", wephm="n", watm="n", cache=True ): hash = hashlib.sha256((psg_type + wephm + watm + config_text).encode("utf-8")) url = join(server, f"{hash.hexdigest()}.txt") if not is_url_in_cache(url, pkgname=PKGNAME) or not cache: with NamedTemporaryFile("w") as cf: cf.write(config_text) cf.flush() result = subprocess.run( f"curl -s -d type={psg_type} -d wgeo={wgeo} -d wephm={wephm} -d watm={watm} --data-urlencode file@{cf.name} {server}/api.php", capture_output=True, shell=True, ) text = result.stdout.decode() if text == "": raise RuntimeError("The PSG server did not return a result") with NamedTemporaryFile("w") as output: output.write(text) output.flush() import_file_to_cache(url, output.name, pkgname=PKGNAME) # Return the filename in the cache result = download_file(url, cache=True, pkgname=PKGNAME) return result @staticmethod def clear_cache(): clear_download_cache(pkgname=PKGNAME) @staticmethod def run_curl_command(server, page="index.php", command=None): call = f"curl {server}/index.php" if command is not None: call = f"{call}?{command}" result = subprocess.run(call, capture_output=True, shell=True,) text = result.stdout.decode() return text def get_info(self): return self.run_curl_command(self.server) def get_installed_packages(self): text = self.get_info() lines = text.splitlines() packages = [l.split("-", 1)[0].strip().lower() for l in lines] return packages def get_package_version(self, package=None): text = self.get_info() if package is not None: match = re.match( package.upper() + r" - .*version \((\d{4}-\d{2}-\d{2})\)", text ) version = match.group(1) return version else: match = re.findall(r"(\w*) - .*version \((\d{4}-\d{2}-\d{2})\)", text) version = {m[0]: m[1] for m in match} return version def install_package(self, package): text = self.run_curl_command(self.server, command=f"install={package}") # TODO: Check that the result is successful return text def update_package(self, package): text = self.run_curl_command(self.server, command=f"update={package}") # TODO: Check that the result is successful return text def remove_package(self, package): text = self.run_curl_command(self.server, command=f"remove={package}") # TODO: Check that the result is successful return text def update_all_packages(self): text = self.run_curl_command(self.server) lines = text.splitlines() lines = [l.split("-", 1) for l in lines] packages = [l[0].strip().lower() for l in lines if "Update available" in l[1]] for package in packages: self.update_package(package) return None def request(self, psg_type="rad", wgeo="y", wephm="n", watm="n"): # Create the configuration for the PSG config_text = self.write_config() # Get the filename from the cache output_name = self.download_file( self.server, config_text, psg_type=psg_type, wgeo=wgeo, wephm=wephm, watm=watm, ) # Read the results from file data = self.read_datafile(output_name) return data
true
true
1c39411b639150078841ad88a31b978e89f9da7c
13,757
py
Python
src/models/test.py
nybupt/athena
2808f5060831382e603e5dc5ec6a9e9d8901a3b2
[ "MIT" ]
null
null
null
src/models/test.py
nybupt/athena
2808f5060831382e603e5dc5ec6a9e9d8901a3b2
[ "MIT" ]
8
2020-09-25T22:32:00.000Z
2022-02-10T01:17:17.000Z
src/models/test.py
nybupt/athena
2808f5060831382e603e5dc5ec6a9e9d8901a3b2
[ "MIT" ]
1
2021-08-12T12:48:51.000Z
2021-08-12T12:48:51.000Z
import os import sys import time import numpy as np from utils.config import * from utils.util import * def usage(): print( "====================================================================================================================") print( "python <this script> samplesDir experimentRootDir modelsDir numOfSamples testResultFoldName datasetName numOfClasses") print( "====================================================================================================================") if len(sys.argv) != 8: usage() exit(1) samplesDir = sys.argv[1] experimentRootDir = sys.argv[2] modelsDir = sys.argv[3] numOfSamples = int(sys.argv[4]) testResultFoldName = sys.argv[5] datasetName = sys.argv[6] numOfClasses = int(sys.argv[7]) DATA.set_current_dataset_name(datasetName) # Basic parameters for k-fold experiment setup architecture = MODEL.ARCHITECTURE testDir = os.path.join(experimentRootDir, testResultFoldName) AETypes = ATTACK.get_AETypes() numOfAETypes = len(AETypes) sampleTypes = ["BS"] sampleTypes.extend(AETypes) numOfSampleTypes = numOfAETypes + 1 targetModelName = "clean" transformConfig = TRANSFORMATION() transformationList = transformConfig.supported_types() # Create fold directories for evaluation predictionResultDir = os.path.join(testDir, "prediction_result") # Prediction : needs a new prediction function predictionForTest( predictionResultDir, datasetName, architecture, numOfClasses, targetModelName, modelsDir, samplesDir, numOfSamples, AETypes, transformationList) numOfTrans = len(transformationList) - 1 numOfModels = 1 + numOfTrans # clean model + transform models # Evaluation: training and testing predProbBS = np.load(os.path.join(predictionResultDir, "BS/predProb.npy")) # predProbBS = predProbBS[1:] predLogitBS = np.load(os.path.join(predictionResultDir, "BS/predLogit.npy")) # predLogitBS = predLogitBS[1:] labels = np.load(os.path.join(samplesDir, "Label-" + datasetName + "-" + targetModelName + ".npy")) labels = np.argmax(labels, axis=1) predLCBS = np.zeros((predProbBS.shape[0], predProbBS.shape[1], 2)) predLCBS[:, :, 0] = np.argmax(predProbBS, axis=2) predLCBS[:, :, 1] = np.max(predProbBS, axis=2) labelsBS = labels trainModelDir = os.path.join(experimentRootDir, "train_models") numOfDefenses = numOfCVDefenses + 2 * numOfWCDefenses acc1Model = np.zeros((numOfAETypes + 1, numOfModels)) acc1Model[0, :] = calAccuracyAllSingleModels(labelsBS, predProbBS) # the 1st dimension maps to a kind of ensemble model trained on the specific type of AE defenseAccAEs = np.zeros((numOfAETypes, numOfDefenses)) defenseAccBSs = np.zeros((numOfAETypes, numOfDefenses)) defenseTCAEs = np.zeros((numOfAETypes, numOfDefenses)) defenseTCBSs = np.zeros((numOfAETypes, numOfDefenses)) # accuracies of clean model, random defense and upper bound rdCleanUPAcc = np.zeros((numOfAETypes + 1, 3)) clusters = [] for tmID in range(numOfTrans): clusters.append([tmID]) # BS - accuracy of clean model, random defense and upper bound # accuracy of clean model rdCleanUPAcc[0, 0] = acc1Model[0, 0] # accuracy of random defense rdCleanUPAcc[0, 1] = np.mean(acc1Model[0, 1:]) # upper-bound accuracy rdCleanUPAcc[0, 2] = getUpperBoundAccuracy( predLCBS[1:, :, :], clusters, labelsBS) # Test each ensemble model trained by each type of AEs for AETypeIdx in range(numOfAETypes): AEType = AETypes[AETypeIdx] curTrainModelDir = os.path.join(trainModelDir, AEType) curPredictionResultDir = os.path.join(predictionResultDir, AEType) print("Evaluating AE type: " + AEType) predProbAE = np.load(os.path.join(curPredictionResultDir, "predProb.npy")) predLogitAE = np.load(os.path.join(curPredictionResultDir, "predLogit.npy")) predProbLC = np.zeros((numOfModels, numOfSamples, 2)) predProbLC[:, :, 0] = np.argmax(predProbAE, axis=2) predProbLC[:, :, 1] = np.max(predProbAE, axis=2) # accuracy of AE on clean model and all transform models acc1Model[AETypeIdx + 1, :] = calAccuracyAllSingleModels(labels, predProbAE) # accuracy of clean model rdCleanUPAcc[AETypeIdx + 1, 0] = acc1Model[AETypeIdx + 1, 0] # accuracy of random defense rdCleanUPAcc[AETypeIdx + 1, 1] = np.mean(acc1Model[AETypeIdx + 1, 1:]) # upper-bound accuracy rdCleanUPAcc[AETypeIdx + 1, 2] = getUpperBoundAccuracy( predProbLC[1:, :, :], clusters, labels) # accuracy of clustering-and-voting based defenses for defenseIdx in range(numOfCVDefenses): defenseName = cvDefenseNames[defenseIdx] clusters = loadCAVModel(os.path.join(curTrainModelDir, defenseName + ".txt")) # testing AE votedResults, defenseTCAEs[AETypeIdx, defenseIdx] = votingAsDefense( predProbLC[1:, :, :], clusters, vsac=cvDefenseNames[defenseIdx], measureTC=True) defenseAccAEs[AETypeIdx, defenseIdx] = calAccuracy(votedResults[:, 0], labels) # tesing BS votedResults, defenseTCBSs[AETypeIdx, defenseIdx] = votingAsDefense( predLCBS[1:, :, :], clusters, vsac=cvDefenseNames[defenseIdx], measureTC=True) defenseAccBSs[AETypeIdx, defenseIdx] = calAccuracy(votedResults[:, 0], labelsBS) # accuracy of weithed-confidence based defenses for defenseIdx in range(numOfWCDefenses): defenseName = wcDefenseNames[defenseIdx] for plIdx in range(2): wcMatFilename = defenseName + "_EM.npy" mIDsFilename = defenseName + "_modelIDs.npy" predAE = predProbAE[1:, :, :] predBS = predProbBS[1:, :, :] if plIdx == 1: # predict logit instead of probability wcMatFilename = "LG_" + wcMatFilename mIDsFilename = "LG_" + mIDsFilename predAE = predLogitAE[1:, :, :] predBS = predLogitBS[1:, :, :] wcMat = np.load(os.path.join(curTrainModelDir, wcMatFilename)) # ID of transform models: starts from 0. mIDs = np.load(os.path.join(curTrainModelDir, mIDsFilename)) curPredAE = predAE[mIDs] curPredBS = predBS[mIDs] dIdx = numOfCVDefenses + plIdx * numOfWCDefenses + defenseIdx # testing AE predLabels, defenseTCAEs[AETypeIdx, dIdx] = wcdefenses( curPredAE, wcMat, defenseName, measureTC=True) defenseAccAEs[AETypeIdx, dIdx] = calAccuracy(predLabels, labels) # testing BS predLabels, defenseTCBSs[AETypeIdx, dIdx] = wcdefenses( curPredBS, wcMat, defenseName, measureTC=True) defenseAccBSs[AETypeIdx, dIdx] = calAccuracy(predLabels, labels) # Report accuracy data # accuracies of random defense, clean model and upper bound # rdCleanUPAcc = np.zeros((numOfAETypes+1, 3)) # defenseAccBSs, defenseAccAEs: (numOfAETypes, numofDefenses) rdCleanUPAccFP = os.path.join(testDir, "acc_randomDefense_cleanModel_upperBound.txt") with open(rdCleanUPAccFP, "w") as fp: sformat = "{}\t{}\t{}\t{}\n" fp.write(sformat.format("Type", "Clean_Model", "Rrandom_Defense", "Upper_Bound")) for sampleTypeIdx in range(numOfSampleTypes): fp.write(sformat.format( sampleTypes[sampleTypeIdx], rdCleanUPAcc[sampleTypeIdx, 0], rdCleanUPAcc[sampleTypeIdx, 1], rdCleanUPAcc[sampleTypeIdx, 2])) defenseAccAEsFP = os.path.join(testDir, "acc_AEs_ensembles.txt") with open(defenseAccAEsFP, "w") as fp: sformat = "{}\t{}\t{}\t{}\t{}\t{}\t{}\t{}\t{}\n" fp.write(sformat.format( "Type", "CV_Maj", "CV_Max", "1s_Mean", "EM_Mean", "EM_MXMV", "1s_Mean_L", "EM_Mean_L", "EM_MXMV_L")) for AETypeIdx in range(numOfAETypes): fp.write(sformat.format( AETypes[AETypeIdx], defenseAccAEs[AETypeIdx, 0], defenseAccAEs[AETypeIdx, 1], defenseAccAEs[AETypeIdx, 2], defenseAccAEs[AETypeIdx, 3], defenseAccAEs[AETypeIdx, 4], defenseAccAEs[AETypeIdx, 5], defenseAccAEs[AETypeIdx, 6], defenseAccAEs[AETypeIdx, 7])) defenseAccBSsFP = os.path.join(testDir, "acc_BSs_ensembles.txt") with open(defenseAccBSsFP, "w") as fp: sformat = "{}\t{}\t{}\t{}\t{}\t{}\t{}\t{}\t{}\n" fp.write(sformat.format( "Type", "CV_Maj", "CV_Max", "1s_Mean", "EM_Mean", "EM_MXMV", "1s_Mean_L", "EM_Mean_L", "EM_MXMV_L")) for AETypeIdx in range(numOfAETypes): fp.write(sformat.format( AETypes[AETypeIdx], defenseAccBSs[AETypeIdx, 0], defenseAccBSs[AETypeIdx, 1], defenseAccBSs[AETypeIdx, 2], defenseAccBSs[AETypeIdx, 3], defenseAccBSs[AETypeIdx, 4], defenseAccBSs[AETypeIdx, 5], defenseAccBSs[AETypeIdx, 6], defenseAccBSs[AETypeIdx, 7])) # Report latency # defenseTCBSs , defenseTCAEs : (numOfAETypes, numofDefenses) # predTCs: (numOfSampleTypes, numOfModels, 3) predTCs = np.load(os.path.join(predictionResultDir, "predTCs.npy")) predAndTransTCs = np.zeros((predTCs.shape[0], predTCs.shape[1], 2)) predAndTransTCs[:, :, 0] = predTCs[:, :, 0] + predTCs[:, :, 1] predAndTransTCs[:, :, 1] = predTCs[:, :, 0] + predTCs[:, :, 2] maxTCTransModels = np.argmax(predAndTransTCs[:, 1:, :], axis=1) maxTCTransModelsFP = os.path.join(testDir, "maxTCTransModels.txt") with open(maxTCTransModelsFP, "w") as fp: sformat = "{}\t{}\t{}\n" fp.write(sformat.format( "Type", "ProbPred", "LogitPred")) fp.write(sformat.format( "BS", maxTCTransModels[0, 0], maxTCTransModels[0, 1])) for AETypeIdx in range(numOfAETypes): fp.write(sformat.format( AETypes[AETypeIdx], maxTCTransModels[1 + AETypeIdx, 0], maxTCTransModels[1 + AETypeIdx, 1])) predAndTransTCs = np.max(predAndTransTCs[:, 1:, :], axis=1) # find the largest time cost of transformation and inference across models CAVEnsembleTCs = np.zeros((numOfAETypes, 2)) CAVEnsembleTCs[:, 0] = predAndTransTCs[1:, 0] + defenseTCAEs[:, 0] CAVEnsembleTCs[:, 1] = predAndTransTCs[1:, 0] + defenseTCAEs[:, 1] WCEnsemblesTCs = np.zeros((numOfAETypes, 6)) WCEnsemblesTCs[:, 0] = predAndTransTCs[1:, 0] + defenseTCAEs[:, 2] WCEnsemblesTCs[:, 1] = predAndTransTCs[1:, 0] + defenseTCAEs[:, 3] WCEnsemblesTCs[:, 2] = predAndTransTCs[1:, 0] + defenseTCAEs[:, 4] WCEnsemblesTCs[:, 3] = predAndTransTCs[1:, 1] + defenseTCAEs[:, 5] WCEnsemblesTCs[:, 4] = predAndTransTCs[1:, 1] + defenseTCAEs[:, 6] WCEnsemblesTCs[:, 5] = predAndTransTCs[1:, 1] + defenseTCAEs[:, 7] # probability inference on clean model # defense time costs totalTCsAE = np.zeros((numOfAETypes, 1 + numOfDefenses)) totalTCsAE[:, 0] = predTCs[1:, 0, 1] totalTCsAE[:, 1:3] = CAVEnsembleTCs totalTCsAE[:, 3:] = WCEnsemblesTCs totalTCAEFP = os.path.join(testDir, "time_cost_of_each_ensemble_model.txt") with open(totalTCAEFP, "w") as fp: sformat = "{}\t{}\t{}\t{}\t{}\t{}\t{}\t{}\t{}\t{}\n" fp.write(sformat.format( "Type", "Clean", "CV_Maj", "CV_Max", "1s_Mean", "EM_Mean", "EM_MXMV", "1s_Mean_L", "EM_Mean_L", "EM_MXMV_L")) for AETypeIdx in range(numOfAETypes): fp.write(sformat.format( AETypes[AETypeIdx], totalTCsAE[AETypeIdx, 0], totalTCsAE[AETypeIdx, 1], totalTCsAE[AETypeIdx, 2], totalTCsAE[AETypeIdx, 3], totalTCsAE[AETypeIdx, 4], totalTCsAE[AETypeIdx, 5], totalTCsAE[AETypeIdx, 6], totalTCsAE[AETypeIdx, 7], totalTCsAE[AETypeIdx, 8])) ensembleModelNames = [ "CV_Maj", "CV_Max", "1s_Mean", "EM_Mean", "EM_MXMV", "1s_Mean_L", "EM_Mean_L", "EM_MXMV_L"] xLabel = ["Clean"] xLabel.extend(ensembleModelNames) yLabel = "Latency (ms)" title = "Latency of clean model and ensemble models" saveFP = os.path.join(testDir, "latency.pdf") xtickSize = 8 boxPlot(totalTCsAE * 1000, title, xLabel, yLabel, saveFP, xtickSize, 45) relativeTotTCAE = totalTCsAE / totalTCsAE[:, 0][:, None] relativeTotTCAEFP = os.path.join(testDir, "relative_time_cost_of_each_ensemble_model.txt") with open(relativeTotTCAEFP, "w") as fp: sformat = "{}\t{}\t{}\t{}\t{}\t{}\t{}\t{}\t{}\n" fp.write(sformat.format( "Type", "CV_Maj", "CV_Max", "1s_Mean", "EM_Mean", "EM_MXMV", "1s_Mean_L", "EM_Mean_L", "EM_MXMV_L")) for AETypeIdx in range(numOfAETypes): fp.write(sformat.format( AETypes[AETypeIdx], relativeTotTCAE[AETypeIdx, 1], relativeTotTCAE[AETypeIdx, 2], relativeTotTCAE[AETypeIdx, 3], relativeTotTCAE[AETypeIdx, 4], relativeTotTCAE[AETypeIdx, 5], relativeTotTCAE[AETypeIdx, 6], relativeTotTCAE[AETypeIdx, 7], relativeTotTCAE[AETypeIdx, 8])) xLabel = ensembleModelNames yLabel = "Latency Percentage" title = "Latency of ensemble models relative to clean model" saveFP = os.path.join(testDir, "relative_latency.pdf") boxPlot(relativeTotTCAE[:, 1:], title, xLabel, yLabel, saveFP, xtickSize, 45) # backup raw data of time cost np.save(os.path.join(testDir, "defenseTC_BS.npy"), defenseTCBSs) np.save(os.path.join(testDir, "defenseTC_AE.npy"), defenseTCAEs) # backup accuracy of BS and AEs on clean models and all transform models np.save(os.path.join(testDir, "acc1Model.npy"), acc1Model)
36.490716
127
0.63902
import os import sys import time import numpy as np from utils.config import * from utils.util import * def usage(): print( "====================================================================================================================") print( "python <this script> samplesDir experimentRootDir modelsDir numOfSamples testResultFoldName datasetName numOfClasses") print( "====================================================================================================================") if len(sys.argv) != 8: usage() exit(1) samplesDir = sys.argv[1] experimentRootDir = sys.argv[2] modelsDir = sys.argv[3] numOfSamples = int(sys.argv[4]) testResultFoldName = sys.argv[5] datasetName = sys.argv[6] numOfClasses = int(sys.argv[7]) DATA.set_current_dataset_name(datasetName) architecture = MODEL.ARCHITECTURE testDir = os.path.join(experimentRootDir, testResultFoldName) AETypes = ATTACK.get_AETypes() numOfAETypes = len(AETypes) sampleTypes = ["BS"] sampleTypes.extend(AETypes) numOfSampleTypes = numOfAETypes + 1 targetModelName = "clean" transformConfig = TRANSFORMATION() transformationList = transformConfig.supported_types() predictionResultDir = os.path.join(testDir, "prediction_result") predictionForTest( predictionResultDir, datasetName, architecture, numOfClasses, targetModelName, modelsDir, samplesDir, numOfSamples, AETypes, transformationList) numOfTrans = len(transformationList) - 1 numOfModels = 1 + numOfTrans predProbBS = np.load(os.path.join(predictionResultDir, "BS/predProb.npy")) predLogitBS = np.load(os.path.join(predictionResultDir, "BS/predLogit.npy")) labels = np.load(os.path.join(samplesDir, "Label-" + datasetName + "-" + targetModelName + ".npy")) labels = np.argmax(labels, axis=1) predLCBS = np.zeros((predProbBS.shape[0], predProbBS.shape[1], 2)) predLCBS[:, :, 0] = np.argmax(predProbBS, axis=2) predLCBS[:, :, 1] = np.max(predProbBS, axis=2) labelsBS = labels trainModelDir = os.path.join(experimentRootDir, "train_models") numOfDefenses = numOfCVDefenses + 2 * numOfWCDefenses acc1Model = np.zeros((numOfAETypes + 1, numOfModels)) acc1Model[0, :] = calAccuracyAllSingleModels(labelsBS, predProbBS) defenseAccAEs = np.zeros((numOfAETypes, numOfDefenses)) defenseAccBSs = np.zeros((numOfAETypes, numOfDefenses)) defenseTCAEs = np.zeros((numOfAETypes, numOfDefenses)) defenseTCBSs = np.zeros((numOfAETypes, numOfDefenses)) rdCleanUPAcc = np.zeros((numOfAETypes + 1, 3)) clusters = [] for tmID in range(numOfTrans): clusters.append([tmID]) rdCleanUPAcc[0, 0] = acc1Model[0, 0] rdCleanUPAcc[0, 1] = np.mean(acc1Model[0, 1:]) rdCleanUPAcc[0, 2] = getUpperBoundAccuracy( predLCBS[1:, :, :], clusters, labelsBS) for AETypeIdx in range(numOfAETypes): AEType = AETypes[AETypeIdx] curTrainModelDir = os.path.join(trainModelDir, AEType) curPredictionResultDir = os.path.join(predictionResultDir, AEType) print("Evaluating AE type: " + AEType) predProbAE = np.load(os.path.join(curPredictionResultDir, "predProb.npy")) predLogitAE = np.load(os.path.join(curPredictionResultDir, "predLogit.npy")) predProbLC = np.zeros((numOfModels, numOfSamples, 2)) predProbLC[:, :, 0] = np.argmax(predProbAE, axis=2) predProbLC[:, :, 1] = np.max(predProbAE, axis=2) acc1Model[AETypeIdx + 1, :] = calAccuracyAllSingleModels(labels, predProbAE) rdCleanUPAcc[AETypeIdx + 1, 0] = acc1Model[AETypeIdx + 1, 0] rdCleanUPAcc[AETypeIdx + 1, 1] = np.mean(acc1Model[AETypeIdx + 1, 1:]) rdCleanUPAcc[AETypeIdx + 1, 2] = getUpperBoundAccuracy( predProbLC[1:, :, :], clusters, labels) for defenseIdx in range(numOfCVDefenses): defenseName = cvDefenseNames[defenseIdx] clusters = loadCAVModel(os.path.join(curTrainModelDir, defenseName + ".txt")) votedResults, defenseTCAEs[AETypeIdx, defenseIdx] = votingAsDefense( predProbLC[1:, :, :], clusters, vsac=cvDefenseNames[defenseIdx], measureTC=True) defenseAccAEs[AETypeIdx, defenseIdx] = calAccuracy(votedResults[:, 0], labels) votedResults, defenseTCBSs[AETypeIdx, defenseIdx] = votingAsDefense( predLCBS[1:, :, :], clusters, vsac=cvDefenseNames[defenseIdx], measureTC=True) defenseAccBSs[AETypeIdx, defenseIdx] = calAccuracy(votedResults[:, 0], labelsBS) for defenseIdx in range(numOfWCDefenses): defenseName = wcDefenseNames[defenseIdx] for plIdx in range(2): wcMatFilename = defenseName + "_EM.npy" mIDsFilename = defenseName + "_modelIDs.npy" predAE = predProbAE[1:, :, :] predBS = predProbBS[1:, :, :] if plIdx == 1: wcMatFilename = "LG_" + wcMatFilename mIDsFilename = "LG_" + mIDsFilename predAE = predLogitAE[1:, :, :] predBS = predLogitBS[1:, :, :] wcMat = np.load(os.path.join(curTrainModelDir, wcMatFilename)) mIDs = np.load(os.path.join(curTrainModelDir, mIDsFilename)) curPredAE = predAE[mIDs] curPredBS = predBS[mIDs] dIdx = numOfCVDefenses + plIdx * numOfWCDefenses + defenseIdx predLabels, defenseTCAEs[AETypeIdx, dIdx] = wcdefenses( curPredAE, wcMat, defenseName, measureTC=True) defenseAccAEs[AETypeIdx, dIdx] = calAccuracy(predLabels, labels) predLabels, defenseTCBSs[AETypeIdx, dIdx] = wcdefenses( curPredBS, wcMat, defenseName, measureTC=True) defenseAccBSs[AETypeIdx, dIdx] = calAccuracy(predLabels, labels) rdCleanUPAccFP = os.path.join(testDir, "acc_randomDefense_cleanModel_upperBound.txt") with open(rdCleanUPAccFP, "w") as fp: sformat = "{}\t{}\t{}\t{}\n" fp.write(sformat.format("Type", "Clean_Model", "Rrandom_Defense", "Upper_Bound")) for sampleTypeIdx in range(numOfSampleTypes): fp.write(sformat.format( sampleTypes[sampleTypeIdx], rdCleanUPAcc[sampleTypeIdx, 0], rdCleanUPAcc[sampleTypeIdx, 1], rdCleanUPAcc[sampleTypeIdx, 2])) defenseAccAEsFP = os.path.join(testDir, "acc_AEs_ensembles.txt") with open(defenseAccAEsFP, "w") as fp: sformat = "{}\t{}\t{}\t{}\t{}\t{}\t{}\t{}\t{}\n" fp.write(sformat.format( "Type", "CV_Maj", "CV_Max", "1s_Mean", "EM_Mean", "EM_MXMV", "1s_Mean_L", "EM_Mean_L", "EM_MXMV_L")) for AETypeIdx in range(numOfAETypes): fp.write(sformat.format( AETypes[AETypeIdx], defenseAccAEs[AETypeIdx, 0], defenseAccAEs[AETypeIdx, 1], defenseAccAEs[AETypeIdx, 2], defenseAccAEs[AETypeIdx, 3], defenseAccAEs[AETypeIdx, 4], defenseAccAEs[AETypeIdx, 5], defenseAccAEs[AETypeIdx, 6], defenseAccAEs[AETypeIdx, 7])) defenseAccBSsFP = os.path.join(testDir, "acc_BSs_ensembles.txt") with open(defenseAccBSsFP, "w") as fp: sformat = "{}\t{}\t{}\t{}\t{}\t{}\t{}\t{}\t{}\n" fp.write(sformat.format( "Type", "CV_Maj", "CV_Max", "1s_Mean", "EM_Mean", "EM_MXMV", "1s_Mean_L", "EM_Mean_L", "EM_MXMV_L")) for AETypeIdx in range(numOfAETypes): fp.write(sformat.format( AETypes[AETypeIdx], defenseAccBSs[AETypeIdx, 0], defenseAccBSs[AETypeIdx, 1], defenseAccBSs[AETypeIdx, 2], defenseAccBSs[AETypeIdx, 3], defenseAccBSs[AETypeIdx, 4], defenseAccBSs[AETypeIdx, 5], defenseAccBSs[AETypeIdx, 6], defenseAccBSs[AETypeIdx, 7])) predTCs = np.load(os.path.join(predictionResultDir, "predTCs.npy")) predAndTransTCs = np.zeros((predTCs.shape[0], predTCs.shape[1], 2)) predAndTransTCs[:, :, 0] = predTCs[:, :, 0] + predTCs[:, :, 1] predAndTransTCs[:, :, 1] = predTCs[:, :, 0] + predTCs[:, :, 2] maxTCTransModels = np.argmax(predAndTransTCs[:, 1:, :], axis=1) maxTCTransModelsFP = os.path.join(testDir, "maxTCTransModels.txt") with open(maxTCTransModelsFP, "w") as fp: sformat = "{}\t{}\t{}\n" fp.write(sformat.format( "Type", "ProbPred", "LogitPred")) fp.write(sformat.format( "BS", maxTCTransModels[0, 0], maxTCTransModels[0, 1])) for AETypeIdx in range(numOfAETypes): fp.write(sformat.format( AETypes[AETypeIdx], maxTCTransModels[1 + AETypeIdx, 0], maxTCTransModels[1 + AETypeIdx, 1])) predAndTransTCs = np.max(predAndTransTCs[:, 1:, :], axis=1) CAVEnsembleTCs = np.zeros((numOfAETypes, 2)) CAVEnsembleTCs[:, 0] = predAndTransTCs[1:, 0] + defenseTCAEs[:, 0] CAVEnsembleTCs[:, 1] = predAndTransTCs[1:, 0] + defenseTCAEs[:, 1] WCEnsemblesTCs = np.zeros((numOfAETypes, 6)) WCEnsemblesTCs[:, 0] = predAndTransTCs[1:, 0] + defenseTCAEs[:, 2] WCEnsemblesTCs[:, 1] = predAndTransTCs[1:, 0] + defenseTCAEs[:, 3] WCEnsemblesTCs[:, 2] = predAndTransTCs[1:, 0] + defenseTCAEs[:, 4] WCEnsemblesTCs[:, 3] = predAndTransTCs[1:, 1] + defenseTCAEs[:, 5] WCEnsemblesTCs[:, 4] = predAndTransTCs[1:, 1] + defenseTCAEs[:, 6] WCEnsemblesTCs[:, 5] = predAndTransTCs[1:, 1] + defenseTCAEs[:, 7] totalTCsAE = np.zeros((numOfAETypes, 1 + numOfDefenses)) totalTCsAE[:, 0] = predTCs[1:, 0, 1] totalTCsAE[:, 1:3] = CAVEnsembleTCs totalTCsAE[:, 3:] = WCEnsemblesTCs totalTCAEFP = os.path.join(testDir, "time_cost_of_each_ensemble_model.txt") with open(totalTCAEFP, "w") as fp: sformat = "{}\t{}\t{}\t{}\t{}\t{}\t{}\t{}\t{}\t{}\n" fp.write(sformat.format( "Type", "Clean", "CV_Maj", "CV_Max", "1s_Mean", "EM_Mean", "EM_MXMV", "1s_Mean_L", "EM_Mean_L", "EM_MXMV_L")) for AETypeIdx in range(numOfAETypes): fp.write(sformat.format( AETypes[AETypeIdx], totalTCsAE[AETypeIdx, 0], totalTCsAE[AETypeIdx, 1], totalTCsAE[AETypeIdx, 2], totalTCsAE[AETypeIdx, 3], totalTCsAE[AETypeIdx, 4], totalTCsAE[AETypeIdx, 5], totalTCsAE[AETypeIdx, 6], totalTCsAE[AETypeIdx, 7], totalTCsAE[AETypeIdx, 8])) ensembleModelNames = [ "CV_Maj", "CV_Max", "1s_Mean", "EM_Mean", "EM_MXMV", "1s_Mean_L", "EM_Mean_L", "EM_MXMV_L"] xLabel = ["Clean"] xLabel.extend(ensembleModelNames) yLabel = "Latency (ms)" title = "Latency of clean model and ensemble models" saveFP = os.path.join(testDir, "latency.pdf") xtickSize = 8 boxPlot(totalTCsAE * 1000, title, xLabel, yLabel, saveFP, xtickSize, 45) relativeTotTCAE = totalTCsAE / totalTCsAE[:, 0][:, None] relativeTotTCAEFP = os.path.join(testDir, "relative_time_cost_of_each_ensemble_model.txt") with open(relativeTotTCAEFP, "w") as fp: sformat = "{}\t{}\t{}\t{}\t{}\t{}\t{}\t{}\t{}\n" fp.write(sformat.format( "Type", "CV_Maj", "CV_Max", "1s_Mean", "EM_Mean", "EM_MXMV", "1s_Mean_L", "EM_Mean_L", "EM_MXMV_L")) for AETypeIdx in range(numOfAETypes): fp.write(sformat.format( AETypes[AETypeIdx], relativeTotTCAE[AETypeIdx, 1], relativeTotTCAE[AETypeIdx, 2], relativeTotTCAE[AETypeIdx, 3], relativeTotTCAE[AETypeIdx, 4], relativeTotTCAE[AETypeIdx, 5], relativeTotTCAE[AETypeIdx, 6], relativeTotTCAE[AETypeIdx, 7], relativeTotTCAE[AETypeIdx, 8])) xLabel = ensembleModelNames yLabel = "Latency Percentage" title = "Latency of ensemble models relative to clean model" saveFP = os.path.join(testDir, "relative_latency.pdf") boxPlot(relativeTotTCAE[:, 1:], title, xLabel, yLabel, saveFP, xtickSize, 45) np.save(os.path.join(testDir, "defenseTC_BS.npy"), defenseTCBSs) np.save(os.path.join(testDir, "defenseTC_AE.npy"), defenseTCAEs) np.save(os.path.join(testDir, "acc1Model.npy"), acc1Model)
true
true
1c39415d2831c402bbcfd6fc9987ca728401fb5c
333,094
py
Python
packages/vaex-core/vaex/dataframe.py
And0k/vaex
298d0d5c6ace0ea4c335339fef10ba7ee54cc077
[ "MIT" ]
337
2016-02-11T07:36:35.000Z
2018-12-10T07:17:35.000Z
packages/vaex-core/vaex/dataframe.py
And0k/vaex
298d0d5c6ace0ea4c335339fef10ba7ee54cc077
[ "MIT" ]
127
2016-07-06T15:43:14.000Z
2018-12-11T18:46:27.000Z
packages/vaex-core/vaex/dataframe.py
And0k/vaex
298d0d5c6ace0ea4c335339fef10ba7ee54cc077
[ "MIT" ]
29
2016-10-05T14:15:28.000Z
2018-11-29T10:17:00.000Z
# -*- coding: utf-8 -*- from __future__ import division, print_function import io import difflib import base64 from typing import Iterable import os import math import time import itertools import functools import collections import sys import platform import warnings import re from functools import reduce import threading import six import vaex.utils # import vaex.image import numpy as np import concurrent.futures import numbers import pyarrow as pa from vaex.utils import Timer import vaex.events # import vaex.ui.undo import vaex.grids import vaex.hash import vaex.multithreading import vaex.promise import vaex.execution import vaex.expresso import logging import vaex.kld from . import selections, tasks, scopes from .expression import expression_namespace from .delayed import delayed, delayed_args, delayed_list from .column import Column, ColumnIndexed, ColumnSparse, ColumnString, ColumnConcatenatedLazy, supported_column_types from . import array_types import vaex.events from .datatype import DataType from .docstrings import docsubst astropy = vaex.utils.optional_import("astropy.units") xarray = vaex.utils.optional_import("xarray") # py2/p3 compatibility try: from urllib.parse import urlparse except ImportError: from urlparse import urlparse _DEBUG = os.environ.get('VAEX_DEBUG', False) # extra sanity checks that might hit performance _REPORT_EXECUTION_TRACES = vaex.utils.get_env_type(int, 'VAEX_EXECUTE_TRACE', 0) DEFAULT_REPR_FORMAT = 'plain' FILTER_SELECTION_NAME = '__filter__' sys_is_le = sys.byteorder == 'little' logger = logging.getLogger("vaex") lock = threading.Lock() default_shape = 128 default_chunk_size = 1024**2 # executor = concurrent.futures.ThreadPoolExecutor(max_workers=2) # executor = vaex.execution.default_executor def _len(o): return o.__len__() def _requires(name): def wrap(*args, **kwargs): raise RuntimeError('this function is wrapped by a placeholder, you probably want to install vaex-' + name) return wrap from .utils import (_ensure_strings_from_expressions, _ensure_string_from_expression, _ensure_list, _is_limit, _isnumber, _issequence, _is_string, _normalize_selection, _parse_reduction, _parse_n, _normalize_selection_name, _normalize, _parse_f, _expand, _expand_shape, _expand_limits, as_flat_float, as_flat_array, _split_and_combine_mask) main_executor = None # vaex.execution.Executor(vaex.multithreading.pool) from vaex.execution import Executor def get_main_executor(): global main_executor if main_executor is None: main_executor = vaex.execution.ExecutorLocal(vaex.multithreading.get_main_pool()) return main_executor # we import after function_mapping is defined from .expression import Expression _functions_statistics_1d = [] def stat_1d(f): _functions_statistics_1d.append(f) return f def _hidden(meth): """Mark a method as hidden""" meth.__hidden__ = True return meth @vaex.encoding.register("dataframe") class _DataFrameEncoder: @staticmethod def encode(encoding, df): state = df.state_get(skip=[df.dataset]) return { 'state': encoding.encode('dataframe-state', state), 'dataset': encoding.encode('dataset', df.dataset) } @staticmethod def decode(encoding, spec): dataset = encoding.decode('dataset', spec['dataset']) state = encoding.decode('dataframe-state', spec['state']) df = vaex.from_dataset(dataset)._future() df.state_set(state) return df class DataFrame(object): """All local or remote datasets are encapsulated in this class, which provides a pandas like API to your dataset. Each DataFrame (df) has a number of columns, and a number of rows, the length of the DataFrame. All DataFrames have multiple 'selection', and all calculations are done on the whole DataFrame (default) or for the selection. The following example shows how to use the selection. >>> df.select("x < 0") >>> df.sum(df.y, selection=True) >>> df.sum(df.y, selection=[df.x < 0, df.x > 0]) :type signal_selection_changed: events.Signal :type executor: Executor """ def __init__(self, name=None, executor=None): self.executor = executor or get_main_executor() self.name = name self._init() def _init(self): self.column_names = [] self.signal_pick = vaex.events.Signal("pick") self.signal_sequence_index_change = vaex.events.Signal("sequence index change") self.signal_selection_changed = vaex.events.Signal("selection changed") self.signal_active_fraction_changed = vaex.events.Signal("active fraction changed") self.signal_column_changed = vaex.events.Signal("a column changed") # (df, column_name, change_type=["add", "remove", "change"]) self.signal_variable_changed = vaex.events.Signal("a variable changed") self.variables = {} self.virtual_columns = {} # we also store the virtual columns as expressions, for performance reasons # the expression object can cache the ast, making renaming/rewriting faster self._virtual_expressions = {} self.functions = {} self._length_original = None self._length_unfiltered = None self._cached_filtered_length = None self._filter_filled = False self._active_fraction = 1 self._current_row = None self._index_start = 0 self._index_end = None self.description = None self.ucds = {} self.units = {} self.descriptions = {} self.favorite_selections = {} # this is to be backward compatible with v4 for now self._future_behaviour = False self.mask = None # a bitmask for the selection does not work for server side # maps from name to list of Selection objets self.selection_histories = collections.defaultdict(list) # after an undo, the last one in the history list is not the active one, -1 means no selection self.selection_history_indices = collections.defaultdict(lambda: -1) assert self.filtered is False self._auto_fraction = False self._sparse_matrices = {} # record which sparse columns belong to which sparse matrix self._categories = {} self._selection_mask_caches = collections.defaultdict(dict) self._selection_masks = {} # maps to vaex.superutils.Mask object self._renamed_columns = [] # weak refs of expression that we keep to rewrite expressions self._expressions = [] self.local = threading.local() # a check to avoid nested aggregator calls, which make stack traces very difficult # like the ExecutorLocal.local.executing, this needs to be thread local self.local._aggregator_nest_count = 0 def fingerprint(self, dependencies=None, treeshake=False): '''Id that uniquely identifies a dataframe (cross runtime). :param set[str] dependencies: set of column, virtual column, function or selection names to be used. :param bool treeshake: Get rid of unused variables before calculating the fingerprint. ''' df = self.copy(treeshake=True) if treeshake else self selections = {name: self.get_selection(name) for name, history in self.selection_histories.items() if self.has_selection(name)} if dependencies is not None: dependencies = set(dependencies) # copy # these are implicit dependencies that we need to add for selection in selections.values(): dependencies.update(selection.dependencies(self)) # we only use the state parts that affect data (no metadata) encoding = vaex.encoding.Encoding() def dep_filter(d : dict): if dependencies is None: return d return {k: v for k, v in d.items() if k in dependencies} state = dict( column_names=[k for k in list(self.column_names) if dependencies is None or k in dependencies], virtual_columns=dep_filter(self.virtual_columns), # variables go unencoded variables=dep_filter(self.variables), # for functions it should be fast enough (not large amounts of data) functions={name: encoding.encode("function", value) for name, value in dep_filter(self.functions).items()}, active_range=[self._index_start, self._index_end] ) # selections can affect the filter, so put them all in state['selections'] = {name: selection.to_dict() if selection is not None else None for name, selection in selections.items()} fp = vaex.cache.fingerprint(state, df.dataset.fingerprint) return f'dataframe-{fp}' def __dataframe__(self, nan_as_null : bool = False, allow_copy : bool = True): """ """ import vaex.dataframe_protocol return vaex.dataframe_protocol._VaexDataFrame(self, nan_as_null=nan_as_null, allow_copy=allow_copy) def _future(self, version=5, inplace=False): '''Act like a Vaex dataframe version 5. meaning: * A dataframe with automatically encoded categorical data * state version 5 (which stored the dataset) ''' df = self if inplace else self.copy() df._future_behaviour = 5 return df _auto_encode = _hidden(vaex.utils.deprecated('use _future')(_future)) def __getattr__(self, name): # will support the hidden methods if name in self.__hidden__: return self.__hidden__[name].__get__(self) else: return object.__getattribute__(self, name) def _ipython_key_completions_(self): return self.get_column_names() @property def func(self): class Functions(object): pass functions = Functions() for name, value in expression_namespace.items(): # f = vaex.expression.FunctionBuiltin(self, name) def closure(name=name, value=value): local_name = name def wrap(*args, **kwargs): def myrepr(k): if isinstance(k, Expression): return str(k) elif isinstance(k, np.ndarray) and k.ndim == 0: # to support numpy scalars return myrepr(k.item()) elif isinstance(k, np.ndarray): # to support numpy arrays var = self.add_variable('arg_numpy_array', k, unique=True) return var elif isinstance(k, list): # to support numpy scalars return '[' + ', '.join(myrepr(i) for i in k) + ']' else: return repr(k) arg_string = ", ".join([myrepr(k) for k in args] + ['{}={}'.format(name, myrepr(value)) for name, value in kwargs.items()]) expression = "{}({})".format(local_name, arg_string) return vaex.expression.Expression(self, expression) return wrap f = closure() try: f = functools.wraps(value)(f) except AttributeError: pass # python2 quicks.. ? setattr(functions, name, f) for name, value in self.functions.items(): setattr(functions, name, value) return functions @_hidden @vaex.utils.deprecated('use is_category') def iscategory(self, column): return self.is_category(column) def is_datetime(self, expression): dtype = self.data_type(expression) return isinstance(dtype, np.dtype) and dtype.kind == 'M' def is_string(self, expression): return vaex.array_types.is_string_type(self.data_type(expression)) def is_category(self, column): """Returns true if column is a category.""" column = _ensure_string_from_expression(column) # TODO: we don't support DictionaryType for remote dataframes if self.is_local() and column in self.columns: # TODO: we don't support categories as expressions dtype = vaex.dtype_of(self.columns[column]) if dtype.is_encoded: return True return column in self._categories def _category_dictionary(self, column): '''Return the dictionary for a column if it is an arrow dict type''' if column in self.columns: x = self.columns[column] dtype = vaex.dtype_of(x) if dtype.is_encoded: x = x[:1] # could be a proxy # we're interested in the type of the dictionary or the indices? if isinstance(x, pa.ChunkedArray): # take the first dictionaryu x = x.chunks[0] dictionary = x.dictionary return dictionary def category_labels(self, column, aslist=True): column = _ensure_string_from_expression(column) if column in self._categories: return self._categories[column]['labels'] dictionary = self._category_dictionary(column) if dictionary is not None: if aslist: dictionary = dictionary.to_pylist() return dictionary else: raise ValueError(f'Column {column} is not a categorical') def category_values(self, column): column = _ensure_string_from_expression(column) return self._categories[column]['values'] def category_count(self, column): column = _ensure_string_from_expression(column) if column in self._categories: return self._categories[column]['N'] dictionary = self._category_dictionary(column) if dictionary is not None: return len(dictionary) else: raise ValueError(f'Column {column} is not a categorical') def category_offset(self, column): column = _ensure_string_from_expression(column) if column in self._categories: return self._categories[column]['min_value'] dictionary = self._category_dictionary(column) if dictionary is not None: return 0 else: raise ValueError(f'Column {column} is not a categorical') def execute(self): '''Execute all delayed jobs.''' # make sure we only add the tasks at the last moment, after all operations are added (for cache keys) if not self.executor.tasks: logger.info('no task to execute') return if _REPORT_EXECUTION_TRACES: import traceback trace = ''.join(traceback.format_stack(limit=_REPORT_EXECUTION_TRACES)) print('Execution triggerd from:\n', trace) print("Tasks:") for task in self.executor.tasks: print(repr(task)) if self.executor.tasks: self.executor.execute() async def execute_async(self): '''Async version of execute''' await self.executor.execute_async() @property def filtered(self): return self.has_selection(FILTER_SELECTION_NAME) def map_reduce(self, map, reduce, arguments, progress=False, delay=False, info=False, to_numpy=True, ignore_filter=False, pre_filter=False, name='map reduce (custom)', selection=None): # def map_wrapper(*blocks): pre_filter = pre_filter and self.filtered task = tasks.TaskMapReduce(self, arguments, map, reduce, info=info, to_numpy=to_numpy, ignore_filter=ignore_filter, selection=selection, pre_filter=pre_filter) progressbar = vaex.utils.progressbars(progress) progressbar.add_task(task, f'map reduce: {name}') task = self.executor.schedule(task) return self._delay(delay, task) def apply(self, f, arguments=None, vectorize=False, multiprocessing=True): """Apply a function on a per row basis across the entire DataFrame. Example: >>> import vaex >>> df = vaex.example() >>> def func(x, y): ... return (x+y)/(x-y) ... >>> df.apply(func, arguments=[df.x, df.y]) Expression = lambda_function(x, y) Length: 330,000 dtype: float64 (expression) ------------------------------------------- 0 -0.460789 1 3.90038 2 -0.642851 3 0.685768 4 -0.543357 :param f: The function to be applied :param arguments: List of arguments to be passed on to the function f. :param vectorize: Call f with arrays instead of a scalars (for better performance). :param bool multiprocessing: Use multiple processes to avoid the GIL (Global interpreter lock). :return: A function that is lazily evaluated. """ assert arguments is not None, 'for now, you need to supply arguments' import types if isinstance(f, types.LambdaType): name = 'lambda_function' else: name = f.__name__ if not vectorize: f = vaex.expression.FunctionToScalar(f, multiprocessing) else: f = vaex.expression.FunctionSerializablePickle(f, multiprocessing) lazy_function = self.add_function(name, f, unique=True) arguments = _ensure_strings_from_expressions(arguments) return lazy_function(*arguments) @docsubst def nop(self, expression=None, progress=False, delay=False): """Evaluates expression or a list of expressions, and drops the result. Usefull for benchmarking, since vaex is usually lazy. :param expression: {expression} :param progress: {progress} :param delay: {delay} :returns: None """ if expression is None: expressions = self.get_column_names() else: expressions = _ensure_list(_ensure_strings_from_expressions(expression)) def map(*ar): pass def reduce(a, b): pass return self.map_reduce(map, reduce, expressions, delay=delay, progress=progress, name='nop', to_numpy=False) def _hash_map_unique(self, expression, progress=False, selection=None, flatten=True, delay=False, limit=None, limit_raise=True, return_inverse=False): if selection is not None: selection = str(selection) expression = _ensure_string_from_expression(expression) task = vaex.tasks.TaskHashmapUniqueCreate(self, expression, flatten, limit=limit, selection=selection, return_inverse=return_inverse, limit_raise=limit_raise) task = self.executor.schedule(task) progressbar = vaex.utils.progressbars(progress) progressbar.add_task(task, f"set for {str(expression)}") return self._delay(delay, task) # kept for compatibility _set = _hash_map_unique def _index(self, expression, progress=False, delay=False, prime_growth=False, cardinality=None): column = _ensure_string_from_expression(expression) # TODO: this does not seem needed # column = vaex.utils.valid_expression(self.dataset, column) columns = [column] from .hash import index_type_from_dtype from vaex.column import _to_string_sequence transient = self[column].transient or self.filtered or self.is_masked(column) if self.is_string(expression) and not transient: # string is a special case, only ColumnString are not transient ar = self.columns[str(self[column].expand())] if not isinstance(ar, ColumnString): transient = True dtype = self.data_type(column) index_type = index_type_from_dtype(dtype, transient, prime_growth=prime_growth) import queue if cardinality is not None: N_index = min(self.executor.thread_pool.nthreads, max(1, len(self)//cardinality)) capacity_initial = len(self) // N_index else: N_index = self.executor.thread_pool.nthreads capacity_initial = 10 indices = queue.Queue() # we put None to lazily create them for i in range(N_index): indices.put(None) def map(thread_index, i1, i2, selection_masks, blocks): ar = blocks[0] index = indices.get() if index is None: index = index_type(1) if hasattr(index, 'reserve'): index.reserve(capacity_initial) if vaex.array_types.is_string_type(dtype): previous_ar = ar ar = _to_string_sequence(ar) if not transient: assert ar is previous_ar.string_sequence if np.ma.isMaskedArray(ar): mask = np.ma.getmaskarray(ar) index.update(ar, mask, i1) else: index.update(ar, i1) indices.put(index) # cardinality_estimated = sum() def reduce(a, b): pass self.map_reduce(map, reduce, columns, delay=delay, name='index', info=True, to_numpy=False) index_list = [] #[k for k in index_list if k is not None] while not indices.empty(): index = indices.get(timeout=10) if index is not None: index_list.append(index) index0 = index_list[0] for other in index_list[1:]: index0.merge(other) return index0 @docsubst def unique(self, expression, return_inverse=False, dropna=False, dropnan=False, dropmissing=False, progress=False, selection=None, axis=None, delay=False, limit=None, limit_raise=True, array_type='python'): """Returns all unique values. :param expression: {expression} :param return_inverse: Return the inverse mapping from unique values to original values. :param dropna: {dropna} :param dropnan: {dropnan} :param dropmissing: {dropmissing} :param progress: {progress} :param selection: {selection} :param int axis: Axis over which to determine the unique elements (None will flatten arrays or lists) :param delay: {delay} :param int limit: {limit} :param bool limit_raise: {limit_raise} :param str array_type: {array_type} """ if dropna: dropnan = True dropmissing = True if axis is not None: raise ValueError('only axis=None is supported') expression = _ensure_string_from_expression(expression) if self._future_behaviour and self.is_category(expression): if self.filtered: keys = pa.array(self.category_labels(expression)) @delayed def encode(codes): used_keys = keys.take(codes) return vaex.array_types.convert(used_keys, array_type) codes = self[expression].index_values().unique(delay=True) return self._delay(delay, encode(codes)) else: keys = pa.array(self.category_labels(expression)) keys = vaex.array_types.convert(keys, array_type) return self._delay(delay, vaex.promise.Promise.fulfilled(keys)) else: @delayed def process(hash_map_unique): transient = True data_type_item = self.data_type(expression, axis=-1) if return_inverse: # inverse type can be smaller, depending on length of set inverse = np.zeros(self._length_unfiltered, dtype=np.int64) dtype = self.data_type(expression) from vaex.column import _to_string_sequence def map(thread_index, i1, i2, selection_mask, blocks): ar = blocks[0] if vaex.array_types.is_string_type(dtype): previous_ar = ar ar = _to_string_sequence(ar) if not transient: assert ar is previous_ar.string_sequence # TODO: what about masked values? inverse[i1:i2] = hash_map_unique.map(ar) def reduce(a, b): pass self.map_reduce(map, reduce, [expression], delay=delay, name='unique_return_inverse', progress=progress_inverse, info=True, to_numpy=False, selection=selection) # ordered_set.seal() # if array_type == 'python': if data_type_item.is_object: key_values = hash_map_unique._internal.extract() keys = list(key_values.keys()) counts = list(key_values.values()) if hash_map_unique.has_nan and not dropnan: keys = [np.nan] + keys counts = [hash_map_unique.nan_count] + counts if hash_map_unique.has_null and not dropmissing: keys = [None] + keys counts = [hash_map_unique.null_count] + counts if dropmissing and None in keys: # we still can have a None in the values index = keys.index(None) keys.pop(index) counts.pop(index) counts = np.array(counts) keys = np.array(keys) else: keys = hash_map_unique.keys() # TODO: we might want to put the dropmissing in .keys(..) deletes = [] if dropmissing and hash_map_unique.has_null: deletes.append(hash_map_unique.null_index) if dropnan and hash_map_unique.has_nan: deletes.append(hash_map_unique.nan_index) if isinstance(keys, (vaex.strings.StringList32, vaex.strings.StringList64)): keys = vaex.strings.to_arrow(keys) indices = np.delete(np.arange(len(keys)), deletes) keys = keys.take(indices) else: keys = np.delete(keys, deletes) if not dropmissing and hash_map_unique.has_null: mask = np.zeros(len(keys), dtype=np.uint8) mask[hash_map_unique.null_index] = 1 keys = np.ma.array(keys, mask=mask) if data_type_item == str and isinstance(keys, np.ndarray): # the np.delete will cast to dtype object keys = pa.array(keys) keys = vaex.array_types.convert(keys, array_type) if return_inverse: return keys, inverse else: return keys progressbar = vaex.utils.progressbars(progress, title="unique") hash_map_result = self._hash_map_unique(expression, progress=progressbar, selection=selection, flatten=axis is None, delay=True, limit=limit, limit_raise=limit_raise) if return_inverse: progress_inverse = progressbar.add("find inverse") return self._delay(delay, progressbar.exit_on(process(hash_map_result))) @docsubst def mutual_information(self, x, y=None, dimension=2, mi_limits=None, mi_shape=256, binby=[], limits=None, shape=default_shape, sort=False, selection=False, delay=False): """Estimate the mutual information between and x and y on a grid with shape mi_shape and mi_limits, possibly on a grid defined by binby. The `x` and `y` arguments can be single expressions of lists of expressions: - If `x` and `y` are single expression, it computes the mutual information between `x` and `y`; - If `x` is a list of expressions and `y` is a single expression, it computes the mutual information between each expression in `x` and the expression in `y`; - If `x` is a list of expressions and `y` is None, it computes the mutual information matrix amongst all expressions in `x`; - If `x` is a list of tuples of length 2, it computes the mutual information for the specified dimension pairs; - If `x` and `y` are lists of expressions, it computes the mutual information matrix defined by the two expression lists. If sort is True, the mutual information is returned in sorted (descending) order and the list of expressions is returned in the same order. Example: >>> import vaex >>> df = vaex.example() >>> df.mutual_information("x", "y") array(0.1511814526380327) >>> df.mutual_information([["x", "y"], ["x", "z"], ["E", "Lz"]]) array([ 0.15118145, 0.18439181, 1.07067379]) >>> df.mutual_information([["x", "y"], ["x", "z"], ["E", "Lz"]], sort=True) (array([ 1.07067379, 0.18439181, 0.15118145]), [['E', 'Lz'], ['x', 'z'], ['x', 'y']]) >>> df.mutual_information(x=['x', 'y', 'z']) array([[3.53535106, 0.06893436, 0.11656418], [0.06893436, 3.49414866, 0.14089177], [0.11656418, 0.14089177, 3.96144906]]) >>> df.mutual_information(x=['x', 'y', 'z'], y=['E', 'Lz']) array([[0.32316291, 0.16110026], [0.36573065, 0.17802792], [0.35239151, 0.21677695]]) :param x: {expression} :param y: {expression} :param limits: {limits} :param shape: {shape} :param binby: {binby} :param limits: {limits} :param shape: {shape} :param sort: return mutual information in sorted (descending) order, and also return the correspond list of expressions when sorted is True :param selection: {selection} :param delay: {delay} :return: {return_stat_scalar}, """ # either a list of tuples with custom combinations if y is None and _issequence(x) and all([_issequence(k) for k in x]): waslist, [combinations, ] = vaex.utils.listify(x) shape_result = (len(combinations),) elif _issequence(x) and (_issequence(y) or y is None): # or ask for a matrix of combinations if y is None: combinations = list(itertools.product(x, repeat=dimension)) shape_result = (len(x), ) * dimension else: shape_result = (len(x), len(y)) combinations = np.array([[(i, j) for i in y] for j in x]).reshape((-1, 2)).tolist() waslist = True elif _issequence(x): shape_result = (len(x),) combinations = [(i, y) for i in x] waslist = True elif _issequence(y): shape_result = (len(y),) combinations = [(i, y) for i in x] waslist = True else: shape_result = tuple() combinations = [(x, y)] waslist = False if mi_limits: mi_limits = [mi_limits] limits = self.limits(binby, limits, delay=True) # make sure we only do the unique combinations combinations_sorted = [tuple(sorted(k)) for k in combinations] combinations_unique, unique_reverse = np.unique(combinations_sorted, return_inverse=True, axis=0) combinations_unique = list(map(tuple, combinations_unique.tolist())) mi_limits = self.limits(combinations_unique, mi_limits, delay=True) @delayed def calculate(counts): # TODO: mutual information doesn't take axis arguments, so ugly solution for now counts = counts.astype(np.float64) fullshape = _expand_shape(shape, len(binby)) out = np.zeros((fullshape), dtype=float) if len(fullshape) == 0: out = vaex.kld.mutual_information(counts) # print("count> ", np.sum(counts)) elif len(fullshape) == 1: for i in range(fullshape[0]): out[i] = vaex.kld.mutual_information(counts[..., i]) # print("counti> ", np.sum(counts[...,i])) # print("countt> ", np.sum(counts)) elif len(fullshape) == 2: for i in range(fullshape[0]): for j in range(fullshape[1]): out[i, j] = vaex.kld.mutual_information(counts[..., i, j]) elif len(fullshape) == 3: for i in range(fullshape[0]): for j in range(fullshape[1]): for k in range(fullshape[2]): out[i, j, k] = vaex.kld.mutual_information(counts[..., i, j, k]) else: raise ValueError("binby with dim > 3 is not yet supported") return out @delayed def has_limits(limits, mi_limits): if not _issequence(binby): limits = [list(limits)] values = [] for expressions, expression_limits in zip(combinations_unique, mi_limits): total_shape = _expand_shape(mi_shape, len(expressions)) + _expand_shape(shape, len(binby)) counts = self.count(binby=list(expressions) + list(binby), limits=list(expression_limits) + list(limits), shape=total_shape, delay=True, selection=selection) values.append(calculate(counts)) return values @delayed def finish(mi_list): if sort: mi_list = np.array(mi_list) indices = np.argsort(mi_list)[::-1] sorted_x = list([x[k] for k in indices]) return mi_list[indices], sorted_x else: mi_list = np.array(mi_list) # reconstruct original ordering mi_list = mi_list[unique_reverse] total_shape = _expand_shape(shape, len(binby)) total_shape += shape_result return np.array(vaex.utils.unlistify(waslist, mi_list)).reshape(total_shape) values = finish(delayed_list(has_limits(limits, mi_limits))) return self._delay(delay, values) def bin_edges(self, expression, limits, shape=default_shape): return self.bins(expression, limits, shape=shape, edges=True) def bin_centers(self, expression, limits, shape=default_shape): return self.bins(expression, limits, shape=shape, edges=False) def bins(self, expression, limits, shape=default_shape, edges=True): vmin, vmax = limits if edges: bins = np.ogrid[limits[0]:limits[1]:(shape + 1) * 1j] return bins else: dx = (limits[1] - limits[0]) / shape bins = np.ogrid[limits[0]:limits[1] - dx:(shape) * 1j] return bins + dx / 2 def nearest_bin(self, value, limits, shape): bins = self.bins('', limits=limits, edges=False, shape=shape) index = np.argmin(np.abs(bins - value)) return index def _compute_agg(self, name, expression, binby=[], limits=None, shape=default_shape, selection=False, delay=False, edges=False, progress=None, extra_expressions=None, array_type=None): logger.debug("aggregate %s(%r, binby=%r, limits=%r)", name, expression, binby, limits) expression = _ensure_strings_from_expressions(expression) if extra_expressions: extra_expressions = _ensure_strings_from_expressions(extra_expressions) expression_waslist, [expressions, ] = vaex.utils.listify(expression) # TODO: doesn't seemn needed anymore? # expressions = [self._column_aliases.get(k, k) for k in expressions] import traceback trace = ''.join(traceback.format_stack()) for expression in expressions: if expression and expression != "*": self.validate_expression(expression) if not hasattr(self.local, '_aggregator_nest_count'): self.local._aggregator_nest_count = 0 if self.local._aggregator_nest_count != 0: raise RuntimeError("nested aggregator call: \nlast trace:\n%s\ncurrent trace:\n%s" % (self.local.last_trace, trace)) else: self.local.last_trace = trace # Instead of 'expression is not None', we would like to have 'not virtual' # but in agg.py we do some casting, which results in calling .dtype(..) with a non-column # expression even though all expressions passed here are column references # virtual = [k for k in expressions if k and k not in self.columns] if self._future_behaviour != 5 and (self.filtered and expression not in [None, '*']): # When our dataframe is filtered, and we have expressions, we may end up calling # df.dtype(..) which in turn may call df.evaluate(..) which in turn needs to have # the filter cache filled in order to compute the first non-missing row. This last # item could call df.count() again, leading to nested aggregators, which we do not # support. df.dtype() needs to call evaluate with filtering enabled since we consider # it invalid that expressions are evaluate with filtered data. Sklearn for instance may # give errors when evaluated with NaN's present. # TODO: GET RID OF THIS # TODO: temporary disabled # len(self) # fill caches and masks pass progressbar = vaex.utils.progressbars(progress, title=name) if not isinstance(binby, (list, tuple)) or len(binby) > 0: progressbar_limits = progressbar.add("binners") binners = self._create_binners(binby, limits, shape, selection=selection, delay=True, progress=progressbar_limits) else: binners = () progressbar_agg = progressbar @delayed def compute(expression, binners, selection, edges): binners = tuple(binners) if not hasattr(self.local, '_aggregator_nest_count'): self.local._aggregator_nest_count = 0 self.local._aggregator_nest_count += 1 try: if expression in ["*", None]: agg = vaex.agg.aggregates[name](selection=selection, edges=edges) else: if extra_expressions: agg = vaex.agg.aggregates[name](expression, *extra_expressions, selection=selection, edges=edges) else: agg = vaex.agg.aggregates[name](expression, selection=selection, edges=edges) tasks, result = agg.add_tasks(self, binners, progress=progressbar) @delayed def finish(counts): return np.asanyarray(counts) return finish(result) finally: self.local._aggregator_nest_count -= 1 @delayed def finish(binners, *counts): if array_type == 'xarray': dims = [binner.expression for binner in binners] if expression_waslist: dims = ['expression'] + dims def to_coord(binner): if isinstance(binner, BinnerOrdinal): return self.category_labels(binner.expression) elif isinstance(binner, BinnerScalar): return self.bin_centers(binner.expression, [binner.minimum, binner.maximum], binner.count) coords = [to_coord(binner) for binner in binners] if expression_waslist: coords = [expressions] + coords counts = np.asanyarray(counts) else: counts = counts[0] return xarray.DataArray(counts, dims=dims, coords=coords) elif array_type == 'list': return vaex.utils.unlistify(expression_waslist, counts).tolist() elif array_type in [None, 'numpy']: def possibly_masked_array(ar): if isinstance(ar, (list, tuple)): has_mask = any(np.ma.isMaskedArray(k) for k in ar) else: has_mask = np.ma.isMaskedArray(ar) if has_mask: return np.ma.array(ar) else: return np.asanyarray(ar) return possibly_masked_array(vaex.utils.unlistify(expression_waslist, counts)) else: raise RuntimeError(f'Unknown array_type {format}') stats = [compute(expression, binners, selection=selection, edges=edges) for expression in expressions] var = finish(binners, *stats) return self._delay(delay, progressbar.exit_on(var)) @docsubst def count(self, expression=None, binby=[], limits=None, shape=default_shape, selection=False, delay=False, edges=False, progress=None, array_type=None): """Count the number of non-NaN values (or all, if expression is None or "*"). Example: >>> df.count() 330000 >>> df.count("*") 330000.0 >>> df.count("*", binby=["x"], shape=4) array([ 10925., 155427., 152007., 10748.]) :param expression: Expression or column for which to count non-missing values, or None or '*' for counting the rows :param binby: {binby} :param limits: {limits} :param shape: {shape} :param selection: {selection} :param delay: {delay} :param progress: {progress} :param edges: {edges} :param array_type: {array_type} :return: {return_stat_scalar} """ return self._compute_agg('count', expression, binby, limits, shape, selection, delay, edges, progress, array_type=array_type) @delayed def _first_calculation(self, expression, order_expression, binby, limits, shape, selection, edges, progressbar): if shape: limits, shapes = limits else: limits, shapes = limits, shape task = tasks.TaskStatistic(self, binby, shapes, limits, weights=[expression, order_expression], op=tasks.OP_FIRST, selection=selection, edges=edges) task = self.executor.schedule(task) progressbar.add_task(task, "count for %s" % expression) @delayed def finish(counts): counts = np.array(counts) return counts return finish(task) @docsubst def first(self, expression, order_expression=None, binby=[], limits=None, shape=default_shape, selection=False, delay=False, edges=False, progress=None, array_type=None): """Return the first element of a binned `expression`, where the values each bin are sorted by `order_expression`. Example: >>> import vaex >>> df = vaex.example() >>> df.first(df.x, df.y, shape=8) >>> df.first(df.x, df.y, shape=8, binby=[df.y]) >>> df.first(df.x, df.y, shape=8, binby=[df.y]) array([-4.81883764, 11.65378 , 9.70084476, -7.3025589 , 4.84954977, 8.47446537, -5.73602629, 10.18783 ]) :param expression: {expression} :param order_expression: Order the values in the bins by this expression. :param binby: {binby} :param limits: {limits} :param shape: {shape} :param selection: {selection} :param delay: {delay} :param progress: {progress} :param edges: {edges} :param array_type: {array_type} :return: Ndarray containing the first elements. :rtype: numpy.array """ return self._compute_agg('first', expression, binby, limits, shape, selection, delay, edges, progress, extra_expressions=[order_expression], array_type=array_type) logger.debug("count(%r, binby=%r, limits=%r)", expression, binby, limits) logger.debug("count(%r, binby=%r, limits=%r)", expression, binby, limits) expression = _ensure_strings_from_expressions(expression) order_expression = _ensure_string_from_expression(order_expression) binby = _ensure_strings_from_expressions(binby) waslist, [expressions,] = vaex.utils.listify(expression) @delayed def finish(*counts): counts = np.asarray(counts) return vaex.utils.unlistify(waslist, counts) progressbar = vaex.utils.progressbars(progress) limits = self.limits(binby, limits, delay=True, shape=shape) stats = [self._first_calculation(expression, order_expression, binby=binby, limits=limits, shape=shape, selection=selection, edges=edges, progressbar=progressbar) for expression in expressions] var = finish(*stats) return self._delay(delay, var) @docsubst def last(self, expression, order_expression=None, binby=[], limits=None, shape=default_shape, selection=False, delay=False, edges=False, progress=None, array_type=None): """Return the last element of a binned `expression`, where the values each bin are sorted by `order_expression`. :param expression: The value to be placed in the bin. :param order_expression: Order the values in the bins by this expression. :param binby: {binby} :param limits: {limits} :param shape: {shape} :param selection: {selection} :param delay: {delay} :param progress: {progress} :param edges: {edges} :param array_type: {array_type} :return: Ndarray containing the first elements. :rtype: numpy.array """ return self._compute_agg('last', expression, binby, limits, shape, selection, delay, edges, progress, extra_expressions=[order_expression], array_type=array_type) @docsubst @stat_1d def mean(self, expression, binby=[], limits=None, shape=default_shape, selection=False, delay=False, progress=None, edges=False, array_type=None): """Calculate the mean for expression, possibly on a grid defined by binby. Example: >>> df.mean("x") -0.067131491264005971 >>> df.mean("(x**2+y**2)**0.5", binby="E", shape=4) array([ 2.43483742, 4.41840721, 8.26742458, 15.53846476]) :param expression: {expression} :param binby: {binby} :param limits: {limits} :param shape: {shape} :param selection: {selection} :param delay: {delay} :param progress: {progress} :param array_type: {array_type} :return: {return_stat_scalar} """ return self._compute_agg('mean', expression, binby, limits, shape, selection, delay, edges, progress, array_type=array_type) logger.debug("mean of %r, with binby=%r, limits=%r, shape=%r, selection=%r, delay=%r", expression, binby, limits, shape, selection, delay) expression = _ensure_strings_from_expressions(expression) selection = _ensure_strings_from_expressions(selection) binby = _ensure_strings_from_expressions(binby) @delayed def calculate(expression, limits): task = tasks.TaskStatistic(self, binby, shape, limits, weight=expression, op=tasks.OP_ADD_WEIGHT_MOMENTS_01, selection=selection) task = self.executor.schedule(task) progressbar.add_task(task, "mean for %s" % expression) return task @delayed def finish(*stats_args): stats = np.array(stats_args) counts = stats[..., 0] with np.errstate(divide='ignore', invalid='ignore'): mean = stats[..., 1] / counts return vaex.utils.unlistify(waslist, mean) waslist, [expressions, ] = vaex.utils.listify(expression) progressbar = vaex.utils.progressbars(progress) limits = self.limits(binby, limits, delay=True) stats = [calculate(expression, limits) for expression in expressions] var = finish(*stats) return self._delay(delay, var) @delayed def _sum_calculation(self, expression, binby, limits, shape, selection, progressbar): task = tasks.TaskStatistic(self, binby, shape, limits, weight=expression, op=tasks.OP_ADD_WEIGHT_MOMENTS_01, selection=selection) task = self.executor.schedule(task) progressbar.add_task(task, "sum for %s" % expression) @delayed def finish(sum_grid): stats = np.array(sum_grid) return stats[...,1] return finish(task) @docsubst @stat_1d def sum(self, expression, binby=[], limits=None, shape=default_shape, selection=False, delay=False, progress=None, edges=False, array_type=None): """Calculate the sum for the given expression, possible on a grid defined by binby Example: >>> df.sum("L") 304054882.49378014 >>> df.sum("L", binby="E", shape=4) array([ 8.83517994e+06, 5.92217598e+07, 9.55218726e+07, 1.40008776e+08]) :param expression: {expression} :param binby: {binby} :param limits: {limits} :param shape: {shape} :param selection: {selection} :param delay: {delay} :param progress: {progress} :param array_type: {array_type} :return: {return_stat_scalar} """ return self._compute_agg('sum', expression, binby, limits, shape, selection, delay, edges, progress, array_type=array_type) @delayed def finish(*sums): return vaex.utils.unlistify(waslist, sums) expression = _ensure_strings_from_expressions(expression) binby = _ensure_strings_from_expressions(binby) waslist, [expressions, ] = vaex.utils.listify(expression) progressbar = vaex.utils.progressbars(progress) limits = self.limits(binby, limits, delay=True) # stats = [calculate(expression, limits) for expression in expressions] sums = [self._sum_calculation(expression, binby=binby, limits=limits, shape=shape, selection=selection, progressbar=progressbar) for expression in expressions] s = finish(*sums) return self._delay(delay, s) @docsubst @stat_1d def std(self, expression, binby=[], limits=None, shape=default_shape, selection=False, delay=False, progress=None, array_type=None): """Calculate the standard deviation for the given expression, possible on a grid defined by binby >>> df.std("vz") 110.31773397535071 >>> df.std("vz", binby=["(x**2+y**2)**0.5"], shape=4) array([ 123.57954851, 85.35190177, 61.14345748, 38.0740619 ]) :param expression: {expression} :param binby: {binby} :param limits: {limits} :param shape: {shape} :param selection: {selection} :param delay: {delay} :param progress: {progress} :param array_type: {array_type} :return: {return_stat_scalar} """ @delayed def finish(var): return var**0.5 return self._delay(delay, finish(self.var(expression, binby=binby, limits=limits, shape=shape, selection=selection, delay=True, progress=progress))) @docsubst @stat_1d def var(self, expression, binby=[], limits=None, shape=default_shape, selection=False, delay=False, progress=None, array_type=None): """Calculate the sample variance for the given expression, possible on a grid defined by binby Example: >>> df.var("vz") 12170.002429456246 >>> df.var("vz", binby=["(x**2+y**2)**0.5"], shape=4) array([ 15271.90481083, 7284.94713504, 3738.52239232, 1449.63418988]) >>> df.var("vz", binby=["(x**2+y**2)**0.5"], shape=4)**0.5 array([ 123.57954851, 85.35190177, 61.14345748, 38.0740619 ]) :param expression: {expression} :param binby: {binby} :param limits: {limits} :param shape: {shape} :param selection: {selection} :param delay: {delay} :param progress: {progress} :param array_type: {array_type} :return: {return_stat_scalar} """ edges = False return self._compute_agg('var', expression, binby, limits, shape, selection, delay, edges, progress, array_type=array_type) @docsubst def skew(self, expression, binby=[], limits=None, shape=default_shape, selection=False, delay=False, progress=None, edges=False, array_type=None): ''' Calculate the skew for the given expression, possible on a grid defined by binby. Example: >>> df.skew("vz") 0.02116528 >>> df.skew("vz", binby=["E"], shape=4) array([-0.069976 , -0.01003445, 0.05624177, -2.2444322 ]) :param expression: {expression} :param binby: {binby} :param limits: {limits} :param shape: {shape} :param selection: {selection} :param delay: {delay} :param progress: {progress} :param array_type: {array_type} :return: {return_stat_scalar} ''' edges=False return self._compute_agg('skew', expression, binby, limits, shape, selection, delay, edges, progress, array_type=array_type) @docsubst def kurtosis(self, expression, binby=[], limits=None, shape=default_shape, selection=False, delay=False, progress=None, edges=False, array_type=None): ''' Calculate the kurtosis for the given expression, possible on a grid defined by binby. Example: >>> df.kurtosis('vz') 0.33414303 >>> df.kurtosis("vz", binby=["E"], shape=4) array([0.35286113, 0.14455428, 0.52955107, 5.06716345]) :param expression: {expression} :param binby: {binby} :param limits: {limits} :param shape: {shape} :param selection: {selection} :param delay: {delay} :param progress: {progress} :param array_type: {array_type} :return: {return_stat_scalar} ''' edges=False return self._compute_agg('kurtosis', expression, binby, limits, shape, selection, delay, edges, progress, array_type=array_type) @docsubst def covar(self, x, y, binby=[], limits=None, shape=default_shape, selection=False, delay=False, progress=None): """Calculate the covariance cov[x,y] between x and y, possibly on a grid defined by binby. Example: >>> df.covar("x**2+y**2+z**2", "-log(-E+1)") array(52.69461456005138) >>> df.covar("x**2+y**2+z**2", "-log(-E+1)")/(df.std("x**2+y**2+z**2") * df.std("-log(-E+1)")) 0.63666373822156686 >>> df.covar("x**2+y**2+z**2", "-log(-E+1)", binby="Lz", shape=4) array([ 10.17387143, 51.94954078, 51.24902796, 20.2163929 ]) :param x: {expression} :param y: {expression} :param binby: {binby} :param limits: {limits} :param shape: {shape} :param selection: {selection} :param delay: {delay} :param progress: {progress} :return: {return_stat_scalar} """ @delayed def cov(mean_x, mean_y, mean_xy): return mean_xy - mean_x * mean_y waslist, [xlist, ylist] = vaex.utils.listify(x, y) # print("limits", limits) limits = self.limits(binby, limits, selection=selection, delay=True) # print("limits", limits) @delayed def calculate(limits): results = [] for x, y in zip(xlist, ylist): mx = self.mean(x, binby=binby, limits=limits, shape=shape, selection=selection, delay=True, progress=progressbar) my = self.mean(y, binby=binby, limits=limits, shape=shape, selection=selection, delay=True, progress=progressbar) cxy = self.mean("(%s)*(%s)" % (x, y), binby=binby, limits=limits, shape=shape, selection=selection, delay=True, progress=progressbar) results.append(cov(mx, my, cxy)) return results progressbar = vaex.utils.progressbars(progress, title="covar") covars = calculate(limits) @delayed def finish(covars): value = np.array(vaex.utils.unlistify(waslist, covars)) return value return self._delay(delay, finish(delayed_list(covars))) @docsubst def correlation(self, x, y=None, binby=[], limits=None, shape=default_shape, sort=False, sort_key=np.abs, selection=False, delay=False, progress=None, array_type=None): """Calculate the correlation coefficient cov[x,y]/(std[x]*std[y]) between x and y, possibly on a grid defined by binby. The `x` and `y` arguments can be single expressions of lists of expressions. - If `x` and `y` are single expression, it computes the correlation between `x` and `y`; - If `x` is a list of expressions and `y` is a single expression, it computes the correlation between each expression in `x` and the expression in `y`; - If `x` is a list of expressions and `y` is None, it computes the correlation matrix amongst all expressions in `x`; - If `x` is a list of tuples of length 2, it computes the correlation for the specified dimension pairs; - If `x` and `y` are lists of expressions, it computes the correlation matrix defined by the two expression lists. Example: >>> import vaex >>> df = vaex.example() >>> df.correlation("x**2+y**2+z**2", "-log(-E+1)") array(0.6366637382215669) >>> df.correlation("x**2+y**2+z**2", "-log(-E+1)", binby="Lz", shape=4) array([ 0.40594394, 0.69868851, 0.61394099, 0.65266318]) >>> df.correlation(x=['x', 'y', 'z']) array([[ 1. , -0.06668907, -0.02709719], [-0.06668907, 1. , 0.03450365], [-0.02709719, 0.03450365, 1. ]]) >>> df.correlation(x=['x', 'y', 'z'], y=['E', 'Lz']) array([[-0.01116315, -0.00369268], [-0.0059848 , 0.02472491], [ 0.01428211, -0.05900035]]) :param x: {expression} :param y: {expression} :param binby: {binby} :param limits: {limits} :param shape: {shape} :param selection: {selection} :param delay: {delay} :param progress: {progress} :return: {return_stat_scalar} """ selection = _normalize_selection(selection) progressbar = vaex.utils.progressbars(progress, title="correlation") if y is None: if not _issequence(x): raise ValueError("if y not given, x is expected to be a list or tuple, not %r" % x) if all([_issequence(k) and len(k) == 2 for k in x]): values = [] pairs = x x = [] y = [] for col1, col2 in pairs: x.append(col1) y.append(col2) values.append(self.correlation(col1, col2, delay=True, progress=progressbar)) @vaex.delayed def finish(values): return vaex.from_arrays(x=x, y=y, correlation=values) result = finish(values) else: result = self._correlation_matrix(x, binby=binby, limits=limits, shape=shape, selection=selection, delay=True, progress=progressbar, array_type=array_type) elif _issequence(x) and _issequence(y): result = delayed(np.array)([[self.correlation(x_, y_, binby=binby, limits=limits, shape=shape, selection=selection, delay=True, progress=progressbar) for y_ in y] for x_ in x]) elif _issequence(x): combinations = [(k, y) for k in x] result = delayed(np.array)([self.correlation(x_, y, binby=binby, limits=limits, shape=shape, selection=selection, delay=True, progress=progressbar)for x_ in x]) elif _issequence(y): combinations = [(x, k) for k in y] result = self.correlation(combinations, binby=binby, limits=limits, shape=shape, selection=selection, delay=True, progress=progressbar) else: @vaex.delayed def finish(matrix): return matrix[...,0,1] matrix = self._correlation_matrix([x, y], binby=binby, limits=limits, shape=shape, selection=selection, delay=True, progress=progressbar) result = finish(matrix) return self._delay(delay, result) @docsubst def _correlation_matrix(self, column_names=None, binby=[], limits=None, shape=default_shape, selection=False, delay=False, progress=None, array_type=None): if column_names is None: column_names = self.get_column_names() @delayed def normalize(cov_matrix): norm = cov_matrix[:] diag = np.diagonal(cov_matrix, axis1=-2, axis2=-1) # generalized outer product norm = (diag[...,np.newaxis,:] * diag[...,np.newaxis]) ** 0.5 # norm = np.outer(diag, diag)**0.5 return cov_matrix/norm result = normalize(self.cov(column_names, binby=binby, limits=limits, shape=shape, selection=selection, delay=True, progress=progress)) @vaex.delayed def finish(array): if array_type == 'xarray': dims = binby + ['x', 'y'] coords = [column_names, column_names] return xarray.DataArray(array, dims=dims, coords=coords) else: return vaex.array_types.convert(array, array_type) return self._delay(delay, finish(result)) @docsubst def cov(self, x, y=None, binby=[], limits=None, shape=default_shape, selection=False, delay=False, progress=None): """Calculate the covariance matrix for x and y or more expressions, possibly on a grid defined by binby. Either x and y are expressions, e.g.: >>> df.cov("x", "y") Or only the x argument is given with a list of expressions, e.g.: >>> df.cov(["x, "y, "z"]) Example: >>> df.cov("x", "y") array([[ 53.54521742, -3.8123135 ], [ -3.8123135 , 60.62257881]]) >>> df.cov(["x", "y", "z"]) array([[ 53.54521742, -3.8123135 , -0.98260511], [ -3.8123135 , 60.62257881, 1.21381057], [ -0.98260511, 1.21381057, 25.55517638]]) >>> df.cov("x", "y", binby="E", shape=2) array([[[ 9.74852878e+00, -3.02004780e-02], [ -3.02004780e-02, 9.99288215e+00]], [[ 8.43996546e+01, -6.51984181e+00], [ -6.51984181e+00, 9.68938284e+01]]]) :param x: {expression} :param y: {expression_single} :param binby: {binby} :param limits: {limits} :param shape: {shape} :param selection: {selection} :param delay: {delay} :return: {return_stat_scalar}, the last dimensions are of shape (2,2) """ selection = _ensure_strings_from_expressions(selection) selection = _normalize_selection(selection) if y is None: if not _issequence(x): raise ValueError("if y argument is not given, x is expected to be sequence, not %r", x) expressions = x else: expressions = [x, y] expressions = _ensure_strings_from_expressions(expressions) N = len(expressions) binby = _ensure_list(binby) shape = _expand_shape(shape, len(binby)) limits = self.limits(binby, limits, selection=selection, delay=True) @delayed def calculate(expressions, limits): # print('limits', limits) task = tasks.TaskStatistic(self, binby, shape, limits, weights=expressions, op=tasks.OP_COV, selection=selection) task = self.executor.schedule(task) progressbar.add_task(task, "covariance values for %r" % expressions) return task @delayed def finish(values): N = len(expressions) counts = values[..., :N] sums = values[..., N:2 * N] with np.errstate(divide='ignore', invalid='ignore'): means = sums / counts # matrix of means * means.T meansxy = means[..., None] * means[..., None, :] counts = values[..., 2 * N:2 * N + N**2] sums = values[..., 2 * N + N**2:] shape = counts.shape[:-1] + (N, N) counts = counts.reshape(shape) sums = sums.reshape(shape) with np.errstate(divide='ignore', invalid='ignore'): moments2 = sums / counts cov_matrix = moments2 - meansxy return cov_matrix progressbar = vaex.utils.progressbars(progress, title="cov") values = calculate(expressions, limits) cov_matrix = finish(values) return self._delay(delay, cov_matrix) @docsubst @stat_1d def minmax(self, expression, binby=[], limits=None, shape=default_shape, selection=False, delay=False, progress=None): """Calculate the minimum and maximum for expressions, possibly on a grid defined by binby. Example: >>> df.minmax("x") array([-128.293991, 271.365997]) >>> df.minmax(["x", "y"]) array([[-128.293991 , 271.365997 ], [ -71.5523682, 146.465836 ]]) >>> df.minmax("x", binby="x", shape=5, limits=[-10, 10]) array([[-9.99919128, -6.00010443], [-5.99972439, -2.00002384], [-1.99991322, 1.99998057], [ 2.0000093 , 5.99983597], [ 6.0004878 , 9.99984646]]) :param expression: {expression} :param binby: {binby} :param limits: {limits} :param shape: {shape} :param selection: {selection} :param delay: {delay} :param progress: {progress} :return: {return_stat_scalar}, the last dimension is of shape (2) """ # vmin = self._compute_agg('min', expression, binby, limits, shape, selection, delay, edges, progress) # vmax = self._compute_agg('max', expression, binby, limits, shape, selection, delay, edges, progress) selection = _ensure_strings_from_expressions(selection) selection = _normalize_selection(selection) @delayed def calculate(expression, limits): task = tasks.TaskStatistic(self, binby, shape, limits, weight=expression, op=tasks.OP_MIN_MAX, selection=selection) task = self.executor.schedule(task) progressbar.add_task(task, "minmax for %s" % expression) return task @delayed def finish(*minmax_list): value = vaex.utils.unlistify(waslist, np.array(minmax_list)) value = vaex.array_types.to_numpy(value) value = value.astype(data_type0.numpy) return value expression = _ensure_strings_from_expressions(expression) binby = _ensure_strings_from_expressions(binby) waslist, [expressions, ] = vaex.utils.listify(expression) column_names = self.get_column_names(hidden=True) expressions = [vaex.utils.valid_expression(column_names, k) for k in expressions] data_types = [self.data_type(expr) for expr in expressions] data_type0 = data_types[0] # special case that we supported mixed endianness for ndarrays all_same_kind = all(isinstance(data_type.internal, np.dtype) for data_type in data_types) and all([k.kind == data_type0.kind for k in data_types]) if not (all_same_kind or all([k == data_type0 for k in data_types])): raise TypeError("cannot mix different dtypes in 1 minmax call") progressbar = vaex.utils.progressbars(progress, title="minmaxes") limits = self.limits(binby, limits, selection=selection, delay=True) all_tasks = [calculate(expression, limits) for expression in expressions] result = finish(*all_tasks) return self._delay(delay, result) @docsubst @stat_1d def min(self, expression, binby=[], limits=None, shape=default_shape, selection=False, delay=False, progress=None, edges=False, array_type=None): """Calculate the minimum for given expressions, possibly on a grid defined by binby. Example: >>> df.min("x") array(-128.293991) >>> df.min(["x", "y"]) array([-128.293991 , -71.5523682]) >>> df.min("x", binby="x", shape=5, limits=[-10, 10]) array([-9.99919128, -5.99972439, -1.99991322, 2.0000093 , 6.0004878 ]) :param expression: {expression} :param binby: {binby} :param limits: {limits} :param shape: {shape} :param selection: {selection} :param delay: {delay} :param progress: {progress} :param array_type: {array_type} :return: {return_stat_scalar}, the last dimension is of shape (2) """ return self._compute_agg('min', expression, binby, limits, shape, selection, delay, edges, progress, array_type=array_type) @delayed def finish(result): return result[..., 0] return self._delay(delay, finish(self.minmax(expression, binby=binby, limits=limits, shape=shape, selection=selection, delay=delay, progress=progress))) @docsubst @stat_1d def max(self, expression, binby=[], limits=None, shape=default_shape, selection=False, delay=False, progress=None, edges=False, array_type=None): """Calculate the maximum for given expressions, possibly on a grid defined by binby. Example: >>> df.max("x") array(271.365997) >>> df.max(["x", "y"]) array([ 271.365997, 146.465836]) >>> df.max("x", binby="x", shape=5, limits=[-10, 10]) array([-6.00010443, -2.00002384, 1.99998057, 5.99983597, 9.99984646]) :param expression: {expression} :param binby: {binby} :param limits: {limits} :param shape: {shape} :param selection: {selection} :param delay: {delay} :param progress: {progress} :param array_type: {array_type} :return: {return_stat_scalar}, the last dimension is of shape (2) """ return self._compute_agg('max', expression, binby, limits, shape, selection, delay, edges, progress, array_type=array_type) @delayed def finish(result): return result[..., 1] return self._delay(delay, finish(self.minmax(expression, binby=binby, limits=limits, shape=shape, selection=selection, delay=delay, progress=progress))) @docsubst @stat_1d def median_approx(self, expression, percentage=50., binby=[], limits=None, shape=default_shape, percentile_shape=256, percentile_limits="minmax", selection=False, delay=False, progress=None): """Calculate the median, possibly on a grid defined by binby. NOTE: this value is approximated by calculating the cumulative distribution on a grid defined by percentile_shape and percentile_limits :param expression: {expression} :param binby: {binby} :param limits: {limits} :param shape: {shape} :param percentile_limits: {percentile_limits} :param percentile_shape: {percentile_shape} :param selection: {selection} :param delay: {delay} :param progress: {progress} :return: {return_stat_scalar} """ return self.percentile_approx(expression, 50, binby=binby, limits=limits, shape=shape, percentile_shape=percentile_shape, percentile_limits=percentile_limits, selection=selection, delay=delay, progress=progress) @docsubst def percentile_approx(self, expression, percentage=50., binby=[], limits=None, shape=default_shape, percentile_shape=1024, percentile_limits="minmax", selection=False, delay=False, progress=None): """Calculate the percentile given by percentage, possibly on a grid defined by binby. NOTE: this value is approximated by calculating the cumulative distribution on a grid defined by percentile_shape and percentile_limits. Example: >>> df.percentile_approx("x", 10), df.percentile_approx("x", 90) (array([-8.3220355]), array([ 7.92080358])) >>> df.percentile_approx("x", 50, binby="x", shape=5, limits=[-10, 10]) array([[-7.56462982], [-3.61036641], [-0.01296306], [ 3.56697863], [ 7.45838367]]) :param expression: {expression} :param binby: {binby} :param limits: {limits} :param shape: {shape} :param percentile_limits: {percentile_limits} :param percentile_shape: {percentile_shape} :param selection: {selection} :param delay: {delay} :param progress: {progress} :return: {return_stat_scalar} """ waslist, [expressions, ] = vaex.utils.listify(expression) if not isinstance(binby, (tuple, list)): binby = [binby] else: binby = binby @delayed def calculate(expression, shape, limits): # task = TaskStatistic(self, [expression] + binby, shape, limits, op=OP_ADD1, selection=selection) # self.executor.schedule(task) # return task return self.count(binby=list(binby) + [expression], shape=shape, limits=limits, selection=selection, delay=True, edges=True, progress=progress) @delayed def finish(percentile_limits, counts_list): results = [] for i, counts in enumerate(counts_list): counts = counts.astype(np.float64) # remove the nan and boundary edges from the first dimension, nonnans = list([slice(2, -1, None) for k in range(len(counts.shape) - 1)]) nonnans.append(slice(1, None, None)) # we're gonna get rid only of the nan's, and keep the overflow edges nonnans = tuple(nonnans) cumulative_grid = np.cumsum(counts.__getitem__(nonnans), -1) # convert to cumulative grid totalcounts = np.sum(counts.__getitem__(nonnans), -1) empty = totalcounts == 0 original_shape = counts.shape shape = cumulative_grid.shape # + (original_shape[-1] - 1,) # counts = np.sum(counts, -1) edges_floor = np.zeros(shape[:-1] + (2,), dtype=np.int64) edges_ceil = np.zeros(shape[:-1] + (2,), dtype=np.int64) # if we have an off # of elements, say, N=3, the center is at i=1=(N-1)/2 # if we have an even # of elements, say, N=4, the center is between i=1=(N-2)/2 and i=2=(N/2) # index = (shape[-1] -1-3) * percentage/100. # the -3 is for the edges waslist_percentage, [percentages, ] = vaex.utils.listify(percentage) percentiles = [] for p in percentages: if p == 0: percentiles.append(percentile_limits[i][0]) continue if p == 100: percentiles.append(percentile_limits[i][1]) continue values = np.array((totalcounts + 1) * p / 100.) # make sure it's an ndarray values[empty] = 0 floor_values = np.array(np.floor(values)) ceil_values = np.array(np.ceil(values)) vaex.vaexfast.grid_find_edges(cumulative_grid, floor_values, edges_floor) vaex.vaexfast.grid_find_edges(cumulative_grid, ceil_values, edges_ceil) def index_choose(a, indices): # alternative to np.choise, which doesn't like the last dim to be >= 32 # print(a, indices) out = np.zeros(a.shape[:-1]) # print(out.shape) for i in np.ndindex(out.shape): # print(i, indices[i]) out[i] = a[i + (indices[i],)] return out def calculate_x(edges, values): left, right = edges[..., 0], edges[..., 1] left_value = index_choose(cumulative_grid, left) right_value = index_choose(cumulative_grid, right) with np.errstate(divide='ignore', invalid='ignore'): u = np.array((values - left_value) / (right_value - left_value)) # TODO: should it really be -3? not -2 xleft, xright = percentile_limits[i][0] + (left - 0.5) * (percentile_limits[i][1] - percentile_limits[i][0]) / (shape[-1] - 3),\ percentile_limits[i][0] + (right - 0.5) * (percentile_limits[i][1] - percentile_limits[i][0]) / (shape[-1] - 3) x = xleft + (xright - xleft) * u # /2 return x x1 = calculate_x(edges_floor, floor_values) x2 = calculate_x(edges_ceil, ceil_values) u = values - floor_values x = x1 + (x2 - x1) * u percentiles.append(x) percentile = vaex.utils.unlistify(waslist_percentage, np.array(percentiles)) results.append(percentile) return results shape = _expand_shape(shape, len(binby)) percentile_shapes = _expand_shape(percentile_shape, len(expressions)) if percentile_limits: percentile_limits = _expand_limits(percentile_limits, len(expressions)) limits = self.limits(binby, limits, selection=selection, delay=True) percentile_limits = self.limits(expressions, percentile_limits, selection=selection, delay=True) @delayed def calculation(limits, percentile_limits): # print(">>>", expressions, percentile_limits) # print(percentile_limits[0], list(percentile_limits[0])) # print(list(np.array(limits).tolist()) + list(percentile_limits[0])) # print("limits", limits, expressions, percentile_limits, ">>", list(limits) + [list(percentile_limits[0])) tasks = [calculate(expression, tuple(shape) + (percentile_shape, ), list(limits) + [list(percentile_limit)]) for percentile_shape, percentile_limit, expression in zip(percentile_shapes, percentile_limits, expressions)] return finish(percentile_limits, delayed_args(*tasks)) # return tasks result = calculation(limits, percentile_limits) @delayed def finish2(grid): value = vaex.utils.unlistify(waslist, np.array(grid)) return value return self._delay(delay, finish2(result)) def _use_delay(self, delay): return delay == True def _delay(self, delay, task, progressbar=False): if task.isRejected: task.get() if delay: return task else: self.execute() return task.get() @docsubst def limits_percentage(self, expression, percentage=99.73, square=False, selection=False, progress=None, delay=False): """Calculate the [min, max] range for expression, containing approximately a percentage of the data as defined by percentage. The range is symmetric around the median, i.e., for a percentage of 90, this gives the same results as: Example: >>> df.limits_percentage("x", 90) array([-12.35081376, 12.14858052] >>> df.percentile_approx("x", 5), df.percentile_approx("x", 95) (array([-12.36813152]), array([ 12.13275818])) NOTE: this value is approximated by calculating the cumulative distribution on a grid. NOTE 2: The values above are not exactly the same, since percentile and limits_percentage do not share the same code :param expression: {expression_limits} :param float percentage: Value between 0 and 100 :param progress: {progress} :param delay: {delay} :return: {return_limits} """ logger.info("limits_percentage for %r, with percentage=%r", expression, percentage) progressbar = vaex.utils.progressbars(progress, title="limits_percentage") waslist, [expressions, ] = vaex.utils.listify(expression) limits = [] for expr in expressions: @delayed def compute(limits_minmax, expr=expr): @delayed def compute_limits(counts): cumcounts = np.concatenate([[0], np.cumsum(counts)]) cumcounts = cumcounts / cumcounts.max() # TODO: this is crude.. see the details! f = (1 - percentage / 100.) / 2 x = np.linspace(vmin, vmax, size + 1) l = np.interp([f, 1 - f], cumcounts, x) return l vmin, vmax = limits_minmax size = 1024 * 16 counts = self.count(binby=expr, shape=size, limits=limits_minmax, selection=selection, progress=progressbar, delay=delay) return compute_limits(counts) # limits.append(l) limits_minmax = self.minmax(expr, selection=selection, delay=delay) limits1 = compute(limits_minmax=limits_minmax) limits.append(limits1) return self._delay(delay, progressbar.exit_on(delayed(vaex.utils.unlistify)(waslist, limits))) @docsubst def limits(self, expression, value=None, square=False, selection=None, delay=False, progress=None, shape=None): """Calculate the [min, max] range for expression, as described by value, which is 'minmax' by default. If value is a list of the form [minvalue, maxvalue], it is simply returned, this is for convenience when using mixed forms. Example: >>> import vaex >>> df = vaex.example() >>> df.limits("x") array([-128.293991, 271.365997]) >>> df.limits("x", "99.7%") array([-28.86381927, 28.9261226 ]) >>> df.limits(["x", "y"]) (array([-128.293991, 271.365997]), array([ -71.5523682, 146.465836 ])) >>> df.limits(["x", "y"], "99.7%") (array([-28.86381927, 28.9261226 ]), array([-28.60476934, 28.96535249])) >>> df.limits(["x", "y"], ["minmax", "90%"]) (array([-128.293991, 271.365997]), array([-13.37438402, 13.4224423 ])) >>> df.limits(["x", "y"], ["minmax", [0, 10]]) (array([-128.293991, 271.365997]), [0, 10]) :param expression: {expression_limits} :param value: {limits} :param selection: {selection} :param delay: {delay} :param progress: {progress} :return: {return_limits} """ if expression == []: return [] if shape is None else ([], []) waslist, [expressions, ] = vaex.utils.listify(expression) expressions = _ensure_strings_from_expressions(expressions) selection = _ensure_strings_from_expressions(selection) if value is None: value = "minmax" if _is_limit(value) or not _issequence(value): values = (value,) * len(expressions) else: values = value # we cannot hash arrow arrays values = [vaex.array_types.to_numpy(k) if isinstance(k, vaex.array_types.supported_arrow_array_types) else k for k in values] progressbar = vaex.utils.progressbars(progress, title="limits") initial_expressions, initial_values = expressions, values expression_values = dict() expression_shapes = dict() for i, (expression, value) in enumerate(zip(expressions, values)): if _issequence(expression): expressions = expression nested = True else: expressions = [expression] nested = False if _is_limit(value) or not _issequence(value): values = (value,) * len(expressions) else: values = value for j, (expression, value) in enumerate(zip(expressions, values)): if shape is not None: if _issequence(shape): shapes = shape else: shapes = (shape, ) * (len(expressions) if nested else len(initial_expressions)) shape_index = j if nested else i if not _is_limit(value): expression_values[(expression, value)] = None if self.is_category(expression): N = self._categories[_ensure_string_from_expression(expression)]['N'] expression_shapes[expression] = min(N, shapes[shape_index] if shape is not None else default_shape) else: expression_shapes[expression] = shapes[shape_index] if shape is not None else default_shape limits_list = [] for expression, value in expression_values.keys(): if self.is_category(expression): N = self._categories[_ensure_string_from_expression(expression)]['N'] limits = [-0.5, N-0.5] else: if isinstance(value, six.string_types): if value == "minmax": limits = self.minmax(expression, selection=selection, progress=progressbar, delay=True) else: match = re.match(r"([\d.]*)(\D*)", value) if match is None: raise ValueError("do not understand limit specifier %r, examples are 90%, 3sigma") else: number, type = match.groups() import ast number = ast.literal_eval(number) type = type.strip() if type in ["s", "sigma"]: limits = self.limits_sigma(number) elif type in ["ss", "sigmasquare"]: limits = self.limits_sigma(number, square=True) elif type in ["%", "percent"]: limits = self.limits_percentage(expression, number, selection=selection, delay=True, progress=progressbar) elif type in ["%s", "%square", "percentsquare"]: limits = self.limits_percentage(expression, number, selection=selection, square=True, delay=True) elif value is None: limits = self.minmax(expression, selection=selection, delay=True) else: limits = value limits_list.append(limits) if limits is None: raise ValueError("limit %r not understood" % value) expression_values[(expression, value)] = limits limits_list = delayed_args(*limits_list) @delayed def finish(limits_list): # print("##### 2)", expression_values.keys()) limits_outer = [] shapes_list = [] for expression, value in zip(initial_expressions, initial_values): if _issequence(expression): expressions = expression waslist2 = True else: expressions = [expression] waslist2 = False if _is_limit(value) or not _issequence(value): values = (value,) * len(expressions) else: values = value # print("expressions 3)", expressions) # print("values 3)", values) limits = [] shapes = [] for expression, value in zip(expressions, values): if not _is_limit(value): value = expression_values[(expression, value)] if not _is_limit(value): # print(">>> value", value) value = value.get() limits.append(value) shapes.append(expression_shapes[expression]) # if not _is_limit(value): # if a # #value = tuple(value) # list is not hashable # expression_values[(expression, value)] = expression_values[(expression, value)].get() # else: # #value = tuple(value) # list is not hashable # expression_values[(expression, value)] = () if waslist2: limits_outer.append(limits) shapes_list.append(shapes) else: limits_outer.append(limits[0]) shapes_list.append(shapes[0]) # logger.debug(">>>>>>>> complete list of limits: %r %r", limits_list, np.array(limits_list).shape) # print("limits", limits_outer) if shape: return vaex.utils.unlistify(waslist, limits_outer), vaex.utils.unlistify(waslist, shapes_list) else: return vaex.utils.unlistify(waslist, limits_outer) return self._delay(delay, progressbar.exit_on(finish(limits_list))) def mode(self, expression, binby=[], limits=None, shape=256, mode_shape=64, mode_limits=None, progressbar=False, selection=None): """Calculate/estimate the mode.""" if len(binby) == 0: raise ValueError("only supported with binby argument given") else: # todo, fix progressbar into two... try: len(shape) shape = tuple(shape) except: shape = len(binby) * (shape,) shape = (mode_shape,) + shape subspace = self(*(list(binby) + [expression])) if selection: subspace = subspace.selected() limits = self.limits(list(binby), limits) mode_limits = self.limits([expression], mode_limits) limits = list(limits) + list(mode_limits) counts = subspace.histogram(limits=limits, size=shape, progressbar=progressbar) indices = np.argmax(counts, axis=0) pmin, pmax = limits[-1] centers = np.linspace(pmin, pmax, mode_shape + 1)[:-1] # ignore last bin centers += (centers[1] - centers[0]) / 2 # and move half a bin to the right modes = centers[indices] ok = counts.sum(axis=0) > 0 modes[~ok] = np.nan return modes @vaex.utils.deprecated('use df.widget.heatmap') def plot_widget(self, x, y, limits=None, f="identity", **kwargs): return self.widget.heatmap(x, y, limits=limits, transform=f, **kwargs) @vaex.utils.deprecated('use plot_widget') def plot_bq(self, x, y, grid=None, shape=256, limits=None, what="count(*)", figsize=None, f="identity", figure_key=None, fig=None, axes=None, xlabel=None, ylabel=None, title=None, show=True, selection=[None, True], colormap="afmhot", grid_limits=None, normalize="normalize", grid_before=None, what_kwargs={}, type="default", scales=None, tool_select=False, bq_cleanup=True, **kwargs): import vaex.ext.bqplot cls = vaex.ext.bqplot.get_class(type) plot2d = cls(df=self, x=x, y=y, grid=grid, shape=shape, limits=limits, what=what, f=f, figure_key=figure_key, fig=fig, selection=selection, grid_before=grid_before, grid_limits=grid_limits, normalize=normalize, colormap=colormap, what_kwargs=what_kwargs, **kwargs) if show: plot2d.show() return plot2d # @_hidden def healpix_count(self, expression=None, healpix_expression=None, healpix_max_level=12, healpix_level=8, binby=None, limits=None, shape=default_shape, delay=False, progress=None, selection=None): """Count non missing value for expression on an array which represents healpix data. :param expression: Expression or column for which to count non-missing values, or None or '*' for counting the rows :param healpix_expression: {healpix_max_level} :param healpix_max_level: {healpix_max_level} :param healpix_level: {healpix_level} :param binby: {binby}, these dimension follow the first healpix dimension. :param limits: {limits} :param shape: {shape} :param selection: {selection} :param delay: {delay} :param progress: {progress} :return: """ # if binby is None: import healpy as hp if healpix_expression is None: if self.ucds.get("source_id", None) == 'meta.id;meta.main': # we now assume we have gaia data healpix_expression = "source_id/34359738368" if healpix_expression is None: raise ValueError("no healpix_expression given, and was unable to guess") reduce_level = healpix_max_level - healpix_level NSIDE = 2**healpix_level nmax = hp.nside2npix(NSIDE) scaling = 4**reduce_level expr = "%s/%s" % (healpix_expression, scaling) binby = [expr] + ([] if binby is None else _ensure_list(binby)) shape = (nmax,) + _expand_shape(shape, len(binby) - 1) epsilon = 1. / scaling / 2 limits = [[-epsilon, nmax - epsilon]] + ([] if limits is None else limits) return self.count(expression, binby=binby, limits=limits, shape=shape, delay=delay, progress=progress, selection=selection) @docsubst @stat_1d def _stat(self, what="count(*)", what_kwargs={}, binby=[], limits=None, shape=default_shape, selection=False, delay=False, progress=None): waslist_what, [whats, ] = vaex.utils.listify(what) limits = self.limits(binby, limits, delay=True) waslist_selection, [selections] = vaex.utils.listify(selection) binby = _ensure_list(binby) what_labels = [] shape = _expand_shape(shape, len(binby)) total_grid = np.zeros((len(whats), len(selections)) + shape, dtype=float) @delayed def copy_grids(grids): total_grid[index] = grid @delayed def get_whats(limits): grids = [] for j, what in enumerate(whats): what = what.strip() index = what.index("(") groups = re.match(r"(.*)\((.*)\)", what).groups() if groups and len(groups) == 2: function = groups[0] arguments = groups[1].strip() if "," in arguments: arguments = arguments.split(",") functions = ["mean", "sum", "std", "var", "correlation", "covar", "min", "max"] unit_expression = None if function in ["mean", "sum", "std", "min", "max"]: unit_expression = arguments if function in ["var"]: unit_expression = "(%s) * (%s)" % (arguments, arguments) if function in ["covar"]: unit_expression = "(%s) * (%s)" % arguments if unit_expression: unit = self.unit(unit_expression) if unit: what_units = unit.to_string('latex_inline') if function in functions: grid = getattr(self, function)(arguments, binby=binby, limits=limits, shape=shape, selection=selections, progress=progress, delay=delay) elif function == "count": grid = self.count(arguments, binby, shape=shape, limits=limits, selection=selections, progress=progress, delay=delay) else: raise ValueError("Could not understand method: %s, expected one of %r'" % (function, functions)) # what_labels.append(what_label) grids.append(grid) # else: # raise ValueError("Could not understand 'what' argument %r, expected something in form: 'count(*)', 'mean(x)'" % what) return grids grids = get_whats(limits) # print grids # grids = delayed_args(*grids) @delayed def finish(grids): for i, grid in enumerate(grids): total_grid[i] = grid return total_grid[slice(None, None, None) if waslist_what else 0, slice(None, None, None) if waslist_selection else 0] s = finish(delayed_list(grids)) return self._delay(delay, s) plot = _requires('viz') plot1d = _requires('viz') scatter = _requires('viz') def plot3d(self, x, y, z, vx=None, vy=None, vz=None, vwhat=None, limits=None, grid=None, what="count(*)", shape=128, selection=[None, True], f=None, vcount_limits=None, smooth_pre=None, smooth_post=None, grid_limits=None, normalize="normalize", colormap="afmhot", figure_key=None, fig=None, lighting=True, level=[0.1, 0.5, 0.9], opacity=[0.01, 0.05, 0.1], level_width=0.1, show=True, **kwargs): """Use at own risk, requires ipyvolume""" import vaex.ext.ipyvolume # vaex.ext.ipyvolume. cls = vaex.ext.ipyvolume.PlotDefault plot3d = cls(df=self, x=x, y=y, z=z, vx=vx, vy=vy, vz=vz, grid=grid, shape=shape, limits=limits, what=what, f=f, figure_key=figure_key, fig=fig, selection=selection, smooth_pre=smooth_pre, smooth_post=smooth_post, grid_limits=grid_limits, vcount_limits=vcount_limits, normalize=normalize, colormap=colormap, **kwargs) if show: plot3d.show() return plot3d @property def col(self): """Gives direct access to the columns only (useful for tab completion). Convenient when working with ipython in combination with small DataFrames, since this gives tab-completion. Columns can be accessed by their names, which are attributes. The attributes are currently expressions, so you can do computations with them. Example >>> ds = vaex.example() >>> df.plot(df.col.x, df.col.y) """ class ColumnList(object): pass data = ColumnList() for name in self.get_column_names(): if name != 'col': # avoid recursion expression = getattr(self, name, None) if not isinstance(expression, Expression): expression = Expression(self, name) else: expression = Expression(self, name) setattr(data, name, expression) return data def close(self): """Close any possible open file handles or other resources, the DataFrame will not be in a usable state afterwards.""" self.dataset.close() def byte_size(self, selection=False, virtual=False): """Return the size in bytes the whole DataFrame requires (or the selection), respecting the active_fraction.""" bytes_per_row = 0 N = self.count(selection=selection) extra = 0 for column in list(self.get_column_names(virtual=virtual)): dtype = self.data_type(column) #if dtype in [str_type, str] and dtype_internal.kind == 'O': if dtype == str: # TODO: document or fix this # is it too expensive to calculate this exactly? extra += self.columns[column].nbytes else: bytes_per_row += dtype.numpy.itemsize if np.ma.isMaskedArray(self.columns[column]): bytes_per_row += 1 return bytes_per_row * self.count(selection=selection) + extra @property def nbytes(self): """Alias for `df.byte_size()`, see :meth:`DataFrame.byte_size`.""" return self.byte_size() def _shape_of(self, expression, filtered=True): # TODO: we don't seem to need it anymore, would expect a valid_expression() call # if check_alias: # if str(expression) in self._column_aliases: # expression = self._column_aliases[str(expression)] # translate the alias name into the real name sample = self.evaluate(expression, 0, 1, filtered=False, array_type="numpy-arrow", parallel=False) dtype = vaex.dtype_of(sample) rows = len(self) if filtered else self.length_unfiltered() if dtype.is_arrow: # for arrow, we don't have nd arrays yet return (rows,) else: return (rows,) + sample.shape[1:] # TODO: remove array_type and internal arguments? def data_type(self, expression, array_type=None, internal=False, axis=0): """Return the datatype for the given expression, if not a column, the first row will be evaluated to get the data type. Example: >>> df = vaex.from_scalars(x=1, s='Hi') :param str array_type: 'numpy', 'arrow' or None, to indicate if the data type should be converted :param int axis: If a nested type (like list), it will return the value_type of the nested type, axis levels deep. """ if isinstance(expression, vaex.expression.Expression): expression = expression._label expression = _ensure_string_from_expression(expression) data_type = None if expression in self.variables: data_type = np.float64(1).dtype elif self.is_local() and expression in self.columns.keys(): column = self.columns[expression] if hasattr(column, 'dtype'): # TODO: this probably would use data_type # to support Columns that wrap arrow arrays data_type = column.dtype data_type = self._auto_encode_type(expression, data_type) if isinstance(data_type, vaex.datatype.DataType): data_type = data_type.internal else: data = column[0:1] data = self._auto_encode_data(expression, data) else: expression = vaex.utils.valid_expression(self.get_column_names(hidden=True), expression) try: data = self.evaluate(expression, 0, 1, filtered=False, array_type=array_type, parallel=False) except: data = self.evaluate(expression, 0, 1, filtered=True, array_type=array_type, parallel=False) if data_type is None: # means we have to determine it from the data if isinstance(data, np.ndarray): data_type = data.dtype elif isinstance(data, Column): data = data.to_arrow() data_type = data.type else: # when we eval constants, let arrow find it out if isinstance(data, numbers.Number): data_type = pa.array([data]).type else: data_type = data.type # assuming arrow if array_type == "arrow": data_type = array_types.to_arrow_type(data_type) elif array_type == "numpy": data_type = array_types.to_numpy_type(data_type) elif array_type == "numpy-arrow": data_type = array_types.to_numpy_type(data_type, strict=False) elif array_type is None: data_type = data_type else: raise ValueError(f'Unknown array_type {array_type}') data_type = DataType(data_type) # ugly, but fixes df.x.apply(lambda x: str(x)) if not internal: if isinstance(data_type.internal, np.dtype) and data_type.kind in 'US': return DataType(pa.string()) if axis != 0: axis_data_type = [data_type] while data_type.is_list: data_type = data_type.value_type axis_data_type.append(data_type) data_type = axis_data_type[axis] return data_type @property def dtypes(self): """Gives a Pandas series object containing all numpy dtypes of all columns (except hidden).""" from pandas import Series return Series({column_name:self.data_type(column_name) for column_name in self.get_column_names()}) def schema(self): '''Similar to df.dtypes, but returns a dict''' return {column_name:self.data_type(column_name) for column_name in self.get_column_names()} @docsubst def schema_arrow(self, reduce_large=False): '''Similar to :method:`schema`, but returns an arrow schema :param bool reduce_large: change large_string to normal string ''' def reduce(type): if reduce_large and type == pa.large_string(): type = pa.string() return type return pa.schema({name: reduce(dtype.arrow) for name, dtype in self.schema().items()}) def is_masked(self, column): '''Return if a column is a masked (numpy.ma) column.''' column = _ensure_string_from_expression(column) if column in self.dataset: return self.dataset.is_masked(column) else: ar = self.evaluate(column, i1=0, i2=1, parallel=False) if isinstance(ar, np.ndarray) and np.ma.isMaskedArray(ar): return True return False def label(self, expression, unit=None, output_unit=None, format="latex_inline"): label = expression unit = unit or self.unit(expression) try: # if we can convert the unit, use that for the labeling if output_unit and unit: # avoid unnecessary error msg'es output_unit.to(unit) unit = output_unit except: logger.exception("unit error") if unit is not None: label = "%s (%s)" % (label, unit.to_string('latex_inline')) return label def unit(self, expression, default=None): """Returns the unit (an astropy.unit.Units object) for the expression. Example >>> import vaex >>> ds = vaex.example() >>> df.unit("x") Unit("kpc") >>> df.unit("x*L") Unit("km kpc2 / s") :param expression: Expression, which can be a column name :param default: if no unit is known, it will return this :return: The resulting unit of the expression :rtype: astropy.units.Unit """ expression = _ensure_string_from_expression(expression) try: # if an expression like pi * <some_expr> it will evaluate to a quantity instead of a unit unit_or_quantity = eval(expression, expression_namespace, scopes.UnitScope(self)) unit = unit_or_quantity.unit if hasattr(unit_or_quantity, "unit") else unit_or_quantity unit_types = (astropy.units.core.UnitBase, ) return unit if isinstance(unit, unit_types) else None except: # logger.exception("error evaluating unit expression: %s", expression) # astropy doesn't add units, so we try with a quatiti try: return eval(expression, expression_namespace, scopes.UnitScope(self, 1.)).unit except: # logger.exception("error evaluating unit expression: %s", expression) return default def ucd_find(self, ucds, exclude=[]): """Find a set of columns (names) which have the ucd, or part of the ucd. Prefixed with a ^, it will only match the first part of the ucd. Example >>> df.ucd_find('pos.eq.ra', 'pos.eq.dec') ['RA', 'DEC'] >>> df.ucd_find('pos.eq.ra', 'doesnotexist') >>> df.ucds[df.ucd_find('pos.eq.ra')] 'pos.eq.ra;meta.main' >>> df.ucd_find('meta.main')] 'dec' >>> df.ucd_find('^meta.main')] """ if isinstance(ucds, six.string_types): ucds = [ucds] if len(ucds) == 1: ucd = ucds[0] if ucd[0] == "^": # we want it to start with ucd = ucd[1:] columns = [name for name in self.get_column_names() if self.ucds.get(name, "").startswith(ucd) and name not in exclude] else: columns = [name for name in self.get_column_names() if ucd in self.ucds.get(name, "") and name not in exclude] return None if len(columns) == 0 else columns[0] else: columns = [self.ucd_find([ucd], exclude=exclude) for ucd in ucds] return None if None in columns else columns @vaex.utils.deprecated('Will most likely disappear or move') @_hidden def selection_favorite_add(self, name, selection_name="default"): selection = self.get_selection(name=selection_name) if selection: self.favorite_selections[name] = selection self.selections_favorite_store() else: raise ValueError("no selection exists") @vaex.utils.deprecated('Will most likely disappear or move') @_hidden def selection_favorite_remove(self, name): del self.favorite_selections[name] self.selections_favorite_store() @vaex.utils.deprecated('Will most likely disappear or move') @_hidden def selection_favorite_apply(self, name, selection_name="default", executor=None): self.set_selection(self.favorite_selections[name], name=selection_name, executor=executor) @vaex.utils.deprecated('Will most likely disappear or move') @_hidden def selections_favorite_store(self): path = os.path.join(self.get_private_dir(create=True), "favorite_selection.yaml") selections = collections.OrderedDict([(key, value.to_dict()) for key, value in self.favorite_selections.items()]) vaex.utils.write_json_or_yaml(path, selections) @vaex.utils.deprecated('Will most likely disappear or move') @_hidden def selections_favorite_load(self): try: path = os.path.join(self.get_private_dir(create=True), "favorite_selection.yaml") if os.path.exists(path): selections_dict = vaex.utils.read_json_or_yaml(path) for key, value in selections_dict.items(): self.favorite_selections[key] = selections.selection_from_dict(self, value) except: logger.exception("non fatal error") def get_private_dir(self, create=False): """Each DataFrame has a directory where files are stored for metadata etc. Example >>> import vaex >>> ds = vaex.example() >>> vaex.get_private_dir() '/Users/users/breddels/.vaex/dfs/_Users_users_breddels_vaex-testing_data_helmi-dezeeuw-2000-10p.hdf5' :param bool create: is True, it will create the directory if it does not exist """ if self.is_local(): name = os.path.abspath(self.path).replace(os.path.sep, "_")[:250] # should not be too long for most os'es name = name.replace(":", "_") # for windows drive names else: server = self.server name = "%s_%s_%s_%s" % (server.hostname, server.port, server.base_path.replace("/", "_"), self.name) dir = os.path.join(vaex.utils.get_private_dir(), "dfs", name) if create and not os.path.exists(dir): os.makedirs(dir) return dir def state_get(self, skip=None): if self._future_behaviour == 5: return self._state_get_vaex_5(skip=skip) else: if not ((skip is None) or (len(skip) == 1 and skip[0] is self.dataset)): raise ValueError(f'skip should be None or its own dataset') return self._state_get_pre_vaex_5() def state_set(self, state, use_active_range=False, keep_columns=None, set_filter=True, trusted=True, warn=True, delete_unused_columns = True): if self._future_behaviour == 5: return self._state_set_vaex_5(state, use_active_range=use_active_range, keep_columns=keep_columns, set_filter=set_filter, trusted=trusted, warn=warn) else: return self._state_set_pre_vaex_5(state, use_active_range=use_active_range, keep_columns=keep_columns, set_filter=set_filter, trusted=trusted, warn=warn, delete_unused_columns=delete_unused_columns) def _state_get_vaex_5(self, skip=None): """Return the internal state of the DataFrame in a dictionary Example: >>> import vaex >>> df = vaex.from_scalars(x=1, y=2) >>> df['r'] = (df.x**2 + df.y**2)**0.5 >>> df.state_get() {'active_range': [0, 1], 'column_names': ['x', 'y', 'r'], 'description': None, 'descriptions': {}, 'functions': {}, 'renamed_columns': [], 'selections': {'__filter__': None}, 'ucds': {}, 'units': {}, 'variables': {}, 'virtual_columns': {'r': '(((x ** 2) + (y ** 2)) ** 0.5)'}} """ virtual_names = list(self.virtual_columns.keys()) + list(self.variables.keys()) units = {key: str(value) for key, value in self.units.items()} ucds = {key: value for key, value in self.ucds.items() if key in virtual_names} descriptions = {key: value for key, value in self.descriptions.items()} selections = {name: self.get_selection(name) for name, history in self.selection_histories.items() if self.has_selection(name)} encoding = vaex.encoding.Encoding() state = dict(virtual_columns=dict(self.virtual_columns), column_names=list(self.column_names), variables={name: encoding.encode("variable", value) for name, value in self.variables.items()}, functions={name: encoding.encode("function", value) for name, value in self.functions.items()}, selections={name: encoding.encode("selection", value) for name, value in selections.items()}, description=self.description, ucds=ucds, units=units, descriptions=descriptions, active_range=[self._index_start, self._index_end] ) datasets = self.dataset.leafs() if skip is None else skip for dataset in datasets: # mark leafs to not encode encoding._object_specs[dataset.id] = None assert encoding.has_object_spec(dataset.id) if len(datasets) != 1: raise ValueError('Multiple datasets present, please pass skip= argument so we know which dataset not to include in the state.') dataset_main = datasets[0] if dataset_main is not self.dataset: # encode without the leafs data = encoding.encode('dataset', self.dataset) # remove the dummy leaf data for dataset in datasets: assert encoding._object_specs[dataset.id] is None del encoding._object_specs[dataset.id] if data is not None: state['dataset'] = data state['dataset_missing'] = {'main': dataset_main.id} state['blobs'] = {key: base64.b64encode(value).decode('ascii') for key, value in encoding.blobs.items()} if encoding._object_specs: state['objects'] = encoding._object_specs return state def _state_set_vaex_5(self, state, use_active_range=False, keep_columns=None, set_filter=True, trusted=True, warn=True): """Sets the internal state of the df Example: >>> import vaex >>> df = vaex.from_scalars(x=1, y=2) >>> df # x y r 0 1 2 2.23607 >>> df['r'] = (df.x**2 + df.y**2)**0.5 >>> state = df.state_get() >>> state {'active_range': [0, 1], 'column_names': ['x', 'y', 'r'], 'description': None, 'descriptions': {}, 'functions': {}, 'renamed_columns': [], 'selections': {'__filter__': None}, 'ucds': {}, 'units': {}, 'variables': {}, 'virtual_columns': {'r': '(((x ** 2) + (y ** 2)) ** 0.5)'}} >>> df2 = vaex.from_scalars(x=3, y=4) >>> df2.state_set(state) # now the virtual functions are 'copied' >>> df2 # x y r 0 3 4 5 :param state: dict as returned by :meth:`DataFrame.state_get`. :param bool use_active_range: Whether to use the active range or not. :param list keep_columns: List of columns that should be kept if the state to be set contains less columns. :param bool set_filter: Set the filter from the state (default), or leave the filter as it is it. :param bool warn: Give warning when issues are found in the state transfer that are recoverable. """ self.description = state['description'] if use_active_range: self._index_start, self._index_end = state['active_range'] self._length_unfiltered = self._index_end - self._index_start if keep_columns: all_columns = self.get_column_names() for column_name in keep_columns: if column_name not in all_columns: raise KeyError(f'Column name {column_name} does not exist') encoding = vaex.encoding.Encoding() if 'blobs' in state: encoding.blobs = {key: base64.b64decode(value.encode('ascii')) for key, value in state['blobs'].items()} if 'objects' in state: encoding._object_specs = state['objects'] if 'dataset' in state: encoding.set_object(state['dataset_missing']['main'], self.dataset) self.dataset = encoding.decode('dataset', state['dataset']) for name, value in state['functions'].items(): self.add_function(name, encoding.decode("function", value, trusted=trusted)) # we clear all columns, and add them later on, since otherwise self[name] = ... will try # to rename the columns (which is unsupported for remote dfs) self.column_names = [] self.virtual_columns = {} self.column_names = list(set(self.dataset) & set(state['column_names'])) # initial values not to have virtual column trigger missing column values if 'variables' in state: self.variables = {name: encoding.decode("variable", value) for name, value in state['variables'].items()} for name, value in state['virtual_columns'].items(): self[name] = self._expr(value) # self._save_assign_expression(name) self.column_names = list(state['column_names']) if keep_columns: self.column_names += list(keep_columns) for name in self.column_names: self._save_assign_expression(name) if "units" in state: units = {key: astropy.units.Unit(value) for key, value in state["units"].items()} self.units.update(units) if 'selections' in state: for name, selection_dict in state['selections'].items(): selection = encoding.decode('selection', selection_dict) if name == FILTER_SELECTION_NAME and not set_filter: continue self.set_selection(selection, name=name) if self.is_local(): for name in self.dataset: if name not in self.column_names: del self.columns[name] def _state_get_pre_vaex_5(self): """Return the internal state of the DataFrame in a dictionary Example: >>> import vaex >>> df = vaex.from_scalars(x=1, y=2) >>> df['r'] = (df.x**2 + df.y**2)**0.5 >>> df.state_get() {'active_range': [0, 1], 'column_names': ['x', 'y', 'r'], 'description': None, 'descriptions': {}, 'functions': {}, 'renamed_columns': [], 'selections': {'__filter__': None}, 'ucds': {}, 'units': {}, 'variables': {}, 'virtual_columns': {'r': '(((x ** 2) + (y ** 2)) ** 0.5)'}} """ virtual_names = list(self.virtual_columns.keys()) + list(self.variables.keys()) units = {key: str(value) for key, value in self.units.items()} ucds = {key: value for key, value in self.ucds.items() if key in virtual_names} descriptions = {key: value for key, value in self.descriptions.items()} import vaex.serialize def check(key, value): if not vaex.serialize.can_serialize(value.f): warnings.warn('Cannot serialize function for virtual column {} (use vaex.serialize.register)'.format(key)) return False return True def clean(value): return vaex.serialize.to_dict(value.f) functions = {key: clean(value) for key, value in self.functions.items() if check(key, value)} virtual_columns = {key: value for key, value in self.virtual_columns.items()} selections = {name: self.get_selection(name) for name, history in self.selection_histories.items()} selections = {name: selection.to_dict() if selection is not None else None for name, selection in selections.items()} # if selection is not None} state = dict(virtual_columns=virtual_columns, column_names=self.column_names, renamed_columns=self._renamed_columns, variables=self.variables, functions=functions, selections=selections, ucds=ucds, units=units, descriptions=descriptions, description=self.description, active_range=[self._index_start, self._index_end]) return state def _state_set_pre_vaex_5(self, state, use_active_range=False, keep_columns=None, set_filter=True, trusted=True, warn=True, delete_unused_columns = True): """Sets the internal state of the df Example: >>> import vaex >>> df = vaex.from_scalars(x=1, y=2) >>> df # x y r 0 1 2 2.23607 >>> df['r'] = (df.x**2 + df.y**2)**0.5 >>> state = df.state_get() >>> state {'active_range': [0, 1], 'column_names': ['x', 'y', 'r'], 'description': None, 'descriptions': {}, 'functions': {}, 'renamed_columns': [], 'selections': {'__filter__': None}, 'ucds': {}, 'units': {}, 'variables': {}, 'virtual_columns': {'r': '(((x ** 2) + (y ** 2)) ** 0.5)'}} >>> df2 = vaex.from_scalars(x=3, y=4) >>> df2.state_set(state) # now the virtual functions are 'copied' >>> df2 # x y r 0 3 4 5 :param state: dict as returned by :meth:`DataFrame.state_get`. :param bool use_active_range: Whether to use the active range or not. :param list keep_columns: List of columns that should be kept if the state to be set contains less columns. :param bool set_filter: Set the filter from the state (default), or leave the filter as it is it. :param bool warn: Give warning when issues are found in the state transfer that are recoverable. :param bool delete_unused_columns: Whether to delete columns from the DataFrame that are not in the column_names. Useful to set to False during prediction time. """ if 'description' in state: self.description = state['description'] if use_active_range: if 'active_range' in state: self._index_start, self._index_end = state['active_range'] self._length_unfiltered = self._index_end - self._index_start if keep_columns: all_columns = self.get_column_names() for column_name in keep_columns: if column_name not in all_columns: raise KeyError(f'Column name {column_name} does not exist') if 'renamed_columns' in state: for old, new in state['renamed_columns']: if old in self: self._rename(old, new) elif warn: warnings.warn(f'The state wants to rename {old} to {new}, but {new} was not found, ignoring the rename') if 'functions' in state: for name, value in state['functions'].items(): self.add_function(name, vaex.serialize.from_dict(value, trusted=trusted)) if 'variables' in state: self.variables = state['variables'] if 'column_names' in state: # we clear all columns, and add them later on, since otherwise self[name] = ... will try # to rename the columns (which is unsupported for remote dfs) self.column_names = [] self.virtual_columns = {} self.column_names = list(set(self.dataset) & set(state['column_names'])) # initial values not to have virtual column trigger missing column values if 'virtual_columns' in state: for name, value in state['virtual_columns'].items(): self[name] = self._expr(value) self.column_names = list(state['column_names']) if keep_columns: self.column_names += list(keep_columns) for name in self.column_names: self._save_assign_expression(name) else: # old behaviour self.virtual_columns = {} for name, value in state['virtual_columns'].items(): self[name] = self._expr(value) if 'units' in state: units = {key: astropy.units.Unit(value) for key, value in state["units"].items()} self.units.update(units) if 'selections' in state: for name, selection_dict in state['selections'].items(): if name == FILTER_SELECTION_NAME and not set_filter: continue # TODO: make selection use the vaex.serialize framework if selection_dict is None: selection = None else: selection = selections.selection_from_dict(selection_dict) self.set_selection(selection, name=name) if self.is_local() and delete_unused_columns: for name in self.dataset: if name not in self.column_names: del self.columns[name] def state_write(self, file, fs_options=None, fs=None): """Write the internal state to a json or yaml file (see :meth:`DataFrame.state_get`) Example >>> import vaex >>> df = vaex.from_scalars(x=1, y=2) >>> df['r'] = (df.x**2 + df.y**2)**0.5 >>> df.state_write('state.json') >>> print(open('state.json').read()) { "virtual_columns": { "r": "(((x ** 2) + (y ** 2)) ** 0.5)" }, "column_names": [ "x", "y", "r" ], "renamed_columns": [], "variables": { "pi": 3.141592653589793, "e": 2.718281828459045, "km_in_au": 149597870.7, "seconds_per_year": 31557600 }, "functions": {}, "selections": { "__filter__": null }, "ucds": {}, "units": {}, "descriptions": {}, "description": null, "active_range": [ 0, 1 ] } >>> df.state_write('state.yaml') >>> print(open('state.yaml').read()) active_range: - 0 - 1 column_names: - x - y - r description: null descriptions: {} functions: {} renamed_columns: [] selections: __filter__: null ucds: {} units: {} variables: pi: 3.141592653589793 e: 2.718281828459045 km_in_au: 149597870.7 seconds_per_year: 31557600 virtual_columns: r: (((x ** 2) + (y ** 2)) ** 0.5) :param str file: filename (ending in .json or .yaml) :param dict fs_options: arguments to pass the the file system handler (s3fs or gcsfs) :param fs: 'Pass a file system object directly, see :func:`vaex.open`' """ fs_options = fs_options or {} vaex.utils.write_json_or_yaml(file, self.state_get(), fs_options=fs_options, fs=fs, old_style=not self._future_behaviour) def state_load(self, file, use_active_range=False, keep_columns=None, set_filter=True, trusted=True, fs_options=None, fs=None): """Load a state previously stored by :meth:`DataFrame.state_write`, see also :meth:`DataFrame.state_set`. :param str file: filename (ending in .json or .yaml) :param bool use_active_range: Whether to use the active range or not. :param list keep_columns: List of columns that should be kept if the state to be set contains less columns. :param bool set_filter: Set the filter from the state (default), or leave the filter as it is it. :param dict fs_options: arguments to pass the the file system handler (s3fs or gcsfs) :param fs: 'Pass a file system object directly, see :func:`vaex.open`' """ state = vaex.utils.read_json_or_yaml(file, fs_options=fs_options, fs=fs, old_style=not self._future_behaviour) self.state_set(state, use_active_range=use_active_range, keep_columns=keep_columns, set_filter=set_filter, trusted=trusted) def remove_virtual_meta(self): """Removes the file with the virtual column etc, it does not change the current virtual columns etc.""" dir = self.get_private_dir(create=True) path = os.path.join(dir, "virtual_meta.yaml") try: if os.path.exists(path): os.remove(path) if not os.listdir(dir): os.rmdir(dir) except: logger.exception("error while trying to remove %s or %s", path, dir) # def remove_meta(self): # path = os.path.join(self.get_private_dir(create=True), "meta.yaml") # os.remove(path) @_hidden def write_virtual_meta(self): """Writes virtual columns, variables and their ucd,description and units. The default implementation is to write this to a file called virtual_meta.yaml in the directory defined by :func:`DataFrame.get_private_dir`. Other implementation may store this in the DataFrame file itself. This method is called after virtual columns or variables are added. Upon opening a file, :func:`DataFrame.update_virtual_meta` is called, so that the information is not lost between sessions. Note: opening a DataFrame twice may result in corruption of this file. """ path = os.path.join(self.get_private_dir(create=True), "virtual_meta.yaml") virtual_names = list(self.virtual_columns.keys()) + list(self.variables.keys()) units = {key: str(value) for key, value in self.units.items() if key in virtual_names} ucds = {key: value for key, value in self.ucds.items() if key in virtual_names} descriptions = {key: value for key, value in self.descriptions.items() if key in virtual_names} meta_info = dict(virtual_columns=self.virtual_columns, variables=self.variables, ucds=ucds, units=units, descriptions=descriptions) vaex.utils.write_json_or_yaml(path, meta_info) @_hidden def update_virtual_meta(self): """Will read back the virtual column etc, written by :func:`DataFrame.write_virtual_meta`. This will be done when opening a DataFrame.""" try: path = os.path.join(self.get_private_dir(create=False), "virtual_meta.yaml") if os.path.exists(path): meta_info = vaex.utils.read_json_or_yaml(path) if 'virtual_columns' not in meta_info: return self.virtual_columns.update(meta_info["virtual_columns"]) self.variables.update(meta_info["variables"]) self.ucds.update(meta_info["ucds"]) self.descriptions.update(meta_info["descriptions"]) units = {key: astropy.units.Unit(value) for key, value in meta_info["units"].items()} self.units.update(units) except: logger.exception("non fatal error") @_hidden def write_meta(self): """Writes all meta data, ucd,description and units The default implementation is to write this to a file called meta.yaml in the directory defined by :func:`DataFrame.get_private_dir`. Other implementation may store this in the DataFrame file itself. (For instance the vaex hdf5 implementation does this) This method is called after virtual columns or variables are added. Upon opening a file, :func:`DataFrame.update_meta` is called, so that the information is not lost between sessions. Note: opening a DataFrame twice may result in corruption of this file. """ # raise NotImplementedError path = os.path.join(self.get_private_dir(create=True), "meta.yaml") units = {key: str(value) for key, value in self.units.items()} meta_info = dict(description=self.description, ucds=self.ucds, units=units, descriptions=self.descriptions, ) vaex.utils.write_json_or_yaml(path, meta_info) @_hidden def update_meta(self): """Will read back the ucd, descriptions, units etc, written by :func:`DataFrame.write_meta`. This will be done when opening a DataFrame.""" try: path = os.path.join(self.get_private_dir(create=False), "meta.yaml") if os.path.exists(path): meta_info = vaex.utils.read_json_or_yaml(path) self.description = meta_info["description"] self.ucds.update(meta_info["ucds"]) self.descriptions.update(meta_info["descriptions"]) # self.virtual_columns.update(meta_info["virtual_columns"]) # self.variables.update(meta_info["variables"]) units = {key: astropy.units.Unit(value) for key, value in meta_info["units"].items()} self.units.update(units) except: logger.exception("non fatal error, but could read/understand %s", path) def is_local(self): """Returns True if the DataFrame is local, False when a DataFrame is remote.""" raise NotImplementedError def get_auto_fraction(self): return self._auto_fraction def set_auto_fraction(self, enabled): self._auto_fraction = enabled @classmethod def can_open(cls, path, *args, **kwargs): # """Tests if this class can open the file given by path""" return False @classmethod def get_options(cls, path): return [] @classmethod def option_to_args(cls, option): return [] def combinations(self, expressions_list=None, dimension=2, exclude=None, **kwargs): """Generate a list of combinations for the possible expressions for the given dimension. :param expressions_list: list of list of expressions, where the inner list defines the subspace :param dimensions: if given, generates a subspace with all possible combinations for that dimension :param exclude: list of """ if dimension is not None: expressions_list = list(itertools.combinations(self.get_column_names(), dimension)) if exclude is not None: import six def excluded(expressions): if callable(exclude): return exclude(expressions) elif isinstance(exclude, six.string_types): return exclude in expressions elif isinstance(exclude, (list, tuple)): # $#expressions = set(expressions) for e in exclude: if isinstance(e, six.string_types): if e in expressions: return True elif isinstance(e, (list, tuple)): if set(e).issubset(expressions): return True else: raise ValueError("elements of exclude should contain a string or a sequence of strings") else: raise ValueError("exclude should contain a string, a sequence of strings, or should be a callable") return False # test if any of the elements of exclude are a subset of the expression expressions_list = [expr for expr in expressions_list if not excluded(expr)] logger.debug("expression list generated: %r", expressions_list) return expressions_list def set_variable(self, name, expression_or_value, write=True): """Set the variable to an expression or value defined by expression_or_value. Example >>> df.set_variable("a", 2.) >>> df.set_variable("b", "a**2") >>> df.get_variable("b") 'a**2' >>> df.evaluate_variable("b") 4.0 :param name: Name of the variable :param write: write variable to meta file :param expression: value or expression """ self.variables[name] = expression_or_value # if write: # self.write_virtual_meta() def get_variable(self, name): """Returns the variable given by name, it will not evaluate it. For evaluation, see :func:`DataFrame.evaluate_variable`, see also :func:`DataFrame.set_variable` """ return self.variables[name] def evaluate_variable(self, name): """Evaluates the variable given by name.""" if isinstance(self.variables[name], six.string_types): # TODO: this does not allow more than one level deep variable, like a depends on b, b on c, c is a const value = eval(self.variables[name], expression_namespace, self.variables) return value else: return self.variables[name] @docsubst def evaluate(self, expression, i1=None, i2=None, out=None, selection=None, filtered=True, array_type=None, parallel=True, chunk_size=None, progress=None): """Evaluate an expression, and return a numpy array with the results for the full column or a part of it. Note that this is not how vaex should be used, since it means a copy of the data needs to fit in memory. To get partial results, use i1 and i2 :param str expression: Name/expression to evaluate :param int i1: Start row index, default is the start (0) :param int i2: End row index, default is the length of the DataFrame :param ndarray out: Output array, to which the result may be written (may be used to reuse an array, or write to a memory mapped array) :param progress: {{progress}} :param selection: selection to apply :return: """ if chunk_size is not None: return self.evaluate_iterator(expression, s1=i1, s2=i2, out=out, selection=selection, filtered=filtered, array_type=array_type, parallel=parallel, chunk_size=chunk_size, progress=progress) else: return self._evaluate_implementation(expression, i1=i1, i2=i2, out=out, selection=selection, filtered=filtered, array_type=array_type, parallel=parallel, chunk_size=chunk_size, progress=progress) @docsubst def evaluate_iterator(self, expression, s1=None, s2=None, out=None, selection=None, filtered=True, array_type=None, parallel=True, chunk_size=None, prefetch=True, progress=None): """Generator to efficiently evaluate expressions in chunks (number of rows). See :func:`DataFrame.evaluate` for other arguments. Example: >>> import vaex >>> df = vaex.example() >>> for i1, i2, chunk in df.evaluate_iterator(df.x, chunk_size=100_000): ... print(f"Total of {{i1}} to {{i2}} = {{chunk.sum()}}") ... Total of 0 to 100000 = -7460.610158279056 Total of 100000 to 200000 = -4964.85827154921 Total of 200000 to 300000 = -7303.271340043915 Total of 300000 to 330000 = -2424.65234724951 :param progress: {{progress}} :param prefetch: Prefetch/compute the next chunk in parallel while the current value is yielded/returned. """ progressbar = vaex.utils.progressbars(progress, title="evaluate iterator") import concurrent.futures self._fill_filter_mask() progressbar(0) if not prefetch: # this is the simple implementation for l1, l2, i1, i2 in self._unfiltered_chunk_slices(chunk_size): yield l1, l2, self._evaluate_implementation(expression, i1=i1, i2=i2, out=out, selection=selection, filtered=filtered, array_type=array_type, parallel=parallel, raw=True) progressbar(l2/len(self)) # But this implementation is faster if the main thread work is single threaded else: with concurrent.futures.ThreadPoolExecutor(1) as executor: iter = self._unfiltered_chunk_slices(chunk_size) def f(i1, i2): return self._evaluate_implementation(expression, i1=i1, i2=i2, out=out, selection=selection, filtered=filtered, array_type=array_type, parallel=parallel, raw=True) try: previous_l1, previous_l2, previous_i1, previous_i2 = next(iter) except StopIteration: # empty dataframe/filter return # we submit the 1st job previous = executor.submit(f, previous_i1, previous_i2) for l1, l2, i1, i2 in iter: # and we submit the next job before returning the previous, so they run in parallel # but make sure the previous is done previous_chunk = previous.result() current = executor.submit(f, i1, i2) yield previous_l1, previous_l2, previous_chunk progressbar(previous_l2/len(self)) previous = current previous_l1, previous_l2 = l1, l2 previous_chunk = previous.result() yield previous_l1, previous_l2, previous_chunk progressbar(previous_l2/len(self)) @docsubst def to_records(self, index=None, selection=None, column_names=None, strings=True, virtual=True, parallel=True, chunk_size=None, array_type='python'): """Return a list of [{{column_name: value}}, ...)] "records" where each dict is an evaluated row. :param index: an index to use to get the record of a specific row when provided :param column_names: list of column names, to export, when None DataFrame.get_column_names(strings=strings, virtual=virtual) is used :param selection: {selection} :param strings: argument passed to DataFrame.get_column_names when column_names is None :param virtual: argument passed to DataFrame.get_column_names when column_names is None :param parallel: {evaluate_parallel} :param chunk_size: {chunk_size} :param array_type: {array_type} :return: list of [{{column_name:value}}, ...] records """ if isinstance(index, int): return {key: value[0] for key, value in self[index:index + 1].to_dict(selection=selection, column_names=column_names, strings=strings, virtual=virtual, parallel=parallel, array_type=array_type).items()} if index is not None: raise RuntimeError(f"index can be None or an int - {type(index)} provided") if chunk_size is not None: def iterator(): for i1, i2, chunk in self.to_dict(selection=selection, column_names=column_names, strings=strings, virtual=virtual, parallel=parallel, chunk_size=chunk_size, array_type=array_type): keys = list(chunk.keys()) yield i1, i2, [{key: value for key, value in zip(keys, values)} for values in zip(*chunk.values())] return iterator() chunk = self.to_dict(selection=selection, column_names=column_names, strings=strings, virtual=virtual, parallel=parallel, chunk_size=chunk_size, array_type=array_type) keys = list(chunk.keys()) return [{key: value for key, value in zip(keys, values)} for values in zip(*chunk.values())] @docsubst def to_items(self, column_names=None, selection=None, strings=True, virtual=True, parallel=True, chunk_size=None, array_type=None): """Return a list of [(column_name, ndarray), ...)] pairs where the ndarray corresponds to the evaluated data :param column_names: list of column names, to export, when None DataFrame.get_column_names(strings=strings, virtual=virtual) is used :param selection: {selection} :param strings: argument passed to DataFrame.get_column_names when column_names is None :param virtual: argument passed to DataFrame.get_column_names when column_names is None :param parallel: {evaluate_parallel} :param chunk_size: {chunk_size} :param array_type: {array_type} :return: list of (name, ndarray) pairs or iterator of """ column_names = column_names or self.get_column_names(strings=strings, virtual=virtual) column_names = _ensure_strings_from_expressions(column_names) if chunk_size is not None: def iterator(): for i1, i2, chunks in self.evaluate_iterator(column_names, selection=selection, parallel=parallel, chunk_size=chunk_size): yield i1, i2, list(zip(column_names, [array_types.convert(chunk, array_type) for chunk in chunks])) return iterator() else: return list(zip(column_names, [array_types.convert(chunk, array_type) for chunk in self.evaluate(column_names, selection=selection, parallel=parallel)])) @docsubst def to_arrays(self, column_names=None, selection=None, strings=True, virtual=True, parallel=True, chunk_size=None, array_type=None): """Return a list of ndarrays :param column_names: list of column names, to export, when None DataFrame.get_column_names(strings=strings, virtual=virtual) is used :param selection: {selection} :param strings: argument passed to DataFrame.get_column_names when column_names is None :param virtual: argument passed to DataFrame.get_column_names when column_names is None :param parallel: {evaluate_parallel} :param chunk_size: {chunk_size} :param array_type: {array_type} :return: list of arrays """ column_names = column_names or self.get_column_names(strings=strings, virtual=virtual) column_names = _ensure_strings_from_expressions(column_names) if chunk_size is not None: def iterator(): for i1, i2, chunks in self.evaluate_iterator(column_names, selection=selection, parallel=parallel, chunk_size=chunk_size): yield i1, i2, [array_types.convert(chunk, array_type) for chunk in chunks] return iterator() return [array_types.convert(chunk, array_type) for chunk in self.evaluate(column_names, selection=selection, parallel=parallel)] @docsubst def to_dict(self, column_names=None, selection=None, strings=True, virtual=True, parallel=True, chunk_size=None, array_type=None): """Return a dict containing the ndarray corresponding to the evaluated data :param column_names: list of column names, to export, when None DataFrame.get_column_names(strings=strings, virtual=virtual) is used :param selection: {selection} :param strings: argument passed to DataFrame.get_column_names when column_names is None :param virtual: argument passed to DataFrame.get_column_names when column_names is None :param parallel: {evaluate_parallel} :param chunk_size: {chunk_size} :param array_type: {array_type} :return: dict """ column_names = column_names or self.get_column_names(strings=strings, virtual=virtual) column_names = _ensure_strings_from_expressions(column_names) if chunk_size is not None: def iterator(): for i1, i2, chunks in self.evaluate_iterator(column_names, selection=selection, parallel=parallel, chunk_size=chunk_size): yield i1, i2, dict(list(zip(column_names, [array_types.convert(chunk, array_type) for chunk in chunks]))) return iterator() return dict(list(zip(column_names, [array_types.convert(chunk, array_type) for chunk in self.evaluate(column_names, selection=selection, parallel=parallel)]))) @_hidden @docsubst @vaex.utils.deprecated('`.to_copy()` is deprecated and it will be removed in version 5.x. Please use `.copy()` instead.') def to_copy(self, column_names=None, selection=None, strings=True, virtual=True, selections=True): """Return a copy of the DataFrame, if selection is None, it does not copy the data, it just has a reference :param column_names: list of column names, to copy, when None DataFrame.get_column_names(strings=strings, virtual=virtual) is used :param selection: {selection} :param strings: argument passed to DataFrame.get_column_names when column_names is None :param virtual: argument passed to DataFrame.get_column_names when column_names is None :param selections: copy selections to a new DataFrame :return: DataFrame """ if column_names: column_names = _ensure_strings_from_expressions(column_names) df = vaex.from_items(*self.to_items(column_names=column_names, selection=selection, strings=strings, virtual=False)) if virtual: for name, value in self.virtual_columns.items(): df.add_virtual_column(name, value) if selections: # the filter selection does not need copying for key, value in self.selection_histories.items(): if key != FILTER_SELECTION_NAME: df.selection_histories[key] = list(value) for key, value in self.selection_history_indices.items(): if key != FILTER_SELECTION_NAME: df.selection_history_indices[key] = value df.functions.update(self.functions) df.copy_metadata(self) return df def copy_metadata(self, other): for name in self.get_column_names(strings=True): if name in other.units: self.units[name] = other.units[name] if name in other.descriptions: self.descriptions[name] = other.descriptions[name] if name in other.ucds: self.ucds[name] = other.ucds[name] self.description = other.description @docsubst def to_pandas_df(self, column_names=None, selection=None, strings=True, virtual=True, index_name=None, parallel=True, chunk_size=None, array_type=None): """Return a pandas DataFrame containing the ndarray corresponding to the evaluated data If index is given, that column is used for the index of the dataframe. Example >>> df_pandas = df.to_pandas_df(["x", "y", "z"]) >>> df_copy = vaex.from_pandas(df_pandas) :param column_names: list of column names, to export, when None DataFrame.get_column_names(strings=strings, virtual=virtual) is used :param selection: {selection} :param strings: argument passed to DataFrame.get_column_names when column_names is None :param virtual: argument passed to DataFrame.get_column_names when column_names is None :param index_column: if this column is given it is used for the index of the DataFrame :param parallel: {evaluate_parallel} :param chunk_size: {chunk_size} :param array_type: {array_type} :return: pandas.DataFrame object or iterator of """ import pandas as pd column_names = column_names or self.get_column_names(strings=strings, virtual=virtual) column_names = _ensure_strings_from_expressions(column_names) if index_name not in column_names and index_name is not None: column_names = column_names + [index_name] def create_pdf(data): if index_name is not None: index = data.pop(index_name) else: index = None df = pd.DataFrame(data=data, index=index) if index is not None: df.index.name = index_name return df if chunk_size is not None: def iterator(): for i1, i2, chunks in self.evaluate_iterator(column_names, selection=selection, parallel=parallel, chunk_size=chunk_size, array_type=array_type): yield i1, i2, create_pdf(dict(zip(column_names, chunks))) return iterator() else: return create_pdf(self.to_dict(column_names=column_names, selection=selection, parallel=parallel, array_type=array_type)) @docsubst def to_arrow_table(self, column_names=None, selection=None, strings=True, virtual=True, parallel=True, chunk_size=None, reduce_large=False): """Returns an arrow Table object containing the arrays corresponding to the evaluated data :param column_names: list of column names, to export, when None DataFrame.get_column_names(strings=strings, virtual=virtual) is used :param selection: {selection} :param strings: argument passed to DataFrame.get_column_names when column_names is None :param virtual: argument passed to DataFrame.get_column_names when column_names is None :param parallel: {evaluate_parallel} :param chunk_size: {chunk_size} :param bool reduce_large: If possible, cast large_string to normal string :return: pyarrow.Table object or iterator of """ import pyarrow as pa column_names = column_names or self.get_column_names(strings=strings, virtual=virtual) column_names = _ensure_strings_from_expressions(column_names) if chunk_size is not None: def iterator(): for i1, i2, chunks in self.evaluate_iterator(column_names, selection=selection, parallel=parallel, chunk_size=chunk_size): chunks = list(map(vaex.array_types.to_arrow, chunks)) if reduce_large: chunks = list(map(vaex.array_types.arrow_reduce_large, chunks)) yield i1, i2, pa.Table.from_arrays(chunks, column_names) return iterator() else: chunks = self.evaluate(column_names, selection=selection, parallel=parallel) chunks = list(map(vaex.array_types.to_arrow, chunks)) if reduce_large: chunks = list(map(vaex.array_types.arrow_reduce_large, chunks)) return pa.Table.from_arrays(chunks, column_names) @docsubst def to_astropy_table(self, column_names=None, selection=None, strings=True, virtual=True, index=None, parallel=True): """Returns a astropy table object containing the ndarrays corresponding to the evaluated data :param column_names: list of column names, to export, when None DataFrame.get_column_names(strings=strings, virtual=virtual) is used :param selection: {selection} :param strings: argument passed to DataFrame.get_column_names when column_names is None :param virtual: argument passed to DataFrame.get_column_names when column_names is None :param index: if this column is given it is used for the index of the DataFrame :return: astropy.table.Table object """ from astropy.table import Table, Column, MaskedColumn meta = dict() meta["description"] = self.description table = Table(meta=meta) for name, data in self.to_items(column_names=column_names, selection=selection, strings=strings, virtual=virtual, parallel=parallel): if self.is_string(name): # for astropy we convert it to unicode, it seems to ignore object type data = np.array(data).astype('U') meta = dict() if name in self.ucds: meta["ucd"] = self.ucds[name] if np.ma.isMaskedArray(data): cls = MaskedColumn else: cls = Column table[name] = cls(data, unit=self.unit(name), description=self.descriptions.get(name), meta=meta) return table def to_dask_array(self, chunks="auto"): """Lazily expose the DataFrame as a dask.array Example >>> df = vaex.example() >>> A = df[['x', 'y', 'z']].to_dask_array() >>> A dask.array<vaex-df-1f048b40-10ec-11ea-9553, shape=(330000, 3), dtype=float64, chunksize=(330000, 3), chunktype=numpy.ndarray> >>> A+1 dask.array<add, shape=(330000, 3), dtype=float64, chunksize=(330000, 3), chunktype=numpy.ndarray> :param chunks: How to chunk the array, similar to :func:`dask.array.from_array`. :return: :class:`dask.array.Array` object. """ import dask.array as da import uuid dtype = self._dtype chunks = da.core.normalize_chunks(chunks, shape=self.shape, dtype=dtype.numpy) name = 'vaex-df-%s' % str(uuid.uuid1()) def getitem(df, item): return np.array(df.__getitem__(item).to_arrays(parallel=False)).T # broken since https://github.com/dask/dask/pull/7417 if hasattr(da.core, "getem"): dsk = da.core.getem(name, chunks, getitem=getitem, shape=self.shape, dtype=dtype.numpy) dsk[name] = self return da.Array(dsk, name, chunks, dtype=dtype.numpy) else: dsk = da.core.graph_from_arraylike(self, name=name, chunks=chunks, getitem=getitem, shape=self.shape, dtype=dtype.numpy) return da.Array(dsk, name, chunks, dtype=dtype.numpy) def validate_expression(self, expression): """Validate an expression (may throw Exceptions)""" # return self.evaluate(expression, 0, 2) if str(expression) in self.virtual_columns: return if self.is_local() and str(expression) in self.columns: return vars = set(self.get_names(hidden=True)) | {'df'} funcs = set(expression_namespace.keys()) | set(self.functions.keys()) try: return vaex.expresso.validate_expression(expression, vars, funcs) except NameError as e: raise NameError(str(e)) from None def _block_scope(self, i1, i2): variables = {key: self.evaluate_variable(key) for key in self.variables.keys()} return scopes._BlockScope(self, i1, i2, **variables) def select(self, boolean_expression, mode="replace", name="default"): """Select rows based on the boolean_expression, if there was a previous selection, the mode is taken into account. if boolean_expression is None, remove the selection, has_selection() will returns false Note that per DataFrame, multiple selections are possible, and one filter (see :func:`DataFrame.select`). :param str boolean_expression: boolean expression, such as 'x < 0', '(x < 0) || (y > -10)' or None to remove the selection :param str mode: boolean operation to perform with the previous selection, "replace", "and", "or", "xor", "subtract" :return: None """ raise NotImplementedError def add_column(self, name, f_or_array, dtype=None): """Add an in memory array as a column.""" column_position = len(self.column_names) if name in self.get_column_names(): column_position = self.column_names.index(name) renamed = '__' +vaex.utils.find_valid_name(name, used=self.get_column_names()) self._rename(name, renamed) if isinstance(f_or_array, supported_column_types): data = ar = f_or_array # it can be None when we have an 'empty' DataFrameArrays if self._length_original is None: self._length_unfiltered = _len(data) self._length_original = _len(data) self._index_end = self._length_unfiltered if _len(ar) != self.length_original(): if self.filtered: # give a better warning to avoid confusion if len(self) == len(ar): raise ValueError("Array is of length %s, while the length of the DataFrame is %s due to the filtering, the (unfiltered) length is %s." % (len(ar), len(self), self.length_unfiltered())) raise ValueError("array is of length %s, while the length of the DataFrame is %s" % (len(ar), self.length_original())) valid_name = vaex.utils.find_valid_name(name, used=self.get_column_names(hidden=True)) self.columns[valid_name] = ar if valid_name not in self.column_names: self.column_names.insert(column_position, valid_name) else: raise ValueError("functions not yet implemented") # self._save_assign_expression(valid_name, Expression(self, valid_name)) self._initialize_column(valid_name) def _initialize_column(self, name): self._save_assign_expression(name) def _sparse_matrix(self, column): column = _ensure_string_from_expression(column) return self._sparse_matrices.get(column) def add_columns(self, names, columns): from scipy.sparse import csc_matrix, csr_matrix if isinstance(columns, csr_matrix): if len(names) != columns.shape[1]: raise ValueError('number of columns ({}) does not match number of column names ({})'.format(columns.shape[1], len(names))) for i, name in enumerate(names): valid_name = vaex.utils.find_valid_name(name, used=self.get_column_names(hidden=True)) self.columns[valid_name] = ColumnSparse(columns, i) self.column_names.append(valid_name) self._sparse_matrices[valid_name] = columns self._save_assign_expression(valid_name) else: raise ValueError('only scipy.sparse.csr_matrix is supported') def _save_assign_expression(self, name, expression=None): obj = getattr(self, name, None) # it's ok to set it if it does not exist, or we overwrite an older expression if obj is None or isinstance(obj, Expression): if expression is None: expression = name if isinstance(expression, str): expression = vaex.utils.valid_expression(self.get_column_names(hidden=True), expression) expression = Expression(self, expression) setattr(self, name, expression) @_hidden def add_column_healpix(self, name="healpix", longitude="ra", latitude="dec", degrees=True, healpix_order=12, nest=True): """Add a healpix (in memory) column based on a longitude and latitude :param name: Name of column :param longitude: longitude expression :param latitude: latitude expression (astronomical convenction latitude=90 is north pole) :param degrees: If lon/lat are in degrees (default) or radians. :param healpix_order: healpix order, >= 0 :param nest: Nested healpix (default) or ring. """ import healpy as hp if degrees: scale = "*pi/180" else: scale = "" # TODO: multithread this phi = self.evaluate("(%s)%s" % (longitude, scale)) theta = self.evaluate("pi/2-(%s)%s" % (latitude, scale)) hp_index = hp.ang2pix(hp.order2nside(healpix_order), theta, phi, nest=nest) self.add_column("healpix", hp_index) @_hidden def add_virtual_columns_matrix3d(self, x, y, z, xnew, ynew, znew, matrix, matrix_name='deprecated', matrix_is_expression=False, translation=[0, 0, 0], propagate_uncertainties=False): """ :param str x: name of x column :param str y: :param str z: :param str xnew: name of transformed x column :param str ynew: :param str znew: :param list[list] matrix: 2d array or list, with [row,column] order :param str matrix_name: :return: """ m = matrix x, y, z = self._expr(x, y, z) self[xnew] = m[0][0] * x + m[0][1] * y + m[0][2] * z + translation[0] self[ynew] = m[1][0] * x + m[1][1] * y + m[1][2] * z + translation[1] self[znew] = m[2][0] * x + m[2][1] * y + m[2][2] * z + translation[2] if propagate_uncertainties: self.propagate_uncertainties([self[xnew], self[ynew], self[znew]], [x, y, z]) # wrap these with an informative msg # add_virtual_columns_eq2ecl = _requires('astro') # add_virtual_columns_eq2gal = _requires('astro') # add_virtual_columns_distance_from_parallax = _requires('astro') # add_virtual_columns_cartesian_velocities_to_pmvr = _requires('astro') # add_virtual_columns_proper_motion_eq2gal = _requires('astro') # add_virtual_columns_lbrvr_proper_motion2vcartesian = _requires('astro') # add_virtual_columns_equatorial_to_galactic_cartesian = _requires('astro') # add_virtual_columns_celestial = _requires('astro') # add_virtual_columns_proper_motion2vperpendicular = _requires('astro') def _covariance_matrix_guess(self, columns, full=False, as_expression=False): all_column_names = self.get_column_names() columns = _ensure_strings_from_expressions(columns) def _guess(x, y): if x == y: postfixes = ["_error", "_uncertainty", "e", "_e"] prefixes = ["e", "e_"] for postfix in postfixes: if x + postfix in all_column_names: return x + postfix for prefix in prefixes: if prefix + x in all_column_names: return prefix + x if full: raise ValueError("No uncertainty found for %r" % x) else: postfixes = ["_cov", "_covariance"] for postfix in postfixes: if x + "_" + y + postfix in all_column_names: return x + "_" + y + postfix if y + "_" + x + postfix in all_column_names: return y + "_" + x + postfix postfixes = ["_correlation", "_corr"] for postfix in postfixes: if x + "_" + y + postfix in all_column_names: return x + "_" + y + postfix + " * " + _guess(x, x) + " * " + _guess(y, y) if y + "_" + x + postfix in all_column_names: return y + "_" + x + postfix + " * " + _guess(y, y) + " * " + _guess(x, x) if full: raise ValueError("No covariance or correlation found for %r and %r" % (x, y)) return "0" N = len(columns) cov_matrix = [[""] * N for i in range(N)] for i in range(N): for j in range(N): cov = _guess(columns[i], columns[j]) if i == j and cov: cov += "**2" # square the diagnal cov_matrix[i][j] = cov if as_expression: return [[self[k] for k in row] for row in cov_matrix] else: return cov_matrix def _jacobian(self, expressions, variables): expressions = _ensure_strings_from_expressions(expressions) return [[self[expression].expand(stop=[var]).derivative(var) for var in variables] for expression in expressions] def propagate_uncertainties(self, columns, depending_variables=None, cov_matrix='auto', covariance_format="{}_{}_covariance", uncertainty_format="{}_uncertainty"): """Propagates uncertainties (full covariance matrix) for a set of virtual columns. Covariance matrix of the depending variables is guessed by finding columns prefixed by "e" or `"e_"` or postfixed by "_error", "_uncertainty", "e" and `"_e"`. Off diagonals (covariance or correlation) by postfixes with "_correlation" or "_corr" for correlation or "_covariance" or "_cov" for covariances. (Note that x_y_cov = x_e * y_e * x_y_correlation.) Example >>> df = vaex.from_scalars(x=1, y=2, e_x=0.1, e_y=0.2) >>> df["u"] = df.x + df.y >>> df["v"] = np.log10(df.x) >>> df.propagate_uncertainties([df.u, df.v]) >>> df.u_uncertainty, df.v_uncertainty :param columns: list of columns for which to calculate the covariance matrix. :param depending_variables: If not given, it is found out automatically, otherwise a list of columns which have uncertainties. :param cov_matrix: List of list with expressions giving the covariance matrix, in the same order as depending_variables. If 'full' or 'auto', the covariance matrix for the depending_variables will be guessed, where 'full' gives an error if an entry was not found. """ names = _ensure_strings_from_expressions(columns) virtual_columns = self._expr(*columns, always_list=True) if depending_variables is None: depending_variables = set() for expression in virtual_columns: depending_variables |= expression.expand().variables() depending_variables = list(sorted(list(depending_variables))) fs = [self[self.virtual_columns[name]] for name in names] jacobian = self._jacobian(fs, depending_variables) m = len(fs) n = len(depending_variables) # n x n matrix cov_matrix = self._covariance_matrix_guess(depending_variables, full=cov_matrix == "full", as_expression=True) # empty m x m matrix cov_matrix_out = [[self['0'] for __ in range(m)] for __ in range(m)] for i in range(m): for j in range(m): for k in range(n): for l in range(n): if jacobian[i][k].expression == '0' or jacobian[j][l].expression == '0' or cov_matrix[k][l].expression == '0': pass else: cov_matrix_out[i][j] = cov_matrix_out[i][j] + jacobian[i][k] * cov_matrix[k][l] * jacobian[j][l] for i in range(m): for j in range(i + 1): sigma = cov_matrix_out[i][j] sigma = self._expr(vaex.expresso.simplify(_ensure_string_from_expression(sigma))) if i != j: self.add_virtual_column(covariance_format.format(names[i], names[j]), sigma) else: self.add_virtual_column(uncertainty_format.format(names[i]), np.sqrt(sigma)) @_hidden def add_virtual_columns_cartesian_to_polar(self, x="x", y="y", radius_out="r_polar", azimuth_out="phi_polar", propagate_uncertainties=False, radians=False): kwargs = dict(**locals()) del kwargs['self'] return self.geo.cartesian_to_polar(inplace=True, **kwargs) @_hidden def add_virtual_columns_cartesian_velocities_to_spherical(self, x="x", y="y", z="z", vx="vx", vy="vy", vz="vz", vr="vr", vlong="vlong", vlat="vlat", distance=None): kwargs = dict(**locals()) del kwargs['self'] return self.geo.velocity_cartesian2spherical(inplace=True, **kwargs) def _expr(self, *expressions, **kwargs): always_list = kwargs.pop('always_list', False) return self[str(expressions[0])] if len(expressions) == 1 and not always_list else [self[str(k)] for k in expressions] def _selection_expression(self, expression): return vaex.expression.Expression(self, str(expression), _selection=True) @_hidden def add_virtual_columns_cartesian_velocities_to_polar(self, x="x", y="y", vx="vx", radius_polar=None, vy="vy", vr_out="vr_polar", vazimuth_out="vphi_polar", propagate_uncertainties=False,): kwargs = dict(**locals()) del kwargs['self'] return self.geo.velocity_cartesian2polar(inplace=True, **kwargs) @_hidden def add_virtual_columns_polar_velocities_to_cartesian(self, x='x', y='y', azimuth=None, vr='vr_polar', vazimuth='vphi_polar', vx_out='vx', vy_out='vy', propagate_uncertainties=False): kwargs = dict(**locals()) del kwargs['self'] return self.geo.velocity_polar2cartesian(inplace=True, **kwargs) @_hidden def add_virtual_columns_rotation(self, x, y, xnew, ynew, angle_degrees, propagate_uncertainties=False): kwargs = dict(**locals()) del kwargs['self'] return self.geo.rotation_2d(inplace=True, **kwargs) @docsubst @_hidden def add_virtual_columns_spherical_to_cartesian(self, alpha, delta, distance, xname="x", yname="y", zname="z", propagate_uncertainties=False, center=[0, 0, 0], radians=False): kwargs = dict(**locals()) del kwargs['self'] return self.geo.spherical2cartesian(inplace=True, **kwargs) @_hidden def add_virtual_columns_cartesian_to_spherical(self, x="x", y="y", z="z", alpha="l", delta="b", distance="distance", radians=False, center=None, center_name="solar_position"): kwargs = dict(**locals()) del kwargs['self'] return self.geo.cartesian2spherical(inplace=True, **kwargs) @_hidden def add_virtual_columns_aitoff(self, alpha, delta, x, y, radians=True): kwargs = dict(**locals()) del kwargs['self'] return self.geo.project_aitoff(inplace=True, **kwargs) @_hidden def add_virtual_columns_projection_gnomic(self, alpha, delta, alpha0=0, delta0=0, x="x", y="y", radians=False, postfix=""): kwargs = dict(**locals()) del kwargs['self'] return self.geo.project_gnomic(inplace=True, **kwargs) def add_function(self, name, f, unique=False): name = vaex.utils.find_valid_name(name, used=[] if not unique else self.functions.keys()) function = vaex.expression.Function(self, name, f) self.functions[name] = function return function def add_virtual_column(self, name, expression, unique=False): """Add a virtual column to the DataFrame. Example: >>> df.add_virtual_column("r", "sqrt(x**2 + y**2 + z**2)") >>> df.select("r < 10") :param: str name: name of virtual column :param: expression: expression for the column :param str unique: if name is already used, make it unique by adding a postfix, e.g. _1, or _2 """ if isinstance(expression, Expression): if expression.df is not self: expression = expression.copy(self) column_position = len(self.column_names) # if the current name is an existing column name.... if name in self.get_column_names(hidden=True): column_position = self.column_names.index(name) renamed = vaex.utils.find_valid_name('__' +name, used=self.get_column_names(hidden=True)) # we rewrite all existing expressions (including the passed down expression argument) self._rename(name, renamed) expression = _ensure_string_from_expression(expression) if vaex.utils.find_valid_name(name) != name: # if we have to rewrite the name, we need to make it unique unique = True valid_name = vaex.utils.find_valid_name(name, used=None if not unique else self.get_column_names(hidden=True)) self.virtual_columns[valid_name] = expression self._virtual_expressions[valid_name] = Expression(self, expression) if name not in self.column_names: self.column_names.insert(column_position, valid_name) self._save_assign_expression(valid_name) self.signal_column_changed.emit(self, valid_name, "add") def rename(self, name, new_name, unique=False): """Renames a column or variable, and rewrite expressions such that they refer to the new name""" if name == new_name: return new_name = vaex.utils.find_valid_name(new_name, used=None if not unique else self.get_column_names(hidden=True)) self._rename(name, new_name, rename_meta_data=True) return new_name def _rename(self, old, new, rename_meta_data=False): is_variable = False is_function = False if old in self.variables: self.variables[new] = self.variables.pop(old) is_variable = True if old in self.functions: self.functions[new] = self.functions.pop(old) is_function = True elif old in self.virtual_columns: # renaming a column should not change the internal order, otherwise virtual # columns do not resolve (it will reference an unknown column) self.virtual_columns = vaex.utils.dict_replace_key(self.virtual_columns, old, new) self._virtual_expressions = vaex.utils.dict_replace_key(self._virtual_expressions, old, new) elif self.is_local() and old in self.columns: # we only have to do this locally # if we don't do this locally, we still store this info # in self._renamed_columns, so it will happen at the server self.dataset = self.dataset.renamed({old: new}) if rename_meta_data: for d in [self.ucds, self.units, self.descriptions]: if old in d: d[new] = d[old] del d[old] for key, value in self.selection_histories.items(): self.selection_histories[key] = list([k if k is None else k._rename(self, old, new) for k in value]) if not (is_variable or is_function): if new not in self.virtual_columns: self._renamed_columns.append((old, new)) self.column_names[self.column_names.index(old)] = new if hasattr(self, old): if isinstance(getattr(self, old), Expression): try: delattr(self, old) except: pass self._save_assign_expression(new) existing_expressions = [k() for k in self._expressions] existing_expressions = [k for k in existing_expressions if k is not None] for expression in existing_expressions: expression._rename(old, new, inplace=True) self.virtual_columns = {k:self._virtual_expressions[k].expression for k, v in self.virtual_columns.items()} def delete_virtual_column(self, name): """Deletes a virtual column from a DataFrame.""" self.drop(name, inplace=True) self.signal_column_changed.emit(self, name, "delete") def add_variable(self, name, expression, overwrite=True, unique=True): """Add a variable to a DataFrame. A variable may refer to other variables, and virtual columns and expression may refer to variables. Example >>> df.add_variable('center', 0) >>> df.add_virtual_column('x_prime', 'x-center') >>> df.select('x_prime < 0') :param: str name: name of virtual varible :param: expression: expression for the variable """ if unique or overwrite or name not in self.variables: existing_names = self.get_column_names(virtual=False) + list(self.variables.keys()) name = vaex.utils.find_valid_name(name, used=[] if not unique else existing_names) self.variables[name] = expression self.signal_variable_changed.emit(self, name, "add") if unique: return name def delete_variable(self, name): """Deletes a variable from a DataFrame.""" del self.variables[name] self.signal_variable_changed.emit(self, name, "delete") def info(self, description=True): from IPython import display self._output_css() display.display(display.HTML(self._info(description=description))) def _info(self, description=True): parts = ["""<div><h2>{}</h2> <b>rows</b>: {:,}</div>""".format(self.name, len(self))] if hasattr(self, 'path'): parts += ["""<div><b>path</b>: <i>%s</i></div>""" % (self.path)] if self.description: parts += ["""<div><b>Description</b>: {}</div>""".format(self.description)] parts += ["<h2>Columns:</h2>"] parts += ["<table class='table-striped'>"] parts += ["<thead><tr>"] for header in "column type unit description expression".split(): if description or header != "description": parts += ["<th>%s</th>" % header] parts += ["</tr></thead>"] for name in self.get_column_names(): parts += ["<tr>"] parts += ["<td>%s</td>" % name] virtual = name in self.virtual_columns if not virtual: dtype = str(self.data_type(name)) if self.data_type(name) != str else 'str' else: dtype = "</i>virtual column</i>" parts += ["<td>%s</td>" % dtype] units = self.unit(name) units = units.to_string("latex_inline") if units else "" parts += ["<td>%s</td>" % units] if description: parts += ["<td ><pre>%s</pre></td>" % self.descriptions.get(name, "")] if virtual: parts += ["<td><code>%s</code></td>" % self.virtual_columns[name]] else: parts += ["<td></td>"] parts += ["</tr>"] parts += "</table>" ignore_list = 'pi e km_in_au seconds_per_year'.split() variable_names = [name for name in self.variables.keys() if name not in ignore_list] if variable_names: parts += ["<h2>Variables:</h2>"] parts += ["<table class='table-striped'>"] parts += ["<thead><tr>"] for header in "variable type unit description expression".split(): if description or header != "description": parts += ["<th>%s</th>" % header] parts += ["</tr></thead>"] for name in variable_names: parts += ["<tr>"] parts += ["<td>%s</td>" % name] parts += ["<td>%r</td>" % type] units = self.unit(name) units = units.to_string("latex_inline") if units else "" parts += ["<td>%s</td>" % units] if description: parts += ["<td ><pre>%s</pre></td>" % self.descriptions.get(name, "")] parts += ["<td><code>%s</code></td>" % (self.variables[name], )] parts += ["</tr>"] parts += "</table>" return "".join(parts) + "<h2>Data:</h2>" + self._head_and_tail_table() def head(self, n=10): """Return a shallow copy a DataFrame with the first n rows.""" return self[:min(n, len(self))] def tail(self, n=10): """Return a shallow copy a DataFrame with the last n rows.""" N = len(self) # self.cat(i1=max(0, N-n), i2=min(len(self), N)) return self[max(0, N - n):min(len(self), N)] def _head_and_tail_table(self, n=None, format='html'): n = n or vaex.settings.display.max_rows N = _len(self) if N <= n: return self._as_table(0, N, format=format) else: return self._as_table(0, math.ceil(n / 2), N - math.floor(n / 2), N, format=format) def head_and_tail_print(self, n=5): """Display the first and last n elements of a DataFrame.""" from IPython import display display.display(display.HTML(self._head_and_tail_table(n))) def describe(self, strings=True, virtual=True, selection=None): """Give a description of the DataFrame. >>> import vaex >>> df = vaex.example()[['x', 'y', 'z']] >>> df.describe() x y z dtype float64 float64 float64 count 330000 330000 330000 missing 0 0 0 mean -0.0671315 -0.0535899 0.0169582 std 7.31746 7.78605 5.05521 min -128.294 -71.5524 -44.3342 max 271.366 146.466 50.7185 >>> df.describe(selection=df.x > 0) x y z dtype float64 float64 float64 count 164060 164060 164060 missing 165940 165940 165940 mean 5.13572 -0.486786 -0.0868073 std 5.18701 7.61621 5.02831 min 1.51635e-05 -71.5524 -44.3342 max 271.366 78.0724 40.2191 :param bool strings: Describe string columns or not :param bool virtual: Describe virtual columns or not :param selection: Optional selection to use. :return: Pandas dataframe """ import pandas as pd N = len(self) columns = {} for feature in self.get_column_names(strings=strings, virtual=virtual)[:]: data_type = self.data_type(feature) if data_type == str: count = self.count(feature, selection=selection, delay=True) self.execute() count = count.get() columns[feature] = ((data_type, count, N-count, '--', '--', '--', '--')) elif data_type.kind in 'SU': # TODO: this blocks is the same as the string block above, can we avoid SU types? count = self.count(feature, selection=selection, delay=True) self.execute() count = count.get() columns[feature] = ((data_type, count, N-count, '--', '--', '--', '--')) elif data_type.kind in 'O': # this will also properly count NaN-like objects like NaT count_na = self[feature].isna().astype('int').sum(delay=True) self.execute() count_na = count_na.get() columns[feature] = ((data_type, N-count_na, count_na, '--', '--', '--', '--')) elif data_type.is_primitive or data_type.is_temporal: mean = self.mean(feature, selection=selection, delay=True) std = self.std(feature, selection=selection, delay=True) minmax = self.minmax(feature, selection=selection, delay=True) if data_type.is_datetime: # this path tests using isna, which test for nat count_na = self[feature].isna().astype('int').sum(delay=True) else: count = self.count(feature, selection=selection, delay=True) self.execute() if data_type.is_datetime: count_na, mean, std, minmax = count_na.get(), mean.get(), std.get(), minmax.get() count = N - int(count_na) else: count, mean, std, minmax = count.get(), mean.get(), std.get(), minmax.get() count = int(count) columns[feature] = ((data_type, count, N-count, mean, std, minmax[0], minmax[1])) else: raise NotImplementedError(f'Did not implement describe for data type {data_type}') return pd.DataFrame(data=columns, index=['data_type', 'count', 'NA', 'mean', 'std', 'min', 'max']) def cat(self, i1, i2, format='html'): """Display the DataFrame from row i1 till i2 For format, see https://pypi.org/project/tabulate/ :param int i1: Start row :param int i2: End row. :param str format: Format to use, e.g. 'html', 'plain', 'latex' """ from IPython import display if format == 'html': output = self._as_html_table(i1, i2) display.display(display.HTML(output)) else: output = self._as_table(i1, i2, format=format) print(output) def _as_table(self, i1, i2, j1=None, j2=None, format='html', ellipsis="..."): from .formatting import _format_value parts = [] # """<div>%s (length=%d)</div>""" % (self.name, len(self))] parts += ["<table class='table-striped'>"] # we need to get the underlying names since we use df.evaluate column_names = self.get_column_names() max_columns = vaex.settings.display.max_columns if (max_columns is not None) and (max_columns > 0): if max_columns < len(column_names): columns_sliced = math.ceil(max_columns/2) column_names = column_names[:columns_sliced] + column_names[-math.floor(max_columns/2):] else: columns_sliced = None values_list = [] values_list.append(['#', []]) # parts += ["<thead><tr>"] for i, name in enumerate(column_names): if columns_sliced == i: values_list.append([ellipsis, []]) values_list.append([name, []]) # parts += ["<th>%s</th>" % name] # parts += ["</tr></thead>"] def table_part(k1, k2, parts): N = k2 - k1 # slicing will invoke .extract which will make the evaluation # much quicker df = self[k1:k2] try: values = dict(zip(column_names, df.evaluate(column_names))) except: values = {} for i, name in enumerate(column_names): try: values[name] = df.evaluate(name) except: values[name] = ["error"] * (N) logger.exception('error evaluating: %s at rows %i-%i' % (name, k1, k2)) for i in range(k2 - k1): # parts += ["<tr>"] # parts += ["<td><i style='opacity: 0.6'>{:,}</i></td>".format(i + k1)] if format == 'html': value = "<i style='opacity: 0.6'>{:,}</i>".format(i + k1) else: value = "{:,}".format(i + k1) values_list[0][1].append(value) for j, name in enumerate(column_names): column_index = j if columns_sliced == j: values_list[column_index+1][1].append(ellipsis) if columns_sliced is not None and j >= columns_sliced: column_index += 1 # skip over the slice/ellipsis value = values[name][i] value = _format_value(value) values_list[column_index+1][1].append(value) # parts += ["</tr>"] # return values_list if i2 - i1 > 0: parts = table_part(i1, i2, parts) if j1 is not None and j2 is not None: values_list[0][1].append(ellipsis) for i in range(len(column_names)): # parts += ["<td>...</td>"] values_list[i+1][1].append(ellipsis) # parts = table_part(j1, j2, parts) table_part(j1, j2, parts) else: for header, values in values_list: values.append(None) # parts += "</table>" # html = "".join(parts) # return html values_list = dict(values_list) # print(values_list) import tabulate table_text = str(tabulate.tabulate(values_list, headers="keys", tablefmt=format)) # Tabulate 0.8.7+ escapes html :() table_text = table_text.replace('&lt;i style=&#x27;opacity: 0.6&#x27;&gt;', "<i style='opacity: 0.6'>") table_text = table_text.replace('&lt;/i&gt;', "</i>") if i2 - i1 == 0: if self._length_unfiltered != len(self): footer_text = 'No rows to display (because of filtering).' else: footer_text = 'No rows to display.' if format == 'html': table_text += f'<i>{footer_text}</i>' if format == 'plain': table_text += f'\n{footer_text}' return table_text def _as_html_table(self, i1, i2, j1=None, j2=None): # TODO: this method can be replaced by _as_table from .formatting import _format_value parts = [] # """<div>%s (length=%d)</div>""" % (self.name, len(self))] parts += ["<table class='table-striped'>"] column_names = self.get_column_names() parts += ["<thead><tr>"] for name in ["#"] + column_names: parts += ["<th>%s</th>" % name] parts += ["</tr></thead>"] def table_part(k1, k2, parts): data_parts = {} N = k2 - k1 for name in column_names: try: data_parts[name] = self.evaluate(name, i1=k1, i2=k2) except: data_parts[name] = ["error"] * (N) logger.exception('error evaluating: %s at rows %i-%i' % (name, k1, k2)) for i in range(k2 - k1): parts += ["<tr>"] parts += ["<td><i style='opacity: 0.6'>{:,}</i></td>".format(i + k1)] for name in column_names: value = data_parts[name][i] value = _format_value(value) parts += ["<td>%r</td>" % value] parts += ["</tr>"] return parts parts = table_part(i1, i2, parts) if j1 is not None and j2 is not None: for i in range(len(column_names) + 1): parts += ["<td>...</td>"] parts = table_part(j1, j2, parts) parts += "</table>" html = "".join(parts) return html def _output_css(self): css = """.vaex-description pre { max-width : 450px; white-space : nowrap; overflow : hidden; text-overflow: ellipsis; } .vex-description pre:hover { max-width : initial; white-space: pre; }""" from IPython import display style = "<style>%s</style>" % css display.display(display.HTML(style)) def _repr_mimebundle_(self, include=None, exclude=None, **kwargs): # TODO: optimize, since we use the same data in both versions # TODO: include latex version return {'text/html':self._head_and_tail_table(format='html'), 'text/plain': self._head_and_tail_table(format='plain')} def _repr_html_(self): """Representation for Jupyter.""" self._output_css() return self._head_and_tail_table() def __str__(self): return self._head_and_tail_table(format='plain') if not _DEBUG: def __repr__(self): return self._head_and_tail_table(format='plain') def __current_sequence_index(self): """TODO""" return 0 def has_current_row(self): """Returns True/False if there currently is a picked row.""" return self._current_row is not None def get_current_row(self): """Individual rows can be 'picked', this is the index (integer) of the current row, or None there is nothing picked.""" return self._current_row def set_current_row(self, value): """Set the current row, and emit the signal signal_pick.""" if (value is not None) and ((value < 0) or (value >= len(self))): raise IndexError("index %d out of range [0,%d]" % (value, len(self))) self._current_row = value self.signal_pick.emit(self, value) def __has_snapshots(self): # currenly disabled return False def column_count(self, hidden=False): """Returns the number of columns (including virtual columns). :param bool hidden: If True, include hidden columns in the tally :returns: Number of columns in the DataFrame """ return len(self.get_column_names(hidden=hidden)) def get_names(self, hidden=False): """Return a list of column names and variable names.""" names = self.get_column_names(hidden=hidden) return names +\ [k for k in self.variables.keys() if not hidden or not k.startswith('__')] +\ [k for k in self.functions.keys() if not hidden or not k.startswith('__')] def get_column_names(self, virtual=True, strings=True, hidden=False, regex=None): """Return a list of column names Example: >>> import vaex >>> df = vaex.from_scalars(x=1, x2=2, y=3, s='string') >>> df['r'] = (df.x**2 + df.y**2)**2 >>> df.get_column_names() ['x', 'x2', 'y', 's', 'r'] >>> df.get_column_names(virtual=False) ['x', 'x2', 'y', 's'] >>> df.get_column_names(regex='x.*') ['x', 'x2'] :param virtual: If False, skip virtual columns :param hidden: If False, skip hidden columns :param strings: If False, skip string columns :param regex: Only return column names matching the (optional) regular expression :param alias: Return the alias (True) or internal name (False). :rtype: list of str """ def column_filter(name): '''Return True if column with specified name should be returned''' if regex and not re.match(regex, name): return False if not virtual and name in self.virtual_columns: return False if not strings and self.is_string(name): return False if not hidden and name.startswith('__'): return False return True if hidden and virtual and regex is None and strings is True: return list(self.column_names) # quick path if not hidden and virtual and regex is None and strings is True: return [k for k in self.column_names if not k.startswith('__')] # also a quick path return [name for name in self.column_names if column_filter(name)] def __bool__(self): return True # we are always true :) otherwise Python might call __len__, which can be expensive def __len__(self): """Returns the number of rows in the DataFrame (filtering applied).""" if not self.filtered: return self._length_unfiltered else: if self._cached_filtered_length is None: self._cached_filtered_length = int(self.count()) return self._cached_filtered_length def selected_length(self): """Returns the number of rows that are selected.""" raise NotImplementedError def length_original(self): """the full length of the DataFrame, independent what active_fraction is, or filtering. This is the real length of the underlying ndarrays.""" return self._length_original def length_unfiltered(self): """The length of the arrays that should be considered (respecting active range), but without filtering.""" return self._length_unfiltered def active_length(self): return self._length_unfiltered def get_active_fraction(self): """Value in the range (0, 1], to work only with a subset of rows. """ return self._active_fraction def set_active_fraction(self, value): """Sets the active_fraction, set picked row to None, and remove selection. TODO: we may be able to keep the selection, if we keep the expression, and also the picked row """ if value != self._active_fraction: self._active_fraction = value # self._fraction_length = int(self._length * self._active_fraction) self.select(None) self.set_current_row(None) self._length_unfiltered = int(round(self._length_original * self._active_fraction)) self._cached_filtered_length = None self._filter_filled = False self._index_start = 0 self._index_end = self._length_unfiltered self.signal_active_fraction_changed.emit(self, value) def get_active_range(self): return self._index_start, self._index_end def set_active_range(self, i1, i2): """Sets the active_fraction, set picked row to None, and remove selection. TODO: we may be able to keep the selection, if we keep the expression, and also the picked row """ # logger.debug("set active range to: %r", (i1, i2)) self._active_fraction = (i2 - i1) / float(self.length_original()) # self._fraction_length = int(self._length * self._active_fraction) self._index_start = i1 self._index_end = i2 self.select(None) self.set_current_row(None) self._length_unfiltered = i2 - i1 if self.filtered: mask = self._selection_masks[FILTER_SELECTION_NAME] if not mask.view(i1, i2).is_dirty(): self._cached_filtered_length = mask.view(i1, i2).count() else: self._cached_filtered_length = None self._filter_filled = False self.signal_active_fraction_changed.emit(self, self._active_fraction) @docsubst def trim(self, inplace=False): '''Return a DataFrame, where all columns are 'trimmed' by the active range. For the returned DataFrame, df.get_active_range() returns (0, df.length_original()). {note_copy} :param inplace: {inplace} :rtype: DataFrame ''' df = self if inplace else self.copy() if self._index_start == 0 and self._index_end == self._length_original: return df df.dataset = self.dataset[self._index_start:self._index_end] if df.filtered: # we're gonna copy the mask from our parent parent_mask = self._selection_masks[FILTER_SELECTION_NAME].view(self._index_start, self._index_end) mask = df._selection_masks[FILTER_SELECTION_NAME] np.copyto(np.asarray(mask), np.asarray(parent_mask)) selection = df.get_selection(FILTER_SELECTION_NAME) if not mask.is_dirty(): df._cached_filtered_length = mask.count() cache = df._selection_mask_caches[FILTER_SELECTION_NAME] assert not cache chunk_size = self.executor.chunk_size_for(mask.length) for i in range(vaex.utils.div_ceil(mask.length, chunk_size)): i1 = i * chunk_size i2 = min(mask.length, (i + 1) * chunk_size) key = (i1, i2) sub_mask = mask.view(i1, i2) sub_mask_array = np.asarray(sub_mask) cache[key] = selection, sub_mask_array else: df._cached_filtered_length = None df._filter_filled = False return df @docsubst def take(self, indices, filtered=True, dropfilter=True): '''Returns a DataFrame containing only rows indexed by indices {note_copy} Example: >>> import vaex, numpy as np >>> df = vaex.from_arrays(s=np.array(['a', 'b', 'c', 'd']), x=np.arange(1,5)) >>> df.take([0,2]) # s x 0 a 1 1 c 3 :param indices: sequence (list or numpy array) with row numbers :param filtered: (for internal use) The indices refer to the filtered data. :param dropfilter: (for internal use) Drop the filter, set to False when indices refer to unfiltered, but may contain rows that still need to be filtered out. :return: DataFrame which is a shallow copy of the original data. :rtype: DataFrame ''' df_trimmed = self.trim() df = df_trimmed.copy() indices = np.asarray(indices) if df.filtered and filtered: # we translate the indices that refer to filters row indices to # indices of the unfiltered row indices df._fill_filter_mask() max_index = indices.max() mask = df._selection_masks[FILTER_SELECTION_NAME] filtered_indices = mask.first(max_index+1) indices = filtered_indices[indices] df.dataset = df.dataset.take(indices) if dropfilter: # if the indices refer to the filtered rows, we can discard the # filter in the final dataframe df.set_selection(None, name=FILTER_SELECTION_NAME) return df @docsubst def extract(self): '''Return a DataFrame containing only the filtered rows. {note_copy} The resulting DataFrame may be more efficient to work with when the original DataFrame is heavily filtered (contains just a small number of rows). If no filtering is applied, it returns a trimmed view. For the returned df, len(df) == df.length_original() == df.length_unfiltered() :rtype: DataFrame ''' df = self.trim() if df.filtered: df._push_down_filter() df._invalidate_caches() return df def _push_down_filter(self): '''Push the filter down the dataset layer''' self._fill_filter_mask() # make sure the mask is filled mask = self._selection_masks[FILTER_SELECTION_NAME] mask = np.asarray(mask) # indices = mask.first(len(self)) # assert len(indices) == len(self) selection = self.get_selection(FILTER_SELECTION_NAME) from .dataset import DatasetFiltered self.set_selection(None, name=FILTER_SELECTION_NAME) self.dataset = DatasetFiltered(self.dataset, mask, state=self.state_get(skip=[self.dataset]), selection=selection) @docsubst def shuffle(self, random_state=None): '''Shuffle order of rows (equivalent to df.sample(frac=1)) {note_copy} Example: >>> import vaex, numpy as np >>> df = vaex.from_arrays(s=np.array(['a', 'b', 'c']), x=np.arange(1,4)) >>> df # s x 0 a 1 1 b 2 2 c 3 >>> df.shuffle(random_state=42) # s x 0 a 1 1 b 2 2 c 3 :param int or RandomState: {random_state} :return: {return_shallow_copy} :rtype: DataFrame ''' return self.sample(frac=1, random_state=random_state) @docsubst def sample(self, n=None, frac=None, replace=False, weights=None, random_state=None): '''Returns a DataFrame with a random set of rows {note_copy} Provide either n or frac. Example: >>> import vaex, numpy as np >>> df = vaex.from_arrays(s=np.array(['a', 'b', 'c', 'd']), x=np.arange(1,5)) >>> df # s x 0 a 1 1 b 2 2 c 3 3 d 4 >>> df.sample(n=2, random_state=42) # 2 random rows, fixed seed # s x 0 b 2 1 d 4 >>> df.sample(frac=1, random_state=42) # 'shuffling' # s x 0 c 3 1 a 1 2 d 4 3 b 2 >>> df.sample(frac=1, replace=True, random_state=42) # useful for bootstrap (may contain repeated samples) # s x 0 d 4 1 a 1 2 a 1 3 d 4 :param int n: number of samples to take (default 1 if frac is None) :param float frac: fractional number of takes to take :param bool replace: If true, a row may be drawn multiple times :param str or expression weights: (unnormalized) probability that a row can be drawn :param int or RandomState: {random_state} :return: {return_shallow_copy} :rtype: DataFrame ''' self = self.extract() if type(random_state) == int or random_state is None: random_state = np.random.RandomState(seed=random_state) if n is None and frac is None: n = 1 elif frac is not None: n = int(round(frac * len(self))) weights_values = None if weights is not None: weights_values = self.evaluate(weights) weights_values = weights_values / self.sum(weights) indices = random_state.choice(len(self), n, replace=replace, p=weights_values) return self.take(indices) @docsubst @vaex.utils.gen_to_list def split_random(self, into, random_state=None): '''Returns a list containing random portions of the DataFrame. {note_copy} Example: >>> import vaex, import numpy as np >>> np.random.seed(111) >>> df = vaex.from_arrays(x = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]) >>> for dfs in df.split_random(into=0.3, random_state=42): ... print(dfs.x.values) ... [8 1 5] [0 7 2 9 4 3 6] >>> for split in df.split_random(into=[0.2, 0.3, 0.5], random_state=42): ... print(dfs.x.values) [8 1] [5 0 7] [2 9 4 3 6] :param int/float/list into: If float will split the DataFrame in two, the first of which will have a relative length as specified by this parameter. When a list, will split into as many portions as elements in the list, where each element defines the relative length of that portion. Note that such a list of fractions will always be re-normalized to 1. When an int, split DataFrame into n dataframes of equal length (last one may deviate), if len(df) < n, it will return len(df) DataFrames. :param int or RandomState: {random_state} :return: A list of DataFrames. :rtype: list ''' self = self.extract() if type(random_state) == int or random_state is None: random_state = np.random.RandomState(seed=random_state) indices = random_state.choice(len(self), len(self), replace=False) return self.take(indices).split(into) @docsubst @vaex.utils.gen_to_list def split(self, into=None): '''Returns a list containing ordered subsets of the DataFrame. {note_copy} Example: >>> import vaex >>> df = vaex.from_arrays(x = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]) >>> for dfs in df.split(into=0.3): ... print(dfs.x.values) ... [0 1 3] [3 4 5 6 7 8 9] >>> for split in df.split(into=[0.2, 0.3, 0.5]): ... print(dfs.x.values) [0 1] [2 3 4] [5 6 7 8 9] :param int/float/list into: If float will split the DataFrame in two, the first of which will have a relative length as specified by this parameter. When a list, will split into as many portions as elements in the list, where each element defines the relative length of that portion. Note that such a list of fractions will always be re-normalized to 1. When an int, split DataFrame into n dataframes of equal length (last one may deviate), if len(df) < n, it will return len(df) DataFrames. ''' self = self.extract() if isinstance(into, numbers.Integral): step = max(1, vaex.utils.div_ceil(len(self), into)) i1 = 0 i2 = step while i1 < len(self): i2 = min(len(self), i2) yield self[i1:i2] i1, i2 = i2, i2 + step return if _issequence(into): # make sure it is normalized total = sum(into) into = [k / total for k in into] else: assert into <= 1, "when float, `into` should be <= 1" assert into > 0, "`into` must be > 0." into = [into, 1 - into] offsets = np.round(np.cumsum(into) * len(self)).astype(np.int64) start = 0 for offset in offsets: yield self[start:offset] start = offset @docsubst def sort(self, by, ascending=True): '''Return a sorted DataFrame, sorted by the expression 'by'. Both 'by' and 'ascending' arguments can be lists. Note that missing/nan/NA values will always be pushed to the end, no matter the sorting order. {note_copy} {note_filter} Example: >>> import vaex, numpy as np >>> df = vaex.from_arrays(s=np.array(['a', 'b', 'c', 'd']), x=np.arange(1,5)) >>> df['y'] = (df.x-1.8)**2 >>> df # s x y 0 a 1 0.64 1 b 2 0.04 2 c 3 1.44 3 d 4 4.84 >>> df.sort('y', ascending=False) # Note: passing '(x-1.8)**2' gives the same result # s x y 0 d 4 4.84 1 c 3 1.44 2 a 1 0.64 3 b 2 0.04 :param str or expression or list of str/expressions by: expression to sort by. :param bool or list of bools ascending: ascending (default, True) or descending (False). ''' self = self.trim() # Ensure "by" is in the proper format by = vaex.utils._ensure_list(by) by = vaex.utils._ensure_strings_from_expressions(by) # Ensure "ascending is in the proper format" if isinstance(ascending, list): assert len(ascending) == len(by), 'If "ascending" is a list, it must have the same number of elements as "by".' else: ascending = vaex.utils._ensure_list(ascending) * len(by) sort_keys = [(key, 'ascending') if order is True else (key, 'descending') for key, order in zip(by, ascending)] pa_table = self[by].to_arrow_table() indices = pa.compute.sort_indices(pa_table, sort_keys=sort_keys) # if we don't cast to int64, we get uint64 scalars, which when adding numbers to will auto case to float (numpy) indices = vaex.array_types.to_numpy(indices).astype('int64') return self.take(indices) @docsubst def diff(self, periods=1, column=None, fill_value=None, trim=False, inplace=False, reverse=False): """Calculate the difference between the current row and the row offset by periods :param int periods: Which row to take the difference with :param str or list[str] column: Column or list of columns to use (default is all). :param fill_value: Value to use instead of missing values. :param bool trim: Do not include rows that would otherwise have missing values :param bool reverse: When true, calculate `row[periods] - row[current]` :param inplace: {inplace} """ df = self.trim(inplace=inplace) if column is None: columns = self.get_column_names() else: if isinstance(column, (list, tuple)): columns = column else: columns = [column] originals = {} for column in columns: new_name = df._find_valid_name(f'__{column}_original') df[new_name] = df[column] originals[column] = new_name df = df.shift(periods, columns, fill_value=fill_value, trim=trim, inplace=inplace) for column in columns: if reverse: df[column] = df[column] - df[originals[column]] else: df[column] = df[originals[column]] - df[column] return df @docsubst def shift(self, periods, column=None, fill_value=None, trim=False, inplace=False): """Shift a column or multiple columns by `periods` amounts of rows. :param int periods: Shift column forward (when positive) or backwards (when negative) :param str or list[str] column: Column or list of columns to shift (default is all). :param fill_value: Value to use instead of missing values. :param bool trim: Do not include rows that would otherwise have missing values :param inplace: {inplace} """ df = self.trim(inplace=inplace) if df.filtered: df._push_down_filter() from .shift import DatasetShifted # we want to shows these shifted if column is not None: columns = set(column) if _issequence(column) else {column} else: columns = set(df.get_column_names()) columns_all = set(df.get_column_names(hidden=True)) # these columns we do NOT want to shift, because we didn't ask it # or because we depend on them (virtual column) columns_keep = columns_all - columns columns_keep |= df._depending_columns(columns_keep, check_filter=False) # TODO: remove filter check columns_shift = columns.copy() columns_shift |= df._depending_columns(columns) virtual_columns = df.virtual_columns.copy() # these are the columns we want to shift, but *also* want to keep the original columns_conflict = columns_keep & columns_shift column_shift_mapping = {} # we use this dataframe for tracking virtual columns when renaming df_shifted = df.copy() shifted_names = {} unshifted_names = {} for name in columns_shift: if name in columns_conflict: # we want to have two columns, an unshifted and shifted # rename the current to unshifted unshifted_name = df.rename(name, f'__{name}_unshifted', unique=True) unshifted_names[name] = unshifted_name # now make a shifted one shifted_name = f'__{name}_shifted' shifted_name = vaex.utils.find_valid_name(shifted_name, used=df.get_column_names(hidden=True)) shifted_names[name] = shifted_name if name not in virtual_columns: # if not virtual, we let the dataset layer handle it column_shift_mapping[unshifted_name] = shifted_name df.column_names.append(shifted_name) # otherwise we can later on copy the virtual columns from this df df_shifted.rename(name, shifted_name) else: if name not in virtual_columns: # easy case, just shift column_shift_mapping[name] = name # now that we renamed columns into _shifted/_unshifted we # restore the dataframe with the real column names for name in columns_shift: if name in columns_conflict: if name in virtual_columns: if name in columns: df.add_virtual_column(name, df_shifted.virtual_columns[shifted_names[name]]) else: df.add_virtual_column(name, unshifted_names[name]) else: if name in columns: df.add_virtual_column(name, shifted_names[name]) else: df.add_virtual_column(name, unshifted_names[name]) else: if name in virtual_columns: df.virtual_columns[name] = df_shifted.virtual_columns[name] df._virtual_expressions[name] = Expression(df, df.virtual_columns[name]) if _issequence(periods): if len(periods) != 2: raise ValueError(f'periods should be a int or a tuple of ints, not {periods}') start, end = periods else: start = end = periods dataset = DatasetShifted(original=df.dataset, start=start, end=end, column_mapping=column_shift_mapping, fill_value=fill_value) if trim: # assert start == end slice_start = 0 slice_end = dataset.row_count if start > 0: slice_start = start elif start < 0: slice_end = dataset.row_count + start if end != start: if end > start: slice_end -= end -1 dataset = dataset.slice(slice_start, slice_end) df.dataset = dataset for name in df.dataset: assert name in df.column_names, f"oops, {name} in dataset, but not in column_names" for name in df.column_names: if name not in df.dataset: assert name in df.virtual_columns return df @docsubst def fillna(self, value, column_names=None, prefix='__original_', inplace=False): '''Return a DataFrame, where missing values/NaN are filled with 'value'. The original columns will be renamed, and by default they will be hidden columns. No data is lost. {note_copy} {note_filter} Example: >>> import vaex >>> import numpy as np >>> x = np.array([3, 1, np.nan, 10, np.nan]) >>> df = vaex.from_arrays(x=x) >>> df_filled = df.fillna(value=-1, column_names=['x']) >>> df_filled # x 0 3 1 1 2 -1 3 10 4 -1 :param float value: The value to use for filling nan or masked values. :param bool fill_na: If True, fill np.nan values with `value`. :param bool fill_masked: If True, fill masked values with `values`. :param list column_names: List of column names in which to fill missing values. :param str prefix: The prefix to give the original columns. :param inplace: {inplace} ''' df = self.trim(inplace=inplace) column_names = column_names or list(self) for name in column_names: column = df.columns.get(name) df[name] = df.func.fillna(df[name], value) return df def materialize(self, column=None, inplace=False, virtual_column=None): '''Turn columns into native CPU format for optimal performance at cost of memory. .. warning:: This may use of lot of memory, be mindfull. Virtual columns will be evaluated immediately, and all real columns will be cached in memory when used for the first time. Example for virtual column: >>> x = np.arange(1,4) >>> y = np.arange(2,5) >>> df = vaex.from_arrays(x=x, y=y) >>> df['r'] = (df.x**2 + df.y**2)**0.5 # 'r' is a virtual column (computed on the fly) >>> df = df.materialize('r') # now 'r' is a 'real' column (i.e. a numpy array) Example with parquet file >>> df = vaex.open('somewhatslow.parquet') >>> df.x.sum() # slow >>> df = df.materialize() >>> df.x.sum() # slow, but will fill the cache >>> df.x.sum() # as fast as possible, will use memory :param column: string or list of strings with column names to materialize, all columns when None :param virtual_column: for backward compatibility :param inplace: {inplace} ''' if virtual_column is not None: warnings.warn("virtual_column argument is deprecated, please use column") column = virtual_column df = self.trim(inplace=inplace) if column is None: columns = df.get_column_names(hidden=True) else: columns = _ensure_strings_from_expressions(column) virtual = [] cache = [] for column in columns: if column in self.dataset: cache.append(column) elif column in self.virtual_columns: virtual.append(column) else: raise NameError(f'{column} is not a column or virtual column') dataset = df._dataset if cache: dataset = vaex.dataset.DatasetCached(dataset, cache) if virtual: arrays = df.evaluate(virtual, filtered=False) materialized = vaex.dataset.DatasetArrays(dict(zip(virtual, arrays))) dataset = dataset.merged(materialized) df.dataset = dataset for name in virtual: del df.virtual_columns[name] else: # in this case we don't need to invalidate caches, # also the fingerprint will be the same df._dataset = dataset return df def _lazy_materialize(self, *virtual_columns): '''Returns a new DataFrame where the virtual column is turned into an lazily evaluated column.''' df = self.trim() virtual_columns = _ensure_strings_from_expressions(virtual_columns) for name in virtual_columns: if name not in df.virtual_columns: raise KeyError('Virtual column not found: %r' % name) column = ColumnConcatenatedLazy([self[name]]) del df[name] df.add_column(name, column) return df def get_selection(self, name="default"): """Get the current selection object (mostly for internal use atm).""" name = _normalize_selection_name(name) selection_history = self.selection_histories[name] index = self.selection_history_indices[name] if index == -1: return None else: return selection_history[index] def selection_undo(self, name="default", executor=None): """Undo selection, for the name.""" logger.debug("undo") executor = executor or self.executor assert self.selection_can_undo(name=name) selection_history = self.selection_histories[name] index = self.selection_history_indices[name] self.selection_history_indices[name] -= 1 self.signal_selection_changed.emit(self, name) logger.debug("undo: selection history is %r, index is %r", selection_history, self.selection_history_indices[name]) def selection_redo(self, name="default", executor=None): """Redo selection, for the name.""" logger.debug("redo") executor = executor or self.executor assert self.selection_can_redo(name=name) selection_history = self.selection_histories[name] index = self.selection_history_indices[name] next = selection_history[index + 1] self.selection_history_indices[name] += 1 self.signal_selection_changed.emit(self, name) logger.debug("redo: selection history is %r, index is %r", selection_history, index) def selection_can_undo(self, name="default"): """Can selection name be undone?""" return self.selection_history_indices[name] > -1 def selection_can_redo(self, name="default"): """Can selection name be redone?""" return (self.selection_history_indices[name] + 1) < len(self.selection_histories[name]) def select(self, boolean_expression, mode="replace", name="default", executor=None): """Perform a selection, defined by the boolean expression, and combined with the previous selection using the given mode. Selections are recorded in a history tree, per name, undo/redo can be done for them separately. :param str boolean_expression: Any valid column expression, with comparison operators :param str mode: Possible boolean operator: replace/and/or/xor/subtract :param str name: history tree or selection 'slot' to use :param executor: :return: """ boolean_expression = _ensure_string_from_expression(boolean_expression) if boolean_expression is None and not self.has_selection(name=name): pass # we don't want to pollute the history with many None selections self.signal_selection_changed.emit(self, name) # TODO: unittest want to know, does this make sense? else: def create(current): return selections.SelectionExpression(boolean_expression, current, mode) if boolean_expression else None self._selection(create, name) def select_non_missing(self, drop_nan=True, drop_masked=True, column_names=None, mode="replace", name="default"): """Create a selection that selects rows having non missing values for all columns in column_names. The name reflects Pandas, no rows are really dropped, but a mask is kept to keep track of the selection :param drop_nan: drop rows when there is a NaN in any of the columns (will only affect float values) :param drop_masked: drop rows when there is a masked value in any of the columns :param column_names: The columns to consider, default: all (real, non-virtual) columns :param str mode: Possible boolean operator: replace/and/or/xor/subtract :param str name: history tree or selection 'slot' to use :return: """ column_names = column_names or self.get_column_names(virtual=False) def create(current): return selections.SelectionDropNa(drop_nan, drop_masked, column_names, current, mode) self._selection(create, name) def dropmissing(self, column_names=None): """Create a shallow copy of a DataFrame, with filtering set using ismissing. :param column_names: The columns to consider, default: all (real, non-virtual) columns :rtype: DataFrame """ return self._filter_all(self.func.ismissing, column_names) def dropnan(self, column_names=None): """Create a shallow copy of a DataFrame, with filtering set using isnan. :param column_names: The columns to consider, default: all (real, non-virtual) columns :rtype: DataFrame """ return self._filter_all(self.func.isnan, column_names) def dropna(self, column_names=None): """Create a shallow copy of a DataFrame, with filtering set using isna. :param column_names: The columns to consider, default: all (real, non-virtual) columns :rtype: DataFrame """ return self._filter_all(self.func.isna, column_names) def dropinf(self, column_names=None): """ Create a shallow copy of a DataFrame, with filtering set using isinf. :param column_names: The columns to consider, default: all (real, non-virtual) columns :rtype: DataFrame """ return self._filter_all(self.func.isinf, column_names) def _filter_all(self, f, column_names=None): column_names = column_names or self.get_column_names(virtual=False) expression = f(self[column_names[0]]) for column in column_names[1:]: expression = expression | f(self[column]) return self.filter(~expression, mode='and') def select_nothing(self, name="default"): """Select nothing.""" logger.debug("selecting nothing") self.select(None, name=name) self.signal_selection_changed.emit(self, name) def select_rectangle(self, x, y, limits, mode="replace", name="default"): """Select a 2d rectangular box in the space given by x and y, bounded by limits. Example: >>> df.select_box('x', 'y', [(0, 10), (0, 1)]) :param x: expression for the x space :param y: expression fo the y space :param limits: sequence of shape [(x1, x2), (y1, y2)] :param mode: """ self.select_box([x, y], limits, mode=mode, name=name) def select_box(self, spaces, limits, mode="replace", name="default"): """Select a n-dimensional rectangular box bounded by limits. The following examples are equivalent: >>> df.select_box(['x', 'y'], [(0, 10), (0, 1)]) >>> df.select_rectangle('x', 'y', [(0, 10), (0, 1)]) :param spaces: list of expressions :param limits: sequence of shape [(x1, x2), (y1, y2)] :param mode: :param name: :return: """ sorted_limits = [(min(l), max(l)) for l in limits] expressions = ["((%s) >= %f) & ((%s) <= %f)" % (expression, lmin, expression, lmax) for (expression, (lmin, lmax)) in zip(spaces, sorted_limits)] self.select("&".join(expressions), mode=mode, name=name) def select_circle(self, x, y, xc, yc, r, mode="replace", name="default", inclusive=True): """ Select a circular region centred on xc, yc, with a radius of r. Example: >>> df.select_circle('x','y',2,3,1) :param x: expression for the x space :param y: expression for the y space :param xc: location of the centre of the circle in x :param yc: location of the centre of the circle in y :param r: the radius of the circle :param name: name of the selection :param mode: :return: """ # expr = "({x}-{xc})**2 + ({y}-{yc})**2 <={r}**2".format(**locals()) if inclusive: expr = (self[x] - xc)**2 + (self[y] - yc)**2 <= r**2 else: expr = (self[x] - xc)**2 + (self[y] - yc)**2 < r**2 self.select(boolean_expression=expr, mode=mode, name=name) def select_ellipse(self, x, y, xc, yc, width, height, angle=0, mode="replace", name="default", radians=False, inclusive=True): """ Select an elliptical region centred on xc, yc, with a certain width, height and angle. Example: >>> df.select_ellipse('x','y', 2, -1, 5,1, 30, name='my_ellipse') :param x: expression for the x space :param y: expression for the y space :param xc: location of the centre of the ellipse in x :param yc: location of the centre of the ellipse in y :param width: the width of the ellipse (diameter) :param height: the width of the ellipse (diameter) :param angle: (degrees) orientation of the ellipse, counter-clockwise measured from the y axis :param name: name of the selection :param mode: :return: """ # Computing the properties of the ellipse prior to selection if radians: pass else: alpha = np.deg2rad(angle) xr = width / 2 yr = height / 2 r = max(xr, yr) a = xr / r b = yr / r expr = "(({x}-{xc})*cos({alpha})+({y}-{yc})*sin({alpha}))**2/{a}**2 + (({x}-{xc})*sin({alpha})-({y}-{yc})*cos({alpha}))**2/{b}**2 <= {r}**2".format(**locals()) if inclusive: expr = ((self[x] - xc) * np.cos(alpha) + (self[y] - yc) * np.sin(alpha))**2 / a**2 + ((self[x] - xc) * np.sin(alpha) - (self[y] - yc) * np.cos(alpha))**2 / b**2 <= r**2 else: expr = ((self[x] - xc) * np.cos(alpha) + (self[y] - yc) * np.sin(alpha))**2 / a**2 + ((self[x] - xc) * np.sin(alpha) - (self[y] - yc) * np.cos(alpha))**2 / b**2 < r**2 self.select(boolean_expression=expr, mode=mode, name=name) def select_lasso(self, expression_x, expression_y, xsequence, ysequence, mode="replace", name="default", executor=None): """For performance reasons, a lasso selection is handled differently. :param str expression_x: Name/expression for the x coordinate :param str expression_y: Name/expression for the y coordinate :param xsequence: list of x numbers defining the lasso, together with y :param ysequence: :param str mode: Possible boolean operator: replace/and/or/xor/subtract :param str name: :param executor: :return: """ def create(current): return selections.SelectionLasso(expression_x, expression_y, xsequence, ysequence, current, mode) self._selection(create, name, executor=executor) def select_inverse(self, name="default", executor=None): """Invert the selection, i.e. what is selected will not be, and vice versa :param str name: :param executor: :return: """ def create(current): return selections.SelectionInvert(current) self._selection(create, name, executor=executor) def set_selection(self, selection, name="default", executor=None): """Sets the selection object :param selection: Selection object :param name: selection 'slot' :param executor: :return: """ def create(current): return selection self._selection(create, name, executor=executor, execute_fully=True) def _selection(self, create_selection, name, executor=None, execute_fully=False): """select_lasso and select almost share the same code""" selection_history = self.selection_histories[name] previous_index = self.selection_history_indices[name] current = selection_history[previous_index] if selection_history else None selection = create_selection(current) executor = executor or self.executor selection_history.append(selection) self.selection_history_indices[name] += 1 # clip any redo history del selection_history[self.selection_history_indices[name]:-1] self.signal_selection_changed.emit(self, name) result = vaex.promise.Promise.fulfilled(None) # logger.debug("select selection history is %r, index is %r", selection_history, self.selection_history_indices[name]) return result def has_selection(self, name="default"): """Returns True if there is a selection with the given name.""" return self.get_selection(name) is not None def __setitem__(self, name, value): '''Convenient way to add a virtual column / expression to this DataFrame. Example: >>> import vaex, numpy as np >>> df = vaex.example() >>> df['r'] = np.sqrt(df.x**2 + df.y**2 + df.z**2) >>> df.r <vaex.expression.Expression(expressions='r')> instance at 0x121687e80 values=[2.9655450396553587, 5.77829281049018, 6.99079603950256, 9.431842752707537, 0.8825613121347967 ... (total 330000 values) ... 7.453831761514681, 15.398412491068198, 8.864250273925633, 17.601047186042507, 14.540181524970293] ''' if isinstance(name, six.string_types): if isinstance(value, supported_column_types): self.add_column(name, value) else: self.add_virtual_column(name, value) else: raise TypeError('__setitem__ only takes strings as arguments, not {}'.format(type(name))) def drop_filter(self, inplace=False): """Removes all filters from the DataFrame""" df = self if inplace else self.copy() df.select_nothing(name=FILTER_SELECTION_NAME) df._invalidate_caches() return df def filter(self, expression, mode="and"): """General version of df[<boolean expression>] to modify the filter applied to the DataFrame. See :func:`DataFrame.select` for usage of selection. Note that using `df = df[<boolean expression>]`, one can only narrow the filter (i.e. only less rows can be selected). Using the filter method, and a different boolean mode (e.g. "or") one can actually cause more rows to be selected. This differs greatly from numpy and pandas for instance, which can only narrow the filter. Example: >>> import vaex >>> import numpy as np >>> x = np.arange(10) >>> df = vaex.from_arrays(x=x, y=x**2) >>> df # x y 0 0 0 1 1 1 2 2 4 3 3 9 4 4 16 5 5 25 6 6 36 7 7 49 8 8 64 9 9 81 >>> dff = df[df.x<=2] >>> dff # x y 0 0 0 1 1 1 2 2 4 >>> dff = dff.filter(dff.x >=7, mode="or") >>> dff # x y 0 0 0 1 1 1 2 2 4 3 7 49 4 8 64 5 9 81 """ df = self.copy() df.select(expression, name=FILTER_SELECTION_NAME, mode=mode) df._cached_filtered_length = None # invalide cached length df._filter_filled = False # WARNING: this is a special case where we create a new filter # the cache mask chunks still hold references to views on the old # mask, and this new mask will be filled when required df._selection_masks[FILTER_SELECTION_NAME] = vaex.superutils.Mask(int(df._length_unfiltered)) return df def __getitem__(self, item): """Convenient way to get expressions, (shallow) copies of a few columns, or to apply filtering. Example: >>> df['Lz'] # the expression 'Lz >>> df['Lz/2'] # the expression 'Lz/2' >>> df[["Lz", "E"]] # a shallow copy with just two columns >>> df[df.Lz < 0] # a shallow copy with the filter Lz < 0 applied """ if isinstance(item, int): names = self.get_column_names() return [self.evaluate(name, item, item+1, array_type='python')[0] for name in names] elif isinstance(item, six.string_types): if hasattr(self, item) and isinstance(getattr(self, item), Expression): return getattr(self, item) # if item in self.virtual_columns: # return Expression(self, self.virtual_columns[item]) # if item in self._virtual_expressions: # return self._virtual_expressions[item] if item not in self.column_names: self.validate_expression(item) item = vaex.utils.valid_expression(self.get_column_names(), item) return Expression(self, item) # TODO we'd like to return the same expression if possible elif isinstance(item, Expression): expression = item.expression return self.filter(expression) elif isinstance(item, (tuple, list)): df = self if isinstance(item[0], slice): df = df[item[0]] if len(item) > 1: if isinstance(item[1], int): name = self.get_column_names()[item[1]] return df[name] elif isinstance(item[1], slice): names = self.get_column_names().__getitem__(item[1]) return df[names] for expression in item: if expression not in self.column_names: self.validate_expression(expression) df = self.copy(column_names=item) return df elif isinstance(item, slice): start, stop, step = item.start, item.stop, item.step start = start or 0 stop = stop or len(self) if start < 0: start = len(self)+start if stop < 0: stop = len(self)+stop stop = min(stop, len(self)) assert step in [None, 1] if self.filtered: self._fill_filter_mask() mask = self._selection_masks[FILTER_SELECTION_NAME] startf, stopf = mask.indices(start, stop-1) # -1 since it is inclusive assert startf != -1 assert stopf != -1 stopf = stopf+1 # +1 to make it inclusive start, stop = startf, stopf df = self.trim() df.set_active_range(start, stop) return df.trim() def __delitem__(self, item): '''Alias of df.drop(item, inplace=True)''' if item in self.columns: name = item if name in self._depending_columns(columns_exclude=[name]): raise ValueError(f'Oops, you are trying to remove column {name} while other columns depend on it (use .drop instead)') self.drop([item], inplace=True) def _real_drop(self, item): '''Removes a (virtual) column from the DataFrame. Note: this does not check if the column is used in a virtual expression or in the filter\ and may lead to issues. It is safer to use :meth:`drop`. ''' if isinstance(item, Expression): name = item.expression else: name = item if name in self.columns: del self.columns[name] self.column_names.remove(name) elif name in self.virtual_columns: del self.virtual_columns[name] del self._virtual_expressions[name] self.column_names.remove(name) else: matches = difflib.get_close_matches(name, self.get_column_names(hidden=True)) msg = "Column or variable %r does not exist." % name if matches: msg += ' Did you mean: ' + " or ".join(map(repr, matches)) raise KeyError(msg) self.signal_column_changed.emit(self, name, "delete") if hasattr(self, name): try: if isinstance(getattr(self, name), Expression): delattr(self, name) except: pass @docsubst def drop(self, columns, inplace=False, check=True): """Drop columns (or a single column). :param columns: List of columns or a single column name :param inplace: {inplace} :param check: When true, it will check if the column is used in virtual columns or the filter, and hide it instead. """ columns = _ensure_list(columns) columns = _ensure_strings_from_expressions(columns) df = self if inplace else self.copy() depending_columns = df._depending_columns(columns_exclude=columns) for column in columns: if check and column in depending_columns: df._hide_column(column) else: df._real_drop(column) return df def _hide_column(self, column): '''Hides a column by prefixing the name with \'__\'''' column = _ensure_string_from_expression(column) new_name = self._find_valid_name('__' + column) self._rename(column, new_name) return new_name def _find_valid_name(self, initial_name): '''Finds a non-colliding name by optional postfixing''' return vaex.utils.find_valid_name(initial_name, used=self.get_column_names(hidden=True)) def _depending_columns(self, columns=None, columns_exclude=None, check_filter=True): '''Find all depending column for a set of column (default all), minus the excluded ones''' columns = set(columns or self.get_column_names(hidden=True)) if columns_exclude: columns -= set(columns_exclude) depending_columns = set() for column in columns: expression = self[str(column)] depending_columns |= expression.variables() depending_columns -= set(columns) if check_filter: if self.filtered: selection = self.get_selection(FILTER_SELECTION_NAME) depending_columns |= selection._depending_columns(self) return depending_columns def iterrows(self): columns = self.get_column_names() for i in range(len(self)): yield i, {key: self.evaluate(key, i, i+1, array_type='python')[0] for key in columns} #return self[i] def __iter__(self): """Iterator over the column names.""" return iter(list(self.get_column_names())) def _root_nodes(self): """Returns a list of string which are the virtual columns that are not used in any other virtual column.""" # these lists (~used as ordered set) keep track of leafes and root nodes # root nodes root_nodes = [] leafes = [] def walk(node): # this function recursively walks the expression graph if isinstance(node, six.string_types): # we end up at a leaf leafes.append(node) if node in root_nodes: # so it cannot be a root node root_nodes.remove(node) else: node_repr, fname, fobj, deps = node if node_repr in self.virtual_columns: # we encountered a virtual column, similar behaviour as leaf leafes.append(node_repr) if node_repr in root_nodes: root_nodes.remove(node_repr) # resursive part for dep in deps: walk(dep) for column in self.virtual_columns.keys(): if column not in leafes: root_nodes.append(column) node = self[column]._graph() # we don't do the virtual column itself, just it's depedencies node_repr, fname, fobj, deps = node for dep in deps: walk(dep) return root_nodes def _graphviz(self, dot=None): """Return a graphviz.Digraph object with a graph of all virtual columns""" from graphviz import Digraph dot = dot or Digraph(comment='whole dataframe') root_nodes = self._root_nodes() for column in root_nodes: self[column]._graphviz(dot=dot) return dot @docsubst @stat_1d def _agg(self, aggregator, binners=tuple(), delay=False, progress=None): """ :param delay: {delay} :return: {return_stat_scalar} """ tasks, result = aggregator.add_tasks(self, binners, progress=progress) return self._delay(delay, result) def _binner(self, expression, limits=None, shape=None, selection=None, progress=None, delay=False): expression = str(expression) if limits is not None and not isinstance(limits, (tuple, str)): limits = tuple(limits) if expression in self._categories: N = self._categories[expression]['N'] min_value = self._categories[expression]['min_value'] binner = self._binner_ordinal(expression, N, min_value) binner = vaex.promise.Promise.fulfilled(binner) else: @delayed def create_binner(limits): return self._binner_scalar(expression, limits, shape) binner = create_binner(self.limits(expression, limits, selection=selection, progress=progress, delay=True)) return self._delay(delay, binner) def _binner_scalar(self, expression, limits, shape): dtype = self.data_type(expression) return BinnerScalar(expression, limits[0], limits[1], shape, dtype) def _binner_ordinal(self, expression, ordinal_count, min_value=0, invert=False): dtype = self.data_type(expression) return BinnerOrdinal(expression, min_value, ordinal_count, invert, dtype) def _binner_hash(self, expression, hash_map_unique): dtype = self.data_type(expression) return BinnerHash(expression, hash_map_unique, dtype) def _create_binners(self, binby, limits, shape, selection=None, progress=None, delay=False): if isinstance(binby, (list, tuple)): binbys = binby else: binbys = [binby] binbys = _ensure_strings_from_expressions(binbys) for expression in binbys: if expression: self.validate_expression(expression) binners = [] if len(binbys): limits = _expand_limits(limits, len(binbys)) else: limits = [] shapes = _expand_shape(shape, len(binbys)) for binby, limits1, shape in zip(binbys, limits, shapes): binners.append(self._binner(binby, limits1, shape, selection, progress=progress, delay=True)) @delayed def finish(*binners): return binners return self._delay(delay, finish(*binners)) @docsubst def rolling(self, window, trim=False, column=None, fill_value=None, edge="right"): '''Create a :py:data:`vaex.rolling.Rolling` rolling window object :param int window: Size of the rolling window. :param bool trim: {trim} :param str or list[str] column: Column name or column names of columns affected (None for all) :param any fill_value: Scalar value to use for data outside of existing rows. :param str edge: Where the edge of the rolling window is for the current row. ''' columns = self.get_column_names() if column is None else (column if _issequence(column) else [column]) from .rolling import Rolling return Rolling(self, window, trim=trim, columns=columns, fill_value=fill_value, edge=edge) DataFrame.__hidden__ = {} hidden = [name for name, func in vars(DataFrame).items() if getattr(func, '__hidden__', False)] for name in hidden: DataFrame.__hidden__[name] = getattr(DataFrame, name) delattr(DataFrame, name) del hidden class ColumnProxy(collections.abc.MutableMapping): def __init__(self, df): self.df = df @property def dataset(self): return self.df.dataset def __delitem__(self, item): assert item in self.dataset self.df._dataset = self.dataset.dropped(item) def __len__(self): return len(self.dataset) def __setitem__(self, item, value): if isinstance(self.dataset, vaex.dataset.DatasetArrays): merged = vaex.dataset.DatasetArrays({**self.dataset._columns, item: value}) else: left = self.dataset if item in self.dataset: left = left.dropped(item) right = vaex.dataset.DatasetArrays({item: value}) merged = left.merged(right) self.df._dataset = merged self.df._length = len(value) if self.df._length_unfiltered is None: self.df._length_unfiltered = self.df._length self.df._length_original = self.df._length self.df._index_end = self.df._length_unfiltered def __iter__(self): return iter(self.dataset) def __getitem__(self, item): return self.dataset[item] class DataFrameLocal(DataFrame): """Base class for DataFrames that work with local file/data""" def __init__(self, dataset=None, name=None): if dataset is None: dataset = vaex.dataset.DatasetArrays() name = name or "no-name" else: name = name or dataset.name super(DataFrameLocal, self).__init__(name) self._dataset = dataset if hasattr(dataset, 'units'): self.units.update(dataset.units) if hasattr(dataset, 'ucds'): self.ucds.update(dataset.ucds) self.column_names = list(self.dataset) if len(self.dataset): self._length = self.dataset.row_count if self._length_unfiltered is None: self._length_unfiltered = self._length self._length_original = self._length self._index_end = self._length_unfiltered # self.path = dataset.path self.mask = None self.columns = ColumnProxy(self) for column_name in self.column_names: self._initialize_column(column_name) def _fill_filter_mask(self): if self.filtered and self._filter_filled is False: task = vaex.tasks.TaskFilterFill(self) # we also get the count, which is almost for free @delayed def set_length(count): self._cached_filtered_length = int(count) self._filter_filled = True set_length(self.count(delay=True)) task = self.executor.schedule(task) self.execute() def __getstate__(self): state = self.state_get(skip=[self.dataset]) return { 'state': state, 'dataset': self.dataset, '_future_behaviour': self. _future_behaviour, } def __setstate__(self, state): self._init() self.executor = get_main_executor() self.columns = ColumnProxy(self) dataset = state['dataset'] self._dataset = dataset assert dataset.row_count is not None self._length_original = dataset.row_count self._length_unfiltered = self._length_original self._cached_filtered_length = None self._filter_filled = False self._index_start = 0 self._index_end = self._length_original self._future_behaviour = state['_future_behaviour'] self.state_set(state['state'], use_active_range=True, trusted=True) @property def dataset(self): return self._dataset @dataset.setter def dataset(self, dataset): if self._dataset.row_count != dataset.row_count: self._length_original = dataset.row_count self._length_unfiltered = self._length_original self._cached_filtered_length = None self._filter_filled = False self._index_start = 0 self._index_end = self._length_original self._dataset = dataset self._invalidate_caches() def hashed(self, inplace=False) -> DataFrame: '''Return a DataFrame with a hashed dataset''' df = self.copy() if not inplace else self df.dataset = df.dataset.hashed() return df def _readonly(self, inplace=False): # make arrays read only if possible df = self if inplace else self.copy() assert isinstance(self.dataset, vaex.dataset.DatasetArrays) columns = {} for key, ar in self.columns.items(): columns[key] = ar if isinstance(ar, np.ndarray): columns[key] = ar = ar.view() # make new object so we don't modify others ar.flags['WRITEABLE'] = False df._dataset = vaex.dataset.DatasetArrays(columns) return df _dict_mapping = { pa.uint8(): pa.int16(), pa.uint16(): pa.int32(), pa.uint32(): pa.int64(), pa.uint64(): pa.int64(), } def _auto_encode_type(self, expression, type): if not self._future_behaviour: return type if self.is_category(expression): if vaex.dtype(type).is_encoded: return type # already encoded value_type = vaex.array_types.to_arrow(self.category_labels(expression)).type type = vaex.array_types.to_arrow_type(type) type = self._dict_mapping.get(type, type) type = pa.dictionary(type, value_type) return type def _auto_encode_data(self, expression, values): if not self._future_behaviour: return values if vaex.array_types.is_arrow_array(values) and pa.types.is_dictionary(values.type): return values if self.is_category(expression): dictionary = vaex.array_types.to_arrow(self.category_labels(expression)) offset = self.category_offset(expression) if offset != 0: values = values - offset values = vaex.array_types.to_arrow(values) to_type = None if values.type in self._dict_mapping: values = values.cast(self._dict_mapping[values.type]) if isinstance(values, pa.ChunkedArray): chunks = [pa.DictionaryArray.from_arrays(k, dictionary) for k in values.chunks] values = pa.chunked_array(chunks) else: values = pa.DictionaryArray.from_arrays(values, dictionary) return values @docsubst def categorize(self, column, min_value=0, max_value=None, labels=None, inplace=False): """Mark column as categorical. This may help speed up calculations using integer columns between a range of [min_value, max_value]. If max_value is not given, the [min_value and max_value] are calcuated from the data. Example: >>> import vaex >>> df = vaex.from_arrays(year=[2012, 2015, 2019], weekday=[0, 4, 6]) >>> df = df.categorize('year', min_value=2020, max_value=2019) >>> df = df.categorize('weekday', labels=['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']) >>> df # year weekday 0 2012 0 1 2015 4 2 2019 6 >>> df.is_category('year') True :param column: column to assume is categorical. :param labels: labels to associate to the values between min_value and max_value :param min_value: minimum integer value (if max_value is not given, this is calculated) :param max_value: maximum integer value (if max_value is not given, this is calculated) :param labels: Labels to associate to each value, list(range(min_value, max_value+1)) by default :param inplace: {inplace} """ df = self if inplace else self.copy() column = _ensure_string_from_expression(column) if df[column].dtype != int: raise TypeError(f'Only integer columns can be marked as categorical, {column} is {df[column].dtype}') if max_value is not None: labels = list(range(min_value, max_value+1)) N = len(labels) else: vmin, vmax = df.minmax(column) if labels is None: N = int(vmax + 1) labels = list(range(vmin, vmax+1)) min_value = vmin else: min_value = vmin if (vmax - vmin) >= len(labels): raise ValueError('value of {} found, which is larger than number of labels {}'.format(vmax, len(labels))) df._categories[column] = dict(labels=labels, N=len(labels), min_value=min_value) return df def ordinal_encode(self, column, values=None, inplace=False, lazy=False): """Encode column as ordinal values and mark it as categorical. The existing column is renamed to a hidden column and replaced by a numerical columns with values between [0, len(values)-1]. :param lazy: When False, it will materialize the ordinal codes. """ column = _ensure_string_from_expression(column) df = self if inplace else self.copy() # for the codes, we need to work on the unfiltered dataset, since the filter # may change, and we also cannot add an array that is smaller in length df_unfiltered = df.copy() # maybe we need some filter manipulation methods df_unfiltered.select_nothing(name=FILTER_SELECTION_NAME) df_unfiltered._length_unfiltered = df._length_original df_unfiltered.set_active_range(0, df._length_original) expression = df_unfiltered[column] if lazy or values is not None: if values is None: found_values = df_unfiltered.unique(column, array_type='numpy-arrow') minimal_type = vaex.utils.required_dtype_for_max(len(found_values), signed=True) dtype = vaex.dtype_of(found_values) if dtype == int: min_value = found_values.min() max_value = found_values.max() if (max_value - min_value +1) == len(found_values): warnings.warn(f'It seems your column {column} is already ordinal encoded (values between {min_value} and {max_value}), automatically switching to use df.categorize') return df.categorize(column, min_value=min_value, max_value=max_value, inplace=inplace) values = found_values else: values = expression.dtype.create_array(values) fp = f'hash-map-unique-{expression.fingerprint()}' hash_map_unique_name = fp.replace('-', '_') hash_map_unique = vaex.hash.HashMapUnique.from_keys(values, fingerprint=fp) if lazy: df.add_variable(hash_map_unique_name, hash_map_unique) expr = df._expr('hashmap_apply({}, {}, check_missing=True)'.format(column, hash_map_unique_name)) df[column] = expr df._categories[column] = dict(labels=values, N=len(values), min_value=0) return df # no else but return to avoid large diff else: dfc = df.copy() dfc.add_variable(hash_map_unique_name, hash_map_unique) expr = dfc._expr('hashmap_apply({}, {}, check_missing=True)'.format(column, hash_map_unique_name)) codes = dfc.evaluate(expr) else: found_values, codes = df_unfiltered.unique(column, return_inverse=True, array_type='numpy-arrow') if isinstance(found_values, array_types.supported_arrow_array_types): # elements of arrow arrays are not in arrow arrays, e.g. ar[0] in ar is False # see tests/arrow/assumptions_test.py::test_in_pylist found_values = found_values.to_pylist() values = found_values max_code = codes.max() minimal_type = vaex.utils.required_dtype_for_max(max_code, signed=True) codes = codes.astype(minimal_type) if isinstance(values, (list, tuple)): values = pa.array(values) dtype = vaex.dtype_of(values) if dtype == int: min_value = values.min() max_value = values.max() if (max_value - min_value +1) == len(values): warnings.warn(f'It seems your column {column} is already ordinal encoded (values between {min_value} and {max_value}), automatically switching to use df.categorize') return df.categorize(column, min_value=min_value, max_value=max_value, inplace=inplace) df.rename(column, '__original_' + column, unique=True) df.add_column(column, codes) values = vaex.array_types.tolist(values) df._categories[column] = dict(labels=values, N=len(values), min_value=0) return df # for backward compatibility label_encode = _hidden(vaex.utils.deprecated('use ordinal_encode')(ordinal_encode)) @property def data(self): """Gives direct access to the data as numpy arrays. Convenient when working with IPython in combination with small DataFrames, since this gives tab-completion. Only real columns (i.e. no virtual) columns can be accessed, for getting the data from virtual columns, use DataFrame.evaluate(...). Columns can be accessed by their names, which are attributes. The attributes are of type numpy.ndarray. Example: >>> df = vaex.example() >>> r = np.sqrt(df.data.x**2 + df.data.y**2) """ class Datas(object): pass datas = Datas() for name, array in self.columns.items(): setattr(datas, name, array[:]) return datas def copy(self, column_names=None, treeshake=False): '''Make a shallow copy of a DataFrame. One can also specify a subset of columns. This is a fairly cheap operation, since no memory copies of the underlying data are made. {note_copy} :param list column_names: A subset of columns to use for the DataFrame copy. If None, all the columns are copied. :param bool treeshake: Get rid of variables not used. :rtype: DataFrame ''' copy_all = column_names is None if copy_all and not treeshake: # fast path df = vaex.from_dataset(self.dataset) df.column_names = list(self.column_names) df.virtual_columns = self.virtual_columns.copy() virtuals = set(df.virtual_columns) for name in df.column_names: if name in virtuals: df._virtual_expressions[name] = Expression(df, df.virtual_columns[name]) df._initialize_column(name) hide = set() else: all_column_names = self.get_column_names(hidden=True) if column_names is None: column_names = all_column_names.copy() else: for name in column_names: self.validate_expression(name) # the columns that we require for a copy (superset of column_names) required = set() # expression like 'x/2' that are not (virtual) columns expression_columns = set() def track(name): if name in self.dataset: required.add(name) else: if name in self.variables: if treeshake: required.add(name) return elif name in self.virtual_columns: required.add(name) expr = self._virtual_expressions[name] else: # this might be an expression, create a valid name expression_columns.add(name) expr = self[name] # we expand it ourselves deps = expr.variables(ourself=True, expand_virtual=False) deps -= {name} # the columns we didn't know we required yet missing = deps - required required.update(deps) for name in missing: track(name) for name in column_names: track(name) # track all selection dependencies, this includes the filters for key, value in list(self.selection_histories.items()): selection = self.get_selection(key) if selection: for name in selection._depending_columns(self): track(name) # first create the DataFrame with real data (dataset) dataset_columns = {k for k in required if k in self.dataset} # we want a deterministic order for fingerprinting dataset_columns = list(dataset_columns) dataset_columns.sort() dataset = self.dataset.project(*dataset_columns) df = vaex.from_dataset(dataset) # and reconstruct the rest (virtual columns and variables) other = {k for k in required if k not in self.dataset} for name in other: if name in self.virtual_columns: valid_name = vaex.utils.find_valid_name(name) df.add_virtual_column(valid_name, self.virtual_columns[name]) elif name in self.variables: # if we treeshake, we copy only what we require if treeshake: df.variables[name] = self.variables[name] pass else: raise RuntimeError(f'Oops {name} is not a virtual column or variable??') # and extra expressions like 'x/2' for expr in expression_columns: df.add_virtual_column(expr, expr) hide = required - set(column_names) - set(self.variables) # restore some metadata df._length_unfiltered = self._length_unfiltered df._length_original = self._length_original df._cached_filtered_length = self._cached_filtered_length df._filter_filled = self._filter_filled df._index_end = self._index_end df._index_start = self._index_start df._active_fraction = self._active_fraction df._renamed_columns = list(self._renamed_columns) df.units.update(self.units) if not treeshake: df.variables.update(self.variables) df._categories.update(self._categories) df._future_behaviour = self._future_behaviour # put in the selections (thus filters) in place # so drop moves instead of really dropping it df.functions.update(self.functions) for key, value in self.selection_histories.items(): # TODO: selection_histories begin a defaultdict always gives # us the filtered selection, so check if we really have a # selection if self.get_selection(key): df.selection_histories[key] = list(value) # the filter should never be modified, so we can share a reference # except when we add filter on filter using # df = df[df.x>0] # df = df[df.x < 10] # in that case we make a copy in __getitem__ if key == FILTER_SELECTION_NAME: df._selection_masks[key] = self._selection_masks[key] else: df._selection_masks[key] = vaex.superutils.Mask(int(df._length_original)) # and make sure the mask is consistent with the cache chunks np.asarray(df._selection_masks[key])[:] = np.asarray(self._selection_masks[key]) for key, value in self.selection_history_indices.items(): if self.get_selection(key): df.selection_history_indices[key] = value # we can also copy the caches, which prevents recomputations of selections df._selection_mask_caches[key] = collections.defaultdict(dict) df._selection_mask_caches[key].update(self._selection_mask_caches[key]) for name in hide: df._hide_column(name) if column_names is not None: # make the the column order is as requested by the column_names argument extra = set(df.column_names) - set(column_names) df.column_names = list(column_names) + list(extra) df.copy_metadata(self) return df def shallow_copy(self, virtual=True, variables=True): """Creates a (shallow) copy of the DataFrame. It will link to the same data, but will have its own state, e.g. virtual columns, variables, selection etc. """ df = DataFrameLocal(self.name, self.path, self.column_names) df.columns.update(self.columns) df._length_unfiltered = self._length_unfiltered df._length_original = self._length_original df._index_end = self._index_end df._index_start = self._index_start df._active_fraction = self._active_fraction if virtual: df.virtual_columns.update(self.virtual_columns) if variables: df.variables.update(self.variables) # half shallow/deep copy # for key, value in self.selection_histories.items(): # df.selection_histories[key] = list(value) # for key, value in self.selection_history_indices.items(): # df.selection_history_indices[key] = value return df def is_local(self): """The local implementation of :func:`DataFrame.evaluate`, always returns True.""" return True def length(self, selection=False): """Get the length of the DataFrames, for the selection of the whole DataFrame. If selection is False, it returns len(df). TODO: Implement this in DataFrameRemote, and move the method up in :func:`DataFrame.length` :param selection: When True, will return the number of selected rows :return: """ if selection: return 0 if self.mask is None else np.sum(self.mask) else: return len(self) @_hidden def __call__(self, *expressions, **kwargs): """The local implementation of :func:`DataFrame.__call__`""" import vaex.legacy return vaex.legacy.SubspaceLocal(self, expressions, kwargs.get("executor") or self.executor, delay=kwargs.get("delay", False)) def echo(self, arg): return arg @property def _dtype(self): dtypes = [self[k].dtype for k in self.get_column_names()] if not all([dtypes[0] == dtype for dtype in dtypes]): return ValueError("Not all dtypes are equal: %r" % dtypes) return dtypes[0] @property def shape(self): return (len(self), len(self.get_column_names())) def __array__(self, dtype=None, parallel=True): """Gives a full memory copy of the DataFrame into a 2d numpy array of shape (n_rows, n_columns). Note that the memory order is fortran, so all values of 1 column are contiguous in memory for performance reasons. Note this returns the same result as: >>> np.array(ds) If any of the columns contain masked arrays, the masks are ignored (i.e. the masked elements are returned as well). """ if dtype is None: dtype = np.float64 chunks = [] column_names = self.get_column_names(strings=False) for name in column_names: column_type = self.data_type(name).numpy if not np.can_cast(column_type, dtype): if column_type != dtype: raise ValueError("Cannot cast %r (of type %r) to %r" % (name, self.data_type(name), dtype)) chunks = self.evaluate(column_names, parallel=parallel, array_type='numpy') if any(np.ma.isMaskedArray(chunk) for chunk in chunks): return np.ma.array(chunks, dtype=dtype).T else: return np.array(chunks, dtype=dtype).T def as_arrow(self): """Lazily cast all columns to arrow, except object types.""" df = self.copy() for name in self.get_column_names(): df[name] = df[name].as_arrow() return df def as_numpy(self, strict=False): """Lazily cast all numerical columns to numpy. If strict is True, it will also cast non-numerical types. """ df = self.copy() for name in self.get_column_names(): df[name] = df[name].as_numpy(strict=strict) return df @vaex.utils.deprecated('use DataFrame.join(other)') def _hstack(self, other, prefix=None): """Join the columns of the other DataFrame to this one, assuming the ordering is the same""" assert len(self) == len(other), "does not make sense to horizontally stack DataFrames with different lengths" for name in other.get_column_names(): if prefix: new_name = prefix + name else: new_name = name self.add_column(new_name, other.columns[name]) def concat(self, *others, resolver='flexible') -> DataFrame: """Concatenates multiple DataFrames, adding the rows of the other DataFrame to the current, returned in a new DataFrame. In the case of resolver='flexible', when not all columns has the same names, the missing data is filled with missing values. In the case of resolver='strict' all datasets need to have matching column names. :param others: The other DataFrames that are concatenated with this DataFrame :param str resolver: How to resolve schema conflicts, 'flexible' or 'strict'. :return: New DataFrame with the rows concatenated """ # to reduce complexity, we 'extract' the dataframes (i.e. remove filter) dfs = [self, *others] dfs = [df.extract() for df in dfs] common = [] dfs_real_column_names = [df.get_column_names(virtual=False, hidden=True) for df in dfs] # for performance dfs_all_column_names = [df.get_column_names(virtual=True, hidden=True) for df in dfs] # for performance # because set does not preserve order, we use a list all_column_names = [] for column_names in dfs_all_column_names: for name in column_names: if name not in all_column_names: all_column_names.append(name) real_column_names = [] for column_names in dfs_real_column_names: for name in column_names: if name not in real_column_names: real_column_names.append(name) for name in all_column_names: if name in real_column_names: # first we look for virtual colums, that are real columns in other dataframes for df, df_real_column_names, df_all_column_names in zip(dfs, dfs_real_column_names, dfs_all_column_names): if name in df_all_column_names and name not in df_real_column_names: # upgrade to a column, so Dataset's concat works dfs[dfs.index(df)] = df._lazy_materialize(name) else: # check virtual column expressions = [df.virtual_columns.get(name, None) for df in dfs] test_expression = [k for k in expressions if k][0] if any([test_expression != k for k in expressions]): # we have a mismatching virtual column, materialize it for df in dfs: # upgrade to a column, so Dataset's concat can concat if name in df.get_column_names(virtual=True, hidden=True): dfs[dfs.index(df)] = df._lazy_materialize(name) first, *tail = dfs # concatenate all datasets dataset = first.dataset.concat(*[df.dataset for df in tail], resolver=resolver) df_concat = vaex.dataframe.DataFrameLocal(dataset) for name in list(first.virtual_columns.keys()): assert all([first.virtual_columns[name] == df.virtual_columns.get(name, None) for df in tail]), 'Virtual column expression mismatch for column {name}' df_concat.add_virtual_column(name, first.virtual_columns[name]) for df in dfs: for name, value in list(df.variables.items()): if name not in df_concat.variables: df_concat.set_variable(name, value, write=False) for df in dfs: for name, value in list(df.functions.items()): if name not in df_concat.functions: if isinstance(value, vaex.expression.Function): value = value.f if isinstance(value, vaex.expression.FunctionSerializablePickle): value = value.f df_concat.add_function(name, value) else: if df_concat.functions[name].f != df.functions[name].f: raise ValueError(f'Unequal function {name} in concatenated dataframes are not supported yet') return df_concat def _invalidate_caches(self): self._invalidate_selection_cache() self._cached_filtered_length = None self._filter_filled = False def _invalidate_selection_cache(self): self._selection_mask_caches.clear() for key in self._selection_masks.keys(): self._selection_masks[key] = vaex.superutils.Mask(int(self._length_original)) def _filtered_range_to_unfiltered_indices(self, i1, i2): assert self.filtered self._fill_filter_mask() count = len(self) assert i2 <= count cache = self._selection_mask_caches[FILTER_SELECTION_NAME] mask_blocks = iter(sorted( [(k1, k2, block) for (k1, k2), (selection, block) in cache.items()], key=lambda item: item[0])) done = False offset_unfiltered = 0 # points to the unfiltered arrays offset_filtered = 0 # points to the filtered array indices = [] while not done: unfiltered_i1, unfiltered_i2, block = next(mask_blocks) count = block.sum() if (offset_filtered + count) < i1: # i1 does not start in this block assert unfiltered_i2 == offset_unfiltered + len(block) offset_unfiltered = unfiltered_i2 offset_filtered += count else: for block_index in range(len(block)): if block[block_index]: # if not filtered, we go to the next index if i1 <= offset_filtered < i2: # if this is in the range we want... indices.append(offset_unfiltered) offset_filtered += 1 offset_unfiltered += 1 done = offset_filtered >= i2 return np.array(indices, dtype=np.int64) def _evaluate(self, expression, i1, i2, out=None, selection=None, internal=False, filter_mask=None): scope = scopes._BlockScope(self, i1, i2, mask=filter_mask, **self.variables) if out is not None: scope.buffers[expression] = out value = scope.evaluate(expression) if isinstance(value, ColumnString) and not internal: value = value.to_numpy() return value def _unfiltered_chunk_slices(self, chunk_size): logical_length = len(self) if self.filtered: full_mask = self._selection_masks[FILTER_SELECTION_NAME] # TODO: python 3, use yield from for item in vaex.utils.subdivide_mask(full_mask, max_length=chunk_size, logical_length=logical_length): yield item else: for i1, i2 in vaex.utils.subdivide(logical_length, max_length=chunk_size): yield i1, i2, i1, i2 def _evaluate_implementation(self, expression, i1=None, i2=None, out=None, selection=None, filtered=True, array_type=None, parallel=True, chunk_size=None, raw=False, progress=None): """The real implementation of :func:`DataFrame.evaluate` (not returning a generator). :param raw: Whether indices i1 and i2 refer to unfiltered (raw=True) or 'logical' offsets (raw=False) """ # expression = _ensure_string_from_expression(expression) was_list, [expressions] = vaex.utils.listify(expression) expressions = vaex.utils._ensure_strings_from_expressions(expressions) column_names = self.get_column_names(hidden=True) expressions = [vaex.utils.valid_expression(column_names, k) for k in expressions] selection = _normalize_selection(selection) selection = _ensure_strings_from_expressions(selection) max_stop = (len(self) if (self.filtered and filtered) else self.length_unfiltered()) i1 = i1 or 0 i2 = i2 or max_stop if parallel: df = self # first, reduce complexity for the parallel path if self.filtered and not filtered: df = df.drop_filter() if i1 != 0 or i2 != max_stop: if not raw and self.filtered and filtered: self._fill_filter_mask() mask = self._selection_masks[FILTER_SELECTION_NAME] i1, i2 = mask.indices(i1, i2-1) assert i1 != -1 i2 += 1 # TODO: performance: can we collapse the two trims in one? df = df.trim() df.set_active_range(i1, i2) df = df.trim() else: df = self # print(df.columns['x'], i1, i2) expression = expressions[0] # here things are simpler or we don't go parallel mask = None if parallel: use_filter = df.filtered and filtered length = df.length_unfiltered() arrays = {} # maps to a dict of start_index -> apache arrow array (a chunk) chunks_map = {} dtypes = {} shapes = {} virtual = set() # TODO: For NEP branch: dtype -> dtype_evaluate expression_to_evaluate = list(set(expressions)) # lets assume we have to do them all for expression in set(expressions): expression_obj = expression expression = self._expr(expression)._label dtypes[expression] = dtype = df.data_type(expression).internal if expression not in df.columns: virtual.add(expression) # since we will use pre_filter=True, we'll get chunks of the data at unknown offset # so we'll also have to stitch those back together if use_filter or selection:# or not isinstance(dtype, np.dtype): chunks_map[expression] = {} else: # we know exactly where to place the chunks, so we pre allocate the arrays if expression in virtual: if isinstance(dtype, np.dtype): shape = (length, ) + df._shape_of(expression, filtered=False)[1:] shapes[expression] = shape # numpy arrays are fixed length, so we can pre allocate them if df.is_masked(expression): arrays[expression] = np.ma.empty(shapes.get(expression, length), dtype=dtypes[expression]) else: arrays[expression] = np.zeros(shapes.get(expression, length), dtype=dtypes[expression]) else: # TODO: find a way to modify an arrow array inplace, e.g. float64 array # probably by making an ndarray, and have an Arrow array view that # fixed_width = False # try: # ts.bit_width # fixed_width = True # except ValueError: # pass # if fixed_width: chunks_map[expression] = {} else: # quick path, we can just copy the column arrays[expression] = df.columns[expression] start, end = df._index_start, df._index_end if start != 0 or end != len(arrays[expression]): arrays[expression] = arrays[expression][start:end] if isinstance(arrays[expression], vaex.column.Column): arrays[expression] = arrays[expression][0:end-start] # materialize fancy columns (lazy, indexed) expression_to_evaluate.remove(expression_obj) def assign(thread_index, i1, i2, selection_masks, blocks): for i, expression in enumerate(expression_to_evaluate): expression_obj = expression expression = self._expr(expression)._label if expression in chunks_map: # for non-primitive arrays we simply keep a reference to the chunk chunks_map[expression][i1] = blocks[i] else: # for primitive arrays (and no filter/selection) we directly add it to the right place in contiguous numpy array arrays[expression][i1:i2] = blocks[i] if expression_to_evaluate: df.map_reduce(assign, lambda *_: None, expression_to_evaluate, progress=progress, ignore_filter=False, selection=selection, pre_filter=use_filter, info=True, to_numpy=False, name="evaluate") def finalize_result(expression): expression_obj = expression expression = self._expr(expression)._label if expression in chunks_map: # put all chunks in order chunks = [chunk for (i1, chunk) in sorted(chunks_map[expression].items(), key=lambda i1_and_chunk: i1_and_chunk[0])] assert len(chunks) > 0 if len(chunks) == 1: values = array_types.convert(chunks[0], array_type) else: values = array_types.convert(chunks, array_type) else: values = array_types.convert(arrays[expression], array_type) values = self._auto_encode_data(expression, values) return values result = [finalize_result(k) for k in expressions] if not was_list: result = result[0] return result else: assert df is self if i1 == i2: # empty arrays values = [array_types.convert(self.data_type(e).create_array([]), array_type) for e in expressions] if not was_list: return values[0] return values if not raw and self.filtered and filtered: self._fill_filter_mask() # fill caches and masks mask = self._selection_masks[FILTER_SELECTION_NAME] # if _DEBUG: # if i1 == 0 and i2 == count_check: # # we cannot check it if we just evaluate a portion # assert not mask.view(self._index_start, self._index_end).is_dirty() # # assert mask.count() == count_check ni1, ni2 = mask.indices(i1, i2-1) # -1 since it is inclusive assert ni1 != -1 assert ni2 != -1 i1, i2 = ni1, ni2 i2 = i2+1 # +1 to make it inclusive values = [] dataset = self.dataset if i1 != 0 or i2 != self.dataset.row_count: dataset = dataset[i1:i2] deps = set() for expression in expressions: deps |= self._expr(expression).dependencies() deps = {k for k in deps if k in dataset} if self.filtered: filter_deps = df.get_selection(vaex.dataframe.FILTER_SELECTION_NAME).dependencies(df) deps |= filter_deps columns = {k: dataset[k][:] for k in deps if k in dataset} if self.filtered and filtered: filter_scope = scopes._BlockScope(df, i1, i2, None, selection=True, values={**df.variables, **{k: columns[k] for k in filter_deps if k in columns}}) filter_scope.filter_mask = None filter_mask = filter_scope.evaluate(vaex.dataframe.FILTER_SELECTION_NAME) columns = {k:vaex.array_types.filter(v, filter_mask) for k, v, in columns.items()} else: filter_mask = None block_scope = scopes._BlockScope(self, i1, i2, mask=mask, values={**self.variables, **columns}) block_scope.mask = filter_mask for expression in expressions: value = block_scope.evaluate(expression) value = array_types.convert(value, array_type) values.append(value) if not was_list: return values[0] return values def _equals(self, other): values = self.compare(other) return values == ([], [], [], []) def compare(self, other, report_missing=True, report_difference=False, show=10, orderby=None, column_names=None): """Compare two DataFrames and report their difference, use with care for large DataFrames""" if column_names is None: column_names = self.get_column_names(virtual=False) for other_column_name in other.get_column_names(virtual=False): if other_column_name not in column_names: column_names.append(other_column_name) different_values = [] missing = [] type_mismatch = [] meta_mismatch = [] assert len(self) == len(other) if orderby: index1 = np.argsort(self.columns[orderby]) index2 = np.argsort(other.columns[orderby]) for column_name in column_names: if column_name not in self.get_column_names(virtual=False): missing.append(column_name) if report_missing: print("%s missing from this DataFrame" % column_name) elif column_name not in other.get_column_names(virtual=False): missing.append(column_name) if report_missing: print("%s missing from other DataFrame" % column_name) else: ucd1 = self.ucds.get(column_name) ucd2 = other.ucds.get(column_name) if ucd1 != ucd2: print("ucd mismatch : %r vs %r for %s" % (ucd1, ucd2, column_name)) meta_mismatch.append(column_name) unit1 = self.units.get(column_name) unit2 = other.units.get(column_name) if unit1 != unit2: print("unit mismatch : %r vs %r for %s" % (unit1, unit2, column_name)) meta_mismatch.append(column_name) type1 = self.data_type(column_name) type2 = other.data_type(column_name) if not vaex.array_types.same_type(type1, type2): print("different data types: %s vs %s for %s" % (self.data_type(column_name), other.data_type(column_name), column_name)) type_mismatch.append(column_name) else: # a = self.columns[column_name] # b = other.columns[column_name] # if self.filtered: # a = a[self.evaluate_selection_mask(None)] # if other.filtered: # b = b[other.evaluate_selection_mask(None)] a = self.evaluate(column_name, array_type="numpy") b = other.evaluate(column_name, array_type="numpy") if orderby: a = a[index1] b = b[index2] def normalize(ar): if isinstance(ar, pa.Array): ar = ar.to_pandas().values # if ar.dtype == str_type: # return ar if ar.dtype.kind == "f" and hasattr(ar, "mask"): mask = ar.mask ar = ar.copy() ar[mask] = np.nan if ar.dtype.kind in "SU": if hasattr(ar, "mask"): data = ar.data else: data = ar values = [value.strip() for value in data.tolist()] if hasattr(ar, "mask"): ar = np.ma.masked_array(values, ar.mask) else: ar = np.array(values) return ar def equal_mask(a, b): a = normalize(a) b = normalize(b) boolean_mask = (a == b) if not self.is_string(column_name) and self.data_type(column_name).kind == 'f': # floats with nan won't equal itself, i.e. NaN != NaN boolean_mask |= (np.isnan(a) & np.isnan(b)) return boolean_mask boolean_mask = equal_mask(a, b) all_equal = np.all(boolean_mask) if not all_equal: count = np.sum(~boolean_mask) print("%s does not match for both DataFrames, %d rows are diffent out of %d" % (column_name, count, len(self))) different_values.append(column_name) if report_difference: indices = np.arange(len(self))[~boolean_mask] values1 = self.columns[column_name][:][~boolean_mask] values2 = other.columns[column_name][:][~boolean_mask] print("\tshowing difference for the first 10") for i in range(min(len(values1), show)): try: diff = values1[i] - values2[i] except: diff = "does not exists" print("%s[%d] == %s != %s other.%s[%d] (diff = %s)" % (column_name, indices[i], values1[i], values2[i], column_name, indices[i], diff)) return different_values, missing, type_mismatch, meta_mismatch @docsubst def join(self, other, on=None, left_on=None, right_on=None, lprefix='', rprefix='', lsuffix='', rsuffix='', how='left', allow_duplication=False, prime_growth=False, cardinality_other=None, inplace=False): """Return a DataFrame joined with other DataFrames, matched by columns/expression on/left_on/right_on If neither on/left_on/right_on is given, the join is done by simply adding the columns (i.e. on the implicit row index). Note: The filters will be ignored when joining, the full DataFrame will be joined (since filters may change). If either DataFrame is heavily filtered (contains just a small number of rows) consider running :func:`DataFrame.extract` first. Example: >>> a = np.array(['a', 'b', 'c']) >>> x = np.arange(1,4) >>> ds1 = vaex.from_arrays(a=a, x=x) >>> b = np.array(['a', 'b', 'd']) >>> y = x**2 >>> ds2 = vaex.from_arrays(b=b, y=y) >>> ds1.join(ds2, left_on='a', right_on='b') :param other: Other DataFrame to join with (the right side) :param on: default key for the left table (self) :param left_on: key for the left table (self), overrides on :param right_on: default key for the right table (other), overrides on :param lprefix: prefix to add to the left column names in case of a name collision :param rprefix: similar for the right :param lsuffix: suffix to add to the left column names in case of a name collision :param rsuffix: similar for the right :param how: how to join, 'left' keeps all rows on the left, and adds columns (with possible missing values) 'right' is similar with self and other swapped. 'inner' will only return rows which overlap. :param bool allow_duplication: Allow duplication of rows when the joined column contains non-unique values. :param int cardinality_other: Number of unique elements (or estimate of) for the other table. :param bool prime_growth: Growth strategy for the hashmaps used internally, can improve performance in some case (e.g. integers with low bits unused). :param inplace: {inplace} :return: """ import vaex.join kwargs = dict(**locals()) kwargs['df'] = kwargs.pop('self') del kwargs['vaex'] return vaex.join.join(**kwargs) @docsubst def export(self, path, progress=None, chunk_size=default_chunk_size, parallel=True, fs_options=None, fs=None): """Exports the DataFrame to a file depending on the file extension. E.g if the filename ends on .hdf5, `df.export_hdf5` is called. :param str path: path for file :param progress: {progress} :param int chunk_size: {chunk_size_export}, if supported. :param bool parallel: {evaluate_parallel} :param dict fs_options: {fs_options} :return: """ naked_path, options = vaex.file.split_options(path) fs_options = fs_options or {} if naked_path.endswith('.arrow'): self.export_arrow(path, progress=progress, chunk_size=chunk_size, parallel=parallel, fs_options=fs_options, fs=fs) elif naked_path.endswith('.feather'): self.export_feather(path, parallel=parallel, fs_options=fs_options) elif naked_path.endswith('.hdf5'): self.export_hdf5(path, progress=progress, parallel=parallel) elif naked_path.endswith('.fits'): self.export_fits(path, progress=progress) elif naked_path.endswith('.parquet'): self.export_parquet(path, progress=progress, parallel=parallel, chunk_size=chunk_size, fs_options=fs_options, fs=fs) elif naked_path.endswith('.csv'): self.export_csv(path, progress=progress, parallel=parallel, chunk_size=chunk_size) elif naked_path.endswith('.json'): self.export_json(path, progress=progress, chunk_size=chunk_size, parallel=parallel, fs_options=fs_options, fs=fs) else: raise ValueError('''Unrecognized file extension. Please use .arrow, .hdf5, .parquet, .fits, or .csv to export to the particular file format.''') @docsubst def export_arrow(self, to, progress=None, chunk_size=default_chunk_size, parallel=True, reduce_large=True, fs_options=None, fs=None, as_stream=True): """Exports the DataFrame to a file of stream written with arrow :param to: filename, file object, or :py:data:`pyarrow.RecordBatchStreamWriter`, py:data:`pyarrow.RecordBatchFileWriter` or :py:data:`pyarrow.parquet.ParquetWriter` :param progress: {progress} :param int chunk_size: {chunk_size_export} :param bool parallel: {evaluate_parallel} :param bool reduce_large: If True, convert arrow large_string type to string type :param bool as_stream: Write as an Arrow stream if true, else a file. see also https://arrow.apache.org/docs/format/Columnar.html?highlight=arrow1#ipc-file-format :param dict fs_options: {fs_options} :return: """ def write(writer): N = len(self) if chunk_size: with vaex.progress.tree(progress, title="export(arrow)") as progressbar: for i1, i2, table in self.to_arrow_table(chunk_size=chunk_size, parallel=parallel, reduce_large=reduce_large): writer.write_table(table) progressbar(i2/N) progressbar(1.) else: table = self.to_arrow_table(chunk_size=chunk_size, parallel=parallel, reduce_large=reduce_large) writer.write_table(table) if vaex.file.is_path_like(to) or vaex.file.is_file_object(to): schema = self.schema_arrow(reduce_large=reduce_large) with vaex.file.open(path=to, mode='wb', fs_options=fs_options, fs=fs) as sink: if as_stream: with pa.RecordBatchStreamWriter(sink, schema) as writer: write(writer) else: with pa.RecordBatchFileWriter(sink, schema) as writer: write(writer) else: write(to) @docsubst def export_feather(self, to, parallel=True, reduce_large=True, compression='lz4', fs_options=None, fs=None): """Exports the DataFrame to an arrow file using the feather file format version 2 Feather is exactly represented as the Arrow IPC file format on disk, but also support compression. see also https://arrow.apache.org/docs/python/feather.html :param to: filename or file object :param bool parallel: {evaluate_parallel} :param bool reduce_large: If True, convert arrow large_string type to string type :param compression: Can be one of 'zstd', 'lz4' or 'uncompressed' :param fs_options: {fs_options} :param fs: {fs} :return: """ import pyarrow.feather as feather table = self.to_arrow_table(parallel=False, reduce_large=reduce_large) fs_options = fs_options or {} with vaex.file.open(path=to, mode='wb', fs_options=fs_options, fs=fs) as sink: feather.write_feather(table, sink, compression=compression) @docsubst def export_parquet(self, path, progress=None, chunk_size=default_chunk_size, parallel=True, fs_options=None, fs=None, **kwargs): """Exports the DataFrame to a parquet file. Note: This may require that all of the data fits into memory (memory mapped data is an exception). Use :py:`DataFrame.export_chunks` to write to multiple files in parallel. :param str path: path for file :param progress: {progress} :param int chunk_size: {chunk_size_export} :param bool parallel: {evaluate_parallel} :param dict fs_options: {fs_options} :param fs: {fs} :param **kwargs: Extra keyword arguments to be passed on to py:data:`pyarrow.parquet.ParquetWriter`. :return: """ import pyarrow.parquet as pq schema = self.schema_arrow(reduce_large=True) with vaex.file.open(path=path, mode='wb', fs_options=fs_options, fs=fs) as sink: with pq.ParquetWriter(sink, schema, **kwargs) as writer: self.export_arrow(writer, progress=progress, chunk_size=chunk_size, parallel=parallel, reduce_large=True) @docsubst def export_partitioned(self, path, by, directory_format='{key}={value}', progress=None, chunk_size=default_chunk_size, parallel=True, fs_options={}, fs=None): '''Expertimental: export files using hive partitioning. If no extension is found in the path, we assume parquet files. Otherwise you can specify the format like an format-string. Where {{i}} is a zero based index, {{uuid}} a unique id, and {{subdir}} the Hive key=value directory. Example paths: * '/some/dir/{{subdir}}/{{i}}.parquet' * '/some/dir/{{subdir}}/fixed_name.parquet' * '/some/dir/{{subdir}}/{{uuid}}.parquet' * '/some/dir/{{subdir}}/{{uuid}}.parquet' :param path: directory where to write the files to. :param str or list of str: Which column to partition by. :param str directory_format: format string for directories, default '{{key}}={{value}}' for Hive layout. :param progress: {progress} :param int chunk_size: {chunk_size_export} :param bool parallel: {evaluate_parallel} :param dict fs_options: {fs_options} ''' from uuid import uuid4 if not _issequence(by): by = [by] by = _ensure_strings_from_expressions(by) # we don't store the partitioned columns columns = self.get_column_names() for name in by: columns.remove(name) progressbar = vaex.utils.progressbars(progress, title="export(partitioned)") progressbar(0) groups = self.groupby(by) _, ext, _ = vaex.file.split_ext(path) if not ext: path = vaex.file.stringyfy(path) + '/{subdir}/{uuid}.parquet' else: path = vaex.file.stringyfy(path) for i, (values, df) in enumerate(groups): parts = [directory_format.format(key=key, value=value) for key, value in dict(zip(by, values)).items()] subdir = '/'.join(parts) uuid = uuid4() fullpath = path.format(uuid=uuid, subdir=subdir, i=i) dirpath = os.path.dirname(fullpath) vaex.file.create_dir(dirpath, fs_options=fs_options, fs=fs) progressbar((i)/len(groups)) df[columns].export(fullpath, chunk_size=chunk_size, parallel=parallel, fs_options=fs_options, fs=fs) progressbar(1) @docsubst def export_many(self, path, progress=None, chunk_size=default_chunk_size, parallel=True, max_workers=None, fs_options=None, fs=None): """Export the DataFrame to multiple files of the same type in parallel. The path will be formatted using the i parameter (which is the chunk index). Example: >>> import vaex >>> df = vaex.open('my_big_dataset.hdf5') >>> print(f'number of rows: {{len(df):,}}') number of rows: 193,938,982 >>> df.export_many(path='my/destination/folder/chunk-{{i:03}}.arrow') >>> df_single_chunk = vaex.open('my/destination/folder/chunk-00001.arrow') >>> print(f'number of rows: {{len(df_single_chunk):,}}') number of rows: 1,048,576 >>> df_all_chunks = vaex.open('my/destination/folder/chunk-*.arrow') >>> print(f'number of rows: {{len(df_all_chunks):,}}') number of rows: 193,938,982 :param str path: Path for file, formatted by chunk index i (e.g. 'chunk-{{i:05}}.parquet') :param progress: {progress} :param int chunk_size: {chunk_size_export} :param bool parallel: {evaluate_parallel} :param int max_workers: Number of workers/threads to use for writing in parallel :param dict fs_options: {fs_options} """ from .itertools import pmap, pwait, buffer, consume path1 = str(path).format(i=0, i1=1, i2=2) path2 = str(path).format(i=1, i1=2, i2=3) if path1 == path2: name, ext = os.path.splitext(path) path = f'{name}-{{i:05}}{ext}' input = self.to_dict(chunk_size=chunk_size, parallel=True) column_names = self.get_column_names() def write(i, item): i1, i2, chunks = item p = str(path).format(i=i, i1=i2, i2=i2) df = vaex.from_dict(chunks) df.export(p, chunk_size=None, parallel=False, fs_options=fs_options, fs=fs) return i2 progressbar = vaex.utils.progressbars(progress, title="export(many)") progressbar(0) length = len(self) def update_progress(offset): progressbar(offset / length) pool = concurrent.futures.ThreadPoolExecutor(max_workers) workers = pool._max_workers consume(map(update_progress, pwait(buffer(pmap(write, enumerate(input), pool=pool), workers+3)))) progressbar(1) @docsubst def export_hdf5(self, path, byteorder="=", progress=None, chunk_size=default_chunk_size, parallel=True, column_count=1, writer_threads=0, group='/table', mode='w'): """Exports the DataFrame to a vaex hdf5 file :param str path: path for file :param str byteorder: = for native, < for little endian and > for big endian :param progress: {progress} :param bool parallel: {evaluate_parallel} :param int column_count: How many columns to evaluate and export in parallel (>1 requires fast random access, like and SSD drive). :param int writer_threads: Use threads for writing or not, only useful when column_count > 1. :param str group: Write the data into a custom group in the hdf5 file. :param str mode: If set to "w" (write), an existing file will be overwritten. If set to "a", one can append additional data to the hdf5 file, but it needs to be in a different group. :return: """ from vaex.hdf5.writer import Writer with vaex.utils.progressbars(progress, title="export(hdf5)") as progressbar: progressbar_layout = progressbar.add("layout file structure") progressbar_write = progressbar.add("write data") with Writer(path=path, group=group, mode=mode, byteorder=byteorder) as writer: writer.layout(self, progress=progressbar_layout) writer.write( self, chunk_size=chunk_size, progress=progressbar_write, column_count=column_count, parallel=parallel, export_threads=writer_threads) @docsubst def export_fits(self, path, progress=None): """Exports the DataFrame to a fits file that is compatible with TOPCAT colfits format :param str path: path for file :param progress: {progress} :return: """ from vaex.astro.fits import export_fits export_fits(self, path, progress=progress) @docsubst def export_csv(self, path, progress=None, chunk_size=default_chunk_size, parallel=True, **kwargs): """ Exports the DataFrame to a CSV file. :param str path: Path for file :param progress: {progress} :param int chunk_size: {chunk_size_export} :param parallel: {evaluate_parallel} :param **kwargs: Extra keyword arguments to be passed on pandas.DataFrame.to_csv() :return: """ import pandas as pd expressions = self.get_column_names() progressbar = vaex.utils.progressbars(progress, title="export(csv)") dtypes = self[expressions].dtypes n_samples = len(self) if chunk_size is None: chunk_size = len(self) # By default vaex does not expect a csv file to have index like column so this is turned of by default if 'index' not in kwargs: kwargs['index'] = False for i1, i2, chunks in self.evaluate_iterator(expressions, chunk_size=chunk_size, parallel=parallel): progressbar( i1 / n_samples) chunk_dict = {col: values for col, values in zip(expressions, chunks)} chunk_pdf = pd.DataFrame(chunk_dict) if i1 == 0: # Only the 1st chunk should have a header and the rest will be appended kwargs['mode'] = 'w' else: kwargs['mode'] = 'a' kwargs['header'] = False chunk_pdf.to_csv(path_or_buf=path, **kwargs) progressbar(1.0) return @docsubst def export_json(self, to, progress=None, chunk_size=default_chunk_size, parallel=True, fs_options=None, fs=None): """ Exports the DataFrame to a CSV file. :param to: filename or file object :param progress: {progress} :param int chunk_size: {chunk_size_export} :param parallel: {evaluate_parallel} :param fs_options: {fs_options} :param fs: {fs} :return: """ json = None # we may want to pass the module as parameter to use a faster library import json as json_std json = json or json_std # not sure if we want to use pandas, it will treat datetime for us, but will convert null to nan use_pandas = True # we take on the '[' and ']' from each chunk, and insert it back ourselves # and we also need to but ',' between each chunk with vaex.progress.tree(progress, title="export(json)"), vaex.file.open(path=to, mode='wb', fs_options=fs_options, fs=fs) as f: f.write(b"[") first = True if use_pandas: for _i1, _i2, df in self.to_pandas_df(chunk_size=chunk_size, parallel=parallel): if not first: f.write(b", ") first = False f_temp = io.StringIO() df.to_json(f_temp, orient='records') f.write(f_temp.getvalue()[1:-1].encode('utf8')) else: for _i1, _i2, records in self.to_records(chunk_size=chunk_size, parallel=parallel): if not first: f.write(b", ") first = False raw = json.dumps(records)[1:-1] f.write(raw.encode("utf8")) f.write(b"]") def _needs_copy(self, column_name): import vaex.file.other return not \ ((column_name in self.column_names and not isinstance(self.columns[column_name], Column) and not isinstance(self.columns[column_name], vaex.file.other.DatasetTap.TapColumn) and self.columns[column_name].dtype.type == np.float64 and self.columns[column_name].strides[0] == 8 and column_name not in self.virtual_columns) or self.data_type(column_name) == str_type or self.data_type(column_name).kind == 'S') # and False: def selected_length(self, selection="default"): """The local implementation of :func:`DataFrame.selected_length`""" return int(self.count(selection=selection).item()) # np.sum(self.mask) if self.has_selection() else None # def _set_mask(self, mask): # self.mask = mask # self._has_selection = mask is not None # # self.signal_selection_changed.emit(self) @docsubst def groupby(self, by=None, agg=None, sort=False, ascending=True, assume_sparse='auto', row_limit=None, copy=True, progress=None, delay=False): """Return a :class:`GroupBy` or :class:`DataFrame` object when agg is not None Examples: >>> import vaex >>> import numpy as np >>> np.random.seed(42) >>> x = np.random.randint(1, 5, 10) >>> y = x**2 >>> df = vaex.from_arrays(x=x, y=y) >>> df.groupby(df.x, agg='count') # x y_count 0 3 4 1 4 2 2 1 3 3 2 1 >>> df.groupby(df.x, agg=[vaex.agg.count('y'), vaex.agg.mean('y')]) # x y_count y_mean 0 3 4 9 1 4 2 16 2 1 3 1 3 2 1 4 >>> df.groupby(df.x, agg={{'z': [vaex.agg.count('y'), vaex.agg.mean('y')]}}) # x z_count z_mean 0 3 4 9 1 4 2 16 2 1 3 1 3 2 1 4 Example using datetime: >>> import vaex >>> import numpy as np >>> t = np.arange('2015-01-01', '2015-02-01', dtype=np.datetime64) >>> y = np.arange(len(t)) >>> df = vaex.from_arrays(t=t, y=y) >>> df.groupby(vaex.BinnerTime.per_week(df.t)).agg({{'y' : 'sum'}}) # t y 0 2015-01-01 00:00:00 21 1 2015-01-08 00:00:00 70 2 2015-01-15 00:00:00 119 3 2015-01-22 00:00:00 168 4 2015-01-29 00:00:00 87 :param dict, list or agg agg: Aggregate operation in the form of a string, vaex.agg object, a dictionary where the keys indicate the target column names, and the values the operations, or the a list of aggregates. When not given, it will return the groupby object. :param bool sort: Sort columns for which we group by. :param bool or list of bools ascending: ascending (default, True) or descending (False). :param bool or str assume_sparse: Assume that when grouping by multiple keys, that the existing pairs are sparse compared to the cartesian product. If 'auto', let vaex decide (e.g. a groupby with 10_000 rows but only 4*3=12 combinations does not matter much to compress into say 8 existing combinations, and will save another pass over the data) :param int row_limit: Limits the resulting dataframe to the number of rows (default is not to check, only works when assume_sparse is True). Throws a :py:`vaex.RowLimitException` when the condition is not met. :param bool copy: Copy the dataframe (shallow, does not cost memory) so that the fingerprint of the original dataframe is not modified. :param bool delay: {delay} :param progress: {progress} :return: :class:`DataFrame` or :class:`GroupBy` object. """ from .groupby import GroupBy progressbar = vaex.utils.progressbars(progress, title="groupby") groupby = GroupBy(self, by=by, sort=sort, ascending=ascending, combine=assume_sparse, row_limit=row_limit, copy=copy, progress=progressbar) if agg: progressbar_agg = progressbar.add('aggregators') @vaex.delayed def next(_ignore): if agg is None: return groupby else: return groupby.agg(agg, delay=delay, progress=progressbar_agg) return self._delay(delay, progressbar.exit_on(next(groupby._promise_by))) @docsubst def binby(self, by=None, agg=None, sort=False, copy=True, delay=False, progress=None): """Return a :class:`BinBy` or :class:`DataArray` object when agg is not None The binby operation does not return a 'flat' DataFrame, instead it returns an N-d grid in the form of an xarray. :param dict, list or agg agg: Aggregate operation in the form of a string, vaex.agg object, a dictionary where the keys indicate the target column names, and the values the operations, or the a list of aggregates. When not given, it will return the binby object. :param bool copy: Copy the dataframe (shallow, does not cost memory) so that the fingerprint of the original dataframe is not modified. :param bool delay: {delay} :param progress: {progress} :return: :class:`DataArray` or :class:`BinBy` object. """ from .groupby import BinBy progressbar = vaex.utils.progressbars(progress, title="binby") binby = BinBy(self, by=by, sort=sort, progress=progressbar, copy=copy) if agg: progressbar_agg = progressbar.add('aggregators') @vaex.delayed def next(_ignore): if agg is None: return binby else: return binby.agg(agg, delay=delay, progress=progressbar_agg) return self._delay(delay, progressbar.exit_on(next(binby._promise_by))) def _selection(self, create_selection, name, executor=None, execute_fully=False): def create_wrapper(current): selection = create_selection(current) # only create a mask when we have a selection, so we do not waste memory if selection is not None and name not in self._selection_masks: self._selection_masks[name] = vaex.superutils.Mask(int(self._length_unfiltered)) return selection return super()._selection(create_wrapper, name, executor, execute_fully) @property def values(self): """Gives a full memory copy of the DataFrame into a 2d numpy array of shape (n_rows, n_columns). Note that the memory order is fortran, so all values of 1 column are contiguous in memory for performance reasons. Note this returns the same result as: >>> np.array(ds) If any of the columns contain masked arrays, the masks are ignored (i.e. the masked elements are returned as well). """ return self.__array__() def _is_dtype_ok(dtype): return dtype.type in [np.bool_, np.int8, np.int16, np.int32, np.int64, np.uint8, np.uint16, np.uint32, np.uint64, np.float32, np.float64, np.datetime64] or\ dtype.type == np.string_ or dtype.type == np.unicode_ def _is_array_type_ok(array): return _is_dtype_ok(array.dtype) # there represent the spec version of the cpu based vaex.superagg.BinnerScalar/Ordinal_<dtype> register_binner = vaex.encoding.make_class_registery('binner') class BinnerBase: @classmethod def decode(cls, encoding, spec): spec = spec.copy() spec['dtype'] = encoding.decode('dtype', spec['dtype']) return cls(**spec) @register_binner class BinnerScalar(BinnerBase): snake_name = 'scalar' def __init__(self, expression, minimum, maximum, count, dtype): self.expression = str(expression) self.minimum = minimum self.maximum = maximum self.count = count self.dtype = dtype def __repr__(self): return f'binner_scalar({self.expression}, {self.minimum}, {self.maximum}, count={self.count})' def encode(self, encoding): dtype = encoding.encode('dtype', self.dtype) return {'expression': self.expression, 'dtype': dtype, 'count': self.count, 'minimum': self.minimum, 'maximum': self.maximum} def __hash__(self) -> int: return hash((self.__class__.__name__, self.expression, self.minimum, self.maximum, self.count, self.dtype)) def __eq__(self, rhs): if not isinstance(rhs, BinnerScalar): return False return \ self.expression == rhs.expression and \ self.minimum == rhs.minimum and \ self.maximum == rhs.maximum and \ self.count == rhs.count and \ self.dtype == rhs.dtype @register_binner class BinnerOrdinal(BinnerBase): snake_name = 'ordinal' def __init__(self, expression, minimum, count, invert, dtype): self.expression = str(expression) self.minimum = minimum self.count = count self.invert = invert self.dtype = dtype def __repr__(self): return f'binner_ordinal({self.expression}, {self.minimum}, {self.count}, {self.invert})' def encode(self, encoding): datatype = encoding.encode("dtype", self.dtype) return {"type": "ordinal", "expression": self.expression, "dtype": datatype, "count": self.count, "minimum": self.minimum, "invert": self.invert} def __hash__(self) -> int: return hash((self.__class__.__name__, self.expression, self.minimum, self.count, self.invert, self.dtype)) def __eq__(self, rhs): if not isinstance(rhs, BinnerOrdinal): return False return \ self.expression == rhs.expression and \ self.minimum == rhs.minimum and \ self.count == rhs.count and \ self.invert == rhs.invert and \ self.dtype == rhs.dtype @register_binner class BinnerHash(BinnerBase): snake_name = 'hash' def __init__(self, expression, hash_map_unique, dtype): self.expression = str(expression) self.hash_map_unique = hash_map_unique self.dtype = dtype def __repr__(self): return f'binner_hash({self.expression}, {self.hash_map_unique})' def encode(self, encoding): datatype = encoding.encode('dtype', self.dtype) hash_map_spec = encoding.encode('hash-map-unique', self.hash_map_unique) assert self.hash_map_unique.fingerprint hash_map_id = vaex.cache.fingerprint('binner-hash', self.hash_map_unique.fingerprint) encoding.set_object_spec(hash_map_id, hash_map_spec) return {'expression': self.expression, 'hash_map_unique': hash_map_id, 'dtype': datatype} def __hash__(self) -> int: return hash((self.__class__.__name__, self.expression, self.hash_map_unique)) def __eq__(self, rhs): if not isinstance(rhs, BinnerHash): return False return \ self.expression == rhs.expression and \ self.hash_map_unique == rhs.hash_map_unique and\ self.dtype == rhs.dtype
45.887037
307
0.595706
from __future__ import division, print_function import io import difflib import base64 from typing import Iterable import os import math import time import itertools import functools import collections import sys import platform import warnings import re from functools import reduce import threading import six import vaex.utils import numpy as np import concurrent.futures import numbers import pyarrow as pa from vaex.utils import Timer import vaex.events import vaex.grids import vaex.hash import vaex.multithreading import vaex.promise import vaex.execution import vaex.expresso import logging import vaex.kld from . import selections, tasks, scopes from .expression import expression_namespace from .delayed import delayed, delayed_args, delayed_list from .column import Column, ColumnIndexed, ColumnSparse, ColumnString, ColumnConcatenatedLazy, supported_column_types from . import array_types import vaex.events from .datatype import DataType from .docstrings import docsubst astropy = vaex.utils.optional_import("astropy.units") xarray = vaex.utils.optional_import("xarray") try: from urllib.parse import urlparse except ImportError: from urlparse import urlparse _DEBUG = os.environ.get('VAEX_DEBUG', False) _REPORT_EXECUTION_TRACES = vaex.utils.get_env_type(int, 'VAEX_EXECUTE_TRACE', 0) DEFAULT_REPR_FORMAT = 'plain' FILTER_SELECTION_NAME = '__filter__' sys_is_le = sys.byteorder == 'little' logger = logging.getLogger("vaex") lock = threading.Lock() default_shape = 128 default_chunk_size = 1024**2 def _len(o): return o.__len__() def _requires(name): def wrap(*args, **kwargs): raise RuntimeError('this function is wrapped by a placeholder, you probably want to install vaex-' + name) return wrap from .utils import (_ensure_strings_from_expressions, _ensure_string_from_expression, _ensure_list, _is_limit, _isnumber, _issequence, _is_string, _normalize_selection, _parse_reduction, _parse_n, _normalize_selection_name, _normalize, _parse_f, _expand, _expand_shape, _expand_limits, as_flat_float, as_flat_array, _split_and_combine_mask) main_executor = None from vaex.execution import Executor def get_main_executor(): global main_executor if main_executor is None: main_executor = vaex.execution.ExecutorLocal(vaex.multithreading.get_main_pool()) return main_executor from .expression import Expression _functions_statistics_1d = [] def stat_1d(f): _functions_statistics_1d.append(f) return f def _hidden(meth): meth.__hidden__ = True return meth @vaex.encoding.register("dataframe") class _DataFrameEncoder: @staticmethod def encode(encoding, df): state = df.state_get(skip=[df.dataset]) return { 'state': encoding.encode('dataframe-state', state), 'dataset': encoding.encode('dataset', df.dataset) } @staticmethod def decode(encoding, spec): dataset = encoding.decode('dataset', spec['dataset']) state = encoding.decode('dataframe-state', spec['state']) df = vaex.from_dataset(dataset)._future() df.state_set(state) return df class DataFrame(object): def __init__(self, name=None, executor=None): self.executor = executor or get_main_executor() self.name = name self._init() def _init(self): self.column_names = [] self.signal_pick = vaex.events.Signal("pick") self.signal_sequence_index_change = vaex.events.Signal("sequence index change") self.signal_selection_changed = vaex.events.Signal("selection changed") self.signal_active_fraction_changed = vaex.events.Signal("active fraction changed") self.signal_column_changed = vaex.events.Signal("a column changed") self.signal_variable_changed = vaex.events.Signal("a variable changed") self.variables = {} self.virtual_columns = {} self._virtual_expressions = {} self.functions = {} self._length_original = None self._length_unfiltered = None self._cached_filtered_length = None self._filter_filled = False self._active_fraction = 1 self._current_row = None self._index_start = 0 self._index_end = None self.description = None self.ucds = {} self.units = {} self.descriptions = {} self.favorite_selections = {} self._future_behaviour = False self.mask = None self.selection_histories = collections.defaultdict(list) self.selection_history_indices = collections.defaultdict(lambda: -1) assert self.filtered is False self._auto_fraction = False self._sparse_matrices = {} self._categories = {} self._selection_mask_caches = collections.defaultdict(dict) self._selection_masks = {} self._renamed_columns = [] self._expressions = [] self.local = threading.local() self.local._aggregator_nest_count = 0 def fingerprint(self, dependencies=None, treeshake=False): df = self.copy(treeshake=True) if treeshake else self selections = {name: self.get_selection(name) for name, history in self.selection_histories.items() if self.has_selection(name)} if dependencies is not None: dependencies = set(dependencies) for selection in selections.values(): dependencies.update(selection.dependencies(self)) encoding = vaex.encoding.Encoding() def dep_filter(d : dict): if dependencies is None: return d return {k: v for k, v in d.items() if k in dependencies} state = dict( column_names=[k for k in list(self.column_names) if dependencies is None or k in dependencies], virtual_columns=dep_filter(self.virtual_columns), variables=dep_filter(self.variables), functions={name: encoding.encode("function", value) for name, value in dep_filter(self.functions).items()}, active_range=[self._index_start, self._index_end] ) state['selections'] = {name: selection.to_dict() if selection is not None else None for name, selection in selections.items()} fp = vaex.cache.fingerprint(state, df.dataset.fingerprint) return f'dataframe-{fp}' def __dataframe__(self, nan_as_null : bool = False, allow_copy : bool = True): import vaex.dataframe_protocol return vaex.dataframe_protocol._VaexDataFrame(self, nan_as_null=nan_as_null, allow_copy=allow_copy) def _future(self, version=5, inplace=False): df = self if inplace else self.copy() df._future_behaviour = 5 return df _auto_encode = _hidden(vaex.utils.deprecated('use _future')(_future)) def __getattr__(self, name): if name in self.__hidden__: return self.__hidden__[name].__get__(self) else: return object.__getattribute__(self, name) def _ipython_key_completions_(self): return self.get_column_names() @property def func(self): class Functions(object): pass functions = Functions() for name, value in expression_namespace.items(): def closure(name=name, value=value): local_name = name def wrap(*args, **kwargs): def myrepr(k): if isinstance(k, Expression): return str(k) elif isinstance(k, np.ndarray) and k.ndim == 0: return myrepr(k.item()) elif isinstance(k, np.ndarray): var = self.add_variable('arg_numpy_array', k, unique=True) return var elif isinstance(k, list): return '[' + ', '.join(myrepr(i) for i in k) + ']' else: return repr(k) arg_string = ", ".join([myrepr(k) for k in args] + ['{}={}'.format(name, myrepr(value)) for name, value in kwargs.items()]) expression = "{}({})".format(local_name, arg_string) return vaex.expression.Expression(self, expression) return wrap f = closure() try: f = functools.wraps(value)(f) except AttributeError: pass setattr(functions, name, f) for name, value in self.functions.items(): setattr(functions, name, value) return functions @_hidden @vaex.utils.deprecated('use is_category') def iscategory(self, column): return self.is_category(column) def is_datetime(self, expression): dtype = self.data_type(expression) return isinstance(dtype, np.dtype) and dtype.kind == 'M' def is_string(self, expression): return vaex.array_types.is_string_type(self.data_type(expression)) def is_category(self, column): column = _ensure_string_from_expression(column) if self.is_local() and column in self.columns: # TODO: we don't support categories as expressions dtype = vaex.dtype_of(self.columns[column]) if dtype.is_encoded: return True return column in self._categories def _category_dictionary(self, column): if column in self.columns: x = self.columns[column] dtype = vaex.dtype_of(x) if dtype.is_encoded: x = x[:1] if isinstance(x, pa.ChunkedArray): # take the first dictionaryu x = x.chunks[0] dictionary = x.dictionary return dictionary def category_labels(self, column, aslist=True): column = _ensure_string_from_expression(column) if column in self._categories: return self._categories[column]['labels'] dictionary = self._category_dictionary(column) if dictionary is not None: if aslist: dictionary = dictionary.to_pylist() return dictionary else: raise ValueError(f'Column {column} is not a categorical') def category_values(self, column): column = _ensure_string_from_expression(column) return self._categories[column]['values'] def category_count(self, column): column = _ensure_string_from_expression(column) if column in self._categories: return self._categories[column]['N'] dictionary = self._category_dictionary(column) if dictionary is not None: return len(dictionary) else: raise ValueError(f'Column {column} is not a categorical') def category_offset(self, column): column = _ensure_string_from_expression(column) if column in self._categories: return self._categories[column]['min_value'] dictionary = self._category_dictionary(column) if dictionary is not None: return 0 else: raise ValueError(f'Column {column} is not a categorical') def execute(self): # make sure we only add the tasks at the last moment, after all operations are added (for cache keys) if not self.executor.tasks: logger.info('no task to execute') return if _REPORT_EXECUTION_TRACES: import traceback trace = ''.join(traceback.format_stack(limit=_REPORT_EXECUTION_TRACES)) print('Execution triggerd from:\n', trace) print("Tasks:") for task in self.executor.tasks: print(repr(task)) if self.executor.tasks: self.executor.execute() async def execute_async(self): await self.executor.execute_async() @property def filtered(self): return self.has_selection(FILTER_SELECTION_NAME) def map_reduce(self, map, reduce, arguments, progress=False, delay=False, info=False, to_numpy=True, ignore_filter=False, pre_filter=False, name='map reduce (custom)', selection=None): # def map_wrapper(*blocks): pre_filter = pre_filter and self.filtered task = tasks.TaskMapReduce(self, arguments, map, reduce, info=info, to_numpy=to_numpy, ignore_filter=ignore_filter, selection=selection, pre_filter=pre_filter) progressbar = vaex.utils.progressbars(progress) progressbar.add_task(task, f'map reduce: {name}') task = self.executor.schedule(task) return self._delay(delay, task) def apply(self, f, arguments=None, vectorize=False, multiprocessing=True): assert arguments is not None, 'for now, you need to supply arguments' import types if isinstance(f, types.LambdaType): name = 'lambda_function' else: name = f.__name__ if not vectorize: f = vaex.expression.FunctionToScalar(f, multiprocessing) else: f = vaex.expression.FunctionSerializablePickle(f, multiprocessing) lazy_function = self.add_function(name, f, unique=True) arguments = _ensure_strings_from_expressions(arguments) return lazy_function(*arguments) @docsubst def nop(self, expression=None, progress=False, delay=False): if expression is None: expressions = self.get_column_names() else: expressions = _ensure_list(_ensure_strings_from_expressions(expression)) def map(*ar): pass def reduce(a, b): pass return self.map_reduce(map, reduce, expressions, delay=delay, progress=progress, name='nop', to_numpy=False) def _hash_map_unique(self, expression, progress=False, selection=None, flatten=True, delay=False, limit=None, limit_raise=True, return_inverse=False): if selection is not None: selection = str(selection) expression = _ensure_string_from_expression(expression) task = vaex.tasks.TaskHashmapUniqueCreate(self, expression, flatten, limit=limit, selection=selection, return_inverse=return_inverse, limit_raise=limit_raise) task = self.executor.schedule(task) progressbar = vaex.utils.progressbars(progress) progressbar.add_task(task, f"set for {str(expression)}") return self._delay(delay, task) # kept for compatibility _set = _hash_map_unique def _index(self, expression, progress=False, delay=False, prime_growth=False, cardinality=None): column = _ensure_string_from_expression(expression) # TODO: this does not seem needed # column = vaex.utils.valid_expression(self.dataset, column) columns = [column] from .hash import index_type_from_dtype from vaex.column import _to_string_sequence transient = self[column].transient or self.filtered or self.is_masked(column) if self.is_string(expression) and not transient: # string is a special case, only ColumnString are not transient ar = self.columns[str(self[column].expand())] if not isinstance(ar, ColumnString): transient = True dtype = self.data_type(column) index_type = index_type_from_dtype(dtype, transient, prime_growth=prime_growth) import queue if cardinality is not None: N_index = min(self.executor.thread_pool.nthreads, max(1, len(self)//cardinality)) capacity_initial = len(self) // N_index else: N_index = self.executor.thread_pool.nthreads capacity_initial = 10 indices = queue.Queue() # we put None to lazily create them for i in range(N_index): indices.put(None) def map(thread_index, i1, i2, selection_masks, blocks): ar = blocks[0] index = indices.get() if index is None: index = index_type(1) if hasattr(index, 'reserve'): index.reserve(capacity_initial) if vaex.array_types.is_string_type(dtype): previous_ar = ar ar = _to_string_sequence(ar) if not transient: assert ar is previous_ar.string_sequence if np.ma.isMaskedArray(ar): mask = np.ma.getmaskarray(ar) index.update(ar, mask, i1) else: index.update(ar, i1) indices.put(index) # cardinality_estimated = sum() def reduce(a, b): pass self.map_reduce(map, reduce, columns, delay=delay, name='index', info=True, to_numpy=False) index_list = [] #[k for k in index_list if k is not None] while not indices.empty(): index = indices.get(timeout=10) if index is not None: index_list.append(index) index0 = index_list[0] for other in index_list[1:]: index0.merge(other) return index0 @docsubst def unique(self, expression, return_inverse=False, dropna=False, dropnan=False, dropmissing=False, progress=False, selection=None, axis=None, delay=False, limit=None, limit_raise=True, array_type='python'): if dropna: dropnan = True dropmissing = True if axis is not None: raise ValueError('only axis=None is supported') expression = _ensure_string_from_expression(expression) if self._future_behaviour and self.is_category(expression): if self.filtered: keys = pa.array(self.category_labels(expression)) @delayed def encode(codes): used_keys = keys.take(codes) return vaex.array_types.convert(used_keys, array_type) codes = self[expression].index_values().unique(delay=True) return self._delay(delay, encode(codes)) else: keys = pa.array(self.category_labels(expression)) keys = vaex.array_types.convert(keys, array_type) return self._delay(delay, vaex.promise.Promise.fulfilled(keys)) else: @delayed def process(hash_map_unique): transient = True data_type_item = self.data_type(expression, axis=-1) if return_inverse: # inverse type can be smaller, depending on length of set inverse = np.zeros(self._length_unfiltered, dtype=np.int64) dtype = self.data_type(expression) from vaex.column import _to_string_sequence def map(thread_index, i1, i2, selection_mask, blocks): ar = blocks[0] if vaex.array_types.is_string_type(dtype): previous_ar = ar ar = _to_string_sequence(ar) if not transient: assert ar is previous_ar.string_sequence # TODO: what about masked values? inverse[i1:i2] = hash_map_unique.map(ar) def reduce(a, b): pass self.map_reduce(map, reduce, [expression], delay=delay, name='unique_return_inverse', progress=progress_inverse, info=True, to_numpy=False, selection=selection) # ordered_set.seal() # if array_type == 'python': if data_type_item.is_object: key_values = hash_map_unique._internal.extract() keys = list(key_values.keys()) counts = list(key_values.values()) if hash_map_unique.has_nan and not dropnan: keys = [np.nan] + keys counts = [hash_map_unique.nan_count] + counts if hash_map_unique.has_null and not dropmissing: keys = [None] + keys counts = [hash_map_unique.null_count] + counts if dropmissing and None in keys: # we still can have a None in the values index = keys.index(None) keys.pop(index) counts.pop(index) counts = np.array(counts) keys = np.array(keys) else: keys = hash_map_unique.keys() # TODO: we might want to put the dropmissing in .keys(..) deletes = [] if dropmissing and hash_map_unique.has_null: deletes.append(hash_map_unique.null_index) if dropnan and hash_map_unique.has_nan: deletes.append(hash_map_unique.nan_index) if isinstance(keys, (vaex.strings.StringList32, vaex.strings.StringList64)): keys = vaex.strings.to_arrow(keys) indices = np.delete(np.arange(len(keys)), deletes) keys = keys.take(indices) else: keys = np.delete(keys, deletes) if not dropmissing and hash_map_unique.has_null: mask = np.zeros(len(keys), dtype=np.uint8) mask[hash_map_unique.null_index] = 1 keys = np.ma.array(keys, mask=mask) if data_type_item == str and isinstance(keys, np.ndarray): # the np.delete will cast to dtype object keys = pa.array(keys) keys = vaex.array_types.convert(keys, array_type) if return_inverse: return keys, inverse else: return keys progressbar = vaex.utils.progressbars(progress, title="unique") hash_map_result = self._hash_map_unique(expression, progress=progressbar, selection=selection, flatten=axis is None, delay=True, limit=limit, limit_raise=limit_raise) if return_inverse: progress_inverse = progressbar.add("find inverse") return self._delay(delay, progressbar.exit_on(process(hash_map_result))) @docsubst def mutual_information(self, x, y=None, dimension=2, mi_limits=None, mi_shape=256, binby=[], limits=None, shape=default_shape, sort=False, selection=False, delay=False): # either a list of tuples with custom combinations if y is None and _issequence(x) and all([_issequence(k) for k in x]): waslist, [combinations, ] = vaex.utils.listify(x) shape_result = (len(combinations),) elif _issequence(x) and (_issequence(y) or y is None): # or ask for a matrix of combinations if y is None: combinations = list(itertools.product(x, repeat=dimension)) shape_result = (len(x), ) * dimension else: shape_result = (len(x), len(y)) combinations = np.array([[(i, j) for i in y] for j in x]).reshape((-1, 2)).tolist() waslist = True elif _issequence(x): shape_result = (len(x),) combinations = [(i, y) for i in x] waslist = True elif _issequence(y): shape_result = (len(y),) combinations = [(i, y) for i in x] waslist = True else: shape_result = tuple() combinations = [(x, y)] waslist = False if mi_limits: mi_limits = [mi_limits] limits = self.limits(binby, limits, delay=True) # make sure we only do the unique combinations combinations_sorted = [tuple(sorted(k)) for k in combinations] combinations_unique, unique_reverse = np.unique(combinations_sorted, return_inverse=True, axis=0) combinations_unique = list(map(tuple, combinations_unique.tolist())) mi_limits = self.limits(combinations_unique, mi_limits, delay=True) @delayed def calculate(counts): # TODO: mutual information doesn't take axis arguments, so ugly solution for now counts = counts.astype(np.float64) fullshape = _expand_shape(shape, len(binby)) out = np.zeros((fullshape), dtype=float) if len(fullshape) == 0: out = vaex.kld.mutual_information(counts) elif len(fullshape) == 1: for i in range(fullshape[0]): out[i] = vaex.kld.mutual_information(counts[..., i]) elif len(fullshape) == 2: for i in range(fullshape[0]): for j in range(fullshape[1]): out[i, j] = vaex.kld.mutual_information(counts[..., i, j]) elif len(fullshape) == 3: for i in range(fullshape[0]): for j in range(fullshape[1]): for k in range(fullshape[2]): out[i, j, k] = vaex.kld.mutual_information(counts[..., i, j, k]) else: raise ValueError("binby with dim > 3 is not yet supported") return out @delayed def has_limits(limits, mi_limits): if not _issequence(binby): limits = [list(limits)] values = [] for expressions, expression_limits in zip(combinations_unique, mi_limits): total_shape = _expand_shape(mi_shape, len(expressions)) + _expand_shape(shape, len(binby)) counts = self.count(binby=list(expressions) + list(binby), limits=list(expression_limits) + list(limits), shape=total_shape, delay=True, selection=selection) values.append(calculate(counts)) return values @delayed def finish(mi_list): if sort: mi_list = np.array(mi_list) indices = np.argsort(mi_list)[::-1] sorted_x = list([x[k] for k in indices]) return mi_list[indices], sorted_x else: mi_list = np.array(mi_list) mi_list = mi_list[unique_reverse] total_shape = _expand_shape(shape, len(binby)) total_shape += shape_result return np.array(vaex.utils.unlistify(waslist, mi_list)).reshape(total_shape) values = finish(delayed_list(has_limits(limits, mi_limits))) return self._delay(delay, values) def bin_edges(self, expression, limits, shape=default_shape): return self.bins(expression, limits, shape=shape, edges=True) def bin_centers(self, expression, limits, shape=default_shape): return self.bins(expression, limits, shape=shape, edges=False) def bins(self, expression, limits, shape=default_shape, edges=True): vmin, vmax = limits if edges: bins = np.ogrid[limits[0]:limits[1]:(shape + 1) * 1j] return bins else: dx = (limits[1] - limits[0]) / shape bins = np.ogrid[limits[0]:limits[1] - dx:(shape) * 1j] return bins + dx / 2 def nearest_bin(self, value, limits, shape): bins = self.bins('', limits=limits, edges=False, shape=shape) index = np.argmin(np.abs(bins - value)) return index def _compute_agg(self, name, expression, binby=[], limits=None, shape=default_shape, selection=False, delay=False, edges=False, progress=None, extra_expressions=None, array_type=None): logger.debug("aggregate %s(%r, binby=%r, limits=%r)", name, expression, binby, limits) expression = _ensure_strings_from_expressions(expression) if extra_expressions: extra_expressions = _ensure_strings_from_expressions(extra_expressions) expression_waslist, [expressions, ] = vaex.utils.listify(expression) # expressions = [self._column_aliases.get(k, k) for k in expressions] import traceback trace = ''.join(traceback.format_stack()) for expression in expressions: if expression and expression != "*": self.validate_expression(expression) if not hasattr(self.local, '_aggregator_nest_count'): self.local._aggregator_nest_count = 0 if self.local._aggregator_nest_count != 0: raise RuntimeError("nested aggregator call: \nlast trace:\n%s\ncurrent trace:\n%s" % (self.local.last_trace, trace)) else: self.local.last_trace = trace # Instead of 'expression is not None', we would like to have 'not virtual' # but in agg.py we do some casting, which results in calling .dtype(..) with a non-column # expression even though all expressions passed here are column references # virtual = [k for k in expressions if k and k not in self.columns] if self._future_behaviour != 5 and (self.filtered and expression not in [None, '*']): # When our dataframe is filtered, and we have expressions, we may end up calling # df.dtype(..) which in turn may call df.evaluate(..) which in turn needs to have # the filter cache filled in order to compute the first non-missing row. This last # item could call df.count() again, leading to nested aggregators, which we do not # support. df.dtype() needs to call evaluate with filtering enabled since we consider # it invalid that expressions are evaluate with filtered data. Sklearn for instance may # give errors when evaluated with NaN's present. progressbar = vaex.utils.progressbars(progress, title=name) if not isinstance(binby, (list, tuple)) or len(binby) > 0: progressbar_limits = progressbar.add("binners") binners = self._create_binners(binby, limits, shape, selection=selection, delay=True, progress=progressbar_limits) else: binners = () progressbar_agg = progressbar @delayed def compute(expression, binners, selection, edges): binners = tuple(binners) if not hasattr(self.local, '_aggregator_nest_count'): self.local._aggregator_nest_count = 0 self.local._aggregator_nest_count += 1 try: if expression in ["*", None]: agg = vaex.agg.aggregates[name](selection=selection, edges=edges) else: if extra_expressions: agg = vaex.agg.aggregates[name](expression, *extra_expressions, selection=selection, edges=edges) else: agg = vaex.agg.aggregates[name](expression, selection=selection, edges=edges) tasks, result = agg.add_tasks(self, binners, progress=progressbar) @delayed def finish(counts): return np.asanyarray(counts) return finish(result) finally: self.local._aggregator_nest_count -= 1 @delayed def finish(binners, *counts): if array_type == 'xarray': dims = [binner.expression for binner in binners] if expression_waslist: dims = ['expression'] + dims def to_coord(binner): if isinstance(binner, BinnerOrdinal): return self.category_labels(binner.expression) elif isinstance(binner, BinnerScalar): return self.bin_centers(binner.expression, [binner.minimum, binner.maximum], binner.count) coords = [to_coord(binner) for binner in binners] if expression_waslist: coords = [expressions] + coords counts = np.asanyarray(counts) else: counts = counts[0] return xarray.DataArray(counts, dims=dims, coords=coords) elif array_type == 'list': return vaex.utils.unlistify(expression_waslist, counts).tolist() elif array_type in [None, 'numpy']: def possibly_masked_array(ar): if isinstance(ar, (list, tuple)): has_mask = any(np.ma.isMaskedArray(k) for k in ar) else: has_mask = np.ma.isMaskedArray(ar) if has_mask: return np.ma.array(ar) else: return np.asanyarray(ar) return possibly_masked_array(vaex.utils.unlistify(expression_waslist, counts)) else: raise RuntimeError(f'Unknown array_type {format}') stats = [compute(expression, binners, selection=selection, edges=edges) for expression in expressions] var = finish(binners, *stats) return self._delay(delay, progressbar.exit_on(var)) @docsubst def count(self, expression=None, binby=[], limits=None, shape=default_shape, selection=False, delay=False, edges=False, progress=None, array_type=None): return self._compute_agg('count', expression, binby, limits, shape, selection, delay, edges, progress, array_type=array_type) @delayed def _first_calculation(self, expression, order_expression, binby, limits, shape, selection, edges, progressbar): if shape: limits, shapes = limits else: limits, shapes = limits, shape task = tasks.TaskStatistic(self, binby, shapes, limits, weights=[expression, order_expression], op=tasks.OP_FIRST, selection=selection, edges=edges) task = self.executor.schedule(task) progressbar.add_task(task, "count for %s" % expression) @delayed def finish(counts): counts = np.array(counts) return counts return finish(task) @docsubst def first(self, expression, order_expression=None, binby=[], limits=None, shape=default_shape, selection=False, delay=False, edges=False, progress=None, array_type=None): return self._compute_agg('first', expression, binby, limits, shape, selection, delay, edges, progress, extra_expressions=[order_expression], array_type=array_type) logger.debug("count(%r, binby=%r, limits=%r)", expression, binby, limits) logger.debug("count(%r, binby=%r, limits=%r)", expression, binby, limits) expression = _ensure_strings_from_expressions(expression) order_expression = _ensure_string_from_expression(order_expression) binby = _ensure_strings_from_expressions(binby) waslist, [expressions,] = vaex.utils.listify(expression) @delayed def finish(*counts): counts = np.asarray(counts) return vaex.utils.unlistify(waslist, counts) progressbar = vaex.utils.progressbars(progress) limits = self.limits(binby, limits, delay=True, shape=shape) stats = [self._first_calculation(expression, order_expression, binby=binby, limits=limits, shape=shape, selection=selection, edges=edges, progressbar=progressbar) for expression in expressions] var = finish(*stats) return self._delay(delay, var) @docsubst def last(self, expression, order_expression=None, binby=[], limits=None, shape=default_shape, selection=False, delay=False, edges=False, progress=None, array_type=None): return self._compute_agg('last', expression, binby, limits, shape, selection, delay, edges, progress, extra_expressions=[order_expression], array_type=array_type) @docsubst @stat_1d def mean(self, expression, binby=[], limits=None, shape=default_shape, selection=False, delay=False, progress=None, edges=False, array_type=None): return self._compute_agg('mean', expression, binby, limits, shape, selection, delay, edges, progress, array_type=array_type) logger.debug("mean of %r, with binby=%r, limits=%r, shape=%r, selection=%r, delay=%r", expression, binby, limits, shape, selection, delay) expression = _ensure_strings_from_expressions(expression) selection = _ensure_strings_from_expressions(selection) binby = _ensure_strings_from_expressions(binby) @delayed def calculate(expression, limits): task = tasks.TaskStatistic(self, binby, shape, limits, weight=expression, op=tasks.OP_ADD_WEIGHT_MOMENTS_01, selection=selection) task = self.executor.schedule(task) progressbar.add_task(task, "mean for %s" % expression) return task @delayed def finish(*stats_args): stats = np.array(stats_args) counts = stats[..., 0] with np.errstate(divide='ignore', invalid='ignore'): mean = stats[..., 1] / counts return vaex.utils.unlistify(waslist, mean) waslist, [expressions, ] = vaex.utils.listify(expression) progressbar = vaex.utils.progressbars(progress) limits = self.limits(binby, limits, delay=True) stats = [calculate(expression, limits) for expression in expressions] var = finish(*stats) return self._delay(delay, var) @delayed def _sum_calculation(self, expression, binby, limits, shape, selection, progressbar): task = tasks.TaskStatistic(self, binby, shape, limits, weight=expression, op=tasks.OP_ADD_WEIGHT_MOMENTS_01, selection=selection) task = self.executor.schedule(task) progressbar.add_task(task, "sum for %s" % expression) @delayed def finish(sum_grid): stats = np.array(sum_grid) return stats[...,1] return finish(task) @docsubst @stat_1d def sum(self, expression, binby=[], limits=None, shape=default_shape, selection=False, delay=False, progress=None, edges=False, array_type=None): return self._compute_agg('sum', expression, binby, limits, shape, selection, delay, edges, progress, array_type=array_type) @delayed def finish(*sums): return vaex.utils.unlistify(waslist, sums) expression = _ensure_strings_from_expressions(expression) binby = _ensure_strings_from_expressions(binby) waslist, [expressions, ] = vaex.utils.listify(expression) progressbar = vaex.utils.progressbars(progress) limits = self.limits(binby, limits, delay=True) sums = [self._sum_calculation(expression, binby=binby, limits=limits, shape=shape, selection=selection, progressbar=progressbar) for expression in expressions] s = finish(*sums) return self._delay(delay, s) @docsubst @stat_1d def std(self, expression, binby=[], limits=None, shape=default_shape, selection=False, delay=False, progress=None, array_type=None): @delayed def finish(var): return var**0.5 return self._delay(delay, finish(self.var(expression, binby=binby, limits=limits, shape=shape, selection=selection, delay=True, progress=progress))) @docsubst @stat_1d def var(self, expression, binby=[], limits=None, shape=default_shape, selection=False, delay=False, progress=None, array_type=None): edges = False return self._compute_agg('var', expression, binby, limits, shape, selection, delay, edges, progress, array_type=array_type) @docsubst def skew(self, expression, binby=[], limits=None, shape=default_shape, selection=False, delay=False, progress=None, edges=False, array_type=None): edges=False return self._compute_agg('skew', expression, binby, limits, shape, selection, delay, edges, progress, array_type=array_type) @docsubst def kurtosis(self, expression, binby=[], limits=None, shape=default_shape, selection=False, delay=False, progress=None, edges=False, array_type=None): edges=False return self._compute_agg('kurtosis', expression, binby, limits, shape, selection, delay, edges, progress, array_type=array_type) @docsubst def covar(self, x, y, binby=[], limits=None, shape=default_shape, selection=False, delay=False, progress=None): @delayed def cov(mean_x, mean_y, mean_xy): return mean_xy - mean_x * mean_y waslist, [xlist, ylist] = vaex.utils.listify(x, y) limits = self.limits(binby, limits, selection=selection, delay=True) @delayed def calculate(limits): results = [] for x, y in zip(xlist, ylist): mx = self.mean(x, binby=binby, limits=limits, shape=shape, selection=selection, delay=True, progress=progressbar) my = self.mean(y, binby=binby, limits=limits, shape=shape, selection=selection, delay=True, progress=progressbar) cxy = self.mean("(%s)*(%s)" % (x, y), binby=binby, limits=limits, shape=shape, selection=selection, delay=True, progress=progressbar) results.append(cov(mx, my, cxy)) return results progressbar = vaex.utils.progressbars(progress, title="covar") covars = calculate(limits) @delayed def finish(covars): value = np.array(vaex.utils.unlistify(waslist, covars)) return value return self._delay(delay, finish(delayed_list(covars))) @docsubst def correlation(self, x, y=None, binby=[], limits=None, shape=default_shape, sort=False, sort_key=np.abs, selection=False, delay=False, progress=None, array_type=None): selection = _normalize_selection(selection) progressbar = vaex.utils.progressbars(progress, title="correlation") if y is None: if not _issequence(x): raise ValueError("if y not given, x is expected to be a list or tuple, not %r" % x) if all([_issequence(k) and len(k) == 2 for k in x]): values = [] pairs = x x = [] y = [] for col1, col2 in pairs: x.append(col1) y.append(col2) values.append(self.correlation(col1, col2, delay=True, progress=progressbar)) @vaex.delayed def finish(values): return vaex.from_arrays(x=x, y=y, correlation=values) result = finish(values) else: result = self._correlation_matrix(x, binby=binby, limits=limits, shape=shape, selection=selection, delay=True, progress=progressbar, array_type=array_type) elif _issequence(x) and _issequence(y): result = delayed(np.array)([[self.correlation(x_, y_, binby=binby, limits=limits, shape=shape, selection=selection, delay=True, progress=progressbar) for y_ in y] for x_ in x]) elif _issequence(x): combinations = [(k, y) for k in x] result = delayed(np.array)([self.correlation(x_, y, binby=binby, limits=limits, shape=shape, selection=selection, delay=True, progress=progressbar)for x_ in x]) elif _issequence(y): combinations = [(x, k) for k in y] result = self.correlation(combinations, binby=binby, limits=limits, shape=shape, selection=selection, delay=True, progress=progressbar) else: @vaex.delayed def finish(matrix): return matrix[...,0,1] matrix = self._correlation_matrix([x, y], binby=binby, limits=limits, shape=shape, selection=selection, delay=True, progress=progressbar) result = finish(matrix) return self._delay(delay, result) @docsubst def _correlation_matrix(self, column_names=None, binby=[], limits=None, shape=default_shape, selection=False, delay=False, progress=None, array_type=None): if column_names is None: column_names = self.get_column_names() @delayed def normalize(cov_matrix): norm = cov_matrix[:] diag = np.diagonal(cov_matrix, axis1=-2, axis2=-1) norm = (diag[...,np.newaxis,:] * diag[...,np.newaxis]) ** 0.5 return cov_matrix/norm result = normalize(self.cov(column_names, binby=binby, limits=limits, shape=shape, selection=selection, delay=True, progress=progress)) @vaex.delayed def finish(array): if array_type == 'xarray': dims = binby + ['x', 'y'] coords = [column_names, column_names] return xarray.DataArray(array, dims=dims, coords=coords) else: return vaex.array_types.convert(array, array_type) return self._delay(delay, finish(result)) @docsubst def cov(self, x, y=None, binby=[], limits=None, shape=default_shape, selection=False, delay=False, progress=None): selection = _ensure_strings_from_expressions(selection) selection = _normalize_selection(selection) if y is None: if not _issequence(x): raise ValueError("if y argument is not given, x is expected to be sequence, not %r", x) expressions = x else: expressions = [x, y] expressions = _ensure_strings_from_expressions(expressions) N = len(expressions) binby = _ensure_list(binby) shape = _expand_shape(shape, len(binby)) limits = self.limits(binby, limits, selection=selection, delay=True) @delayed def calculate(expressions, limits): task = tasks.TaskStatistic(self, binby, shape, limits, weights=expressions, op=tasks.OP_COV, selection=selection) task = self.executor.schedule(task) progressbar.add_task(task, "covariance values for %r" % expressions) return task @delayed def finish(values): N = len(expressions) counts = values[..., :N] sums = values[..., N:2 * N] with np.errstate(divide='ignore', invalid='ignore'): means = sums / counts meansxy = means[..., None] * means[..., None, :] counts = values[..., 2 * N:2 * N + N**2] sums = values[..., 2 * N + N**2:] shape = counts.shape[:-1] + (N, N) counts = counts.reshape(shape) sums = sums.reshape(shape) with np.errstate(divide='ignore', invalid='ignore'): moments2 = sums / counts cov_matrix = moments2 - meansxy return cov_matrix progressbar = vaex.utils.progressbars(progress, title="cov") values = calculate(expressions, limits) cov_matrix = finish(values) return self._delay(delay, cov_matrix) @docsubst @stat_1d def minmax(self, expression, binby=[], limits=None, shape=default_shape, selection=False, delay=False, progress=None): selection = _ensure_strings_from_expressions(selection) selection = _normalize_selection(selection) @delayed def calculate(expression, limits): task = tasks.TaskStatistic(self, binby, shape, limits, weight=expression, op=tasks.OP_MIN_MAX, selection=selection) task = self.executor.schedule(task) progressbar.add_task(task, "minmax for %s" % expression) return task @delayed def finish(*minmax_list): value = vaex.utils.unlistify(waslist, np.array(minmax_list)) value = vaex.array_types.to_numpy(value) value = value.astype(data_type0.numpy) return value expression = _ensure_strings_from_expressions(expression) binby = _ensure_strings_from_expressions(binby) waslist, [expressions, ] = vaex.utils.listify(expression) column_names = self.get_column_names(hidden=True) expressions = [vaex.utils.valid_expression(column_names, k) for k in expressions] data_types = [self.data_type(expr) for expr in expressions] data_type0 = data_types[0] all_same_kind = all(isinstance(data_type.internal, np.dtype) for data_type in data_types) and all([k.kind == data_type0.kind for k in data_types]) if not (all_same_kind or all([k == data_type0 for k in data_types])): raise TypeError("cannot mix different dtypes in 1 minmax call") progressbar = vaex.utils.progressbars(progress, title="minmaxes") limits = self.limits(binby, limits, selection=selection, delay=True) all_tasks = [calculate(expression, limits) for expression in expressions] result = finish(*all_tasks) return self._delay(delay, result) @docsubst @stat_1d def min(self, expression, binby=[], limits=None, shape=default_shape, selection=False, delay=False, progress=None, edges=False, array_type=None): return self._compute_agg('min', expression, binby, limits, shape, selection, delay, edges, progress, array_type=array_type) @delayed def finish(result): return result[..., 0] return self._delay(delay, finish(self.minmax(expression, binby=binby, limits=limits, shape=shape, selection=selection, delay=delay, progress=progress))) @docsubst @stat_1d def max(self, expression, binby=[], limits=None, shape=default_shape, selection=False, delay=False, progress=None, edges=False, array_type=None): return self._compute_agg('max', expression, binby, limits, shape, selection, delay, edges, progress, array_type=array_type) @delayed def finish(result): return result[..., 1] return self._delay(delay, finish(self.minmax(expression, binby=binby, limits=limits, shape=shape, selection=selection, delay=delay, progress=progress))) @docsubst @stat_1d def median_approx(self, expression, percentage=50., binby=[], limits=None, shape=default_shape, percentile_shape=256, percentile_limits="minmax", selection=False, delay=False, progress=None): return self.percentile_approx(expression, 50, binby=binby, limits=limits, shape=shape, percentile_shape=percentile_shape, percentile_limits=percentile_limits, selection=selection, delay=delay, progress=progress) @docsubst def percentile_approx(self, expression, percentage=50., binby=[], limits=None, shape=default_shape, percentile_shape=1024, percentile_limits="minmax", selection=False, delay=False, progress=None): waslist, [expressions, ] = vaex.utils.listify(expression) if not isinstance(binby, (tuple, list)): binby = [binby] else: binby = binby @delayed def calculate(expression, shape, limits): return self.count(binby=list(binby) + [expression], shape=shape, limits=limits, selection=selection, delay=True, edges=True, progress=progress) @delayed def finish(percentile_limits, counts_list): results = [] for i, counts in enumerate(counts_list): counts = counts.astype(np.float64) nonnans = list([slice(2, -1, None) for k in range(len(counts.shape) - 1)]) nonnans.append(slice(1, None, None)) nonnans = tuple(nonnans) cumulative_grid = np.cumsum(counts.__getitem__(nonnans), -1) totalcounts = np.sum(counts.__getitem__(nonnans), -1) empty = totalcounts == 0 original_shape = counts.shape shape = cumulative_grid.shape counts = np.sum(counts, -1) edges_floor = np.zeros(shape[:-1] + (2,), dtype=np.int64) edges_ceil = np.zeros(shape[:-1] + (2,), dtype=np.int64) [] for p in percentages: if p == 0: percentiles.append(percentile_limits[i][0]) continue if p == 100: percentiles.append(percentile_limits[i][1]) continue values = np.array((totalcounts + 1) * p / 100.) values[empty] = 0 floor_values = np.array(np.floor(values)) ceil_values = np.array(np.ceil(values)) vaex.vaexfast.grid_find_edges(cumulative_grid, floor_values, edges_floor) vaex.vaexfast.grid_find_edges(cumulative_grid, ceil_values, edges_ceil) def index_choose(a, indices): # alternative to np.choise, which doesn't like the last dim to be >= 32 out = np.zeros(a.shape[:-1]) for i in np.ndindex(out.shape): out[i] = a[i + (indices[i],)] return out def calculate_x(edges, values): left, right = edges[..., 0], edges[..., 1] left_value = index_choose(cumulative_grid, left) right_value = index_choose(cumulative_grid, right) with np.errstate(divide='ignore', invalid='ignore'): u = np.array((values - left_value) / (right_value - left_value)) xleft, xright = percentile_limits[i][0] + (left - 0.5) * (percentile_limits[i][1] - percentile_limits[i][0]) / (shape[-1] - 3),\ percentile_limits[i][0] + (right - 0.5) * (percentile_limits[i][1] - percentile_limits[i][0]) / (shape[-1] - 3) x = xleft + (xright - xleft) * u return x x1 = calculate_x(edges_floor, floor_values) x2 = calculate_x(edges_ceil, ceil_values) u = values - floor_values x = x1 + (x2 - x1) * u percentiles.append(x) percentile = vaex.utils.unlistify(waslist_percentage, np.array(percentiles)) results.append(percentile) return results shape = _expand_shape(shape, len(binby)) percentile_shapes = _expand_shape(percentile_shape, len(expressions)) if percentile_limits: percentile_limits = _expand_limits(percentile_limits, len(expressions)) limits = self.limits(binby, limits, selection=selection, delay=True) percentile_limits = self.limits(expressions, percentile_limits, selection=selection, delay=True) @delayed def calculation(limits, percentile_limits): tasks = [calculate(expression, tuple(shape) + (percentile_shape, ), list(limits) + [list(percentile_limit)]) for percentile_shape, percentile_limit, expression in zip(percentile_shapes, percentile_limits, expressions)] return finish(percentile_limits, delayed_args(*tasks)) result = calculation(limits, percentile_limits) @delayed def finish2(grid): value = vaex.utils.unlistify(waslist, np.array(grid)) return value return self._delay(delay, finish2(result)) def _use_delay(self, delay): return delay == True def _delay(self, delay, task, progressbar=False): if task.isRejected: task.get() if delay: return task else: self.execute() return task.get() @docsubst def limits_percentage(self, expression, percentage=99.73, square=False, selection=False, progress=None, delay=False): logger.info("limits_percentage for %r, with percentage=%r", expression, percentage) progressbar = vaex.utils.progressbars(progress, title="limits_percentage") waslist, [expressions, ] = vaex.utils.listify(expression) limits = [] for expr in expressions: @delayed def compute(limits_minmax, expr=expr): @delayed def compute_limits(counts): cumcounts = np.concatenate([[0], np.cumsum(counts)]) cumcounts = cumcounts / cumcounts.max() f = (1 - percentage / 100.) / 2 x = np.linspace(vmin, vmax, size + 1) l = np.interp([f, 1 - f], cumcounts, x) return l vmin, vmax = limits_minmax size = 1024 * 16 counts = self.count(binby=expr, shape=size, limits=limits_minmax, selection=selection, progress=progressbar, delay=delay) return compute_limits(counts) limits_minmax = self.minmax(expr, selection=selection, delay=delay) limits1 = compute(limits_minmax=limits_minmax) limits.append(limits1) return self._delay(delay, progressbar.exit_on(delayed(vaex.utils.unlistify)(waslist, limits))) @docsubst def limits(self, expression, value=None, square=False, selection=None, delay=False, progress=None, shape=None): if expression == []: return [] if shape is None else ([], []) waslist, [expressions, ] = vaex.utils.listify(expression) expressions = _ensure_strings_from_expressions(expressions) selection = _ensure_strings_from_expressions(selection) if value is None: value = "minmax" if _is_limit(value) or not _issequence(value): values = (value,) * len(expressions) else: values = value values = [vaex.array_types.to_numpy(k) if isinstance(k, vaex.array_types.supported_arrow_array_types) else k for k in values] progressbar = vaex.utils.progressbars(progress, title="limits") initial_expressions, initial_values = expressions, values expression_values = dict() expression_shapes = dict() for i, (expression, value) in enumerate(zip(expressions, values)): if _issequence(expression): expressions = expression nested = True else: expressions = [expression] nested = False if _is_limit(value) or not _issequence(value): values = (value,) * len(expressions) else: values = value for j, (expression, value) in enumerate(zip(expressions, values)): if shape is not None: if _issequence(shape): shapes = shape else: shapes = (shape, ) * (len(expressions) if nested else len(initial_expressions)) shape_index = j if nested else i if not _is_limit(value): expression_values[(expression, value)] = None if self.is_category(expression): N = self._categories[_ensure_string_from_expression(expression)]['N'] expression_shapes[expression] = min(N, shapes[shape_index] if shape is not None else default_shape) else: expression_shapes[expression] = shapes[shape_index] if shape is not None else default_shape limits_list = [] for expression, value in expression_values.keys(): if self.is_category(expression): N = self._categories[_ensure_string_from_expression(expression)]['N'] limits = [-0.5, N-0.5] else: if isinstance(value, six.string_types): if value == "minmax": limits = self.minmax(expression, selection=selection, progress=progressbar, delay=True) else: match = re.match(r"([\d.]*)(\D*)", value) if match is None: raise ValueError("do not understand limit specifier %r, examples are 90%, 3sigma") else: number, type = match.groups() import ast number = ast.literal_eval(number) type = type.strip() if type in ["s", "sigma"]: limits = self.limits_sigma(number) elif type in ["ss", "sigmasquare"]: limits = self.limits_sigma(number, square=True) elif type in ["%", "percent"]: limits = self.limits_percentage(expression, number, selection=selection, delay=True, progress=progressbar) elif type in ["%s", "%square", "percentsquare"]: limits = self.limits_percentage(expression, number, selection=selection, square=True, delay=True) elif value is None: limits = self.minmax(expression, selection=selection, delay=True) else: limits = value limits_list.append(limits) if limits is None: raise ValueError("limit %r not understood" % value) expression_values[(expression, value)] = limits limits_list = delayed_args(*limits_list) @delayed def finish(limits_list): limits_outer = [] shapes_list = [] for expression, value in zip(initial_expressions, initial_values): if _issequence(expression): expressions = expression waslist2 = True else: expressions = [expression] waslist2 = False if _is_limit(value) or not _issequence(value): values = (value,) * len(expressions) else: values = value limits = [] shapes = [] for expression, value in zip(expressions, values): if not _is_limit(value): value = expression_values[(expression, value)] if not _is_limit(value): value = value.get() limits.append(value) shapes.append(expression_shapes[expression]) limits_outer.append(limits) shapes_list.append(shapes) else: limits_outer.append(limits[0]) shapes_list.append(shapes[0]) if shape: return vaex.utils.unlistify(waslist, limits_outer), vaex.utils.unlistify(waslist, shapes_list) else: return vaex.utils.unlistify(waslist, limits_outer) return self._delay(delay, progressbar.exit_on(finish(limits_list))) def mode(self, expression, binby=[], limits=None, shape=256, mode_shape=64, mode_limits=None, progressbar=False, selection=None): if len(binby) == 0: raise ValueError("only supported with binby argument given") else: try: len(shape) shape = tuple(shape) except: shape = len(binby) * (shape,) shape = (mode_shape,) + shape subspace = self(*(list(binby) + [expression])) if selection: subspace = subspace.selected() limits = self.limits(list(binby), limits) mode_limits = self.limits([expression], mode_limits) limits = list(limits) + list(mode_limits) counts = subspace.histogram(limits=limits, size=shape, progressbar=progressbar) indices = np.argmax(counts, axis=0) pmin, pmax = limits[-1] centers = np.linspace(pmin, pmax, mode_shape + 1)[:-1] centers += (centers[1] - centers[0]) / 2 modes = centers[indices] ok = counts.sum(axis=0) > 0 modes[~ok] = np.nan return modes @vaex.utils.deprecated('use df.widget.heatmap') def plot_widget(self, x, y, limits=None, f="identity", **kwargs): return self.widget.heatmap(x, y, limits=limits, transform=f, **kwargs) @vaex.utils.deprecated('use plot_widget') def plot_bq(self, x, y, grid=None, shape=256, limits=None, what="count(*)", figsize=None, f="identity", figure_key=None, fig=None, axes=None, xlabel=None, ylabel=None, title=None, show=True, selection=[None, True], colormap="afmhot", grid_limits=None, normalize="normalize", grid_before=None, what_kwargs={}, type="default", scales=None, tool_select=False, bq_cleanup=True, **kwargs): import vaex.ext.bqplot cls = vaex.ext.bqplot.get_class(type) plot2d = cls(df=self, x=x, y=y, grid=grid, shape=shape, limits=limits, what=what, f=f, figure_key=figure_key, fig=fig, selection=selection, grid_before=grid_before, grid_limits=grid_limits, normalize=normalize, colormap=colormap, what_kwargs=what_kwargs, **kwargs) if show: plot2d.show() return plot2d def healpix_count(self, expression=None, healpix_expression=None, healpix_max_level=12, healpix_level=8, binby=None, limits=None, shape=default_shape, delay=False, progress=None, selection=None): import healpy as hp if healpix_expression is None: if self.ucds.get("source_id", None) == 'meta.id;meta.main': healpix_expression = "source_id/34359738368" if healpix_expression is None: raise ValueError("no healpix_expression given, and was unable to guess") reduce_level = healpix_max_level - healpix_level NSIDE = 2**healpix_level nmax = hp.nside2npix(NSIDE) scaling = 4**reduce_level expr = "%s/%s" % (healpix_expression, scaling) binby = [expr] + ([] if binby is None else _ensure_list(binby)) shape = (nmax,) + _expand_shape(shape, len(binby) - 1) epsilon = 1. / scaling / 2 limits = [[-epsilon, nmax - epsilon]] + ([] if limits is None else limits) return self.count(expression, binby=binby, limits=limits, shape=shape, delay=delay, progress=progress, selection=selection) @docsubst @stat_1d def _stat(self, what="count(*)", what_kwargs={}, binby=[], limits=None, shape=default_shape, selection=False, delay=False, progress=None): waslist_what, [whats, ] = vaex.utils.listify(what) limits = self.limits(binby, limits, delay=True) waslist_selection, [selections] = vaex.utils.listify(selection) binby = _ensure_list(binby) what_labels = [] shape = _expand_shape(shape, len(binby)) total_grid = np.zeros((len(whats), len(selections)) + shape, dtype=float) @delayed def copy_grids(grids): total_grid[index] = grid @delayed def get_whats(limits): grids = [] for j, what in enumerate(whats): what = what.strip() index = what.index("(") groups = re.match(r"(.*)\((.*)\)", what).groups() if groups and len(groups) == 2: function = groups[0] arguments = groups[1].strip() if "," in arguments: arguments = arguments.split(",") functions = ["mean", "sum", "std", "var", "correlation", "covar", "min", "max"] unit_expression = None if function in ["mean", "sum", "std", "min", "max"]: unit_expression = arguments if function in ["var"]: unit_expression = "(%s) * (%s)" % (arguments, arguments) if function in ["covar"]: unit_expression = "(%s) * (%s)" % arguments if unit_expression: unit = self.unit(unit_expression) if unit: what_units = unit.to_string('latex_inline') if function in functions: grid = getattr(self, function)(arguments, binby=binby, limits=limits, shape=shape, selection=selections, progress=progress, delay=delay) elif function == "count": grid = self.count(arguments, binby, shape=shape, limits=limits, selection=selections, progress=progress, delay=delay) else: raise ValueError("Could not understand method: %s, expected one of %r'" % (function, functions)) # what_labels.append(what_label) grids.append(grid) # else: # raise ValueError("Could not understand 'what' argument %r, expected something in form: 'count(*)', 'mean(x)'" % what) return grids grids = get_whats(limits) # print grids # grids = delayed_args(*grids) @delayed def finish(grids): for i, grid in enumerate(grids): total_grid[i] = grid return total_grid[slice(None, None, None) if waslist_what else 0, slice(None, None, None) if waslist_selection else 0] s = finish(delayed_list(grids)) return self._delay(delay, s) plot = _requires('viz') plot1d = _requires('viz') scatter = _requires('viz') def plot3d(self, x, y, z, vx=None, vy=None, vz=None, vwhat=None, limits=None, grid=None, what="count(*)", shape=128, selection=[None, True], f=None, vcount_limits=None, smooth_pre=None, smooth_post=None, grid_limits=None, normalize="normalize", colormap="afmhot", figure_key=None, fig=None, lighting=True, level=[0.1, 0.5, 0.9], opacity=[0.01, 0.05, 0.1], level_width=0.1, show=True, **kwargs): import vaex.ext.ipyvolume # vaex.ext.ipyvolume. cls = vaex.ext.ipyvolume.PlotDefault plot3d = cls(df=self, x=x, y=y, z=z, vx=vx, vy=vy, vz=vz, grid=grid, shape=shape, limits=limits, what=what, f=f, figure_key=figure_key, fig=fig, selection=selection, smooth_pre=smooth_pre, smooth_post=smooth_post, grid_limits=grid_limits, vcount_limits=vcount_limits, normalize=normalize, colormap=colormap, **kwargs) if show: plot3d.show() return plot3d @property def col(self): class ColumnList(object): pass data = ColumnList() for name in self.get_column_names(): if name != 'col': # avoid recursion expression = getattr(self, name, None) if not isinstance(expression, Expression): expression = Expression(self, name) else: expression = Expression(self, name) setattr(data, name, expression) return data def close(self): self.dataset.close() def byte_size(self, selection=False, virtual=False): bytes_per_row = 0 N = self.count(selection=selection) extra = 0 for column in list(self.get_column_names(virtual=virtual)): dtype = self.data_type(column) #if dtype in [str_type, str] and dtype_internal.kind == 'O': if dtype == str: # TODO: document or fix this # is it too expensive to calculate this exactly? extra += self.columns[column].nbytes else: bytes_per_row += dtype.numpy.itemsize if np.ma.isMaskedArray(self.columns[column]): bytes_per_row += 1 return bytes_per_row * self.count(selection=selection) + extra @property def nbytes(self): return self.byte_size() def _shape_of(self, expression, filtered=True): # TODO: we don't seem to need it anymore, would expect a valid_expression() call , 1, filtered=False, array_type="numpy-arrow", parallel=False) dtype = vaex.dtype_of(sample) rows = len(self) if filtered else self.length_unfiltered() if dtype.is_arrow: return (rows,) else: return (rows,) + sample.shape[1:] # TODO: remove array_type and internal arguments? def data_type(self, expression, array_type=None, internal=False, axis=0): if isinstance(expression, vaex.expression.Expression): expression = expression._label expression = _ensure_string_from_expression(expression) data_type = None if expression in self.variables: data_type = np.float64(1).dtype elif self.is_local() and expression in self.columns.keys(): column = self.columns[expression] if hasattr(column, 'dtype'): # TODO: this probably would use data_type # to support Columns that wrap arrow arrays data_type = column.dtype data_type = self._auto_encode_type(expression, data_type) if isinstance(data_type, vaex.datatype.DataType): data_type = data_type.internal else: data = column[0:1] data = self._auto_encode_data(expression, data) else: expression = vaex.utils.valid_expression(self.get_column_names(hidden=True), expression) try: data = self.evaluate(expression, 0, 1, filtered=False, array_type=array_type, parallel=False) except: data = self.evaluate(expression, 0, 1, filtered=True, array_type=array_type, parallel=False) if data_type is None: # means we have to determine it from the data if isinstance(data, np.ndarray): data_type = data.dtype elif isinstance(data, Column): data = data.to_arrow() data_type = data.type else: # when we eval constants, let arrow find it out if isinstance(data, numbers.Number): data_type = pa.array([data]).type else: data_type = data.type # assuming arrow if array_type == "arrow": data_type = array_types.to_arrow_type(data_type) elif array_type == "numpy": data_type = array_types.to_numpy_type(data_type) elif array_type == "numpy-arrow": data_type = array_types.to_numpy_type(data_type, strict=False) elif array_type is None: data_type = data_type else: raise ValueError(f'Unknown array_type {array_type}') data_type = DataType(data_type) # ugly, but fixes df.x.apply(lambda x: str(x)) if not internal: if isinstance(data_type.internal, np.dtype) and data_type.kind in 'US': return DataType(pa.string()) if axis != 0: axis_data_type = [data_type] while data_type.is_list: data_type = data_type.value_type axis_data_type.append(data_type) data_type = axis_data_type[axis] return data_type @property def dtypes(self): from pandas import Series return Series({column_name:self.data_type(column_name) for column_name in self.get_column_names()}) def schema(self): return {column_name:self.data_type(column_name) for column_name in self.get_column_names()} @docsubst def schema_arrow(self, reduce_large=False): def reduce(type): if reduce_large and type == pa.large_string(): type = pa.string() return type return pa.schema({name: reduce(dtype.arrow) for name, dtype in self.schema().items()}) def is_masked(self, column): column = _ensure_string_from_expression(column) if column in self.dataset: return self.dataset.is_masked(column) else: ar = self.evaluate(column, i1=0, i2=1, parallel=False) if isinstance(ar, np.ndarray) and np.ma.isMaskedArray(ar): return True return False def label(self, expression, unit=None, output_unit=None, format="latex_inline"): label = expression unit = unit or self.unit(expression) try: # if we can convert the unit, use that for the labeling if output_unit and unit: # avoid unnecessary error msg'es output_unit.to(unit) unit = output_unit except: logger.exception("unit error") if unit is not None: label = "%s (%s)" % (label, unit.to_string('latex_inline')) return label def unit(self, expression, default=None): expression = _ensure_string_from_expression(expression) try: unit_or_quantity = eval(expression, expression_namespace, scopes.UnitScope(self)) unit = unit_or_quantity.unit if hasattr(unit_or_quantity, "unit") else unit_or_quantity unit_types = (astropy.units.core.UnitBase, ) return unit if isinstance(unit, unit_types) else None except: try: return eval(expression, expression_namespace, scopes.UnitScope(self, 1.)).unit except: # logger.exception("error evaluating unit expression: %s", expression) return default def ucd_find(self, ucds, exclude=[]): if isinstance(ucds, six.string_types): ucds = [ucds] if len(ucds) == 1: ucd = ucds[0] if ucd[0] == "^": # we want it to start with ucd = ucd[1:] columns = [name for name in self.get_column_names() if self.ucds.get(name, "").startswith(ucd) and name not in exclude] else: columns = [name for name in self.get_column_names() if ucd in self.ucds.get(name, "") and name not in exclude] return None if len(columns) == 0 else columns[0] else: columns = [self.ucd_find([ucd], exclude=exclude) for ucd in ucds] return None if None in columns else columns @vaex.utils.deprecated('Will most likely disappear or move') @_hidden def selection_favorite_add(self, name, selection_name="default"): selection = self.get_selection(name=selection_name) if selection: self.favorite_selections[name] = selection self.selections_favorite_store() else: raise ValueError("no selection exists") @vaex.utils.deprecated('Will most likely disappear or move') @_hidden def selection_favorite_remove(self, name): del self.favorite_selections[name] self.selections_favorite_store() @vaex.utils.deprecated('Will most likely disappear or move') @_hidden def selection_favorite_apply(self, name, selection_name="default", executor=None): self.set_selection(self.favorite_selections[name], name=selection_name, executor=executor) @vaex.utils.deprecated('Will most likely disappear or move') @_hidden def selections_favorite_store(self): path = os.path.join(self.get_private_dir(create=True), "favorite_selection.yaml") selections = collections.OrderedDict([(key, value.to_dict()) for key, value in self.favorite_selections.items()]) vaex.utils.write_json_or_yaml(path, selections) @vaex.utils.deprecated('Will most likely disappear or move') @_hidden def selections_favorite_load(self): try: path = os.path.join(self.get_private_dir(create=True), "favorite_selection.yaml") if os.path.exists(path): selections_dict = vaex.utils.read_json_or_yaml(path) for key, value in selections_dict.items(): self.favorite_selections[key] = selections.selection_from_dict(self, value) except: logger.exception("non fatal error") def get_private_dir(self, create=False): if self.is_local(): name = os.path.abspath(self.path).replace(os.path.sep, "_")[:250] # should not be too long for most os'es name = name.replace(":", "_") else: server = self.server name = "%s_%s_%s_%s" % (server.hostname, server.port, server.base_path.replace("/", "_"), self.name) dir = os.path.join(vaex.utils.get_private_dir(), "dfs", name) if create and not os.path.exists(dir): os.makedirs(dir) return dir def state_get(self, skip=None): if self._future_behaviour == 5: return self._state_get_vaex_5(skip=skip) else: if not ((skip is None) or (len(skip) == 1 and skip[0] is self.dataset)): raise ValueError(f'skip should be None or its own dataset') return self._state_get_pre_vaex_5() def state_set(self, state, use_active_range=False, keep_columns=None, set_filter=True, trusted=True, warn=True, delete_unused_columns = True): if self._future_behaviour == 5: return self._state_set_vaex_5(state, use_active_range=use_active_range, keep_columns=keep_columns, set_filter=set_filter, trusted=trusted, warn=warn) else: return self._state_set_pre_vaex_5(state, use_active_range=use_active_range, keep_columns=keep_columns, set_filter=set_filter, trusted=trusted, warn=warn, delete_unused_columns=delete_unused_columns) def _state_get_vaex_5(self, skip=None): virtual_names = list(self.virtual_columns.keys()) + list(self.variables.keys()) units = {key: str(value) for key, value in self.units.items()} ucds = {key: value for key, value in self.ucds.items() if key in virtual_names} descriptions = {key: value for key, value in self.descriptions.items()} selections = {name: self.get_selection(name) for name, history in self.selection_histories.items() if self.has_selection(name)} encoding = vaex.encoding.Encoding() state = dict(virtual_columns=dict(self.virtual_columns), column_names=list(self.column_names), variables={name: encoding.encode("variable", value) for name, value in self.variables.items()}, functions={name: encoding.encode("function", value) for name, value in self.functions.items()}, selections={name: encoding.encode("selection", value) for name, value in selections.items()}, description=self.description, ucds=ucds, units=units, descriptions=descriptions, active_range=[self._index_start, self._index_end] ) datasets = self.dataset.leafs() if skip is None else skip for dataset in datasets: encoding._object_specs[dataset.id] = None assert encoding.has_object_spec(dataset.id) if len(datasets) != 1: raise ValueError('Multiple datasets present, please pass skip= argument so we know which dataset not to include in the state.') dataset_main = datasets[0] if dataset_main is not self.dataset: data = encoding.encode('dataset', self.dataset) for dataset in datasets: assert encoding._object_specs[dataset.id] is None del encoding._object_specs[dataset.id] if data is not None: state['dataset'] = data state['dataset_missing'] = {'main': dataset_main.id} state['blobs'] = {key: base64.b64encode(value).decode('ascii') for key, value in encoding.blobs.items()} if encoding._object_specs: state['objects'] = encoding._object_specs return state def _state_set_vaex_5(self, state, use_active_range=False, keep_columns=None, set_filter=True, trusted=True, warn=True): self.description = state['description'] if use_active_range: self._index_start, self._index_end = state['active_range'] self._length_unfiltered = self._index_end - self._index_start if keep_columns: all_columns = self.get_column_names() for column_name in keep_columns: if column_name not in all_columns: raise KeyError(f'Column name {column_name} does not exist') encoding = vaex.encoding.Encoding() if 'blobs' in state: encoding.blobs = {key: base64.b64decode(value.encode('ascii')) for key, value in state['blobs'].items()} if 'objects' in state: encoding._object_specs = state['objects'] if 'dataset' in state: encoding.set_object(state['dataset_missing']['main'], self.dataset) self.dataset = encoding.decode('dataset', state['dataset']) for name, value in state['functions'].items(): self.add_function(name, encoding.decode("function", value, trusted=trusted)) self.column_names = [] self.virtual_columns = {} self.column_names = list(set(self.dataset) & set(state['column_names'])) if 'variables' in state: self.variables = {name: encoding.decode("variable", value) for name, value in state['variables'].items()} for name, value in state['virtual_columns'].items(): self[name] = self._expr(value) self.column_names = list(state['column_names']) if keep_columns: self.column_names += list(keep_columns) for name in self.column_names: self._save_assign_expression(name) if "units" in state: units = {key: astropy.units.Unit(value) for key, value in state["units"].items()} self.units.update(units) if 'selections' in state: for name, selection_dict in state['selections'].items(): selection = encoding.decode('selection', selection_dict) if name == FILTER_SELECTION_NAME and not set_filter: continue self.set_selection(selection, name=name) if self.is_local(): for name in self.dataset: if name not in self.column_names: del self.columns[name] def _state_get_pre_vaex_5(self): virtual_names = list(self.virtual_columns.keys()) + list(self.variables.keys()) units = {key: str(value) for key, value in self.units.items()} ucds = {key: value for key, value in self.ucds.items() if key in virtual_names} descriptions = {key: value for key, value in self.descriptions.items()} import vaex.serialize def check(key, value): if not vaex.serialize.can_serialize(value.f): warnings.warn('Cannot serialize function for virtual column {} (use vaex.serialize.register)'.format(key)) return False return True def clean(value): return vaex.serialize.to_dict(value.f) functions = {key: clean(value) for key, value in self.functions.items() if check(key, value)} virtual_columns = {key: value for key, value in self.virtual_columns.items()} selections = {name: self.get_selection(name) for name, history in self.selection_histories.items()} selections = {name: selection.to_dict() if selection is not None else None for name, selection in selections.items()} state = dict(virtual_columns=virtual_columns, column_names=self.column_names, renamed_columns=self._renamed_columns, variables=self.variables, functions=functions, selections=selections, ucds=ucds, units=units, descriptions=descriptions, description=self.description, active_range=[self._index_start, self._index_end]) return state def _state_set_pre_vaex_5(self, state, use_active_range=False, keep_columns=None, set_filter=True, trusted=True, warn=True, delete_unused_columns = True): if 'description' in state: self.description = state['description'] if use_active_range: if 'active_range' in state: self._index_start, self._index_end = state['active_range'] self._length_unfiltered = self._index_end - self._index_start if keep_columns: all_columns = self.get_column_names() for column_name in keep_columns: if column_name not in all_columns: raise KeyError(f'Column name {column_name} does not exist') if 'renamed_columns' in state: for old, new in state['renamed_columns']: if old in self: self._rename(old, new) elif warn: warnings.warn(f'The state wants to rename {old} to {new}, but {new} was not found, ignoring the rename') if 'functions' in state: for name, value in state['functions'].items(): self.add_function(name, vaex.serialize.from_dict(value, trusted=trusted)) if 'variables' in state: self.variables = state['variables'] if 'column_names' in state: self.column_names = [] self.virtual_columns = {} self.column_names = list(set(self.dataset) & set(state['column_names'])) if 'virtual_columns' in state: for name, value in state['virtual_columns'].items(): self[name] = self._expr(value) self.column_names = list(state['column_names']) if keep_columns: self.column_names += list(keep_columns) for name in self.column_names: self._save_assign_expression(name) else: self.virtual_columns = {} for name, value in state['virtual_columns'].items(): self[name] = self._expr(value) if 'units' in state: units = {key: astropy.units.Unit(value) for key, value in state["units"].items()} self.units.update(units) if 'selections' in state: for name, selection_dict in state['selections'].items(): if name == FILTER_SELECTION_NAME and not set_filter: continue if selection_dict is None: selection = None else: selection = selections.selection_from_dict(selection_dict) self.set_selection(selection, name=name) if self.is_local() and delete_unused_columns: for name in self.dataset: if name not in self.column_names: del self.columns[name] def state_write(self, file, fs_options=None, fs=None): fs_options = fs_options or {} vaex.utils.write_json_or_yaml(file, self.state_get(), fs_options=fs_options, fs=fs, old_style=not self._future_behaviour) def state_load(self, file, use_active_range=False, keep_columns=None, set_filter=True, trusted=True, fs_options=None, fs=None): state = vaex.utils.read_json_or_yaml(file, fs_options=fs_options, fs=fs, old_style=not self._future_behaviour) self.state_set(state, use_active_range=use_active_range, keep_columns=keep_columns, set_filter=set_filter, trusted=trusted) def remove_virtual_meta(self): dir = self.get_private_dir(create=True) path = os.path.join(dir, "virtual_meta.yaml") try: if os.path.exists(path): os.remove(path) if not os.listdir(dir): os.rmdir(dir) except: logger.exception("error while trying to remove %s or %s", path, dir) @_hidden def write_virtual_meta(self): path = os.path.join(self.get_private_dir(create=True), "virtual_meta.yaml") virtual_names = list(self.virtual_columns.keys()) + list(self.variables.keys()) units = {key: str(value) for key, value in self.units.items() if key in virtual_names} ucds = {key: value for key, value in self.ucds.items() if key in virtual_names} descriptions = {key: value for key, value in self.descriptions.items() if key in virtual_names} meta_info = dict(virtual_columns=self.virtual_columns, variables=self.variables, ucds=ucds, units=units, descriptions=descriptions) vaex.utils.write_json_or_yaml(path, meta_info) @_hidden def update_virtual_meta(self): try: path = os.path.join(self.get_private_dir(create=False), "virtual_meta.yaml") if os.path.exists(path): meta_info = vaex.utils.read_json_or_yaml(path) if 'virtual_columns' not in meta_info: return self.virtual_columns.update(meta_info["virtual_columns"]) self.variables.update(meta_info["variables"]) self.ucds.update(meta_info["ucds"]) self.descriptions.update(meta_info["descriptions"]) units = {key: astropy.units.Unit(value) for key, value in meta_info["units"].items()} self.units.update(units) except: logger.exception("non fatal error") @_hidden def write_meta(self): path = os.path.join(self.get_private_dir(create=True), "meta.yaml") units = {key: str(value) for key, value in self.units.items()} meta_info = dict(description=self.description, ucds=self.ucds, units=units, descriptions=self.descriptions, ) vaex.utils.write_json_or_yaml(path, meta_info) @_hidden def update_meta(self): try: path = os.path.join(self.get_private_dir(create=False), "meta.yaml") if os.path.exists(path): meta_info = vaex.utils.read_json_or_yaml(path) self.description = meta_info["description"] self.ucds.update(meta_info["ucds"]) self.descriptions.update(meta_info["descriptions"]) units = {key: astropy.units.Unit(value) for key, value in meta_info["units"].items()} self.units.update(units) except: logger.exception("non fatal error, but could read/understand %s", path) def is_local(self): raise NotImplementedError def get_auto_fraction(self): return self._auto_fraction def set_auto_fraction(self, enabled): self._auto_fraction = enabled @classmethod def can_open(cls, path, *args, **kwargs): return False @classmethod def get_options(cls, path): return [] @classmethod def option_to_args(cls, option): return [] def combinations(self, expressions_list=None, dimension=2, exclude=None, **kwargs): if dimension is not None: expressions_list = list(itertools.combinations(self.get_column_names(), dimension)) if exclude is not None: import six def excluded(expressions): if callable(exclude): return exclude(expressions) elif isinstance(exclude, six.string_types): return exclude in expressions elif isinstance(exclude, (list, tuple)): in exclude: if isinstance(e, six.string_types): if e in expressions: return True elif isinstance(e, (list, tuple)): if set(e).issubset(expressions): return True else: raise ValueError("elements of exclude should contain a string or a sequence of strings") else: raise ValueError("exclude should contain a string, a sequence of strings, or should be a callable") return False expressions_list = [expr for expr in expressions_list if not excluded(expr)] logger.debug("expression list generated: %r", expressions_list) return expressions_list def set_variable(self, name, expression_or_value, write=True): self.variables[name] = expression_or_value def get_variable(self, name): return self.variables[name] def evaluate_variable(self, name): if isinstance(self.variables[name], six.string_types): value = eval(self.variables[name], expression_namespace, self.variables) return value else: return self.variables[name] @docsubst def evaluate(self, expression, i1=None, i2=None, out=None, selection=None, filtered=True, array_type=None, parallel=True, chunk_size=None, progress=None): if chunk_size is not None: return self.evaluate_iterator(expression, s1=i1, s2=i2, out=out, selection=selection, filtered=filtered, array_type=array_type, parallel=parallel, chunk_size=chunk_size, progress=progress) else: return self._evaluate_implementation(expression, i1=i1, i2=i2, out=out, selection=selection, filtered=filtered, array_type=array_type, parallel=parallel, chunk_size=chunk_size, progress=progress) @docsubst def evaluate_iterator(self, expression, s1=None, s2=None, out=None, selection=None, filtered=True, array_type=None, parallel=True, chunk_size=None, prefetch=True, progress=None): progressbar = vaex.utils.progressbars(progress, title="evaluate iterator") import concurrent.futures self._fill_filter_mask() progressbar(0) if not prefetch: for l1, l2, i1, i2 in self._unfiltered_chunk_slices(chunk_size): yield l1, l2, self._evaluate_implementation(expression, i1=i1, i2=i2, out=out, selection=selection, filtered=filtered, array_type=array_type, parallel=parallel, raw=True) progressbar(l2/len(self)) else: with concurrent.futures.ThreadPoolExecutor(1) as executor: iter = self._unfiltered_chunk_slices(chunk_size) def f(i1, i2): return self._evaluate_implementation(expression, i1=i1, i2=i2, out=out, selection=selection, filtered=filtered, array_type=array_type, parallel=parallel, raw=True) try: previous_l1, previous_l2, previous_i1, previous_i2 = next(iter) except StopIteration: return previous = executor.submit(f, previous_i1, previous_i2) for l1, l2, i1, i2 in iter: previous_chunk = previous.result() current = executor.submit(f, i1, i2) yield previous_l1, previous_l2, previous_chunk progressbar(previous_l2/len(self)) previous = current previous_l1, previous_l2 = l1, l2 previous_chunk = previous.result() yield previous_l1, previous_l2, previous_chunk progressbar(previous_l2/len(self)) @docsubst def to_records(self, index=None, selection=None, column_names=None, strings=True, virtual=True, parallel=True, chunk_size=None, array_type='python'): if isinstance(index, int): return {key: value[0] for key, value in self[index:index + 1].to_dict(selection=selection, column_names=column_names, strings=strings, virtual=virtual, parallel=parallel, array_type=array_type).items()} if index is not None: raise RuntimeError(f"index can be None or an int - {type(index)} provided") if chunk_size is not None: def iterator(): for i1, i2, chunk in self.to_dict(selection=selection, column_names=column_names, strings=strings, virtual=virtual, parallel=parallel, chunk_size=chunk_size, array_type=array_type): keys = list(chunk.keys()) yield i1, i2, [{key: value for key, value in zip(keys, values)} for values in zip(*chunk.values())] return iterator() chunk = self.to_dict(selection=selection, column_names=column_names, strings=strings, virtual=virtual, parallel=parallel, chunk_size=chunk_size, array_type=array_type) keys = list(chunk.keys()) return [{key: value for key, value in zip(keys, values)} for values in zip(*chunk.values())] @docsubst def to_items(self, column_names=None, selection=None, strings=True, virtual=True, parallel=True, chunk_size=None, array_type=None): column_names = column_names or self.get_column_names(strings=strings, virtual=virtual) column_names = _ensure_strings_from_expressions(column_names) if chunk_size is not None: def iterator(): for i1, i2, chunks in self.evaluate_iterator(column_names, selection=selection, parallel=parallel, chunk_size=chunk_size): yield i1, i2, list(zip(column_names, [array_types.convert(chunk, array_type) for chunk in chunks])) return iterator() else: return list(zip(column_names, [array_types.convert(chunk, array_type) for chunk in self.evaluate(column_names, selection=selection, parallel=parallel)])) @docsubst def to_arrays(self, column_names=None, selection=None, strings=True, virtual=True, parallel=True, chunk_size=None, array_type=None): column_names = column_names or self.get_column_names(strings=strings, virtual=virtual) column_names = _ensure_strings_from_expressions(column_names) if chunk_size is not None: def iterator(): for i1, i2, chunks in self.evaluate_iterator(column_names, selection=selection, parallel=parallel, chunk_size=chunk_size): yield i1, i2, [array_types.convert(chunk, array_type) for chunk in chunks] return iterator() return [array_types.convert(chunk, array_type) for chunk in self.evaluate(column_names, selection=selection, parallel=parallel)] @docsubst def to_dict(self, column_names=None, selection=None, strings=True, virtual=True, parallel=True, chunk_size=None, array_type=None): column_names = column_names or self.get_column_names(strings=strings, virtual=virtual) column_names = _ensure_strings_from_expressions(column_names) if chunk_size is not None: def iterator(): for i1, i2, chunks in self.evaluate_iterator(column_names, selection=selection, parallel=parallel, chunk_size=chunk_size): yield i1, i2, dict(list(zip(column_names, [array_types.convert(chunk, array_type) for chunk in chunks]))) return iterator() return dict(list(zip(column_names, [array_types.convert(chunk, array_type) for chunk in self.evaluate(column_names, selection=selection, parallel=parallel)]))) @_hidden @docsubst @vaex.utils.deprecated('`.to_copy()` is deprecated and it will be removed in version 5.x. Please use `.copy()` instead.') def to_copy(self, column_names=None, selection=None, strings=True, virtual=True, selections=True): if column_names: column_names = _ensure_strings_from_expressions(column_names) df = vaex.from_items(*self.to_items(column_names=column_names, selection=selection, strings=strings, virtual=False)) if virtual: for name, value in self.virtual_columns.items(): df.add_virtual_column(name, value) if selections: for key, value in self.selection_histories.items(): if key != FILTER_SELECTION_NAME: df.selection_histories[key] = list(value) for key, value in self.selection_history_indices.items(): if key != FILTER_SELECTION_NAME: df.selection_history_indices[key] = value df.functions.update(self.functions) df.copy_metadata(self) return df def copy_metadata(self, other): for name in self.get_column_names(strings=True): if name in other.units: self.units[name] = other.units[name] if name in other.descriptions: self.descriptions[name] = other.descriptions[name] if name in other.ucds: self.ucds[name] = other.ucds[name] self.description = other.description @docsubst def to_pandas_df(self, column_names=None, selection=None, strings=True, virtual=True, index_name=None, parallel=True, chunk_size=None, array_type=None): import pandas as pd column_names = column_names or self.get_column_names(strings=strings, virtual=virtual) column_names = _ensure_strings_from_expressions(column_names) if index_name not in column_names and index_name is not None: column_names = column_names + [index_name] def create_pdf(data): if index_name is not None: index = data.pop(index_name) else: index = None df = pd.DataFrame(data=data, index=index) if index is not None: df.index.name = index_name return df if chunk_size is not None: def iterator(): for i1, i2, chunks in self.evaluate_iterator(column_names, selection=selection, parallel=parallel, chunk_size=chunk_size, array_type=array_type): yield i1, i2, create_pdf(dict(zip(column_names, chunks))) return iterator() else: return create_pdf(self.to_dict(column_names=column_names, selection=selection, parallel=parallel, array_type=array_type)) @docsubst def to_arrow_table(self, column_names=None, selection=None, strings=True, virtual=True, parallel=True, chunk_size=None, reduce_large=False): import pyarrow as pa column_names = column_names or self.get_column_names(strings=strings, virtual=virtual) column_names = _ensure_strings_from_expressions(column_names) if chunk_size is not None: def iterator(): for i1, i2, chunks in self.evaluate_iterator(column_names, selection=selection, parallel=parallel, chunk_size=chunk_size): chunks = list(map(vaex.array_types.to_arrow, chunks)) if reduce_large: chunks = list(map(vaex.array_types.arrow_reduce_large, chunks)) yield i1, i2, pa.Table.from_arrays(chunks, column_names) return iterator() else: chunks = self.evaluate(column_names, selection=selection, parallel=parallel) chunks = list(map(vaex.array_types.to_arrow, chunks)) if reduce_large: chunks = list(map(vaex.array_types.arrow_reduce_large, chunks)) return pa.Table.from_arrays(chunks, column_names) @docsubst def to_astropy_table(self, column_names=None, selection=None, strings=True, virtual=True, index=None, parallel=True): from astropy.table import Table, Column, MaskedColumn meta = dict() meta["description"] = self.description table = Table(meta=meta) for name, data in self.to_items(column_names=column_names, selection=selection, strings=strings, virtual=virtual, parallel=parallel): if self.is_string(name): data = np.array(data).astype('U') meta = dict() if name in self.ucds: meta["ucd"] = self.ucds[name] if np.ma.isMaskedArray(data): cls = MaskedColumn else: cls = Column table[name] = cls(data, unit=self.unit(name), description=self.descriptions.get(name), meta=meta) return table def to_dask_array(self, chunks="auto"): import dask.array as da import uuid dtype = self._dtype chunks = da.core.normalize_chunks(chunks, shape=self.shape, dtype=dtype.numpy) name = 'vaex-df-%s' % str(uuid.uuid1()) def getitem(df, item): return np.array(df.__getitem__(item).to_arrays(parallel=False)).T if hasattr(da.core, "getem"): dsk = da.core.getem(name, chunks, getitem=getitem, shape=self.shape, dtype=dtype.numpy) dsk[name] = self return da.Array(dsk, name, chunks, dtype=dtype.numpy) else: dsk = da.core.graph_from_arraylike(self, name=name, chunks=chunks, getitem=getitem, shape=self.shape, dtype=dtype.numpy) return da.Array(dsk, name, chunks, dtype=dtype.numpy) def validate_expression(self, expression): if str(expression) in self.virtual_columns: return if self.is_local() and str(expression) in self.columns: return vars = set(self.get_names(hidden=True)) | {'df'} funcs = set(expression_namespace.keys()) | set(self.functions.keys()) try: return vaex.expresso.validate_expression(expression, vars, funcs) except NameError as e: raise NameError(str(e)) from None def _block_scope(self, i1, i2): variables = {key: self.evaluate_variable(key) for key in self.variables.keys()} return scopes._BlockScope(self, i1, i2, **variables) def select(self, boolean_expression, mode="replace", name="default"): raise NotImplementedError def add_column(self, name, f_or_array, dtype=None): column_position = len(self.column_names) if name in self.get_column_names(): column_position = self.column_names.index(name) renamed = '__' +vaex.utils.find_valid_name(name, used=self.get_column_names()) self._rename(name, renamed) if isinstance(f_or_array, supported_column_types): data = ar = f_or_array if self._length_original is None: self._length_unfiltered = _len(data) self._length_original = _len(data) self._index_end = self._length_unfiltered if _len(ar) != self.length_original(): if self.filtered: if len(self) == len(ar): raise ValueError("Array is of length %s, while the length of the DataFrame is %s due to the filtering, the (unfiltered) length is %s." % (len(ar), len(self), self.length_unfiltered())) raise ValueError("array is of length %s, while the length of the DataFrame is %s" % (len(ar), self.length_original())) valid_name = vaex.utils.find_valid_name(name, used=self.get_column_names(hidden=True)) self.columns[valid_name] = ar if valid_name not in self.column_names: self.column_names.insert(column_position, valid_name) else: raise ValueError("functions not yet implemented") self._initialize_column(valid_name) def _initialize_column(self, name): self._save_assign_expression(name) def _sparse_matrix(self, column): column = _ensure_string_from_expression(column) return self._sparse_matrices.get(column) def add_columns(self, names, columns): from scipy.sparse import csc_matrix, csr_matrix if isinstance(columns, csr_matrix): if len(names) != columns.shape[1]: raise ValueError('number of columns ({}) does not match number of column names ({})'.format(columns.shape[1], len(names))) for i, name in enumerate(names): valid_name = vaex.utils.find_valid_name(name, used=self.get_column_names(hidden=True)) self.columns[valid_name] = ColumnSparse(columns, i) self.column_names.append(valid_name) self._sparse_matrices[valid_name] = columns self._save_assign_expression(valid_name) else: raise ValueError('only scipy.sparse.csr_matrix is supported') def _save_assign_expression(self, name, expression=None): obj = getattr(self, name, None) if obj is None or isinstance(obj, Expression): if expression is None: expression = name if isinstance(expression, str): expression = vaex.utils.valid_expression(self.get_column_names(hidden=True), expression) expression = Expression(self, expression) setattr(self, name, expression) @_hidden def add_column_healpix(self, name="healpix", longitude="ra", latitude="dec", degrees=True, healpix_order=12, nest=True): import healpy as hp if degrees: scale = "*pi/180" else: scale = "" # TODO: multithread this phi = self.evaluate("(%s)%s" % (longitude, scale)) theta = self.evaluate("pi/2-(%s)%s" % (latitude, scale)) hp_index = hp.ang2pix(hp.order2nside(healpix_order), theta, phi, nest=nest) self.add_column("healpix", hp_index) @_hidden def add_virtual_columns_matrix3d(self, x, y, z, xnew, ynew, znew, matrix, matrix_name='deprecated', matrix_is_expression=False, translation=[0, 0, 0], propagate_uncertainties=False): m = matrix x, y, z = self._expr(x, y, z) self[xnew] = m[0][0] * x + m[0][1] * y + m[0][2] * z + translation[0] self[ynew] = m[1][0] * x + m[1][1] * y + m[1][2] * z + translation[1] self[znew] = m[2][0] * x + m[2][1] * y + m[2][2] * z + translation[2] if propagate_uncertainties: self.propagate_uncertainties([self[xnew], self[ynew], self[znew]], [x, y, z]) # wrap these with an informative msg # add_virtual_columns_eq2ecl = _requires('astro') # add_virtual_columns_eq2gal = _requires('astro') # add_virtual_columns_distance_from_parallax = _requires('astro') # add_virtual_columns_cartesian_velocities_to_pmvr = _requires('astro') # add_virtual_columns_proper_motion_eq2gal = _requires('astro') # add_virtual_columns_lbrvr_proper_motion2vcartesian = _requires('astro') # add_virtual_columns_equatorial_to_galactic_cartesian = _requires('astro') # add_virtual_columns_celestial = _requires('astro') # add_virtual_columns_proper_motion2vperpendicular = _requires('astro') def _covariance_matrix_guess(self, columns, full=False, as_expression=False): all_column_names = self.get_column_names() columns = _ensure_strings_from_expressions(columns) def _guess(x, y): if x == y: postfixes = ["_error", "_uncertainty", "e", "_e"] prefixes = ["e", "e_"] for postfix in postfixes: if x + postfix in all_column_names: return x + postfix for prefix in prefixes: if prefix + x in all_column_names: return prefix + x if full: raise ValueError("No uncertainty found for %r" % x) else: postfixes = ["_cov", "_covariance"] for postfix in postfixes: if x + "_" + y + postfix in all_column_names: return x + "_" + y + postfix if y + "_" + x + postfix in all_column_names: return y + "_" + x + postfix postfixes = ["_correlation", "_corr"] for postfix in postfixes: if x + "_" + y + postfix in all_column_names: return x + "_" + y + postfix + " * " + _guess(x, x) + " * " + _guess(y, y) if y + "_" + x + postfix in all_column_names: return y + "_" + x + postfix + " * " + _guess(y, y) + " * " + _guess(x, x) if full: raise ValueError("No covariance or correlation found for %r and %r" % (x, y)) return "0" N = len(columns) cov_matrix = [[""] * N for i in range(N)] for i in range(N): for j in range(N): cov = _guess(columns[i], columns[j]) if i == j and cov: cov += "**2" # square the diagnal cov_matrix[i][j] = cov if as_expression: return [[self[k] for k in row] for row in cov_matrix] else: return cov_matrix def _jacobian(self, expressions, variables): expressions = _ensure_strings_from_expressions(expressions) return [[self[expression].expand(stop=[var]).derivative(var) for var in variables] for expression in expressions] def propagate_uncertainties(self, columns, depending_variables=None, cov_matrix='auto', covariance_format="{}_{}_covariance", uncertainty_format="{}_uncertainty"): names = _ensure_strings_from_expressions(columns) virtual_columns = self._expr(*columns, always_list=True) if depending_variables is None: depending_variables = set() for expression in virtual_columns: depending_variables |= expression.expand().variables() depending_variables = list(sorted(list(depending_variables))) fs = [self[self.virtual_columns[name]] for name in names] jacobian = self._jacobian(fs, depending_variables) m = len(fs) n = len(depending_variables) # n x n matrix cov_matrix = self._covariance_matrix_guess(depending_variables, full=cov_matrix == "full", as_expression=True) # empty m x m matrix cov_matrix_out = [[self['0'] for __ in range(m)] for __ in range(m)] for i in range(m): for j in range(m): for k in range(n): for l in range(n): if jacobian[i][k].expression == '0' or jacobian[j][l].expression == '0' or cov_matrix[k][l].expression == '0': pass else: cov_matrix_out[i][j] = cov_matrix_out[i][j] + jacobian[i][k] * cov_matrix[k][l] * jacobian[j][l] for i in range(m): for j in range(i + 1): sigma = cov_matrix_out[i][j] sigma = self._expr(vaex.expresso.simplify(_ensure_string_from_expression(sigma))) if i != j: self.add_virtual_column(covariance_format.format(names[i], names[j]), sigma) else: self.add_virtual_column(uncertainty_format.format(names[i]), np.sqrt(sigma)) @_hidden def add_virtual_columns_cartesian_to_polar(self, x="x", y="y", radius_out="r_polar", azimuth_out="phi_polar", propagate_uncertainties=False, radians=False): kwargs = dict(**locals()) del kwargs['self'] return self.geo.cartesian_to_polar(inplace=True, **kwargs) @_hidden def add_virtual_columns_cartesian_velocities_to_spherical(self, x="x", y="y", z="z", vx="vx", vy="vy", vz="vz", vr="vr", vlong="vlong", vlat="vlat", distance=None): kwargs = dict(**locals()) del kwargs['self'] return self.geo.velocity_cartesian2spherical(inplace=True, **kwargs) def _expr(self, *expressions, **kwargs): always_list = kwargs.pop('always_list', False) return self[str(expressions[0])] if len(expressions) == 1 and not always_list else [self[str(k)] for k in expressions] def _selection_expression(self, expression): return vaex.expression.Expression(self, str(expression), _selection=True) @_hidden def add_virtual_columns_cartesian_velocities_to_polar(self, x="x", y="y", vx="vx", radius_polar=None, vy="vy", vr_out="vr_polar", vazimuth_out="vphi_polar", propagate_uncertainties=False,): kwargs = dict(**locals()) del kwargs['self'] return self.geo.velocity_cartesian2polar(inplace=True, **kwargs) @_hidden def add_virtual_columns_polar_velocities_to_cartesian(self, x='x', y='y', azimuth=None, vr='vr_polar', vazimuth='vphi_polar', vx_out='vx', vy_out='vy', propagate_uncertainties=False): kwargs = dict(**locals()) del kwargs['self'] return self.geo.velocity_polar2cartesian(inplace=True, **kwargs) @_hidden def add_virtual_columns_rotation(self, x, y, xnew, ynew, angle_degrees, propagate_uncertainties=False): kwargs = dict(**locals()) del kwargs['self'] return self.geo.rotation_2d(inplace=True, **kwargs) @docsubst @_hidden def add_virtual_columns_spherical_to_cartesian(self, alpha, delta, distance, xname="x", yname="y", zname="z", propagate_uncertainties=False, center=[0, 0, 0], radians=False): kwargs = dict(**locals()) del kwargs['self'] return self.geo.spherical2cartesian(inplace=True, **kwargs) @_hidden def add_virtual_columns_cartesian_to_spherical(self, x="x", y="y", z="z", alpha="l", delta="b", distance="distance", radians=False, center=None, center_name="solar_position"): kwargs = dict(**locals()) del kwargs['self'] return self.geo.cartesian2spherical(inplace=True, **kwargs) @_hidden def add_virtual_columns_aitoff(self, alpha, delta, x, y, radians=True): kwargs = dict(**locals()) del kwargs['self'] return self.geo.project_aitoff(inplace=True, **kwargs) @_hidden def add_virtual_columns_projection_gnomic(self, alpha, delta, alpha0=0, delta0=0, x="x", y="y", radians=False, postfix=""): kwargs = dict(**locals()) del kwargs['self'] return self.geo.project_gnomic(inplace=True, **kwargs) def add_function(self, name, f, unique=False): name = vaex.utils.find_valid_name(name, used=[] if not unique else self.functions.keys()) function = vaex.expression.Function(self, name, f) self.functions[name] = function return function def add_virtual_column(self, name, expression, unique=False): if isinstance(expression, Expression): if expression.df is not self: expression = expression.copy(self) column_position = len(self.column_names) # if the current name is an existing column name.... if name in self.get_column_names(hidden=True): column_position = self.column_names.index(name) renamed = vaex.utils.find_valid_name('__' +name, used=self.get_column_names(hidden=True)) # we rewrite all existing expressions (including the passed down expression argument) self._rename(name, renamed) expression = _ensure_string_from_expression(expression) if vaex.utils.find_valid_name(name) != name: # if we have to rewrite the name, we need to make it unique unique = True valid_name = vaex.utils.find_valid_name(name, used=None if not unique else self.get_column_names(hidden=True)) self.virtual_columns[valid_name] = expression self._virtual_expressions[valid_name] = Expression(self, expression) if name not in self.column_names: self.column_names.insert(column_position, valid_name) self._save_assign_expression(valid_name) self.signal_column_changed.emit(self, valid_name, "add") def rename(self, name, new_name, unique=False): if name == new_name: return new_name = vaex.utils.find_valid_name(new_name, used=None if not unique else self.get_column_names(hidden=True)) self._rename(name, new_name, rename_meta_data=True) return new_name def _rename(self, old, new, rename_meta_data=False): is_variable = False is_function = False if old in self.variables: self.variables[new] = self.variables.pop(old) is_variable = True if old in self.functions: self.functions[new] = self.functions.pop(old) is_function = True elif old in self.virtual_columns: # renaming a column should not change the internal order, otherwise virtual # columns do not resolve (it will reference an unknown column) self.virtual_columns = vaex.utils.dict_replace_key(self.virtual_columns, old, new) self._virtual_expressions = vaex.utils.dict_replace_key(self._virtual_expressions, old, new) elif self.is_local() and old in self.columns: # we only have to do this locally # if we don't do this locally, we still store this info self.dataset = self.dataset.renamed({old: new}) if rename_meta_data: for d in [self.ucds, self.units, self.descriptions]: if old in d: d[new] = d[old] del d[old] for key, value in self.selection_histories.items(): self.selection_histories[key] = list([k if k is None else k._rename(self, old, new) for k in value]) if not (is_variable or is_function): if new not in self.virtual_columns: self._renamed_columns.append((old, new)) self.column_names[self.column_names.index(old)] = new if hasattr(self, old): if isinstance(getattr(self, old), Expression): try: delattr(self, old) except: pass self._save_assign_expression(new) existing_expressions = [k() for k in self._expressions] existing_expressions = [k for k in existing_expressions if k is not None] for expression in existing_expressions: expression._rename(old, new, inplace=True) self.virtual_columns = {k:self._virtual_expressions[k].expression for k, v in self.virtual_columns.items()} def delete_virtual_column(self, name): self.drop(name, inplace=True) self.signal_column_changed.emit(self, name, "delete") def add_variable(self, name, expression, overwrite=True, unique=True): if unique or overwrite or name not in self.variables: existing_names = self.get_column_names(virtual=False) + list(self.variables.keys()) name = vaex.utils.find_valid_name(name, used=[] if not unique else existing_names) self.variables[name] = expression self.signal_variable_changed.emit(self, name, "add") if unique: return name def delete_variable(self, name): del self.variables[name] self.signal_variable_changed.emit(self, name, "delete") def info(self, description=True): from IPython import display self._output_css() display.display(display.HTML(self._info(description=description))) def _info(self, description=True): parts = ["""<div><h2>{}</h2> <b>rows</b>: {:,}</div>""".format(self.name, len(self))] if hasattr(self, 'path'): parts += ["""<div><b>path</b>: <i>%s</i></div>""" % (self.path)] if self.description: parts += ["""<div><b>Description</b>: {}</div>""".format(self.description)] parts += ["<h2>Columns:</h2>"] parts += ["<table class='table-striped'>"] parts += ["<thead><tr>"] for header in "column type unit description expression".split(): if description or header != "description": parts += ["<th>%s</th>" % header] parts += ["</tr></thead>"] for name in self.get_column_names(): parts += ["<tr>"] parts += ["<td>%s</td>" % name] virtual = name in self.virtual_columns if not virtual: dtype = str(self.data_type(name)) if self.data_type(name) != str else 'str' else: dtype = "</i>virtual column</i>" parts += ["<td>%s</td>" % dtype] units = self.unit(name) units = units.to_string("latex_inline") if units else "" parts += ["<td>%s</td>" % units] if description: parts += ["<td ><pre>%s</pre></td>" % self.descriptions.get(name, "")] if virtual: parts += ["<td><code>%s</code></td>" % self.virtual_columns[name]] else: parts += ["<td></td>"] parts += ["</tr>"] parts += "</table>" ignore_list = 'pi e km_in_au seconds_per_year'.split() variable_names = [name for name in self.variables.keys() if name not in ignore_list] if variable_names: parts += ["<h2>Variables:</h2>"] parts += ["<table class='table-striped'>"] parts += ["<thead><tr>"] for header in "variable type unit description expression".split(): if description or header != "description": parts += ["<th>%s</th>" % header] parts += ["</tr></thead>"] for name in variable_names: parts += ["<tr>"] parts += ["<td>%s</td>" % name] parts += ["<td>%r</td>" % type] units = self.unit(name) units = units.to_string("latex_inline") if units else "" parts += ["<td>%s</td>" % units] if description: parts += ["<td ><pre>%s</pre></td>" % self.descriptions.get(name, "")] parts += ["<td><code>%s</code></td>" % (self.variables[name], )] parts += ["</tr>"] parts += "</table>" return "".join(parts) + "<h2>Data:</h2>" + self._head_and_tail_table() def head(self, n=10): return self[:min(n, len(self))] def tail(self, n=10): N = len(self) return self[max(0, N - n):min(len(self), N)] def _head_and_tail_table(self, n=None, format='html'): n = n or vaex.settings.display.max_rows N = _len(self) if N <= n: return self._as_table(0, N, format=format) else: return self._as_table(0, math.ceil(n / 2), N - math.floor(n / 2), N, format=format) def head_and_tail_print(self, n=5): from IPython import display display.display(display.HTML(self._head_and_tail_table(n))) def describe(self, strings=True, virtual=True, selection=None): import pandas as pd N = len(self) columns = {} for feature in self.get_column_names(strings=strings, virtual=virtual)[:]: data_type = self.data_type(feature) if data_type == str: count = self.count(feature, selection=selection, delay=True) self.execute() count = count.get() columns[feature] = ((data_type, count, N-count, '--', '--', '--', '--')) elif data_type.kind in 'SU': count = self.count(feature, selection=selection, delay=True) self.execute() count = count.get() columns[feature] = ((data_type, count, N-count, '--', '--', '--', '--')) elif data_type.kind in 'O': count_na = self[feature].isna().astype('int').sum(delay=True) self.execute() count_na = count_na.get() columns[feature] = ((data_type, N-count_na, count_na, '--', '--', '--', '--')) elif data_type.is_primitive or data_type.is_temporal: mean = self.mean(feature, selection=selection, delay=True) std = self.std(feature, selection=selection, delay=True) minmax = self.minmax(feature, selection=selection, delay=True) if data_type.is_datetime: count_na = self[feature].isna().astype('int').sum(delay=True) else: count = self.count(feature, selection=selection, delay=True) self.execute() if data_type.is_datetime: count_na, mean, std, minmax = count_na.get(), mean.get(), std.get(), minmax.get() count = N - int(count_na) else: count, mean, std, minmax = count.get(), mean.get(), std.get(), minmax.get() count = int(count) columns[feature] = ((data_type, count, N-count, mean, std, minmax[0], minmax[1])) else: raise NotImplementedError(f'Did not implement describe for data type {data_type}') return pd.DataFrame(data=columns, index=['data_type', 'count', 'NA', 'mean', 'std', 'min', 'max']) def cat(self, i1, i2, format='html'): from IPython import display if format == 'html': output = self._as_html_table(i1, i2) display.display(display.HTML(output)) else: output = self._as_table(i1, i2, format=format) print(output) def _as_table(self, i1, i2, j1=None, j2=None, format='html', ellipsis="..."): from .formatting import _format_value parts = [] parts += ["<table class='table-striped'>"] column_names = self.get_column_names() max_columns = vaex.settings.display.max_columns if (max_columns is not None) and (max_columns > 0): if max_columns < len(column_names): columns_sliced = math.ceil(max_columns/2) column_names = column_names[:columns_sliced] + column_names[-math.floor(max_columns/2):] else: columns_sliced = None values_list = [] values_list.append(['#', []]) for i, name in enumerate(column_names): if columns_sliced == i: values_list.append([ellipsis, []]) values_list.append([name, []]) def table_part(k1, k2, parts): N = k2 - k1 df = self[k1:k2] try: values = dict(zip(column_names, df.evaluate(column_names))) except: values = {} for i, name in enumerate(column_names): try: values[name] = df.evaluate(name) except: values[name] = ["error"] * (N) logger.exception('error evaluating: %s at rows %i-%i' % (name, k1, k2)) for i in range(k2 - k1): if format == 'html': value = "<i style='opacity: 0.6'>{:,}</i>".format(i + k1) else: value = "{:,}".format(i + k1) values_list[0][1].append(value) for j, name in enumerate(column_names): column_index = j if columns_sliced == j: values_list[column_index+1][1].append(ellipsis) if columns_sliced is not None and j >= columns_sliced: column_index += 1 value = values[name][i] value = _format_value(value) values_list[column_index+1][1].append(value) if i2 - i1 > 0: parts = table_part(i1, i2, parts) if j1 is not None and j2 is not None: values_list[0][1].append(ellipsis) for i in range(len(column_names)): values_list[i+1][1].append(ellipsis) table_part(j1, j2, parts) else: for header, values in values_list: values.append(None) values_list = dict(values_list) import tabulate table_text = str(tabulate.tabulate(values_list, headers="keys", tablefmt=format)) table_text = table_text.replace('&lt;i style=&#x27;opacity: 0.6&#x27;&gt;', "<i style='opacity: 0.6'>") table_text = table_text.replace('&lt;/i&gt;', "</i>") if i2 - i1 == 0: if self._length_unfiltered != len(self): footer_text = 'No rows to display (because of filtering).' else: footer_text = 'No rows to display.' if format == 'html': table_text += f'<i>{footer_text}</i>' if format == 'plain': table_text += f'\n{footer_text}' return table_text def _as_html_table(self, i1, i2, j1=None, j2=None): from .formatting import _format_value parts = [] parts += ["<table class='table-striped'>"] column_names = self.get_column_names() parts += ["<thead><tr>"] for name in ["#"] + column_names: parts += ["<th>%s</th>" % name] parts += ["</tr></thead>"] def table_part(k1, k2, parts): data_parts = {} N = k2 - k1 for name in column_names: try: data_parts[name] = self.evaluate(name, i1=k1, i2=k2) except: data_parts[name] = ["error"] * (N) logger.exception('error evaluating: %s at rows %i-%i' % (name, k1, k2)) for i in range(k2 - k1): parts += ["<tr>"] parts += ["<td><i style='opacity: 0.6'>{:,}</i></td>".format(i + k1)] for name in column_names: value = data_parts[name][i] value = _format_value(value) parts += ["<td>%r</td>" % value] parts += ["</tr>"] return parts parts = table_part(i1, i2, parts) if j1 is not None and j2 is not None: for i in range(len(column_names) + 1): parts += ["<td>...</td>"] parts = table_part(j1, j2, parts) parts += "</table>" html = "".join(parts) return html def _output_css(self): css = """.vaex-description pre { max-width : 450px; white-space : nowrap; overflow : hidden; text-overflow: ellipsis; } .vex-description pre:hover { max-width : initial; white-space: pre; }""" from IPython import display style = "<style>%s</style>" % css display.display(display.HTML(style)) def _repr_mimebundle_(self, include=None, exclude=None, **kwargs): return {'text/html':self._head_and_tail_table(format='html'), 'text/plain': self._head_and_tail_table(format='plain')} def _repr_html_(self): self._output_css() return self._head_and_tail_table() def __str__(self): return self._head_and_tail_table(format='plain') if not _DEBUG: def __repr__(self): return self._head_and_tail_table(format='plain') def __current_sequence_index(self): return 0 def has_current_row(self): return self._current_row is not None def get_current_row(self): return self._current_row def set_current_row(self, value): if (value is not None) and ((value < 0) or (value >= len(self))): raise IndexError("index %d out of range [0,%d]" % (value, len(self))) self._current_row = value self.signal_pick.emit(self, value) def __has_snapshots(self): return False def column_count(self, hidden=False): return len(self.get_column_names(hidden=hidden)) def get_names(self, hidden=False): names = self.get_column_names(hidden=hidden) return names +\ [k for k in self.variables.keys() if not hidden or not k.startswith('__')] +\ [k for k in self.functions.keys() if not hidden or not k.startswith('__')] def get_column_names(self, virtual=True, strings=True, hidden=False, regex=None): def column_filter(name): if regex and not re.match(regex, name): return False if not virtual and name in self.virtual_columns: return False if not strings and self.is_string(name): return False if not hidden and name.startswith('__'): return False return True if hidden and virtual and regex is None and strings is True: return list(self.column_names) if not hidden and virtual and regex is None and strings is True: return [k for k in self.column_names if not k.startswith('__')] return [name for name in self.column_names if column_filter(name)] def __bool__(self): return True def __len__(self): if not self.filtered: return self._length_unfiltered else: if self._cached_filtered_length is None: self._cached_filtered_length = int(self.count()) return self._cached_filtered_length def selected_length(self): raise NotImplementedError def length_original(self): return self._length_original def length_unfiltered(self): return self._length_unfiltered def active_length(self): return self._length_unfiltered def get_active_fraction(self): return self._active_fraction def set_active_fraction(self, value): if value != self._active_fraction: self._active_fraction = value self.select(None) self.set_current_row(None) self._length_unfiltered = int(round(self._length_original * self._active_fraction)) self._cached_filtered_length = None self._filter_filled = False self._index_start = 0 self._index_end = self._length_unfiltered self.signal_active_fraction_changed.emit(self, value) def get_active_range(self): return self._index_start, self._index_end def set_active_range(self, i1, i2): self._active_fraction = (i2 - i1) / float(self.length_original()) self._index_start = i1 self._index_end = i2 self.select(None) self.set_current_row(None) self._length_unfiltered = i2 - i1 if self.filtered: mask = self._selection_masks[FILTER_SELECTION_NAME] if not mask.view(i1, i2).is_dirty(): self._cached_filtered_length = mask.view(i1, i2).count() else: self._cached_filtered_length = None self._filter_filled = False self.signal_active_fraction_changed.emit(self, self._active_fraction) @docsubst def trim(self, inplace=False): df = self if inplace else self.copy() if self._index_start == 0 and self._index_end == self._length_original: return df df.dataset = self.dataset[self._index_start:self._index_end] if df.filtered: parent_mask = self._selection_masks[FILTER_SELECTION_NAME].view(self._index_start, self._index_end) mask = df._selection_masks[FILTER_SELECTION_NAME] np.copyto(np.asarray(mask), np.asarray(parent_mask)) selection = df.get_selection(FILTER_SELECTION_NAME) if not mask.is_dirty(): df._cached_filtered_length = mask.count() cache = df._selection_mask_caches[FILTER_SELECTION_NAME] assert not cache chunk_size = self.executor.chunk_size_for(mask.length) for i in range(vaex.utils.div_ceil(mask.length, chunk_size)): i1 = i * chunk_size i2 = min(mask.length, (i + 1) * chunk_size) key = (i1, i2) sub_mask = mask.view(i1, i2) sub_mask_array = np.asarray(sub_mask) cache[key] = selection, sub_mask_array else: df._cached_filtered_length = None df._filter_filled = False return df @docsubst def take(self, indices, filtered=True, dropfilter=True): df_trimmed = self.trim() df = df_trimmed.copy() indices = np.asarray(indices) if df.filtered and filtered: # we translate the indices that refer to filters row indices to # indices of the unfiltered row indices df._fill_filter_mask() max_index = indices.max() mask = df._selection_masks[FILTER_SELECTION_NAME] filtered_indices = mask.first(max_index+1) indices = filtered_indices[indices] df.dataset = df.dataset.take(indices) if dropfilter: # if the indices refer to the filtered rows, we can discard the # filter in the final dataframe df.set_selection(None, name=FILTER_SELECTION_NAME) return df @docsubst def extract(self): df = self.trim() if df.filtered: df._push_down_filter() df._invalidate_caches() return df def _push_down_filter(self): self._fill_filter_mask() # make sure the mask is filled mask = self._selection_masks[FILTER_SELECTION_NAME] mask = np.asarray(mask) # indices = mask.first(len(self)) # assert len(indices) == len(self) selection = self.get_selection(FILTER_SELECTION_NAME) from .dataset import DatasetFiltered self.set_selection(None, name=FILTER_SELECTION_NAME) self.dataset = DatasetFiltered(self.dataset, mask, state=self.state_get(skip=[self.dataset]), selection=selection) @docsubst def shuffle(self, random_state=None): return self.sample(frac=1, random_state=random_state) @docsubst def sample(self, n=None, frac=None, replace=False, weights=None, random_state=None): self = self.extract() if type(random_state) == int or random_state is None: random_state = np.random.RandomState(seed=random_state) if n is None and frac is None: n = 1 elif frac is not None: n = int(round(frac * len(self))) weights_values = None if weights is not None: weights_values = self.evaluate(weights) weights_values = weights_values / self.sum(weights) indices = random_state.choice(len(self), n, replace=replace, p=weights_values) return self.take(indices) @docsubst @vaex.utils.gen_to_list def split_random(self, into, random_state=None): self = self.extract() if type(random_state) == int or random_state is None: random_state = np.random.RandomState(seed=random_state) indices = random_state.choice(len(self), len(self), replace=False) return self.take(indices).split(into) @docsubst @vaex.utils.gen_to_list def split(self, into=None): self = self.extract() if isinstance(into, numbers.Integral): step = max(1, vaex.utils.div_ceil(len(self), into)) i1 = 0 i2 = step while i1 < len(self): i2 = min(len(self), i2) yield self[i1:i2] i1, i2 = i2, i2 + step return if _issequence(into): # make sure it is normalized total = sum(into) into = [k / total for k in into] else: assert into <= 1, "when float, `into` should be <= 1" assert into > 0, "`into` must be > 0." into = [into, 1 - into] offsets = np.round(np.cumsum(into) * len(self)).astype(np.int64) start = 0 for offset in offsets: yield self[start:offset] start = offset @docsubst def sort(self, by, ascending=True): self = self.trim() # Ensure "by" is in the proper format by = vaex.utils._ensure_list(by) by = vaex.utils._ensure_strings_from_expressions(by) # Ensure "ascending is in the proper format" if isinstance(ascending, list): assert len(ascending) == len(by), 'If "ascending" is a list, it must have the same number of elements as "by".' else: ascending = vaex.utils._ensure_list(ascending) * len(by) sort_keys = [(key, 'ascending') if order is True else (key, 'descending') for key, order in zip(by, ascending)] pa_table = self[by].to_arrow_table() indices = pa.compute.sort_indices(pa_table, sort_keys=sort_keys) # if we don't cast to int64, we get uint64 scalars, which when adding numbers to will auto case to float (numpy) indices = vaex.array_types.to_numpy(indices).astype('int64') return self.take(indices) @docsubst def diff(self, periods=1, column=None, fill_value=None, trim=False, inplace=False, reverse=False): df = self.trim(inplace=inplace) if column is None: columns = self.get_column_names() else: if isinstance(column, (list, tuple)): columns = column else: columns = [column] originals = {} for column in columns: new_name = df._find_valid_name(f'__{column}_original') df[new_name] = df[column] originals[column] = new_name df = df.shift(periods, columns, fill_value=fill_value, trim=trim, inplace=inplace) for column in columns: if reverse: df[column] = df[column] - df[originals[column]] else: df[column] = df[originals[column]] - df[column] return df @docsubst def shift(self, periods, column=None, fill_value=None, trim=False, inplace=False): df = self.trim(inplace=inplace) if df.filtered: df._push_down_filter() from .shift import DatasetShifted if column is not None: columns = set(column) if _issequence(column) else {column} else: columns = set(df.get_column_names()) columns_all = set(df.get_column_names(hidden=True)) # or because we depend on them (virtual column) columns_keep = columns_all - columns columns_keep |= df._depending_columns(columns_keep, check_filter=False) # TODO: remove filter check columns_shift = columns.copy() columns_shift |= df._depending_columns(columns) virtual_columns = df.virtual_columns.copy() # these are the columns we want to shift, but *also* want to keep the original columns_conflict = columns_keep & columns_shift column_shift_mapping = {} # we use this dataframe for tracking virtual columns when renaming df_shifted = df.copy() shifted_names = {} unshifted_names = {} for name in columns_shift: if name in columns_conflict: # we want to have two columns, an unshifted and shifted # rename the current to unshifted unshifted_name = df.rename(name, f'__{name}_unshifted', unique=True) unshifted_names[name] = unshifted_name # now make a shifted one shifted_name = f'__{name}_shifted' shifted_name = vaex.utils.find_valid_name(shifted_name, used=df.get_column_names(hidden=True)) shifted_names[name] = shifted_name if name not in virtual_columns: # if not virtual, we let the dataset layer handle it column_shift_mapping[unshifted_name] = shifted_name df.column_names.append(shifted_name) # otherwise we can later on copy the virtual columns from this df df_shifted.rename(name, shifted_name) else: if name not in virtual_columns: # easy case, just shift column_shift_mapping[name] = name # now that we renamed columns into _shifted/_unshifted we # restore the dataframe with the real column names for name in columns_shift: if name in columns_conflict: if name in virtual_columns: if name in columns: df.add_virtual_column(name, df_shifted.virtual_columns[shifted_names[name]]) else: df.add_virtual_column(name, unshifted_names[name]) else: if name in columns: df.add_virtual_column(name, shifted_names[name]) else: df.add_virtual_column(name, unshifted_names[name]) else: if name in virtual_columns: df.virtual_columns[name] = df_shifted.virtual_columns[name] df._virtual_expressions[name] = Expression(df, df.virtual_columns[name]) if _issequence(periods): if len(periods) != 2: raise ValueError(f'periods should be a int or a tuple of ints, not {periods}') start, end = periods else: start = end = periods dataset = DatasetShifted(original=df.dataset, start=start, end=end, column_mapping=column_shift_mapping, fill_value=fill_value) if trim: # assert start == end slice_start = 0 slice_end = dataset.row_count if start > 0: slice_start = start elif start < 0: slice_end = dataset.row_count + start if end != start: if end > start: slice_end -= end -1 dataset = dataset.slice(slice_start, slice_end) df.dataset = dataset for name in df.dataset: assert name in df.column_names, f"oops, {name} in dataset, but not in column_names" for name in df.column_names: if name not in df.dataset: assert name in df.virtual_columns return df @docsubst def fillna(self, value, column_names=None, prefix='__original_', inplace=False): df = self.trim(inplace=inplace) column_names = column_names or list(self) for name in column_names: column = df.columns.get(name) df[name] = df.func.fillna(df[name], value) return df def materialize(self, column=None, inplace=False, virtual_column=None): if virtual_column is not None: warnings.warn("virtual_column argument is deprecated, please use column") column = virtual_column df = self.trim(inplace=inplace) if column is None: columns = df.get_column_names(hidden=True) else: columns = _ensure_strings_from_expressions(column) virtual = [] cache = [] for column in columns: if column in self.dataset: cache.append(column) elif column in self.virtual_columns: virtual.append(column) else: raise NameError(f'{column} is not a column or virtual column') dataset = df._dataset if cache: dataset = vaex.dataset.DatasetCached(dataset, cache) if virtual: arrays = df.evaluate(virtual, filtered=False) materialized = vaex.dataset.DatasetArrays(dict(zip(virtual, arrays))) dataset = dataset.merged(materialized) df.dataset = dataset for name in virtual: del df.virtual_columns[name] else: # in this case we don't need to invalidate caches, df._dataset = dataset return df def _lazy_materialize(self, *virtual_columns): df = self.trim() virtual_columns = _ensure_strings_from_expressions(virtual_columns) for name in virtual_columns: if name not in df.virtual_columns: raise KeyError('Virtual column not found: %r' % name) column = ColumnConcatenatedLazy([self[name]]) del df[name] df.add_column(name, column) return df def get_selection(self, name="default"): name = _normalize_selection_name(name) selection_history = self.selection_histories[name] index = self.selection_history_indices[name] if index == -1: return None else: return selection_history[index] def selection_undo(self, name="default", executor=None): logger.debug("undo") executor = executor or self.executor assert self.selection_can_undo(name=name) selection_history = self.selection_histories[name] index = self.selection_history_indices[name] self.selection_history_indices[name] -= 1 self.signal_selection_changed.emit(self, name) logger.debug("undo: selection history is %r, index is %r", selection_history, self.selection_history_indices[name]) def selection_redo(self, name="default", executor=None): logger.debug("redo") executor = executor or self.executor assert self.selection_can_redo(name=name) selection_history = self.selection_histories[name] index = self.selection_history_indices[name] next = selection_history[index + 1] self.selection_history_indices[name] += 1 self.signal_selection_changed.emit(self, name) logger.debug("redo: selection history is %r, index is %r", selection_history, index) def selection_can_undo(self, name="default"): return self.selection_history_indices[name] > -1 def selection_can_redo(self, name="default"): return (self.selection_history_indices[name] + 1) < len(self.selection_histories[name]) def select(self, boolean_expression, mode="replace", name="default", executor=None): boolean_expression = _ensure_string_from_expression(boolean_expression) if boolean_expression is None and not self.has_selection(name=name): pass self.signal_selection_changed.emit(self, name) # TODO: unittest want to know, does this make sense? else: def create(current): return selections.SelectionExpression(boolean_expression, current, mode) if boolean_expression else None self._selection(create, name) def select_non_missing(self, drop_nan=True, drop_masked=True, column_names=None, mode="replace", name="default"): column_names = column_names or self.get_column_names(virtual=False) def create(current): return selections.SelectionDropNa(drop_nan, drop_masked, column_names, current, mode) self._selection(create, name) def dropmissing(self, column_names=None): return self._filter_all(self.func.ismissing, column_names) def dropnan(self, column_names=None): return self._filter_all(self.func.isnan, column_names) def dropna(self, column_names=None): return self._filter_all(self.func.isna, column_names) def dropinf(self, column_names=None): return self._filter_all(self.func.isinf, column_names) def _filter_all(self, f, column_names=None): column_names = column_names or self.get_column_names(virtual=False) expression = f(self[column_names[0]]) for column in column_names[1:]: expression = expression | f(self[column]) return self.filter(~expression, mode='and') def select_nothing(self, name="default"): logger.debug("selecting nothing") self.select(None, name=name) self.signal_selection_changed.emit(self, name) def select_rectangle(self, x, y, limits, mode="replace", name="default"): self.select_box([x, y], limits, mode=mode, name=name) def select_box(self, spaces, limits, mode="replace", name="default"): sorted_limits = [(min(l), max(l)) for l in limits] expressions = ["((%s) >= %f) & ((%s) <= %f)" % (expression, lmin, expression, lmax) for (expression, (lmin, lmax)) in zip(spaces, sorted_limits)] self.select("&".join(expressions), mode=mode, name=name) def select_circle(self, x, y, xc, yc, r, mode="replace", name="default", inclusive=True): # expr = "({x}-{xc})**2 + ({y}-{yc})**2 <={r}**2".format(**locals()) if inclusive: expr = (self[x] - xc)**2 + (self[y] - yc)**2 <= r**2 else: expr = (self[x] - xc)**2 + (self[y] - yc)**2 < r**2 self.select(boolean_expression=expr, mode=mode, name=name) def select_ellipse(self, x, y, xc, yc, width, height, angle=0, mode="replace", name="default", radians=False, inclusive=True): # Computing the properties of the ellipse prior to selection if radians: pass else: alpha = np.deg2rad(angle) xr = width / 2 yr = height / 2 r = max(xr, yr) a = xr / r b = yr / r expr = "(({x}-{xc})*cos({alpha})+({y}-{yc})*sin({alpha}))**2/{a}**2 + (({x}-{xc})*sin({alpha})-({y}-{yc})*cos({alpha}))**2/{b}**2 <= {r}**2".format(**locals()) if inclusive: expr = ((self[x] - xc) * np.cos(alpha) + (self[y] - yc) * np.sin(alpha))**2 / a**2 + ((self[x] - xc) * np.sin(alpha) - (self[y] - yc) * np.cos(alpha))**2 / b**2 <= r**2 else: expr = ((self[x] - xc) * np.cos(alpha) + (self[y] - yc) * np.sin(alpha))**2 / a**2 + ((self[x] - xc) * np.sin(alpha) - (self[y] - yc) * np.cos(alpha))**2 / b**2 < r**2 self.select(boolean_expression=expr, mode=mode, name=name) def select_lasso(self, expression_x, expression_y, xsequence, ysequence, mode="replace", name="default", executor=None): def create(current): return selections.SelectionLasso(expression_x, expression_y, xsequence, ysequence, current, mode) self._selection(create, name, executor=executor) def select_inverse(self, name="default", executor=None): def create(current): return selections.SelectionInvert(current) self._selection(create, name, executor=executor) def set_selection(self, selection, name="default", executor=None): def create(current): return selection self._selection(create, name, executor=executor, execute_fully=True) def _selection(self, create_selection, name, executor=None, execute_fully=False): selection_history = self.selection_histories[name] previous_index = self.selection_history_indices[name] current = selection_history[previous_index] if selection_history else None selection = create_selection(current) executor = executor or self.executor selection_history.append(selection) self.selection_history_indices[name] += 1 # clip any redo history del selection_history[self.selection_history_indices[name]:-1] self.signal_selection_changed.emit(self, name) result = vaex.promise.Promise.fulfilled(None) # logger.debug("select selection history is %r, index is %r", selection_history, self.selection_history_indices[name]) return result def has_selection(self, name="default"): return self.get_selection(name) is not None def __setitem__(self, name, value): if isinstance(name, six.string_types): if isinstance(value, supported_column_types): self.add_column(name, value) else: self.add_virtual_column(name, value) else: raise TypeError('__setitem__ only takes strings as arguments, not {}'.format(type(name))) def drop_filter(self, inplace=False): df = self if inplace else self.copy() df.select_nothing(name=FILTER_SELECTION_NAME) df._invalidate_caches() return df def filter(self, expression, mode="and"): df = self.copy() df.select(expression, name=FILTER_SELECTION_NAME, mode=mode) df._cached_filtered_length = None # invalide cached length df._filter_filled = False # WARNING: this is a special case where we create a new filter # the cache mask chunks still hold references to views on the old # mask, and this new mask will be filled when required df._selection_masks[FILTER_SELECTION_NAME] = vaex.superutils.Mask(int(df._length_unfiltered)) return df def __getitem__(self, item): if isinstance(item, int): names = self.get_column_names() return [self.evaluate(name, item, item+1, array_type='python')[0] for name in names] elif isinstance(item, six.string_types): if hasattr(self, item) and isinstance(getattr(self, item), Expression): return getattr(self, item) # if item in self.virtual_columns: # return Expression(self, self.virtual_columns[item]) # if item in self._virtual_expressions: # return self._virtual_expressions[item] if item not in self.column_names: self.validate_expression(item) item = vaex.utils.valid_expression(self.get_column_names(), item) return Expression(self, item) # TODO we'd like to return the same expression if possible elif isinstance(item, Expression): expression = item.expression return self.filter(expression) elif isinstance(item, (tuple, list)): df = self if isinstance(item[0], slice): df = df[item[0]] if len(item) > 1: if isinstance(item[1], int): name = self.get_column_names()[item[1]] return df[name] elif isinstance(item[1], slice): names = self.get_column_names().__getitem__(item[1]) return df[names] for expression in item: if expression not in self.column_names: self.validate_expression(expression) df = self.copy(column_names=item) return df elif isinstance(item, slice): start, stop, step = item.start, item.stop, item.step start = start or 0 stop = stop or len(self) if start < 0: start = len(self)+start if stop < 0: stop = len(self)+stop stop = min(stop, len(self)) assert step in [None, 1] if self.filtered: self._fill_filter_mask() mask = self._selection_masks[FILTER_SELECTION_NAME] startf, stopf = mask.indices(start, stop-1) assert startf != -1 assert stopf != -1 stopf = stopf+1 start, stop = startf, stopf df = self.trim() df.set_active_range(start, stop) return df.trim() def __delitem__(self, item): if item in self.columns: name = item if name in self._depending_columns(columns_exclude=[name]): raise ValueError(f'Oops, you are trying to remove column {name} while other columns depend on it (use .drop instead)') self.drop([item], inplace=True) def _real_drop(self, item): if isinstance(item, Expression): name = item.expression else: name = item if name in self.columns: del self.columns[name] self.column_names.remove(name) elif name in self.virtual_columns: del self.virtual_columns[name] del self._virtual_expressions[name] self.column_names.remove(name) else: matches = difflib.get_close_matches(name, self.get_column_names(hidden=True)) msg = "Column or variable %r does not exist." % name if matches: msg += ' Did you mean: ' + " or ".join(map(repr, matches)) raise KeyError(msg) self.signal_column_changed.emit(self, name, "delete") if hasattr(self, name): try: if isinstance(getattr(self, name), Expression): delattr(self, name) except: pass @docsubst def drop(self, columns, inplace=False, check=True): columns = _ensure_list(columns) columns = _ensure_strings_from_expressions(columns) df = self if inplace else self.copy() depending_columns = df._depending_columns(columns_exclude=columns) for column in columns: if check and column in depending_columns: df._hide_column(column) else: df._real_drop(column) return df def _hide_column(self, column): column = _ensure_string_from_expression(column) new_name = self._find_valid_name('__' + column) self._rename(column, new_name) return new_name def _find_valid_name(self, initial_name): return vaex.utils.find_valid_name(initial_name, used=self.get_column_names(hidden=True)) def _depending_columns(self, columns=None, columns_exclude=None, check_filter=True): columns = set(columns or self.get_column_names(hidden=True)) if columns_exclude: columns -= set(columns_exclude) depending_columns = set() for column in columns: expression = self[str(column)] depending_columns |= expression.variables() depending_columns -= set(columns) if check_filter: if self.filtered: selection = self.get_selection(FILTER_SELECTION_NAME) depending_columns |= selection._depending_columns(self) return depending_columns def iterrows(self): columns = self.get_column_names() for i in range(len(self)): yield i, {key: self.evaluate(key, i, i+1, array_type='python')[0] for key in columns} def __iter__(self): return iter(list(self.get_column_names())) def _root_nodes(self): root_nodes = [] leafes = [] def walk(node): if isinstance(node, six.string_types): leafes.append(node) if node in root_nodes: root_nodes.remove(node) else: node_repr, fname, fobj, deps = node if node_repr in self.virtual_columns: leafes.append(node_repr) if node_repr in root_nodes: root_nodes.remove(node_repr) for dep in deps: walk(dep) for column in self.virtual_columns.keys(): if column not in leafes: root_nodes.append(column) node = self[column]._graph() node_repr, fname, fobj, deps = node for dep in deps: walk(dep) return root_nodes def _graphviz(self, dot=None): from graphviz import Digraph dot = dot or Digraph(comment='whole dataframe') root_nodes = self._root_nodes() for column in root_nodes: self[column]._graphviz(dot=dot) return dot @docsubst @stat_1d def _agg(self, aggregator, binners=tuple(), delay=False, progress=None): tasks, result = aggregator.add_tasks(self, binners, progress=progress) return self._delay(delay, result) def _binner(self, expression, limits=None, shape=None, selection=None, progress=None, delay=False): expression = str(expression) if limits is not None and not isinstance(limits, (tuple, str)): limits = tuple(limits) if expression in self._categories: N = self._categories[expression]['N'] min_value = self._categories[expression]['min_value'] binner = self._binner_ordinal(expression, N, min_value) binner = vaex.promise.Promise.fulfilled(binner) else: @delayed def create_binner(limits): return self._binner_scalar(expression, limits, shape) binner = create_binner(self.limits(expression, limits, selection=selection, progress=progress, delay=True)) return self._delay(delay, binner) def _binner_scalar(self, expression, limits, shape): dtype = self.data_type(expression) return BinnerScalar(expression, limits[0], limits[1], shape, dtype) def _binner_ordinal(self, expression, ordinal_count, min_value=0, invert=False): dtype = self.data_type(expression) return BinnerOrdinal(expression, min_value, ordinal_count, invert, dtype) def _binner_hash(self, expression, hash_map_unique): dtype = self.data_type(expression) return BinnerHash(expression, hash_map_unique, dtype) def _create_binners(self, binby, limits, shape, selection=None, progress=None, delay=False): if isinstance(binby, (list, tuple)): binbys = binby else: binbys = [binby] binbys = _ensure_strings_from_expressions(binbys) for expression in binbys: if expression: self.validate_expression(expression) binners = [] if len(binbys): limits = _expand_limits(limits, len(binbys)) else: limits = [] shapes = _expand_shape(shape, len(binbys)) for binby, limits1, shape in zip(binbys, limits, shapes): binners.append(self._binner(binby, limits1, shape, selection, progress=progress, delay=True)) @delayed def finish(*binners): return binners return self._delay(delay, finish(*binners)) @docsubst def rolling(self, window, trim=False, column=None, fill_value=None, edge="right"): columns = self.get_column_names() if column is None else (column if _issequence(column) else [column]) from .rolling import Rolling return Rolling(self, window, trim=trim, columns=columns, fill_value=fill_value, edge=edge) DataFrame.__hidden__ = {} hidden = [name for name, func in vars(DataFrame).items() if getattr(func, '__hidden__', False)] for name in hidden: DataFrame.__hidden__[name] = getattr(DataFrame, name) delattr(DataFrame, name) del hidden class ColumnProxy(collections.abc.MutableMapping): def __init__(self, df): self.df = df @property def dataset(self): return self.df.dataset def __delitem__(self, item): assert item in self.dataset self.df._dataset = self.dataset.dropped(item) def __len__(self): return len(self.dataset) def __setitem__(self, item, value): if isinstance(self.dataset, vaex.dataset.DatasetArrays): merged = vaex.dataset.DatasetArrays({**self.dataset._columns, item: value}) else: left = self.dataset if item in self.dataset: left = left.dropped(item) right = vaex.dataset.DatasetArrays({item: value}) merged = left.merged(right) self.df._dataset = merged self.df._length = len(value) if self.df._length_unfiltered is None: self.df._length_unfiltered = self.df._length self.df._length_original = self.df._length self.df._index_end = self.df._length_unfiltered def __iter__(self): return iter(self.dataset) def __getitem__(self, item): return self.dataset[item] class DataFrameLocal(DataFrame): def __init__(self, dataset=None, name=None): if dataset is None: dataset = vaex.dataset.DatasetArrays() name = name or "no-name" else: name = name or dataset.name super(DataFrameLocal, self).__init__(name) self._dataset = dataset if hasattr(dataset, 'units'): self.units.update(dataset.units) if hasattr(dataset, 'ucds'): self.ucds.update(dataset.ucds) self.column_names = list(self.dataset) if len(self.dataset): self._length = self.dataset.row_count if self._length_unfiltered is None: self._length_unfiltered = self._length self._length_original = self._length self._index_end = self._length_unfiltered self.mask = None self.columns = ColumnProxy(self) for column_name in self.column_names: self._initialize_column(column_name) def _fill_filter_mask(self): if self.filtered and self._filter_filled is False: task = vaex.tasks.TaskFilterFill(self) @delayed def set_length(count): self._cached_filtered_length = int(count) self._filter_filled = True set_length(self.count(delay=True)) task = self.executor.schedule(task) self.execute() def __getstate__(self): state = self.state_get(skip=[self.dataset]) return { 'state': state, 'dataset': self.dataset, '_future_behaviour': self. _future_behaviour, } def __setstate__(self, state): self._init() self.executor = get_main_executor() self.columns = ColumnProxy(self) dataset = state['dataset'] self._dataset = dataset assert dataset.row_count is not None self._length_original = dataset.row_count self._length_unfiltered = self._length_original self._cached_filtered_length = None self._filter_filled = False self._index_start = 0 self._index_end = self._length_original self._future_behaviour = state['_future_behaviour'] self.state_set(state['state'], use_active_range=True, trusted=True) @property def dataset(self): return self._dataset @dataset.setter def dataset(self, dataset): if self._dataset.row_count != dataset.row_count: self._length_original = dataset.row_count self._length_unfiltered = self._length_original self._cached_filtered_length = None self._filter_filled = False self._index_start = 0 self._index_end = self._length_original self._dataset = dataset self._invalidate_caches() def hashed(self, inplace=False) -> DataFrame: df = self.copy() if not inplace else self df.dataset = df.dataset.hashed() return df def _readonly(self, inplace=False): df = self if inplace else self.copy() assert isinstance(self.dataset, vaex.dataset.DatasetArrays) columns = {} for key, ar in self.columns.items(): columns[key] = ar if isinstance(ar, np.ndarray): columns[key] = ar = ar.view() ar.flags['WRITEABLE'] = False df._dataset = vaex.dataset.DatasetArrays(columns) return df _dict_mapping = { pa.uint8(): pa.int16(), pa.uint16(): pa.int32(), pa.uint32(): pa.int64(), pa.uint64(): pa.int64(), } def _auto_encode_type(self, expression, type): if not self._future_behaviour: return type if self.is_category(expression): if vaex.dtype(type).is_encoded: return type # already encoded value_type = vaex.array_types.to_arrow(self.category_labels(expression)).type type = vaex.array_types.to_arrow_type(type) type = self._dict_mapping.get(type, type) type = pa.dictionary(type, value_type) return type def _auto_encode_data(self, expression, values): if not self._future_behaviour: return values if vaex.array_types.is_arrow_array(values) and pa.types.is_dictionary(values.type): return values if self.is_category(expression): dictionary = vaex.array_types.to_arrow(self.category_labels(expression)) offset = self.category_offset(expression) if offset != 0: values = values - offset values = vaex.array_types.to_arrow(values) to_type = None if values.type in self._dict_mapping: values = values.cast(self._dict_mapping[values.type]) if isinstance(values, pa.ChunkedArray): chunks = [pa.DictionaryArray.from_arrays(k, dictionary) for k in values.chunks] values = pa.chunked_array(chunks) else: values = pa.DictionaryArray.from_arrays(values, dictionary) return values @docsubst def categorize(self, column, min_value=0, max_value=None, labels=None, inplace=False): df = self if inplace else self.copy() column = _ensure_string_from_expression(column) if df[column].dtype != int: raise TypeError(f'Only integer columns can be marked as categorical, {column} is {df[column].dtype}') if max_value is not None: labels = list(range(min_value, max_value+1)) N = len(labels) else: vmin, vmax = df.minmax(column) if labels is None: N = int(vmax + 1) labels = list(range(vmin, vmax+1)) min_value = vmin else: min_value = vmin if (vmax - vmin) >= len(labels): raise ValueError('value of {} found, which is larger than number of labels {}'.format(vmax, len(labels))) df._categories[column] = dict(labels=labels, N=len(labels), min_value=min_value) return df def ordinal_encode(self, column, values=None, inplace=False, lazy=False): column = _ensure_string_from_expression(column) df = self if inplace else self.copy() # for the codes, we need to work on the unfiltered dataset, since the filter # may change, and we also cannot add an array that is smaller in length df_unfiltered = df.copy() # maybe we need some filter manipulation methods df_unfiltered.select_nothing(name=FILTER_SELECTION_NAME) df_unfiltered._length_unfiltered = df._length_original df_unfiltered.set_active_range(0, df._length_original) expression = df_unfiltered[column] if lazy or values is not None: if values is None: found_values = df_unfiltered.unique(column, array_type='numpy-arrow') minimal_type = vaex.utils.required_dtype_for_max(len(found_values), signed=True) dtype = vaex.dtype_of(found_values) if dtype == int: min_value = found_values.min() max_value = found_values.max() if (max_value - min_value +1) == len(found_values): warnings.warn(f'It seems your column {column} is already ordinal encoded (values between {min_value} and {max_value}), automatically switching to use df.categorize') return df.categorize(column, min_value=min_value, max_value=max_value, inplace=inplace) values = found_values else: values = expression.dtype.create_array(values) fp = f'hash-map-unique-{expression.fingerprint()}' hash_map_unique_name = fp.replace('-', '_') hash_map_unique = vaex.hash.HashMapUnique.from_keys(values, fingerprint=fp) if lazy: df.add_variable(hash_map_unique_name, hash_map_unique) expr = df._expr('hashmap_apply({}, {}, check_missing=True)'.format(column, hash_map_unique_name)) df[column] = expr df._categories[column] = dict(labels=values, N=len(values), min_value=0) return df # no else but return to avoid large diff else: dfc = df.copy() dfc.add_variable(hash_map_unique_name, hash_map_unique) expr = dfc._expr('hashmap_apply({}, {}, check_missing=True)'.format(column, hash_map_unique_name)) codes = dfc.evaluate(expr) else: found_values, codes = df_unfiltered.unique(column, return_inverse=True, array_type='numpy-arrow') if isinstance(found_values, array_types.supported_arrow_array_types): # elements of arrow arrays are not in arrow arrays, e.g. ar[0] in ar is False # see tests/arrow/assumptions_test.py::test_in_pylist found_values = found_values.to_pylist() values = found_values max_code = codes.max() minimal_type = vaex.utils.required_dtype_for_max(max_code, signed=True) codes = codes.astype(minimal_type) if isinstance(values, (list, tuple)): values = pa.array(values) dtype = vaex.dtype_of(values) if dtype == int: min_value = values.min() max_value = values.max() if (max_value - min_value +1) == len(values): warnings.warn(f'It seems your column {column} is already ordinal encoded (values between {min_value} and {max_value}), automatically switching to use df.categorize') return df.categorize(column, min_value=min_value, max_value=max_value, inplace=inplace) df.rename(column, '__original_' + column, unique=True) df.add_column(column, codes) values = vaex.array_types.tolist(values) df._categories[column] = dict(labels=values, N=len(values), min_value=0) return df # for backward compatibility label_encode = _hidden(vaex.utils.deprecated('use ordinal_encode')(ordinal_encode)) @property def data(self): class Datas(object): pass datas = Datas() for name, array in self.columns.items(): setattr(datas, name, array[:]) return datas def copy(self, column_names=None, treeshake=False): copy_all = column_names is None if copy_all and not treeshake: # fast path df = vaex.from_dataset(self.dataset) df.column_names = list(self.column_names) df.virtual_columns = self.virtual_columns.copy() virtuals = set(df.virtual_columns) for name in df.column_names: if name in virtuals: df._virtual_expressions[name] = Expression(df, df.virtual_columns[name]) df._initialize_column(name) hide = set() else: all_column_names = self.get_column_names(hidden=True) if column_names is None: column_names = all_column_names.copy() else: for name in column_names: self.validate_expression(name) # the columns that we require for a copy (superset of column_names) required = set() # expression like 'x/2' that are not (virtual) columns expression_columns = set() def track(name): if name in self.dataset: required.add(name) else: if name in self.variables: if treeshake: required.add(name) return elif name in self.virtual_columns: required.add(name) expr = self._virtual_expressions[name] else: # this might be an expression, create a valid name expression_columns.add(name) expr = self[name] # we expand it ourselves deps = expr.variables(ourself=True, expand_virtual=False) deps -= {name} # the columns we didn't know we required yet missing = deps - required required.update(deps) for name in missing: track(name) for name in column_names: track(name) for key, value in list(self.selection_histories.items()): selection = self.get_selection(key) if selection: for name in selection._depending_columns(self): track(name) dataset_columns = {k for k in required if k in self.dataset} dataset_columns = list(dataset_columns) dataset_columns.sort() dataset = self.dataset.project(*dataset_columns) df = vaex.from_dataset(dataset) other = {k for k in required if k not in self.dataset} for name in other: if name in self.virtual_columns: valid_name = vaex.utils.find_valid_name(name) df.add_virtual_column(valid_name, self.virtual_columns[name]) elif name in self.variables: if treeshake: df.variables[name] = self.variables[name] pass else: raise RuntimeError(f'Oops {name} is not a virtual column or variable??') for expr in expression_columns: df.add_virtual_column(expr, expr) hide = required - set(column_names) - set(self.variables) df._length_unfiltered = self._length_unfiltered df._length_original = self._length_original df._cached_filtered_length = self._cached_filtered_length df._filter_filled = self._filter_filled df._index_end = self._index_end df._index_start = self._index_start df._active_fraction = self._active_fraction df._renamed_columns = list(self._renamed_columns) df.units.update(self.units) if not treeshake: df.variables.update(self.variables) df._categories.update(self._categories) df._future_behaviour = self._future_behaviour df.functions.update(self.functions) for key, value in self.selection_histories.items(): if self.get_selection(key): df.selection_histories[key] = list(value) if key == FILTER_SELECTION_NAME: df._selection_masks[key] = self._selection_masks[key] else: df._selection_masks[key] = vaex.superutils.Mask(int(df._length_original)) np.asarray(df._selection_masks[key])[:] = np.asarray(self._selection_masks[key]) for key, value in self.selection_history_indices.items(): if self.get_selection(key): df.selection_history_indices[key] = value df._selection_mask_caches[key] = collections.defaultdict(dict) df._selection_mask_caches[key].update(self._selection_mask_caches[key]) for name in hide: df._hide_column(name) if column_names is not None: extra = set(df.column_names) - set(column_names) df.column_names = list(column_names) + list(extra) df.copy_metadata(self) return df def shallow_copy(self, virtual=True, variables=True): df = DataFrameLocal(self.name, self.path, self.column_names) df.columns.update(self.columns) df._length_unfiltered = self._length_unfiltered df._length_original = self._length_original df._index_end = self._index_end df._index_start = self._index_start df._active_fraction = self._active_fraction if virtual: df.virtual_columns.update(self.virtual_columns) if variables: df.variables.update(self.variables) return df def is_local(self): return True def length(self, selection=False): if selection: return 0 if self.mask is None else np.sum(self.mask) else: return len(self) @_hidden def __call__(self, *expressions, **kwargs): import vaex.legacy return vaex.legacy.SubspaceLocal(self, expressions, kwargs.get("executor") or self.executor, delay=kwargs.get("delay", False)) def echo(self, arg): return arg @property def _dtype(self): dtypes = [self[k].dtype for k in self.get_column_names()] if not all([dtypes[0] == dtype for dtype in dtypes]): return ValueError("Not all dtypes are equal: %r" % dtypes) return dtypes[0] @property def shape(self): return (len(self), len(self.get_column_names())) def __array__(self, dtype=None, parallel=True): if dtype is None: dtype = np.float64 chunks = [] column_names = self.get_column_names(strings=False) for name in column_names: column_type = self.data_type(name).numpy if not np.can_cast(column_type, dtype): if column_type != dtype: raise ValueError("Cannot cast %r (of type %r) to %r" % (name, self.data_type(name), dtype)) chunks = self.evaluate(column_names, parallel=parallel, array_type='numpy') if any(np.ma.isMaskedArray(chunk) for chunk in chunks): return np.ma.array(chunks, dtype=dtype).T else: return np.array(chunks, dtype=dtype).T def as_arrow(self): df = self.copy() for name in self.get_column_names(): df[name] = df[name].as_arrow() return df def as_numpy(self, strict=False): df = self.copy() for name in self.get_column_names(): df[name] = df[name].as_numpy(strict=strict) return df @vaex.utils.deprecated('use DataFrame.join(other)') def _hstack(self, other, prefix=None): assert len(self) == len(other), "does not make sense to horizontally stack DataFrames with different lengths" for name in other.get_column_names(): if prefix: new_name = prefix + name else: new_name = name self.add_column(new_name, other.columns[name]) def concat(self, *others, resolver='flexible') -> DataFrame: dfs = [self, *others] dfs = [df.extract() for df in dfs] common = [] dfs_real_column_names = [df.get_column_names(virtual=False, hidden=True) for df in dfs] dfs_all_column_names = [df.get_column_names(virtual=True, hidden=True) for df in dfs] all_column_names = [] for column_names in dfs_all_column_names: for name in column_names: if name not in all_column_names: all_column_names.append(name) real_column_names = [] for column_names in dfs_real_column_names: for name in column_names: if name not in real_column_names: real_column_names.append(name) for name in all_column_names: if name in real_column_names: for df, df_real_column_names, df_all_column_names in zip(dfs, dfs_real_column_names, dfs_all_column_names): if name in df_all_column_names and name not in df_real_column_names: dfs[dfs.index(df)] = df._lazy_materialize(name) else: # check virtual column expressions = [df.virtual_columns.get(name, None) for df in dfs] test_expression = [k for k in expressions if k][0] if any([test_expression != k for k in expressions]): # we have a mismatching virtual column, materialize it for df in dfs: # upgrade to a column, so Dataset's concat can concat if name in df.get_column_names(virtual=True, hidden=True): dfs[dfs.index(df)] = df._lazy_materialize(name) first, *tail = dfs dataset = first.dataset.concat(*[df.dataset for df in tail], resolver=resolver) df_concat = vaex.dataframe.DataFrameLocal(dataset) for name in list(first.virtual_columns.keys()): assert all([first.virtual_columns[name] == df.virtual_columns.get(name, None) for df in tail]), 'Virtual column expression mismatch for column {name}' df_concat.add_virtual_column(name, first.virtual_columns[name]) for df in dfs: for name, value in list(df.variables.items()): if name not in df_concat.variables: df_concat.set_variable(name, value, write=False) for df in dfs: for name, value in list(df.functions.items()): if name not in df_concat.functions: if isinstance(value, vaex.expression.Function): value = value.f if isinstance(value, vaex.expression.FunctionSerializablePickle): value = value.f df_concat.add_function(name, value) else: if df_concat.functions[name].f != df.functions[name].f: raise ValueError(f'Unequal function {name} in concatenated dataframes are not supported yet') return df_concat def _invalidate_caches(self): self._invalidate_selection_cache() self._cached_filtered_length = None self._filter_filled = False def _invalidate_selection_cache(self): self._selection_mask_caches.clear() for key in self._selection_masks.keys(): self._selection_masks[key] = vaex.superutils.Mask(int(self._length_original)) def _filtered_range_to_unfiltered_indices(self, i1, i2): assert self.filtered self._fill_filter_mask() count = len(self) assert i2 <= count cache = self._selection_mask_caches[FILTER_SELECTION_NAME] mask_blocks = iter(sorted( [(k1, k2, block) for (k1, k2), (selection, block) in cache.items()], key=lambda item: item[0])) done = False offset_unfiltered = 0 offset_filtered = 0 indices = [] while not done: unfiltered_i1, unfiltered_i2, block = next(mask_blocks) count = block.sum() if (offset_filtered + count) < i1: assert unfiltered_i2 == offset_unfiltered + len(block) offset_unfiltered = unfiltered_i2 offset_filtered += count else: for block_index in range(len(block)): if block[block_index]: if i1 <= offset_filtered < i2: indices.append(offset_unfiltered) offset_filtered += 1 offset_unfiltered += 1 done = offset_filtered >= i2 return np.array(indices, dtype=np.int64) def _evaluate(self, expression, i1, i2, out=None, selection=None, internal=False, filter_mask=None): scope = scopes._BlockScope(self, i1, i2, mask=filter_mask, **self.variables) if out is not None: scope.buffers[expression] = out value = scope.evaluate(expression) if isinstance(value, ColumnString) and not internal: value = value.to_numpy() return value def _unfiltered_chunk_slices(self, chunk_size): logical_length = len(self) if self.filtered: full_mask = self._selection_masks[FILTER_SELECTION_NAME] for item in vaex.utils.subdivide_mask(full_mask, max_length=chunk_size, logical_length=logical_length): yield item else: for i1, i2 in vaex.utils.subdivide(logical_length, max_length=chunk_size): yield i1, i2, i1, i2 def _evaluate_implementation(self, expression, i1=None, i2=None, out=None, selection=None, filtered=True, array_type=None, parallel=True, chunk_size=None, raw=False, progress=None): was_list, [expressions] = vaex.utils.listify(expression) expressions = vaex.utils._ensure_strings_from_expressions(expressions) column_names = self.get_column_names(hidden=True) expressions = [vaex.utils.valid_expression(column_names, k) for k in expressions] selection = _normalize_selection(selection) selection = _ensure_strings_from_expressions(selection) max_stop = (len(self) if (self.filtered and filtered) else self.length_unfiltered()) i1 = i1 or 0 i2 = i2 or max_stop if parallel: df = self if self.filtered and not filtered: df = df.drop_filter() if i1 != 0 or i2 != max_stop: if not raw and self.filtered and filtered: self._fill_filter_mask() mask = self._selection_masks[FILTER_SELECTION_NAME] i1, i2 = mask.indices(i1, i2-1) assert i1 != -1 i2 += 1 df = df.trim() df.set_active_range(i1, i2) df = df.trim() else: df = self expression = expressions[0] mask = None if parallel: use_filter = df.filtered and filtered length = df.length_unfiltered() arrays = {} # maps to a dict of start_index -> apache arrow array (a chunk) chunks_map = {} dtypes = {} shapes = {} virtual = set() # TODO: For NEP branch: dtype -> dtype_evaluate expression_to_evaluate = list(set(expressions)) # lets assume we have to do them all for expression in set(expressions): expression_obj = expression expression = self._expr(expression)._label dtypes[expression] = dtype = df.data_type(expression).internal if expression not in df.columns: virtual.add(expression) # since we will use pre_filter=True, we'll get chunks of the data at unknown offset if use_filter or selection:# or not isinstance(dtype, np.dtype): chunks_map[expression] = {} else: # we know exactly where to place the chunks, so we pre allocate the arrays if expression in virtual: if isinstance(dtype, np.dtype): shape = (length, ) + df._shape_of(expression, filtered=False)[1:] shapes[expression] = shape # numpy arrays are fixed length, so we can pre allocate them if df.is_masked(expression): arrays[expression] = np.ma.empty(shapes.get(expression, length), dtype=dtypes[expression]) else: arrays[expression] = np.zeros(shapes.get(expression, length), dtype=dtypes[expression]) else: # TODO: find a way to modify an arrow array inplace, e.g. float64 array # probably by making an ndarray, and have an Arrow array view that # fixed_width = False # try: # ts.bit_width # fixed_width = True # except ValueError: # pass # if fixed_width: chunks_map[expression] = {} else: # quick path, we can just copy the column arrays[expression] = df.columns[expression] start, end = df._index_start, df._index_end if start != 0 or end != len(arrays[expression]): arrays[expression] = arrays[expression][start:end] if isinstance(arrays[expression], vaex.column.Column): arrays[expression] = arrays[expression][0:end-start] # materialize fancy columns (lazy, indexed) expression_to_evaluate.remove(expression_obj) def assign(thread_index, i1, i2, selection_masks, blocks): for i, expression in enumerate(expression_to_evaluate): expression_obj = expression expression = self._expr(expression)._label if expression in chunks_map: # for non-primitive arrays we simply keep a reference to the chunk chunks_map[expression][i1] = blocks[i] else: # for primitive arrays (and no filter/selection) we directly add it to the right place in contiguous numpy array arrays[expression][i1:i2] = blocks[i] if expression_to_evaluate: df.map_reduce(assign, lambda *_: None, expression_to_evaluate, progress=progress, ignore_filter=False, selection=selection, pre_filter=use_filter, info=True, to_numpy=False, name="evaluate") def finalize_result(expression): expression_obj = expression expression = self._expr(expression)._label if expression in chunks_map: # put all chunks in order chunks = [chunk for (i1, chunk) in sorted(chunks_map[expression].items(), key=lambda i1_and_chunk: i1_and_chunk[0])] assert len(chunks) > 0 if len(chunks) == 1: values = array_types.convert(chunks[0], array_type) else: values = array_types.convert(chunks, array_type) else: values = array_types.convert(arrays[expression], array_type) values = self._auto_encode_data(expression, values) return values result = [finalize_result(k) for k in expressions] if not was_list: result = result[0] return result else: assert df is self if i1 == i2: # empty arrays values = [array_types.convert(self.data_type(e).create_array([]), array_type) for e in expressions] if not was_list: return values[0] return values if not raw and self.filtered and filtered: self._fill_filter_mask() # fill caches and masks mask = self._selection_masks[FILTER_SELECTION_NAME] # if _DEBUG: # if i1 == 0 and i2 == count_check: # # we cannot check it if we just evaluate a portion # assert not mask.view(self._index_start, self._index_end).is_dirty() # # assert mask.count() == count_check ni1, ni2 = mask.indices(i1, i2-1) # -1 since it is inclusive assert ni1 != -1 assert ni2 != -1 i1, i2 = ni1, ni2 i2 = i2+1 # +1 to make it inclusive values = [] dataset = self.dataset if i1 != 0 or i2 != self.dataset.row_count: dataset = dataset[i1:i2] deps = set() for expression in expressions: deps |= self._expr(expression).dependencies() deps = {k for k in deps if k in dataset} if self.filtered: filter_deps = df.get_selection(vaex.dataframe.FILTER_SELECTION_NAME).dependencies(df) deps |= filter_deps columns = {k: dataset[k][:] for k in deps if k in dataset} if self.filtered and filtered: filter_scope = scopes._BlockScope(df, i1, i2, None, selection=True, values={**df.variables, **{k: columns[k] for k in filter_deps if k in columns}}) filter_scope.filter_mask = None filter_mask = filter_scope.evaluate(vaex.dataframe.FILTER_SELECTION_NAME) columns = {k:vaex.array_types.filter(v, filter_mask) for k, v, in columns.items()} else: filter_mask = None block_scope = scopes._BlockScope(self, i1, i2, mask=mask, values={**self.variables, **columns}) block_scope.mask = filter_mask for expression in expressions: value = block_scope.evaluate(expression) value = array_types.convert(value, array_type) values.append(value) if not was_list: return values[0] return values def _equals(self, other): values = self.compare(other) return values == ([], [], [], []) def compare(self, other, report_missing=True, report_difference=False, show=10, orderby=None, column_names=None): if column_names is None: column_names = self.get_column_names(virtual=False) for other_column_name in other.get_column_names(virtual=False): if other_column_name not in column_names: column_names.append(other_column_name) different_values = [] missing = [] type_mismatch = [] meta_mismatch = [] assert len(self) == len(other) if orderby: index1 = np.argsort(self.columns[orderby]) index2 = np.argsort(other.columns[orderby]) for column_name in column_names: if column_name not in self.get_column_names(virtual=False): missing.append(column_name) if report_missing: print("%s missing from this DataFrame" % column_name) elif column_name not in other.get_column_names(virtual=False): missing.append(column_name) if report_missing: print("%s missing from other DataFrame" % column_name) else: ucd1 = self.ucds.get(column_name) ucd2 = other.ucds.get(column_name) if ucd1 != ucd2: print("ucd mismatch : %r vs %r for %s" % (ucd1, ucd2, column_name)) meta_mismatch.append(column_name) unit1 = self.units.get(column_name) unit2 = other.units.get(column_name) if unit1 != unit2: print("unit mismatch : %r vs %r for %s" % (unit1, unit2, column_name)) meta_mismatch.append(column_name) type1 = self.data_type(column_name) type2 = other.data_type(column_name) if not vaex.array_types.same_type(type1, type2): print("different data types: %s vs %s for %s" % (self.data_type(column_name), other.data_type(column_name), column_name)) type_mismatch.append(column_name) else: # a = self.columns[column_name] # b = other.columns[column_name] # if self.filtered: # a = a[self.evaluate_selection_mask(None)] # if other.filtered: # b = b[other.evaluate_selection_mask(None)] a = self.evaluate(column_name, array_type="numpy") b = other.evaluate(column_name, array_type="numpy") if orderby: a = a[index1] b = b[index2] def normalize(ar): if isinstance(ar, pa.Array): ar = ar.to_pandas().values # if ar.dtype == str_type: # return ar if ar.dtype.kind == "f" and hasattr(ar, "mask"): mask = ar.mask ar = ar.copy() ar[mask] = np.nan if ar.dtype.kind in "SU": if hasattr(ar, "mask"): data = ar.data else: data = ar values = [value.strip() for value in data.tolist()] if hasattr(ar, "mask"): ar = np.ma.masked_array(values, ar.mask) else: ar = np.array(values) return ar def equal_mask(a, b): a = normalize(a) b = normalize(b) boolean_mask = (a == b) if not self.is_string(column_name) and self.data_type(column_name).kind == 'f': # floats with nan won't equal itself, i.e. NaN != NaN boolean_mask |= (np.isnan(a) & np.isnan(b)) return boolean_mask boolean_mask = equal_mask(a, b) all_equal = np.all(boolean_mask) if not all_equal: count = np.sum(~boolean_mask) print("%s does not match for both DataFrames, %d rows are diffent out of %d" % (column_name, count, len(self))) different_values.append(column_name) if report_difference: indices = np.arange(len(self))[~boolean_mask] values1 = self.columns[column_name][:][~boolean_mask] values2 = other.columns[column_name][:][~boolean_mask] print("\tshowing difference for the first 10") for i in range(min(len(values1), show)): try: diff = values1[i] - values2[i] except: diff = "does not exists" print("%s[%d] == %s != %s other.%s[%d] (diff = %s)" % (column_name, indices[i], values1[i], values2[i], column_name, indices[i], diff)) return different_values, missing, type_mismatch, meta_mismatch @docsubst def join(self, other, on=None, left_on=None, right_on=None, lprefix='', rprefix='', lsuffix='', rsuffix='', how='left', allow_duplication=False, prime_growth=False, cardinality_other=None, inplace=False): import vaex.join kwargs = dict(**locals()) kwargs['df'] = kwargs.pop('self') del kwargs['vaex'] return vaex.join.join(**kwargs) @docsubst def export(self, path, progress=None, chunk_size=default_chunk_size, parallel=True, fs_options=None, fs=None): naked_path, options = vaex.file.split_options(path) fs_options = fs_options or {} if naked_path.endswith('.arrow'): self.export_arrow(path, progress=progress, chunk_size=chunk_size, parallel=parallel, fs_options=fs_options, fs=fs) elif naked_path.endswith('.feather'): self.export_feather(path, parallel=parallel, fs_options=fs_options) elif naked_path.endswith('.hdf5'): self.export_hdf5(path, progress=progress, parallel=parallel) elif naked_path.endswith('.fits'): self.export_fits(path, progress=progress) elif naked_path.endswith('.parquet'): self.export_parquet(path, progress=progress, parallel=parallel, chunk_size=chunk_size, fs_options=fs_options, fs=fs) elif naked_path.endswith('.csv'): self.export_csv(path, progress=progress, parallel=parallel, chunk_size=chunk_size) elif naked_path.endswith('.json'): self.export_json(path, progress=progress, chunk_size=chunk_size, parallel=parallel, fs_options=fs_options, fs=fs) else: raise ValueError('''Unrecognized file extension. Please use .arrow, .hdf5, .parquet, .fits, or .csv to export to the particular file format.''') @docsubst def export_arrow(self, to, progress=None, chunk_size=default_chunk_size, parallel=True, reduce_large=True, fs_options=None, fs=None, as_stream=True): def write(writer): N = len(self) if chunk_size: with vaex.progress.tree(progress, title="export(arrow)") as progressbar: for i1, i2, table in self.to_arrow_table(chunk_size=chunk_size, parallel=parallel, reduce_large=reduce_large): writer.write_table(table) progressbar(i2/N) progressbar(1.) else: table = self.to_arrow_table(chunk_size=chunk_size, parallel=parallel, reduce_large=reduce_large) writer.write_table(table) if vaex.file.is_path_like(to) or vaex.file.is_file_object(to): schema = self.schema_arrow(reduce_large=reduce_large) with vaex.file.open(path=to, mode='wb', fs_options=fs_options, fs=fs) as sink: if as_stream: with pa.RecordBatchStreamWriter(sink, schema) as writer: write(writer) else: with pa.RecordBatchFileWriter(sink, schema) as writer: write(writer) else: write(to) @docsubst def export_feather(self, to, parallel=True, reduce_large=True, compression='lz4', fs_options=None, fs=None): import pyarrow.feather as feather table = self.to_arrow_table(parallel=False, reduce_large=reduce_large) fs_options = fs_options or {} with vaex.file.open(path=to, mode='wb', fs_options=fs_options, fs=fs) as sink: feather.write_feather(table, sink, compression=compression) @docsubst def export_parquet(self, path, progress=None, chunk_size=default_chunk_size, parallel=True, fs_options=None, fs=None, **kwargs): import pyarrow.parquet as pq schema = self.schema_arrow(reduce_large=True) with vaex.file.open(path=path, mode='wb', fs_options=fs_options, fs=fs) as sink: with pq.ParquetWriter(sink, schema, **kwargs) as writer: self.export_arrow(writer, progress=progress, chunk_size=chunk_size, parallel=parallel, reduce_large=True) @docsubst def export_partitioned(self, path, by, directory_format='{key}={value}', progress=None, chunk_size=default_chunk_size, parallel=True, fs_options={}, fs=None): from uuid import uuid4 if not _issequence(by): by = [by] by = _ensure_strings_from_expressions(by) columns = self.get_column_names() for name in by: columns.remove(name) progressbar = vaex.utils.progressbars(progress, title="export(partitioned)") progressbar(0) groups = self.groupby(by) _, ext, _ = vaex.file.split_ext(path) if not ext: path = vaex.file.stringyfy(path) + '/{subdir}/{uuid}.parquet' else: path = vaex.file.stringyfy(path) for i, (values, df) in enumerate(groups): parts = [directory_format.format(key=key, value=value) for key, value in dict(zip(by, values)).items()] subdir = '/'.join(parts) uuid = uuid4() fullpath = path.format(uuid=uuid, subdir=subdir, i=i) dirpath = os.path.dirname(fullpath) vaex.file.create_dir(dirpath, fs_options=fs_options, fs=fs) progressbar((i)/len(groups)) df[columns].export(fullpath, chunk_size=chunk_size, parallel=parallel, fs_options=fs_options, fs=fs) progressbar(1) @docsubst def export_many(self, path, progress=None, chunk_size=default_chunk_size, parallel=True, max_workers=None, fs_options=None, fs=None): from .itertools import pmap, pwait, buffer, consume path1 = str(path).format(i=0, i1=1, i2=2) path2 = str(path).format(i=1, i1=2, i2=3) if path1 == path2: name, ext = os.path.splitext(path) path = f'{name}-{{i:05}}{ext}' input = self.to_dict(chunk_size=chunk_size, parallel=True) column_names = self.get_column_names() def write(i, item): i1, i2, chunks = item p = str(path).format(i=i, i1=i2, i2=i2) df = vaex.from_dict(chunks) df.export(p, chunk_size=None, parallel=False, fs_options=fs_options, fs=fs) return i2 progressbar = vaex.utils.progressbars(progress, title="export(many)") progressbar(0) length = len(self) def update_progress(offset): progressbar(offset / length) pool = concurrent.futures.ThreadPoolExecutor(max_workers) workers = pool._max_workers consume(map(update_progress, pwait(buffer(pmap(write, enumerate(input), pool=pool), workers+3)))) progressbar(1) @docsubst def export_hdf5(self, path, byteorder="=", progress=None, chunk_size=default_chunk_size, parallel=True, column_count=1, writer_threads=0, group='/table', mode='w'): from vaex.hdf5.writer import Writer with vaex.utils.progressbars(progress, title="export(hdf5)") as progressbar: progressbar_layout = progressbar.add("layout file structure") progressbar_write = progressbar.add("write data") with Writer(path=path, group=group, mode=mode, byteorder=byteorder) as writer: writer.layout(self, progress=progressbar_layout) writer.write( self, chunk_size=chunk_size, progress=progressbar_write, column_count=column_count, parallel=parallel, export_threads=writer_threads) @docsubst def export_fits(self, path, progress=None): from vaex.astro.fits import export_fits export_fits(self, path, progress=progress) @docsubst def export_csv(self, path, progress=None, chunk_size=default_chunk_size, parallel=True, **kwargs): import pandas as pd expressions = self.get_column_names() progressbar = vaex.utils.progressbars(progress, title="export(csv)") dtypes = self[expressions].dtypes n_samples = len(self) if chunk_size is None: chunk_size = len(self) # By default vaex does not expect a csv file to have index like column so this is turned of by default if 'index' not in kwargs: kwargs['index'] = False for i1, i2, chunks in self.evaluate_iterator(expressions, chunk_size=chunk_size, parallel=parallel): progressbar( i1 / n_samples) chunk_dict = {col: values for col, values in zip(expressions, chunks)} chunk_pdf = pd.DataFrame(chunk_dict) if i1 == 0: # Only the 1st chunk should have a header and the rest will be appended kwargs['mode'] = 'w' else: kwargs['mode'] = 'a' kwargs['header'] = False chunk_pdf.to_csv(path_or_buf=path, **kwargs) progressbar(1.0) return @docsubst def export_json(self, to, progress=None, chunk_size=default_chunk_size, parallel=True, fs_options=None, fs=None): json = None # we may want to pass the module as parameter to use a faster library import json as json_std json = json or json_std # not sure if we want to use pandas, it will treat datetime for us, but will convert null to nan use_pandas = True # we take on the '[' and ']' from each chunk, and insert it back ourselves # and we also need to but ',' between each chunk with vaex.progress.tree(progress, title="export(json)"), vaex.file.open(path=to, mode='wb', fs_options=fs_options, fs=fs) as f: f.write(b"[") first = True if use_pandas: for _i1, _i2, df in self.to_pandas_df(chunk_size=chunk_size, parallel=parallel): if not first: f.write(b", ") first = False f_temp = io.StringIO() df.to_json(f_temp, orient='records') f.write(f_temp.getvalue()[1:-1].encode('utf8')) else: for _i1, _i2, records in self.to_records(chunk_size=chunk_size, parallel=parallel): if not first: f.write(b", ") first = False raw = json.dumps(records)[1:-1] f.write(raw.encode("utf8")) f.write(b"]") def _needs_copy(self, column_name): import vaex.file.other return not \ ((column_name in self.column_names and not isinstance(self.columns[column_name], Column) and not isinstance(self.columns[column_name], vaex.file.other.DatasetTap.TapColumn) and self.columns[column_name].dtype.type == np.float64 and self.columns[column_name].strides[0] == 8 and column_name not in self.virtual_columns) or self.data_type(column_name) == str_type or self.data_type(column_name).kind == 'S') # and False: def selected_length(self, selection="default"): return int(self.count(selection=selection).item()) # np.sum(self.mask) if self.has_selection() else None # def _set_mask(self, mask): # self.mask = mask # self._has_selection = mask is not None # # self.signal_selection_changed.emit(self) @docsubst def groupby(self, by=None, agg=None, sort=False, ascending=True, assume_sparse='auto', row_limit=None, copy=True, progress=None, delay=False): from .groupby import GroupBy progressbar = vaex.utils.progressbars(progress, title="groupby") groupby = GroupBy(self, by=by, sort=sort, ascending=ascending, combine=assume_sparse, row_limit=row_limit, copy=copy, progress=progressbar) if agg: progressbar_agg = progressbar.add('aggregators') @vaex.delayed def next(_ignore): if agg is None: return groupby else: return groupby.agg(agg, delay=delay, progress=progressbar_agg) return self._delay(delay, progressbar.exit_on(next(groupby._promise_by))) @docsubst def binby(self, by=None, agg=None, sort=False, copy=True, delay=False, progress=None): from .groupby import BinBy progressbar = vaex.utils.progressbars(progress, title="binby") binby = BinBy(self, by=by, sort=sort, progress=progressbar, copy=copy) if agg: progressbar_agg = progressbar.add('aggregators') @vaex.delayed def next(_ignore): if agg is None: return binby else: return binby.agg(agg, delay=delay, progress=progressbar_agg) return self._delay(delay, progressbar.exit_on(next(binby._promise_by))) def _selection(self, create_selection, name, executor=None, execute_fully=False): def create_wrapper(current): selection = create_selection(current) # only create a mask when we have a selection, so we do not waste memory if selection is not None and name not in self._selection_masks: self._selection_masks[name] = vaex.superutils.Mask(int(self._length_unfiltered)) return selection return super()._selection(create_wrapper, name, executor, execute_fully) @property def values(self): return self.__array__() def _is_dtype_ok(dtype): return dtype.type in [np.bool_, np.int8, np.int16, np.int32, np.int64, np.uint8, np.uint16, np.uint32, np.uint64, np.float32, np.float64, np.datetime64] or\ dtype.type == np.string_ or dtype.type == np.unicode_ def _is_array_type_ok(array): return _is_dtype_ok(array.dtype) # there represent the spec version of the cpu based vaex.superagg.BinnerScalar/Ordinal_<dtype> register_binner = vaex.encoding.make_class_registery('binner') class BinnerBase: @classmethod def decode(cls, encoding, spec): spec = spec.copy() spec['dtype'] = encoding.decode('dtype', spec['dtype']) return cls(**spec) @register_binner class BinnerScalar(BinnerBase): snake_name = 'scalar' def __init__(self, expression, minimum, maximum, count, dtype): self.expression = str(expression) self.minimum = minimum self.maximum = maximum self.count = count self.dtype = dtype def __repr__(self): return f'binner_scalar({self.expression}, {self.minimum}, {self.maximum}, count={self.count})' def encode(self, encoding): dtype = encoding.encode('dtype', self.dtype) return {'expression': self.expression, 'dtype': dtype, 'count': self.count, 'minimum': self.minimum, 'maximum': self.maximum} def __hash__(self) -> int: return hash((self.__class__.__name__, self.expression, self.minimum, self.maximum, self.count, self.dtype)) def __eq__(self, rhs): if not isinstance(rhs, BinnerScalar): return False return \ self.expression == rhs.expression and \ self.minimum == rhs.minimum and \ self.maximum == rhs.maximum and \ self.count == rhs.count and \ self.dtype == rhs.dtype @register_binner class BinnerOrdinal(BinnerBase): snake_name = 'ordinal' def __init__(self, expression, minimum, count, invert, dtype): self.expression = str(expression) self.minimum = minimum self.count = count self.invert = invert self.dtype = dtype def __repr__(self): return f'binner_ordinal({self.expression}, {self.minimum}, {self.count}, {self.invert})' def encode(self, encoding): datatype = encoding.encode("dtype", self.dtype) return {"type": "ordinal", "expression": self.expression, "dtype": datatype, "count": self.count, "minimum": self.minimum, "invert": self.invert} def __hash__(self) -> int: return hash((self.__class__.__name__, self.expression, self.minimum, self.count, self.invert, self.dtype)) def __eq__(self, rhs): if not isinstance(rhs, BinnerOrdinal): return False return \ self.expression == rhs.expression and \ self.minimum == rhs.minimum and \ self.count == rhs.count and \ self.invert == rhs.invert and \ self.dtype == rhs.dtype @register_binner class BinnerHash(BinnerBase): snake_name = 'hash' def __init__(self, expression, hash_map_unique, dtype): self.expression = str(expression) self.hash_map_unique = hash_map_unique self.dtype = dtype def __repr__(self): return f'binner_hash({self.expression}, {self.hash_map_unique})' def encode(self, encoding): datatype = encoding.encode('dtype', self.dtype) hash_map_spec = encoding.encode('hash-map-unique', self.hash_map_unique) assert self.hash_map_unique.fingerprint hash_map_id = vaex.cache.fingerprint('binner-hash', self.hash_map_unique.fingerprint) encoding.set_object_spec(hash_map_id, hash_map_spec) return {'expression': self.expression, 'hash_map_unique': hash_map_id, 'dtype': datatype} def __hash__(self) -> int: return hash((self.__class__.__name__, self.expression, self.hash_map_unique)) def __eq__(self, rhs): if not isinstance(rhs, BinnerHash): return False return \ self.expression == rhs.expression and \ self.hash_map_unique == rhs.hash_map_unique and\ self.dtype == rhs.dtype
true
true
1c39437443bb429a67763236a1f6ec0fef6ababf
2,494
py
Python
tests/riscv/address_solving/RVC_misaligned_force.py
Wlgen/force-riscv
9f09b86c5a21ca00f8e5ade8e5186d65bc3e26f8
[ "Apache-2.0" ]
null
null
null
tests/riscv/address_solving/RVC_misaligned_force.py
Wlgen/force-riscv
9f09b86c5a21ca00f8e5ade8e5186d65bc3e26f8
[ "Apache-2.0" ]
null
null
null
tests/riscv/address_solving/RVC_misaligned_force.py
Wlgen/force-riscv
9f09b86c5a21ca00f8e5ade8e5186d65bc3e26f8
[ "Apache-2.0" ]
null
null
null
# # Copyright (C) [2020] Futurewei Technologies, Inc. # # FORCE-RISCV is 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 # # THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES # OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO # NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. # See the License for the specific language governing permissions and # limitations under the License. # from riscv.EnvRISCV import EnvRISCV from riscv.GenThreadRISCV import GenThreadRISCV from base.Sequence import Sequence # ********************************************************************************* # generate N misaligned random RVC load/stores... # ********************************************************************************* # Riscv RVC load/store instrs, word/dword accesses: RVC_load_store_instructions = { "C.FLD##RISCV": 10, "C.LD##RISCV": 10, "C.LW##RISCV": 10, "C.FLDSP##RISCV": 10, "C.LDSP##RISCV": 10, "C.LWSP##RISCV": 10, "C.FSD##RISCV": 10, "C.SD##RISCV": 10, "C.SW##RISCV": 10, "C.FSDSP##RISCV": 10, "C.SDSP##RISCV": 10, "C.SWSP##RISCV": 10, } RVC32_load_store_instructions = { "C.FLD##RISCV": 10, "C.LW##RISCV": 10, "C.FLDSP##RISCV": 10, "C.LWSP##RISCV": 10, "C.FSD##RISCV": 10, "C.SW##RISCV": 10, "C.FSDSP##RISCV": 10, "C.SWSP##RISCV": 10, } class MyMainSequence(Sequence): def generate(self, **kargs): for _ in range(100): # pick random RVC load/store instruction... if self.getGlobalState("AppRegisterWidth") == 32: instr = self.pickWeighted(RVC32_load_store_instructions) else: instr = self.pickWeighted(RVC_load_store_instructions) # pick a random address aligned to a page boundary, # then (re)align that address close to the end of the page, on # half-word boundary. should yield a fair amount of misaligned # load/stores... target_addr = self.genVA(Align=0x1000) | 0xFFE self.notice(">>>>> Instruction: {} Target addr: {:012x}".format(instr, target_addr)) self.genInstruction(instr, {"LSTarget": target_addr}) MainSequenceClass = MyMainSequence GenThreadClass = GenThreadRISCV EnvClass = EnvRISCV
34.164384
97
0.60826
from riscv.EnvRISCV import EnvRISCV from riscv.GenThreadRISCV import GenThreadRISCV from base.Sequence import Sequence RVC_load_store_instructions = { "C.FLD##RISCV": 10, "C.LD##RISCV": 10, "C.LW##RISCV": 10, "C.FLDSP##RISCV": 10, "C.LDSP##RISCV": 10, "C.LWSP##RISCV": 10, "C.FSD##RISCV": 10, "C.SD##RISCV": 10, "C.SW##RISCV": 10, "C.FSDSP##RISCV": 10, "C.SDSP##RISCV": 10, "C.SWSP##RISCV": 10, } RVC32_load_store_instructions = { "C.FLD##RISCV": 10, "C.LW##RISCV": 10, "C.FLDSP##RISCV": 10, "C.LWSP##RISCV": 10, "C.FSD##RISCV": 10, "C.SW##RISCV": 10, "C.FSDSP##RISCV": 10, "C.SWSP##RISCV": 10, } class MyMainSequence(Sequence): def generate(self, **kargs): for _ in range(100): if self.getGlobalState("AppRegisterWidth") == 32: instr = self.pickWeighted(RVC32_load_store_instructions) else: instr = self.pickWeighted(RVC_load_store_instructions) target_addr = self.genVA(Align=0x1000) | 0xFFE self.notice(">>>>> Instruction: {} Target addr: {:012x}".format(instr, target_addr)) self.genInstruction(instr, {"LSTarget": target_addr}) MainSequenceClass = MyMainSequence GenThreadClass = GenThreadRISCV EnvClass = EnvRISCV
true
true
1c394495ee78dcc6978a8c9ea7280ee260d6dedc
296
py
Python
ex085c.py
lucaspereirag/pythonProject
15a88762ca94322918474537bbed13e0ed2b60a6
[ "MIT" ]
null
null
null
ex085c.py
lucaspereirag/pythonProject
15a88762ca94322918474537bbed13e0ed2b60a6
[ "MIT" ]
null
null
null
ex085c.py
lucaspereirag/pythonProject
15a88762ca94322918474537bbed13e0ed2b60a6
[ "MIT" ]
null
null
null
lista = [[], []] for cont in range(0, 4): numero = int(input(f'Número {cont + 1}: ')) if numero % 2 == 0: lista[0].append(numero) else: lista[1].append(numero) lista[0].sort() lista[1].sort() print(f'Números pares: {lista[0]}') print(f'Números ímpares: {lista[1]}')
21.142857
47
0.564189
lista = [[], []] for cont in range(0, 4): numero = int(input(f'Número {cont + 1}: ')) if numero % 2 == 0: lista[0].append(numero) else: lista[1].append(numero) lista[0].sort() lista[1].sort() print(f'Números pares: {lista[0]}') print(f'Números ímpares: {lista[1]}')
true
true
1c39457a03a863ae96ea4251a04280ff26a408c8
7,773
py
Python
meditemp.py
phseiff/MediTemp
cdbcf5b42894f250caa39145fb4c2318247c6761
[ "MIT" ]
null
null
null
meditemp.py
phseiff/MediTemp
cdbcf5b42894f250caa39145fb4c2318247c6761
[ "MIT" ]
null
null
null
meditemp.py
phseiff/MediTemp
cdbcf5b42894f250caa39145fb4c2318247c6761
[ "MIT" ]
null
null
null
#!/usr/bin/python3 """ You gotta run this with sudo!! optional arguments: * supply with --no-notifs if you don't want to use telegram-sent to get notifications. * supply with --no-logfile to disable printing. * supply with --no-gnuplot to disable gnuplot. For a full documentation on how to use this and how to set it up, see README.md """ import sys import os import time from datetime import datetime import subprocess import re import urllib.parse import shutil import pwd import getpass import traceback import warnings import textwrap import temper if "--no-notifs" not in sys.argv: import telegram_send ALREADY_DETECTED_INFUNCTIONAL_GNUPLOT = False CACHED_FILES = dict() if not (os.path.exists("gnuplot.cached_files") and os.path.isdir("gnuplot.cached_files")): os.mkdir("gnuplot.cached_files") else: shutil.rmtree("gnuplot.cached_files") os.mkdir("gnuplot.cached_files") try: with open("meditemp-log.txt", "r") as log_file: log = log_file.read() except FileNotFoundError: open("meditemp-log.txt", "w").close() log = str() def log_print(*args, log_into_file=True): if "--no-logfile" not in sys.argv and log_into_file: global log log += " ".join(args) + "\n" print(*args) def get_user(): """Try to find the user who called sudo/pkexec. Taken from https://unix.stackexchange.com/a/626389 .""" try: return os.getlogin() except OSError: # failed in some ubuntu installations and in systemd services pass try: user = os.environ['USER'] except KeyError: # possibly a systemd service. no sudo was used return getpass.getuser() if user == 'root': try: return os.environ['SUDO_USER'] except KeyError: # no sudo was used pass try: pkexec_uid = int(os.environ['PKEXEC_UID']) return pwd.getpwuid(pkexec_uid).pw_name except KeyError: # no pkexec was used pass return user def file_name_to_cached_file_name(file_name: str) -> str: return "gnuplot.cached_files/" + urllib.parse.quote(file_name).replace("/", "___") def generate_graph(): # run gnuplot if "--no-gnuplot" in sys.argv: return try: subprocess.run("gnuplot meditemp.gnuplot".split(), check=True, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) except subprocess.CalledProcessError: global ALREADY_DETECTED_INFUNCTIONAL_GNUPLOT if not ALREADY_DETECTED_INFUNCTIONAL_GNUPLOT: ALREADY_DETECTED_INFUNCTIONAL_GNUPLOT = True log_print( datetime.now().strftime("%m/%d/%Y, %H:%M") + ": Gnuplot doesn't seem to be installed; data is collected, but won't be plotted for now." ) return # cache things: with open("med_temp.html", "r") as f: html = f.read() srcs = re.findall(r'(?=src)src=\"(?P<src>[^\"]+)', html) srcs = [(src[7:] if src.startswith("file://") else src) for src in srcs] for src in srcs: if src not in CACHED_FILES: if src != "excanvas.js": src_new = file_name_to_cached_file_name(src) shutil.copy(src, src_new) shutil.chown(src_new, get_user()) CACHED_FILES[src] = src_new # uncache things: for src in CACHED_FILES: if src not in srcs: os.remove(CACHED_FILES[src]) del CACHED_FILES[src] # redirect links and make them compatible to Firefox: for src, src_new in CACHED_FILES.items(): for qt in "\"\'": for protocol in ("file://", ""): html = html.replace("src=" + qt + protocol + src + qt, 'src="' + src_new + '"') # safe modified html: with open("med_temp.html", "w") as f: f.write(html) # set ownership to everyone: shutil.chown("gnuplot.cached_files", get_user()) def mainloop(): last_error = None while True: start_time = time.time() date_time = datetime.now().strftime("%m/%d/%Y, %H:%M") warning_list = list() temper_driver_warnings = list() try: # get device and temperature: t = temper.Temper() with warnings.catch_warnings(record=True) as caught_warnings: results = t.read(verbose=False) temper_driver_warnings = list(caught_warnings) results = [result for result in results if "error" not in result and "firmware" in result] results_simplified = [ (r['internal temperature'], r.get('internal humidity')) for r in results ] results_simplified = list(set(results_simplified)) # <- get rid of doubled results assert len(results_simplified) != 0, "no TEMPer devices found. Run temper.py for debugging." assert len(results_simplified) <= 1, ": multiple TEMPer devices found. Run `temper.py -l` for debugging." temperature, humidity = results_simplified.pop() # note time: new_data_line = date_time + "; " + str(temperature) if humidity is not None: # <- important 'cause it could be zero new_data_line += "; " + str(humidity) if not (os.path.exists("med_temp.csv") and os.path.isfile("med_temp.csv")): open("med_temp.csv", "w").close() with open("med_temp.csv", "r") as f_in: data = f_in.read() data += "\n" + new_data_line with open("med_temp.csv", "w") as f_out: f_out.write(data) # alert if alarming: if temperature < 15 or temperature > 25: warning_list.append("Temperature alert: " + str(temperature) + "°") if humidity and humidity > 0.6: warning_list.append("Humidity alert: " + str(humidity * 100) + "%") if warning_list and "--no-notif" not in sys.argv: telegram_send.send(messages=warning_list) # print relevant info: for loggable_line in (warning_list + [new_data_line]): log_print(loggable_line, log_into_file=False) # run gnuplot: generate_graph() last_error = None except AssertionError as e: with open("meditemp-log.txt", "w") as log_file: for exc_text in [w.message.__str__() for w in temper_driver_warnings] + [str(e)]: log_print(date_time + ": " + exc_text) log_file.write(log) shutil.chown("meditemp-log.txt", get_user()) except Exception as e: exc_str = traceback.format_exc() if exc_str == last_error: exc_str = "same as above." else: last_error = exc_str exc_str = "\n" + exc_str log_print(date_time + ": an unknown error occured: " + textwrap.indent(exc_str, " ")) with open("meditemp-log.txt", "w") as log_file: log_file.write(log) shutil.chown("meditemp-log.txt", get_user()) # wait for the next test: try: time.sleep(10 * 60 - (time.time() - start_time)) except KeyboardInterrupt: log_print(date_time + ": exited program.") with open("meditemp-log.txt", "w") as log_file: log_file.write(log) shutil.chown("meditemp-log.txt", get_user()) shutil.chown("med_temp.csv", get_user()) shutil.chown("gnuplot.cached_files", get_user()) exit(0) def main(): mainloop() if __name__ == "__main__": main()
33.076596
117
0.586646
import sys import os import time from datetime import datetime import subprocess import re import urllib.parse import shutil import pwd import getpass import traceback import warnings import textwrap import temper if "--no-notifs" not in sys.argv: import telegram_send ALREADY_DETECTED_INFUNCTIONAL_GNUPLOT = False CACHED_FILES = dict() if not (os.path.exists("gnuplot.cached_files") and os.path.isdir("gnuplot.cached_files")): os.mkdir("gnuplot.cached_files") else: shutil.rmtree("gnuplot.cached_files") os.mkdir("gnuplot.cached_files") try: with open("meditemp-log.txt", "r") as log_file: log = log_file.read() except FileNotFoundError: open("meditemp-log.txt", "w").close() log = str() def log_print(*args, log_into_file=True): if "--no-logfile" not in sys.argv and log_into_file: global log log += " ".join(args) + "\n" print(*args) def get_user(): try: return os.getlogin() except OSError: pass try: user = os.environ['USER'] except KeyError: return getpass.getuser() if user == 'root': try: return os.environ['SUDO_USER'] except KeyError: pass try: pkexec_uid = int(os.environ['PKEXEC_UID']) return pwd.getpwuid(pkexec_uid).pw_name except KeyError: pass return user def file_name_to_cached_file_name(file_name: str) -> str: return "gnuplot.cached_files/" + urllib.parse.quote(file_name).replace("/", "___") def generate_graph(): if "--no-gnuplot" in sys.argv: return try: subprocess.run("gnuplot meditemp.gnuplot".split(), check=True, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) except subprocess.CalledProcessError: global ALREADY_DETECTED_INFUNCTIONAL_GNUPLOT if not ALREADY_DETECTED_INFUNCTIONAL_GNUPLOT: ALREADY_DETECTED_INFUNCTIONAL_GNUPLOT = True log_print( datetime.now().strftime("%m/%d/%Y, %H:%M") + ": Gnuplot doesn't seem to be installed; data is collected, but won't be plotted for now." ) return with open("med_temp.html", "r") as f: html = f.read() srcs = re.findall(r'(?=src)src=\"(?P<src>[^\"]+)', html) srcs = [(src[7:] if src.startswith("file://") else src) for src in srcs] for src in srcs: if src not in CACHED_FILES: if src != "excanvas.js": src_new = file_name_to_cached_file_name(src) shutil.copy(src, src_new) shutil.chown(src_new, get_user()) CACHED_FILES[src] = src_new for src in CACHED_FILES: if src not in srcs: os.remove(CACHED_FILES[src]) del CACHED_FILES[src] for src, src_new in CACHED_FILES.items(): for qt in "\"\'": for protocol in ("file://", ""): html = html.replace("src=" + qt + protocol + src + qt, 'src="' + src_new + '"') # safe modified html: with open("med_temp.html", "w") as f: f.write(html) # set ownership to everyone: shutil.chown("gnuplot.cached_files", get_user()) def mainloop(): last_error = None while True: start_time = time.time() date_time = datetime.now().strftime("%m/%d/%Y, %H:%M") warning_list = list() temper_driver_warnings = list() try: # get device and temperature: t = temper.Temper() with warnings.catch_warnings(record=True) as caught_warnings: results = t.read(verbose=False) temper_driver_warnings = list(caught_warnings) results = [result for result in results if "error" not in result and "firmware" in result] results_simplified = [ (r['internal temperature'], r.get('internal humidity')) for r in results ] results_simplified = list(set(results_simplified)) # <- get rid of doubled results assert len(results_simplified) != 0, "no TEMPer devices found. Run temper.py for debugging." assert len(results_simplified) <= 1, ": multiple TEMPer devices found. Run `temper.py -l` for debugging." temperature, humidity = results_simplified.pop() # note time: new_data_line = date_time + "; " + str(temperature) if humidity is not None: # <- important 'cause it could be zero new_data_line += "; " + str(humidity) if not (os.path.exists("med_temp.csv") and os.path.isfile("med_temp.csv")): open("med_temp.csv", "w").close() with open("med_temp.csv", "r") as f_in: data = f_in.read() data += "\n" + new_data_line with open("med_temp.csv", "w") as f_out: f_out.write(data) # alert if alarming: if temperature < 15 or temperature > 25: warning_list.append("Temperature alert: " + str(temperature) + "°") if humidity and humidity > 0.6: warning_list.append("Humidity alert: " + str(humidity * 100) + "%") if warning_list and "--no-notif" not in sys.argv: telegram_send.send(messages=warning_list) # print relevant info: for loggable_line in (warning_list + [new_data_line]): log_print(loggable_line, log_into_file=False) # run gnuplot: generate_graph() last_error = None except AssertionError as e: with open("meditemp-log.txt", "w") as log_file: for exc_text in [w.message.__str__() for w in temper_driver_warnings] + [str(e)]: log_print(date_time + ": " + exc_text) log_file.write(log) shutil.chown("meditemp-log.txt", get_user()) except Exception as e: exc_str = traceback.format_exc() if exc_str == last_error: exc_str = "same as above." else: last_error = exc_str exc_str = "\n" + exc_str log_print(date_time + ": an unknown error occured: " + textwrap.indent(exc_str, " ")) with open("meditemp-log.txt", "w") as log_file: log_file.write(log) shutil.chown("meditemp-log.txt", get_user()) # wait for the next test: try: time.sleep(10 * 60 - (time.time() - start_time)) except KeyboardInterrupt: log_print(date_time + ": exited program.") with open("meditemp-log.txt", "w") as log_file: log_file.write(log) shutil.chown("meditemp-log.txt", get_user()) shutil.chown("med_temp.csv", get_user()) shutil.chown("gnuplot.cached_files", get_user()) exit(0) def main(): mainloop() if __name__ == "__main__": main()
true
true
1c39458530ceec542f15fe8ab7a396f63b750c45
1,210
py
Python
bootcamp/wiki/plugins/links/wiki_plugin.py
basiltiger/easy_bootcamp
875b9ed287f1a7824bb38f142dbe2f3b1ce54389
[ "MIT" ]
null
null
null
bootcamp/wiki/plugins/links/wiki_plugin.py
basiltiger/easy_bootcamp
875b9ed287f1a7824bb38f142dbe2f3b1ce54389
[ "MIT" ]
null
null
null
bootcamp/wiki/plugins/links/wiki_plugin.py
basiltiger/easy_bootcamp
875b9ed287f1a7824bb38f142dbe2f3b1ce54389
[ "MIT" ]
null
null
null
from __future__ import unicode_literals # -*- coding: utf-8 -*- from django.conf.urls import url from django.core.urlresolvers import reverse_lazy from django.utils.translation import ugettext as _ from wiki.core.plugins import registry from wiki.core.plugins.base import BasePlugin from wiki.plugins.links import settings, views from wiki.plugins.links.mdx.djangowikilinks import WikiPathExtension from wiki.plugins.links.mdx.urlize import makeExtension as urlize_makeExtension class LinkPlugin(BasePlugin): slug = 'links' urlpatterns = {'article': [ url(r'^json/query-urlpath/$', views.QueryUrlPath.as_view(), name='links_query_urlpath'), ]} sidebar = {'headline': _('Links'), 'icon_class': 'fa-bookmark', 'template': 'wiki/plugins/links/sidebar.html', 'form_class': None, 'get_form_kwargs': (lambda a: {})} wikipath_config = [ ('base_url', reverse_lazy('wiki:get', kwargs={'path': ''})), ('default_level', settings.LOOKUP_LEVEL), ] markdown_extensions = [ urlize_makeExtension(), WikiPathExtension(wikipath_config)] registry.register(LinkPlugin)
30.25
79
0.673554
from __future__ import unicode_literals from django.conf.urls import url from django.core.urlresolvers import reverse_lazy from django.utils.translation import ugettext as _ from wiki.core.plugins import registry from wiki.core.plugins.base import BasePlugin from wiki.plugins.links import settings, views from wiki.plugins.links.mdx.djangowikilinks import WikiPathExtension from wiki.plugins.links.mdx.urlize import makeExtension as urlize_makeExtension class LinkPlugin(BasePlugin): slug = 'links' urlpatterns = {'article': [ url(r'^json/query-urlpath/$', views.QueryUrlPath.as_view(), name='links_query_urlpath'), ]} sidebar = {'headline': _('Links'), 'icon_class': 'fa-bookmark', 'template': 'wiki/plugins/links/sidebar.html', 'form_class': None, 'get_form_kwargs': (lambda a: {})} wikipath_config = [ ('base_url', reverse_lazy('wiki:get', kwargs={'path': ''})), ('default_level', settings.LOOKUP_LEVEL), ] markdown_extensions = [ urlize_makeExtension(), WikiPathExtension(wikipath_config)] registry.register(LinkPlugin)
true
true
1c3945eae691de7baaef4774b2e28e69f9ac26a3
2,763
py
Python
src/valiant/repositories/factory.py
pomes/valiant
786d417a7903d40e54136f645fdbe51575612902
[ "MIT" ]
2
2020-11-11T00:13:32.000Z
2021-04-26T08:31:28.000Z
src/valiant/repositories/factory.py
pomes/valiant
786d417a7903d40e54136f645fdbe51575612902
[ "MIT" ]
10
2020-03-15T00:09:23.000Z
2021-06-10T22:43:53.000Z
src/valiant/repositories/factory.py
pomes/valiant
786d417a7903d40e54136f645fdbe51575612902
[ "MIT" ]
null
null
null
"""Works out which repo wrangler ya need. Copyright (c) 2020 The Valiant Authors 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 .config import RepositoryConfiguration from .repository import BaseRepository class RepositoryFactory: """Helps construct a repository instance based on the configuration.""" def __init__(self): """Constructor.""" from typing import Dict self._cache: Dict[str, BaseRepository] = {} def _instantiate_handler(self, conf: RepositoryConfiguration) -> BaseRepository: from .pypi import PyPiRepository if conf.repository_type in PyPiRepository.list_supported_repository_types(): return PyPiRepository(conf) raise ValueError( f"Unable to handle repositories of type {conf.repository_type}" ) def _check_cache(self, conf: RepositoryConfiguration) -> BaseRepository: if conf.name in self._cache: if self._cache[conf.name].repository_configuration != conf: raise ValueError( "Cache clash" " - repository configuration uses the same name as an existing cache entry" ) else: self._cache[conf.name] = self._instantiate_handler(conf) return self._cache[conf.name] def get_repository( self, repository_configuration: RepositoryConfiguration, ) -> BaseRepository: """Factory method. Args: repository_configuration: The repository config Returns: A repository instance that handles the type set in the config """ return self._check_cache(repository_configuration) def reset_cache(self) -> None: """Clears the cache.""" self._cache = {}
37.849315
95
0.706478
from .config import RepositoryConfiguration from .repository import BaseRepository class RepositoryFactory: def __init__(self): from typing import Dict self._cache: Dict[str, BaseRepository] = {} def _instantiate_handler(self, conf: RepositoryConfiguration) -> BaseRepository: from .pypi import PyPiRepository if conf.repository_type in PyPiRepository.list_supported_repository_types(): return PyPiRepository(conf) raise ValueError( f"Unable to handle repositories of type {conf.repository_type}" ) def _check_cache(self, conf: RepositoryConfiguration) -> BaseRepository: if conf.name in self._cache: if self._cache[conf.name].repository_configuration != conf: raise ValueError( "Cache clash" " - repository configuration uses the same name as an existing cache entry" ) else: self._cache[conf.name] = self._instantiate_handler(conf) return self._cache[conf.name] def get_repository( self, repository_configuration: RepositoryConfiguration, ) -> BaseRepository: return self._check_cache(repository_configuration) def reset_cache(self) -> None: self._cache = {}
true
true
1c39460ba37951a4967580d366596462867ba20e
8,653
py
Python
plugins/modules/oci_mysql_analytics_cluster_memory_estimate_facts.py
sohwaje/oci-ansible-collection
9e6b8cf55e596a96560710a457a7df05886fc59c
[ "Apache-2.0" ]
null
null
null
plugins/modules/oci_mysql_analytics_cluster_memory_estimate_facts.py
sohwaje/oci-ansible-collection
9e6b8cf55e596a96560710a457a7df05886fc59c
[ "Apache-2.0" ]
null
null
null
plugins/modules/oci_mysql_analytics_cluster_memory_estimate_facts.py
sohwaje/oci-ansible-collection
9e6b8cf55e596a96560710a457a7df05886fc59c
[ "Apache-2.0" ]
null
null
null
#!/usr/bin/python # Copyright (c) 2020, 2021 Oracle and/or its affiliates. # This software is made available to you under the terms of the GPL 3.0 license or the Apache 2.0 license. # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) # Apache License v2.0 # See LICENSE.TXT for details. # GENERATED FILE - DO NOT EDIT - MANUAL CHANGES WILL BE OVERWRITTEN from __future__ import absolute_import, division, print_function __metaclass__ = type ANSIBLE_METADATA = { "metadata_version": "1.1", "status": ["preview"], "supported_by": "community", } DOCUMENTATION = """ --- module: oci_mysql_analytics_cluster_memory_estimate_facts short_description: Fetches details about a AnalyticsClusterMemoryEstimate resource in Oracle Cloud Infrastructure description: - Fetches details about a AnalyticsClusterMemoryEstimate resource in Oracle Cloud Infrastructure - "DEPRECATED -- please use HeatWave API instead. Gets the most recent Analytics Cluster memory estimate that can be used to determine a suitable Analytics Cluster size." version_added: "2.9.0" author: Oracle (@oracle) options: db_system_id: description: - The DB System L(OCID,https://docs.cloud.oracle.com/Content/General/Concepts/identifiers.htm). type: str aliases: ["id"] required: true extends_documentation_fragment: [ oracle.oci.oracle ] """ EXAMPLES = """ - name: Get a specific analytics_cluster_memory_estimate oci_mysql_analytics_cluster_memory_estimate_facts: db_system_id: "ocid1.dbsystem.oc1..xxxxxxEXAMPLExxxxxx" """ RETURN = """ analytics_cluster_memory_estimate: description: - AnalyticsClusterMemoryEstimate resource returned: on success type: complex contains: db_system_id: description: - The OCID of the DB System the Analytics Cluster memory estimate is associated with. returned: on success type: str sample: "ocid1.dbsystem.oc1..xxxxxxEXAMPLExxxxxx" status: description: - Current status of the Work Request generating the Analytics Cluster memory estimate. returned: on success type: str sample: ACCEPTED time_created: description: - The date and time that the Work Request to generate the Analytics Cluster memory estimate was issued, as described by L(RFC 3339,https://tools.ietf.org/rfc/rfc333). returned: on success type: str sample: "2013-10-20T19:20:30+01:00" time_updated: description: - The date and time that the Analytics Cluster memory estimate was generated, as described by L(RFC 3339,https://tools.ietf.org/rfc/rfc333). returned: on success type: str sample: "2013-10-20T19:20:30+01:00" table_schemas: description: - Collection of schemas with estimated memory footprints for MySQL user tables of each schema when loaded to Analytics Cluster memory. returned: on success type: complex contains: schema_name: description: - The name of the schema. returned: on success type: str sample: schema_name_example per_table_estimates: description: - Estimated memory footprints for MySQL user tables of the schema when loaded to Analytics Cluster memory. returned: on success type: complex contains: table_name: description: - The table name. returned: on success type: str sample: table_name_example to_load_column_count: description: - The number of columns to be loaded to Analytics Cluster memory. These columns contribute to the analytical memory footprint. returned: on success type: int sample: 56 varlen_column_count: description: - The number of variable-length columns to be loaded to Analytics Cluster memory. These columns contribute to the analytical memory footprint. returned: on success type: int sample: 56 estimated_row_count: description: - The estimated number of rows in the table. This number was used to derive the analytical memory footprint. returned: on success type: int sample: 56 analytical_footprint_in_mbs: description: - The estimated memory footprint of the table in MBs when loaded to Analytics Cluster memory (null if the table cannot be loaded to the Analytics Cluster). returned: on success type: int sample: 56 error_comment: description: - Error comment (empty string if no errors occured). returned: on success type: str sample: error_comment_example sample: { "db_system_id": "ocid1.dbsystem.oc1..xxxxxxEXAMPLExxxxxx", "status": "ACCEPTED", "time_created": "2013-10-20T19:20:30+01:00", "time_updated": "2013-10-20T19:20:30+01:00", "table_schemas": [{ "schema_name": "schema_name_example", "per_table_estimates": [{ "table_name": "table_name_example", "to_load_column_count": 56, "varlen_column_count": 56, "estimated_row_count": 56, "analytical_footprint_in_mbs": 56, "error_comment": "error_comment_example" }] }] } """ from ansible.module_utils.basic import AnsibleModule from ansible_collections.oracle.oci.plugins.module_utils import oci_common_utils from ansible_collections.oracle.oci.plugins.module_utils.oci_resource_utils import ( OCIResourceFactsHelperBase, get_custom_class, ) try: from oci.mysql import DbSystemClient HAS_OCI_PY_SDK = True except ImportError: HAS_OCI_PY_SDK = False class MysqlAnalyticsClusterMemoryEstimateFactsHelperGen(OCIResourceFactsHelperBase): """Supported operations: get""" def get_required_params_for_get(self): return [ "db_system_id", ] def get_resource(self): return oci_common_utils.call_with_backoff( self.client.get_analytics_cluster_memory_estimate, db_system_id=self.module.params.get("db_system_id"), ) MysqlAnalyticsClusterMemoryEstimateFactsHelperCustom = get_custom_class( "MysqlAnalyticsClusterMemoryEstimateFactsHelperCustom" ) class ResourceFactsHelper( MysqlAnalyticsClusterMemoryEstimateFactsHelperCustom, MysqlAnalyticsClusterMemoryEstimateFactsHelperGen, ): pass def main(): module_args = oci_common_utils.get_common_arg_spec() module_args.update( dict(db_system_id=dict(aliases=["id"], type="str", required=True),) ) module = AnsibleModule(argument_spec=module_args) if not HAS_OCI_PY_SDK: module.fail_json(msg="oci python sdk required for this module.") resource_facts_helper = ResourceFactsHelper( module=module, resource_type="analytics_cluster_memory_estimate", service_client_class=DbSystemClient, namespace="mysql", ) result = [] if resource_facts_helper.is_get(): result = resource_facts_helper.get() else: resource_facts_helper.fail() module.exit_json(analytics_cluster_memory_estimate=result) if __name__ == "__main__": main()
37.297414
156
0.585924
from __future__ import absolute_import, division, print_function __metaclass__ = type ANSIBLE_METADATA = { "metadata_version": "1.1", "status": ["preview"], "supported_by": "community", } DOCUMENTATION = """ --- module: oci_mysql_analytics_cluster_memory_estimate_facts short_description: Fetches details about a AnalyticsClusterMemoryEstimate resource in Oracle Cloud Infrastructure description: - Fetches details about a AnalyticsClusterMemoryEstimate resource in Oracle Cloud Infrastructure - "DEPRECATED -- please use HeatWave API instead. Gets the most recent Analytics Cluster memory estimate that can be used to determine a suitable Analytics Cluster size." version_added: "2.9.0" author: Oracle (@oracle) options: db_system_id: description: - The DB System L(OCID,https://docs.cloud.oracle.com/Content/General/Concepts/identifiers.htm). type: str aliases: ["id"] required: true extends_documentation_fragment: [ oracle.oci.oracle ] """ EXAMPLES = """ - name: Get a specific analytics_cluster_memory_estimate oci_mysql_analytics_cluster_memory_estimate_facts: db_system_id: "ocid1.dbsystem.oc1..xxxxxxEXAMPLExxxxxx" """ RETURN = """ analytics_cluster_memory_estimate: description: - AnalyticsClusterMemoryEstimate resource returned: on success type: complex contains: db_system_id: description: - The OCID of the DB System the Analytics Cluster memory estimate is associated with. returned: on success type: str sample: "ocid1.dbsystem.oc1..xxxxxxEXAMPLExxxxxx" status: description: - Current status of the Work Request generating the Analytics Cluster memory estimate. returned: on success type: str sample: ACCEPTED time_created: description: - The date and time that the Work Request to generate the Analytics Cluster memory estimate was issued, as described by L(RFC 3339,https://tools.ietf.org/rfc/rfc333). returned: on success type: str sample: "2013-10-20T19:20:30+01:00" time_updated: description: - The date and time that the Analytics Cluster memory estimate was generated, as described by L(RFC 3339,https://tools.ietf.org/rfc/rfc333). returned: on success type: str sample: "2013-10-20T19:20:30+01:00" table_schemas: description: - Collection of schemas with estimated memory footprints for MySQL user tables of each schema when loaded to Analytics Cluster memory. returned: on success type: complex contains: schema_name: description: - The name of the schema. returned: on success type: str sample: schema_name_example per_table_estimates: description: - Estimated memory footprints for MySQL user tables of the schema when loaded to Analytics Cluster memory. returned: on success type: complex contains: table_name: description: - The table name. returned: on success type: str sample: table_name_example to_load_column_count: description: - The number of columns to be loaded to Analytics Cluster memory. These columns contribute to the analytical memory footprint. returned: on success type: int sample: 56 varlen_column_count: description: - The number of variable-length columns to be loaded to Analytics Cluster memory. These columns contribute to the analytical memory footprint. returned: on success type: int sample: 56 estimated_row_count: description: - The estimated number of rows in the table. This number was used to derive the analytical memory footprint. returned: on success type: int sample: 56 analytical_footprint_in_mbs: description: - The estimated memory footprint of the table in MBs when loaded to Analytics Cluster memory (null if the table cannot be loaded to the Analytics Cluster). returned: on success type: int sample: 56 error_comment: description: - Error comment (empty string if no errors occured). returned: on success type: str sample: error_comment_example sample: { "db_system_id": "ocid1.dbsystem.oc1..xxxxxxEXAMPLExxxxxx", "status": "ACCEPTED", "time_created": "2013-10-20T19:20:30+01:00", "time_updated": "2013-10-20T19:20:30+01:00", "table_schemas": [{ "schema_name": "schema_name_example", "per_table_estimates": [{ "table_name": "table_name_example", "to_load_column_count": 56, "varlen_column_count": 56, "estimated_row_count": 56, "analytical_footprint_in_mbs": 56, "error_comment": "error_comment_example" }] }] } """ from ansible.module_utils.basic import AnsibleModule from ansible_collections.oracle.oci.plugins.module_utils import oci_common_utils from ansible_collections.oracle.oci.plugins.module_utils.oci_resource_utils import ( OCIResourceFactsHelperBase, get_custom_class, ) try: from oci.mysql import DbSystemClient HAS_OCI_PY_SDK = True except ImportError: HAS_OCI_PY_SDK = False class MysqlAnalyticsClusterMemoryEstimateFactsHelperGen(OCIResourceFactsHelperBase): def get_required_params_for_get(self): return [ "db_system_id", ] def get_resource(self): return oci_common_utils.call_with_backoff( self.client.get_analytics_cluster_memory_estimate, db_system_id=self.module.params.get("db_system_id"), ) MysqlAnalyticsClusterMemoryEstimateFactsHelperCustom = get_custom_class( "MysqlAnalyticsClusterMemoryEstimateFactsHelperCustom" ) class ResourceFactsHelper( MysqlAnalyticsClusterMemoryEstimateFactsHelperCustom, MysqlAnalyticsClusterMemoryEstimateFactsHelperGen, ): pass def main(): module_args = oci_common_utils.get_common_arg_spec() module_args.update( dict(db_system_id=dict(aliases=["id"], type="str", required=True),) ) module = AnsibleModule(argument_spec=module_args) if not HAS_OCI_PY_SDK: module.fail_json(msg="oci python sdk required for this module.") resource_facts_helper = ResourceFactsHelper( module=module, resource_type="analytics_cluster_memory_estimate", service_client_class=DbSystemClient, namespace="mysql", ) result = [] if resource_facts_helper.is_get(): result = resource_facts_helper.get() else: resource_facts_helper.fail() module.exit_json(analytics_cluster_memory_estimate=result) if __name__ == "__main__": main()
true
true
1c39477d259e9ad716d99cbf82e58e6f3b87381e
2,399
py
Python
clif/testing/python/sequence_methods_test.py
timgates42/clif
b865c88beff70b31068889926d1184d5ddc0b9eb
[ "Apache-2.0" ]
null
null
null
clif/testing/python/sequence_methods_test.py
timgates42/clif
b865c88beff70b31068889926d1184d5ddc0b9eb
[ "Apache-2.0" ]
null
null
null
clif/testing/python/sequence_methods_test.py
timgates42/clif
b865c88beff70b31068889926d1184d5ddc0b9eb
[ "Apache-2.0" ]
null
null
null
# Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from absl.testing import absltest from absl.testing import parameterized from clif.testing.python import sequence_methods # TODO: Restore simple import after OSS setup includes pybind11. # pylint: disable=g-import-not-at-top try: from clif.testing.python import sequence_methods_pybind11 except ImportError: sequence_methods_pybind11 = None # pylint: enable=g-import-not-at-top @parameterized.named_parameters([ np for np in zip(('c_api', 'pybind11'), (sequence_methods, sequence_methods_pybind11)) if np[1] is not None ]) class SequenceMethodsTest(absltest.TestCase): def testTwoSequence(self, wrapper_lib): s13 = wrapper_lib.TwoSequence(1, 3) self.assertLen(s13, 2) # sq_length s50 = wrapper_lib.TwoSequence(5, 0) self.assertLen(s50, 1) s00 = wrapper_lib.TwoSequence(0, 0) self.assertEmpty(s00) s51 = s50 + s13 # sq_concat self.assertEqual(s51[0], 5) # sq_item self.assertEqual(s51[1], 1) s57 = s50 * (-7) # sq_repeat self.assertSequenceEqual((s57[0], s57[1]), (5, -7)) svv = wrapper_lib.TwoSequence(4, 9) self.assertSequenceEqual((svv[0], svv[1]), (4, 9)) svv[1] = 6 # sq_ass_item: setitem self.assertSequenceEqual((svv[0], svv[1]), (4, 6)) del svv[0] # sq_ass_item: delitem self.assertSequenceEqual((svv[0], svv[1]), (0, 6)) del svv[1] self.assertEmpty(svv) self.assertIn(5, s57) # sq_contains self.assertIn(-7, s57) self.assertNotIn(7, s57) svv = wrapper_lib.TwoSequence(13, 15) svv += s57 # sq_inplace_concat self.assertSequenceEqual((svv[0], svv[1]), (13, -7)) svv = wrapper_lib.TwoSequence(17, 19) svv *= 11 # sq_inplace_repeat self.assertSequenceEqual((svv[0], svv[1]), (17, 11)) if __name__ == '__main__': absltest.main()
33.788732
74
0.689037
from absl.testing import absltest from absl.testing import parameterized from clif.testing.python import sequence_methods try: from clif.testing.python import sequence_methods_pybind11 except ImportError: sequence_methods_pybind11 = None @parameterized.named_parameters([ np for np in zip(('c_api', 'pybind11'), (sequence_methods, sequence_methods_pybind11)) if np[1] is not None ]) class SequenceMethodsTest(absltest.TestCase): def testTwoSequence(self, wrapper_lib): s13 = wrapper_lib.TwoSequence(1, 3) self.assertLen(s13, 2) s50 = wrapper_lib.TwoSequence(5, 0) self.assertLen(s50, 1) s00 = wrapper_lib.TwoSequence(0, 0) self.assertEmpty(s00) s51 = s50 + s13 self.assertEqual(s51[0], 5) self.assertEqual(s51[1], 1) s57 = s50 * (-7) self.assertSequenceEqual((s57[0], s57[1]), (5, -7)) svv = wrapper_lib.TwoSequence(4, 9) self.assertSequenceEqual((svv[0], svv[1]), (4, 9)) svv[1] = 6 self.assertSequenceEqual((svv[0], svv[1]), (4, 6)) del svv[0] self.assertSequenceEqual((svv[0], svv[1]), (0, 6)) del svv[1] self.assertEmpty(svv) self.assertIn(5, s57) self.assertIn(-7, s57) self.assertNotIn(7, s57) svv = wrapper_lib.TwoSequence(13, 15) svv += s57 self.assertSequenceEqual((svv[0], svv[1]), (13, -7)) svv = wrapper_lib.TwoSequence(17, 19) svv *= 11 self.assertSequenceEqual((svv[0], svv[1]), (17, 11)) if __name__ == '__main__': absltest.main()
true
true
1c3948496ed8396ce882619ab8bb6c566ec5d7ec
685
py
Python
hardware/tests/firmware_integration/test_echo.py
y3rsh/opentrons
b446567910db218030fef40396ab2255cc074bba
[ "Apache-2.0" ]
235
2017-10-27T20:37:27.000Z
2022-03-30T14:09:49.000Z
hardware/tests/firmware_integration/test_echo.py
y3rsh/opentrons
b446567910db218030fef40396ab2255cc074bba
[ "Apache-2.0" ]
8,425
2017-10-26T15:25:43.000Z
2022-03-31T23:54:26.000Z
hardware/tests/firmware_integration/test_echo.py
y3rsh/opentrons
b446567910db218030fef40396ab2255cc074bba
[ "Apache-2.0" ]
130
2017-11-09T21:02:37.000Z
2022-03-15T18:01:24.000Z
"""Test Echo firmware.""" import pytest import asyncio from typing import AsyncGenerator from opentrons_hardware.drivers.can_bus import CanDriver, ArbitrationId, CanMessage @pytest.fixture async def driver(loop: asyncio.BaseEventLoop) -> AsyncGenerator[CanDriver, None]: """Create CanDriver connected to OT-3 Emulator.""" driver = await CanDriver.from_env() yield driver driver.shutdown() @pytest.mark.requires_emulator async def test_send(driver: CanDriver) -> None: """Verify sending a message to the emulator.""" message = CanMessage( arbitration_id=ArbitrationId(id=0x1FFFFFFF), data=bytearray([1, 2, 3, 4]) ) await driver.send(message)
29.782609
83
0.737226
import pytest import asyncio from typing import AsyncGenerator from opentrons_hardware.drivers.can_bus import CanDriver, ArbitrationId, CanMessage @pytest.fixture async def driver(loop: asyncio.BaseEventLoop) -> AsyncGenerator[CanDriver, None]: driver = await CanDriver.from_env() yield driver driver.shutdown() @pytest.mark.requires_emulator async def test_send(driver: CanDriver) -> None: message = CanMessage( arbitration_id=ArbitrationId(id=0x1FFFFFFF), data=bytearray([1, 2, 3, 4]) ) await driver.send(message)
true
true
1c3948fdeaf5c6d61eddbba04d30e311127ec3f6
7,300
py
Python
graphql/validation/validation.py
ThanksBoomerang/graphql-core-legacy
6e2fbccdec655ce9122b84d3808c14242c4e6b96
[ "MIT" ]
8
2020-03-23T21:34:02.000Z
2021-11-12T11:27:45.000Z
graphql/validation/validation.py
ThanksBoomerang/graphql-core-legacy
6e2fbccdec655ce9122b84d3808c14242c4e6b96
[ "MIT" ]
17
2020-03-14T22:22:29.000Z
2022-03-16T19:26:37.000Z
graphql/validation/validation.py
ThanksBoomerang/graphql-core-legacy
6e2fbccdec655ce9122b84d3808c14242c4e6b96
[ "MIT" ]
17
2020-03-23T12:06:23.000Z
2022-02-13T05:33:32.000Z
from ..language.ast import FragmentDefinition, FragmentSpread, OperationDefinition from ..language.visitor import ParallelVisitor, TypeInfoVisitor, Visitor, visit from ..type import GraphQLSchema from ..utils.type_info import TypeInfo from .rules import specified_rules # Necessary for static type checking if False: # flake8: noqa from typing import List, Union, Optional, Dict, Set, Any, Type from ..language.ast import Document, SelectionSet, Node from ..error import GraphQLError from .rules.base import ValidationRule from ..type.definition import ( GraphQLObjectType, GraphQLInterfaceType, GraphQLField, GraphQLArgument, GraphQLType, GraphQLInputObjectType, ) def validate(schema, ast, rules=specified_rules): # type: (GraphQLSchema, Document, List[Type[ValidationRule]]) -> List assert schema, "Must provide schema" assert ast, "Must provide document" assert isinstance(schema, GraphQLSchema) type_info = TypeInfo(schema) return visit_using_rules(schema, type_info, ast, rules) def visit_using_rules(schema, type_info, ast, rules): # type: (GraphQLSchema, TypeInfo, Document, List[Type[ValidationRule]]) -> List context = ValidationContext(schema, ast, type_info) visitors = [rule(context) for rule in rules] visit(ast, TypeInfoVisitor(type_info, ParallelVisitor(visitors))) return context.get_errors() class VariableUsage(object): __slots__ = "node", "type" def __init__(self, node, type): self.node = node self.type = type class UsageVisitor(Visitor): __slots__ = "usages", "type_info" def __init__(self, usages, type_info): # type: (List[VariableUsage], TypeInfo) -> None self.usages = usages self.type_info = type_info def enter_VariableDefinition(self, node, key, parent, path, ancestors): return False def enter_Variable(self, node, key, parent, path, ancestors): usage = VariableUsage(node, type=self.type_info.get_input_type()) self.usages.append(usage) class ValidationContext(object): __slots__ = ( "_schema", "_ast", "_type_info", "_errors", "_fragments", "_fragment_spreads", "_recursively_referenced_fragments", "_variable_usages", "_recursive_variable_usages", ) def __init__(self, schema, ast, type_info): # type: (GraphQLSchema, Document, TypeInfo) -> None self._schema = schema self._ast = ast self._type_info = type_info self._errors = [] # type: List[GraphQLError] self._fragments = None # type: Optional[Dict[str, FragmentDefinition]] self._fragment_spreads = {} # type: Dict[Node, List[FragmentSpread]] self._recursively_referenced_fragments = ( {} ) # type: Dict[OperationDefinition, List[FragmentSpread]] self._variable_usages = {} # type: Dict[Node, List[VariableUsage]] self._recursive_variable_usages = ( {} ) # type: Dict[OperationDefinition, List[VariableUsage]] def report_error(self, error): self._errors.append(error) def get_errors(self): # type: () -> List return self._errors def get_schema(self): # type: () -> GraphQLSchema return self._schema def get_variable_usages(self, node): # type: (OperationDefinition) -> List[VariableUsage] usages = self._variable_usages.get(node) if usages is None: usages = [] sub_visitor = UsageVisitor(usages, self._type_info) visit(node, TypeInfoVisitor(self._type_info, sub_visitor)) self._variable_usages[node] = usages return usages def get_recursive_variable_usages(self, operation): # type: (OperationDefinition) -> List[VariableUsage] assert isinstance(operation, OperationDefinition) usages = self._recursive_variable_usages.get(operation) if usages is None: usages = self.get_variable_usages(operation) fragments = self.get_recursively_referenced_fragments(operation) for fragment in fragments: usages.extend(self.get_variable_usages(fragment)) self._recursive_variable_usages[operation] = usages return usages def get_recursively_referenced_fragments(self, operation): # type: (OperationDefinition) -> List assert isinstance(operation, OperationDefinition) fragments = self._recursively_referenced_fragments.get(operation) if not fragments: fragments = [] collected_names = set() # type: Set[str] nodes_to_visit = [operation.selection_set] while nodes_to_visit: node = nodes_to_visit.pop() spreads = self.get_fragment_spreads(node) for spread in spreads: frag_name = spread.name.value if frag_name not in collected_names: collected_names.add(frag_name) fragment = self.get_fragment(frag_name) if fragment: fragments.append(fragment) nodes_to_visit.append(fragment.selection_set) self._recursively_referenced_fragments[operation] = fragments return fragments def get_fragment_spreads(self, node): # type: (SelectionSet) -> List[FragmentSpread] spreads = self._fragment_spreads.get(node) if not spreads: spreads = [] sets_to_visit = [node] while sets_to_visit: _set = sets_to_visit.pop() for selection in _set.selections: if isinstance(selection, FragmentSpread): spreads.append(selection) elif selection.selection_set: sets_to_visit.append(selection.selection_set) self._fragment_spreads[node] = spreads return spreads def get_ast(self): return self._ast def get_fragment(self, name): fragments = self._fragments if fragments is None: self._fragments = fragments = {} for statement in self.get_ast().definitions: if isinstance(statement, FragmentDefinition): fragments[statement.name.value] = statement return fragments.get(name) def get_type(self): # type: () -> Optional[GraphQLType] return self._type_info.get_type() def get_parent_type(self): # type: () -> Union[GraphQLInterfaceType, GraphQLObjectType, None] return self._type_info.get_parent_type() def get_input_type(self): # type: () -> Optional[GraphQLInputObjectType] return self._type_info.get_input_type() # type: ignore def get_field_def(self): # type: () -> Optional[GraphQLField] return self._type_info.get_field_def() def get_directive(self): # type: () -> Optional[Any] return self._type_info.get_directive() def get_argument(self): # type: () -> Optional[GraphQLArgument] return self._type_info.get_argument()
36.138614
83
0.636849
from ..language.ast import FragmentDefinition, FragmentSpread, OperationDefinition from ..language.visitor import ParallelVisitor, TypeInfoVisitor, Visitor, visit from ..type import GraphQLSchema from ..utils.type_info import TypeInfo from .rules import specified_rules if False: from typing import List, Union, Optional, Dict, Set, Any, Type from ..language.ast import Document, SelectionSet, Node from ..error import GraphQLError from .rules.base import ValidationRule from ..type.definition import ( GraphQLObjectType, GraphQLInterfaceType, GraphQLField, GraphQLArgument, GraphQLType, GraphQLInputObjectType, ) def validate(schema, ast, rules=specified_rules): assert schema, "Must provide schema" assert ast, "Must provide document" assert isinstance(schema, GraphQLSchema) type_info = TypeInfo(schema) return visit_using_rules(schema, type_info, ast, rules) def visit_using_rules(schema, type_info, ast, rules): context = ValidationContext(schema, ast, type_info) visitors = [rule(context) for rule in rules] visit(ast, TypeInfoVisitor(type_info, ParallelVisitor(visitors))) return context.get_errors() class VariableUsage(object): __slots__ = "node", "type" def __init__(self, node, type): self.node = node self.type = type class UsageVisitor(Visitor): __slots__ = "usages", "type_info" def __init__(self, usages, type_info): self.usages = usages self.type_info = type_info def enter_VariableDefinition(self, node, key, parent, path, ancestors): return False def enter_Variable(self, node, key, parent, path, ancestors): usage = VariableUsage(node, type=self.type_info.get_input_type()) self.usages.append(usage) class ValidationContext(object): __slots__ = ( "_schema", "_ast", "_type_info", "_errors", "_fragments", "_fragment_spreads", "_recursively_referenced_fragments", "_variable_usages", "_recursive_variable_usages", ) def __init__(self, schema, ast, type_info): self._schema = schema self._ast = ast self._type_info = type_info self._errors = [] self._fragments = None self._fragment_spreads = {} self._recursively_referenced_fragments = ( {} ) self._variable_usages = {} self._recursive_variable_usages = ( {} ) def report_error(self, error): self._errors.append(error) def get_errors(self): return self._errors def get_schema(self): return self._schema def get_variable_usages(self, node): usages = self._variable_usages.get(node) if usages is None: usages = [] sub_visitor = UsageVisitor(usages, self._type_info) visit(node, TypeInfoVisitor(self._type_info, sub_visitor)) self._variable_usages[node] = usages return usages def get_recursive_variable_usages(self, operation): assert isinstance(operation, OperationDefinition) usages = self._recursive_variable_usages.get(operation) if usages is None: usages = self.get_variable_usages(operation) fragments = self.get_recursively_referenced_fragments(operation) for fragment in fragments: usages.extend(self.get_variable_usages(fragment)) self._recursive_variable_usages[operation] = usages return usages def get_recursively_referenced_fragments(self, operation): assert isinstance(operation, OperationDefinition) fragments = self._recursively_referenced_fragments.get(operation) if not fragments: fragments = [] collected_names = set() nodes_to_visit = [operation.selection_set] while nodes_to_visit: node = nodes_to_visit.pop() spreads = self.get_fragment_spreads(node) for spread in spreads: frag_name = spread.name.value if frag_name not in collected_names: collected_names.add(frag_name) fragment = self.get_fragment(frag_name) if fragment: fragments.append(fragment) nodes_to_visit.append(fragment.selection_set) self._recursively_referenced_fragments[operation] = fragments return fragments def get_fragment_spreads(self, node): spreads = self._fragment_spreads.get(node) if not spreads: spreads = [] sets_to_visit = [node] while sets_to_visit: _set = sets_to_visit.pop() for selection in _set.selections: if isinstance(selection, FragmentSpread): spreads.append(selection) elif selection.selection_set: sets_to_visit.append(selection.selection_set) self._fragment_spreads[node] = spreads return spreads def get_ast(self): return self._ast def get_fragment(self, name): fragments = self._fragments if fragments is None: self._fragments = fragments = {} for statement in self.get_ast().definitions: if isinstance(statement, FragmentDefinition): fragments[statement.name.value] = statement return fragments.get(name) def get_type(self): return self._type_info.get_type() def get_parent_type(self): return self._type_info.get_parent_type() def get_input_type(self): return self._type_info.get_input_type() def get_field_def(self): return self._type_info.get_field_def() def get_directive(self): return self._type_info.get_directive() def get_argument(self): return self._type_info.get_argument()
true
true
1c3949beb5e0e8c7ba3be86949a81306113cad5c
876
py
Python
releasetools/releasetools.py
scto/android_device_samsung_sm8250-common
912e07a86f4157f788833f7e65747e0a7e6d9882
[ "Apache-2.0" ]
null
null
null
releasetools/releasetools.py
scto/android_device_samsung_sm8250-common
912e07a86f4157f788833f7e65747e0a7e6d9882
[ "Apache-2.0" ]
null
null
null
releasetools/releasetools.py
scto/android_device_samsung_sm8250-common
912e07a86f4157f788833f7e65747e0a7e6d9882
[ "Apache-2.0" ]
null
null
null
# SPDX-License-Identifier: Apache-2.0 # Copyright (C) 2020 The LineageOS Project import common import re def FullOTA_InstallEnd(info): OTA_InstallEnd(info) return def IncrementalOTA_InstallEnd(info): OTA_InstallEnd(info) return def AddImage(info, basename, dest): path = "IMAGES/" + basename if path not in info.input_zip.namelist(): return data = info.input_zip.read(path) common.ZipWriteStr(info.output_zip, basename, data) info.script.AppendExtra('package_extract_file("%s", "%s");' % (basename, dest)) def OTA_InstallEnd(info): info.script.Print("Patching firmware images...") AddImage(info, "dtbo.img", "/dev/block/bootdevice/by-name/dtbo") AddImage(info, "vbmeta.img", "/dev/block/bootdevice/by-name/vbmeta") return def FullOTA_InstallBegin(info): AddImage(info, "super_empty.img", "/dev/block/bootdevice/by-name/super") return
25.764706
81
0.734018
import common import re def FullOTA_InstallEnd(info): OTA_InstallEnd(info) return def IncrementalOTA_InstallEnd(info): OTA_InstallEnd(info) return def AddImage(info, basename, dest): path = "IMAGES/" + basename if path not in info.input_zip.namelist(): return data = info.input_zip.read(path) common.ZipWriteStr(info.output_zip, basename, data) info.script.AppendExtra('package_extract_file("%s", "%s");' % (basename, dest)) def OTA_InstallEnd(info): info.script.Print("Patching firmware images...") AddImage(info, "dtbo.img", "/dev/block/bootdevice/by-name/dtbo") AddImage(info, "vbmeta.img", "/dev/block/bootdevice/by-name/vbmeta") return def FullOTA_InstallBegin(info): AddImage(info, "super_empty.img", "/dev/block/bootdevice/by-name/super") return
true
true
1c394c7520609260e85412e55eb6764cf76dc1ad
81,813
py
Python
dojo/product/views.py
SPoint42/django-DefectDojo
ce386a5c9ae7405366109bf8faea8dce1ca2d8e6
[ "BSD-3-Clause" ]
null
null
null
dojo/product/views.py
SPoint42/django-DefectDojo
ce386a5c9ae7405366109bf8faea8dce1ca2d8e6
[ "BSD-3-Clause" ]
275
2021-02-19T15:16:15.000Z
2022-03-31T21:09:29.000Z
dojo/product/views.py
SPoint42/django-DefectDojo
ce386a5c9ae7405366109bf8faea8dce1ca2d8e6
[ "BSD-3-Clause" ]
null
null
null
# # product import calendar as tcalendar import logging import base64 from collections import OrderedDict from datetime import datetime, date, timedelta from math import ceil from dateutil.relativedelta import relativedelta from django.contrib import messages from django.core.exceptions import PermissionDenied, ValidationError from django.urls import reverse from django.http import HttpResponseRedirect, Http404 from django.shortcuts import render, get_object_or_404 from django.utils import timezone from django.db.models import Sum, Count, Q, Max from django.contrib.admin.utils import NestedObjects from django.db import DEFAULT_DB_ALIAS, connection from dojo.templatetags.display_tags import get_level from dojo.filters import ProductEngagementFilter, ProductFilter, EngagementFilter, MetricsEndpointFilter, MetricsFindingFilter, ProductComponentFilter from dojo.forms import ProductForm, EngForm, DeleteProductForm, DojoMetaDataForm, JIRAProjectForm, JIRAFindingForm, AdHocFindingForm, \ EngagementPresetsForm, DeleteEngagementPresetsForm, ProductNotificationsForm, \ GITHUB_Product_Form, GITHUBFindingForm, AppAnalysisForm, JIRAEngagementForm, Add_Product_MemberForm, \ Edit_Product_MemberForm, Delete_Product_MemberForm, Add_Product_GroupForm, Edit_Product_Group_Form, Delete_Product_GroupForm, \ DeleteAppAnalysisForm, Product_API_Scan_ConfigurationForm, DeleteProduct_API_Scan_ConfigurationForm from dojo.models import Product_Type, Note_Type, Finding, Product, Engagement, Test, GITHUB_PKey, \ Test_Type, System_Settings, Languages, App_Analysis, Benchmark_Type, Benchmark_Product_Summary, Endpoint_Status, \ Endpoint, Engagement_Presets, DojoMeta, Notifications, BurpRawRequestResponse, Product_Member, \ Product_Group, Product_API_Scan_Configuration from dojo.utils import add_external_issue, add_error_message_to_response, add_field_errors_to_response, get_page_items, add_breadcrumb, \ get_system_setting, Product_Tab, get_punchcard_data, queryset_check, is_title_in_breadcrumbs from dojo.notifications.helper import create_notification from django.db.models import Prefetch, F, OuterRef, Subquery from django.db.models.query import QuerySet from github import Github from django.contrib.postgres.aggregates import StringAgg from dojo.components.sql_group_concat import Sql_GroupConcat import dojo.jira_link.helper as jira_helper from dojo.authorization.authorization import user_has_permission, user_has_permission_or_403 from django.conf import settings from dojo.authorization.roles_permissions import Permissions from dojo.authorization.authorization_decorators import user_is_authorized from dojo.product.queries import get_authorized_products, get_authorized_members_for_product, get_authorized_groups_for_product from dojo.product_type.queries import get_authorized_members_for_product_type, get_authorized_groups_for_product_type from dojo.tool_config.factory import create_API import dojo.finding.helper as finding_helper logger = logging.getLogger(__name__) def product(request): # validate prod_type param product_type = None if 'prod_type' in request.GET: p = request.GET.getlist('prod_type', []) if len(p) == 1: product_type = get_object_or_404(Product_Type, id=p[0]) prods = get_authorized_products(Permissions.Product_View) # perform all stuff for filtering and pagination first, before annotation/prefetching # otherwise the paginator will perform all the annotations/prefetching already only to count the total number of records # see https://code.djangoproject.com/ticket/23771 and https://code.djangoproject.com/ticket/25375 name_words = prods.values_list('name', flat=True) prod_filter = ProductFilter(request.GET, queryset=prods, user=request.user) prod_list = get_page_items(request, prod_filter.qs, 25) # perform annotation/prefetching by replacing the queryset in the page with an annotated/prefetched queryset. prod_list.object_list = prefetch_for_product(prod_list.object_list) # print(prod_list.object_list.explain) add_breadcrumb(title="Product List", top_level=not len(request.GET), request=request) return render(request, 'dojo/product.html', {'prod_list': prod_list, 'prod_filter': prod_filter, 'name_words': sorted(set(name_words)), 'user': request.user}) def prefetch_for_product(prods): prefetched_prods = prods if isinstance(prods, QuerySet): # old code can arrive here with prods being a list because the query was already executed prefetched_prods = prefetched_prods.prefetch_related('team_manager') prefetched_prods = prefetched_prods.prefetch_related('product_manager') prefetched_prods = prefetched_prods.prefetch_related('technical_contact') prefetched_prods = prefetched_prods.annotate( active_engagement_count=Count('engagement__id', filter=Q(engagement__active=True))) prefetched_prods = prefetched_prods.annotate( closed_engagement_count=Count('engagement__id', filter=Q(engagement__active=False))) prefetched_prods = prefetched_prods.annotate(last_engagement_date=Max('engagement__target_start')) prefetched_prods = prefetched_prods.annotate(active_finding_count=Count('engagement__test__finding__id', filter=Q( engagement__test__finding__active=True))) prefetched_prods = prefetched_prods.annotate(active_verified_finding_count=Count('engagement__test__finding__id', filter=Q( engagement__test__finding__active=True, engagement__test__finding__verified=True))) prefetched_prods = prefetched_prods.prefetch_related('jira_project_set__jira_instance') prefetched_prods = prefetched_prods.prefetch_related('authorized_users') prefetched_prods = prefetched_prods.prefetch_related('prod_type__authorized_users') prefetched_prods = prefetched_prods.prefetch_related('members') prefetched_prods = prefetched_prods.prefetch_related('prod_type__members') active_endpoint_query = Endpoint.objects.filter( finding__active=True, finding__mitigated__isnull=True).distinct() prefetched_prods = prefetched_prods.prefetch_related( Prefetch('endpoint_set', queryset=active_endpoint_query, to_attr='active_endpoints')) prefetched_prods = prefetched_prods.prefetch_related('tags') if get_system_setting('enable_github'): prefetched_prods = prefetched_prods.prefetch_related( Prefetch('github_pkey_set', queryset=GITHUB_PKey.objects.all().select_related('git_conf'), to_attr='github_confs')) else: logger.debug('unable to prefetch because query was already executed') return prefetched_prods def iso_to_gregorian(iso_year, iso_week, iso_day): jan4 = date(iso_year, 1, 4) start = jan4 - timedelta(days=jan4.isoweekday() - 1) return start + timedelta(weeks=iso_week - 1, days=iso_day - 1) @user_is_authorized(Product, Permissions.Product_View, 'pid') def view_product(request, pid): prod_query = Product.objects.all().select_related('product_manager', 'technical_contact', 'team_manager') \ .prefetch_related('authorized_users') \ .prefetch_related('members') \ .prefetch_related('prod_type__members') prod = get_object_or_404(prod_query, id=pid) product_members = get_authorized_members_for_product(prod, Permissions.Product_View) product_type_members = get_authorized_members_for_product_type(prod.prod_type, Permissions.Product_Type_View) product_groups = get_authorized_groups_for_product(prod, Permissions.Product_View) product_type_groups = get_authorized_groups_for_product_type(prod.prod_type, Permissions.Product_Type_View) personal_notifications_form = ProductNotificationsForm( instance=Notifications.objects.filter(user=request.user).filter(product=prod).first()) langSummary = Languages.objects.filter(product=prod).aggregate(Sum('files'), Sum('code'), Count('files')) languages = Languages.objects.filter(product=prod).order_by('-code') app_analysis = App_Analysis.objects.filter(product=prod).order_by('name') benchmark_type = Benchmark_Type.objects.filter(enabled=True).order_by('name') benchmarks = Benchmark_Product_Summary.objects.filter(product=prod, publish=True, benchmark_type__enabled=True).order_by('benchmark_type__name') benchAndPercent = [] for i in range(0, len(benchmarks)): benchAndPercent.append([benchmarks[i].benchmark_type, get_level(benchmarks[i])]) system_settings = System_Settings.objects.get() product_metadata = dict(prod.product_meta.order_by('name').values_list('name', 'value')) open_findings = Finding.objects.filter(test__engagement__product=prod, false_p=False, active=True, duplicate=False, out_of_scope=False).order_by('numerical_severity').values( 'severity').annotate(count=Count('severity')) critical = 0 high = 0 medium = 0 low = 0 info = 0 for v in open_findings: if v["severity"] == "Critical": critical = v["count"] elif v["severity"] == "High": high = v["count"] elif v["severity"] == "Medium": medium = v["count"] elif v["severity"] == "Low": low = v["count"] elif v["severity"] == "Info": info = v["count"] total = critical + high + medium + low + info product_tab = Product_Tab(pid, title="Product", tab="overview") return render(request, 'dojo/view_product_details.html', { 'prod': prod, 'product_tab': product_tab, 'product_metadata': product_metadata, 'critical': critical, 'high': high, 'medium': medium, 'low': low, 'info': info, 'total': total, 'user': request.user, 'languages': languages, 'langSummary': langSummary, 'app_analysis': app_analysis, 'system_settings': system_settings, 'benchmarks_percents': benchAndPercent, 'benchmarks': benchmarks, 'product_members': product_members, 'product_type_members': product_type_members, 'product_groups': product_groups, 'product_type_groups': product_type_groups, 'personal_notifications_form': personal_notifications_form}) @user_is_authorized(Product, Permissions.Component_View, 'pid') def view_product_components(request, pid): prod = get_object_or_404(Product, id=pid) product_tab = Product_Tab(pid, title="Product", tab="components") separator = ', ' # Get components ordered by component_name and concat component versions to the same row if connection.vendor == 'postgresql': component_query = Finding.objects.filter(test__engagement__product__id=pid).values("component_name").order_by( 'component_name').annotate( component_version=StringAgg('component_version', delimiter=separator, distinct=True)) else: component_query = Finding.objects.filter(test__engagement__product__id=pid).values("component_name") component_query = component_query.annotate( component_version=Sql_GroupConcat('component_version', separator=separator, distinct=True)) # Append finding counts component_query = component_query.annotate(total=Count('id')).order_by('component_name', 'component_version') component_query = component_query.annotate(active=Count('id', filter=Q(active=True))) component_query = component_query.annotate(duplicate=(Count('id', filter=Q(duplicate=True)))) # Default sort by total descending component_query = component_query.order_by('-total') comp_filter = ProductComponentFilter(request.GET, queryset=component_query) result = get_page_items(request, comp_filter.qs, 25) # Filter out None values for auto-complete component_words = component_query.exclude(component_name__isnull=True).values_list('component_name', flat=True) return render(request, 'dojo/product_components.html', { 'prod': prod, 'filter': comp_filter, 'product_tab': product_tab, 'result': result, 'component_words': sorted(set(component_words)) }) def identify_view(request): get_data = request.GET view = get_data.get('type', None) if view: # value of view is reflected in the template, make sure it's valid # although any XSS should be catch by django autoescape, we see people sometimes using '|safe'... if view in ['Endpoint', 'Finding']: return view raise ValueError('invalid view, view must be "Endpoint" or "Finding"') else: if get_data.get('finding__severity', None): return 'Endpoint' elif get_data.get('false_positive', None): return 'Endpoint' referer = request.META.get('HTTP_REFERER', None) if referer: if referer.find('type=Endpoint') > -1: return 'Endpoint' return 'Finding' def finding_querys(request, prod): filters = dict() findings_query = Finding.objects.filter(test__engagement__product=prod, severity__in=('Critical', 'High', 'Medium', 'Low', 'Info')) # prefetch only what's needed to avoid lots of repeated queries findings_query = findings_query.prefetch_related( # 'test__engagement', # 'test__engagement__risk_acceptance', # 'found_by', # 'test', # 'test__test_type', # 'risk_acceptance_set', 'reporter') findings = MetricsFindingFilter(request.GET, queryset=findings_query, pid=prod) findings_qs = queryset_check(findings) filters['form'] = findings.form # dead code: # if not findings_qs and not findings_query: # # logger.debug('all filtered') # findings = findings_query # findings_qs = queryset_check(findings) # messages.add_message(request, # messages.ERROR, # 'All objects have been filtered away. Displaying all objects', # extra_tags='alert-danger') try: # logger.debug(findings_qs.query) start_date = findings_qs.earliest('date').date start_date = datetime(start_date.year, start_date.month, start_date.day, tzinfo=timezone.get_current_timezone()) end_date = findings_qs.latest('date').date end_date = datetime(end_date.year, end_date.month, end_date.day, tzinfo=timezone.get_current_timezone()) except Exception as e: logger.debug(e) start_date = timezone.now() end_date = timezone.now() week = end_date - timedelta(days=7) # seven days and /newnewer are considered "new" # risk_acceptances = Risk_Acceptance.objects.filter(engagement__in=Engagement.objects.filter(product=prod)).prefetch_related('accepted_findings') # filters['accepted'] = [finding for ra in risk_acceptances for finding in ra.accepted_findings.all()] from dojo.finding.helper import ACCEPTED_FINDINGS_QUERY filters['accepted'] = findings_qs.filter(ACCEPTED_FINDINGS_QUERY).filter(date__range=[start_date, end_date]) filters['verified'] = findings_qs.filter(date__range=[start_date, end_date], false_p=False, active=True, verified=True, duplicate=False, out_of_scope=False).order_by("date") filters['new_verified'] = findings_qs.filter(date__range=[week, end_date], false_p=False, verified=True, active=True, duplicate=False, out_of_scope=False).order_by("date") filters['open'] = findings_qs.filter(date__range=[start_date, end_date], false_p=False, duplicate=False, out_of_scope=False, active=True, is_mitigated=False) filters['inactive'] = findings_qs.filter(date__range=[start_date, end_date], duplicate=False, out_of_scope=False, active=False, is_mitigated=False) filters['closed'] = findings_qs.filter(date__range=[start_date, end_date], false_p=False, duplicate=False, out_of_scope=False, active=False, is_mitigated=True) filters['false_positive'] = findings_qs.filter(date__range=[start_date, end_date], false_p=True, duplicate=False, out_of_scope=False) filters['out_of_scope'] = findings_qs.filter(date__range=[start_date, end_date], false_p=False, duplicate=False, out_of_scope=True) filters['all'] = findings_qs filters['open_vulns'] = findings_qs.filter( false_p=False, duplicate=False, out_of_scope=False, active=True, mitigated__isnull=True, cwe__isnull=False, ).order_by('cwe').values( 'cwe' ).annotate( count=Count('cwe') ) filters['all_vulns'] = findings_qs.filter( duplicate=False, cwe__isnull=False, ).order_by('cwe').values( 'cwe' ).annotate( count=Count('cwe') ) filters['start_date'] = start_date filters['end_date'] = end_date filters['week'] = week return filters def endpoint_querys(request, prod): filters = dict() endpoints_query = Endpoint_Status.objects.filter(finding__test__engagement__product=prod, finding__severity__in=( 'Critical', 'High', 'Medium', 'Low', 'Info')).prefetch_related( 'finding__test__engagement', 'finding__test__engagement__risk_acceptance', 'finding__risk_acceptance_set', 'finding__reporter').annotate(severity=F('finding__severity')) endpoints = MetricsEndpointFilter(request.GET, queryset=endpoints_query) endpoints_qs = queryset_check(endpoints) filters['form'] = endpoints.form if not endpoints_qs and not endpoints_query: endpoints = endpoints_query endpoints_qs = queryset_check(endpoints) messages.add_message(request, messages.ERROR, 'All objects have been filtered away. Displaying all objects', extra_tags='alert-danger') try: start_date = endpoints_qs.earliest('date').date start_date = datetime(start_date.year, start_date.month, start_date.day, tzinfo=timezone.get_current_timezone()) end_date = endpoints_qs.latest('date').date end_date = datetime(end_date.year, end_date.month, end_date.day, tzinfo=timezone.get_current_timezone()) except: start_date = timezone.now() end_date = timezone.now() week = end_date - timedelta(days=7) # seven days and /newnewer are considered "new" filters['accepted'] = endpoints_qs.filter(date__range=[start_date, end_date], risk_accepted=True).order_by("date") filters['verified'] = endpoints_qs.filter(date__range=[start_date, end_date], false_positive=False, mitigated=True, out_of_scope=False).order_by("date") filters['new_verified'] = endpoints_qs.filter(date__range=[week, end_date], false_positive=False, mitigated=True, out_of_scope=False).order_by("date") filters['open'] = endpoints_qs.filter(date__range=[start_date, end_date], mitigated=False) filters['inactive'] = endpoints_qs.filter(date__range=[start_date, end_date], mitigated=True) filters['closed'] = endpoints_qs.filter(date__range=[start_date, end_date], mitigated=True) filters['false_positive'] = endpoints_qs.filter(date__range=[start_date, end_date], false_positive=True) filters['out_of_scope'] = endpoints_qs.filter(date__range=[start_date, end_date], out_of_scope=True) filters['all'] = endpoints_qs filters['open_vulns'] = endpoints_qs.filter( false_positive=False, out_of_scope=False, mitigated=True, finding__cwe__isnull=False, ).order_by('finding__cwe').values( 'finding__cwe' ).annotate( count=Count('finding__cwe') ) filters['all_vulns'] = endpoints_qs.filter( finding__cwe__isnull=False, ).order_by('finding__cwe').values( 'finding__cwe' ).annotate( count=Count('finding__cwe') ) filters['start_date'] = start_date filters['end_date'] = end_date filters['week'] = week return filters @user_is_authorized(Product, Permissions.Product_View, 'pid') def view_product_metrics(request, pid): prod = get_object_or_404(Product, id=pid) engs = Engagement.objects.filter(product=prod, active=True) view = identify_view(request) result = EngagementFilter( request.GET, queryset=Engagement.objects.filter(product=prod, active=False).order_by('-target_end')) inactive_engs_page = get_page_items(request, result.qs, 10) filters = dict() if view == 'Finding': filters = finding_querys(request, prod) elif view == 'Endpoint': filters = endpoint_querys(request, prod) start_date = filters['start_date'] end_date = filters['end_date'] week_date = filters['week'] tests = Test.objects.filter(engagement__product=prod).prefetch_related('finding_set', 'test_type') tests = tests.annotate(verified_finding_count=Count('finding__id', filter=Q(finding__verified=True))) open_vulnerabilities = filters['open_vulns'] all_vulnerabilities = filters['all_vulns'] start_date = timezone.make_aware(datetime.combine(start_date, datetime.min.time())) r = relativedelta(end_date, start_date) weeks_between = int(ceil((((r.years * 12) + r.months) * 4.33) + (r.days / 7))) if weeks_between <= 0: weeks_between += 2 punchcard, ticks = get_punchcard_data(filters.get('open', None), start_date, weeks_between, view) add_breadcrumb(parent=prod, top_level=False, request=request) open_close_weekly = OrderedDict() new_weekly = OrderedDict() severity_weekly = OrderedDict() critical_weekly = OrderedDict() high_weekly = OrderedDict() medium_weekly = OrderedDict() for v in filters.get('open', None): iso_cal = v.date.isocalendar() x = iso_to_gregorian(iso_cal[0], iso_cal[1], 1) y = x.strftime("<span class='small'>%m/%d<br/>%Y</span>") x = (tcalendar.timegm(x.timetuple()) * 1000) if x not in critical_weekly: critical_weekly[x] = {'count': 0, 'week': y} if x not in high_weekly: high_weekly[x] = {'count': 0, 'week': y} if x not in medium_weekly: medium_weekly[x] = {'count': 0, 'week': y} if x in open_close_weekly: if v.mitigated: open_close_weekly[x]['closed'] += 1 else: open_close_weekly[x]['open'] += 1 else: if v.mitigated: open_close_weekly[x] = {'closed': 1, 'open': 0, 'accepted': 0} else: open_close_weekly[x] = {'closed': 0, 'open': 1, 'accepted': 0} open_close_weekly[x]['week'] = y if view == 'Finding': severity = v.severity elif view == 'Endpoint': severity = v.finding.severity if x in severity_weekly: if severity in severity_weekly[x]: severity_weekly[x][severity] += 1 else: severity_weekly[x][severity] = 1 else: severity_weekly[x] = {'Critical': 0, 'High': 0, 'Medium': 0, 'Low': 0, 'Info': 0} severity_weekly[x][severity] = 1 severity_weekly[x]['week'] = y if severity == 'Critical': if x in critical_weekly: critical_weekly[x]['count'] += 1 else: critical_weekly[x] = {'count': 1, 'week': y} elif severity == 'High': if x in high_weekly: high_weekly[x]['count'] += 1 else: high_weekly[x] = {'count': 1, 'week': y} elif severity == 'Medium': if x in medium_weekly: medium_weekly[x]['count'] += 1 else: medium_weekly[x] = {'count': 1, 'week': y} for a in filters.get('accepted', None): if view == 'Finding': finding = a elif view == 'Endpoint': finding = v.finding iso_cal = a.date.isocalendar() x = iso_to_gregorian(iso_cal[0], iso_cal[1], 1) y = x.strftime("<span class='small'>%m/%d<br/>%Y</span>") x = (tcalendar.timegm(x.timetuple()) * 1000) if x in open_close_weekly: open_close_weekly[x]['accepted'] += 1 else: open_close_weekly[x] = {'closed': 0, 'open': 0, 'accepted': 1} open_close_weekly[x]['week'] = y test_data = {} for t in tests: if t.test_type.name in test_data: test_data[t.test_type.name] += t.verified_finding_count else: test_data[t.test_type.name] = t.verified_finding_count product_tab = Product_Tab(pid, title="Product", tab="metrics") return render(request, 'dojo/product_metrics.html', {'prod': prod, 'product_tab': product_tab, 'engs': engs, 'inactive_engs': inactive_engs_page, 'view': view, 'verified_objs': filters.get('verified', None), 'open_objs': filters.get('open', None), 'inactive_objs': filters.get('inactive', None), 'closed_objs': filters.get('closed', None), 'false_positive_objs': filters.get('false_positive', None), 'out_of_scope_objs': filters.get('out_of_scope', None), 'accepted_objs': filters.get('accepted', None), 'new_objs': filters.get('new_verified', None), 'all_objs': filters.get('all', None), 'form': filters.get('form', None), 'reset_link': reverse('view_product_metrics', args=(prod.id,)) + '?type=' + view, 'open_vulnerabilities': open_vulnerabilities, 'all_vulnerabilities': all_vulnerabilities, 'start_date': start_date, 'punchcard': punchcard, 'ticks': ticks, 'open_close_weekly': open_close_weekly, 'severity_weekly': severity_weekly, 'critical_weekly': critical_weekly, 'high_weekly': high_weekly, 'medium_weekly': medium_weekly, 'test_data': test_data, 'user': request.user}) @user_is_authorized(Product, Permissions.Engagement_View, 'pid') def view_engagements(request, pid): prod = get_object_or_404(Product, id=pid) default_page_num = 10 recent_test_day_count = 7 # In Progress Engagements engs = Engagement.objects.filter(product=prod, active=True, status="In Progress").order_by('-updated') active_engs_filter = ProductEngagementFilter(request.GET, queryset=engs, prefix='active') result_active_engs = get_page_items(request, active_engs_filter.qs, default_page_num, prefix="engs") # prefetch only after creating the filters to avoid https://code.djangoproject.com/ticket/23771 and https://code.djangoproject.com/ticket/25375 result_active_engs.object_list = prefetch_for_view_engagements(result_active_engs.object_list, recent_test_day_count) # Engagements that are queued because they haven't started or paused engs = Engagement.objects.filter(~Q(status="In Progress"), product=prod, active=True).order_by('-updated') queued_engs_filter = ProductEngagementFilter(request.GET, queryset=engs, prefix='queued') result_queued_engs = get_page_items(request, queued_engs_filter.qs, default_page_num, prefix="queued_engs") result_queued_engs.object_list = prefetch_for_view_engagements(result_queued_engs.object_list, recent_test_day_count) # Cancelled or Completed Engagements engs = Engagement.objects.filter(product=prod, active=False).order_by('-target_end') inactive_engs_filter = ProductEngagementFilter(request.GET, queryset=engs, prefix='closed') result_inactive_engs = get_page_items(request, inactive_engs_filter.qs, default_page_num, prefix="inactive_engs") result_inactive_engs.object_list = prefetch_for_view_engagements(result_inactive_engs.object_list, recent_test_day_count) title = "All Engagements" product_tab = Product_Tab(pid, title=title, tab="engagements") return render(request, 'dojo/view_engagements.html', {'prod': prod, 'product_tab': product_tab, 'engs': result_active_engs, 'engs_count': result_active_engs.paginator.count, 'engs_filter': active_engs_filter, 'queued_engs': result_queued_engs, 'queued_engs_count': result_queued_engs.paginator.count, 'queued_engs_filter': queued_engs_filter, 'inactive_engs': result_inactive_engs, 'inactive_engs_count': result_inactive_engs.paginator.count, 'inactive_engs_filter': inactive_engs_filter, 'recent_test_day_count': recent_test_day_count, 'user': request.user}) def prefetch_for_view_engagements(engagements, recent_test_day_count): engagements = engagements.select_related( 'lead' ).prefetch_related( Prefetch('test_set', queryset=Test.objects.filter( id__in=Subquery( Test.objects.filter( engagement_id=OuterRef('engagement_id'), updated__gte=timezone.now() - timedelta(days=recent_test_day_count) ).values_list('id', flat=True) )) ), 'test_set__test_type', ).annotate( count_tests=Count('test', distinct=True), count_findings_all=Count('test__finding__id'), count_findings_open=Count('test__finding__id', filter=Q(test__finding__active=True)), count_findings_open_verified=Count('test__finding__id', filter=Q(test__finding__active=True) & Q(test__finding__verified=True)), count_findings_close=Count('test__finding__id', filter=Q(test__finding__is_mitigated=True)), count_findings_duplicate=Count('test__finding__id', filter=Q(test__finding__duplicate=True)), count_findings_accepted=Count('test__finding__id', filter=Q(test__finding__risk_accepted=True)), ) if System_Settings.objects.get().enable_jira: engagements = engagements.prefetch_related( 'jira_project__jira_instance', 'product__jira_project_set__jira_instance', ) return engagements # Authorization is within the import_scan_results method def import_scan_results_prod(request, pid=None): from dojo.engagement.views import import_scan_results return import_scan_results(request, pid=pid) def new_product(request, ptid=None): jira_project_form = None error = False initial = None if ptid is not None: prod_type = get_object_or_404(Product_Type, pk=ptid) initial = {'prod_type': prod_type} form = ProductForm(initial=initial) if request.method == 'POST': form = ProductForm(request.POST, instance=Product()) if get_system_setting('enable_github'): gform = GITHUB_Product_Form(request.POST, instance=GITHUB_PKey()) else: gform = None if form.is_valid(): if settings.FEATURE_AUTHORIZATION_V2: product_type = form.instance.prod_type user_has_permission_or_403(request.user, product_type, Permissions.Product_Type_Add_Product) else: if not request.user.is_staff: raise PermissionDenied product = form.save() messages.add_message(request, messages.SUCCESS, 'Product added successfully.', extra_tags='alert-success') success, jira_project_form = jira_helper.process_jira_project_form(request, product=product) error = not success if get_system_setting('enable_github'): if gform.is_valid(): github_pkey = gform.save(commit=False) if github_pkey.git_conf is not None and github_pkey.git_project: github_pkey.product = product github_pkey.save() messages.add_message(request, messages.SUCCESS, 'GitHub information added successfully.', extra_tags='alert-success') # Create appropriate labels in the repo logger.info('Create label in repo: ' + github_pkey.git_project) try: g = Github(github_pkey.git_conf.api_key) repo = g.get_repo(github_pkey.git_project) repo.create_label(name="security", color="FF0000", description="This label is automatically applied to all issues created by DefectDojo") repo.create_label(name="security / info", color="00FEFC", description="This label is automatically applied to all issues created by DefectDojo") repo.create_label(name="security / low", color="B7FE00", description="This label is automatically applied to all issues created by DefectDojo") repo.create_label(name="security / medium", color="FEFE00", description="This label is automatically applied to all issues created by DefectDojo") repo.create_label(name="security / high", color="FE9A00", description="This label is automatically applied to all issues created by DefectDojo") repo.create_label(name="security / critical", color="FE2200", description="This label is automatically applied to all issues created by DefectDojo") except: logger.info('Labels cannot be created - they may already exists') create_notification(event='product_added', title=product.name, product=product, url=reverse('view_product', args=(product.id,))) if not error: return HttpResponseRedirect(reverse('view_product', args=(product.id,))) else: # engagement was saved, but JIRA errors, so goto edit_product return HttpResponseRedirect(reverse('edit_product', args=(product.id,))) else: if get_system_setting('enable_jira'): jira_project_form = JIRAProjectForm() if get_system_setting('enable_github'): gform = GITHUB_Product_Form() else: gform = None add_breadcrumb(title="New Product", top_level=False, request=request) return render(request, 'dojo/new_product.html', {'form': form, 'jform': jira_project_form, 'gform': gform}) @user_is_authorized(Product, Permissions.Product_Edit, 'pid') def edit_product(request, pid): product = Product.objects.get(pk=pid) system_settings = System_Settings.objects.get() jira_enabled = system_settings.enable_jira jira_project = None jform = None github_enabled = system_settings.enable_github github_inst = None gform = None error = False try: github_inst = GITHUB_PKey.objects.get(product=product) except: github_inst = None pass if request.method == 'POST': form = ProductForm(request.POST, instance=product) jira_project = jira_helper.get_jira_project(product) if form.is_valid(): form.save() tags = request.POST.getlist('tags') messages.add_message(request, messages.SUCCESS, 'Product updated successfully.', extra_tags='alert-success') success, jform = jira_helper.process_jira_project_form(request, instance=jira_project, product=product) error = not success if get_system_setting('enable_github') and github_inst: gform = GITHUB_Product_Form(request.POST, instance=github_inst) # need to handle delete try: gform.save() except: pass elif get_system_setting('enable_github'): gform = GITHUB_Product_Form(request.POST) if gform.is_valid(): new_conf = gform.save(commit=False) new_conf.product_id = pid new_conf.save() messages.add_message(request, messages.SUCCESS, 'GITHUB information updated successfully.', extra_tags='alert-success') if not error: return HttpResponseRedirect(reverse('view_product', args=(pid,))) else: form = ProductForm(instance=product, initial={'auth_users': product.authorized_users.all()}) if jira_enabled: jira_project = jira_helper.get_jira_project(product) jform = JIRAProjectForm(instance=jira_project) else: jform = None if github_enabled and (github_inst is not None): if github_inst is not None: gform = GITHUB_Product_Form(instance=github_inst) gform = GITHUB_Product_Form() gform = GITHUB_Product_Form() else: gform = None product_tab = Product_Tab(pid, title="Edit Product", tab="settings") return render(request, 'dojo/edit_product.html', {'form': form, 'product_tab': product_tab, 'jform': jform, 'gform': gform, 'product': product }) @user_is_authorized(Product, Permissions.Product_Delete, 'pid') def delete_product(request, pid): product = get_object_or_404(Product, pk=pid) form = DeleteProductForm(instance=product) if request.method == 'POST': logger.debug('delete_product: POST') if 'id' in request.POST and str(product.id) == request.POST['id']: form = DeleteProductForm(request.POST, instance=product) if form.is_valid(): product_type = product.prod_type product.delete() messages.add_message(request, messages.SUCCESS, 'Product and relationships removed.', extra_tags='alert-success') create_notification(event='other', title='Deletion of %s' % product.name, product_type=product_type, description='The product "%s" was deleted by %s' % (product.name, request.user), url=request.build_absolute_uri(reverse('product')), icon="exclamation-triangle") logger.debug('delete_product: POST RETURN') return HttpResponseRedirect(reverse('product')) else: logger.debug('delete_product: POST INVALID FORM') logger.error(form.errors) logger.debug('delete_product: GET') collector = NestedObjects(using=DEFAULT_DB_ALIAS) collector.collect([product]) rels = collector.nested() product_tab = Product_Tab(pid, title="Product", tab="settings") logger.debug('delete_product: GET RENDER') return render(request, 'dojo/delete_product.html', {'product': product, 'form': form, 'product_tab': product_tab, 'rels': rels, }) @user_is_authorized(Product, Permissions.Engagement_Add, 'pid') def new_eng_for_app(request, pid, cicd=False): jira_project = None jira_project_form = None jira_epic_form = None product = Product.objects.get(id=pid) jira_error = False if request.method == 'POST': form = EngForm(request.POST, cicd=cicd, product=product, user=request.user) jira_project = jira_helper.get_jira_project(product) logger.debug('new_eng_for_app') if form.is_valid(): # first create the new engagement engagement = form.save(commit=False) engagement.threat_model = False engagement.api_test = False engagement.pen_test = False engagement.check_list = False engagement.product = form.cleaned_data.get('product') if engagement.threat_model: engagement.progress = 'threat_model' else: engagement.progress = 'other' if cicd: engagement.engagement_type = 'CI/CD' engagement.status = "In Progress" engagement.active = True engagement.save() form.save_m2m() logger.debug('new_eng_for_app: process jira coming') # new engagement, so do not provide jira_project success, jira_project_form = jira_helper.process_jira_project_form(request, instance=None, engagement=engagement) error = not success logger.debug('new_eng_for_app: process jira epic coming') success, jira_epic_form = jira_helper.process_jira_epic_form(request, engagement=engagement) error = error or not success create_notification(event='engagement_added', title=engagement.name + " for " + product.name, engagement=engagement, url=reverse('view_engagement', args=(engagement.id,)), objowner=engagement.lead) messages.add_message(request, messages.SUCCESS, 'Engagement added successfully.', extra_tags='alert-success') if not error: if "_Add Tests" in request.POST: return HttpResponseRedirect(reverse('add_tests', args=(engagement.id,))) elif "_Import Scan Results" in request.POST: return HttpResponseRedirect(reverse('import_scan_results', args=(engagement.id,))) else: return HttpResponseRedirect(reverse('view_engagement', args=(engagement.id,))) else: # engagement was saved, but JIRA errors, so goto edit_engagement logger.debug('new_eng_for_app: jira errors') return HttpResponseRedirect(reverse('edit_engagement', args=(engagement.id,))) else: logger.debug(form.errors) else: form = EngForm(initial={'lead': request.user, 'target_start': timezone.now().date(), 'target_end': timezone.now().date() + timedelta(days=7), 'product': product}, cicd=cicd, product=product, user=request.user) if get_system_setting('enable_jira'): jira_project = jira_helper.get_jira_project(product) logger.debug('showing jira-project-form') jira_project_form = JIRAProjectForm(target='engagement', product=product) logger.debug('showing jira-epic-form') jira_epic_form = JIRAEngagementForm() if cicd: title = 'New CI/CD Engagement' else: title = 'New Interactive Engagement' product_tab = Product_Tab(pid, title=title, tab="engagements") return render(request, 'dojo/new_eng.html', {'form': form, 'title': title, 'product_tab': product_tab, 'jira_epic_form': jira_epic_form, 'jira_project_form': jira_project_form, }) @user_is_authorized(Product, Permissions.Technology_Add, 'pid') def new_tech_for_prod(request, pid): if request.method == 'POST': form = AppAnalysisForm(request.POST) if form.is_valid(): tech = form.save(commit=False) tech.product_id = pid tech.save() messages.add_message(request, messages.SUCCESS, 'Technology added successfully.', extra_tags='alert-success') return HttpResponseRedirect(reverse('view_product', args=(pid,))) form = AppAnalysisForm(initial={'user': request.user}) product_tab = Product_Tab(pid, title="Add Technology", tab="settings") return render(request, 'dojo/new_tech.html', {'form': form, 'product_tab': product_tab, 'pid': pid}) @user_is_authorized(App_Analysis, Permissions.Technology_Edit, 'tid') def edit_technology(request, tid): technology = get_object_or_404(App_Analysis, id=tid) form = AppAnalysisForm(instance=technology) if request.method == 'POST': form = AppAnalysisForm(request.POST) if form.is_valid(): tech = form.save(commit=False) tech.id = technology.id tech.product_id = technology.product.id tech.save() messages.add_message(request, messages.SUCCESS, 'Technology changed successfully.', extra_tags='alert-success') return HttpResponseRedirect(reverse('view_product', args=(technology.product.id,))) product_tab = Product_Tab(technology.product.id, title="Edit Technology", tab="settings") return render(request, 'dojo/edit_technology.html', {'form': form, 'product_tab': product_tab, 'technology': technology}) @user_is_authorized(App_Analysis, Permissions.Technology_Delete, 'tid') def delete_technology(request, tid): technology = get_object_or_404(App_Analysis, id=tid) form = DeleteAppAnalysisForm(instance=technology) if request.method == 'POST': form = Delete_Product_MemberForm(request.POST, instance=technology) technology = form.instance technology.delete() messages.add_message(request, messages.SUCCESS, 'Technology deleted successfully.', extra_tags='alert-success') return HttpResponseRedirect(reverse('view_product', args=(technology.product.id,))) product_tab = Product_Tab(technology.product.id, title="Delete Technology", tab="settings") return render(request, 'dojo/delete_technology.html', { 'technology': technology, 'form': form, 'product_tab': product_tab, }) @user_is_authorized(Product, Permissions.Engagement_Add, 'pid') def new_eng_for_app_cicd(request, pid): # we have to use pid=pid here as new_eng_for_app expects kwargs, because that is how django calls the function based on urls.py named groups return new_eng_for_app(request, pid=pid, cicd=True) @user_is_authorized(Product, Permissions.Product_Edit, 'pid') def add_meta_data(request, pid): prod = Product.objects.get(id=pid) if request.method == 'POST': form = DojoMetaDataForm(request.POST, instance=DojoMeta(product=prod)) if form.is_valid(): form.save() messages.add_message(request, messages.SUCCESS, 'Metadata added successfully.', extra_tags='alert-success') if 'add_another' in request.POST: return HttpResponseRedirect(reverse('add_meta_data', args=(pid,))) else: return HttpResponseRedirect(reverse('view_product', args=(pid,))) else: form = DojoMetaDataForm() product_tab = Product_Tab(pid, title="Add Metadata", tab="settings") return render(request, 'dojo/add_product_meta_data.html', {'form': form, 'product_tab': product_tab, 'product': prod, }) @user_is_authorized(Product, Permissions.Product_Edit, 'pid') def edit_meta_data(request, pid): prod = Product.objects.get(id=pid) if request.method == 'POST': for key, value in request.POST.items(): if key.startswith('cfv_'): cfv_id = int(key.split('_')[1]) cfv = get_object_or_404(DojoMeta, id=cfv_id) value = value.strip() if value: cfv.value = value cfv.save() if key.startswith('delete_'): cfv_id = int(key.split('_')[2]) cfv = get_object_or_404(DojoMeta, id=cfv_id) cfv.delete() messages.add_message(request, messages.SUCCESS, 'Metadata edited successfully.', extra_tags='alert-success') return HttpResponseRedirect(reverse('view_product', args=(pid,))) product_tab = Product_Tab(pid, title="Edit Metadata", tab="settings") return render(request, 'dojo/edit_product_meta_data.html', {'product': prod, 'product_tab': product_tab, }) @user_is_authorized(Product, Permissions.Finding_Add, 'pid') def ad_hoc_finding(request, pid): prod = Product.objects.get(id=pid) test_type, _ = Test_Type.objects.get_or_create(name="Pen Test") test = None try: eng = Engagement.objects.get(product=prod, name="Ad Hoc Engagement") tests = Test.objects.filter(engagement=eng) if len(tests) != 0: test = tests[0] else: test = Test(engagement=eng, test_type=test_type, target_start=timezone.now(), target_end=timezone.now()) test.save() except: eng = Engagement(name="Ad Hoc Engagement", target_start=timezone.now(), target_end=timezone.now(), active=False, product=prod) eng.save() test = Test(engagement=eng, test_type=test_type, target_start=timezone.now(), target_end=timezone.now()) test.save() form_error = False push_all_jira_issues = jira_helper.is_push_all_issues(test) jform = None gform = None form = AdHocFindingForm(initial={'date': timezone.now().date()}, req_resp=None, product=prod) use_jira = jira_helper.get_jira_project(test) is not None if request.method == 'POST': form = AdHocFindingForm(request.POST, req_resp=None, product=prod) if (form['active'].value() is False or form['false_p'].value()) and form['duplicate'].value() is False: closing_disabled = Note_Type.objects.filter(is_mandatory=True, is_active=True).count() if closing_disabled != 0: error_inactive = ValidationError('Can not set a finding as inactive without adding all mandatory notes', code='inactive_without_mandatory_notes') error_false_p = ValidationError( 'Can not set a finding as false positive without adding all mandatory notes', code='false_p_without_mandatory_notes') if form['active'].value() is False: form.add_error('active', error_inactive) if form['false_p'].value(): form.add_error('false_p', error_false_p) messages.add_message(request, messages.ERROR, 'Can not set a finding as inactive or false positive without adding all mandatory notes', extra_tags='alert-danger') if use_jira: jform = JIRAFindingForm(request.POST, prefix='jiraform', push_all=push_all_jira_issues, jira_project=jira_helper.get_jira_project(test), finding_form=form) if form.is_valid() and (jform is None or jform.is_valid()): new_finding = form.save(commit=False) new_finding.test = test new_finding.reporter = request.user new_finding.numerical_severity = Finding.get_numerical_severity( new_finding.severity) new_finding.tags = form.cleaned_data['tags'] new_finding.save() # Save and add new endpoints finding_helper.add_endpoints(new_finding, form) new_finding.save() # Push to jira? push_to_jira = False jira_message = None if jform and jform.is_valid(): # Push to Jira? logger.debug('jira form valid') push_to_jira = push_all_jira_issues or jform.cleaned_data.get('push_to_jira') # if the jira issue key was changed, update database new_jira_issue_key = jform.cleaned_data.get('jira_issue') if new_finding.has_jira_issue: jira_issue = new_finding.jira_issue # everything in DD around JIRA integration is based on the internal id of the issue in JIRA # instead of on the public jira issue key. # I have no idea why, but it means we have to retrieve the issue from JIRA to get the internal JIRA id. # we can assume the issue exist, which is already checked in the validation of the jform if not new_jira_issue_key: jira_helper.finding_unlink_jira(request, new_finding) jira_message = 'Link to JIRA issue removed successfully.' elif new_jira_issue_key != new_finding.jira_issue.jira_key: jira_helper.finding_unlink_jira(request, new_finding) jira_helper.finding_link_jira(request, new_finding, new_jira_issue_key) jira_message = 'Changed JIRA link successfully.' else: logger.debug('finding has no jira issue yet') if new_jira_issue_key: logger.debug( 'finding has no jira issue yet, but jira issue specified in request. trying to link.') jira_helper.finding_link_jira(request, new_finding, new_jira_issue_key) jira_message = 'Linked a JIRA issue successfully.' if 'githubform-push_to_github' in request.POST: gform = GITHUBFindingForm(request.POST, prefix='jiragithub', enabled=push_all_jira_issues) if gform.is_valid(): add_external_issue(new_finding, 'github') new_finding.save(push_to_jira=push_to_jira) if 'request' in form.cleaned_data or 'response' in form.cleaned_data: burp_rr = BurpRawRequestResponse( finding=new_finding, burpRequestBase64=base64.b64encode(form.cleaned_data['request'].encode()), burpResponseBase64=base64.b64encode(form.cleaned_data['response'].encode()), ) burp_rr.clean() burp_rr.save() messages.add_message(request, messages.SUCCESS, 'Finding added successfully.', extra_tags='alert-success') if '_Finished' in request.POST: return HttpResponseRedirect(reverse('view_test', args=(test.id,))) else: return HttpResponseRedirect(reverse('add_findings', args=(test.id,))) else: form_error = True add_error_message_to_response('The form has errors, please correct them below.') add_field_errors_to_response(jform) add_field_errors_to_response(form) else: if use_jira: jform = JIRAFindingForm(push_all=jira_helper.is_push_all_issues(test), prefix='jiraform', jira_project=jira_helper.get_jira_project(test), finding_form=form) if get_system_setting('enable_github'): if GITHUB_PKey.objects.filter(product=test.engagement.product).count() != 0: gform = GITHUBFindingForm(enabled=push_all_jira_issues, prefix='githubform') else: gform = None product_tab = Product_Tab(pid, title="Add Finding", tab="engagements") product_tab.setEngagement(eng) return render(request, 'dojo/ad_hoc_findings.html', {'form': form, 'product_tab': product_tab, 'temp': False, 'tid': test.id, 'pid': pid, 'form_error': form_error, 'jform': jform, 'gform': gform, }) @user_is_authorized(Product, Permissions.Product_View, 'pid') def engagement_presets(request, pid): prod = get_object_or_404(Product, id=pid) presets = Engagement_Presets.objects.filter(product=prod).all() product_tab = Product_Tab(prod.id, title="Engagement Presets", tab="settings") return render(request, 'dojo/view_presets.html', {'product_tab': product_tab, 'presets': presets, 'prod': prod}) @user_is_authorized(Product, Permissions.Product_Edit, 'pid') def edit_engagement_presets(request, pid, eid): prod = get_object_or_404(Product, id=pid) preset = get_object_or_404(Engagement_Presets, id=eid) product_tab = Product_Tab(prod.id, title="Edit Engagement Preset", tab="settings") if request.method == 'POST': tform = EngagementPresetsForm(request.POST, instance=preset) if tform.is_valid(): tform.save() messages.add_message( request, messages.SUCCESS, 'Engagement Preset Successfully Updated.', extra_tags='alert-success') return HttpResponseRedirect(reverse('engagement_presets', args=(pid,))) else: tform = EngagementPresetsForm(instance=preset) return render(request, 'dojo/edit_presets.html', {'product_tab': product_tab, 'tform': tform, 'prod': prod}) @user_is_authorized(Product, Permissions.Product_Edit, 'pid') def add_engagement_presets(request, pid): prod = get_object_or_404(Product, id=pid) if request.method == 'POST': tform = EngagementPresetsForm(request.POST) if tform.is_valid(): form_copy = tform.save(commit=False) form_copy.product = prod form_copy.save() tform.save_m2m() messages.add_message( request, messages.SUCCESS, 'Engagement Preset Successfully Created.', extra_tags='alert-success') return HttpResponseRedirect(reverse('engagement_presets', args=(pid,))) else: tform = EngagementPresetsForm() product_tab = Product_Tab(pid, title="New Engagement Preset", tab="settings") return render(request, 'dojo/new_params.html', {'tform': tform, 'pid': pid, 'product_tab': product_tab}) @user_is_authorized(Product, Permissions.Product_Edit, 'pid') def delete_engagement_presets(request, pid, eid): prod = get_object_or_404(Product, id=pid) preset = get_object_or_404(Engagement_Presets, id=eid) form = DeleteEngagementPresetsForm(instance=preset) if request.method == 'POST': if 'id' in request.POST: form = DeleteEngagementPresetsForm(request.POST, instance=preset) if form.is_valid(): preset.delete() messages.add_message(request, messages.SUCCESS, 'Engagement presets and engagement relationships removed.', extra_tags='alert-success') return HttpResponseRedirect(reverse('engagement_presets', args=(pid,))) collector = NestedObjects(using=DEFAULT_DB_ALIAS) collector.collect([preset]) rels = collector.nested() product_tab = Product_Tab(pid, title="Delete Engagement Preset", tab="settings") return render(request, 'dojo/delete_presets.html', {'product': product, 'form': form, 'product_tab': product_tab, 'rels': rels, }) @user_is_authorized(Product, Permissions.Product_View, 'pid') def edit_notifications(request, pid): prod = get_object_or_404(Product, id=pid) if request.method == 'POST': product_notifications = Notifications.objects.filter(user=request.user).filter(product=prod).first() if not product_notifications: product_notifications = Notifications(user=request.user, product=prod) logger.debug('no existing product notifications found') else: logger.debug('existing product notifications found') form = ProductNotificationsForm(request.POST, instance=product_notifications) # print(vars(form)) if form.is_valid(): form.save() messages.add_message(request, messages.SUCCESS, 'Notification settings updated.', extra_tags='alert-success') return HttpResponseRedirect(reverse('view_product', args=(pid,))) @user_is_authorized(Product, Permissions.Product_Manage_Members, 'pid') def add_product_member(request, pid): product = get_object_or_404(Product, pk=pid) memberform = Add_Product_MemberForm(initial={'product': product.id}) if request.method == 'POST': memberform = Add_Product_MemberForm(request.POST, initial={'product': product.id}) if memberform.is_valid(): if memberform.cleaned_data['role'].is_owner and not user_has_permission(request.user, product, Permissions.Product_Member_Add_Owner): messages.add_message(request, messages.WARNING, 'You are not permitted to add users as owners.', extra_tags='alert-warning') else: if 'users' in memberform.cleaned_data and len(memberform.cleaned_data['users']) > 0: for user in memberform.cleaned_data['users']: existing_members = Product_Member.objects.filter(product=product, user=user) if existing_members.count() == 0: product_member = Product_Member() product_member.product = product product_member.user = user product_member.role = memberform.cleaned_data['role'] product_member.save() messages.add_message(request, messages.SUCCESS, 'Product members added successfully.', extra_tags='alert-success') return HttpResponseRedirect(reverse('view_product', args=(pid, ))) product_tab = Product_Tab(pid, title="Add Product Member", tab="settings") return render(request, 'dojo/new_product_member.html', { 'product': product, 'form': memberform, 'product_tab': product_tab, }) @user_is_authorized(Product_Member, Permissions.Product_Manage_Members, 'memberid') def edit_product_member(request, memberid): member = get_object_or_404(Product_Member, pk=memberid) memberform = Edit_Product_MemberForm(instance=member) if request.method == 'POST': memberform = Edit_Product_MemberForm(request.POST, instance=member) if memberform.is_valid(): if member.role.is_owner and not user_has_permission(request.user, member.product, Permissions.Product_Member_Add_Owner): messages.add_message(request, messages.WARNING, 'You are not permitted to make users to owners.', extra_tags='alert-warning') else: memberform.save() messages.add_message(request, messages.SUCCESS, 'Product member updated successfully.', extra_tags='alert-success') if is_title_in_breadcrumbs('View User'): return HttpResponseRedirect(reverse('view_user', args=(member.user.id, ))) else: return HttpResponseRedirect(reverse('view_product', args=(member.product.id, ))) product_tab = Product_Tab(member.product.id, title="Edit Product Member", tab="settings") return render(request, 'dojo/edit_product_member.html', { 'memberid': memberid, 'form': memberform, 'product_tab': product_tab, }) @user_is_authorized(Product_Member, Permissions.Product_Member_Delete, 'memberid') def delete_product_member(request, memberid): member = get_object_or_404(Product_Member, pk=memberid) memberform = Delete_Product_MemberForm(instance=member) if request.method == 'POST': memberform = Delete_Product_MemberForm(request.POST, instance=member) member = memberform.instance user = member.user member.delete() messages.add_message(request, messages.SUCCESS, 'Product member deleted successfully.', extra_tags='alert-success') if is_title_in_breadcrumbs('View User'): return HttpResponseRedirect(reverse('view_user', args=(member.user.id, ))) else: if user == request.user: return HttpResponseRedirect(reverse('product')) else: return HttpResponseRedirect(reverse('view_product', args=(member.product.id, ))) product_tab = Product_Tab(member.product.id, title="Delete Product Member", tab="settings") return render(request, 'dojo/delete_product_member.html', { 'memberid': memberid, 'form': memberform, 'product_tab': product_tab, }) @user_is_authorized(Product, Permissions.Product_API_Scan_Configuration_Add, 'pid') def add_api_scan_configuration(request, pid): product = get_object_or_404(Product, id=pid) if request.method == 'POST': form = Product_API_Scan_ConfigurationForm(request.POST) if form.is_valid(): product_api_scan_configuration = form.save(commit=False) product_api_scan_configuration.product = product try: api = create_API(product_api_scan_configuration.tool_configuration) if api and hasattr(api, 'test_product_connection'): result = api.test_product_connection(product_api_scan_configuration) messages.add_message(request, messages.SUCCESS, f'API connection successful with message: {result}.', extra_tags='alert-success') product_api_scan_configuration.save() messages.add_message(request, messages.SUCCESS, 'API Scan Configuration added successfully.', extra_tags='alert-success') if 'add_another' in request.POST: return HttpResponseRedirect(reverse('add_api_scan_configuration', args=(pid,))) else: return HttpResponseRedirect(reverse('view_api_scan_configurations', args=(pid,))) except Exception as e: logger.exception(e) messages.add_message(request, messages.ERROR, str(e), extra_tags='alert-danger') else: form = Product_API_Scan_ConfigurationForm() product_tab = Product_Tab(pid, title="Add API Scan Configuration", tab="settings") return render(request, 'dojo/add_product_api_scan_configuration.html', {'form': form, 'product_tab': product_tab, 'product': product, }) @user_is_authorized(Product, Permissions.Product_View, 'pid') def view_api_scan_configurations(request, pid): product_api_scan_configurations = Product_API_Scan_Configuration.objects.filter(product=pid) product_tab = Product_Tab(pid, title="API Scan Configurations", tab="settings") return render(request, 'dojo/view_product_api_scan_configurations.html', { 'product_api_scan_configurations': product_api_scan_configurations, 'product_tab': product_tab, 'pid': pid }) @user_is_authorized(Product_API_Scan_Configuration, Permissions.Product_API_Scan_Configuration_Edit, 'pascid') def edit_api_scan_configuration(request, pid, pascid): product_api_scan_configuration = get_object_or_404(Product_API_Scan_Configuration, id=pascid) if product_api_scan_configuration.product.pk != int(pid): # user is trying to edit Tool Configuration from another product (trying to by-pass auth) raise Http404() if request.method == 'POST': form = Product_API_Scan_ConfigurationForm(request.POST, instance=product_api_scan_configuration) if form.is_valid(): try: form_copy = form.save(commit=False) api = create_API(form_copy.tool_configuration) if api and hasattr(api, 'test_product_connection'): result = api.test_product_connection(form_copy) messages.add_message(request, messages.SUCCESS, f'API connection successful with message: {result}.', extra_tags='alert-success') form.save() messages.add_message(request, messages.SUCCESS, 'API Scan Configuration successfully updated.', extra_tags='alert-success') return HttpResponseRedirect(reverse('view_api_scan_configurations', args=(pid,))) except Exception as e: logger.info(e) messages.add_message(request, messages.ERROR, str(e), extra_tags='alert-danger') else: form = Product_API_Scan_ConfigurationForm(instance=product_api_scan_configuration) product_tab = Product_Tab(pid, title="Edit API Scan Configuration", tab="settings") return render(request, 'dojo/edit_product_api_scan_configuration.html', { 'form': form, 'product_tab': product_tab }) @user_is_authorized(Product_API_Scan_Configuration, Permissions.Product_API_Scan_Configuration_Delete, 'pascid') def delete_api_scan_configuration(request, pid, pascid): product_api_scan_configuration = get_object_or_404(Product_API_Scan_Configuration, id=pascid) if product_api_scan_configuration.product.pk != int(pid): # user is trying to delete Tool Configuration from another product (trying to by-pass auth) raise Http404() if request.method == 'POST': form = Product_API_Scan_ConfigurationForm(request.POST) product_api_scan_configuration.delete() messages.add_message(request, messages.SUCCESS, 'API Scan Configuration deleted.', extra_tags='alert-success') return HttpResponseRedirect(reverse('view_api_scan_configurations', args=(pid,))) else: form = DeleteProduct_API_Scan_ConfigurationForm(instance=product_api_scan_configuration) product_tab = Product_Tab(pid, title="Delete Tool Configuration", tab="settings") return render(request, 'dojo/delete_product_api_scan_configuration.html', { 'form': form, 'product_tab': product_tab }) @user_is_authorized(Product_Group, Permissions.Product_Group_Edit, 'groupid') def edit_product_group(request, groupid): logger.exception(groupid) group = get_object_or_404(Product_Group, pk=groupid) groupform = Edit_Product_Group_Form(instance=group) if request.method == 'POST': groupform = Edit_Product_Group_Form(request.POST, instance=group) if groupform.is_valid(): if group.role.is_owner and not user_has_permission(request.user, group.product, Permissions.Product_Group_Add_Owner): messages.add_message(request, messages.WARNING, 'You are not permitted to make groups owners.', extra_tags='alert-warning') else: groupform.save() messages.add_message(request, messages.SUCCESS, 'Product group updated successfully.', extra_tags='alert-success') if is_title_in_breadcrumbs('View Group'): return HttpResponseRedirect(reverse('view_group', args=(group.group.id, ))) else: return HttpResponseRedirect(reverse('view_product', args=(group.product.id, ))) product_tab = Product_Tab(group.product.id, title="Edit Product Group", tab="settings") return render(request, 'dojo/edit_product_group.html', { 'groupid': groupid, 'form': groupform, 'product_tab': product_tab, }) @user_is_authorized(Product_Group, Permissions.Product_Group_Delete, 'groupid') def delete_product_group(request, groupid): group = get_object_or_404(Product_Group, pk=groupid) groupform = Delete_Product_GroupForm(instance=group) if request.method == 'POST': groupform = Delete_Product_GroupForm(request.POST, instance=group) group = groupform.instance group.delete() messages.add_message(request, messages.SUCCESS, 'Product group deleted successfully.', extra_tags='alert-success') if is_title_in_breadcrumbs('View Group'): return HttpResponseRedirect(reverse('view_group', args=(group.group.id, ))) else: # TODO: If user was in the group that was deleted and no longer has access, redirect back to product listing # page return HttpResponseRedirect(reverse('view_product', args=(group.product.id, ))) product_tab = Product_Tab(group.product.id, title="Delete Product Group", tab="settings") return render(request, 'dojo/delete_product_group.html', { 'groupid': groupid, 'form': groupform, 'product_tab': product_tab, }) @user_is_authorized(Product, Permissions.Product_Group_Add, 'pid') def add_product_group(request, pid): product = get_object_or_404(Product, pk=pid) group_form = Add_Product_GroupForm(initial={'product': product.id}) if request.method == 'POST': group_form = Add_Product_GroupForm(request.POST, initial={'product': product.id}) if group_form.is_valid(): if group_form.cleaned_data['role'].is_owner and not user_has_permission(request.user, product, Permissions.Product_Group_Add_Owner): messages.add_message(request, messages.WARNING, 'You are not permitted to add groups as owners.', extra_tags='alert-warning') else: if 'groups' in group_form.cleaned_data and len(group_form.cleaned_data['groups']) > 0: for group in group_form.cleaned_data['groups']: groups = Product_Group.objects.filter(product=product, group=group) if groups.count() == 0: product_group = Product_Group() product_group.product = product product_group.group = group product_group.role = group_form.cleaned_data['role'] product_group.save() messages.add_message(request, messages.SUCCESS, 'Product groups added successfully.', extra_tags='alert-success') return HttpResponseRedirect(reverse('view_product', args=(pid, ))) product_tab = Product_Tab(pid, title="Edit Product Group", tab="settings") return render(request, 'dojo/new_product_group.html', { 'product': product, 'form': group_form, 'product_tab': product_tab, })
46.803776
154
0.597741
lendar as tcalendar import logging import base64 from collections import OrderedDict from datetime import datetime, date, timedelta from math import ceil from dateutil.relativedelta import relativedelta from django.contrib import messages from django.core.exceptions import PermissionDenied, ValidationError from django.urls import reverse from django.http import HttpResponseRedirect, Http404 from django.shortcuts import render, get_object_or_404 from django.utils import timezone from django.db.models import Sum, Count, Q, Max from django.contrib.admin.utils import NestedObjects from django.db import DEFAULT_DB_ALIAS, connection from dojo.templatetags.display_tags import get_level from dojo.filters import ProductEngagementFilter, ProductFilter, EngagementFilter, MetricsEndpointFilter, MetricsFindingFilter, ProductComponentFilter from dojo.forms import ProductForm, EngForm, DeleteProductForm, DojoMetaDataForm, JIRAProjectForm, JIRAFindingForm, AdHocFindingForm, \ EngagementPresetsForm, DeleteEngagementPresetsForm, ProductNotificationsForm, \ GITHUB_Product_Form, GITHUBFindingForm, AppAnalysisForm, JIRAEngagementForm, Add_Product_MemberForm, \ Edit_Product_MemberForm, Delete_Product_MemberForm, Add_Product_GroupForm, Edit_Product_Group_Form, Delete_Product_GroupForm, \ DeleteAppAnalysisForm, Product_API_Scan_ConfigurationForm, DeleteProduct_API_Scan_ConfigurationForm from dojo.models import Product_Type, Note_Type, Finding, Product, Engagement, Test, GITHUB_PKey, \ Test_Type, System_Settings, Languages, App_Analysis, Benchmark_Type, Benchmark_Product_Summary, Endpoint_Status, \ Endpoint, Engagement_Presets, DojoMeta, Notifications, BurpRawRequestResponse, Product_Member, \ Product_Group, Product_API_Scan_Configuration from dojo.utils import add_external_issue, add_error_message_to_response, add_field_errors_to_response, get_page_items, add_breadcrumb, \ get_system_setting, Product_Tab, get_punchcard_data, queryset_check, is_title_in_breadcrumbs from dojo.notifications.helper import create_notification from django.db.models import Prefetch, F, OuterRef, Subquery from django.db.models.query import QuerySet from github import Github from django.contrib.postgres.aggregates import StringAgg from dojo.components.sql_group_concat import Sql_GroupConcat import dojo.jira_link.helper as jira_helper from dojo.authorization.authorization import user_has_permission, user_has_permission_or_403 from django.conf import settings from dojo.authorization.roles_permissions import Permissions from dojo.authorization.authorization_decorators import user_is_authorized from dojo.product.queries import get_authorized_products, get_authorized_members_for_product, get_authorized_groups_for_product from dojo.product_type.queries import get_authorized_members_for_product_type, get_authorized_groups_for_product_type from dojo.tool_config.factory import create_API import dojo.finding.helper as finding_helper logger = logging.getLogger(__name__) def product(request): product_type = None if 'prod_type' in request.GET: p = request.GET.getlist('prod_type', []) if len(p) == 1: product_type = get_object_or_404(Product_Type, id=p[0]) prods = get_authorized_products(Permissions.Product_View) name_words = prods.values_list('name', flat=True) prod_filter = ProductFilter(request.GET, queryset=prods, user=request.user) prod_list = get_page_items(request, prod_filter.qs, 25) prod_list.object_list = prefetch_for_product(prod_list.object_list) add_breadcrumb(title="Product List", top_level=not len(request.GET), request=request) return render(request, 'dojo/product.html', {'prod_list': prod_list, 'prod_filter': prod_filter, 'name_words': sorted(set(name_words)), 'user': request.user}) def prefetch_for_product(prods): prefetched_prods = prods if isinstance(prods, QuerySet): prefetched_prods = prefetched_prods.prefetch_related('team_manager') prefetched_prods = prefetched_prods.prefetch_related('product_manager') prefetched_prods = prefetched_prods.prefetch_related('technical_contact') prefetched_prods = prefetched_prods.annotate( active_engagement_count=Count('engagement__id', filter=Q(engagement__active=True))) prefetched_prods = prefetched_prods.annotate( closed_engagement_count=Count('engagement__id', filter=Q(engagement__active=False))) prefetched_prods = prefetched_prods.annotate(last_engagement_date=Max('engagement__target_start')) prefetched_prods = prefetched_prods.annotate(active_finding_count=Count('engagement__test__finding__id', filter=Q( engagement__test__finding__active=True))) prefetched_prods = prefetched_prods.annotate(active_verified_finding_count=Count('engagement__test__finding__id', filter=Q( engagement__test__finding__active=True, engagement__test__finding__verified=True))) prefetched_prods = prefetched_prods.prefetch_related('jira_project_set__jira_instance') prefetched_prods = prefetched_prods.prefetch_related('authorized_users') prefetched_prods = prefetched_prods.prefetch_related('prod_type__authorized_users') prefetched_prods = prefetched_prods.prefetch_related('members') prefetched_prods = prefetched_prods.prefetch_related('prod_type__members') active_endpoint_query = Endpoint.objects.filter( finding__active=True, finding__mitigated__isnull=True).distinct() prefetched_prods = prefetched_prods.prefetch_related( Prefetch('endpoint_set', queryset=active_endpoint_query, to_attr='active_endpoints')) prefetched_prods = prefetched_prods.prefetch_related('tags') if get_system_setting('enable_github'): prefetched_prods = prefetched_prods.prefetch_related( Prefetch('github_pkey_set', queryset=GITHUB_PKey.objects.all().select_related('git_conf'), to_attr='github_confs')) else: logger.debug('unable to prefetch because query was already executed') return prefetched_prods def iso_to_gregorian(iso_year, iso_week, iso_day): jan4 = date(iso_year, 1, 4) start = jan4 - timedelta(days=jan4.isoweekday() - 1) return start + timedelta(weeks=iso_week - 1, days=iso_day - 1) @user_is_authorized(Product, Permissions.Product_View, 'pid') def view_product(request, pid): prod_query = Product.objects.all().select_related('product_manager', 'technical_contact', 'team_manager') \ .prefetch_related('authorized_users') \ .prefetch_related('members') \ .prefetch_related('prod_type__members') prod = get_object_or_404(prod_query, id=pid) product_members = get_authorized_members_for_product(prod, Permissions.Product_View) product_type_members = get_authorized_members_for_product_type(prod.prod_type, Permissions.Product_Type_View) product_groups = get_authorized_groups_for_product(prod, Permissions.Product_View) product_type_groups = get_authorized_groups_for_product_type(prod.prod_type, Permissions.Product_Type_View) personal_notifications_form = ProductNotificationsForm( instance=Notifications.objects.filter(user=request.user).filter(product=prod).first()) langSummary = Languages.objects.filter(product=prod).aggregate(Sum('files'), Sum('code'), Count('files')) languages = Languages.objects.filter(product=prod).order_by('-code') app_analysis = App_Analysis.objects.filter(product=prod).order_by('name') benchmark_type = Benchmark_Type.objects.filter(enabled=True).order_by('name') benchmarks = Benchmark_Product_Summary.objects.filter(product=prod, publish=True, benchmark_type__enabled=True).order_by('benchmark_type__name') benchAndPercent = [] for i in range(0, len(benchmarks)): benchAndPercent.append([benchmarks[i].benchmark_type, get_level(benchmarks[i])]) system_settings = System_Settings.objects.get() product_metadata = dict(prod.product_meta.order_by('name').values_list('name', 'value')) open_findings = Finding.objects.filter(test__engagement__product=prod, false_p=False, active=True, duplicate=False, out_of_scope=False).order_by('numerical_severity').values( 'severity').annotate(count=Count('severity')) critical = 0 high = 0 medium = 0 low = 0 info = 0 for v in open_findings: if v["severity"] == "Critical": critical = v["count"] elif v["severity"] == "High": high = v["count"] elif v["severity"] == "Medium": medium = v["count"] elif v["severity"] == "Low": low = v["count"] elif v["severity"] == "Info": info = v["count"] total = critical + high + medium + low + info product_tab = Product_Tab(pid, title="Product", tab="overview") return render(request, 'dojo/view_product_details.html', { 'prod': prod, 'product_tab': product_tab, 'product_metadata': product_metadata, 'critical': critical, 'high': high, 'medium': medium, 'low': low, 'info': info, 'total': total, 'user': request.user, 'languages': languages, 'langSummary': langSummary, 'app_analysis': app_analysis, 'system_settings': system_settings, 'benchmarks_percents': benchAndPercent, 'benchmarks': benchmarks, 'product_members': product_members, 'product_type_members': product_type_members, 'product_groups': product_groups, 'product_type_groups': product_type_groups, 'personal_notifications_form': personal_notifications_form}) @user_is_authorized(Product, Permissions.Component_View, 'pid') def view_product_components(request, pid): prod = get_object_or_404(Product, id=pid) product_tab = Product_Tab(pid, title="Product", tab="components") separator = ', ' if connection.vendor == 'postgresql': component_query = Finding.objects.filter(test__engagement__product__id=pid).values("component_name").order_by( 'component_name').annotate( component_version=StringAgg('component_version', delimiter=separator, distinct=True)) else: component_query = Finding.objects.filter(test__engagement__product__id=pid).values("component_name") component_query = component_query.annotate( component_version=Sql_GroupConcat('component_version', separator=separator, distinct=True)) component_query = component_query.annotate(total=Count('id')).order_by('component_name', 'component_version') component_query = component_query.annotate(active=Count('id', filter=Q(active=True))) component_query = component_query.annotate(duplicate=(Count('id', filter=Q(duplicate=True)))) component_query = component_query.order_by('-total') comp_filter = ProductComponentFilter(request.GET, queryset=component_query) result = get_page_items(request, comp_filter.qs, 25) component_words = component_query.exclude(component_name__isnull=True).values_list('component_name', flat=True) return render(request, 'dojo/product_components.html', { 'prod': prod, 'filter': comp_filter, 'product_tab': product_tab, 'result': result, 'component_words': sorted(set(component_words)) }) def identify_view(request): get_data = request.GET view = get_data.get('type', None) if view: # although any XSS should be catch by django autoescape, we see people sometimes using '|safe'... if view in ['Endpoint', 'Finding']: return view raise ValueError('invalid view, view must be "Endpoint" or "Finding"') else: if get_data.get('finding__severity', None): return 'Endpoint' elif get_data.get('false_positive', None): return 'Endpoint' referer = request.META.get('HTTP_REFERER', None) if referer: if referer.find('type=Endpoint') > -1: return 'Endpoint' return 'Finding' def finding_querys(request, prod): filters = dict() findings_query = Finding.objects.filter(test__engagement__product=prod, severity__in=('Critical', 'High', 'Medium', 'Low', 'Info')) # prefetch only what's needed to avoid lots of repeated queries findings_query = findings_query.prefetch_related( 'reporter') findings = MetricsFindingFilter(request.GET, queryset=findings_query, pid=prod) findings_qs = queryset_check(findings) filters['form'] = findings.form try: start_date = findings_qs.earliest('date').date start_date = datetime(start_date.year, start_date.month, start_date.day, tzinfo=timezone.get_current_timezone()) end_date = findings_qs.latest('date').date end_date = datetime(end_date.year, end_date.month, end_date.day, tzinfo=timezone.get_current_timezone()) except Exception as e: logger.debug(e) start_date = timezone.now() end_date = timezone.now() week = end_date - timedelta(days=7) from dojo.finding.helper import ACCEPTED_FINDINGS_QUERY filters['accepted'] = findings_qs.filter(ACCEPTED_FINDINGS_QUERY).filter(date__range=[start_date, end_date]) filters['verified'] = findings_qs.filter(date__range=[start_date, end_date], false_p=False, active=True, verified=True, duplicate=False, out_of_scope=False).order_by("date") filters['new_verified'] = findings_qs.filter(date__range=[week, end_date], false_p=False, verified=True, active=True, duplicate=False, out_of_scope=False).order_by("date") filters['open'] = findings_qs.filter(date__range=[start_date, end_date], false_p=False, duplicate=False, out_of_scope=False, active=True, is_mitigated=False) filters['inactive'] = findings_qs.filter(date__range=[start_date, end_date], duplicate=False, out_of_scope=False, active=False, is_mitigated=False) filters['closed'] = findings_qs.filter(date__range=[start_date, end_date], false_p=False, duplicate=False, out_of_scope=False, active=False, is_mitigated=True) filters['false_positive'] = findings_qs.filter(date__range=[start_date, end_date], false_p=True, duplicate=False, out_of_scope=False) filters['out_of_scope'] = findings_qs.filter(date__range=[start_date, end_date], false_p=False, duplicate=False, out_of_scope=True) filters['all'] = findings_qs filters['open_vulns'] = findings_qs.filter( false_p=False, duplicate=False, out_of_scope=False, active=True, mitigated__isnull=True, cwe__isnull=False, ).order_by('cwe').values( 'cwe' ).annotate( count=Count('cwe') ) filters['all_vulns'] = findings_qs.filter( duplicate=False, cwe__isnull=False, ).order_by('cwe').values( 'cwe' ).annotate( count=Count('cwe') ) filters['start_date'] = start_date filters['end_date'] = end_date filters['week'] = week return filters def endpoint_querys(request, prod): filters = dict() endpoints_query = Endpoint_Status.objects.filter(finding__test__engagement__product=prod, finding__severity__in=( 'Critical', 'High', 'Medium', 'Low', 'Info')).prefetch_related( 'finding__test__engagement', 'finding__test__engagement__risk_acceptance', 'finding__risk_acceptance_set', 'finding__reporter').annotate(severity=F('finding__severity')) endpoints = MetricsEndpointFilter(request.GET, queryset=endpoints_query) endpoints_qs = queryset_check(endpoints) filters['form'] = endpoints.form if not endpoints_qs and not endpoints_query: endpoints = endpoints_query endpoints_qs = queryset_check(endpoints) messages.add_message(request, messages.ERROR, 'All objects have been filtered away. Displaying all objects', extra_tags='alert-danger') try: start_date = endpoints_qs.earliest('date').date start_date = datetime(start_date.year, start_date.month, start_date.day, tzinfo=timezone.get_current_timezone()) end_date = endpoints_qs.latest('date').date end_date = datetime(end_date.year, end_date.month, end_date.day, tzinfo=timezone.get_current_timezone()) except: start_date = timezone.now() end_date = timezone.now() week = end_date - timedelta(days=7) filters['accepted'] = endpoints_qs.filter(date__range=[start_date, end_date], risk_accepted=True).order_by("date") filters['verified'] = endpoints_qs.filter(date__range=[start_date, end_date], false_positive=False, mitigated=True, out_of_scope=False).order_by("date") filters['new_verified'] = endpoints_qs.filter(date__range=[week, end_date], false_positive=False, mitigated=True, out_of_scope=False).order_by("date") filters['open'] = endpoints_qs.filter(date__range=[start_date, end_date], mitigated=False) filters['inactive'] = endpoints_qs.filter(date__range=[start_date, end_date], mitigated=True) filters['closed'] = endpoints_qs.filter(date__range=[start_date, end_date], mitigated=True) filters['false_positive'] = endpoints_qs.filter(date__range=[start_date, end_date], false_positive=True) filters['out_of_scope'] = endpoints_qs.filter(date__range=[start_date, end_date], out_of_scope=True) filters['all'] = endpoints_qs filters['open_vulns'] = endpoints_qs.filter( false_positive=False, out_of_scope=False, mitigated=True, finding__cwe__isnull=False, ).order_by('finding__cwe').values( 'finding__cwe' ).annotate( count=Count('finding__cwe') ) filters['all_vulns'] = endpoints_qs.filter( finding__cwe__isnull=False, ).order_by('finding__cwe').values( 'finding__cwe' ).annotate( count=Count('finding__cwe') ) filters['start_date'] = start_date filters['end_date'] = end_date filters['week'] = week return filters @user_is_authorized(Product, Permissions.Product_View, 'pid') def view_product_metrics(request, pid): prod = get_object_or_404(Product, id=pid) engs = Engagement.objects.filter(product=prod, active=True) view = identify_view(request) result = EngagementFilter( request.GET, queryset=Engagement.objects.filter(product=prod, active=False).order_by('-target_end')) inactive_engs_page = get_page_items(request, result.qs, 10) filters = dict() if view == 'Finding': filters = finding_querys(request, prod) elif view == 'Endpoint': filters = endpoint_querys(request, prod) start_date = filters['start_date'] end_date = filters['end_date'] week_date = filters['week'] tests = Test.objects.filter(engagement__product=prod).prefetch_related('finding_set', 'test_type') tests = tests.annotate(verified_finding_count=Count('finding__id', filter=Q(finding__verified=True))) open_vulnerabilities = filters['open_vulns'] all_vulnerabilities = filters['all_vulns'] start_date = timezone.make_aware(datetime.combine(start_date, datetime.min.time())) r = relativedelta(end_date, start_date) weeks_between = int(ceil((((r.years * 12) + r.months) * 4.33) + (r.days / 7))) if weeks_between <= 0: weeks_between += 2 punchcard, ticks = get_punchcard_data(filters.get('open', None), start_date, weeks_between, view) add_breadcrumb(parent=prod, top_level=False, request=request) open_close_weekly = OrderedDict() new_weekly = OrderedDict() severity_weekly = OrderedDict() critical_weekly = OrderedDict() high_weekly = OrderedDict() medium_weekly = OrderedDict() for v in filters.get('open', None): iso_cal = v.date.isocalendar() x = iso_to_gregorian(iso_cal[0], iso_cal[1], 1) y = x.strftime("<span class='small'>%m/%d<br/>%Y</span>") x = (tcalendar.timegm(x.timetuple()) * 1000) if x not in critical_weekly: critical_weekly[x] = {'count': 0, 'week': y} if x not in high_weekly: high_weekly[x] = {'count': 0, 'week': y} if x not in medium_weekly: medium_weekly[x] = {'count': 0, 'week': y} if x in open_close_weekly: if v.mitigated: open_close_weekly[x]['closed'] += 1 else: open_close_weekly[x]['open'] += 1 else: if v.mitigated: open_close_weekly[x] = {'closed': 1, 'open': 0, 'accepted': 0} else: open_close_weekly[x] = {'closed': 0, 'open': 1, 'accepted': 0} open_close_weekly[x]['week'] = y if view == 'Finding': severity = v.severity elif view == 'Endpoint': severity = v.finding.severity if x in severity_weekly: if severity in severity_weekly[x]: severity_weekly[x][severity] += 1 else: severity_weekly[x][severity] = 1 else: severity_weekly[x] = {'Critical': 0, 'High': 0, 'Medium': 0, 'Low': 0, 'Info': 0} severity_weekly[x][severity] = 1 severity_weekly[x]['week'] = y if severity == 'Critical': if x in critical_weekly: critical_weekly[x]['count'] += 1 else: critical_weekly[x] = {'count': 1, 'week': y} elif severity == 'High': if x in high_weekly: high_weekly[x]['count'] += 1 else: high_weekly[x] = {'count': 1, 'week': y} elif severity == 'Medium': if x in medium_weekly: medium_weekly[x]['count'] += 1 else: medium_weekly[x] = {'count': 1, 'week': y} for a in filters.get('accepted', None): if view == 'Finding': finding = a elif view == 'Endpoint': finding = v.finding iso_cal = a.date.isocalendar() x = iso_to_gregorian(iso_cal[0], iso_cal[1], 1) y = x.strftime("<span class='small'>%m/%d<br/>%Y</span>") x = (tcalendar.timegm(x.timetuple()) * 1000) if x in open_close_weekly: open_close_weekly[x]['accepted'] += 1 else: open_close_weekly[x] = {'closed': 0, 'open': 0, 'accepted': 1} open_close_weekly[x]['week'] = y test_data = {} for t in tests: if t.test_type.name in test_data: test_data[t.test_type.name] += t.verified_finding_count else: test_data[t.test_type.name] = t.verified_finding_count product_tab = Product_Tab(pid, title="Product", tab="metrics") return render(request, 'dojo/product_metrics.html', {'prod': prod, 'product_tab': product_tab, 'engs': engs, 'inactive_engs': inactive_engs_page, 'view': view, 'verified_objs': filters.get('verified', None), 'open_objs': filters.get('open', None), 'inactive_objs': filters.get('inactive', None), 'closed_objs': filters.get('closed', None), 'false_positive_objs': filters.get('false_positive', None), 'out_of_scope_objs': filters.get('out_of_scope', None), 'accepted_objs': filters.get('accepted', None), 'new_objs': filters.get('new_verified', None), 'all_objs': filters.get('all', None), 'form': filters.get('form', None), 'reset_link': reverse('view_product_metrics', args=(prod.id,)) + '?type=' + view, 'open_vulnerabilities': open_vulnerabilities, 'all_vulnerabilities': all_vulnerabilities, 'start_date': start_date, 'punchcard': punchcard, 'ticks': ticks, 'open_close_weekly': open_close_weekly, 'severity_weekly': severity_weekly, 'critical_weekly': critical_weekly, 'high_weekly': high_weekly, 'medium_weekly': medium_weekly, 'test_data': test_data, 'user': request.user}) @user_is_authorized(Product, Permissions.Engagement_View, 'pid') def view_engagements(request, pid): prod = get_object_or_404(Product, id=pid) default_page_num = 10 recent_test_day_count = 7 engs = Engagement.objects.filter(product=prod, active=True, status="In Progress").order_by('-updated') active_engs_filter = ProductEngagementFilter(request.GET, queryset=engs, prefix='active') result_active_engs = get_page_items(request, active_engs_filter.qs, default_page_num, prefix="engs") result_active_engs.object_list = prefetch_for_view_engagements(result_active_engs.object_list, recent_test_day_count) engs = Engagement.objects.filter(~Q(status="In Progress"), product=prod, active=True).order_by('-updated') queued_engs_filter = ProductEngagementFilter(request.GET, queryset=engs, prefix='queued') result_queued_engs = get_page_items(request, queued_engs_filter.qs, default_page_num, prefix="queued_engs") result_queued_engs.object_list = prefetch_for_view_engagements(result_queued_engs.object_list, recent_test_day_count) # Cancelled or Completed Engagements engs = Engagement.objects.filter(product=prod, active=False).order_by('-target_end') inactive_engs_filter = ProductEngagementFilter(request.GET, queryset=engs, prefix='closed') result_inactive_engs = get_page_items(request, inactive_engs_filter.qs, default_page_num, prefix="inactive_engs") result_inactive_engs.object_list = prefetch_for_view_engagements(result_inactive_engs.object_list, recent_test_day_count) title = "All Engagements" product_tab = Product_Tab(pid, title=title, tab="engagements") return render(request, 'dojo/view_engagements.html', {'prod': prod, 'product_tab': product_tab, 'engs': result_active_engs, 'engs_count': result_active_engs.paginator.count, 'engs_filter': active_engs_filter, 'queued_engs': result_queued_engs, 'queued_engs_count': result_queued_engs.paginator.count, 'queued_engs_filter': queued_engs_filter, 'inactive_engs': result_inactive_engs, 'inactive_engs_count': result_inactive_engs.paginator.count, 'inactive_engs_filter': inactive_engs_filter, 'recent_test_day_count': recent_test_day_count, 'user': request.user}) def prefetch_for_view_engagements(engagements, recent_test_day_count): engagements = engagements.select_related( 'lead' ).prefetch_related( Prefetch('test_set', queryset=Test.objects.filter( id__in=Subquery( Test.objects.filter( engagement_id=OuterRef('engagement_id'), updated__gte=timezone.now() - timedelta(days=recent_test_day_count) ).values_list('id', flat=True) )) ), 'test_set__test_type', ).annotate( count_tests=Count('test', distinct=True), count_findings_all=Count('test__finding__id'), count_findings_open=Count('test__finding__id', filter=Q(test__finding__active=True)), count_findings_open_verified=Count('test__finding__id', filter=Q(test__finding__active=True) & Q(test__finding__verified=True)), count_findings_close=Count('test__finding__id', filter=Q(test__finding__is_mitigated=True)), count_findings_duplicate=Count('test__finding__id', filter=Q(test__finding__duplicate=True)), count_findings_accepted=Count('test__finding__id', filter=Q(test__finding__risk_accepted=True)), ) if System_Settings.objects.get().enable_jira: engagements = engagements.prefetch_related( 'jira_project__jira_instance', 'product__jira_project_set__jira_instance', ) return engagements # Authorization is within the import_scan_results method def import_scan_results_prod(request, pid=None): from dojo.engagement.views import import_scan_results return import_scan_results(request, pid=pid) def new_product(request, ptid=None): jira_project_form = None error = False initial = None if ptid is not None: prod_type = get_object_or_404(Product_Type, pk=ptid) initial = {'prod_type': prod_type} form = ProductForm(initial=initial) if request.method == 'POST': form = ProductForm(request.POST, instance=Product()) if get_system_setting('enable_github'): gform = GITHUB_Product_Form(request.POST, instance=GITHUB_PKey()) else: gform = None if form.is_valid(): if settings.FEATURE_AUTHORIZATION_V2: product_type = form.instance.prod_type user_has_permission_or_403(request.user, product_type, Permissions.Product_Type_Add_Product) else: if not request.user.is_staff: raise PermissionDenied product = form.save() messages.add_message(request, messages.SUCCESS, 'Product added successfully.', extra_tags='alert-success') success, jira_project_form = jira_helper.process_jira_project_form(request, product=product) error = not success if get_system_setting('enable_github'): if gform.is_valid(): github_pkey = gform.save(commit=False) if github_pkey.git_conf is not None and github_pkey.git_project: github_pkey.product = product github_pkey.save() messages.add_message(request, messages.SUCCESS, 'GitHub information added successfully.', extra_tags='alert-success') # Create appropriate labels in the repo logger.info('Create label in repo: ' + github_pkey.git_project) try: g = Github(github_pkey.git_conf.api_key) repo = g.get_repo(github_pkey.git_project) repo.create_label(name="security", color="FF0000", description="This label is automatically applied to all issues created by DefectDojo") repo.create_label(name="security / info", color="00FEFC", description="This label is automatically applied to all issues created by DefectDojo") repo.create_label(name="security / low", color="B7FE00", description="This label is automatically applied to all issues created by DefectDojo") repo.create_label(name="security / medium", color="FEFE00", description="This label is automatically applied to all issues created by DefectDojo") repo.create_label(name="security / high", color="FE9A00", description="This label is automatically applied to all issues created by DefectDojo") repo.create_label(name="security / critical", color="FE2200", description="This label is automatically applied to all issues created by DefectDojo") except: logger.info('Labels cannot be created - they may already exists') create_notification(event='product_added', title=product.name, product=product, url=reverse('view_product', args=(product.id,))) if not error: return HttpResponseRedirect(reverse('view_product', args=(product.id,))) else: # engagement was saved, but JIRA errors, so goto edit_product return HttpResponseRedirect(reverse('edit_product', args=(product.id,))) else: if get_system_setting('enable_jira'): jira_project_form = JIRAProjectForm() if get_system_setting('enable_github'): gform = GITHUB_Product_Form() else: gform = None add_breadcrumb(title="New Product", top_level=False, request=request) return render(request, 'dojo/new_product.html', {'form': form, 'jform': jira_project_form, 'gform': gform}) @user_is_authorized(Product, Permissions.Product_Edit, 'pid') def edit_product(request, pid): product = Product.objects.get(pk=pid) system_settings = System_Settings.objects.get() jira_enabled = system_settings.enable_jira jira_project = None jform = None github_enabled = system_settings.enable_github github_inst = None gform = None error = False try: github_inst = GITHUB_PKey.objects.get(product=product) except: github_inst = None pass if request.method == 'POST': form = ProductForm(request.POST, instance=product) jira_project = jira_helper.get_jira_project(product) if form.is_valid(): form.save() tags = request.POST.getlist('tags') messages.add_message(request, messages.SUCCESS, 'Product updated successfully.', extra_tags='alert-success') success, jform = jira_helper.process_jira_project_form(request, instance=jira_project, product=product) error = not success if get_system_setting('enable_github') and github_inst: gform = GITHUB_Product_Form(request.POST, instance=github_inst) # need to handle delete try: gform.save() except: pass elif get_system_setting('enable_github'): gform = GITHUB_Product_Form(request.POST) if gform.is_valid(): new_conf = gform.save(commit=False) new_conf.product_id = pid new_conf.save() messages.add_message(request, messages.SUCCESS, 'GITHUB information updated successfully.', extra_tags='alert-success') if not error: return HttpResponseRedirect(reverse('view_product', args=(pid,))) else: form = ProductForm(instance=product, initial={'auth_users': product.authorized_users.all()}) if jira_enabled: jira_project = jira_helper.get_jira_project(product) jform = JIRAProjectForm(instance=jira_project) else: jform = None if github_enabled and (github_inst is not None): if github_inst is not None: gform = GITHUB_Product_Form(instance=github_inst) gform = GITHUB_Product_Form() gform = GITHUB_Product_Form() else: gform = None product_tab = Product_Tab(pid, title="Edit Product", tab="settings") return render(request, 'dojo/edit_product.html', {'form': form, 'product_tab': product_tab, 'jform': jform, 'gform': gform, 'product': product }) @user_is_authorized(Product, Permissions.Product_Delete, 'pid') def delete_product(request, pid): product = get_object_or_404(Product, pk=pid) form = DeleteProductForm(instance=product) if request.method == 'POST': logger.debug('delete_product: POST') if 'id' in request.POST and str(product.id) == request.POST['id']: form = DeleteProductForm(request.POST, instance=product) if form.is_valid(): product_type = product.prod_type product.delete() messages.add_message(request, messages.SUCCESS, 'Product and relationships removed.', extra_tags='alert-success') create_notification(event='other', title='Deletion of %s' % product.name, product_type=product_type, description='The product "%s" was deleted by %s' % (product.name, request.user), url=request.build_absolute_uri(reverse('product')), icon="exclamation-triangle") logger.debug('delete_product: POST RETURN') return HttpResponseRedirect(reverse('product')) else: logger.debug('delete_product: POST INVALID FORM') logger.error(form.errors) logger.debug('delete_product: GET') collector = NestedObjects(using=DEFAULT_DB_ALIAS) collector.collect([product]) rels = collector.nested() product_tab = Product_Tab(pid, title="Product", tab="settings") logger.debug('delete_product: GET RENDER') return render(request, 'dojo/delete_product.html', {'product': product, 'form': form, 'product_tab': product_tab, 'rels': rels, }) @user_is_authorized(Product, Permissions.Engagement_Add, 'pid') def new_eng_for_app(request, pid, cicd=False): jira_project = None jira_project_form = None jira_epic_form = None product = Product.objects.get(id=pid) jira_error = False if request.method == 'POST': form = EngForm(request.POST, cicd=cicd, product=product, user=request.user) jira_project = jira_helper.get_jira_project(product) logger.debug('new_eng_for_app') if form.is_valid(): # first create the new engagement engagement = form.save(commit=False) engagement.threat_model = False engagement.api_test = False engagement.pen_test = False engagement.check_list = False engagement.product = form.cleaned_data.get('product') if engagement.threat_model: engagement.progress = 'threat_model' else: engagement.progress = 'other' if cicd: engagement.engagement_type = 'CI/CD' engagement.status = "In Progress" engagement.active = True engagement.save() form.save_m2m() logger.debug('new_eng_for_app: process jira coming') # new engagement, so do not provide jira_project success, jira_project_form = jira_helper.process_jira_project_form(request, instance=None, engagement=engagement) error = not success logger.debug('new_eng_for_app: process jira epic coming') success, jira_epic_form = jira_helper.process_jira_epic_form(request, engagement=engagement) error = error or not success create_notification(event='engagement_added', title=engagement.name + " for " + product.name, engagement=engagement, url=reverse('view_engagement', args=(engagement.id,)), objowner=engagement.lead) messages.add_message(request, messages.SUCCESS, 'Engagement added successfully.', extra_tags='alert-success') if not error: if "_Add Tests" in request.POST: return HttpResponseRedirect(reverse('add_tests', args=(engagement.id,))) elif "_Import Scan Results" in request.POST: return HttpResponseRedirect(reverse('import_scan_results', args=(engagement.id,))) else: return HttpResponseRedirect(reverse('view_engagement', args=(engagement.id,))) else: # engagement was saved, but JIRA errors, so goto edit_engagement logger.debug('new_eng_for_app: jira errors') return HttpResponseRedirect(reverse('edit_engagement', args=(engagement.id,))) else: logger.debug(form.errors) else: form = EngForm(initial={'lead': request.user, 'target_start': timezone.now().date(), 'target_end': timezone.now().date() + timedelta(days=7), 'product': product}, cicd=cicd, product=product, user=request.user) if get_system_setting('enable_jira'): jira_project = jira_helper.get_jira_project(product) logger.debug('showing jira-project-form') jira_project_form = JIRAProjectForm(target='engagement', product=product) logger.debug('showing jira-epic-form') jira_epic_form = JIRAEngagementForm() if cicd: title = 'New CI/CD Engagement' else: title = 'New Interactive Engagement' product_tab = Product_Tab(pid, title=title, tab="engagements") return render(request, 'dojo/new_eng.html', {'form': form, 'title': title, 'product_tab': product_tab, 'jira_epic_form': jira_epic_form, 'jira_project_form': jira_project_form, }) @user_is_authorized(Product, Permissions.Technology_Add, 'pid') def new_tech_for_prod(request, pid): if request.method == 'POST': form = AppAnalysisForm(request.POST) if form.is_valid(): tech = form.save(commit=False) tech.product_id = pid tech.save() messages.add_message(request, messages.SUCCESS, 'Technology added successfully.', extra_tags='alert-success') return HttpResponseRedirect(reverse('view_product', args=(pid,))) form = AppAnalysisForm(initial={'user': request.user}) product_tab = Product_Tab(pid, title="Add Technology", tab="settings") return render(request, 'dojo/new_tech.html', {'form': form, 'product_tab': product_tab, 'pid': pid}) @user_is_authorized(App_Analysis, Permissions.Technology_Edit, 'tid') def edit_technology(request, tid): technology = get_object_or_404(App_Analysis, id=tid) form = AppAnalysisForm(instance=technology) if request.method == 'POST': form = AppAnalysisForm(request.POST) if form.is_valid(): tech = form.save(commit=False) tech.id = technology.id tech.product_id = technology.product.id tech.save() messages.add_message(request, messages.SUCCESS, 'Technology changed successfully.', extra_tags='alert-success') return HttpResponseRedirect(reverse('view_product', args=(technology.product.id,))) product_tab = Product_Tab(technology.product.id, title="Edit Technology", tab="settings") return render(request, 'dojo/edit_technology.html', {'form': form, 'product_tab': product_tab, 'technology': technology}) @user_is_authorized(App_Analysis, Permissions.Technology_Delete, 'tid') def delete_technology(request, tid): technology = get_object_or_404(App_Analysis, id=tid) form = DeleteAppAnalysisForm(instance=technology) if request.method == 'POST': form = Delete_Product_MemberForm(request.POST, instance=technology) technology = form.instance technology.delete() messages.add_message(request, messages.SUCCESS, 'Technology deleted successfully.', extra_tags='alert-success') return HttpResponseRedirect(reverse('view_product', args=(technology.product.id,))) product_tab = Product_Tab(technology.product.id, title="Delete Technology", tab="settings") return render(request, 'dojo/delete_technology.html', { 'technology': technology, 'form': form, 'product_tab': product_tab, }) @user_is_authorized(Product, Permissions.Engagement_Add, 'pid') def new_eng_for_app_cicd(request, pid): # we have to use pid=pid here as new_eng_for_app expects kwargs, because that is how django calls the function based on urls.py named groups return new_eng_for_app(request, pid=pid, cicd=True) @user_is_authorized(Product, Permissions.Product_Edit, 'pid') def add_meta_data(request, pid): prod = Product.objects.get(id=pid) if request.method == 'POST': form = DojoMetaDataForm(request.POST, instance=DojoMeta(product=prod)) if form.is_valid(): form.save() messages.add_message(request, messages.SUCCESS, 'Metadata added successfully.', extra_tags='alert-success') if 'add_another' in request.POST: return HttpResponseRedirect(reverse('add_meta_data', args=(pid,))) else: return HttpResponseRedirect(reverse('view_product', args=(pid,))) else: form = DojoMetaDataForm() product_tab = Product_Tab(pid, title="Add Metadata", tab="settings") return render(request, 'dojo/add_product_meta_data.html', {'form': form, 'product_tab': product_tab, 'product': prod, }) @user_is_authorized(Product, Permissions.Product_Edit, 'pid') def edit_meta_data(request, pid): prod = Product.objects.get(id=pid) if request.method == 'POST': for key, value in request.POST.items(): if key.startswith('cfv_'): cfv_id = int(key.split('_')[1]) cfv = get_object_or_404(DojoMeta, id=cfv_id) value = value.strip() if value: cfv.value = value cfv.save() if key.startswith('delete_'): cfv_id = int(key.split('_')[2]) cfv = get_object_or_404(DojoMeta, id=cfv_id) cfv.delete() messages.add_message(request, messages.SUCCESS, 'Metadata edited successfully.', extra_tags='alert-success') return HttpResponseRedirect(reverse('view_product', args=(pid,))) product_tab = Product_Tab(pid, title="Edit Metadata", tab="settings") return render(request, 'dojo/edit_product_meta_data.html', {'product': prod, 'product_tab': product_tab, }) @user_is_authorized(Product, Permissions.Finding_Add, 'pid') def ad_hoc_finding(request, pid): prod = Product.objects.get(id=pid) test_type, _ = Test_Type.objects.get_or_create(name="Pen Test") test = None try: eng = Engagement.objects.get(product=prod, name="Ad Hoc Engagement") tests = Test.objects.filter(engagement=eng) if len(tests) != 0: test = tests[0] else: test = Test(engagement=eng, test_type=test_type, target_start=timezone.now(), target_end=timezone.now()) test.save() except: eng = Engagement(name="Ad Hoc Engagement", target_start=timezone.now(), target_end=timezone.now(), active=False, product=prod) eng.save() test = Test(engagement=eng, test_type=test_type, target_start=timezone.now(), target_end=timezone.now()) test.save() form_error = False push_all_jira_issues = jira_helper.is_push_all_issues(test) jform = None gform = None form = AdHocFindingForm(initial={'date': timezone.now().date()}, req_resp=None, product=prod) use_jira = jira_helper.get_jira_project(test) is not None if request.method == 'POST': form = AdHocFindingForm(request.POST, req_resp=None, product=prod) if (form['active'].value() is False or form['false_p'].value()) and form['duplicate'].value() is False: closing_disabled = Note_Type.objects.filter(is_mandatory=True, is_active=True).count() if closing_disabled != 0: error_inactive = ValidationError('Can not set a finding as inactive without adding all mandatory notes', code='inactive_without_mandatory_notes') error_false_p = ValidationError( 'Can not set a finding as false positive without adding all mandatory notes', code='false_p_without_mandatory_notes') if form['active'].value() is False: form.add_error('active', error_inactive) if form['false_p'].value(): form.add_error('false_p', error_false_p) messages.add_message(request, messages.ERROR, 'Can not set a finding as inactive or false positive without adding all mandatory notes', extra_tags='alert-danger') if use_jira: jform = JIRAFindingForm(request.POST, prefix='jiraform', push_all=push_all_jira_issues, jira_project=jira_helper.get_jira_project(test), finding_form=form) if form.is_valid() and (jform is None or jform.is_valid()): new_finding = form.save(commit=False) new_finding.test = test new_finding.reporter = request.user new_finding.numerical_severity = Finding.get_numerical_severity( new_finding.severity) new_finding.tags = form.cleaned_data['tags'] new_finding.save() # Save and add new endpoints finding_helper.add_endpoints(new_finding, form) new_finding.save() # Push to jira? push_to_jira = False jira_message = None if jform and jform.is_valid(): # Push to Jira? logger.debug('jira form valid') push_to_jira = push_all_jira_issues or jform.cleaned_data.get('push_to_jira') # if the jira issue key was changed, update database new_jira_issue_key = jform.cleaned_data.get('jira_issue') if new_finding.has_jira_issue: jira_issue = new_finding.jira_issue # everything in DD around JIRA integration is based on the internal id of the issue in JIRA # instead of on the public jira issue key. # I have no idea why, but it means we have to retrieve the issue from JIRA to get the internal JIRA id. # we can assume the issue exist, which is already checked in the validation of the jform if not new_jira_issue_key: jira_helper.finding_unlink_jira(request, new_finding) jira_message = 'Link to JIRA issue removed successfully.' elif new_jira_issue_key != new_finding.jira_issue.jira_key: jira_helper.finding_unlink_jira(request, new_finding) jira_helper.finding_link_jira(request, new_finding, new_jira_issue_key) jira_message = 'Changed JIRA link successfully.' else: logger.debug('finding has no jira issue yet') if new_jira_issue_key: logger.debug( 'finding has no jira issue yet, but jira issue specified in request. trying to link.') jira_helper.finding_link_jira(request, new_finding, new_jira_issue_key) jira_message = 'Linked a JIRA issue successfully.' if 'githubform-push_to_github' in request.POST: gform = GITHUBFindingForm(request.POST, prefix='jiragithub', enabled=push_all_jira_issues) if gform.is_valid(): add_external_issue(new_finding, 'github') new_finding.save(push_to_jira=push_to_jira) if 'request' in form.cleaned_data or 'response' in form.cleaned_data: burp_rr = BurpRawRequestResponse( finding=new_finding, burpRequestBase64=base64.b64encode(form.cleaned_data['request'].encode()), burpResponseBase64=base64.b64encode(form.cleaned_data['response'].encode()), ) burp_rr.clean() burp_rr.save() messages.add_message(request, messages.SUCCESS, 'Finding added successfully.', extra_tags='alert-success') if '_Finished' in request.POST: return HttpResponseRedirect(reverse('view_test', args=(test.id,))) else: return HttpResponseRedirect(reverse('add_findings', args=(test.id,))) else: form_error = True add_error_message_to_response('The form has errors, please correct them below.') add_field_errors_to_response(jform) add_field_errors_to_response(form) else: if use_jira: jform = JIRAFindingForm(push_all=jira_helper.is_push_all_issues(test), prefix='jiraform', jira_project=jira_helper.get_jira_project(test), finding_form=form) if get_system_setting('enable_github'): if GITHUB_PKey.objects.filter(product=test.engagement.product).count() != 0: gform = GITHUBFindingForm(enabled=push_all_jira_issues, prefix='githubform') else: gform = None product_tab = Product_Tab(pid, title="Add Finding", tab="engagements") product_tab.setEngagement(eng) return render(request, 'dojo/ad_hoc_findings.html', {'form': form, 'product_tab': product_tab, 'temp': False, 'tid': test.id, 'pid': pid, 'form_error': form_error, 'jform': jform, 'gform': gform, }) @user_is_authorized(Product, Permissions.Product_View, 'pid') def engagement_presets(request, pid): prod = get_object_or_404(Product, id=pid) presets = Engagement_Presets.objects.filter(product=prod).all() product_tab = Product_Tab(prod.id, title="Engagement Presets", tab="settings") return render(request, 'dojo/view_presets.html', {'product_tab': product_tab, 'presets': presets, 'prod': prod}) @user_is_authorized(Product, Permissions.Product_Edit, 'pid') def edit_engagement_presets(request, pid, eid): prod = get_object_or_404(Product, id=pid) preset = get_object_or_404(Engagement_Presets, id=eid) product_tab = Product_Tab(prod.id, title="Edit Engagement Preset", tab="settings") if request.method == 'POST': tform = EngagementPresetsForm(request.POST, instance=preset) if tform.is_valid(): tform.save() messages.add_message( request, messages.SUCCESS, 'Engagement Preset Successfully Updated.', extra_tags='alert-success') return HttpResponseRedirect(reverse('engagement_presets', args=(pid,))) else: tform = EngagementPresetsForm(instance=preset) return render(request, 'dojo/edit_presets.html', {'product_tab': product_tab, 'tform': tform, 'prod': prod}) @user_is_authorized(Product, Permissions.Product_Edit, 'pid') def add_engagement_presets(request, pid): prod = get_object_or_404(Product, id=pid) if request.method == 'POST': tform = EngagementPresetsForm(request.POST) if tform.is_valid(): form_copy = tform.save(commit=False) form_copy.product = prod form_copy.save() tform.save_m2m() messages.add_message( request, messages.SUCCESS, 'Engagement Preset Successfully Created.', extra_tags='alert-success') return HttpResponseRedirect(reverse('engagement_presets', args=(pid,))) else: tform = EngagementPresetsForm() product_tab = Product_Tab(pid, title="New Engagement Preset", tab="settings") return render(request, 'dojo/new_params.html', {'tform': tform, 'pid': pid, 'product_tab': product_tab}) @user_is_authorized(Product, Permissions.Product_Edit, 'pid') def delete_engagement_presets(request, pid, eid): prod = get_object_or_404(Product, id=pid) preset = get_object_or_404(Engagement_Presets, id=eid) form = DeleteEngagementPresetsForm(instance=preset) if request.method == 'POST': if 'id' in request.POST: form = DeleteEngagementPresetsForm(request.POST, instance=preset) if form.is_valid(): preset.delete() messages.add_message(request, messages.SUCCESS, 'Engagement presets and engagement relationships removed.', extra_tags='alert-success') return HttpResponseRedirect(reverse('engagement_presets', args=(pid,))) collector = NestedObjects(using=DEFAULT_DB_ALIAS) collector.collect([preset]) rels = collector.nested() product_tab = Product_Tab(pid, title="Delete Engagement Preset", tab="settings") return render(request, 'dojo/delete_presets.html', {'product': product, 'form': form, 'product_tab': product_tab, 'rels': rels, }) @user_is_authorized(Product, Permissions.Product_View, 'pid') def edit_notifications(request, pid): prod = get_object_or_404(Product, id=pid) if request.method == 'POST': product_notifications = Notifications.objects.filter(user=request.user).filter(product=prod).first() if not product_notifications: product_notifications = Notifications(user=request.user, product=prod) logger.debug('no existing product notifications found') else: logger.debug('existing product notifications found') form = ProductNotificationsForm(request.POST, instance=product_notifications) # print(vars(form)) if form.is_valid(): form.save() messages.add_message(request, messages.SUCCESS, 'Notification settings updated.', extra_tags='alert-success') return HttpResponseRedirect(reverse('view_product', args=(pid,))) @user_is_authorized(Product, Permissions.Product_Manage_Members, 'pid') def add_product_member(request, pid): product = get_object_or_404(Product, pk=pid) memberform = Add_Product_MemberForm(initial={'product': product.id}) if request.method == 'POST': memberform = Add_Product_MemberForm(request.POST, initial={'product': product.id}) if memberform.is_valid(): if memberform.cleaned_data['role'].is_owner and not user_has_permission(request.user, product, Permissions.Product_Member_Add_Owner): messages.add_message(request, messages.WARNING, 'You are not permitted to add users as owners.', extra_tags='alert-warning') else: if 'users' in memberform.cleaned_data and len(memberform.cleaned_data['users']) > 0: for user in memberform.cleaned_data['users']: existing_members = Product_Member.objects.filter(product=product, user=user) if existing_members.count() == 0: product_member = Product_Member() product_member.product = product product_member.user = user product_member.role = memberform.cleaned_data['role'] product_member.save() messages.add_message(request, messages.SUCCESS, 'Product members added successfully.', extra_tags='alert-success') return HttpResponseRedirect(reverse('view_product', args=(pid, ))) product_tab = Product_Tab(pid, title="Add Product Member", tab="settings") return render(request, 'dojo/new_product_member.html', { 'product': product, 'form': memberform, 'product_tab': product_tab, }) @user_is_authorized(Product_Member, Permissions.Product_Manage_Members, 'memberid') def edit_product_member(request, memberid): member = get_object_or_404(Product_Member, pk=memberid) memberform = Edit_Product_MemberForm(instance=member) if request.method == 'POST': memberform = Edit_Product_MemberForm(request.POST, instance=member) if memberform.is_valid(): if member.role.is_owner and not user_has_permission(request.user, member.product, Permissions.Product_Member_Add_Owner): messages.add_message(request, messages.WARNING, 'You are not permitted to make users to owners.', extra_tags='alert-warning') else: memberform.save() messages.add_message(request, messages.SUCCESS, 'Product member updated successfully.', extra_tags='alert-success') if is_title_in_breadcrumbs('View User'): return HttpResponseRedirect(reverse('view_user', args=(member.user.id, ))) else: return HttpResponseRedirect(reverse('view_product', args=(member.product.id, ))) product_tab = Product_Tab(member.product.id, title="Edit Product Member", tab="settings") return render(request, 'dojo/edit_product_member.html', { 'memberid': memberid, 'form': memberform, 'product_tab': product_tab, }) @user_is_authorized(Product_Member, Permissions.Product_Member_Delete, 'memberid') def delete_product_member(request, memberid): member = get_object_or_404(Product_Member, pk=memberid) memberform = Delete_Product_MemberForm(instance=member) if request.method == 'POST': memberform = Delete_Product_MemberForm(request.POST, instance=member) member = memberform.instance user = member.user member.delete() messages.add_message(request, messages.SUCCESS, 'Product member deleted successfully.', extra_tags='alert-success') if is_title_in_breadcrumbs('View User'): return HttpResponseRedirect(reverse('view_user', args=(member.user.id, ))) else: if user == request.user: return HttpResponseRedirect(reverse('product')) else: return HttpResponseRedirect(reverse('view_product', args=(member.product.id, ))) product_tab = Product_Tab(member.product.id, title="Delete Product Member", tab="settings") return render(request, 'dojo/delete_product_member.html', { 'memberid': memberid, 'form': memberform, 'product_tab': product_tab, }) @user_is_authorized(Product, Permissions.Product_API_Scan_Configuration_Add, 'pid') def add_api_scan_configuration(request, pid): product = get_object_or_404(Product, id=pid) if request.method == 'POST': form = Product_API_Scan_ConfigurationForm(request.POST) if form.is_valid(): product_api_scan_configuration = form.save(commit=False) product_api_scan_configuration.product = product try: api = create_API(product_api_scan_configuration.tool_configuration) if api and hasattr(api, 'test_product_connection'): result = api.test_product_connection(product_api_scan_configuration) messages.add_message(request, messages.SUCCESS, f'API connection successful with message: {result}.', extra_tags='alert-success') product_api_scan_configuration.save() messages.add_message(request, messages.SUCCESS, 'API Scan Configuration added successfully.', extra_tags='alert-success') if 'add_another' in request.POST: return HttpResponseRedirect(reverse('add_api_scan_configuration', args=(pid,))) else: return HttpResponseRedirect(reverse('view_api_scan_configurations', args=(pid,))) except Exception as e: logger.exception(e) messages.add_message(request, messages.ERROR, str(e), extra_tags='alert-danger') else: form = Product_API_Scan_ConfigurationForm() product_tab = Product_Tab(pid, title="Add API Scan Configuration", tab="settings") return render(request, 'dojo/add_product_api_scan_configuration.html', {'form': form, 'product_tab': product_tab, 'product': product, }) @user_is_authorized(Product, Permissions.Product_View, 'pid') def view_api_scan_configurations(request, pid): product_api_scan_configurations = Product_API_Scan_Configuration.objects.filter(product=pid) product_tab = Product_Tab(pid, title="API Scan Configurations", tab="settings") return render(request, 'dojo/view_product_api_scan_configurations.html', { 'product_api_scan_configurations': product_api_scan_configurations, 'product_tab': product_tab, 'pid': pid }) @user_is_authorized(Product_API_Scan_Configuration, Permissions.Product_API_Scan_Configuration_Edit, 'pascid') def edit_api_scan_configuration(request, pid, pascid): product_api_scan_configuration = get_object_or_404(Product_API_Scan_Configuration, id=pascid) if product_api_scan_configuration.product.pk != int(pid): # user is trying to edit Tool Configuration from another product (trying to by-pass auth) raise Http404() if request.method == 'POST': form = Product_API_Scan_ConfigurationForm(request.POST, instance=product_api_scan_configuration) if form.is_valid(): try: form_copy = form.save(commit=False) api = create_API(form_copy.tool_configuration) if api and hasattr(api, 'test_product_connection'): result = api.test_product_connection(form_copy) messages.add_message(request, messages.SUCCESS, f'API connection successful with message: {result}.', extra_tags='alert-success') form.save() messages.add_message(request, messages.SUCCESS, 'API Scan Configuration successfully updated.', extra_tags='alert-success') return HttpResponseRedirect(reverse('view_api_scan_configurations', args=(pid,))) except Exception as e: logger.info(e) messages.add_message(request, messages.ERROR, str(e), extra_tags='alert-danger') else: form = Product_API_Scan_ConfigurationForm(instance=product_api_scan_configuration) product_tab = Product_Tab(pid, title="Edit API Scan Configuration", tab="settings") return render(request, 'dojo/edit_product_api_scan_configuration.html', { 'form': form, 'product_tab': product_tab }) @user_is_authorized(Product_API_Scan_Configuration, Permissions.Product_API_Scan_Configuration_Delete, 'pascid') def delete_api_scan_configuration(request, pid, pascid): product_api_scan_configuration = get_object_or_404(Product_API_Scan_Configuration, id=pascid) if product_api_scan_configuration.product.pk != int(pid): # user is trying to delete Tool Configuration from another product (trying to by-pass auth) raise Http404() if request.method == 'POST': form = Product_API_Scan_ConfigurationForm(request.POST) product_api_scan_configuration.delete() messages.add_message(request, messages.SUCCESS, 'API Scan Configuration deleted.', extra_tags='alert-success') return HttpResponseRedirect(reverse('view_api_scan_configurations', args=(pid,))) else: form = DeleteProduct_API_Scan_ConfigurationForm(instance=product_api_scan_configuration) product_tab = Product_Tab(pid, title="Delete Tool Configuration", tab="settings") return render(request, 'dojo/delete_product_api_scan_configuration.html', { 'form': form, 'product_tab': product_tab }) @user_is_authorized(Product_Group, Permissions.Product_Group_Edit, 'groupid') def edit_product_group(request, groupid): logger.exception(groupid) group = get_object_or_404(Product_Group, pk=groupid) groupform = Edit_Product_Group_Form(instance=group) if request.method == 'POST': groupform = Edit_Product_Group_Form(request.POST, instance=group) if groupform.is_valid(): if group.role.is_owner and not user_has_permission(request.user, group.product, Permissions.Product_Group_Add_Owner): messages.add_message(request, messages.WARNING, 'You are not permitted to make groups owners.', extra_tags='alert-warning') else: groupform.save() messages.add_message(request, messages.SUCCESS, 'Product group updated successfully.', extra_tags='alert-success') if is_title_in_breadcrumbs('View Group'): return HttpResponseRedirect(reverse('view_group', args=(group.group.id, ))) else: return HttpResponseRedirect(reverse('view_product', args=(group.product.id, ))) product_tab = Product_Tab(group.product.id, title="Edit Product Group", tab="settings") return render(request, 'dojo/edit_product_group.html', { 'groupid': groupid, 'form': groupform, 'product_tab': product_tab, }) @user_is_authorized(Product_Group, Permissions.Product_Group_Delete, 'groupid') def delete_product_group(request, groupid): group = get_object_or_404(Product_Group, pk=groupid) groupform = Delete_Product_GroupForm(instance=group) if request.method == 'POST': groupform = Delete_Product_GroupForm(request.POST, instance=group) group = groupform.instance group.delete() messages.add_message(request, messages.SUCCESS, 'Product group deleted successfully.', extra_tags='alert-success') if is_title_in_breadcrumbs('View Group'): return HttpResponseRedirect(reverse('view_group', args=(group.group.id, ))) else: # TODO: If user was in the group that was deleted and no longer has access, redirect back to product listing # page return HttpResponseRedirect(reverse('view_product', args=(group.product.id, ))) product_tab = Product_Tab(group.product.id, title="Delete Product Group", tab="settings") return render(request, 'dojo/delete_product_group.html', { 'groupid': groupid, 'form': groupform, 'product_tab': product_tab, }) @user_is_authorized(Product, Permissions.Product_Group_Add, 'pid') def add_product_group(request, pid): product = get_object_or_404(Product, pk=pid) group_form = Add_Product_GroupForm(initial={'product': product.id}) if request.method == 'POST': group_form = Add_Product_GroupForm(request.POST, initial={'product': product.id}) if group_form.is_valid(): if group_form.cleaned_data['role'].is_owner and not user_has_permission(request.user, product, Permissions.Product_Group_Add_Owner): messages.add_message(request, messages.WARNING, 'You are not permitted to add groups as owners.', extra_tags='alert-warning') else: if 'groups' in group_form.cleaned_data and len(group_form.cleaned_data['groups']) > 0: for group in group_form.cleaned_data['groups']: groups = Product_Group.objects.filter(product=product, group=group) if groups.count() == 0: product_group = Product_Group() product_group.product = product product_group.group = group product_group.role = group_form.cleaned_data['role'] product_group.save() messages.add_message(request, messages.SUCCESS, 'Product groups added successfully.', extra_tags='alert-success') return HttpResponseRedirect(reverse('view_product', args=(pid, ))) product_tab = Product_Tab(pid, title="Edit Product Group", tab="settings") return render(request, 'dojo/new_product_group.html', { 'product': product, 'form': group_form, 'product_tab': product_tab, })
true
true
1c394cd42f5508ae906a8a9b784fa9c02b3ade1e
33
py
Python
web_app/shap4mmf/__init__.py
yongkangzzz/mmfgroup
098a78c83e1c2973dc895d1dc7fd30d7d3668143
[ "MIT" ]
null
null
null
web_app/shap4mmf/__init__.py
yongkangzzz/mmfgroup
098a78c83e1c2973dc895d1dc7fd30d7d3668143
[ "MIT" ]
null
null
null
web_app/shap4mmf/__init__.py
yongkangzzz/mmfgroup
098a78c83e1c2973dc895d1dc7fd30d7d3668143
[ "MIT" ]
null
null
null
from ._explainer import Explainer
33
33
0.878788
from ._explainer import Explainer
true
true
1c394dd6465c72408da41055c65ade522768351a
1,198
py
Python
finrl_meta/env_future_trading/wt4elegantrl/wtpy/wrapper/ContractLoader.py
eitin-infant/FinRL-Meta
4c94011e58425796e7e2e5c1bf848afd65c828d6
[ "MIT" ]
214
2021-11-08T17:06:11.000Z
2022-03-31T18:29:48.000Z
finrl_meta/env_future_trading/wt4elegantrl/wtpy/wrapper/ContractLoader.py
eitin-infant/FinRL-Meta
4c94011e58425796e7e2e5c1bf848afd65c828d6
[ "MIT" ]
51
2021-11-14T19:11:02.000Z
2022-03-30T20:23:08.000Z
finrl_meta/env_future_trading/wt4elegantrl/wtpy/wrapper/ContractLoader.py
eitin-infant/FinRL-Meta
4c94011e58425796e7e2e5c1bf848afd65c828d6
[ "MIT" ]
110
2021-11-03T07:41:40.000Z
2022-03-31T03:23:38.000Z
''' Descripttion: Automatically generated file comment version: Author: Wesley Date: 2021-05-24 15:05:01 LastEditors: Wesley LastEditTime: 2021-08-13 15:35:59 ''' from .PlatformHelper import PlatformHelper as ph import os from ctypes import cdll,c_char_p from enum import Enum class LoaderType(Enum): ''' 引擎类型 枚举变量 ''' LT_CTP = 1 LT_CTPMini = 2 LT_CTPOpt = 3 def getModuleName(lType:LoaderType)->str: if lType == LoaderType.LT_CTP: filename = "CTPLoader" elif lType == LoaderType.LT_CTPMini: filename = "CTPMiniLoader" elif lType == LoaderType.LT_CTPOpt: filename = "CTPOptLoader" else: raise Exception('Invalid loader type') return paths = os.path.split(__file__) exename = ph.getModule(filename) a = (paths[:-1] + (exename,)) return os.path.join(*a) class ContractLoader: def __init__(self, lType:LoaderType = LoaderType.LT_CTP): print(getModuleName(lType)) self.api = cdll.LoadLibrary(getModuleName(lType)) self.api.run.argtypes = [ c_char_p] def start(self, cfgfile:str = 'config.ini'): self.api.run(bytes(cfgfile, encoding = "utf8"))
24.958333
61
0.658598
from .PlatformHelper import PlatformHelper as ph import os from ctypes import cdll,c_char_p from enum import Enum class LoaderType(Enum): LT_CTP = 1 LT_CTPMini = 2 LT_CTPOpt = 3 def getModuleName(lType:LoaderType)->str: if lType == LoaderType.LT_CTP: filename = "CTPLoader" elif lType == LoaderType.LT_CTPMini: filename = "CTPMiniLoader" elif lType == LoaderType.LT_CTPOpt: filename = "CTPOptLoader" else: raise Exception('Invalid loader type') return paths = os.path.split(__file__) exename = ph.getModule(filename) a = (paths[:-1] + (exename,)) return os.path.join(*a) class ContractLoader: def __init__(self, lType:LoaderType = LoaderType.LT_CTP): print(getModuleName(lType)) self.api = cdll.LoadLibrary(getModuleName(lType)) self.api.run.argtypes = [ c_char_p] def start(self, cfgfile:str = 'config.ini'): self.api.run(bytes(cfgfile, encoding = "utf8"))
true
true
1c394f272ec8618035bfe7e93a7a40d94808dc99
401
py
Python
studydiscord/wsgi.py
cwhittaker123/django-blog
a89408a86434b0aeb3b179e5885de28740222880
[ "MIT" ]
null
null
null
studydiscord/wsgi.py
cwhittaker123/django-blog
a89408a86434b0aeb3b179e5885de28740222880
[ "MIT" ]
null
null
null
studydiscord/wsgi.py
cwhittaker123/django-blog
a89408a86434b0aeb3b179e5885de28740222880
[ "MIT" ]
null
null
null
""" WSGI config for studydiscord project. It exposes the WSGI callable as a module-level variable named ``application``. For more information on this file, see https://docs.djangoproject.com/en/4.0/howto/deployment/wsgi/ """ import os from django.core.wsgi import get_wsgi_application os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'studydiscord.settings') application = get_wsgi_application()
23.588235
78
0.790524
import os from django.core.wsgi import get_wsgi_application os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'studydiscord.settings') application = get_wsgi_application()
true
true
1c395176e9e2ab1dac36b34689a73bf733882451
2,564
py
Python
src/oci/cloud_guard/models/change_security_recipe_compartment_details.py
pabs3/oci-python-sdk
437ba18ce39af2d1090e277c4bb8750c89f83021
[ "Apache-2.0", "BSD-3-Clause" ]
null
null
null
src/oci/cloud_guard/models/change_security_recipe_compartment_details.py
pabs3/oci-python-sdk
437ba18ce39af2d1090e277c4bb8750c89f83021
[ "Apache-2.0", "BSD-3-Clause" ]
null
null
null
src/oci/cloud_guard/models/change_security_recipe_compartment_details.py
pabs3/oci-python-sdk
437ba18ce39af2d1090e277c4bb8750c89f83021
[ "Apache-2.0", "BSD-3-Clause" ]
null
null
null
# coding: utf-8 # Copyright (c) 2016, 2022, Oracle and/or its affiliates. All rights reserved. # This software is dual-licensed to you under the Universal Permissive License (UPL) 1.0 as shown at https://oss.oracle.com/licenses/upl or Apache License 2.0 as shown at http://www.apache.org/licenses/LICENSE-2.0. You may choose either license. from oci.util import formatted_flat_dict, NONE_SENTINEL, value_allowed_none_or_none_sentinel # noqa: F401 from oci.decorators import init_model_state_from_kwargs @init_model_state_from_kwargs class ChangeSecurityRecipeCompartmentDetails(object): """ The compartment for the security zone recipe """ def __init__(self, **kwargs): """ Initializes a new ChangeSecurityRecipeCompartmentDetails object with values from keyword arguments. The following keyword arguments are supported (corresponding to the getters/setters of this class): :param compartment_id: The value to assign to the compartment_id property of this ChangeSecurityRecipeCompartmentDetails. :type compartment_id: str """ self.swagger_types = { 'compartment_id': 'str' } self.attribute_map = { 'compartment_id': 'compartmentId' } self._compartment_id = None @property def compartment_id(self): """ **[Required]** Gets the compartment_id of this ChangeSecurityRecipeCompartmentDetails. The `OCID`__ of the compartment into which the resource should be moved. __ https://docs.cloud.oracle.com/Content/General/Concepts/identifiers.htm :return: The compartment_id of this ChangeSecurityRecipeCompartmentDetails. :rtype: str """ return self._compartment_id @compartment_id.setter def compartment_id(self, compartment_id): """ Sets the compartment_id of this ChangeSecurityRecipeCompartmentDetails. The `OCID`__ of the compartment into which the resource should be moved. __ https://docs.cloud.oracle.com/Content/General/Concepts/identifiers.htm :param compartment_id: The compartment_id of this ChangeSecurityRecipeCompartmentDetails. :type: str """ self._compartment_id = compartment_id def __repr__(self): return formatted_flat_dict(self) def __eq__(self, other): if other is None: return False return self.__dict__ == other.__dict__ def __ne__(self, other): return not self == other
33.298701
245
0.691108
from oci.util import formatted_flat_dict, NONE_SENTINEL, value_allowed_none_or_none_sentinel from oci.decorators import init_model_state_from_kwargs @init_model_state_from_kwargs class ChangeSecurityRecipeCompartmentDetails(object): def __init__(self, **kwargs): self.swagger_types = { 'compartment_id': 'str' } self.attribute_map = { 'compartment_id': 'compartmentId' } self._compartment_id = None @property def compartment_id(self): return self._compartment_id @compartment_id.setter def compartment_id(self, compartment_id): self._compartment_id = compartment_id def __repr__(self): return formatted_flat_dict(self) def __eq__(self, other): if other is None: return False return self.__dict__ == other.__dict__ def __ne__(self, other): return not self == other
true
true
1c3951895d68db584912d0df9d55f2d91408dd34
24,475
py
Python
scale/data/models.py
kaydoh/scale
1b6a3b879ffe83e10d3b9d9074835a4c3bf476ee
[ "Apache-2.0" ]
121
2015-11-18T18:15:33.000Z
2022-03-10T01:55:00.000Z
scale/data/models.py
kaydoh/scale
1b6a3b879ffe83e10d3b9d9074835a4c3bf476ee
[ "Apache-2.0" ]
1,415
2015-12-23T23:36:04.000Z
2022-01-07T14:10:09.000Z
scale/data/models.py
kaydoh/scale
1b6a3b879ffe83e10d3b9d9074835a4c3bf476ee
[ "Apache-2.0" ]
66
2015-12-03T20:38:56.000Z
2020-07-27T15:28:11.000Z
"""Defines the database models for datasets""" from __future__ import absolute_import, unicode_literals import copy import logging from collections import namedtuple import django.contrib.postgres.fields from django.db import models, transaction from django.db.models import Q, Count from data.data import data_util from data.data.json.data_v6 import convert_data_to_v6_json, DataV6 from data.data.exceptions import InvalidData from data.data.value import FileValue from data.dataset.dataset import DataSetDefinition from data.dataset.json.dataset_v6 import convert_definition_to_v6_json, DataSetDefinitionV6 from data.exceptions import InvalidDataSetDefinition, InvalidDataSetMember from data.serializers import DataSetFileSerializerV6, DataSetMemberSerializerV6 from storage.models import ScaleFile from util import rest as rest_utils from util.database import alphabetize logger = logging.getLogger(__name__) DataSetValidation = namedtuple('DataSetValidation', ['is_valid', 'errors', 'warnings']) # DataSetKey = namedtuple('DataSetKey', ['name', 'version']) class DataSetManager(models.Manager): """Provides additional methods for handling datasets""" def create_dataset_v6(self, definition, title=None, description=None): """Creates and returns a new dataset for the given name/title/description/definition/version?? :param definition: Parameter definition of the dataset :type definition: :class:`data.dataset.dataset.DataSetDefinition` :param title: Optional title of the dataset :type title: string :param description: Optional description of the dataset :type description: string :returns: The new dataset :rtype: :class:`data.models.DataSet` :raises :class:`data.exceptions.InvalidDataSet`: If a give dataset has an invalid value """ if not definition: definition = DataSetDefinition(definition={}) dataset = DataSet() dataset.title = title dataset.description = description dataset.definition = definition.get_dict() dataset.save() return dataset def get_details_v6(self, dataset_id): """Gets additional details for the given dataset id :returns: The full dataset for the given id :rtype: :class:`data.models.DataSet` """ ds = DataSet.objects.get(pk=dataset_id) ds.files = DataSetFile.objects.get_dataset_files(ds.id) return ds def get_datasets_v6(self, started=None, ended=None, dataset_ids=None, keywords=None, order=None): """Handles retrieving datasets - possibly filtered and ordered :returns: The list of datasets that match the given filters :rtype: [:class:`data.models.DataSet`] """ return self.filter_datasets(started=started, ended=ended, dataset_ids=dataset_ids, keywords=keywords, order=order) def filter_datasets(self, started=None, ended=None, dataset_ids=None, keywords=None, order=None): """Returns a query for dataset models that filters on the given fields :param started: Query datasets created after this amount of time. :type started: :class:`datetime.datetime` :param ended: Query datasets created before this amount of time. :type ended: :class:`datetime.datetime` :param dataset_ids: Query datasets assciated with the given id(s) :type dataset_ids: :func:`list` :param keywords: Query datasets with title or description matching one of the specified keywords :type keywords: :func:`list` :param order: A list of fields to control the sort order. :type order: :func:`list` :returns: The dataset query :rtype: :class:`django.db.models.QuerySet` """ # Fetch a list of the datasets datasets = self.all() # Apply time range filtering if started: datasets = datasets.filter(created__gte=started) if ended: datasets = datasets.filter(created__lte=ended) # Apply additional filters if dataset_ids: datasets = datasets.filter(id__in=dataset_ids) # Execute a sub-query that returns distinct job type names that match the provided filter arguments if keywords: key_query = Q() for keyword in keywords: key_query |= Q(title__icontains=keyword) key_query |= Q(description__icontains=keyword) datasets = datasets.filter(key_query) # Apply sorting if order: ordering = alphabetize(order, DataSet.ALPHABETIZE_FIELDS) datasets = datasets.order_by(*ordering) else: datasets = datasets.order_by('id') for ds in datasets: files = DataSetFile.objects.get_file_ids(dataset_ids=[ds.id]) ds.files = len(files) return datasets def validate_dataset_v6(self, definition, title=None, description=None): """Validates the given dataset definiton :param definition: The dataset definition :type definition: dict :returns: The dataset validation :rtype: :class:`datset.models.DataSetValidation` """ is_valid = True errors = [] warnings = [] dataset_definition = None try: dataset_definition = DataSetDefinitionV6(definition=definition, do_validate=True) except InvalidDataSetDefinition as ex: is_valid = False errors.append(ex.error) message = 'Dataset definition is invalid: %s' % ex logger.info(message) pass # validate other fields return DataSetValidation(is_valid, errors, warnings) def get_dataset_files(self, dataset_id): """Returns the files associated with the given dataset :returns: The list of DataSetFiles matching the file_id :rtype: [:class:`data.models.DataSetFile`] """ files = DataSetFile.objects.get_dataset_files(dataset_id=dataset_id) return files def get_dataset_members(self, dataset_id): """Returns the members associated with the given dataset_id :returns: The list of DataSetMembers :rtype: [:class:`data.models.DataSetMember`] """ dataset = self.get(pk=dataset_id) members = DataSetMember.objects.all().filter(dataset=dataset) return members class DataSet(models.Model): """ Represents a DataSet object :keyword name: The identifying name of the dataset used by clients for queries :type name: :class:`django.db.models.CharField` :keyword version: The version of the dataset :type version: :class:`django.db.models.CharField` :keyword version_array: The version of the dataset split into SemVer integer components (major,minor,patch,prerelease) :type version_array: :func:`list` :keyword title: The human-readable title of this dataset (optional) :type title: :class:`django.db.models.CharField` :keyword description: The description of the dataset (optional) :type description: :class:`django.db.models.CharField` :keyword created: Defines the created time of the dataset :type created: :class:`django.db.models.DateTimeField` :keyword definition: Defines the dataset :type definition: class:`django.contrib.postgres.fields.JSONField` """ ALPHABETIZE_FIELDS = ['title', 'description'] title = models.CharField(blank=True, max_length=50, null=True) description = models.TextField(blank=True, null=True) created = models.DateTimeField(auto_now_add=True) definition = django.contrib.postgres.fields.JSONField(default=dict) objects = DataSetManager() def get_definition(self): """Returns the dataset definition :returns: The DataSet definition :rtype: :class:`data.dataset.dataset.DataSetDefinition` """ if isinstance(self.definition, basestring): self.definition = {} return DataSetDefinitionV6(definition=self.definition).get_definition() def get_v6_definition_json(self): """Returns the dataset definition in v6 of the JSON schema :returns: The dataset definition in v6 of the JSON schema :rtype: dict """ return rest_utils.strip_schema_version(convert_definition_to_v6_json(self.get_definition()).get_dict()) def get_dataset_definition(self): """Returns the dataset definition :returns: The dataset definition json :rtype: dict """ return self.definition def get_dataset_members_json(self): """Returns the JSON for the associated dataset members :returns: Returns the outgoing primitive representation. :rtype: dict? """ members = DataSet.objects.get_dataset_members(dataset_id=self.id) serializer = DataSetMemberSerializerV6(members, many=True) return serializer.data def get_dataset_files_json(self): """Returns the JSON for the associated dataset files :returns: Returns the outgoing primitive representation. :rtype: dict? """ files = DataSet.objects.get_dataset_files(self.id) serializer = DataSetFileSerializerV6(files, many=True) return serializer.data class Meta(object): """meta information for the db""" db_table = 'data_set' class DataSetMemberManager(models.Manager): """Provides additional methods for handling dataset members""" def build_data_list(self, template, data_started=None, data_ended=None, created_started=None, created_ended=None, source_started=None, source_ended=None, source_sensor_classes=None, source_sensors=None, source_collections=None,source_tasks=None, mod_started=None, mod_ended=None, job_type_ids=None, job_type_names=None, job_ids=None, is_published=None, is_superseded=None, file_names=None, file_name_search=None, job_outputs=None, recipe_ids=None, recipe_type_ids=None, recipe_nodes=None, batch_ids=None, order=None,file_type=None, media_type=None): """Builds a list of data dictionaries from a template and file filters :param template: The template to fill with files found through filters :type template: dict :param data_started: Query files where data started after this time. :type data_started: :class:`datetime.datetime` :param data_ended: Query files where data ended before this time. :type data_ended: :class:`datetime.datetime` :param created_started: Query files created after this time. :type created_started: :class:`datetime.datetime` :param created_ended: Query files created before this time. :type created_ended: :class:`datetime.datetime` :param source_started: Query files where source collection started after this time. :type source_started: :class:`datetime.datetime` :param source_ended: Query files where source collection ended before this time. :type source_ended: :class:`datetime.datetime` :param source_sensor_classes: Query files with the given source sensor class. :type source_sensor_classes: :func:`list` :param source_sensor: Query files with the given source sensor. :type source_sensor: :func:`list` :param source_collection: Query files with the given source class. :type source_collection: :func:`list` :param source_tasks: Query files with the given source tasks. :type source_tasks: :func:`list` :param mod_started: Query files where the last modified date is after this time. :type mod_started: :class:`datetime.datetime` :param mod_ended: Query files where the last modified date is before this time. :type mod_ended: :class:`datetime.datetime` :param job_type_ids: Query files with jobs with the given type identifier. :type job_type_ids: :func:`list` :param job_type_names: Query files with jobs with the given type name. :type job_type_names: :func:`list` :keyword job_ids: Query files with a given job id :type job_ids: :func:`list` :param is_published: Query files flagged as currently exposed for publication. :type is_published: bool :param is_superseded: Query files that have/have not been superseded. :type is_superseded: bool :param file_names: Query files with the given file names. :type file_names: :func:`list` :param file_name_search: Query files with the given string in their file name. :type file_name_search: : string :keyword job_outputs: Query files with the given job outputs :type job_outputs: :func:`list` :keyword recipe_ids: Query files with a given recipe id :type recipe_ids: :func:`list` :keyword recipe_nodes: Query files with a given recipe nodes :type recipe_nodes: :func:`list` :keyword recipe_type_ids: Query files with the given recipe types :type recipe_type_ids: :func:`list` :keyword batch_ids: Query files with batches with the given identifiers. :type batch_ids: :func:`list` :param order: A list of fields to control the sort order. :type order: :func:`list` :keyword file_type: Query files with a given file_type :type recipe_ids: :func:`list` """ files = ScaleFile.objects.filter_files( data_started=data_started, data_ended=data_ended, created_started=created_started, created_ended=created_ended, source_started=source_started, source_ended=source_ended, source_sensor_classes=source_sensor_classes, source_sensors=source_sensors, source_collections=source_collections, source_tasks=source_tasks, mod_started=mod_started, mod_ended=mod_ended, job_type_ids=job_type_ids, job_type_names=job_type_names, job_ids=job_ids, file_names=file_names, file_name_search=file_name_search, job_outputs=job_outputs, recipe_ids=recipe_ids, recipe_type_ids=recipe_type_ids, recipe_nodes=recipe_nodes, batch_ids=batch_ids, order=order,file_type=file_type,media_type=media_type) data_list = [] try: for f in files: entry = copy.deepcopy(template) file_params = entry['files'] for p in file_params: if file_params[p] == 'FILE_VALUE': file_params[p] = [f.id] data_list.append(DataV6(data=entry, do_validate=True).get_data()) except (KeyError, TypeError) as ex: raise InvalidData('INVALID_TEMPLATE', "Specified template is invalid: %s" % ex) return data_list def validate_data_list(self, dataset_def, data_list): """Validates a list of data objects against a dataset :param dataset_def: The dataset definition the member is a part of :type dataset_def: :param data_list: Data definitions of the dataset members :type data_list: [:class:`data.data.data.Data`] """ is_valid = True errors = [] warnings = [] for data in data_list: try: dataset_def.validate(data) except (InvalidData, InvalidDataSetMember) as ex: is_valid = False errors.append(ex.error) message = 'Dataset definition is invalid: %s' % ex logger.info(message) pass # validate other fields return DataSetValidation(is_valid, errors, warnings) def create_dataset_members(self, dataset, data_list): """Creates a dataset member :param dataset: The dataset the member is a part of :type dataset: :class:`data.models.DataSet` :param data_list: Data definitions of the dataset members :type data_list: [:class:`data.data.data.Data`] """ with transaction.atomic(): dataset_members = [] datasetfiles = [] existing_scale_ids = DataSetFile.objects.get_file_ids(dataset_ids=[dataset.id]) for d in data_list: dataset_member = DataSetMember() dataset_member.dataset = dataset dataset_member.data = convert_data_to_v6_json(d).get_dict() dataset_member.file_ids = list(data_util.get_file_ids(d)) dataset_members.append(dataset_member) datasetfiles.extend(DataSetFile.objects.create_dataset_files(dataset, d, existing_scale_ids)) existing_scale_ids.append(dataset_member.file_ids) DataSetFile.objects.bulk_create(datasetfiles) return DataSetMember.objects.bulk_create(dataset_members) def get_dataset_members(self, dataset): """Returns dataset members for the given dataset :returns: members for a given dataset :rtype: QuerySet<DataSetMember> """ return self.all().filter(dataset=dataset).order_by('id') def get_details_v6(self, dsm_id): """Gets additional details for the given dataset member id :returns: The full dataset member for the given id :rtype: :class:`data.models.DataSetMember` """ dsm = DataSetMember.objects.get(pk=dsm_id) dsm.files = DataSetFile.objects.filter(dataset=dsm.dataset, scale_file_id__in=list(dsm.file_ids)) return dsm class DataSetMember(models.Model): """ Defines the data of a dataset? contains list/descriptors of DataFiles :keyword dataset: Refers to dataset member belongs to :type dataset: :class:`django.db.models.ForeignKey` :keyword data: JSON description of the data in this DataSetMember. :type data: :class: `django.contrib.postgres.fields.JSONField(default=dict)` :keyword created: Created Time :type created: datetime """ dataset = models.ForeignKey('data.DataSet', on_delete=models.PROTECT) data = django.contrib.postgres.fields.JSONField(default=dict) file_ids = django.contrib.postgres.fields.ArrayField(models.IntegerField(null=True)) created = models.DateTimeField(auto_now_add=True) objects = DataSetMemberManager() def get_dataset_definition(self): """Returns the dataset definition :returns: The dataset definition :rtype: :class:`data.dataset.dataset.DataSetDefinition` """ return self.dataset.get_definition() def get_data(self): """Returns the data for this datasetmember :returns: The data for this datasetmember :rtype: :class:`data.data.data.Data` """ return DataV6(data=self.data, do_validate=False).get_data() def get_v6_data_json(self): """Returns the data for this datasetmember as v6 json with the version stripped :returns: The v6 JSON output data dict for this datasetmember :rtype: dict """ return rest_utils.strip_schema_version(convert_data_to_v6_json(self.get_data()).get_dict()) class Meta(object): """meta information for the db""" db_table = 'data_set_member' class DataSetFileManager(models.Manager): """Manages the datasetfile model""" def create_dataset_files(self, dataset, data, existing_scale_ids): """Creates dataset files for the given dataset and data""" datasetfiles = [] for i in data.values.keys(): v = data.values[i] if type(v) is FileValue: for id in v.file_ids: if id in existing_scale_ids: continue file = DataSetFile() file.dataset = dataset file.scale_file = ScaleFile.objects.get(pk=id) file.parameter_name = i datasetfiles.append(file) return datasetfiles def get_file_ids(self, dataset_ids, parameter_names=None): """Returns a list of the file IDs for the given datasets, optionally filtered by parameter_name. :param dataset_ids: The ids of the associated datasets :type dataset_ids: integer :param parameter_names: The parameter names to search for in the given datasets :type parameter_names: string :returns: The list of scale file IDs :rtype: :func:`list` """ query = self.all().filter(dataset_id__in=list(dataset_ids)) if parameter_names: query = query.filter(parameter_name__in=list(parameter_names)) return [result.scale_file_id for result in query.only('scale_file_id').distinct()] def get_dataset_ids(self, file_ids, all_files=False): """Returns a list of the dataset IDs that contain the given files :param file_ids: The ids of the files to look for :type dataset_id: integer :param all_files: Whether or not a dataset must contain all files or just some of the files in the list :type all_files: bool :returns: The list of dataset IDs :rtype: :func:`list` """ results = [] if not all_files: query = self.all().filter(scale_file_id__in=list(file_ids)).only('dataset_id').distinct() results = [result.dataset_id for result in query] else: query = self.all().filter(scale_file_id__in=list(file_ids)).values('dataset_id').annotate(total=Count('dataset_id')).order_by('total') for result in query: if result['total'] == len(file_ids): results.append(result['dataset_id']) return results def get_files(self, dataset_ids, parameter_names=None): """Returns the dataset files associated with the given dataset_ids :param dataset_ids: The ids of the associated datasets :type dataset_ids: integer :param parameter_names: The parameter names to search for in the given datasets :type parameter_names: string :returns: The DataSetFiles associated with that dataset_id :rtype: [:class:`data.models.DataSetFile`] """ files = self.all().filter(dataset_id__in=list(dataset_ids)) if parameter_names: files = files.filter(parameter_name__in=list(parameter_names)) return files def get_datasets(self, file_ids, all_files=False): """Returns the datasets associated with the given file_id :param file_id: The id of the associated file :type file_id: integer :param all_files: Whether or not a dataset must contain all files or just some of the files in the list :type all_files: bool :returns: The DataSets associated with that dataset_id :rtype: [:class:`data.models.DataSet`] """ dataset_ids = self.get_dataset_ids(file_ids=file_ids, all_files=all_files) datasets = DataSet.objects.filter(id__in=dataset_ids) return datasets def get_dataset_files(self, dataset_id): """Returns the dataset files associated with the given dataset_id :param dataset_id: The id of the associated dataset :type dataset_id: integer :returns: The DataSetFiles associated with that dataset_id :rtype: [:class:`data.models.DataSetFile`] """ files = DataSetFile.objects.filter(dataset_id=dataset_id) return files class DataSetFile(models.Model): """ The actual file in a dataset member :keyword dataset: Refers to the dataset the file is a member of :type dataset: :class:`django.db.models.ForeignKey` :keyword scale_file: Refers to the ScaleFile :type scale_file: :class:`django.db.models.ForeignKey` :keyword parameter_name: Refers to the File parameter name :type parameter_name: :class:`django.db.models.CharField` """ dataset = models.ForeignKey('data.DataSet', on_delete=models.PROTECT) scale_file = models.ForeignKey('storage.ScaleFile', on_delete=models.PROTECT) parameter_name = models.CharField(db_index=True, max_length=50) objects = DataSetFileManager() class Meta(object): """meta information for the db""" db_table = 'data_set_file' unique_together = ("dataset", "scale_file")
41.134454
160
0.671175
from __future__ import absolute_import, unicode_literals import copy import logging from collections import namedtuple import django.contrib.postgres.fields from django.db import models, transaction from django.db.models import Q, Count from data.data import data_util from data.data.json.data_v6 import convert_data_to_v6_json, DataV6 from data.data.exceptions import InvalidData from data.data.value import FileValue from data.dataset.dataset import DataSetDefinition from data.dataset.json.dataset_v6 import convert_definition_to_v6_json, DataSetDefinitionV6 from data.exceptions import InvalidDataSetDefinition, InvalidDataSetMember from data.serializers import DataSetFileSerializerV6, DataSetMemberSerializerV6 from storage.models import ScaleFile from util import rest as rest_utils from util.database import alphabetize logger = logging.getLogger(__name__) DataSetValidation = namedtuple('DataSetValidation', ['is_valid', 'errors', 'warnings']) class DataSetManager(models.Manager): def create_dataset_v6(self, definition, title=None, description=None): if not definition: definition = DataSetDefinition(definition={}) dataset = DataSet() dataset.title = title dataset.description = description dataset.definition = definition.get_dict() dataset.save() return dataset def get_details_v6(self, dataset_id): ds = DataSet.objects.get(pk=dataset_id) ds.files = DataSetFile.objects.get_dataset_files(ds.id) return ds def get_datasets_v6(self, started=None, ended=None, dataset_ids=None, keywords=None, order=None): return self.filter_datasets(started=started, ended=ended, dataset_ids=dataset_ids, keywords=keywords, order=order) def filter_datasets(self, started=None, ended=None, dataset_ids=None, keywords=None, order=None): datasets = self.all() if started: datasets = datasets.filter(created__gte=started) if ended: datasets = datasets.filter(created__lte=ended) if dataset_ids: datasets = datasets.filter(id__in=dataset_ids) if keywords: key_query = Q() for keyword in keywords: key_query |= Q(title__icontains=keyword) key_query |= Q(description__icontains=keyword) datasets = datasets.filter(key_query) if order: ordering = alphabetize(order, DataSet.ALPHABETIZE_FIELDS) datasets = datasets.order_by(*ordering) else: datasets = datasets.order_by('id') for ds in datasets: files = DataSetFile.objects.get_file_ids(dataset_ids=[ds.id]) ds.files = len(files) return datasets def validate_dataset_v6(self, definition, title=None, description=None): is_valid = True errors = [] warnings = [] dataset_definition = None try: dataset_definition = DataSetDefinitionV6(definition=definition, do_validate=True) except InvalidDataSetDefinition as ex: is_valid = False errors.append(ex.error) message = 'Dataset definition is invalid: %s' % ex logger.info(message) pass return DataSetValidation(is_valid, errors, warnings) def get_dataset_files(self, dataset_id): files = DataSetFile.objects.get_dataset_files(dataset_id=dataset_id) return files def get_dataset_members(self, dataset_id): dataset = self.get(pk=dataset_id) members = DataSetMember.objects.all().filter(dataset=dataset) return members class DataSet(models.Model): ALPHABETIZE_FIELDS = ['title', 'description'] title = models.CharField(blank=True, max_length=50, null=True) description = models.TextField(blank=True, null=True) created = models.DateTimeField(auto_now_add=True) definition = django.contrib.postgres.fields.JSONField(default=dict) objects = DataSetManager() def get_definition(self): if isinstance(self.definition, basestring): self.definition = {} return DataSetDefinitionV6(definition=self.definition).get_definition() def get_v6_definition_json(self): return rest_utils.strip_schema_version(convert_definition_to_v6_json(self.get_definition()).get_dict()) def get_dataset_definition(self): return self.definition def get_dataset_members_json(self): members = DataSet.objects.get_dataset_members(dataset_id=self.id) serializer = DataSetMemberSerializerV6(members, many=True) return serializer.data def get_dataset_files_json(self): files = DataSet.objects.get_dataset_files(self.id) serializer = DataSetFileSerializerV6(files, many=True) return serializer.data class Meta(object): db_table = 'data_set' class DataSetMemberManager(models.Manager): def build_data_list(self, template, data_started=None, data_ended=None, created_started=None, created_ended=None, source_started=None, source_ended=None, source_sensor_classes=None, source_sensors=None, source_collections=None,source_tasks=None, mod_started=None, mod_ended=None, job_type_ids=None, job_type_names=None, job_ids=None, is_published=None, is_superseded=None, file_names=None, file_name_search=None, job_outputs=None, recipe_ids=None, recipe_type_ids=None, recipe_nodes=None, batch_ids=None, order=None,file_type=None, media_type=None): files = ScaleFile.objects.filter_files( data_started=data_started, data_ended=data_ended, created_started=created_started, created_ended=created_ended, source_started=source_started, source_ended=source_ended, source_sensor_classes=source_sensor_classes, source_sensors=source_sensors, source_collections=source_collections, source_tasks=source_tasks, mod_started=mod_started, mod_ended=mod_ended, job_type_ids=job_type_ids, job_type_names=job_type_names, job_ids=job_ids, file_names=file_names, file_name_search=file_name_search, job_outputs=job_outputs, recipe_ids=recipe_ids, recipe_type_ids=recipe_type_ids, recipe_nodes=recipe_nodes, batch_ids=batch_ids, order=order,file_type=file_type,media_type=media_type) data_list = [] try: for f in files: entry = copy.deepcopy(template) file_params = entry['files'] for p in file_params: if file_params[p] == 'FILE_VALUE': file_params[p] = [f.id] data_list.append(DataV6(data=entry, do_validate=True).get_data()) except (KeyError, TypeError) as ex: raise InvalidData('INVALID_TEMPLATE', "Specified template is invalid: %s" % ex) return data_list def validate_data_list(self, dataset_def, data_list): is_valid = True errors = [] warnings = [] for data in data_list: try: dataset_def.validate(data) except (InvalidData, InvalidDataSetMember) as ex: is_valid = False errors.append(ex.error) message = 'Dataset definition is invalid: %s' % ex logger.info(message) pass return DataSetValidation(is_valid, errors, warnings) def create_dataset_members(self, dataset, data_list): with transaction.atomic(): dataset_members = [] datasetfiles = [] existing_scale_ids = DataSetFile.objects.get_file_ids(dataset_ids=[dataset.id]) for d in data_list: dataset_member = DataSetMember() dataset_member.dataset = dataset dataset_member.data = convert_data_to_v6_json(d).get_dict() dataset_member.file_ids = list(data_util.get_file_ids(d)) dataset_members.append(dataset_member) datasetfiles.extend(DataSetFile.objects.create_dataset_files(dataset, d, existing_scale_ids)) existing_scale_ids.append(dataset_member.file_ids) DataSetFile.objects.bulk_create(datasetfiles) return DataSetMember.objects.bulk_create(dataset_members) def get_dataset_members(self, dataset): return self.all().filter(dataset=dataset).order_by('id') def get_details_v6(self, dsm_id): dsm = DataSetMember.objects.get(pk=dsm_id) dsm.files = DataSetFile.objects.filter(dataset=dsm.dataset, scale_file_id__in=list(dsm.file_ids)) return dsm class DataSetMember(models.Model): dataset = models.ForeignKey('data.DataSet', on_delete=models.PROTECT) data = django.contrib.postgres.fields.JSONField(default=dict) file_ids = django.contrib.postgres.fields.ArrayField(models.IntegerField(null=True)) created = models.DateTimeField(auto_now_add=True) objects = DataSetMemberManager() def get_dataset_definition(self): return self.dataset.get_definition() def get_data(self): return DataV6(data=self.data, do_validate=False).get_data() def get_v6_data_json(self): return rest_utils.strip_schema_version(convert_data_to_v6_json(self.get_data()).get_dict()) class Meta(object): db_table = 'data_set_member' class DataSetFileManager(models.Manager): def create_dataset_files(self, dataset, data, existing_scale_ids): datasetfiles = [] for i in data.values.keys(): v = data.values[i] if type(v) is FileValue: for id in v.file_ids: if id in existing_scale_ids: continue file = DataSetFile() file.dataset = dataset file.scale_file = ScaleFile.objects.get(pk=id) file.parameter_name = i datasetfiles.append(file) return datasetfiles def get_file_ids(self, dataset_ids, parameter_names=None): query = self.all().filter(dataset_id__in=list(dataset_ids)) if parameter_names: query = query.filter(parameter_name__in=list(parameter_names)) return [result.scale_file_id for result in query.only('scale_file_id').distinct()] def get_dataset_ids(self, file_ids, all_files=False): results = [] if not all_files: query = self.all().filter(scale_file_id__in=list(file_ids)).only('dataset_id').distinct() results = [result.dataset_id for result in query] else: query = self.all().filter(scale_file_id__in=list(file_ids)).values('dataset_id').annotate(total=Count('dataset_id')).order_by('total') for result in query: if result['total'] == len(file_ids): results.append(result['dataset_id']) return results def get_files(self, dataset_ids, parameter_names=None): files = self.all().filter(dataset_id__in=list(dataset_ids)) if parameter_names: files = files.filter(parameter_name__in=list(parameter_names)) return files def get_datasets(self, file_ids, all_files=False): dataset_ids = self.get_dataset_ids(file_ids=file_ids, all_files=all_files) datasets = DataSet.objects.filter(id__in=dataset_ids) return datasets def get_dataset_files(self, dataset_id): files = DataSetFile.objects.filter(dataset_id=dataset_id) return files class DataSetFile(models.Model): dataset = models.ForeignKey('data.DataSet', on_delete=models.PROTECT) scale_file = models.ForeignKey('storage.ScaleFile', on_delete=models.PROTECT) parameter_name = models.CharField(db_index=True, max_length=50) objects = DataSetFileManager() class Meta(object): db_table = 'data_set_file' unique_together = ("dataset", "scale_file")
true
true
1c395295389303bc1d6b9b1cf2f5f624ba63beff
1,850
py
Python
setup.py
maksyuki/TaichiGAME
647d08d3d31b209314ec0dfec5270c565b2f6a61
[ "MIT" ]
37
2021-12-30T02:03:11.000Z
2022-03-21T11:37:52.000Z
setup.py
maksyuki/TaichiGame
647d08d3d31b209314ec0dfec5270c565b2f6a61
[ "MIT" ]
2
2022-01-09T13:04:04.000Z
2022-01-11T06:47:43.000Z
setup.py
maksyuki/TaichiGame
647d08d3d31b209314ec0dfec5270c565b2f6a61
[ "MIT" ]
2
2022-01-03T06:52:23.000Z
2022-01-11T06:31:30.000Z
import setuptools with open("README.md", "r", encoding="utf-8") as fh: long_description = fh.read() setuptools.setup( name="TaichiGAME", version="0.0.3", author="maksyuki", author_email="maksyuki@126.com", description="GPU Accelerated Motion Engine based on Taichi Lang", long_description=long_description, long_description_content_type="text/markdown", url="https://github.com/maksyuki/TaichiGAME", project_urls={ 'Documentation': 'https://github.com/maksyuki/TaichiGAME', 'Funding': 'https://donate.pypi.org', 'Say Thanks!': 'http://saythanks.io/to/example', 'Source': 'https://github.com/maksyuki/TaichiGAME', 'Tracker': 'https://github.com/maksyuki/TaichiGAME/issues', }, classifiers=[ 'Development Status :: 2 - Pre-Alpha', 'License :: OSI Approved :: MIT License', 'Operating System :: POSIX', 'Operating System :: MacOS :: MacOS X', 'Operating System :: Microsoft :: Windows', 'Programming Language :: Python :: 3.7', 'Programming Language :: Python :: 3.8', 'Programming Language :: Python :: 3.9', 'Intended Audience :: Science/Research', 'Intended Audience :: Developers', 'Framework :: Robot Framework :: Library', 'Topic :: Games/Entertainment :: Simulation', 'Topic :: Multimedia :: Graphics', 'Topic :: Scientific/Engineering :: Physics', 'Topic :: Scientific/Engineering :: Visualization', 'Topic :: Software Development :: Libraries :: Application Frameworks' ], license='MIT', keywords=['phyics engine', 'dynamics simulation', 'robot motion control'], packages=setuptools.find_packages(exclude=['tests']), include_package_data=True, install_requires=['taichi'], python_requires=">=3.7,<3.10", )
40.217391
78
0.636216
import setuptools with open("README.md", "r", encoding="utf-8") as fh: long_description = fh.read() setuptools.setup( name="TaichiGAME", version="0.0.3", author="maksyuki", author_email="maksyuki@126.com", description="GPU Accelerated Motion Engine based on Taichi Lang", long_description=long_description, long_description_content_type="text/markdown", url="https://github.com/maksyuki/TaichiGAME", project_urls={ 'Documentation': 'https://github.com/maksyuki/TaichiGAME', 'Funding': 'https://donate.pypi.org', 'Say Thanks!': 'http://saythanks.io/to/example', 'Source': 'https://github.com/maksyuki/TaichiGAME', 'Tracker': 'https://github.com/maksyuki/TaichiGAME/issues', }, classifiers=[ 'Development Status :: 2 - Pre-Alpha', 'License :: OSI Approved :: MIT License', 'Operating System :: POSIX', 'Operating System :: MacOS :: MacOS X', 'Operating System :: Microsoft :: Windows', 'Programming Language :: Python :: 3.7', 'Programming Language :: Python :: 3.8', 'Programming Language :: Python :: 3.9', 'Intended Audience :: Science/Research', 'Intended Audience :: Developers', 'Framework :: Robot Framework :: Library', 'Topic :: Games/Entertainment :: Simulation', 'Topic :: Multimedia :: Graphics', 'Topic :: Scientific/Engineering :: Physics', 'Topic :: Scientific/Engineering :: Visualization', 'Topic :: Software Development :: Libraries :: Application Frameworks' ], license='MIT', keywords=['phyics engine', 'dynamics simulation', 'robot motion control'], packages=setuptools.find_packages(exclude=['tests']), include_package_data=True, install_requires=['taichi'], python_requires=">=3.7,<3.10", )
true
true
1c39529af27c755a11f591ced76bc5b85c5600df
5,601
py
Python
tests/mock_objects.py
jmuilwijk/DiscordBot
63cbb3e96d473b24ecc2928fd5e65ab0e4fec4a8
[ "MIT" ]
3
2018-11-29T23:31:22.000Z
2019-05-15T12:13:05.000Z
tests/mock_objects.py
jmuilwijk/DiscordBot
63cbb3e96d473b24ecc2928fd5e65ab0e4fec4a8
[ "MIT" ]
1
2018-12-13T21:07:13.000Z
2018-12-13T21:07:13.000Z
tests/mock_objects.py
jmuilwijk/DiscordBot
63cbb3e96d473b24ecc2928fd5e65ab0e4fec4a8
[ "MIT" ]
2
2019-05-26T15:49:24.000Z
2019-07-31T21:13:49.000Z
""" Module containing mocked objects of discord.py """ # Builtin import collections import itertools import unittest.mock from asyncio import AbstractEventLoop from aiohttp import ClientSession # pip import discord from discord.ext.commands import Context # Locals from KonekoBot import Koneko class CustomMock: """Class to assign some commonly used functionality.""" spec_set = None discord_id = itertools.count(0) def __init__(self, **kwargs): name = kwargs.pop('name', None) super().__init__(spec_set=self.spec_set, **kwargs) if name: self.name = name # Create a `discord.Guild` instance guild_data = { 'id': 1, 'name': 'guild', 'region': 'Europe', 'verification_level': 2, 'default_notications': 1, 'afk_timeout': 100, 'icon': "icon.png", 'banner': 'banner.png', 'mfa_level': 1, 'splash': 'splash.png', 'system_channel_id': 657571218324586499, 'description': 'description', 'max_presences': 10_000, 'max_members': 100_000, 'preferred_locale': 'UTC', 'owner_id': 1, 'afk_channel_id': 657571218324586499, } guild_instance = discord.Guild(data=guild_data, state=unittest.mock.MagicMock()) class MockGuild(unittest.mock.Mock): """A mock subclass to mock `discord.Guild` objects.""" spec_set = guild_instance # Create a `discord.Role` instance role_data = {'name': 'role', 'display_name': 'user', 'id': 1} role_instance = discord.Role(guild=guild_instance, state=unittest.mock.MagicMock(), data=role_data) class MockRole(CustomMock, unittest.mock.Mock): """A mock subclass to mock `discord.Role` objects.""" spec_set = role_instance def __init__(self, **kwargs) -> None: default_kwargs = { 'id': next(self.discord_id), 'name': 'role', 'position': 1, 'colour': discord.Colour(0xdeadbf), 'permissions': discord.Permissions(), } super().__init__(**collections.ChainMap(kwargs, default_kwargs)) # Create a `discord.Member` instance member_data = {'user': 'mrjamy', 'roles': [1]} member_instance = discord.Member(data=member_data, guild=guild_instance, state=unittest.mock.MagicMock()) class MockMember(CustomMock, unittest.mock.Mock): """A mock subclass to mock `discord.Member` objects.""" def __init__(self, roles=None, **kwargs) -> None: default_kwargs = {'name': 'member', 'display_name': 'user', 'id': next(self.discord_id), 'bot': False} super().__init__(**collections.ChainMap(kwargs, default_kwargs)) self.roles = [MockRole(name="@everyone", position=1, id=0)] if roles: self.roles.extend(roles) if 'mention' not in kwargs: self.mention = f"@{self.name}" def __str__(self) -> str: return self.name spec_set = member_instance # Create a User instance to get a realistic Mock of `discord.User` user_instance = discord.User(data=unittest.mock.MagicMock(), state=unittest.mock.MagicMock()) class MockUser(CustomMock, unittest.mock.Mock): """A mock subclass to mock `discord.User` objects.""" spec_set = user_instance def __init__(self, **kwargs) -> None: default_kwargs = {'name': 'user', 'display_name': 'user', 'id': next(self.discord_id), 'bot': False} super().__init__(**collections.ChainMap(kwargs, default_kwargs)) if 'mention' not in kwargs: self.mention = f"@{self.name}" def __str__(self) -> str: return self.name def _get_mock_loop() -> unittest.mock.Mock: """Return a mocked asyncio.AbstractEventLoop.""" loop = unittest.mock.create_autospec(spec=AbstractEventLoop, spec_set=True) loop.create_task.side_effect = lambda coroutine: coroutine.close() return loop class MockBot(unittest.mock.MagicMock): """A mock subclass to mock `discord.ext.commands.AutoShardedBot` objects.""" spec_set = Koneko(command_prefix=unittest.mock.MagicMock(), loop=_get_mock_loop()) def __init__(self, **kwargs) -> None: super().__init__(**kwargs) self.loop = _get_mock_loop() self.http_session = unittest.mock.create_autospec(spec=ClientSession, spec_set=True) # Create a `discord.TextChannel` instance channel_data = { 'id': 1, 'type': 'TextChannel', 'name': 'channel', 'parent_id': 657571218324586497, 'topic': 'topic', 'position': 1, 'nsfw': False, 'last_message_id': 1, } channel_instance = discord.TextChannel(state=unittest.mock.MagicMock(), guild=unittest.mock.MagicMock(), data=channel_data) class MockTextChannel(unittest.mock.AsyncMock): """A mock subclass to mock `discord.TextChannel` objects.""" spec_set = channel_instance # Create a `discord.ext.commands.Context` instance context_instance = Context(message=unittest.mock.MagicMock(), prefix=unittest.mock.MagicMock()) class MockContext(unittest.mock.Mock): """A mock subclass to mock `discord.ext.commands.Context` objects.""" spec_set = context_instance def __init__(self, **kwargs) -> None: super().__init__(**kwargs) self.bot = kwargs.get('bot', MockBot()) self.guild = kwargs.get('guild', MockGuild()) self.author = kwargs.get('author', MockMember()) self.channel = kwargs.get('channel', MockTextChannel())
29.951872
99
0.636851
import collections import itertools import unittest.mock from asyncio import AbstractEventLoop from aiohttp import ClientSession import discord from discord.ext.commands import Context from KonekoBot import Koneko class CustomMock: spec_set = None discord_id = itertools.count(0) def __init__(self, **kwargs): name = kwargs.pop('name', None) super().__init__(spec_set=self.spec_set, **kwargs) if name: self.name = name guild_data = { 'id': 1, 'name': 'guild', 'region': 'Europe', 'verification_level': 2, 'default_notications': 1, 'afk_timeout': 100, 'icon': "icon.png", 'banner': 'banner.png', 'mfa_level': 1, 'splash': 'splash.png', 'system_channel_id': 657571218324586499, 'description': 'description', 'max_presences': 10_000, 'max_members': 100_000, 'preferred_locale': 'UTC', 'owner_id': 1, 'afk_channel_id': 657571218324586499, } guild_instance = discord.Guild(data=guild_data, state=unittest.mock.MagicMock()) class MockGuild(unittest.mock.Mock): spec_set = guild_instance role_data = {'name': 'role', 'display_name': 'user', 'id': 1} role_instance = discord.Role(guild=guild_instance, state=unittest.mock.MagicMock(), data=role_data) class MockRole(CustomMock, unittest.mock.Mock): spec_set = role_instance def __init__(self, **kwargs) -> None: default_kwargs = { 'id': next(self.discord_id), 'name': 'role', 'position': 1, 'colour': discord.Colour(0xdeadbf), 'permissions': discord.Permissions(), } super().__init__(**collections.ChainMap(kwargs, default_kwargs)) member_data = {'user': 'mrjamy', 'roles': [1]} member_instance = discord.Member(data=member_data, guild=guild_instance, state=unittest.mock.MagicMock()) class MockMember(CustomMock, unittest.mock.Mock): def __init__(self, roles=None, **kwargs) -> None: default_kwargs = {'name': 'member', 'display_name': 'user', 'id': next(self.discord_id), 'bot': False} super().__init__(**collections.ChainMap(kwargs, default_kwargs)) self.roles = [MockRole(name="@everyone", position=1, id=0)] if roles: self.roles.extend(roles) if 'mention' not in kwargs: self.mention = f"@{self.name}" def __str__(self) -> str: return self.name spec_set = member_instance user_instance = discord.User(data=unittest.mock.MagicMock(), state=unittest.mock.MagicMock()) class MockUser(CustomMock, unittest.mock.Mock): spec_set = user_instance def __init__(self, **kwargs) -> None: default_kwargs = {'name': 'user', 'display_name': 'user', 'id': next(self.discord_id), 'bot': False} super().__init__(**collections.ChainMap(kwargs, default_kwargs)) if 'mention' not in kwargs: self.mention = f"@{self.name}" def __str__(self) -> str: return self.name def _get_mock_loop() -> unittest.mock.Mock: loop = unittest.mock.create_autospec(spec=AbstractEventLoop, spec_set=True) loop.create_task.side_effect = lambda coroutine: coroutine.close() return loop class MockBot(unittest.mock.MagicMock): spec_set = Koneko(command_prefix=unittest.mock.MagicMock(), loop=_get_mock_loop()) def __init__(self, **kwargs) -> None: super().__init__(**kwargs) self.loop = _get_mock_loop() self.http_session = unittest.mock.create_autospec(spec=ClientSession, spec_set=True) channel_data = { 'id': 1, 'type': 'TextChannel', 'name': 'channel', 'parent_id': 657571218324586497, 'topic': 'topic', 'position': 1, 'nsfw': False, 'last_message_id': 1, } channel_instance = discord.TextChannel(state=unittest.mock.MagicMock(), guild=unittest.mock.MagicMock(), data=channel_data) class MockTextChannel(unittest.mock.AsyncMock): spec_set = channel_instance context_instance = Context(message=unittest.mock.MagicMock(), prefix=unittest.mock.MagicMock()) class MockContext(unittest.mock.Mock): spec_set = context_instance def __init__(self, **kwargs) -> None: super().__init__(**kwargs) self.bot = kwargs.get('bot', MockBot()) self.guild = kwargs.get('guild', MockGuild()) self.author = kwargs.get('author', MockMember()) self.channel = kwargs.get('channel', MockTextChannel())
true
true
1c3953de6c5b5802e6221ab2d6af6d68757d930e
498
py
Python
yardstick/service/__init__.py
upfront710/yardstick
2c3898f2ca061962cedbfc7435f78b59aa39b097
[ "Apache-2.0" ]
28
2017-02-07T07:46:42.000Z
2021-06-30T08:11:06.000Z
yardstick/service/__init__.py
upfront710/yardstick
2c3898f2ca061962cedbfc7435f78b59aa39b097
[ "Apache-2.0" ]
6
2018-01-18T08:00:54.000Z
2019-04-11T04:51:41.000Z
yardstick/service/__init__.py
upfront710/yardstick
2c3898f2ca061962cedbfc7435f78b59aa39b097
[ "Apache-2.0" ]
46
2016-12-13T10:05:47.000Z
2021-02-18T07:33:06.000Z
############################################################################## # Copyright (c) 2016 Huawei Technologies Co.,Ltd and others. # # All rights reserved. This program and the accompanying materials # are made available under the terms of the Apache License, Version 2.0 # which accompanies this distribution, and is available at # http://www.apache.org/licenses/LICENSE-2.0 ############################################################################## class Service(object): pass
38.307692
78
0.522088
true
true
1c3955cfd469102938ead8fe91221387a47491ec
1,087
py
Python
tests/test_fluid_lists.py
portyanikhin/PyFluids
c570c6708f88d24fb3100d90b81271c3171cd87b
[ "MIT" ]
null
null
null
tests/test_fluid_lists.py
portyanikhin/PyFluids
c570c6708f88d24fb3100d90b81271c3171cd87b
[ "MIT" ]
null
null
null
tests/test_fluid_lists.py
portyanikhin/PyFluids
c570c6708f88d24fb3100d90b81271c3171cd87b
[ "MIT" ]
1
2021-08-08T01:36:59.000Z
2021-08-08T01:36:59.000Z
# PyFluids # Copyright (c) 2021 Vladimir Portyanikhin import pytest from pyfluids import * fluid_list = ( list(PureFluids) + list(IncompPureFluids) + list(IncompMixturesMF) + list(IncompMixturesVF) ) class TestFluidLists: @pytest.mark.parametrize("name", fluid_list) def test_coolprop_name(self, name): try: assert name.coolprop_name == { PureFluids.cis2Butene: "cis-2-Butene", PureFluids.nDecane: "n-Decane", PureFluids.nNonane: "n-Nonane", PureFluids.nPropane: "n-Propane", PureFluids.nUndecane: "n-Undecane", PureFluids.R1234zeZ: "R1234ze(Z)", PureFluids.trans2Butene: "trans-2-Butene", }[name] except KeyError: return name.coolprop_name == name.name @pytest.mark.parametrize("name", fluid_list) def test_repr(self, name): assert repr(name) == name.name @pytest.mark.parametrize("name", fluid_list) def test_str(self, name): assert str(name) == name.name
27.871795
58
0.605336
import pytest from pyfluids import * fluid_list = ( list(PureFluids) + list(IncompPureFluids) + list(IncompMixturesMF) + list(IncompMixturesVF) ) class TestFluidLists: @pytest.mark.parametrize("name", fluid_list) def test_coolprop_name(self, name): try: assert name.coolprop_name == { PureFluids.cis2Butene: "cis-2-Butene", PureFluids.nDecane: "n-Decane", PureFluids.nNonane: "n-Nonane", PureFluids.nPropane: "n-Propane", PureFluids.nUndecane: "n-Undecane", PureFluids.R1234zeZ: "R1234ze(Z)", PureFluids.trans2Butene: "trans-2-Butene", }[name] except KeyError: return name.coolprop_name == name.name @pytest.mark.parametrize("name", fluid_list) def test_repr(self, name): assert repr(name) == name.name @pytest.mark.parametrize("name", fluid_list) def test_str(self, name): assert str(name) == name.name
true
true
1c39573626ef3ac70fdc9ac65ce63eb25e33fcf4
23,681
py
Python
qcodes/data/hdf5_format.py
edumur/Qcodes
ac262035c299a872995cecd210f0e84b0b85d751
[ "MIT" ]
null
null
null
qcodes/data/hdf5_format.py
edumur/Qcodes
ac262035c299a872995cecd210f0e84b0b85d751
[ "MIT" ]
62
2021-12-23T04:32:54.000Z
2022-03-31T04:28:12.000Z
qcodes/data/hdf5_format.py
emartinez/Qcodes
478af6e746f918a9e1dded7ec626484987f894d2
[ "MIT" ]
null
null
null
import json import logging import os from typing import TYPE_CHECKING import h5py import numpy as np import qcodes as qc from .data_array import DataArray from .format import Formatter if TYPE_CHECKING: from .data_set import DataSet class HDF5Format(Formatter): """ HDF5 formatter for saving qcodes datasets. Capable of storing (write) and recovering (read) qcodes datasets. """ _format_tag = 'hdf5' def close_file(self, data_set: 'DataSet'): """ Closes the hdf5 file open in the dataset. Args: data_set: DataSet object """ if hasattr(data_set, '_h5_base_group'): data_set._h5_base_group.close() # Removes reference to closed file del data_set._h5_base_group else: logging.warning( 'Cannot close file, data_set has no open hdf5 file') def _create_file(self, filepath): """ creates a hdf5 file (data_object) at a location specified by filepath """ folder, _filename = os.path.split(filepath) if not os.path.isdir(folder): os.makedirs(folder) file = h5py.File(filepath, 'a') return file def _open_file(self, data_set, location=None): if location is None: location = data_set.location filepath = self._filepath_from_location(location, io_manager=data_set.io) data_set._h5_base_group = h5py.File(filepath, 'r+') def read(self, data_set: 'DataSet', location=None): """ Reads an hdf5 file specified by location into a data_set object. If no data_set is provided will create an empty data_set to read into. Args: data_set: the data to read into. Should already have attributes ``io`` (an io manager), ``location`` (string), and ``arrays`` (dict of ``{array_id: array}``, can be empty or can already have some or all of the arrays present, they expect to be overwritten) location (None or str): Location to write the data. If no location is provided will use the location specified in the dataset. """ def decode_bytes_if_needed(s): """ h5py 2 stores strings encoded as bytestrings h5py 3 fixes this and stores them as regular utf8 strings This is a simple wrapper to always convert to regular strings """ try: s = s.decode() except AttributeError: pass return s self._open_file(data_set, location) if '__format_tag' in data_set._h5_base_group.attrs: format_tag = data_set._h5_base_group.attrs['__format_tag'] if format_tag != self._format_tag: raise Exception('format tag %s does not match tag %s of file %s' % (format_tag, self._format_tag, location)) for i, array_id in enumerate( data_set._h5_base_group['Data Arrays'].keys()): # Decoding string is needed because of h5py/issues/379 name = array_id # will be overwritten if not in file dat_arr = data_set._h5_base_group['Data Arrays'][array_id] # write ensures these attributes always exist name = decode_bytes_if_needed(dat_arr.attrs['name']) label = decode_bytes_if_needed(dat_arr.attrs['label']) # get unit from units if no unit field, for backward compatibility if 'unit' in dat_arr.attrs: unit = decode_bytes_if_needed(dat_arr.attrs['unit']) else: unit = decode_bytes_if_needed(dat_arr.attrs['units']) is_setpoint_str = decode_bytes_if_needed(dat_arr.attrs['is_setpoint']) is_setpoint = str_to_bool(is_setpoint_str) # if not is_setpoint: set_arrays = dat_arr.attrs['set_arrays'] set_arrays = [decode_bytes_if_needed(s) for s in set_arrays] # else: # set_arrays = () vals = dat_arr[:, 0] if 'shape' in dat_arr.attrs.keys(): # extend with NaN if needed esize = np.prod(dat_arr.attrs['shape']) vals = np.append(vals, [np.nan] * (esize - vals.size)) vals = vals.reshape(dat_arr.attrs['shape']) if array_id not in data_set.arrays.keys(): # create new array d_array = DataArray( name=name, array_id=array_id, label=label, parameter=None, unit=unit, is_setpoint=is_setpoint, set_arrays=(), preset_data=vals) data_set.add_array(d_array) else: # update existing array with extracted values d_array = data_set.arrays[array_id] d_array.name = name d_array.label = label d_array.unit = unit d_array.is_setpoint = is_setpoint d_array.ndarray = vals d_array.shape = dat_arr.attrs['shape'] # needed because I cannot add set_arrays at this point data_set.arrays[array_id]._sa_array_ids = set_arrays # Add copy/ref of setarrays (not array id only) # Note, this is not pretty but a result of how the dataset works for array_id, d_array in data_set.arrays.items(): for sa_id in d_array._sa_array_ids: d_array.set_arrays += (data_set.arrays[sa_id], ) data_set = self.read_metadata(data_set) return data_set def _filepath_from_location(self, location, io_manager): filename = os.path.split(location)[-1] filepath = io_manager.to_path(location + f'/{filename}.hdf5') return filepath def _create_data_object(self, data_set, io_manager=None, location=None): # Create the file if it is not there yet if io_manager is None: io_manager = data_set.io if location is None: location = data_set.location filepath = self._filepath_from_location(location, io_manager) # note that this creates an hdf5 file in a folder with the same # name. This is useful for saving e.g. images in the same folder # I think this is a sane default (MAR). data_set._h5_base_group = self._create_file(filepath) data_set._h5_base_group.attrs["__qcodes_version"] = qc.__version__ data_set._h5_base_group.attrs["__format_tag"] = self._format_tag return data_set._h5_base_group def write(self, data_set, io_manager=None, location=None, force_write=False, flush=True, write_metadata=True, only_complete=False): """ Writes a data_set to an hdf5 file. Args: data_set: qcodes data_set to write to hdf5 file io_manager: io_manger used for providing path location: location can be used to specify custom location force_write (bool): if True creates a new file to write to flush (bool) : whether to flush after writing, can be disabled for testing or performance reasons write_metadata (bool): If True write the dataset metadata to disk only_complete (bool): Not used by this formatter, but must be included in the call signature to avoid an "unexpected keyword argument" TypeError. N.B. It is recommended to close the file after writing, this can be done by calling ``HDF5Format.close_file(data_set)`` or ``data_set.finalize()`` if the data_set formatter is set to an hdf5 formatter. Note that this is not required if the dataset is created from a Loop as this includes a data_set.finalize() statement. The write function consists of two parts, writing DataArrays and writing metadata. - The main part of write consists of writing and resizing arrays, the resizing providing support for incremental writes. - write_metadata is called at the end of write and dumps a dictionary to an hdf5 file. If there already is metadata it will delete this and overwrite it with current metadata. """ if not hasattr(data_set, '_h5_base_group') or force_write: data_set._h5_base_group = self._create_data_object( data_set, io_manager, location) data_name = 'Data Arrays' if data_name not in data_set._h5_base_group.keys(): arr_group = data_set._h5_base_group.create_group(data_name) else: arr_group = data_set._h5_base_group[data_name] for array_id in data_set.arrays.keys(): if array_id not in arr_group.keys() or force_write: self._create_dataarray_dset(array=data_set.arrays[array_id], group=arr_group) dset = arr_group[array_id] # Resize the dataset and add the new values # dataset refers to the hdf5 dataset here datasetshape = dset.shape old_dlen = datasetshape[0] x = data_set.arrays[array_id] try: # get latest NaN element new_dlen = (~np.isnan(x)).flatten().nonzero()[0][-1] + 1 except IndexError: new_dlen = old_dlen new_datasetshape = (new_dlen, datasetshape[1]) dset.resize(new_datasetshape) new_data_shape = (new_dlen - old_dlen, datasetshape[1]) dset[old_dlen:new_dlen] = x[old_dlen:new_dlen].reshape( new_data_shape) # allow resizing extracted data, here so it gets written for # incremental writes aswell dset.attrs['shape'] = x.shape if write_metadata: self.write_metadata( data_set, io_manager=io_manager, location=location) # flush ensures buffers are written to disk # (useful for ensuring openable by other files) if flush: data_set._h5_base_group.file.flush() def _create_dataarray_dset(self, array, group): """ input arguments array: Dataset data array group: group in the hdf5 file where the dset will be created creates a hdf5 datasaset that represents the data array. """ # Check for empty meta attributes, use array_id if name and/or label # is not specified if array.label is not None: label = array.label else: label = array.array_id if array.name is not None: name = array.name else: name = array.array_id # Create the hdf5 dataset dset = group.create_dataset( array.array_id, (0, 1), maxshape=(None, 1)) dset.attrs['label'] = _encode_to_utf8(str(label)) dset.attrs['name'] = _encode_to_utf8(str(name)) dset.attrs['unit'] = _encode_to_utf8(str(array.unit or '')) dset.attrs['is_setpoint'] = _encode_to_utf8(str(array.is_setpoint)) set_arrays = [] # list will remain empty if array does not have set_array for i in range(len(array.set_arrays)): set_arrays += [_encode_to_utf8( str(array.set_arrays[i].array_id))] dset.attrs['set_arrays'] = set_arrays return dset def write_metadata(self, data_set, io_manager=None, location=None, read_first=True, **kwargs): """ Writes metadata of dataset to file using write_dict_to_hdf5 method Note that io and location are arguments that are only here because of backwards compatibility with the loop. This formatter uses io and location as specified for the main dataset. The read_first argument is ignored. """ if not hasattr(data_set, '_h5_base_group'): # added here because loop writes metadata before data itself data_set._h5_base_group = self._create_data_object(data_set) if 'metadata' in data_set._h5_base_group.keys(): del data_set._h5_base_group['metadata'] metadata_group = data_set._h5_base_group.create_group('metadata') self.write_dict_to_hdf5(data_set.metadata, metadata_group) # flush ensures buffers are written to disk # (useful for ensuring openable by other files) data_set._h5_base_group.file.flush() def _read_list_group(self, entry_point, list_type): d = {} self.read_dict_from_hdf5(data_dict=d, h5_group=entry_point[list_type]) if list_type == 'tuple': item = tuple(d[k] for k in sorted(d.keys())) elif list_type == 'list': item = [d[k] for k in sorted(d.keys())] else: raise Exception('type %s not supported' % list_type) return item def _write_list_group(self, key, item, entry_point, list_type): entry_point.create_group(key) group_attrs = entry_point[key].attrs group_attrs['list_type'] = list_type if list_type == 'tuple' or list_type == 'list': item = {str(v[0]): v[1] for v in enumerate(item)} else: raise Exception('type %s not supported' % type(item)) entry_point[key].create_group(list_type) self.write_dict_to_hdf5( data_dict=item, entry_point=entry_point[key][list_type]) def write_dict_to_hdf5(self, data_dict, entry_point): """ Write a (nested) dictionary to HDF5 Args: data_dict (dict): Dicionary to be written entry_point (object): Object to write to """ for key, item in data_dict.items(): if isinstance(key, (float, int)): key = '__' + str(type(key)) + '__' + str(key) if isinstance(item, (str, bool, float, int)): entry_point.attrs[key] = item elif isinstance(item, np.ndarray): entry_point.create_dataset(key, data=item) elif isinstance(item, (np.int32, np.int64)): entry_point.attrs[key] = int(item) elif item is None: # as h5py does not support saving None as attribute # I create special string, note that this can create # unexpected behaviour if someone saves a string with this name entry_point.attrs[key] = 'NoneType:__None__' elif isinstance(item, dict): entry_point.create_group(key) self.write_dict_to_hdf5(data_dict=item, entry_point=entry_point[key]) elif isinstance(item, tuple): self._write_list_group(key, item, entry_point, 'tuple') elif isinstance(item, list): if len(item) > 0: elt_type = type(item[0]) if all(isinstance(x, elt_type) for x in item): if isinstance(item[0], (int, float, np.int32, np.int64)): entry_point.create_dataset(key, data=np.array(item)) entry_point[key].attrs['list_type'] = 'array' elif isinstance(item[0], str): dt = h5py.special_dtype(vlen=str) data = np.array(item) data = data.reshape((-1, 1)) ds = entry_point.create_dataset( key, (len(data), 1), dtype=dt) ds[:] = data elif isinstance(item[0], dict): entry_point.create_group(key) group_attrs = entry_point[key].attrs group_attrs['list_type'] = 'dict' base_list_key = 'list_idx_{}' group_attrs['base_list_key'] = base_list_key group_attrs['list_length'] = len(item) for i, list_item in enumerate(item): list_item_grp = entry_point[key].create_group( base_list_key.format(i)) self.write_dict_to_hdf5( data_dict=list_item, entry_point=list_item_grp) else: logging.warning( 'List of type "{}" for "{}":"{}" not ' 'supported, storing as string'.format( elt_type, key, item)) entry_point.attrs[key] = str(item) else: self._write_list_group(key, item, entry_point, 'list') else: # as h5py does not support saving None as attribute entry_point.attrs[key] = 'NoneType:__emptylist__' else: logging.warning( 'Type "{}" for "{}":"{}" not supported, ' 'storing as string'.format(type(item), key, item)) entry_point.attrs[key] = str(item) def read_metadata(self, data_set: 'DataSet'): """ Reads in the metadata, this is also called at the end of a read statement so there should be no need to call this explicitly. Args: data_set: Dataset object to read the metadata into """ # checks if there is an open file in the dataset as load_data does # reading of metadata before reading the complete dataset if not hasattr(self, '_h5_base_group'): self._open_file(data_set) if 'metadata' in data_set._h5_base_group.keys(): metadata_group = data_set._h5_base_group['metadata'] self.read_dict_from_hdf5(data_set.metadata, metadata_group) return data_set def read_dict_from_hdf5(self, data_dict, h5_group): """ Read a dictionary from HDF5 Args: data_dict (dict): Dataset to read from h5_group (object): HDF5 object to read from """ if 'list_type' not in h5_group.attrs: for key, item in h5_group.items(): if isinstance(item, h5py.Group): data_dict[key] = {} data_dict[key] = self.read_dict_from_hdf5(data_dict[key], item) else: # item either a group or a dataset if 'list_type' not in item.attrs: data_dict[key] = item[...] else: data_dict[key] = list(item[...]) for key, item in h5_group.attrs.items(): if type(item) is str: # Extracts "None" as an exception as h5py does not support # storing None, nested if statement to avoid elementwise # comparison warning if item == 'NoneType:__None__': item = None elif item == 'NoneType:__emptylist__': item = [] else: pass data_dict[key] = item elif h5_group.attrs['list_type'] == 'tuple': data_dict = self._read_list_group(h5_group, 'tuple') elif h5_group.attrs['list_type'] == 'list': data_dict = self._read_list_group(h5_group, 'list') elif h5_group.attrs['list_type'] == 'dict': # preallocate empty list list_to_be_filled = [None] * h5_group.attrs['list_length'] base_list_key = h5_group.attrs['base_list_key'] for i in range(h5_group.attrs['list_length']): list_to_be_filled[i] = {} self.read_dict_from_hdf5( data_dict=list_to_be_filled[i], h5_group=h5_group[base_list_key.format(i)]) # THe error is here!, extract correctly but not adding to # data dict correctly data_dict = list_to_be_filled else: raise NotImplementedError('cannot read "list_type":"{}"'.format( h5_group.attrs['list_type'])) return data_dict def _encode_to_utf8(s): """ Required because h5py does not support python3 strings converts byte type to string """ return s.encode('utf-8') def str_to_bool(s): if s == 'True': return True elif s == 'False': return False else: raise ValueError(f"Cannot covert {s} to a bool") from qcodes.utils.helpers import NumpyJSONEncoder, deep_update class HDF5FormatMetadata(HDF5Format): _format_tag = 'hdf5-json' metadata_file = 'snapshot.json' def write_metadata(self, data_set: 'DataSet', io_manager=None, location=None, read_first=False, **kwargs): """ Write all metadata in this DataSet to storage. Args: data_set: the data we're storing io_manager (io_manager): the base location to write to location (str): the file location within io_manager read_first (Optional[bool]): read previously saved metadata before writing? The current metadata will still be the used if there are changes, but if the saved metadata has information not present in the current metadata, it will be retained. Default True. kwargs (dict): From the dicionary the key sort_keys is extracted (default value: False). If True, then the keys of the metadata will be stored sorted in the json file. Note: sorting is only possible if the keys of the metadata dictionary can be compared. """ sort_keys = kwargs.get('sort_keys', False) # this statement is here to make the linter happy if io_manager is None or location is None: raise Exception('please set io_manager and location arguments ') if read_first: # In case the saved file has more metadata than we have here, # read it in first. But any changes to the in-memory copy should # override the saved file data. memory_metadata = data_set.metadata data_set.metadata = {} self.read_metadata(data_set) deep_update(data_set.metadata, memory_metadata) fn = io_manager.join(location, self.metadata_file) with io_manager.open(fn, 'w', encoding='utf8') as snap_file: json.dump(data_set.metadata, snap_file, sort_keys=sort_keys, indent=4, ensure_ascii=False, cls=NumpyJSONEncoder) def read_metadata(self, data_set): io_manager = data_set.io location = data_set.location fn = io_manager.join(location, self.metadata_file) if io_manager.list(fn): with io_manager.open(fn, 'r') as snap_file: metadata = json.load(snap_file) data_set.metadata.update(metadata)
41.839223
118
0.57164
import json import logging import os from typing import TYPE_CHECKING import h5py import numpy as np import qcodes as qc from .data_array import DataArray from .format import Formatter if TYPE_CHECKING: from .data_set import DataSet class HDF5Format(Formatter): _format_tag = 'hdf5' def close_file(self, data_set: 'DataSet'): if hasattr(data_set, '_h5_base_group'): data_set._h5_base_group.close() del data_set._h5_base_group else: logging.warning( 'Cannot close file, data_set has no open hdf5 file') def _create_file(self, filepath): folder, _filename = os.path.split(filepath) if not os.path.isdir(folder): os.makedirs(folder) file = h5py.File(filepath, 'a') return file def _open_file(self, data_set, location=None): if location is None: location = data_set.location filepath = self._filepath_from_location(location, io_manager=data_set.io) data_set._h5_base_group = h5py.File(filepath, 'r+') def read(self, data_set: 'DataSet', location=None): def decode_bytes_if_needed(s): try: s = s.decode() except AttributeError: pass return s self._open_file(data_set, location) if '__format_tag' in data_set._h5_base_group.attrs: format_tag = data_set._h5_base_group.attrs['__format_tag'] if format_tag != self._format_tag: raise Exception('format tag %s does not match tag %s of file %s' % (format_tag, self._format_tag, location)) for i, array_id in enumerate( data_set._h5_base_group['Data Arrays'].keys()): name = array_id dat_arr = data_set._h5_base_group['Data Arrays'][array_id] name = decode_bytes_if_needed(dat_arr.attrs['name']) label = decode_bytes_if_needed(dat_arr.attrs['label']) if 'unit' in dat_arr.attrs: unit = decode_bytes_if_needed(dat_arr.attrs['unit']) else: unit = decode_bytes_if_needed(dat_arr.attrs['units']) is_setpoint_str = decode_bytes_if_needed(dat_arr.attrs['is_setpoint']) is_setpoint = str_to_bool(is_setpoint_str) set_arrays = dat_arr.attrs['set_arrays'] set_arrays = [decode_bytes_if_needed(s) for s in set_arrays] vals = dat_arr[:, 0] if 'shape' in dat_arr.attrs.keys(): esize = np.prod(dat_arr.attrs['shape']) vals = np.append(vals, [np.nan] * (esize - vals.size)) vals = vals.reshape(dat_arr.attrs['shape']) if array_id not in data_set.arrays.keys(): d_array = DataArray( name=name, array_id=array_id, label=label, parameter=None, unit=unit, is_setpoint=is_setpoint, set_arrays=(), preset_data=vals) data_set.add_array(d_array) else: d_array = data_set.arrays[array_id] d_array.name = name d_array.label = label d_array.unit = unit d_array.is_setpoint = is_setpoint d_array.ndarray = vals d_array.shape = dat_arr.attrs['shape'] data_set.arrays[array_id]._sa_array_ids = set_arrays for array_id, d_array in data_set.arrays.items(): for sa_id in d_array._sa_array_ids: d_array.set_arrays += (data_set.arrays[sa_id], ) data_set = self.read_metadata(data_set) return data_set def _filepath_from_location(self, location, io_manager): filename = os.path.split(location)[-1] filepath = io_manager.to_path(location + f'/{filename}.hdf5') return filepath def _create_data_object(self, data_set, io_manager=None, location=None): if io_manager is None: io_manager = data_set.io if location is None: location = data_set.location filepath = self._filepath_from_location(location, io_manager) data_set._h5_base_group = self._create_file(filepath) data_set._h5_base_group.attrs["__qcodes_version"] = qc.__version__ data_set._h5_base_group.attrs["__format_tag"] = self._format_tag return data_set._h5_base_group def write(self, data_set, io_manager=None, location=None, force_write=False, flush=True, write_metadata=True, only_complete=False): if not hasattr(data_set, '_h5_base_group') or force_write: data_set._h5_base_group = self._create_data_object( data_set, io_manager, location) data_name = 'Data Arrays' if data_name not in data_set._h5_base_group.keys(): arr_group = data_set._h5_base_group.create_group(data_name) else: arr_group = data_set._h5_base_group[data_name] for array_id in data_set.arrays.keys(): if array_id not in arr_group.keys() or force_write: self._create_dataarray_dset(array=data_set.arrays[array_id], group=arr_group) dset = arr_group[array_id] datasetshape = dset.shape old_dlen = datasetshape[0] x = data_set.arrays[array_id] try: new_dlen = (~np.isnan(x)).flatten().nonzero()[0][-1] + 1 except IndexError: new_dlen = old_dlen new_datasetshape = (new_dlen, datasetshape[1]) dset.resize(new_datasetshape) new_data_shape = (new_dlen - old_dlen, datasetshape[1]) dset[old_dlen:new_dlen] = x[old_dlen:new_dlen].reshape( new_data_shape) dset.attrs['shape'] = x.shape if write_metadata: self.write_metadata( data_set, io_manager=io_manager, location=location) if flush: data_set._h5_base_group.file.flush() def _create_dataarray_dset(self, array, group): if array.label is not None: label = array.label else: label = array.array_id if array.name is not None: name = array.name else: name = array.array_id dset = group.create_dataset( array.array_id, (0, 1), maxshape=(None, 1)) dset.attrs['label'] = _encode_to_utf8(str(label)) dset.attrs['name'] = _encode_to_utf8(str(name)) dset.attrs['unit'] = _encode_to_utf8(str(array.unit or '')) dset.attrs['is_setpoint'] = _encode_to_utf8(str(array.is_setpoint)) set_arrays = [] for i in range(len(array.set_arrays)): set_arrays += [_encode_to_utf8( str(array.set_arrays[i].array_id))] dset.attrs['set_arrays'] = set_arrays return dset def write_metadata(self, data_set, io_manager=None, location=None, read_first=True, **kwargs): if not hasattr(data_set, '_h5_base_group'): data_set._h5_base_group = self._create_data_object(data_set) if 'metadata' in data_set._h5_base_group.keys(): del data_set._h5_base_group['metadata'] metadata_group = data_set._h5_base_group.create_group('metadata') self.write_dict_to_hdf5(data_set.metadata, metadata_group) data_set._h5_base_group.file.flush() def _read_list_group(self, entry_point, list_type): d = {} self.read_dict_from_hdf5(data_dict=d, h5_group=entry_point[list_type]) if list_type == 'tuple': item = tuple(d[k] for k in sorted(d.keys())) elif list_type == 'list': item = [d[k] for k in sorted(d.keys())] else: raise Exception('type %s not supported' % list_type) return item def _write_list_group(self, key, item, entry_point, list_type): entry_point.create_group(key) group_attrs = entry_point[key].attrs group_attrs['list_type'] = list_type if list_type == 'tuple' or list_type == 'list': item = {str(v[0]): v[1] for v in enumerate(item)} else: raise Exception('type %s not supported' % type(item)) entry_point[key].create_group(list_type) self.write_dict_to_hdf5( data_dict=item, entry_point=entry_point[key][list_type]) def write_dict_to_hdf5(self, data_dict, entry_point): for key, item in data_dict.items(): if isinstance(key, (float, int)): key = '__' + str(type(key)) + '__' + str(key) if isinstance(item, (str, bool, float, int)): entry_point.attrs[key] = item elif isinstance(item, np.ndarray): entry_point.create_dataset(key, data=item) elif isinstance(item, (np.int32, np.int64)): entry_point.attrs[key] = int(item) elif item is None: entry_point.attrs[key] = 'NoneType:__None__' elif isinstance(item, dict): entry_point.create_group(key) self.write_dict_to_hdf5(data_dict=item, entry_point=entry_point[key]) elif isinstance(item, tuple): self._write_list_group(key, item, entry_point, 'tuple') elif isinstance(item, list): if len(item) > 0: elt_type = type(item[0]) if all(isinstance(x, elt_type) for x in item): if isinstance(item[0], (int, float, np.int32, np.int64)): entry_point.create_dataset(key, data=np.array(item)) entry_point[key].attrs['list_type'] = 'array' elif isinstance(item[0], str): dt = h5py.special_dtype(vlen=str) data = np.array(item) data = data.reshape((-1, 1)) ds = entry_point.create_dataset( key, (len(data), 1), dtype=dt) ds[:] = data elif isinstance(item[0], dict): entry_point.create_group(key) group_attrs = entry_point[key].attrs group_attrs['list_type'] = 'dict' base_list_key = 'list_idx_{}' group_attrs['base_list_key'] = base_list_key group_attrs['list_length'] = len(item) for i, list_item in enumerate(item): list_item_grp = entry_point[key].create_group( base_list_key.format(i)) self.write_dict_to_hdf5( data_dict=list_item, entry_point=list_item_grp) else: logging.warning( 'List of type "{}" for "{}":"{}" not ' 'supported, storing as string'.format( elt_type, key, item)) entry_point.attrs[key] = str(item) else: self._write_list_group(key, item, entry_point, 'list') else: entry_point.attrs[key] = 'NoneType:__emptylist__' else: logging.warning( 'Type "{}" for "{}":"{}" not supported, ' 'storing as string'.format(type(item), key, item)) entry_point.attrs[key] = str(item) def read_metadata(self, data_set: 'DataSet'): if not hasattr(self, '_h5_base_group'): self._open_file(data_set) if 'metadata' in data_set._h5_base_group.keys(): metadata_group = data_set._h5_base_group['metadata'] self.read_dict_from_hdf5(data_set.metadata, metadata_group) return data_set def read_dict_from_hdf5(self, data_dict, h5_group): if 'list_type' not in h5_group.attrs: for key, item in h5_group.items(): if isinstance(item, h5py.Group): data_dict[key] = {} data_dict[key] = self.read_dict_from_hdf5(data_dict[key], item) else: if 'list_type' not in item.attrs: data_dict[key] = item[...] else: data_dict[key] = list(item[...]) for key, item in h5_group.attrs.items(): if type(item) is str: if item == 'NoneType:__None__': item = None elif item == 'NoneType:__emptylist__': item = [] else: pass data_dict[key] = item elif h5_group.attrs['list_type'] == 'tuple': data_dict = self._read_list_group(h5_group, 'tuple') elif h5_group.attrs['list_type'] == 'list': data_dict = self._read_list_group(h5_group, 'list') elif h5_group.attrs['list_type'] == 'dict': list_to_be_filled = [None] * h5_group.attrs['list_length'] base_list_key = h5_group.attrs['base_list_key'] for i in range(h5_group.attrs['list_length']): list_to_be_filled[i] = {} self.read_dict_from_hdf5( data_dict=list_to_be_filled[i], h5_group=h5_group[base_list_key.format(i)]) data_dict = list_to_be_filled else: raise NotImplementedError('cannot read "list_type":"{}"'.format( h5_group.attrs['list_type'])) return data_dict def _encode_to_utf8(s): return s.encode('utf-8') def str_to_bool(s): if s == 'True': return True elif s == 'False': return False else: raise ValueError(f"Cannot covert {s} to a bool") from qcodes.utils.helpers import NumpyJSONEncoder, deep_update class HDF5FormatMetadata(HDF5Format): _format_tag = 'hdf5-json' metadata_file = 'snapshot.json' def write_metadata(self, data_set: 'DataSet', io_manager=None, location=None, read_first=False, **kwargs): sort_keys = kwargs.get('sort_keys', False) if io_manager is None or location is None: raise Exception('please set io_manager and location arguments ') if read_first: memory_metadata = data_set.metadata data_set.metadata = {} self.read_metadata(data_set) deep_update(data_set.metadata, memory_metadata) fn = io_manager.join(location, self.metadata_file) with io_manager.open(fn, 'w', encoding='utf8') as snap_file: json.dump(data_set.metadata, snap_file, sort_keys=sort_keys, indent=4, ensure_ascii=False, cls=NumpyJSONEncoder) def read_metadata(self, data_set): io_manager = data_set.io location = data_set.location fn = io_manager.join(location, self.metadata_file) if io_manager.list(fn): with io_manager.open(fn, 'r') as snap_file: metadata = json.load(snap_file) data_set.metadata.update(metadata)
true
true
1c3957e91fba49529695f8315f9933a48df10e2d
1,547
py
Python
Kuka_examples/plot_monitor.py
zhigenzhao/stable-baselines3
a69a4f0497849d9c20f6b77870ca77ae92f5c7bb
[ "MIT" ]
null
null
null
Kuka_examples/plot_monitor.py
zhigenzhao/stable-baselines3
a69a4f0497849d9c20f6b77870ca77ae92f5c7bb
[ "MIT" ]
null
null
null
Kuka_examples/plot_monitor.py
zhigenzhao/stable-baselines3
a69a4f0497849d9c20f6b77870ca77ae92f5c7bb
[ "MIT" ]
null
null
null
from matplotlib import pyplot as plt import numpy as np import csv def main(): filename = "/home/zhigen/code/stable-baselines3/Kuka_examples/saved_models/monitor (copy).csv" with open(filename) as csvfile: training_monitor = csv.reader(csvfile) reward = [] for (i, row) in enumerate(training_monitor): if i > 1: reward.append(float(row[0])) reward = np.array(reward) reward_vec = [] reward_std = [] i = 0 n = 5000 while i < len(reward): if i+n < len(reward): temp = reward[i:i+n] else: temp = reward[i:] m = np.mean(temp) s = np.std(temp) reward_vec.append(m) reward_std.append(s) i += n plt.plot(np.arange(len(reward_vec))*n, -np.array(reward_vec), linewidth=3) plt.plot(np.arange(len(reward_vec))*n, np.ones_like(reward_vec)*1750, linestyle="dashed", linewidth=3) plt.fill_between(np.arange(len(reward_vec))*n, -np.array(reward_vec)+np.array(reward_std), -np.array(reward_vec)-np.array(reward_std), alpha=0.5) plt.yscale("log") plt.xlabel("Timestep", fontsize=24) plt.xticks(fontsize=14) plt.ylabel("Cost", fontsize=24) plt.yticks(fontsize=16) plt.legend(["PPO", "VERONICA baseline"], fontsize=16) plt.xlim([0, 300000]) plt.show() if __name__=="__main__": main()
29.75
110
0.548158
from matplotlib import pyplot as plt import numpy as np import csv def main(): filename = "/home/zhigen/code/stable-baselines3/Kuka_examples/saved_models/monitor (copy).csv" with open(filename) as csvfile: training_monitor = csv.reader(csvfile) reward = [] for (i, row) in enumerate(training_monitor): if i > 1: reward.append(float(row[0])) reward = np.array(reward) reward_vec = [] reward_std = [] i = 0 n = 5000 while i < len(reward): if i+n < len(reward): temp = reward[i:i+n] else: temp = reward[i:] m = np.mean(temp) s = np.std(temp) reward_vec.append(m) reward_std.append(s) i += n plt.plot(np.arange(len(reward_vec))*n, -np.array(reward_vec), linewidth=3) plt.plot(np.arange(len(reward_vec))*n, np.ones_like(reward_vec)*1750, linestyle="dashed", linewidth=3) plt.fill_between(np.arange(len(reward_vec))*n, -np.array(reward_vec)+np.array(reward_std), -np.array(reward_vec)-np.array(reward_std), alpha=0.5) plt.yscale("log") plt.xlabel("Timestep", fontsize=24) plt.xticks(fontsize=14) plt.ylabel("Cost", fontsize=24) plt.yticks(fontsize=16) plt.legend(["PPO", "VERONICA baseline"], fontsize=16) plt.xlim([0, 300000]) plt.show() if __name__=="__main__": main()
true
true
1c395835516cc3cdac94a16be11eafdeeb9614e5
12,088
py
Python
tscribe/__init__.py
craigmayhew/aws_transcribe_to_docx
1aded9a7c0f14b8242991e564aec3275fc9f83f9
[ "MIT" ]
null
null
null
tscribe/__init__.py
craigmayhew/aws_transcribe_to_docx
1aded9a7c0f14b8242991e564aec3275fc9f83f9
[ "MIT" ]
null
null
null
tscribe/__init__.py
craigmayhew/aws_transcribe_to_docx
1aded9a7c0f14b8242991e564aec3275fc9f83f9
[ "MIT" ]
null
null
null
""" Produce Word Document transcriptions using the automatic speech recognition from AWS Transcribe. """ from docx import Document from docx.shared import Cm, Mm, Inches, RGBColor from docx.enum.text import WD_ALIGN_PARAGRAPH import json, datetime import matplotlib.pyplot as plt import statistics def convert_time_stamp(n): """ Function to help convert timestamps from s to H:M:S """ ts = datetime.timedelta(seconds=float(n)) ts = ts - datetime.timedelta(microseconds=ts.microseconds) return str(ts) def write(file, **kwargs): """ Write a transcript from the .json transcription file. """ # Initiate Document document = Document() # A4 Size document.sections[0].page_width = Mm(210) document.sections[0].page_height = Mm(297) # Font font = document.styles['Normal'].font font.name = 'Calibri' # Load Transcription output data = json.load(open(file, 'r', encoding='utf-8')) # Document title and intro title = f"Transcription of {data['jobName']}" document.add_heading(title, level=1) # Set thresholds for formatting later threshold_for_grey = 0.98 # Intro document.add_paragraph('Transcription using AWS Transcribe automatic speech recognition.') document.add_paragraph(datetime.datetime.now().strftime('Document produced on %A %d %B %Y at %X.')) document.add_paragraph() # Spacing document.add_paragraph(f"Grey text has less than {int(threshold_for_grey * 100)}% confidence.") # Stats dictionary stats = { 'timestamps': [], 'accuracy': [], '9.8': 0, '9': 0, '8': 0, '7': 0, '6': 0, '5': 0, '4': 0, '3': 0, '2': 0, '1': 0, '0': 0, 'total': len(data['results']['items'])} # Confidence count for item in data['results']['items']: if item['type'] == 'pronunciation': stats['timestamps'].append(float(item['start_time'])) stats['accuracy'].append(int(float(item['alternatives'][0]['confidence']) * 100)) if float(item['alternatives'][0]['confidence']) >= 0.98: stats['9.8'] += 1 elif float(item['alternatives'][0]['confidence']) >= 0.9: stats['9'] += 1 elif float(item['alternatives'][0]['confidence']) >= 0.8: stats['8'] += 1 elif float(item['alternatives'][0]['confidence']) >= 0.7: stats['7'] += 1 elif float(item['alternatives'][0]['confidence']) >= 0.6: stats['6'] += 1 elif float(item['alternatives'][0]['confidence']) >= 0.5: stats['5'] += 1 elif float(item['alternatives'][0]['confidence']) >= 0.4: stats['4'] += 1 elif float(item['alternatives'][0]['confidence']) >= 0.3: stats['3'] += 1 elif float(item['alternatives'][0]['confidence']) >= 0.2: stats['2'] += 1 elif float(item['alternatives'][0]['confidence']) >= 0.1: stats['1'] += 1 else: stats['0'] += 1 # Display confidence count table table = document.add_table(rows=1, cols=3) table.style = document.styles['Light List Accent 1'] table.alignment = WD_ALIGN_PARAGRAPH.CENTER hdr_cells = table.rows[0].cells hdr_cells[0].text = 'Confidence' hdr_cells[1].text = 'Count' hdr_cells[2].text = 'Percentage' row_cells = table.add_row().cells row_cells[0].text = str('98% - 100%') row_cells[1].text = str(stats['9.8']) row_cells[2].text = str(round(stats['9.8'] / stats['total'] * 100, 2)) + '%' row_cells = table.add_row().cells row_cells[0].text = str('90% - 97%') row_cells[1].text = str(stats['9']) row_cells[2].text = str(round(stats['9'] / stats['total'] * 100, 2)) + '%' row_cells = table.add_row().cells row_cells[0].text = str('80% - 89%') row_cells[1].text = str(stats['8']) row_cells[2].text = str(round(stats['8'] / stats['total'] * 100, 2)) + '%' row_cells = table.add_row().cells row_cells[0].text = str('70% - 79%') row_cells[1].text = str(stats['7']) row_cells[2].text = str(round(stats['7'] / stats['total'] * 100, 2)) + '%' row_cells = table.add_row().cells row_cells[0].text = str('60% - 69%') row_cells[1].text = str(stats['6']) row_cells[2].text = str(round(stats['6'] / stats['total'] * 100, 2)) + '%' row_cells = table.add_row().cells row_cells[0].text = str('50% - 59%') row_cells[1].text = str(stats['5']) row_cells[2].text = str(round(stats['5'] / stats['total'] * 100, 2)) + '%' row_cells = table.add_row().cells row_cells[0].text = str('40% - 49%') row_cells[1].text = str(stats['4']) row_cells[2].text = str(round(stats['4'] / stats['total'] * 100, 2)) + '%' row_cells = table.add_row().cells row_cells[0].text = str('30% - 39%') row_cells[1].text = str(stats['3']) row_cells[2].text = str(round(stats['3'] / stats['total'] * 100, 2)) + '%' row_cells = table.add_row().cells row_cells[0].text = str('20% - 29%') row_cells[1].text = str(stats['2']) row_cells[2].text = str(round(stats['2'] / stats['total'] * 100, 2)) + '%' row_cells = table.add_row().cells row_cells[0].text = str('10% - 19%') row_cells[1].text = str(stats['1']) row_cells[2].text = str(round(stats['1'] / stats['total'] * 100, 2)) + '%' row_cells = table.add_row().cells row_cells[0].text = str('0% - 9%') row_cells[1].text = str(stats['0']) row_cells[2].text = str(round(stats['0'] / stats['total'] * 100, 2)) + '%' # Add paragraph for spacing document.add_paragraph() # Display scatter graph of confidence # Confidence of each word as scatter graph plt.scatter(stats['timestamps'], stats['accuracy']) # Mean average as line across graph plt.plot([stats['timestamps'][0], stats['timestamps'][-1]], [statistics.mean(stats['accuracy']), statistics.mean(stats['accuracy'])], 'r') # Formatting plt.xlabel('Time (seconds)') # plt.xticks(range(0, int(stats['timestamps'][-1]), 60)) plt.ylabel('Accuracy (percent)') plt.yticks(range(0, 101, 10)) plt.title('Accuracy during video') plt.legend(['Accuracy average (mean)', 'Individual words'], loc='lower center') # not all file systems are writable, so we allow specifying a writable tmp directory # alternatively if it is not set, we use ./ tmp_dir = kwargs.get('tmp_dir', "./") chart_file_name = tmp_dir+'chart.png' plt.savefig(chart_file_name) document.add_picture(chart_file_name, width=Cm(14.64)) document.paragraphs[-1].alignment = WD_ALIGN_PARAGRAPH.CENTER document.add_page_break() # Process and display transcript by speaker segments table = document.add_table(rows=1, cols=3) table.style = document.styles['Light List Accent 1'] hdr_cells = table.rows[0].cells hdr_cells[0].text = 'Time' hdr_cells[1].text = 'Speaker' hdr_cells[2].text = 'Content' # If speaker identification if 'speaker_labels' in data['results'].keys(): for segment in data['results']['speaker_labels']['segments']: # If there is content in the segment if len(segment['items']) > 0: # Add a row, write the time and speaker row_cells = table.add_row().cells row_cells[0].text = convert_time_stamp(segment['start_time']) row_cells[1].text = str(segment['speaker_label']) # Segments group individual word results by speaker. They are cross-referenced by time. # For each word in the segment... for word in segment['items']: # Run through the word results and get the corresponding result for result in data['results']['items']: if result['type'] == 'pronunciation': if result['start_time'] == word['start_time']: # Get the word with the highest confidence if len(result['alternatives']) > 0: current_word = dict() confidence_scores = [] for score in result['alternatives']: confidence_scores.append(score['confidence']) for alternative in result['alternatives']: if alternative['confidence'] == max(confidence_scores): current_word = alternative.copy() # Write and format the word run = row_cells[2].paragraphs[0].add_run(' ' + current_word['content']) if float(current_word['confidence']) < threshold_for_grey: font = run.font font.color.rgb = RGBColor(204, 204, 204) # If the next item is punctuation, add it try: if data['results']['items'][data['results']['items'].index(result) + 1]['type'] == 'punctuation': run = row_cells[2].paragraphs[0].add_run(data['results']['items'][data['results']['items'].index(result) + 1]['alternatives'][0]['content']) # Occasional IndexErrors encountered except: pass # Else no speaker identification else: # Run through the word results # Start the first row row_cells = table.add_row().cells row_cells[0].text = convert_time_stamp(data['results']['items'][0]['start_time']) # Add words for result in data['results']['items']: if result['type'] == 'pronunciation': # Write the time if it's not yet there if table.cell(-1, 0).text == "": table.cell(-1, 0).text = convert_time_stamp(result["start_time"]) # Get the word with the highest confidence if len(result['alternatives']) > 0: current_word = dict() confidence_scores = [] for score in result['alternatives']: confidence_scores.append(score['confidence']) for alternative in result['alternatives']: if alternative['confidence'] == max(confidence_scores): current_word = alternative.copy() # Write and format the word run = table.cell(-1, 2).paragraphs[0].add_run(' ' + current_word['content']) if float(current_word['confidence']) < threshold_for_grey: font = run.font font.color.rgb = RGBColor(204, 204, 204) # If the next item is punctuation, add it and start a new row elif result['type'] == 'punctuation': # Get the punctuation with the highest confidence if len(result['alternatives']) > 0: current_word = dict() confidence_scores = [] for score in result['alternatives']: confidence_scores.append(score['confidence']) for alternative in result['alternatives']: if alternative['confidence'] == max(confidence_scores): current_word = alternative.copy() # Write and format the word run = table.cell(-1, 2).paragraphs[0].add_run(current_word['content']) table.add_row().cells # Formatting transcript table widthds widths = (Inches(0.6), Inches(1), Inches(4.5)) for row in table.rows: for idx, width in enumerate(widths): row.cells[idx].width = width # Save filename = kwargs.get('save_as', f"{data['jobName']}.docx") document.save(filename) print(f"Transcript {filename} writen.")
47.968254
184
0.558653
from docx import Document from docx.shared import Cm, Mm, Inches, RGBColor from docx.enum.text import WD_ALIGN_PARAGRAPH import json, datetime import matplotlib.pyplot as plt import statistics def convert_time_stamp(n): ts = datetime.timedelta(seconds=float(n)) ts = ts - datetime.timedelta(microseconds=ts.microseconds) return str(ts) def write(file, **kwargs): document = Document() document.sections[0].page_width = Mm(210) document.sections[0].page_height = Mm(297) font = document.styles['Normal'].font font.name = 'Calibri' data = json.load(open(file, 'r', encoding='utf-8')) title = f"Transcription of {data['jobName']}" document.add_heading(title, level=1) threshold_for_grey = 0.98 document.add_paragraph('Transcription using AWS Transcribe automatic speech recognition.') document.add_paragraph(datetime.datetime.now().strftime('Document produced on %A %d %B %Y at %X.')) document.add_paragraph() document.add_paragraph(f"Grey text has less than {int(threshold_for_grey * 100)}% confidence.") stats = { 'timestamps': [], 'accuracy': [], '9.8': 0, '9': 0, '8': 0, '7': 0, '6': 0, '5': 0, '4': 0, '3': 0, '2': 0, '1': 0, '0': 0, 'total': len(data['results']['items'])} for item in data['results']['items']: if item['type'] == 'pronunciation': stats['timestamps'].append(float(item['start_time'])) stats['accuracy'].append(int(float(item['alternatives'][0]['confidence']) * 100)) if float(item['alternatives'][0]['confidence']) >= 0.98: stats['9.8'] += 1 elif float(item['alternatives'][0]['confidence']) >= 0.9: stats['9'] += 1 elif float(item['alternatives'][0]['confidence']) >= 0.8: stats['8'] += 1 elif float(item['alternatives'][0]['confidence']) >= 0.7: stats['7'] += 1 elif float(item['alternatives'][0]['confidence']) >= 0.6: stats['6'] += 1 elif float(item['alternatives'][0]['confidence']) >= 0.5: stats['5'] += 1 elif float(item['alternatives'][0]['confidence']) >= 0.4: stats['4'] += 1 elif float(item['alternatives'][0]['confidence']) >= 0.3: stats['3'] += 1 elif float(item['alternatives'][0]['confidence']) >= 0.2: stats['2'] += 1 elif float(item['alternatives'][0]['confidence']) >= 0.1: stats['1'] += 1 else: stats['0'] += 1 table = document.add_table(rows=1, cols=3) table.style = document.styles['Light List Accent 1'] table.alignment = WD_ALIGN_PARAGRAPH.CENTER hdr_cells = table.rows[0].cells hdr_cells[0].text = 'Confidence' hdr_cells[1].text = 'Count' hdr_cells[2].text = 'Percentage' row_cells = table.add_row().cells row_cells[0].text = str('98% - 100%') row_cells[1].text = str(stats['9.8']) row_cells[2].text = str(round(stats['9.8'] / stats['total'] * 100, 2)) + '%' row_cells = table.add_row().cells row_cells[0].text = str('90% - 97%') row_cells[1].text = str(stats['9']) row_cells[2].text = str(round(stats['9'] / stats['total'] * 100, 2)) + '%' row_cells = table.add_row().cells row_cells[0].text = str('80% - 89%') row_cells[1].text = str(stats['8']) row_cells[2].text = str(round(stats['8'] / stats['total'] * 100, 2)) + '%' row_cells = table.add_row().cells row_cells[0].text = str('70% - 79%') row_cells[1].text = str(stats['7']) row_cells[2].text = str(round(stats['7'] / stats['total'] * 100, 2)) + '%' row_cells = table.add_row().cells row_cells[0].text = str('60% - 69%') row_cells[1].text = str(stats['6']) row_cells[2].text = str(round(stats['6'] / stats['total'] * 100, 2)) + '%' row_cells = table.add_row().cells row_cells[0].text = str('50% - 59%') row_cells[1].text = str(stats['5']) row_cells[2].text = str(round(stats['5'] / stats['total'] * 100, 2)) + '%' row_cells = table.add_row().cells row_cells[0].text = str('40% - 49%') row_cells[1].text = str(stats['4']) row_cells[2].text = str(round(stats['4'] / stats['total'] * 100, 2)) + '%' row_cells = table.add_row().cells row_cells[0].text = str('30% - 39%') row_cells[1].text = str(stats['3']) row_cells[2].text = str(round(stats['3'] / stats['total'] * 100, 2)) + '%' row_cells = table.add_row().cells row_cells[0].text = str('20% - 29%') row_cells[1].text = str(stats['2']) row_cells[2].text = str(round(stats['2'] / stats['total'] * 100, 2)) + '%' row_cells = table.add_row().cells row_cells[0].text = str('10% - 19%') row_cells[1].text = str(stats['1']) row_cells[2].text = str(round(stats['1'] / stats['total'] * 100, 2)) + '%' row_cells = table.add_row().cells row_cells[0].text = str('0% - 9%') row_cells[1].text = str(stats['0']) row_cells[2].text = str(round(stats['0'] / stats['total'] * 100, 2)) + '%' document.add_paragraph() plt.scatter(stats['timestamps'], stats['accuracy']) plt.plot([stats['timestamps'][0], stats['timestamps'][-1]], [statistics.mean(stats['accuracy']), statistics.mean(stats['accuracy'])], 'r') plt.xlabel('Time (seconds)') plt.ylabel('Accuracy (percent)') plt.yticks(range(0, 101, 10)) plt.title('Accuracy during video') plt.legend(['Accuracy average (mean)', 'Individual words'], loc='lower center') tmp_dir = kwargs.get('tmp_dir', "./") chart_file_name = tmp_dir+'chart.png' plt.savefig(chart_file_name) document.add_picture(chart_file_name, width=Cm(14.64)) document.paragraphs[-1].alignment = WD_ALIGN_PARAGRAPH.CENTER document.add_page_break() table = document.add_table(rows=1, cols=3) table.style = document.styles['Light List Accent 1'] hdr_cells = table.rows[0].cells hdr_cells[0].text = 'Time' hdr_cells[1].text = 'Speaker' hdr_cells[2].text = 'Content' if 'speaker_labels' in data['results'].keys(): for segment in data['results']['speaker_labels']['segments']: if len(segment['items']) > 0: row_cells = table.add_row().cells row_cells[0].text = convert_time_stamp(segment['start_time']) row_cells[1].text = str(segment['speaker_label']) for word in segment['items']: for result in data['results']['items']: if result['type'] == 'pronunciation': if result['start_time'] == word['start_time']: if len(result['alternatives']) > 0: current_word = dict() confidence_scores = [] for score in result['alternatives']: confidence_scores.append(score['confidence']) for alternative in result['alternatives']: if alternative['confidence'] == max(confidence_scores): current_word = alternative.copy() run = row_cells[2].paragraphs[0].add_run(' ' + current_word['content']) if float(current_word['confidence']) < threshold_for_grey: font = run.font font.color.rgb = RGBColor(204, 204, 204) try: if data['results']['items'][data['results']['items'].index(result) + 1]['type'] == 'punctuation': run = row_cells[2].paragraphs[0].add_run(data['results']['items'][data['results']['items'].index(result) + 1]['alternatives'][0]['content']) except: pass else: row_cells = table.add_row().cells row_cells[0].text = convert_time_stamp(data['results']['items'][0]['start_time']) for result in data['results']['items']: if result['type'] == 'pronunciation': if table.cell(-1, 0).text == "": table.cell(-1, 0).text = convert_time_stamp(result["start_time"]) # Get the word with the highest confidence if len(result['alternatives']) > 0: current_word = dict() confidence_scores = [] for score in result['alternatives']: confidence_scores.append(score['confidence']) for alternative in result['alternatives']: if alternative['confidence'] == max(confidence_scores): current_word = alternative.copy() # Write and format the word run = table.cell(-1, 2).paragraphs[0].add_run(' ' + current_word['content']) if float(current_word['confidence']) < threshold_for_grey: font = run.font font.color.rgb = RGBColor(204, 204, 204) # If the next item is punctuation, add it and start a new row elif result['type'] == 'punctuation': # Get the punctuation with the highest confidence if len(result['alternatives']) > 0: current_word = dict() confidence_scores = [] for score in result['alternatives']: confidence_scores.append(score['confidence']) for alternative in result['alternatives']: if alternative['confidence'] == max(confidence_scores): current_word = alternative.copy() # Write and format the word run = table.cell(-1, 2).paragraphs[0].add_run(current_word['content']) table.add_row().cells # Formatting transcript table widthds widths = (Inches(0.6), Inches(1), Inches(4.5)) for row in table.rows: for idx, width in enumerate(widths): row.cells[idx].width = width # Save filename = kwargs.get('save_as', f"{data['jobName']}.docx") document.save(filename) print(f"Transcript {filename} writen.")
true
true
1c39586ec92ace93580f38c62c9dc9d24e87e440
3,249
py
Python
third-party/dool-1.0.0/plugins/dool_top_io_adv.py
rreye/bdev
8ad775f8c14b9aa51e6813529c7022fbc2b297d7
[ "MIT" ]
34
2021-01-18T14:25:24.000Z
2021-06-05T03:21:10.000Z
docker/dstat/plugins/dstat_top_io_adv.py
dbiir/WooKongDB
2afe19ce291d786249f97d37094a26078ceb571c
[ "PostgreSQL", "Apache-2.0" ]
null
null
null
docker/dstat/plugins/dstat_top_io_adv.py
dbiir/WooKongDB
2afe19ce291d786249f97d37094a26078ceb571c
[ "PostgreSQL", "Apache-2.0" ]
2
2021-04-20T20:11:08.000Z
2021-06-02T02:56:16.000Z
### Dstat all I/O process plugin ### Displays all processes' I/O read/write stats and CPU usage ### ### Authority: Guillermo Cantu Luna class dstat_plugin(dstat): def __init__(self): self.name = 'most expensive i/o process' self.vars = ('process pid read write cpu',) self.type = 's' self.width = 40 self.scale = 0 self.pidset1 = {} def check(self): if not os.access('/proc/self/io', os.R_OK): raise Exception('Kernel has no per-process I/O accounting [CONFIG_TASK_IO_ACCOUNTING], use at least 2.6.20') return True def extract(self): self.output = '' self.pidset2 = {} self.val['usage'] = 0.0 for pid in proc_pidlist(): try: ### Reset values if pid not in self.pidset2: self.pidset2[pid] = {'rchar:': 0, 'wchar:': 0, 'cputime:': 0, 'cpuper:': 0} if pid not in self.pidset1: self.pidset1[pid] = {'rchar:': 0, 'wchar:': 0, 'cputime:': 0, 'cpuper:': 0} ### Extract name name = proc_splitline('/proc/%s/stat' % pid)[1][1:-1] ### Extract counters for l in proc_splitlines('/proc/%s/io' % pid): if len(l) != 2: continue self.pidset2[pid][l[0]] = int(l[1]) ### Get CPU usage l = proc_splitline('/proc/%s/stat' % pid) if len(l) < 15: cpu_usage = 0 else: self.pidset2[pid]['cputime:'] = int(l[13]) + int(l[14]) cpu_usage = (self.pidset2[pid]['cputime:'] - self.pidset1[pid]['cputime:']) * 1.0 / elapsed / cpunr except ValueError: continue except IOError: continue except IndexError: continue read_usage = (self.pidset2[pid]['rchar:'] - self.pidset1[pid]['rchar:']) * 1.0 / elapsed write_usage = (self.pidset2[pid]['wchar:'] - self.pidset1[pid]['wchar:']) * 1.0 / elapsed usage = read_usage + write_usage ### Get the process that spends the most jiffies if usage > self.val['usage']: self.val['usage'] = usage self.val['read_usage'] = read_usage self.val['write_usage'] = write_usage self.val['pid'] = pid self.val['name'] = getnamebypid(pid, name) self.val['cpu_usage'] = cpu_usage if step == op.delay: self.pidset1 = self.pidset2 if self.val['usage'] != 0.0: self.output = '%-*s%s%-5s%s%s%s%s%%' % (self.width-14-len(pid), self.val['name'][0:self.width-14-len(pid)], color['darkblue'], self.val['pid'], cprint(self.val['read_usage'], 'd', 5, 1024), cprint(self.val['write_usage'], 'd', 5, 1024), cprint(self.val['cpu_usage'], 'f', 3, 34), color['darkgray']) def showcsv(self): return 'Top: %s\t%s\t%s\t%s' % (self.val['name'][0:self.width-20], self.val['read_usage'], self.val['write_usage'], self.val['cpu_usage'])
42.75
311
0.495537
pid read write cpu',) self.type = 's' self.width = 40 self.scale = 0 self.pidset1 = {} def check(self): if not os.access('/proc/self/io', os.R_OK): raise Exception('Kernel has no per-process I/O accounting [CONFIG_TASK_IO_ACCOUNTING], use at least 2.6.20') return True def extract(self): self.output = '' self.pidset2 = {} self.val['usage'] = 0.0 for pid in proc_pidlist(): try: ### Reset values if pid not in self.pidset2: self.pidset2[pid] = {'rchar:': 0, 'wchar:': 0, 'cputime:': 0, 'cpuper:': 0} if pid not in self.pidset1: self.pidset1[pid] = {'rchar:': 0, 'wchar:': 0, 'cputime:': 0, 'cpuper:': 0} ### Extract name name = proc_splitline('/proc/%s/stat' % pid)[1][1:-1] ### Extract counters for l in proc_splitlines('/proc/%s/io' % pid): if len(l) != 2: continue self.pidset2[pid][l[0]] = int(l[1]) ### Get CPU usage l = proc_splitline('/proc/%s/stat' % pid) if len(l) < 15: cpu_usage = 0 else: self.pidset2[pid]['cputime:'] = int(l[13]) + int(l[14]) cpu_usage = (self.pidset2[pid]['cputime:'] - self.pidset1[pid]['cputime:']) * 1.0 / elapsed / cpunr except ValueError: continue except IOError: continue except IndexError: continue read_usage = (self.pidset2[pid]['rchar:'] - self.pidset1[pid]['rchar:']) * 1.0 / elapsed write_usage = (self.pidset2[pid]['wchar:'] - self.pidset1[pid]['wchar:']) * 1.0 / elapsed usage = read_usage + write_usage ### Get the process that spends the most jiffies if usage > self.val['usage']: self.val['usage'] = usage self.val['read_usage'] = read_usage self.val['write_usage'] = write_usage self.val['pid'] = pid self.val['name'] = getnamebypid(pid, name) self.val['cpu_usage'] = cpu_usage if step == op.delay: self.pidset1 = self.pidset2 if self.val['usage'] != 0.0: self.output = '%-*s%s%-5s%s%s%s%s%%' % (self.width-14-len(pid), self.val['name'][0:self.width-14-len(pid)], color['darkblue'], self.val['pid'], cprint(self.val['read_usage'], 'd', 5, 1024), cprint(self.val['write_usage'], 'd', 5, 1024), cprint(self.val['cpu_usage'], 'f', 3, 34), color['darkgray']) def showcsv(self): return 'Top: %s\t%s\t%s\t%s' % (self.val['name'][0:self.width-20], self.val['read_usage'], self.val['write_usage'], self.val['cpu_usage'])
true
true
1c3959f5ce2f0e894ca1fdf9c1723ed860f7f4df
3,267
py
Python
Examples/EventProfiler/tutorial.py
romanbsd/QuantSoftwareToolkit
6b7e15fa3c0ba483a30674ff5acf30c77b91b877
[ "BSD-3-Clause" ]
3
2018-03-03T02:03:18.000Z
2020-07-31T23:10:03.000Z
Examples/EventProfiler/tutorial.py
romanbsd/QuantSoftwareToolkit
6b7e15fa3c0ba483a30674ff5acf30c77b91b877
[ "BSD-3-Clause" ]
null
null
null
Examples/EventProfiler/tutorial.py
romanbsd/QuantSoftwareToolkit
6b7e15fa3c0ba483a30674ff5acf30c77b91b877
[ "BSD-3-Clause" ]
6
2018-03-04T15:39:01.000Z
2021-12-30T13:26:22.000Z
''' (c) 2011, 2012 Georgia Tech Research Corporation This source code is released under the New BSD license. Please see http://wiki.quantsoftware.org/index.php?title=QSTK_License for license details. Created on January, 23, 2013 @author: Sourabh Bajaj @contact: sourabhbajaj@gatech.edu @summary: Event Profiler Tutorial ''' import pandas as pd import numpy as np import math import copy import QSTK.qstkutil.qsdateutil as du import datetime as dt import QSTK.qstkutil.DataAccess as da import QSTK.qstkutil.tsutil as tsu import QSTK.qstkstudy.EventProfiler as ep """ Accepts a list of symbols along with start and end date Returns the Event Matrix which is a pandas Datamatrix Event matrix has the following structure : |IBM |GOOG|XOM |MSFT| GS | JP | (d1)|nan |nan | 1 |nan |nan | 1 | (d2)|nan | 1 |nan |nan |nan |nan | (d3)| 1 |nan | 1 |nan | 1 |nan | (d4)|nan | 1 |nan | 1 |nan |nan | ................................... ................................... Also, d1 = start date nan = no information about any event. 1 = status bit(positively confirms the event occurence) """ def find_events(ls_symbols, d_data): ''' Finding the event dataframe ''' df_close = d_data['close'] ts_market = df_close['SPY'] print("Finding Events") # Creating an empty dataframe df_events = copy.deepcopy(df_close) df_events = df_events * np.NAN # Time stamps for the event range ldt_timestamps = df_close.index for s_sym in ls_symbols: for i in range(1, len(ldt_timestamps)): # Calculating the returns for this timestamp f_symprice_today = df_close[s_sym].ix[ldt_timestamps[i]] f_symprice_yest = df_close[s_sym].ix[ldt_timestamps[i - 1]] f_marketprice_today = ts_market.ix[ldt_timestamps[i]] f_marketprice_yest = ts_market.ix[ldt_timestamps[i - 1]] f_symreturn_today = (f_symprice_today / f_symprice_yest) - 1 f_marketreturn_today = (f_marketprice_today / f_marketprice_yest) - 1 # Event is found if the symbol is down more then 3% while the # market is up more then 2% if f_symreturn_today <= -0.03 and f_marketreturn_today >= 0.02: df_events[s_sym].ix[ldt_timestamps[i]] = 1 return df_events if __name__ == '__main__': dt_start = dt.datetime(2008, 1, 1) dt_end = dt.datetime(2009, 12, 31) ldt_timestamps = du.getNYSEdays(dt_start, dt_end, dt.timedelta(hours=16)) dataobj = da.DataAccess('Yahoo') ls_symbols = dataobj.get_symbols_from_list('sp5002012') ls_symbols.append('SPY') ls_keys = ['open', 'high', 'low', 'close', 'volume', 'actual_close'] ldf_data = dataobj.get_data(ldt_timestamps, ls_symbols, ls_keys) d_data = dict(list(zip(ls_keys, ldf_data))) for s_key in ls_keys: d_data[s_key] = d_data[s_key].fillna(method='ffill') d_data[s_key] = d_data[s_key].fillna(method='bfill') d_data[s_key] = d_data[s_key].fillna(1.0) df_events = find_events(ls_symbols, d_data) print("Creating Study") ep.eventprofiler(df_events, d_data, i_lookback=20, i_lookforward=20, s_filename='MyEventStudy.pdf', b_market_neutral=True, b_errorbars=True, s_market_sym='SPY')
33.680412
87
0.666361
import pandas as pd import numpy as np import math import copy import QSTK.qstkutil.qsdateutil as du import datetime as dt import QSTK.qstkutil.DataAccess as da import QSTK.qstkutil.tsutil as tsu import QSTK.qstkstudy.EventProfiler as ep def find_events(ls_symbols, d_data): df_close = d_data['close'] ts_market = df_close['SPY'] print("Finding Events") df_events = copy.deepcopy(df_close) df_events = df_events * np.NAN ldt_timestamps = df_close.index for s_sym in ls_symbols: for i in range(1, len(ldt_timestamps)): f_symprice_today = df_close[s_sym].ix[ldt_timestamps[i]] f_symprice_yest = df_close[s_sym].ix[ldt_timestamps[i - 1]] f_marketprice_today = ts_market.ix[ldt_timestamps[i]] f_marketprice_yest = ts_market.ix[ldt_timestamps[i - 1]] f_symreturn_today = (f_symprice_today / f_symprice_yest) - 1 f_marketreturn_today = (f_marketprice_today / f_marketprice_yest) - 1 if f_symreturn_today <= -0.03 and f_marketreturn_today >= 0.02: df_events[s_sym].ix[ldt_timestamps[i]] = 1 return df_events if __name__ == '__main__': dt_start = dt.datetime(2008, 1, 1) dt_end = dt.datetime(2009, 12, 31) ldt_timestamps = du.getNYSEdays(dt_start, dt_end, dt.timedelta(hours=16)) dataobj = da.DataAccess('Yahoo') ls_symbols = dataobj.get_symbols_from_list('sp5002012') ls_symbols.append('SPY') ls_keys = ['open', 'high', 'low', 'close', 'volume', 'actual_close'] ldf_data = dataobj.get_data(ldt_timestamps, ls_symbols, ls_keys) d_data = dict(list(zip(ls_keys, ldf_data))) for s_key in ls_keys: d_data[s_key] = d_data[s_key].fillna(method='ffill') d_data[s_key] = d_data[s_key].fillna(method='bfill') d_data[s_key] = d_data[s_key].fillna(1.0) df_events = find_events(ls_symbols, d_data) print("Creating Study") ep.eventprofiler(df_events, d_data, i_lookback=20, i_lookforward=20, s_filename='MyEventStudy.pdf', b_market_neutral=True, b_errorbars=True, s_market_sym='SPY')
true
true
1c395a2bb49bfe09ed8c4a70a44d073ecd425a73
2,000
py
Python
asgn09.py
qadeerassan/python-data-structures-I-a9
714bff87e22a2f7ef2b546a449e2bf90482d650a
[ "MIT" ]
null
null
null
asgn09.py
qadeerassan/python-data-structures-I-a9
714bff87e22a2f7ef2b546a449e2bf90482d650a
[ "MIT" ]
null
null
null
asgn09.py
qadeerassan/python-data-structures-I-a9
714bff87e22a2f7ef2b546a449e2bf90482d650a
[ "MIT" ]
null
null
null
""" ---------------------------------------------------- asgn09.py Holds functions for assignment 9. ---------------------------------------------------- Author: Qadeer Assan ID: 160257370 Email: assa7370@mylaurier.ca _updated_="2018-03-22" ---------------------------------------------------- """ from word import Word def insert_words(file_variable, hash_set): """ ------------------------------------------------------- Retrieves every Word in file_variable and inserts into a HashSet. ------------------------------------------------------- Preconditions: file_variable - the already open file containing data to evaluate (file) hash_set - the HashSet to insert the words into (HashSet) Postconditions: Each Word object in hash_set contains the number of comparisons required to insert that Word object from file_variable into hash_set. ------------------------------------------------------- """ for line in file_variable: line = line.strip().split() for word in line: if word.isalpha(): obj = Word(word.lower()) hash_set.insert(obj) def comparison_total(hash_set): """ ------------------------------------------------------- Sums the comparison values of all Word objects in hash_set. ------------------------------------------------------- Preconditions: hash_set - a hash set of Word objects (HashSet) Postconditions: returns total - the total of all comparison fields in the HashSet Word objects (int) max_word - the word having the most comparisons (Word) ------------------------------------------------------- """ total = 0 max_word = Word("temp") for word in hash_set: total += word.comparisons if word.comparisons > max_word.comparisons: max_word = word return total, max_word
35.714286
81
0.466
from word import Word def insert_words(file_variable, hash_set): for line in file_variable: line = line.strip().split() for word in line: if word.isalpha(): obj = Word(word.lower()) hash_set.insert(obj) def comparison_total(hash_set): total = 0 max_word = Word("temp") for word in hash_set: total += word.comparisons if word.comparisons > max_word.comparisons: max_word = word return total, max_word
true
true
1c395c05fd3ea21bc967978556d244ddb33ac6a5
12,086
py
Python
aries_cloudagent/core/tests/test_conductor.py
euroledger/aries-cloudagent-python
caf457276b19df374c16c2890e1c7e4914f46254
[ "Apache-2.0" ]
2
2019-10-10T16:33:01.000Z
2019-10-10T19:22:17.000Z
aries_cloudagent/core/tests/test_conductor.py
euroledger/aries-cloudagent-python
caf457276b19df374c16c2890e1c7e4914f46254
[ "Apache-2.0" ]
5
2019-10-13T01:28:48.000Z
2019-10-21T20:10:47.000Z
aries_cloudagent/core/tests/test_conductor.py
euroledger/aries-cloudagent-python
caf457276b19df374c16c2890e1c7e4914f46254
[ "Apache-2.0" ]
4
2019-07-09T20:41:03.000Z
2021-06-06T10:45:23.000Z
import asyncio from io import StringIO from asynctest import TestCase as AsyncTestCase from asynctest import mock as async_mock from .. import conductor as test_module from ...admin.base_server import BaseAdminServer from ...config.base_context import ContextBuilder from ...config.injection_context import InjectionContext from ...connections.models.connection_record import ConnectionRecord from ...connections.models.connection_target import ConnectionTarget from ...connections.models.diddoc import ( DIDDoc, PublicKey, PublicKeyType, Service, ) from ...core.protocol_registry import ProtocolRegistry from ...protocols.connections.manager import ConnectionManager from ...storage.base import BaseStorage from ...storage.basic import BasicStorage from ...transport.inbound.base import InboundTransportConfiguration from ...transport.inbound.message import InboundMessage from ...transport.inbound.receipt import MessageReceipt from ...transport.outbound.base import OutboundDeliveryError from ...transport.outbound.message import OutboundMessage from ...transport.wire_format import BaseWireFormat from ...utils.stats import Collector from ...wallet.base import BaseWallet from ...wallet.basic import BasicWallet class Config: test_settings = {} test_settings_with_queue = {"queue.enable_undelivered_queue": True} class TestDIDs: test_seed = "testseed000000000000000000000001" test_did = "55GkHamhTU1ZbTbV2ab9DE" test_verkey = "3Dn1SJNPaCXcvvJvSbsFWP2xaCjMom3can8CQNhWrTRx" test_endpoint = "http://localhost" test_target_did = "GbuDUYXaUZRfHD2jeDuQuP" test_target_verkey = "9WCgWKUaAJj3VWxxtzvvMQN3AoFxoBtBDo9ntwJnVVCC" def make_did_doc(self, did, verkey): doc = DIDDoc(did=did) controller = did ident = "1" pk_value = verkey pk = PublicKey( did, ident, pk_value, PublicKeyType.ED25519_SIG_2018, controller, False ) doc.set(pk) recip_keys = [pk] router_keys = [] service = Service( did, "indy", "IndyAgent", recip_keys, router_keys, self.test_endpoint ) doc.set(service) return doc, pk class StubContextBuilder(ContextBuilder): def __init__(self, settings): super().__init__(settings) self.wire_format = async_mock.create_autospec(BaseWireFormat()) async def build(self) -> InjectionContext: context = InjectionContext(settings=self.settings) context.injector.enforce_typing = False context.injector.bind_instance(BaseStorage, BasicStorage()) context.injector.bind_instance(BaseWallet, BasicWallet()) context.injector.bind_instance(ProtocolRegistry, ProtocolRegistry()) context.injector.bind_instance(BaseWireFormat, self.wire_format) return context class StubCollectorContextBuilder(StubContextBuilder): async def build(self) -> InjectionContext: context = await super().build() context.injector.bind_instance(Collector, Collector()) return context class TestConductor(AsyncTestCase, Config, TestDIDs): async def test_startup(self): builder: ContextBuilder = StubContextBuilder(self.test_settings) conductor = test_module.Conductor(builder) with async_mock.patch.object( test_module, "InboundTransportManager", autospec=True ) as mock_inbound_mgr, async_mock.patch.object( test_module, "OutboundTransportManager", autospec=True ) as mock_outbound_mgr, async_mock.patch.object( test_module, "LoggingConfigurator", autospec=True ) as mock_logger: await conductor.setup() mock_inbound_mgr.return_value.setup.assert_awaited_once() mock_outbound_mgr.return_value.setup.assert_awaited_once() mock_inbound_mgr.return_value.registered_transports = {} mock_outbound_mgr.return_value.registered_transports = {} await conductor.start() mock_inbound_mgr.return_value.start.assert_awaited_once_with() mock_outbound_mgr.return_value.start.assert_awaited_once_with() mock_logger.print_banner.assert_called_once() await conductor.stop() mock_inbound_mgr.return_value.stop.assert_awaited_once_with() mock_outbound_mgr.return_value.stop.assert_awaited_once_with() async def test_inbound_message_handler(self): builder: ContextBuilder = StubContextBuilder(self.test_settings) conductor = test_module.Conductor(builder) await conductor.setup() with async_mock.patch.object( conductor.dispatcher, "queue_message", autospec=True ) as mock_dispatch: message_body = "{}" receipt = MessageReceipt() message = InboundMessage(message_body, receipt) conductor.inbound_message_router(message) mock_dispatch.assert_called_once() assert mock_dispatch.call_args[0][0] is message assert mock_dispatch.call_args[0][1] == conductor.outbound_message_router assert mock_dispatch.call_args[0][2] is None # admin webhook router assert callable(mock_dispatch.call_args[0][3]) async def test_outbound_message_handler_return_route(self): builder: ContextBuilder = StubContextBuilder(self.test_settings) conductor = test_module.Conductor(builder) test_to_verkey = "test-to-verkey" test_from_verkey = "test-from-verkey" await conductor.setup() payload = "{}" message = OutboundMessage(payload=payload) message.reply_to_verkey = test_to_verkey receipt = MessageReceipt() receipt.recipient_verkey = test_from_verkey inbound = InboundMessage("[]", receipt) with async_mock.patch.object( conductor.inbound_transport_manager, "return_to_session" ) as mock_return, async_mock.patch.object( conductor, "queue_outbound", async_mock.CoroutineMock() ) as mock_queue: mock_return.return_value = True await conductor.outbound_message_router(conductor.context, message) mock_return.assert_called_once_with(message) mock_queue.assert_not_awaited() async def test_outbound_message_handler_with_target(self): builder: ContextBuilder = StubContextBuilder(self.test_settings) conductor = test_module.Conductor(builder) with async_mock.patch.object( test_module, "OutboundTransportManager", autospec=True ) as mock_outbound_mgr: await conductor.setup() payload = "{}" target = ConnectionTarget( endpoint="endpoint", recipient_keys=(), routing_keys=(), sender_key="" ) message = OutboundMessage(payload=payload, target=target) await conductor.outbound_message_router(conductor.context, message) mock_outbound_mgr.return_value.enqueue_message.assert_called_once_with( conductor.context, message ) async def test_outbound_message_handler_with_connection(self): builder: ContextBuilder = StubContextBuilder(self.test_settings) conductor = test_module.Conductor(builder) with async_mock.patch.object( test_module, "OutboundTransportManager", autospec=True ) as mock_outbound_mgr, async_mock.patch.object( test_module, "ConnectionManager", autospec=True ) as conn_mgr: await conductor.setup() payload = "{}" connection_id = "connection_id" message = OutboundMessage(payload=payload, connection_id=connection_id) await conductor.outbound_message_router(conductor.context, message) conn_mgr.assert_called_once_with(conductor.context) conn_mgr.return_value.get_connection_targets.assert_awaited_once_with( connection_id=connection_id ) assert ( message.target_list is conn_mgr.return_value.get_connection_targets.return_value ) mock_outbound_mgr.return_value.enqueue_message.assert_called_once_with( conductor.context, message ) async def test_admin(self): builder: ContextBuilder = StubContextBuilder(self.test_settings) builder.update_settings({"admin.enabled": "1"}) conductor = test_module.Conductor(builder) await conductor.setup() admin = await conductor.context.inject(BaseAdminServer) assert admin is conductor.admin_server with async_mock.patch.object( admin, "start", autospec=True ) as admin_start, async_mock.patch.object( admin, "stop", autospec=True ) as admin_stop: await conductor.start() admin_start.assert_awaited_once_with() await conductor.stop() admin_stop.assert_awaited_once_with() async def test_setup_collector(self): builder: ContextBuilder = StubCollectorContextBuilder(self.test_settings) conductor = test_module.Conductor(builder) with async_mock.patch.object( test_module, "InboundTransportManager", autospec=True ) as mock_inbound_mgr, async_mock.patch.object( test_module, "OutboundTransportManager", autospec=True ) as mock_outbound_mgr, async_mock.patch.object( test_module, "LoggingConfigurator", autospec=True ) as mock_logger: await conductor.setup() async def test_start_static(self): builder: ContextBuilder = StubContextBuilder(self.test_settings) builder.update_settings({"debug.test_suite_endpoint": True}) conductor = test_module.Conductor(builder) with async_mock.patch.object(test_module, "ConnectionManager") as mock_mgr: await conductor.setup() mock_mgr.return_value.create_static_connection = async_mock.CoroutineMock() await conductor.start() mock_mgr.return_value.create_static_connection.assert_awaited_once() async def test_print_invite(self): builder: ContextBuilder = StubContextBuilder(self.test_settings) builder.update_settings( {"debug.print_invitation": True, "invite_base_url": "http://localhost"} ) conductor = test_module.Conductor(builder) with async_mock.patch("sys.stdout", new=StringIO()) as captured: await conductor.setup() await conductor.start() await conductor.stop() assert "http://localhost?c_i=" in captured.getvalue() async def test_webhook_router(self): builder: ContextBuilder = StubContextBuilder(self.test_settings) builder.update_settings( {"debug.print_invitation": True, "invite_base_url": "http://localhost"} ) conductor = test_module.Conductor(builder) test_topic = "test-topic" test_payload = {"test": "payload"} test_endpoint = "http://example" test_attempts = 2 await conductor.setup() with async_mock.patch.object( conductor.outbound_transport_manager, "enqueue_webhook" ) as mock_enqueue: conductor.webhook_router( test_topic, test_payload, test_endpoint, test_attempts ) mock_enqueue.assert_called_once_with( test_topic, test_payload, test_endpoint, test_attempts ) # swallow error with async_mock.patch.object( conductor.outbound_transport_manager, "enqueue_webhook", side_effect=OutboundDeliveryError, ) as mock_enqueue: conductor.webhook_router( test_topic, test_payload, test_endpoint, test_attempts ) mock_enqueue.assert_called_once_with( test_topic, test_payload, test_endpoint, test_attempts )
38.006289
87
0.684015
import asyncio from io import StringIO from asynctest import TestCase as AsyncTestCase from asynctest import mock as async_mock from .. import conductor as test_module from ...admin.base_server import BaseAdminServer from ...config.base_context import ContextBuilder from ...config.injection_context import InjectionContext from ...connections.models.connection_record import ConnectionRecord from ...connections.models.connection_target import ConnectionTarget from ...connections.models.diddoc import ( DIDDoc, PublicKey, PublicKeyType, Service, ) from ...core.protocol_registry import ProtocolRegistry from ...protocols.connections.manager import ConnectionManager from ...storage.base import BaseStorage from ...storage.basic import BasicStorage from ...transport.inbound.base import InboundTransportConfiguration from ...transport.inbound.message import InboundMessage from ...transport.inbound.receipt import MessageReceipt from ...transport.outbound.base import OutboundDeliveryError from ...transport.outbound.message import OutboundMessage from ...transport.wire_format import BaseWireFormat from ...utils.stats import Collector from ...wallet.base import BaseWallet from ...wallet.basic import BasicWallet class Config: test_settings = {} test_settings_with_queue = {"queue.enable_undelivered_queue": True} class TestDIDs: test_seed = "testseed000000000000000000000001" test_did = "55GkHamhTU1ZbTbV2ab9DE" test_verkey = "3Dn1SJNPaCXcvvJvSbsFWP2xaCjMom3can8CQNhWrTRx" test_endpoint = "http://localhost" test_target_did = "GbuDUYXaUZRfHD2jeDuQuP" test_target_verkey = "9WCgWKUaAJj3VWxxtzvvMQN3AoFxoBtBDo9ntwJnVVCC" def make_did_doc(self, did, verkey): doc = DIDDoc(did=did) controller = did ident = "1" pk_value = verkey pk = PublicKey( did, ident, pk_value, PublicKeyType.ED25519_SIG_2018, controller, False ) doc.set(pk) recip_keys = [pk] router_keys = [] service = Service( did, "indy", "IndyAgent", recip_keys, router_keys, self.test_endpoint ) doc.set(service) return doc, pk class StubContextBuilder(ContextBuilder): def __init__(self, settings): super().__init__(settings) self.wire_format = async_mock.create_autospec(BaseWireFormat()) async def build(self) -> InjectionContext: context = InjectionContext(settings=self.settings) context.injector.enforce_typing = False context.injector.bind_instance(BaseStorage, BasicStorage()) context.injector.bind_instance(BaseWallet, BasicWallet()) context.injector.bind_instance(ProtocolRegistry, ProtocolRegistry()) context.injector.bind_instance(BaseWireFormat, self.wire_format) return context class StubCollectorContextBuilder(StubContextBuilder): async def build(self) -> InjectionContext: context = await super().build() context.injector.bind_instance(Collector, Collector()) return context class TestConductor(AsyncTestCase, Config, TestDIDs): async def test_startup(self): builder: ContextBuilder = StubContextBuilder(self.test_settings) conductor = test_module.Conductor(builder) with async_mock.patch.object( test_module, "InboundTransportManager", autospec=True ) as mock_inbound_mgr, async_mock.patch.object( test_module, "OutboundTransportManager", autospec=True ) as mock_outbound_mgr, async_mock.patch.object( test_module, "LoggingConfigurator", autospec=True ) as mock_logger: await conductor.setup() mock_inbound_mgr.return_value.setup.assert_awaited_once() mock_outbound_mgr.return_value.setup.assert_awaited_once() mock_inbound_mgr.return_value.registered_transports = {} mock_outbound_mgr.return_value.registered_transports = {} await conductor.start() mock_inbound_mgr.return_value.start.assert_awaited_once_with() mock_outbound_mgr.return_value.start.assert_awaited_once_with() mock_logger.print_banner.assert_called_once() await conductor.stop() mock_inbound_mgr.return_value.stop.assert_awaited_once_with() mock_outbound_mgr.return_value.stop.assert_awaited_once_with() async def test_inbound_message_handler(self): builder: ContextBuilder = StubContextBuilder(self.test_settings) conductor = test_module.Conductor(builder) await conductor.setup() with async_mock.patch.object( conductor.dispatcher, "queue_message", autospec=True ) as mock_dispatch: message_body = "{}" receipt = MessageReceipt() message = InboundMessage(message_body, receipt) conductor.inbound_message_router(message) mock_dispatch.assert_called_once() assert mock_dispatch.call_args[0][0] is message assert mock_dispatch.call_args[0][1] == conductor.outbound_message_router assert mock_dispatch.call_args[0][2] is None assert callable(mock_dispatch.call_args[0][3]) async def test_outbound_message_handler_return_route(self): builder: ContextBuilder = StubContextBuilder(self.test_settings) conductor = test_module.Conductor(builder) test_to_verkey = "test-to-verkey" test_from_verkey = "test-from-verkey" await conductor.setup() payload = "{}" message = OutboundMessage(payload=payload) message.reply_to_verkey = test_to_verkey receipt = MessageReceipt() receipt.recipient_verkey = test_from_verkey inbound = InboundMessage("[]", receipt) with async_mock.patch.object( conductor.inbound_transport_manager, "return_to_session" ) as mock_return, async_mock.patch.object( conductor, "queue_outbound", async_mock.CoroutineMock() ) as mock_queue: mock_return.return_value = True await conductor.outbound_message_router(conductor.context, message) mock_return.assert_called_once_with(message) mock_queue.assert_not_awaited() async def test_outbound_message_handler_with_target(self): builder: ContextBuilder = StubContextBuilder(self.test_settings) conductor = test_module.Conductor(builder) with async_mock.patch.object( test_module, "OutboundTransportManager", autospec=True ) as mock_outbound_mgr: await conductor.setup() payload = "{}" target = ConnectionTarget( endpoint="endpoint", recipient_keys=(), routing_keys=(), sender_key="" ) message = OutboundMessage(payload=payload, target=target) await conductor.outbound_message_router(conductor.context, message) mock_outbound_mgr.return_value.enqueue_message.assert_called_once_with( conductor.context, message ) async def test_outbound_message_handler_with_connection(self): builder: ContextBuilder = StubContextBuilder(self.test_settings) conductor = test_module.Conductor(builder) with async_mock.patch.object( test_module, "OutboundTransportManager", autospec=True ) as mock_outbound_mgr, async_mock.patch.object( test_module, "ConnectionManager", autospec=True ) as conn_mgr: await conductor.setup() payload = "{}" connection_id = "connection_id" message = OutboundMessage(payload=payload, connection_id=connection_id) await conductor.outbound_message_router(conductor.context, message) conn_mgr.assert_called_once_with(conductor.context) conn_mgr.return_value.get_connection_targets.assert_awaited_once_with( connection_id=connection_id ) assert ( message.target_list is conn_mgr.return_value.get_connection_targets.return_value ) mock_outbound_mgr.return_value.enqueue_message.assert_called_once_with( conductor.context, message ) async def test_admin(self): builder: ContextBuilder = StubContextBuilder(self.test_settings) builder.update_settings({"admin.enabled": "1"}) conductor = test_module.Conductor(builder) await conductor.setup() admin = await conductor.context.inject(BaseAdminServer) assert admin is conductor.admin_server with async_mock.patch.object( admin, "start", autospec=True ) as admin_start, async_mock.patch.object( admin, "stop", autospec=True ) as admin_stop: await conductor.start() admin_start.assert_awaited_once_with() await conductor.stop() admin_stop.assert_awaited_once_with() async def test_setup_collector(self): builder: ContextBuilder = StubCollectorContextBuilder(self.test_settings) conductor = test_module.Conductor(builder) with async_mock.patch.object( test_module, "InboundTransportManager", autospec=True ) as mock_inbound_mgr, async_mock.patch.object( test_module, "OutboundTransportManager", autospec=True ) as mock_outbound_mgr, async_mock.patch.object( test_module, "LoggingConfigurator", autospec=True ) as mock_logger: await conductor.setup() async def test_start_static(self): builder: ContextBuilder = StubContextBuilder(self.test_settings) builder.update_settings({"debug.test_suite_endpoint": True}) conductor = test_module.Conductor(builder) with async_mock.patch.object(test_module, "ConnectionManager") as mock_mgr: await conductor.setup() mock_mgr.return_value.create_static_connection = async_mock.CoroutineMock() await conductor.start() mock_mgr.return_value.create_static_connection.assert_awaited_once() async def test_print_invite(self): builder: ContextBuilder = StubContextBuilder(self.test_settings) builder.update_settings( {"debug.print_invitation": True, "invite_base_url": "http://localhost"} ) conductor = test_module.Conductor(builder) with async_mock.patch("sys.stdout", new=StringIO()) as captured: await conductor.setup() await conductor.start() await conductor.stop() assert "http://localhost?c_i=" in captured.getvalue() async def test_webhook_router(self): builder: ContextBuilder = StubContextBuilder(self.test_settings) builder.update_settings( {"debug.print_invitation": True, "invite_base_url": "http://localhost"} ) conductor = test_module.Conductor(builder) test_topic = "test-topic" test_payload = {"test": "payload"} test_endpoint = "http://example" test_attempts = 2 await conductor.setup() with async_mock.patch.object( conductor.outbound_transport_manager, "enqueue_webhook" ) as mock_enqueue: conductor.webhook_router( test_topic, test_payload, test_endpoint, test_attempts ) mock_enqueue.assert_called_once_with( test_topic, test_payload, test_endpoint, test_attempts ) with async_mock.patch.object( conductor.outbound_transport_manager, "enqueue_webhook", side_effect=OutboundDeliveryError, ) as mock_enqueue: conductor.webhook_router( test_topic, test_payload, test_endpoint, test_attempts ) mock_enqueue.assert_called_once_with( test_topic, test_payload, test_endpoint, test_attempts )
true
true
1c395d7edb3f718bfdf9111d3fd63749240be388
811
py
Python
python/523_Continuous_Subarray_Sum.py
liaison/LeetCode
8b10a1f6bbeb3ebfda99248994f7c325140ee2fd
[ "MIT" ]
17
2016-03-01T22:40:53.000Z
2021-04-19T02:15:03.000Z
python/523_Continuous_Subarray_Sum.py
liaison/LeetCode
8b10a1f6bbeb3ebfda99248994f7c325140ee2fd
[ "MIT" ]
null
null
null
python/523_Continuous_Subarray_Sum.py
liaison/LeetCode
8b10a1f6bbeb3ebfda99248994f7c325140ee2fd
[ "MIT" ]
3
2019-03-07T03:48:43.000Z
2020-04-05T01:11:36.000Z
class Solution: def checkSubarraySum(self, nums: List[int], k: int) -> bool: # the earliest index with the same module remaider of k prefix_sum_indices = {} # a virtual prefix sum index. # for the test case of [0, 0] k = 0 prefix_sum = 0 prefix_sum_indices[0] = -1 for index, num in enumerate(nums): prefix_sum += num # group the prefix sums with modulo if k != 0: prefix_sum %= k # normalize the sum if prefix_sum in prefix_sum_indices: if index - prefix_sum_indices[prefix_sum] > 1: return True else: prefix_sum_indices[prefix_sum] = index return False
30.037037
64
0.509248
class Solution: def checkSubarraySum(self, nums: List[int], k: int) -> bool: prefix_sum_indices = {} prefix_sum = 0 prefix_sum_indices[0] = -1 for index, num in enumerate(nums): prefix_sum += num if k != 0: prefix_sum %= k if prefix_sum in prefix_sum_indices: if index - prefix_sum_indices[prefix_sum] > 1: return True else: prefix_sum_indices[prefix_sum] = index return False
true
true
1c395dbab07719fc7ed142448f04c349ad8f54ca
1,951
py
Python
espnet/nets/tts_interface.py
szmmm/speechchain
909724c6f305588a52958f64f584ad21696b5173
[ "Apache-2.0" ]
3
2019-10-11T11:41:27.000Z
2020-05-21T09:08:44.000Z
espnet/nets/tts_interface.py
szmmm/speechchain
909724c6f305588a52958f64f584ad21696b5173
[ "Apache-2.0" ]
null
null
null
espnet/nets/tts_interface.py
szmmm/speechchain
909724c6f305588a52958f64f584ad21696b5173
[ "Apache-2.0" ]
1
2021-04-07T09:47:44.000Z
2021-04-07T09:47:44.000Z
import chainer class Reporter(chainer.Chain): def report(self, dicts): for d in dicts: chainer.reporter.report(d, self) class TTSInterface(object): """TTS Interface for ESPnet model implementation""" @staticmethod def add_arguments(parser): return parser def __init__(self): self.reporter = Reporter() def forward(self, *args, **kwargs): """Calculate TTS forward propagation :return: loss value :rtype: torch.Tensor """ raise NotImplementedError("forward method is not implemented") def inference(self, *args, **kwargs): """Generates the sequence of features given the sequences of characters :return: the sequence of features (L, odim) :rtype: torch.Tensor :return: the sequence of stop probabilities (L) :rtype: torch.Tensor :return: the sequence of attention weight (L, T) :rtype: torch.Tensor """ raise NotImplementedError("inference method is not implemented") def calculate_all_attentions(self, *args, **kwargs): """Calculate TTS attention weights :return: attention weights (B, Lmax, Tmax) :rtype: numpy array """ raise NotImplementedError("calculate_all_attentions method is not implemented") @property def attention_plot_class(self): from espnet.asr.asr_utils import PlotAttentionReport return PlotAttentionReport @property def base_plot_keys(self): """base key names to plot during training. keys should match what `chainer.reporter` reports if you add the key `loss`, the reporter will report `main/loss` and `validation/main/loss` values. also `loss.png` will be created as a figure visulizing `main/loss` and `validation/main/loss` values. :rtype list[str] plot_keys: base keys to plot during training """ return ['loss']
30.968254
109
0.652486
import chainer class Reporter(chainer.Chain): def report(self, dicts): for d in dicts: chainer.reporter.report(d, self) class TTSInterface(object): @staticmethod def add_arguments(parser): return parser def __init__(self): self.reporter = Reporter() def forward(self, *args, **kwargs): raise NotImplementedError("forward method is not implemented") def inference(self, *args, **kwargs): raise NotImplementedError("inference method is not implemented") def calculate_all_attentions(self, *args, **kwargs): raise NotImplementedError("calculate_all_attentions method is not implemented") @property def attention_plot_class(self): from espnet.asr.asr_utils import PlotAttentionReport return PlotAttentionReport @property def base_plot_keys(self): return ['loss']
true
true
1c395e81d0785fcb41d2e2daa5b42f97a6d910e7
1,672
py
Python
neutron/tests/unit/linuxbridge/test_defaults.py
SnabbCo/neutron
a657c06d10f2171149c6b1863df36522bdc11cd7
[ "Apache-2.0" ]
3
2015-02-02T02:51:39.000Z
2015-02-23T10:20:23.000Z
neutron/tests/unit/linuxbridge/test_defaults.py
SnabbCo/neutron
a657c06d10f2171149c6b1863df36522bdc11cd7
[ "Apache-2.0" ]
4
2015-02-23T10:21:11.000Z
2015-03-04T09:28:20.000Z
neutron/tests/unit/linuxbridge/test_defaults.py
SnabbCo/neutron
a657c06d10f2171149c6b1863df36522bdc11cd7
[ "Apache-2.0" ]
4
2015-04-14T10:06:51.000Z
2019-10-02T01:28:34.000Z
# Copyright (c) 2012 OpenStack Foundation. # # 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 oslo.config import cfg from neutron.plugins.linuxbridge.common import config # noqa from neutron.tests import base class ConfigurationTest(base.BaseTestCase): def test_defaults(self): self.assertEqual(2, cfg.CONF.AGENT.polling_interval) self.assertEqual(False, cfg.CONF.AGENT.rpc_support_old_agents) self.assertEqual('sudo', cfg.CONF.AGENT.root_helper) self.assertEqual('local', cfg.CONF.VLANS.tenant_network_type) self.assertEqual(0, len(cfg.CONF.VLANS.network_vlan_ranges)) self.assertEqual(0, len(cfg.CONF.LINUX_BRIDGE. physical_interface_mappings)) self.assertEqual(False, cfg.CONF.VXLAN.enable_vxlan) self.assertEqual(config.DEFAULT_VXLAN_GROUP, cfg.CONF.VXLAN.vxlan_group) self.assertEqual(0, len(cfg.CONF.VXLAN.local_ip)) self.assertEqual(False, cfg.CONF.VXLAN.l2_population)
38.883721
69
0.660287
from oslo.config import cfg from neutron.plugins.linuxbridge.common import config from neutron.tests import base class ConfigurationTest(base.BaseTestCase): def test_defaults(self): self.assertEqual(2, cfg.CONF.AGENT.polling_interval) self.assertEqual(False, cfg.CONF.AGENT.rpc_support_old_agents) self.assertEqual('sudo', cfg.CONF.AGENT.root_helper) self.assertEqual('local', cfg.CONF.VLANS.tenant_network_type) self.assertEqual(0, len(cfg.CONF.VLANS.network_vlan_ranges)) self.assertEqual(0, len(cfg.CONF.LINUX_BRIDGE. physical_interface_mappings)) self.assertEqual(False, cfg.CONF.VXLAN.enable_vxlan) self.assertEqual(config.DEFAULT_VXLAN_GROUP, cfg.CONF.VXLAN.vxlan_group) self.assertEqual(0, len(cfg.CONF.VXLAN.local_ip)) self.assertEqual(False, cfg.CONF.VXLAN.l2_population)
true
true
1c395eb8b89c86ddd4fe3e5cf7c5322c461ea836
2,204
py
Python
hypixelaPY/objects/quake.py
QuartzWarrior/hypixelaPY
cb6a96ce8b15ebd3f6fa0666df46bc6135f0afb0
[ "MIT" ]
3
2021-01-04T14:29:03.000Z
2021-02-24T11:06:41.000Z
hypixelaPY/objects/quake.py
QuartzWarrior/hypixelaPY
cb6a96ce8b15ebd3f6fa0666df46bc6135f0afb0
[ "MIT" ]
2
2021-09-21T18:31:46.000Z
2021-09-22T13:50:28.000Z
hypixelaPY/objects/quake.py
myerrr/hypixelaPY
336ff2723a336142254b9e01b969adda98fa5f96
[ "MIT" ]
1
2021-05-01T02:16:36.000Z
2021-05-01T02:16:36.000Z
""" MIT License Copyright (c) 2020 Myer 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 .stats import KillsDeaths class Quake: def __init__(self, data): self.name = "Quake" self.coins = data.get("player", {}).get("stats", {}).get("Quake", {}).get("coins", 0) self.kills = KillsDeaths( data.get("player", {}).get("stats", {}).get("Quake", {}).get("kills", 0), data.get("player", {}).get("stats", {}).get("Quake", {}).get("deaths", 0) ) self.wins = data.get("player", {}).get("stats", {}).get("Quake", {}).get("wins", 0) self.headshots = data.get("player", {}).get("stats", {}).get("Quake", {}).get("headshots", 0) self.killstreaks = Killstreaks(data) self.shots_fired = data.get("player", {}).get("stats", {}).get("Quake", {}).get("shots_fired", 0) def __str__(self): return self.name class Killstreaks: def __init__(self, data): self.name = "Killstreaks" self.killstreaks = self.amount = self.total = data.get("player", {}).get("stats", {}).get("Quake", {}).get("killstreaks", 0) self.highest = data.get("player", {}).get("stats", {}).get("Quake", {}).get("highest_killstreak", 0)
44.979592
132
0.670145
from .stats import KillsDeaths class Quake: def __init__(self, data): self.name = "Quake" self.coins = data.get("player", {}).get("stats", {}).get("Quake", {}).get("coins", 0) self.kills = KillsDeaths( data.get("player", {}).get("stats", {}).get("Quake", {}).get("kills", 0), data.get("player", {}).get("stats", {}).get("Quake", {}).get("deaths", 0) ) self.wins = data.get("player", {}).get("stats", {}).get("Quake", {}).get("wins", 0) self.headshots = data.get("player", {}).get("stats", {}).get("Quake", {}).get("headshots", 0) self.killstreaks = Killstreaks(data) self.shots_fired = data.get("player", {}).get("stats", {}).get("Quake", {}).get("shots_fired", 0) def __str__(self): return self.name class Killstreaks: def __init__(self, data): self.name = "Killstreaks" self.killstreaks = self.amount = self.total = data.get("player", {}).get("stats", {}).get("Quake", {}).get("killstreaks", 0) self.highest = data.get("player", {}).get("stats", {}).get("Quake", {}).get("highest_killstreak", 0)
true
true
1c395f2ce46aa11c29c30e7c60549fb45d8d9850
3,284
py
Python
benchmark/startCirq3278.py
UCLA-SEAL/QDiff
d968cbc47fe926b7f88b4adf10490f1edd6f8819
[ "BSD-3-Clause" ]
null
null
null
benchmark/startCirq3278.py
UCLA-SEAL/QDiff
d968cbc47fe926b7f88b4adf10490f1edd6f8819
[ "BSD-3-Clause" ]
null
null
null
benchmark/startCirq3278.py
UCLA-SEAL/QDiff
d968cbc47fe926b7f88b4adf10490f1edd6f8819
[ "BSD-3-Clause" ]
null
null
null
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Time : 5/15/20 4:49 PM # @File : grover.py # qubit number=4 # total number=43 import cirq import cirq.google as cg from typing import Optional import sys from math import log2 import numpy as np #thatsNoCode from cirq.contrib.svg import SVGCircuit # Symbols for the rotation angles in the QAOA circuit. def make_circuit(n: int, input_qubit): c = cirq.Circuit() # circuit begin c.append(cirq.H.on(input_qubit[0])) # number=9 c.append(cirq.H.on(input_qubit[1])) # number=2 c.append(cirq.H.on(input_qubit[2])) # number=3 c.append(cirq.H.on(input_qubit[3])) # number=4 c.append(cirq.H.on(input_qubit[0])) # number=5 c.append(cirq.H.on(input_qubit[1])) # number=6 c.append(cirq.H.on(input_qubit[2])) # number=7 c.append(cirq.H.on(input_qubit[3])) # number=8 c.append(cirq.CNOT.on(input_qubit[0],input_qubit[2])) # number=37 c.append(cirq.X.on(input_qubit[2])) # number=38 c.append(cirq.CNOT.on(input_qubit[0],input_qubit[2])) # number=39 c.append(cirq.Y.on(input_qubit[1])) # number=19 c.append(cirq.H.on(input_qubit[3])) # number=31 c.append(cirq.CZ.on(input_qubit[0],input_qubit[3])) # number=32 c.append(cirq.H.on(input_qubit[3])) # number=33 c.append(cirq.X.on(input_qubit[3])) # number=29 c.append(cirq.H.on(input_qubit[3])) # number=40 c.append(cirq.CZ.on(input_qubit[0],input_qubit[3])) # number=41 c.append(cirq.H.on(input_qubit[3])) # number=42 c.append(cirq.Y.on(input_qubit[2])) # number=10 c.append(cirq.Y.on(input_qubit[2])) # number=11 c.append(cirq.Y.on(input_qubit[3])) # number=20 c.append(cirq.Y.on(input_qubit[1])) # number=12 c.append(cirq.rx(-2.158274153016188).on(input_qubit[3])) # number=24 c.append(cirq.H.on(input_qubit[0])) # number=16 c.append(cirq.CZ.on(input_qubit[2],input_qubit[0])) # number=17 c.append(cirq.H.on(input_qubit[0])) # number=18 c.append(cirq.CNOT.on(input_qubit[1],input_qubit[0])) # number=21 c.append(cirq.Z.on(input_qubit[1])) # number=22 c.append(cirq.CNOT.on(input_qubit[1],input_qubit[0])) # number=23 c.append(cirq.H.on(input_qubit[0])) # number=25 c.append(cirq.CZ.on(input_qubit[2],input_qubit[0])) # number=26 c.append(cirq.H.on(input_qubit[0])) # number=27 c.append(cirq.X.on(input_qubit[0])) # number=35 c.append(cirq.X.on(input_qubit[0])) # number=36 # circuit end c.append(cirq.measure(*input_qubit, key='result')) return c def bitstring(bits): return ''.join(str(int(b)) for b in bits) if __name__ == '__main__': qubit_count = 4 input_qubits = [cirq.GridQubit(i, 0) for i in range(qubit_count)] circuit = make_circuit(qubit_count,input_qubits) circuit = cg.optimized_for_sycamore(circuit, optimizer_type='sqrt_iswap') circuit_sample_count =2000 simulator = cirq.Simulator() result = simulator.run(circuit, repetitions=circuit_sample_count) frequencies = result.histogram(key='result', fold_func=bitstring) writefile = open("../data/startCirq3278.csv","w+") print(format(frequencies),file=writefile) print("results end", file=writefile) print(circuit.__len__(), file=writefile) print(circuit,file=writefile) writefile.close()
36.898876
77
0.678745
import cirq import cirq.google as cg from typing import Optional import sys from math import log2 import numpy as np from cirq.contrib.svg import SVGCircuit def make_circuit(n: int, input_qubit): c = cirq.Circuit() c.append(cirq.H.on(input_qubit[0])) c.append(cirq.H.on(input_qubit[1])) c.append(cirq.H.on(input_qubit[2])) c.append(cirq.H.on(input_qubit[3])) c.append(cirq.H.on(input_qubit[0])) c.append(cirq.H.on(input_qubit[1])) c.append(cirq.H.on(input_qubit[2])) c.append(cirq.H.on(input_qubit[3])) c.append(cirq.CNOT.on(input_qubit[0],input_qubit[2])) c.append(cirq.X.on(input_qubit[2])) c.append(cirq.CNOT.on(input_qubit[0],input_qubit[2])) c.append(cirq.Y.on(input_qubit[1])) c.append(cirq.H.on(input_qubit[3])) c.append(cirq.CZ.on(input_qubit[0],input_qubit[3])) c.append(cirq.H.on(input_qubit[3])) c.append(cirq.X.on(input_qubit[3])) c.append(cirq.H.on(input_qubit[3])) c.append(cirq.CZ.on(input_qubit[0],input_qubit[3])) c.append(cirq.H.on(input_qubit[3])) c.append(cirq.Y.on(input_qubit[2])) c.append(cirq.Y.on(input_qubit[2])) c.append(cirq.Y.on(input_qubit[3])) c.append(cirq.Y.on(input_qubit[1])) c.append(cirq.rx(-2.158274153016188).on(input_qubit[3])) c.append(cirq.H.on(input_qubit[0])) c.append(cirq.CZ.on(input_qubit[2],input_qubit[0])) c.append(cirq.H.on(input_qubit[0])) c.append(cirq.CNOT.on(input_qubit[1],input_qubit[0])) c.append(cirq.Z.on(input_qubit[1])) c.append(cirq.CNOT.on(input_qubit[1],input_qubit[0])) c.append(cirq.H.on(input_qubit[0])) c.append(cirq.CZ.on(input_qubit[2],input_qubit[0])) c.append(cirq.H.on(input_qubit[0])) c.append(cirq.X.on(input_qubit[0])) c.append(cirq.X.on(input_qubit[0])) c.append(cirq.measure(*input_qubit, key='result')) return c def bitstring(bits): return ''.join(str(int(b)) for b in bits) if __name__ == '__main__': qubit_count = 4 input_qubits = [cirq.GridQubit(i, 0) for i in range(qubit_count)] circuit = make_circuit(qubit_count,input_qubits) circuit = cg.optimized_for_sycamore(circuit, optimizer_type='sqrt_iswap') circuit_sample_count =2000 simulator = cirq.Simulator() result = simulator.run(circuit, repetitions=circuit_sample_count) frequencies = result.histogram(key='result', fold_func=bitstring) writefile = open("../data/startCirq3278.csv","w+") print(format(frequencies),file=writefile) print("results end", file=writefile) print(circuit.__len__(), file=writefile) print(circuit,file=writefile) writefile.close()
true
true
1c39613a5d2cda13b72a9b04ba4f1fd6dbc8681a
513
py
Python
tests/conftest.py
prorevizor/noc
37e44b8afc64318b10699c06a1138eee9e7d6a4e
[ "BSD-3-Clause" ]
84
2017-10-22T11:01:39.000Z
2022-02-27T03:43:48.000Z
tests/conftest.py
prorevizor/noc
37e44b8afc64318b10699c06a1138eee9e7d6a4e
[ "BSD-3-Clause" ]
22
2017-12-11T07:21:56.000Z
2021-09-23T02:53:50.000Z
tests/conftest.py
prorevizor/noc
37e44b8afc64318b10699c06a1138eee9e7d6a4e
[ "BSD-3-Clause" ]
23
2017-12-06T06:59:52.000Z
2022-02-24T00:02:25.000Z
# ---------------------------------------------------------------------- # pytest configuration # ---------------------------------------------------------------------- # Copyright (C) 2007-2020 The NOC Project # See LICENSE for details # ---------------------------------------------------------------------- # NOC modules from noc.tests.fixtures.database import database # noqa def pytest_terminal_summary(terminalreporter, exitstatus): global _stats _stats = terminalreporter.stats _stats = None
28.5
72
0.442495
from noc.tests.fixtures.database import database def pytest_terminal_summary(terminalreporter, exitstatus): global _stats _stats = terminalreporter.stats _stats = None
true
true
1c396179fdc1baf926d524a0f740d38daaa3bc17
20,506
py
Python
main.py
FloWuenne/semi-auto-image-annotation-tool
f48f521c480a436bafb148b4ecaf9f2c4a898211
[ "Apache-2.0" ]
null
null
null
main.py
FloWuenne/semi-auto-image-annotation-tool
f48f521c480a436bafb148b4ecaf9f2c4a898211
[ "Apache-2.0" ]
null
null
null
main.py
FloWuenne/semi-auto-image-annotation-tool
f48f521c480a436bafb148b4ecaf9f2c4a898211
[ "Apache-2.0" ]
null
null
null
""" Copyright {2018} {Viraj Mavani} 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 """ from tkinter import * from tkinter import filedialog from PIL import Image, ImageTk import keras from keras_retinanet import models from keras_retinanet.utils.image import preprocess_image # import miscellaneous modules import os import numpy as np import tensorflow as tf import config import math def get_session(): config = tf.compat.v1.ConfigProto() config.gpu_options.allow_growth = True return tf.compat.v1.Session(config=config) tf.compat.v1.keras.backend.set_session(get_session()) model_path = os.path.join('.', 'snapshots', 'resnet50_coco_best_v2.1.0.h5') model = models.load_model(model_path, backbone_name='resnet50') class MainGUI: def __init__(self, master): self.parent = master self.parent.title("Semi Automatic Image Annotation Tool") self.frame = Frame(self.parent) self.frame.pack(fill=BOTH, expand=1) self.parent.resizable(width=False, height=False) # Initialize class variables self.img = None self.tkimg = None self.imageDir = '' self.imageDirPathBuffer = '' self.imageList = [] self.imageTotal = 0 self.imageCur = 0 self.cur = 0 self.bboxIdList = [] self.bboxList = [] self.bboxPointList = [] self.o1 = None self.o2 = None self.o3 = None self.o4 = None self.bboxId = None self.currLabel = None self.editbboxId = None self.currBboxColor = None self.zoomImgId = None self.zoomImg = None self.zoomImgCrop = None self.tkZoomImg = None self.hl = None self.vl = None self.editPointId = None self.filename = None self.filenameBuffer = None self.objectLabelList = [] self.EDIT = False # initialize mouse state self.STATE = {'x': 0, 'y': 0} self.STATE_COCO = {'click': 0} # initialize annotation file self.anno_filename = 'annotations.csv' self.annotation_file = open('annotations/' + self.anno_filename, 'w+') self.annotation_file.write("") self.annotation_file.close() # ------------------ GUI --------------------- # Control Panel self.ctrlPanel = Frame(self.frame) self.ctrlPanel.grid(row=0, column=0, sticky=W + N) self.openBtn = Button(self.ctrlPanel, text='Open', command=self.open_image) self.openBtn.pack(fill=X, side=TOP) self.openDirBtn = Button(self.ctrlPanel, text='Open Dir', command=self.open_image_dir) self.openDirBtn.pack(fill=X, side=TOP) self.nextBtn = Button(self.ctrlPanel, text='Next -->', command=self.open_next) self.nextBtn.pack(fill=X, side=TOP) self.previousBtn = Button(self.ctrlPanel, text='<-- Previous', command=self.open_previous) self.previousBtn.pack(fill=X, side=TOP) self.saveBtn = Button(self.ctrlPanel, text='Save', command=self.save) self.saveBtn.pack(fill=X, side=TOP) self.semiAutoBtn = Button(self.ctrlPanel, text="Show Suggestions", command=self.automate) self.semiAutoBtn.pack(fill=X, side=TOP) self.disp = Label(self.ctrlPanel, text='Coordinates:') self.disp.pack(fill=X, side=TOP) self.mb = Menubutton(self.ctrlPanel, text="COCO Classes for Suggestions", relief=RAISED) self.mb.pack(fill=X, side=TOP) self.mb.menu = Menu(self.mb, tearoff=0) self.mb["menu"] = self.mb.menu self.addCocoBtn = Button(self.ctrlPanel, text="+", command=self.add_labels_coco) self.addCocoBtn.pack(fill=X, side=TOP) self.zoomPanelLabel = Label(self.ctrlPanel, text="Precision View Panel") self.zoomPanelLabel.pack(fill=X, side=TOP) self.zoomcanvas = Canvas(self.ctrlPanel, width=150, height=150) self.zoomcanvas.pack(fill=X, side=TOP, anchor='center') # Image Editing Region self.canvas = Canvas(self.frame, width=500, height=500) self.canvas.grid(row=0, column=1, sticky=W + N) self.canvas.bind("<Button-1>", self.mouse_click) self.canvas.bind("<Motion>", self.mouse_move, "+") self.canvas.bind("<B1-Motion>", self.mouse_drag) self.canvas.bind("<ButtonRelease-1>", self.mouse_release) self.parent.bind("<Key-Left>", self.open_previous) self.parent.bind("<Key-Right>", self.open_next) self.parent.bind("Escape", self.cancel_bbox) # Labels and Bounding Box Lists Panel self.listPanel = Frame(self.frame) self.listPanel.grid(row=0, column=2, sticky=W + N) self.listBoxNameLabel = Label(self.listPanel, text="List of Objects").pack(fill=X, side=TOP) self.objectListBox = Listbox(self.listPanel, width=40) self.objectListBox.pack(fill=X, side=TOP) self.delObjectBtn = Button(self.listPanel, text="Delete", command=self.del_bbox) self.delObjectBtn.pack(fill=X, side=TOP) self.clearAllBtn = Button(self.listPanel, text="Clear All", command=self.clear_bbox) self.clearAllBtn.pack(fill=X, side=TOP) self.classesNameLabel = Label(self.listPanel, text="Classes").pack(fill=X, side=TOP) self.textBox = Entry(self.listPanel, text="Enter label") self.textBox.pack(fill=X, side=TOP) self.addLabelBtn = Button(self.listPanel, text="+", command=self.add_label).pack(fill=X, side=TOP) self.delLabelBtn = Button(self.listPanel, text="-", command=self.del_label).pack(fill=X, side=TOP) self.labelListBox = Listbox(self.listPanel) self.labelListBox.pack(fill=X, side=TOP) self.cocoLabels = config.labels_to_names.values() self.cocoIntVars = [] for idxcoco, label_coco in enumerate(self.cocoLabels): self.cocoIntVars.append(IntVar()) self.mb.menu.add_checkbutton(label=label_coco, variable=self.cocoIntVars[idxcoco]) # print(self.cocoIntVars) # STATUS BAR self.statusBar = Frame(self.frame, width=500) self.statusBar.grid(row=1, column=1, sticky=W + N) self.processingLabel = Label(self.statusBar, text=" ") self.processingLabel.pack(side="left", fill=X) self.imageIdxLabel = Label(self.statusBar, text=" ") self.imageIdxLabel.pack(side="right", fill=X) def open_image(self): self.filename = filedialog.askopenfilename(title="Select Image", filetypes=(("jpeg files", "*.jpg"), ("all files", "*.*"))) if not self.filename: return None self.filenameBuffer = self.filename self.load_image(self.filenameBuffer) def open_image_dir(self): self.imageDir = filedialog.askdirectory(title="Select Dataset Directory") if not self.imageDir: return None self.imageList = os.listdir(self.imageDir) self.imageList = sorted(self.imageList) self.imageTotal = len(self.imageList) self.filename = None self.imageDirPathBuffer = self.imageDir self.load_image(self.imageDirPathBuffer + '/' + self.imageList[self.cur]) def load_image(self, file): self.img = Image.open(file) self.imageCur = self.cur + 1 self.imageIdxLabel.config(text=' || Image Number: %d / %d' % (self.imageCur, self.imageTotal)) # Resize to Pascal VOC format w, h = self.img.size if w >= h: baseW = 500 wpercent = (baseW / float(w)) hsize = int((float(h) * float(wpercent))) self.img = self.img.resize((baseW, hsize), Image.BICUBIC) else: baseH = 500 wpercent = (baseH / float(h)) wsize = int((float(w) * float(wpercent))) self.img = self.img.resize((wsize, baseH), Image.BICUBIC) self.tkimg = ImageTk.PhotoImage(self.img) self.canvas.create_image(0, 0, image=self.tkimg, anchor=NW) self.clear_bbox() def open_next(self, event=None): self.save() if self.cur < len(self.imageList): self.cur += 1 self.load_image(self.imageDirPathBuffer + '/' + self.imageList[self.cur]) self.processingLabel.config(text=" ") self.processingLabel.update_idletasks() def open_previous(self, event=None): self.save() if self.cur > 0: self.cur -= 1 self.load_image(self.imageDirPathBuffer + '/' + self.imageList[self.cur]) self.processingLabel.config(text=" ") self.processingLabel.update_idletasks() def save(self): if self.filenameBuffer is None: self.annotation_file = open('annotations/' + self.anno_filename, 'a') for idx, item in enumerate(self.bboxList): self.annotation_file.write(self.imageDirPathBuffer + '/' + self.imageList[self.cur] + ',' + ','.join(map(str, self.bboxList[idx])) + ',' + str(self.objectLabelList[idx]) + '\n') self.annotation_file.close() else: self.annotation_file = open('annotations/' + self.anno_filename, 'a') for idx, item in enumerate(self.bboxList): self.annotation_file.write(self.filenameBuffer + ',' + ','.join(map(str, self.bboxList[idx])) + ',' + str(self.objectLabelList[idx]) + '\n') self.annotation_file.close() def mouse_click(self, event): # Check if Updating BBox if self.canvas.find_enclosed(event.x - 5, event.y - 5, event.x + 5, event.y + 5): self.EDIT = True self.editPointId = int(self.canvas.find_enclosed(event.x - 5, event.y - 5, event.x + 5, event.y + 5)[0]) else: self.EDIT = False # Set the initial point if self.EDIT: idx = self.bboxPointList.index(self.editPointId) self.editbboxId = self.bboxIdList[math.floor(idx/4.0)] self.bboxId = self.editbboxId pidx = self.bboxIdList.index(self.editbboxId) pidx = pidx * 4 self.o1 = self.bboxPointList[pidx] self.o2 = self.bboxPointList[pidx + 1] self.o3 = self.bboxPointList[pidx + 2] self.o4 = self.bboxPointList[pidx + 3] if self.editPointId == self.o1: a, b, c, d = self.canvas.coords(self.o3) elif self.editPointId == self.o2: a, b, c, d = self.canvas.coords(self.o4) elif self.editPointId == self.o3: a, b, c, d = self.canvas.coords(self.o1) elif self.editPointId == self.o4: a, b, c, d = self.canvas.coords(self.o2) self.STATE['x'], self.STATE['y'] = int((a+c)/2), int((b+d)/2) else: self.STATE['x'], self.STATE['y'] = event.x, event.y def mouse_drag(self, event): self.mouse_move(event) if self.bboxId: self.currBboxColor = self.canvas.itemcget(self.bboxId, "outline") self.canvas.delete(self.bboxId) self.canvas.delete(self.o1) self.canvas.delete(self.o2) self.canvas.delete(self.o3) self.canvas.delete(self.o4) if self.EDIT: self.bboxId = self.canvas.create_rectangle(self.STATE['x'], self.STATE['y'], event.x, event.y, width=2, outline=self.currBboxColor) else: self.currBboxColor = config.COLORS[len(self.bboxList) % len(config.COLORS)] self.bboxId = self.canvas.create_rectangle(self.STATE['x'], self.STATE['y'], event.x, event.y, width=2, outline=self.currBboxColor) def mouse_move(self, event): self.disp.config(text='x: %d, y: %d' % (event.x, event.y)) self.zoom_view(event) if self.tkimg: # Horizontal and Vertical Line for precision if self.hl: self.canvas.delete(self.hl) self.hl = self.canvas.create_line(0, event.y, self.tkimg.width(), event.y, width=2) if self.vl: self.canvas.delete(self.vl) self.vl = self.canvas.create_line(event.x, 0, event.x, self.tkimg.height(), width=2) # elif (event.x, event.y) in self.bboxBRPointList: # pass def mouse_release(self, event): try: labelidx = self.labelListBox.curselection() self.currLabel = self.labelListBox.get(labelidx) except: pass if self.EDIT: self.update_bbox() self.EDIT = False x1, x2 = min(self.STATE['x'], event.x), max(self.STATE['x'], event.x) y1, y2 = min(self.STATE['y'], event.y), max(self.STATE['y'], event.y) self.bboxList.append((x1, y1, x2, y2)) o1 = self.canvas.create_oval(x1 - 3, y1 - 3, x1 + 3, y1 + 3, fill="red") o2 = self.canvas.create_oval(x2 - 3, y1 - 3, x2 + 3, y1 + 3, fill="red") o3 = self.canvas.create_oval(x2 - 3, y2 - 3, x2 + 3, y2 + 3, fill="red") o4 = self.canvas.create_oval(x1 - 3, y2 - 3, x1 + 3, y2 + 3, fill="red") self.bboxPointList.append(o1) self.bboxPointList.append(o2) self.bboxPointList.append(o3) self.bboxPointList.append(o4) self.bboxIdList.append(self.bboxId) self.bboxId = None self.objectLabelList.append(str(self.currLabel)) self.objectListBox.insert(END, '(%d, %d) -> (%d, %d)' % (x1, y1, x2, y2) + ': ' + str(self.currLabel)) self.objectListBox.itemconfig(len(self.bboxIdList) - 1, fg=self.currBboxColor) self.currLabel = None def zoom_view(self, event): try: if self.zoomImgId: self.zoomcanvas.delete(self.zoomImgId) self.zoomImg = self.img.copy() self.zoomImgCrop = self.zoomImg.crop(((event.x - 25), (event.y - 25), (event.x + 25), (event.y + 25))) self.zoomImgCrop = self.zoomImgCrop.resize((150, 150)) self.tkZoomImg = ImageTk.PhotoImage(self.zoomImgCrop) self.zoomImgId = self.zoomcanvas.create_image(0, 0, image=self.tkZoomImg, anchor=NW) hl = self.zoomcanvas.create_line(0, 75, 150, 75, width=2) vl = self.zoomcanvas.create_line(75, 0, 75, 150, width=2) except: pass def update_bbox(self): idx = self.bboxIdList.index(self.editbboxId) self.bboxIdList.pop(idx) self.bboxList.pop(idx) self.objectListBox.delete(idx) self.currLabel = self.objectLabelList[idx] self.objectLabelList.pop(idx) idx = idx*4 self.canvas.delete(self.bboxPointList[idx]) self.canvas.delete(self.bboxPointList[idx+1]) self.canvas.delete(self.bboxPointList[idx+2]) self.canvas.delete(self.bboxPointList[idx+3]) self.bboxPointList.pop(idx) self.bboxPointList.pop(idx) self.bboxPointList.pop(idx) self.bboxPointList.pop(idx) def cancel_bbox(self, event): if self.STATE['click'] == 1: if self.bboxId: self.canvas.delete(self.bboxId) self.bboxId = None self.STATE['click'] = 0 def del_bbox(self): sel = self.objectListBox.curselection() if len(sel) != 1: return idx = int(sel[0]) self.canvas.delete(self.bboxIdList[idx]) self.canvas.delete(self.bboxPointList[idx * 4]) self.canvas.delete(self.bboxPointList[(idx * 4) + 1]) self.canvas.delete(self.bboxPointList[(idx * 4) + 2]) self.canvas.delete(self.bboxPointList[(idx * 4) + 3]) self.bboxPointList.pop(idx * 4) self.bboxPointList.pop(idx * 4) self.bboxPointList.pop(idx * 4) self.bboxPointList.pop(idx * 4) self.bboxIdList.pop(idx) self.bboxList.pop(idx) self.objectLabelList.pop(idx) self.objectListBox.delete(idx) def clear_bbox(self): for idx in range(len(self.bboxIdList)): self.canvas.delete(self.bboxIdList[idx]) for idx in range(len(self.bboxPointList)): self.canvas.delete(self.bboxPointList[idx]) self.objectListBox.delete(0, len(self.bboxList)) self.bboxIdList = [] self.bboxList = [] self.objectLabelList = [] self.bboxPointList = [] def add_label(self): if self.textBox.get() is not '': curr_label_list = self.labelListBox.get(0, END) curr_label_list = list(curr_label_list) if self.textBox.get() not in curr_label_list: self.labelListBox.insert(END, str(self.textBox.get())) self.textBox.delete(0, 'end') def del_label(self): labelidx = self.labelListBox.curselection() self.labelListBox.delete(labelidx) def add_labels_coco(self): for listidxcoco, list_label_coco in enumerate(self.cocoLabels): if self.cocoIntVars[listidxcoco].get(): curr_label_list = self.labelListBox.get(0, END) curr_label_list = list(curr_label_list) if list_label_coco not in curr_label_list: self.labelListBox.insert(END, str(list_label_coco)) def automate(self): self.processingLabel.config(text="Processing ") self.processingLabel.update_idletasks() open_cv_image = np.array(self.img) # Convert RGB to BGR opencvImage= open_cv_image[:, :, ::-1].copy() # opencvImage = cv2.cvtColor(np.array(self.img), cv2.COLOR_RGB2BGR) image = preprocess_image(opencvImage) boxes, scores, labels = model.predict_on_batch(np.expand_dims(image, axis=0)) for idx, (box, label, score) in enumerate(zip(boxes[0], labels[0], scores[0])): curr_label_list = self.labelListBox.get(0, END) curr_label_list = list(curr_label_list) if score < 0.5: continue if config.labels_to_names[label] not in curr_label_list: continue b = box.astype(int) self.bboxId = self.canvas.create_rectangle(b[0], b[1], b[2], b[3], width=2, outline=config.COLORS[len(self.bboxList) % len(config.COLORS)]) self.bboxList.append((b[0], b[1], b[2], b[3])) o1 = self.canvas.create_oval(b[0] - 3, b[1] - 3, b[0] + 3, b[1] + 3, fill="red") o2 = self.canvas.create_oval(b[2] - 3, b[1] - 3, b[2] + 3, b[1] + 3, fill="red") o3 = self.canvas.create_oval(b[2] - 3, b[3] - 3, b[2] + 3, b[3] + 3, fill="red") o4 = self.canvas.create_oval(b[0] - 3, b[3] - 3, b[0] + 3, b[3] + 3, fill="red") self.bboxPointList.append(o1) self.bboxPointList.append(o2) self.bboxPointList.append(o3) self.bboxPointList.append(o4) self.bboxIdList.append(self.bboxId) self.bboxId = None self.objectLabelList.append(str(config.labels_to_names[label])) self.objectListBox.insert(END, '(%d, %d) -> (%d, %d)' % (b[0], b[1], b[2], b[3]) + ': ' + str(config.labels_to_names[label])) self.objectListBox.itemconfig(len(self.bboxIdList) - 1, fg=config.COLORS[(len(self.bboxIdList) - 1) % len(config.COLORS)]) self.processingLabel.config(text="Done ") if __name__ == '__main__': root = Tk() imgicon = PhotoImage(file='icon.gif') root.tk.call('wm', 'iconphoto', root._w, imgicon) tool = MainGUI(root) root.mainloop()
43.629787
120
0.578611
from tkinter import * from tkinter import filedialog from PIL import Image, ImageTk import keras from keras_retinanet import models from keras_retinanet.utils.image import preprocess_image import os import numpy as np import tensorflow as tf import config import math def get_session(): config = tf.compat.v1.ConfigProto() config.gpu_options.allow_growth = True return tf.compat.v1.Session(config=config) tf.compat.v1.keras.backend.set_session(get_session()) model_path = os.path.join('.', 'snapshots', 'resnet50_coco_best_v2.1.0.h5') model = models.load_model(model_path, backbone_name='resnet50') class MainGUI: def __init__(self, master): self.parent = master self.parent.title("Semi Automatic Image Annotation Tool") self.frame = Frame(self.parent) self.frame.pack(fill=BOTH, expand=1) self.parent.resizable(width=False, height=False) self.img = None self.tkimg = None self.imageDir = '' self.imageDirPathBuffer = '' self.imageList = [] self.imageTotal = 0 self.imageCur = 0 self.cur = 0 self.bboxIdList = [] self.bboxList = [] self.bboxPointList = [] self.o1 = None self.o2 = None self.o3 = None self.o4 = None self.bboxId = None self.currLabel = None self.editbboxId = None self.currBboxColor = None self.zoomImgId = None self.zoomImg = None self.zoomImgCrop = None self.tkZoomImg = None self.hl = None self.vl = None self.editPointId = None self.filename = None self.filenameBuffer = None self.objectLabelList = [] self.EDIT = False self.STATE = {'x': 0, 'y': 0} self.STATE_COCO = {'click': 0} self.anno_filename = 'annotations.csv' self.annotation_file = open('annotations/' + self.anno_filename, 'w+') self.annotation_file.write("") self.annotation_file.close() self.ctrlPanel = Frame(self.frame) self.ctrlPanel.grid(row=0, column=0, sticky=W + N) self.openBtn = Button(self.ctrlPanel, text='Open', command=self.open_image) self.openBtn.pack(fill=X, side=TOP) self.openDirBtn = Button(self.ctrlPanel, text='Open Dir', command=self.open_image_dir) self.openDirBtn.pack(fill=X, side=TOP) self.nextBtn = Button(self.ctrlPanel, text='Next -->', command=self.open_next) self.nextBtn.pack(fill=X, side=TOP) self.previousBtn = Button(self.ctrlPanel, text='<-- Previous', command=self.open_previous) self.previousBtn.pack(fill=X, side=TOP) self.saveBtn = Button(self.ctrlPanel, text='Save', command=self.save) self.saveBtn.pack(fill=X, side=TOP) self.semiAutoBtn = Button(self.ctrlPanel, text="Show Suggestions", command=self.automate) self.semiAutoBtn.pack(fill=X, side=TOP) self.disp = Label(self.ctrlPanel, text='Coordinates:') self.disp.pack(fill=X, side=TOP) self.mb = Menubutton(self.ctrlPanel, text="COCO Classes for Suggestions", relief=RAISED) self.mb.pack(fill=X, side=TOP) self.mb.menu = Menu(self.mb, tearoff=0) self.mb["menu"] = self.mb.menu self.addCocoBtn = Button(self.ctrlPanel, text="+", command=self.add_labels_coco) self.addCocoBtn.pack(fill=X, side=TOP) self.zoomPanelLabel = Label(self.ctrlPanel, text="Precision View Panel") self.zoomPanelLabel.pack(fill=X, side=TOP) self.zoomcanvas = Canvas(self.ctrlPanel, width=150, height=150) self.zoomcanvas.pack(fill=X, side=TOP, anchor='center') self.canvas = Canvas(self.frame, width=500, height=500) self.canvas.grid(row=0, column=1, sticky=W + N) self.canvas.bind("<Button-1>", self.mouse_click) self.canvas.bind("<Motion>", self.mouse_move, "+") self.canvas.bind("<B1-Motion>", self.mouse_drag) self.canvas.bind("<ButtonRelease-1>", self.mouse_release) self.parent.bind("<Key-Left>", self.open_previous) self.parent.bind("<Key-Right>", self.open_next) self.parent.bind("Escape", self.cancel_bbox) self.listPanel = Frame(self.frame) self.listPanel.grid(row=0, column=2, sticky=W + N) self.listBoxNameLabel = Label(self.listPanel, text="List of Objects").pack(fill=X, side=TOP) self.objectListBox = Listbox(self.listPanel, width=40) self.objectListBox.pack(fill=X, side=TOP) self.delObjectBtn = Button(self.listPanel, text="Delete", command=self.del_bbox) self.delObjectBtn.pack(fill=X, side=TOP) self.clearAllBtn = Button(self.listPanel, text="Clear All", command=self.clear_bbox) self.clearAllBtn.pack(fill=X, side=TOP) self.classesNameLabel = Label(self.listPanel, text="Classes").pack(fill=X, side=TOP) self.textBox = Entry(self.listPanel, text="Enter label") self.textBox.pack(fill=X, side=TOP) self.addLabelBtn = Button(self.listPanel, text="+", command=self.add_label).pack(fill=X, side=TOP) self.delLabelBtn = Button(self.listPanel, text="-", command=self.del_label).pack(fill=X, side=TOP) self.labelListBox = Listbox(self.listPanel) self.labelListBox.pack(fill=X, side=TOP) self.cocoLabels = config.labels_to_names.values() self.cocoIntVars = [] for idxcoco, label_coco in enumerate(self.cocoLabels): self.cocoIntVars.append(IntVar()) self.mb.menu.add_checkbutton(label=label_coco, variable=self.cocoIntVars[idxcoco]) self.statusBar = Frame(self.frame, width=500) self.statusBar.grid(row=1, column=1, sticky=W + N) self.processingLabel = Label(self.statusBar, text=" ") self.processingLabel.pack(side="left", fill=X) self.imageIdxLabel = Label(self.statusBar, text=" ") self.imageIdxLabel.pack(side="right", fill=X) def open_image(self): self.filename = filedialog.askopenfilename(title="Select Image", filetypes=(("jpeg files", "*.jpg"), ("all files", "*.*"))) if not self.filename: return None self.filenameBuffer = self.filename self.load_image(self.filenameBuffer) def open_image_dir(self): self.imageDir = filedialog.askdirectory(title="Select Dataset Directory") if not self.imageDir: return None self.imageList = os.listdir(self.imageDir) self.imageList = sorted(self.imageList) self.imageTotal = len(self.imageList) self.filename = None self.imageDirPathBuffer = self.imageDir self.load_image(self.imageDirPathBuffer + '/' + self.imageList[self.cur]) def load_image(self, file): self.img = Image.open(file) self.imageCur = self.cur + 1 self.imageIdxLabel.config(text=' || Image Number: %d / %d' % (self.imageCur, self.imageTotal)) w, h = self.img.size if w >= h: baseW = 500 wpercent = (baseW / float(w)) hsize = int((float(h) * float(wpercent))) self.img = self.img.resize((baseW, hsize), Image.BICUBIC) else: baseH = 500 wpercent = (baseH / float(h)) wsize = int((float(w) * float(wpercent))) self.img = self.img.resize((wsize, baseH), Image.BICUBIC) self.tkimg = ImageTk.PhotoImage(self.img) self.canvas.create_image(0, 0, image=self.tkimg, anchor=NW) self.clear_bbox() def open_next(self, event=None): self.save() if self.cur < len(self.imageList): self.cur += 1 self.load_image(self.imageDirPathBuffer + '/' + self.imageList[self.cur]) self.processingLabel.config(text=" ") self.processingLabel.update_idletasks() def open_previous(self, event=None): self.save() if self.cur > 0: self.cur -= 1 self.load_image(self.imageDirPathBuffer + '/' + self.imageList[self.cur]) self.processingLabel.config(text=" ") self.processingLabel.update_idletasks() def save(self): if self.filenameBuffer is None: self.annotation_file = open('annotations/' + self.anno_filename, 'a') for idx, item in enumerate(self.bboxList): self.annotation_file.write(self.imageDirPathBuffer + '/' + self.imageList[self.cur] + ',' + ','.join(map(str, self.bboxList[idx])) + ',' + str(self.objectLabelList[idx]) + '\n') self.annotation_file.close() else: self.annotation_file = open('annotations/' + self.anno_filename, 'a') for idx, item in enumerate(self.bboxList): self.annotation_file.write(self.filenameBuffer + ',' + ','.join(map(str, self.bboxList[idx])) + ',' + str(self.objectLabelList[idx]) + '\n') self.annotation_file.close() def mouse_click(self, event): if self.canvas.find_enclosed(event.x - 5, event.y - 5, event.x + 5, event.y + 5): self.EDIT = True self.editPointId = int(self.canvas.find_enclosed(event.x - 5, event.y - 5, event.x + 5, event.y + 5)[0]) else: self.EDIT = False if self.EDIT: idx = self.bboxPointList.index(self.editPointId) self.editbboxId = self.bboxIdList[math.floor(idx/4.0)] self.bboxId = self.editbboxId pidx = self.bboxIdList.index(self.editbboxId) pidx = pidx * 4 self.o1 = self.bboxPointList[pidx] self.o2 = self.bboxPointList[pidx + 1] self.o3 = self.bboxPointList[pidx + 2] self.o4 = self.bboxPointList[pidx + 3] if self.editPointId == self.o1: a, b, c, d = self.canvas.coords(self.o3) elif self.editPointId == self.o2: a, b, c, d = self.canvas.coords(self.o4) elif self.editPointId == self.o3: a, b, c, d = self.canvas.coords(self.o1) elif self.editPointId == self.o4: a, b, c, d = self.canvas.coords(self.o2) self.STATE['x'], self.STATE['y'] = int((a+c)/2), int((b+d)/2) else: self.STATE['x'], self.STATE['y'] = event.x, event.y def mouse_drag(self, event): self.mouse_move(event) if self.bboxId: self.currBboxColor = self.canvas.itemcget(self.bboxId, "outline") self.canvas.delete(self.bboxId) self.canvas.delete(self.o1) self.canvas.delete(self.o2) self.canvas.delete(self.o3) self.canvas.delete(self.o4) if self.EDIT: self.bboxId = self.canvas.create_rectangle(self.STATE['x'], self.STATE['y'], event.x, event.y, width=2, outline=self.currBboxColor) else: self.currBboxColor = config.COLORS[len(self.bboxList) % len(config.COLORS)] self.bboxId = self.canvas.create_rectangle(self.STATE['x'], self.STATE['y'], event.x, event.y, width=2, outline=self.currBboxColor) def mouse_move(self, event): self.disp.config(text='x: %d, y: %d' % (event.x, event.y)) self.zoom_view(event) if self.tkimg: if self.hl: self.canvas.delete(self.hl) self.hl = self.canvas.create_line(0, event.y, self.tkimg.width(), event.y, width=2) if self.vl: self.canvas.delete(self.vl) self.vl = self.canvas.create_line(event.x, 0, event.x, self.tkimg.height(), width=2) def mouse_release(self, event): try: labelidx = self.labelListBox.curselection() self.currLabel = self.labelListBox.get(labelidx) except: pass if self.EDIT: self.update_bbox() self.EDIT = False x1, x2 = min(self.STATE['x'], event.x), max(self.STATE['x'], event.x) y1, y2 = min(self.STATE['y'], event.y), max(self.STATE['y'], event.y) self.bboxList.append((x1, y1, x2, y2)) o1 = self.canvas.create_oval(x1 - 3, y1 - 3, x1 + 3, y1 + 3, fill="red") o2 = self.canvas.create_oval(x2 - 3, y1 - 3, x2 + 3, y1 + 3, fill="red") o3 = self.canvas.create_oval(x2 - 3, y2 - 3, x2 + 3, y2 + 3, fill="red") o4 = self.canvas.create_oval(x1 - 3, y2 - 3, x1 + 3, y2 + 3, fill="red") self.bboxPointList.append(o1) self.bboxPointList.append(o2) self.bboxPointList.append(o3) self.bboxPointList.append(o4) self.bboxIdList.append(self.bboxId) self.bboxId = None self.objectLabelList.append(str(self.currLabel)) self.objectListBox.insert(END, '(%d, %d) -> (%d, %d)' % (x1, y1, x2, y2) + ': ' + str(self.currLabel)) self.objectListBox.itemconfig(len(self.bboxIdList) - 1, fg=self.currBboxColor) self.currLabel = None def zoom_view(self, event): try: if self.zoomImgId: self.zoomcanvas.delete(self.zoomImgId) self.zoomImg = self.img.copy() self.zoomImgCrop = self.zoomImg.crop(((event.x - 25), (event.y - 25), (event.x + 25), (event.y + 25))) self.zoomImgCrop = self.zoomImgCrop.resize((150, 150)) self.tkZoomImg = ImageTk.PhotoImage(self.zoomImgCrop) self.zoomImgId = self.zoomcanvas.create_image(0, 0, image=self.tkZoomImg, anchor=NW) hl = self.zoomcanvas.create_line(0, 75, 150, 75, width=2) vl = self.zoomcanvas.create_line(75, 0, 75, 150, width=2) except: pass def update_bbox(self): idx = self.bboxIdList.index(self.editbboxId) self.bboxIdList.pop(idx) self.bboxList.pop(idx) self.objectListBox.delete(idx) self.currLabel = self.objectLabelList[idx] self.objectLabelList.pop(idx) idx = idx*4 self.canvas.delete(self.bboxPointList[idx]) self.canvas.delete(self.bboxPointList[idx+1]) self.canvas.delete(self.bboxPointList[idx+2]) self.canvas.delete(self.bboxPointList[idx+3]) self.bboxPointList.pop(idx) self.bboxPointList.pop(idx) self.bboxPointList.pop(idx) self.bboxPointList.pop(idx) def cancel_bbox(self, event): if self.STATE['click'] == 1: if self.bboxId: self.canvas.delete(self.bboxId) self.bboxId = None self.STATE['click'] = 0 def del_bbox(self): sel = self.objectListBox.curselection() if len(sel) != 1: return idx = int(sel[0]) self.canvas.delete(self.bboxIdList[idx]) self.canvas.delete(self.bboxPointList[idx * 4]) self.canvas.delete(self.bboxPointList[(idx * 4) + 1]) self.canvas.delete(self.bboxPointList[(idx * 4) + 2]) self.canvas.delete(self.bboxPointList[(idx * 4) + 3]) self.bboxPointList.pop(idx * 4) self.bboxPointList.pop(idx * 4) self.bboxPointList.pop(idx * 4) self.bboxPointList.pop(idx * 4) self.bboxIdList.pop(idx) self.bboxList.pop(idx) self.objectLabelList.pop(idx) self.objectListBox.delete(idx) def clear_bbox(self): for idx in range(len(self.bboxIdList)): self.canvas.delete(self.bboxIdList[idx]) for idx in range(len(self.bboxPointList)): self.canvas.delete(self.bboxPointList[idx]) self.objectListBox.delete(0, len(self.bboxList)) self.bboxIdList = [] self.bboxList = [] self.objectLabelList = [] self.bboxPointList = [] def add_label(self): if self.textBox.get() is not '': curr_label_list = self.labelListBox.get(0, END) curr_label_list = list(curr_label_list) if self.textBox.get() not in curr_label_list: self.labelListBox.insert(END, str(self.textBox.get())) self.textBox.delete(0, 'end') def del_label(self): labelidx = self.labelListBox.curselection() self.labelListBox.delete(labelidx) def add_labels_coco(self): for listidxcoco, list_label_coco in enumerate(self.cocoLabels): if self.cocoIntVars[listidxcoco].get(): curr_label_list = self.labelListBox.get(0, END) curr_label_list = list(curr_label_list) if list_label_coco not in curr_label_list: self.labelListBox.insert(END, str(list_label_coco)) def automate(self): self.processingLabel.config(text="Processing ") self.processingLabel.update_idletasks() open_cv_image = np.array(self.img) opencvImage= open_cv_image[:, :, ::-1].copy() image = preprocess_image(opencvImage) boxes, scores, labels = model.predict_on_batch(np.expand_dims(image, axis=0)) for idx, (box, label, score) in enumerate(zip(boxes[0], labels[0], scores[0])): curr_label_list = self.labelListBox.get(0, END) curr_label_list = list(curr_label_list) if score < 0.5: continue if config.labels_to_names[label] not in curr_label_list: continue b = box.astype(int) self.bboxId = self.canvas.create_rectangle(b[0], b[1], b[2], b[3], width=2, outline=config.COLORS[len(self.bboxList) % len(config.COLORS)]) self.bboxList.append((b[0], b[1], b[2], b[3])) o1 = self.canvas.create_oval(b[0] - 3, b[1] - 3, b[0] + 3, b[1] + 3, fill="red") o2 = self.canvas.create_oval(b[2] - 3, b[1] - 3, b[2] + 3, b[1] + 3, fill="red") o3 = self.canvas.create_oval(b[2] - 3, b[3] - 3, b[2] + 3, b[3] + 3, fill="red") o4 = self.canvas.create_oval(b[0] - 3, b[3] - 3, b[0] + 3, b[3] + 3, fill="red") self.bboxPointList.append(o1) self.bboxPointList.append(o2) self.bboxPointList.append(o3) self.bboxPointList.append(o4) self.bboxIdList.append(self.bboxId) self.bboxId = None self.objectLabelList.append(str(config.labels_to_names[label])) self.objectListBox.insert(END, '(%d, %d) -> (%d, %d)' % (b[0], b[1], b[2], b[3]) + ': ' + str(config.labels_to_names[label])) self.objectListBox.itemconfig(len(self.bboxIdList) - 1, fg=config.COLORS[(len(self.bboxIdList) - 1) % len(config.COLORS)]) self.processingLabel.config(text="Done ") if __name__ == '__main__': root = Tk() imgicon = PhotoImage(file='icon.gif') root.tk.call('wm', 'iconphoto', root._w, imgicon) tool = MainGUI(root) root.mainloop()
true
true
1c3961b70cb71bf46342e39b85de8960e6ba64c2
1,016
py
Python
pajbot/web/routes/admin/moderators.py
MrBean355/pajbot
3f27aabccfb242f5e3e8eedd20c97633b0d39950
[ "MIT" ]
null
null
null
pajbot/web/routes/admin/moderators.py
MrBean355/pajbot
3f27aabccfb242f5e3e8eedd20c97633b0d39950
[ "MIT" ]
null
null
null
pajbot/web/routes/admin/moderators.py
MrBean355/pajbot
3f27aabccfb242f5e3e8eedd20c97633b0d39950
[ "MIT" ]
null
null
null
import collections from flask import render_template from pajbot.managers.db import DBManager from pajbot.models.user import User from pajbot.web.utils import requires_level def init(page): @page.route("/moderators/") @requires_level(500) def moderators(**options): with DBManager.create_session_scope() as db_session: moderator_users = db_session.query(User).filter(User.level > 100).order_by(User.level.desc()).all() userlists = collections.OrderedDict() userlists["Admins"] = list(filter(lambda user: user.level == 2000, moderator_users)) userlists["Super Moderators"] = list(filter(lambda user: 1000 <= user.level < 1999, moderator_users)) userlists["Moderators"] = list(filter(lambda user: 500 <= user.level < 1000, moderator_users)) userlists["Notables/Helpers"] = list(filter(lambda user: 101 <= user.level < 500, moderator_users)) return render_template("admin/moderators.html", userlists=userlists)
46.181818
113
0.698819
import collections from flask import render_template from pajbot.managers.db import DBManager from pajbot.models.user import User from pajbot.web.utils import requires_level def init(page): @page.route("/moderators/") @requires_level(500) def moderators(**options): with DBManager.create_session_scope() as db_session: moderator_users = db_session.query(User).filter(User.level > 100).order_by(User.level.desc()).all() userlists = collections.OrderedDict() userlists["Admins"] = list(filter(lambda user: user.level == 2000, moderator_users)) userlists["Super Moderators"] = list(filter(lambda user: 1000 <= user.level < 1999, moderator_users)) userlists["Moderators"] = list(filter(lambda user: 500 <= user.level < 1000, moderator_users)) userlists["Notables/Helpers"] = list(filter(lambda user: 101 <= user.level < 500, moderator_users)) return render_template("admin/moderators.html", userlists=userlists)
true
true