content
stringlengths
0
894k
type
stringclasses
2 values
import glob import setuptools with open("README.md", "r") as fh: long_description = fh.read() with open('requirements.txt') as f: requirements = f.read().splitlines() setuptools.setup( name="mldiag", version="0.0.1", author="Aymen SHABOU", author_email="[email protected]", description="A framework to diagnose ML models", long_description=long_description, long_description_content_type="text/markdown", include_package_data=True, url="https://github.com/AI-MEN/MLDiag/blob/master/mldiag", packages=setuptools.find_packages(), classifiers=[ "Programming Language :: Python :: 3", "License :: OSI Approved :: MIT License", "Operating System :: OS Independent", ], python_requires='>=3.7', keywords=["diagnose", "machine learning", "deep learning", "augmenter", "tensorflow", "pytorch", "scikit-learn"], install_requires=requirements, data_files=[('resources', ['resources/ml-diag.css', 'resources/ml-diag.jpg']), ('examples/text_classification', glob.glob('examples/text_classification/*', )) ], entry_points={ 'console_scripts': ['mldiag_test=examples.tf_text_classification_diag:main', 'mldiag=mldiag.cli:diag' ], } ) ''' ''' # twine upload --repository-url https://upload.pypi.org/legacy/ dist/*
python
#!/usr/bin/env python import roslib import rospy import tf from geometry_msgs.msg import TransformStamped from posedetection_msgs.msg import ObjectDetection def handle_pose(msg): br = tf.TransformBroadcaster() if len(msg.objects)==0: return p = msg.objects[0].pose br.sendTransform((p.position.x, p.position.y, p.position.z), (p.orientation.x, p.orientation.y, p.orientation.z, p.orientation.w), msg.header.stamp, "checker_marker_frame", "camera_color_optical_frame") if __name__ == '__main__': rospy.init_node('marker_tf_broadcaster') rospy.Subscriber('/checkerdetector/ObjectDetection', ObjectDetection, handle_pose) rospy.spin()
python
#!/usr/bin/env python3 # # Author: Jeremy Compostella <[email protected]> # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer # in the documentation and/or other materials provided with the # distribution. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS # FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE # COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, # INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES # (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR # SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) # HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, # STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) # ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED # OF THE POSSIBILITY OF SUCH DAMAGE. import os import sys from select import select import Pyro5.api from sensor import Sensor from tools import NameServer, Settings, debug, init, log_exception DEFAULT_SETTINGS = {'max_loop_duration': 5} MODULE_NAME = 'monitor' class Monitor(Sensor): def __init__(self): self._states = {} @Pyro5.api.expose def track(self, name, state): '''Update or start tracking "name" with current value "state"''' if not isinstance(state, bool): raise TypeError('state must be a boolean') self._states[name] = state @Pyro5.api.expose def read(self, **kwargs): return self._states @Pyro5.api.expose def units(self, **kwargs): return {key:'binary' for key, _ in self._states.items()} class MonitorProxy: '''Helper class for monitor service users. This class is a wrapper with exception handler of the monitor service. It provides convenience for modules using the monitor by suppressing the burden of locating the monitor and handling the various remote object related errors. ''' def __init__(self, max_attempt=2): self._monitor = None self.max_attempt = max_attempt def track(self, *args): for attempt in range(self.max_attempt): if not self._monitor: try: self._monitor = NameServer().locate_service(MODULE_NAME) except Pyro5.errors.NamingError: if attempt == self.max_attempt - 1: log_exception('Failed to locate the monitor', *sys.exc_info()) except Pyro5.errors.CommunicationError: if attempt == self.max_attempt - 1: log_exception('Cannot communicate with the nameserver', *sys.exc_info()) if self._monitor: try: self._monitor.track(*args) except Pyro5.errors.PyroError: if attempt == self.max_attempt - 1: log_exception('Communication failed with the monitor', *sys.exc_info()) self._monitor = None def main(): # pylint: disable=too-many-locals base = os.path.splitext(__file__)[0] init(base + '.log') settings = Settings(base + '.ini', DEFAULT_SETTINGS) Pyro5.config.MAX_RETRIES = 3 daemon = Pyro5.api.Daemon() nameserver = NameServer() uri = daemon.register(Monitor()) nameserver.register_sensor(MODULE_NAME, uri) nameserver.register_service(MODULE_NAME, uri) debug("... is now ready to run") while True: try: nameserver.register_sensor(MODULE_NAME, uri) nameserver.register_service(MODULE_NAME, uri) except RuntimeError: log_exception('Failed to register the watchdog service', *sys.exc_info()) sockets, _, _ = select(daemon.sockets, [], [], # pylint: disable=maybe-no-member settings.max_loop_duration) if sockets: daemon.events(sockets) if __name__ == "__main__": main()
python
# Definition for singly-linked list. # class ListNode(object): # def __init__(self, x): # self.val = x # self.next = None class Solution(object): def addTwoNumbers(self, l1, l2): """ :type l1: ListNode :type l2: ListNode :rtype: ListNode """ carry = 0 result = head = ListNode(0) while l1 or l2 or carry: l1, v1 = [l1.next, l1.val] if l1 else [0, 0] l2, v2 = [l2.next, l2.val] if l2 else [0, 0] carry, num = divmod(v1 + v2 + carry, 10) head.next = ListNode(num) head = head.next return result.next
python
""" Merged String Checker http://www.codewars.com/kata/54c9fcad28ec4c6e680011aa/train/python """ def is_merge(s, part1, part2): result = list(s) def findall(part): pointer = 0 for c in part: found = False for i in range(pointer, len(result)): if result[i] == c: pointer = i + 1 found = True break if not found: return False return True def removechar(part): for c in part: if c in result: result.remove(c) else: return False return True return findall(part1) and findall(part2) and removechar(part1 + part2) and len(result) == 0
python
import os import docker.errors import pandas as pd import pytest from ebonite.build.docker import create_docker_client, is_docker_running from ebonite.core.objects.core import Model from sklearn.linear_model import LinearRegression from tests.client.test_func import func def has_docker(): if os.environ.get('SKIP_DOCKER_TESTS', None) == 'true': return False return is_docker_running() def has_local_image(img_name: str) -> bool: if not has_docker(): return False with create_docker_client() as client: try: client.images.get(img_name) except docker.errors.ImageNotFound: return False return True def rm_container(container_name: str, host: str = ''): with create_docker_client(host) as client: containers = client.containers.list() if any(container_name == c.name for c in containers): client.containers.get(container_name).remove(force=True) def rm_image(image_tag: str, host: str = ''): with create_docker_client(host) as client: tags = [t for i in client.images.list() for t in i.tags] if any(image_tag == t for t in tags): client.images.remove(image_tag, force=True) def train_model(): reg = LinearRegression() data = pd.DataFrame([[1, 1], [2, 1]], columns=['a', 'b']) reg.fit(data, [1, 0]) return reg, data @pytest.fixture def model(): model = Model.create(func, "kek", "Test Model") return model
python
from ..value_set import ValueSet class BmiRatio(ValueSet): """ **Clinical Focus:** This value set contains concepts that represent a body mass index (BMI) ratio. **Data Element Scope:** This value set may use the Quality Data Model (QDM) category or attribute related to Procedure. **Inclusion Criteria:** Includes only relevant concepts associated with or related to BMI ratio. **Exclusion Criteria:** No exclusions. """ OID = '2.16.840.1.113883.3.600.1.1490' VALUE_SET_NAME = 'BMI Ratio' EXPANSION_VERSION = 'eCQM Update 2020-05-07' LOINC = { '39156-5' } class CabgPciProcedure(ValueSet): """ **Clinical Focus:** CABG and PCI procedures **Data Element Scope:** CABG and PCI procedures **Inclusion Criteria:** Codes from 2018_Registry_SingleSource_v2.2 **Exclusion Criteria:** None """ OID = '2.16.840.1.113762.1.4.1138.566' VALUE_SET_NAME = 'CABG, PCI Procedure' EXPANSION_VERSION = 'eCQM Update 2020-05-07' CPT = { '33510', '33511', '33512', '33513', '33514', '33516', '33517', '33518', '33519', '33521', '33522', '33523', '33533', '33534', '33535', '33536', '92920', '92924', '92928', '92933', '92937', '92941', '92943' } HCPCSLEVELII = { 'S2205', 'S2206', 'S2207', 'S2208', 'S2209' } class CabgSurgeries(ValueSet): """ **Clinical Focus:** This value set grouping contains concepts that represent coronary artery bypass (CABG) surgical procedures. **Data Element Scope:** This value set may use the Quality Data Model (QDM) category related to Procedure. The intent of this data element is to identify patients who have a CABG surgical procedure. **Inclusion Criteria:** Includes only relevant concepts associated with CABG surgical procedures. This is a grouping of SNOMED CT, ICD-9-CM, and ICD-10-CM codes. **Exclusion Criteria:** Excludes codes that represent a CABG performed using a scope. """ OID = '2.16.840.1.113883.3.666.5.694' VALUE_SET_NAME = 'CABG Surgeries' EXPANSION_VERSION = 'eCQM Update 2020-05-07' ICD10PCS = { '0210083', '0210088', '0210089', '021008C', '021008F', '021008W', '0210093', '0210098', '0210099', '021009C', '021009F', '021009W', '02100A3', '02100A8', '02100A9', '02100AC', '02100AF', '02100AW', '02100J3', '02100J8', '02100J9', '02100JC', '02100JF', '02100JW', '02100K3', '02100K8', '02100K9', '02100KC', '02100KF', '02100KW', '02100Z3', '02100Z8', '02100Z9', '02100ZC', '02100ZF', '0210483', '0210488', '0210489', '021048C', '021048F', '021048W', '0210493', '0210498', '0210499', '021049C', '021049F', '021049W', '02104A3', '02104A8', '02104A9', '02104AC', '02104AF', '02104AW', '02104J3', '02104J8', '02104J9', '02104JC', '02104JF', '02104JW', '02104K3', '02104K8', '02104K9', '02104KC', '02104KF', '02104KW', '02104Z3', '02104Z8', '02104Z9', '02104ZC', '02104ZF', '0211083', '0211088', '0211089', '021108C', '021108F', '021108W', '0211093', '0211098', '0211099', '021109C', '021109F', '021109W', '02110A3', '02110A8', '02110A9', '02110AC', '02110AF', '02110AW', '02110J3', '02110J8', '02110J9', '02110JC', '02110JF', '02110JW', '02110K3', '02110K8', '02110K9', '02110KC', '02110KF', '02110KW', '02110Z3', '02110Z8', '02110Z9', '02110ZC', '02110ZF', '0211483', '0211488', '0211489', '021148C', '021148F', '021148W', '0211493', '0211498', '0211499', '021149C', '021149F', '021149W', '02114A3', '02114A8', '02114A9', '02114AC', '02114AF', '02114AW', '02114J3', '02114J8', '02114J9', '02114JC', '02114JF', '02114JW', '02114K3', '02114K8', '02114K9', '02114KC', '02114KF', '02114KW', '02114Z3', '02114Z8', '02114Z9', '02114ZC', '02114ZF', '0212083', '0212088', '0212089', '021208C', '021208F', '021208W', '0212093', '0212098', '0212099', '021209C', '021209F', '021209W', '02120A3', '02120A8', '02120A9', '02120AC', '02120AF', '02120AW', '02120J3', '02120J8', '02120J9', '02120JC', '02120JF', '02120JW', '02120K3', '02120K8', '02120K9', '02120KC', '02120KF', '02120KW', '02120Z3', '02120Z8', '02120Z9', '02120ZC', '02120ZF', '0212488', '0212489', '021248C', '021248F', '021248W', '0212493', '0212498', '0212499', '021249C', '021249F', '021249W', '02124A3', '02124A8', '02124A9', '02124AC', '02124AF', '02124AW', '02124J3', '02124J8', '02124J9', '02124JC', '02124JF', '02124JW', '02124K3', '02124K8', '02124K9', '02124KC', '02124KF', '02124KW', '02124Z3', '02124Z8', '02124Z9', '02124ZC', '02124ZF', '0213083', '0213088', '0213089', '021308C', '021308F', '021308W', '0213093', '0213098', '0213099', '021309C', '021309F', '021309W', '02130A3', '02130A8', '02130A9', '02130AC', '02130AF', '02130AW', '02130J3', '02130J8', '02130J9', '02130JC', '02130JF', '02130JW', '02130K3', '02130K8', '02130K9', '02130KC', '02130KF', '02130KW', '02130Z3', '02130Z8', '02130Z9', '02130ZC', '02130ZF', '0213483', '0213488', '0213489', '021348C', '021348F', '021348W', '0213493', '0213498', '0213499', '021349C', '021349F', '021349W', '02134A3', '02134A8', '02134A9', '02134AC', '02134AF', '02134AW', '02134J3', '02134J8', '02134J9', '02134JC', '02134JF', '02134JW', '02134K3', '02134K8', '02134K9', '02134KC', '02134KF', '02134KW', '02134Z3', '02134Z8', '02134Z9', '02134ZC', '02134ZF' } ICD9CM = { '3610', '3611', '3612', '3613', '3614', '3615', '3616', '3617', '3619' } SNOMEDCT = { '10190003', '10326007', '119564002', '119565001', '14323007', '17073005', '175021005', '175029007', '175036008', '175037004', '175038009', '175039001', '175040004', '175066001', '232717009', '232719007', '232720001', '232721002', '232722009', '232723004', '232724005', '252427007', '29819009', '309814006', '3546002', '359597003', '359601003', '39202005', '39724006', '405598005', '405599002', '414088005', '418551006', '419132001', '438530000', '440332008', '450506009', '67166004', '736970002', '736971003', '736972005', '736973000', '74371005', '82247006', '8876004', '90487008' } class CardiacSurgery(ValueSet): """ **Clinical Focus:** This value set contains concepts that represent cardiac surgery. **Data Element Scope:** This value set may use Quality Data Model (QDM) category related to Procedure. **Inclusion Criteria:** Includes only relevant concepts associated with cardiac surgery. **Exclusion Criteria:** No exclusions. """ OID = '2.16.840.1.113883.3.526.3.371' VALUE_SET_NAME = 'Cardiac Surgery' EXPANSION_VERSION = 'eCQM Update 2020-05-07' CPT = { '33140', '33510', '33511', '33512', '33513', '33514', '33516', '33533', '33534', '33535', '33536', '92920', '92924', '92928', '92933', '92937', '92941', '92943', '92980', '92981', '92982', '92984', '92995', '92996' } SNOMEDCT = { '10326007', '119564002', '119565001', '15256002', '174911007', '175007008', '175008003', '175009006', '175011002', '175021005', '175022003', '175024002', '175025001', '175026000', '175036008', '175037004', '175038009', '175039001', '175040004', '175041000', '175045009', '175047001', '175048006', '175050003', '232717009', '232719007', '232720001', '232721002', '232722009', '232723004', '232724005', '265481001', '275215001', '275216000', '275227003', '275252001', '275253006', '287277008', '30670000', '309814006', '3546002', '359597003', '359601003', '39202005', '39724006', '414088005', '418551006', '418824004', '419132001', '48431000', '736966005', '736967001', '736968006', '736969003', '736970002', '736971003', '736972005', '736973000', '74371005', '81266008', '82247006', '90205004' } class CarotidIntervention(ValueSet): """ **Clinical Focus:** This value set contains concepts that represent carotid intervention surgical procedures. **Data Element Scope:** This value set may use the Quality Data Model (QDM) category or attribute related to Procedure. **Inclusion Criteria:** Includes only relevant concepts associated with representing carotid intervention surgical procedures. **Exclusion Criteria:** No exclusions. """ OID = '2.16.840.1.113883.3.117.1.7.1.204' VALUE_SET_NAME = 'Carotid Intervention' EXPANSION_VERSION = 'eCQM Update 2020-05-07' ICD10PCS = { '031H09G', '031H09J', '031H09K', '031H09Y', '031H0AG', '031H0AJ', '031H0AK', '031H0AY', '031H0JG', '031H0JJ', '031H0JK', '031H0JY', '031H0KG', '031H0KJ', '031H0KK', '031H0KY', '031H0ZG', '031H0ZJ', '031H0ZK', '031H0ZY', '031J09G', '031J09J', '031J09K', '031J09Y', '031J0AG', '031J0AJ', '031J0AK', '031J0AY', '031J0JG', '031J0JJ', '031J0JK', '031J0JY', '031J0KG', '031J0KJ', '031J0KK', '031J0KY', '031J0ZG', '031J0ZJ', '031J0ZK', '031J0ZY', '031K09J', '031K09K', '031K0AJ', '031K0AK', '031K0JJ', '031K0JK', '031K0KJ', '031K0KK', '031K0ZJ', '031K0ZK', '031L09J', '031L09K', '031L0AJ', '031L0AK', '031L0JJ', '031L0JK', '031L0KJ', '031L0KK', '031L0ZJ', '031L0ZK', '031M09J', '031M09K', '031M0AJ', '031M0AK', '031M0JJ', '031M0JK', '031M0KJ', '031M0KK', '031M0ZJ', '031M0ZK', '031N09J', '031N09K', '031N0AJ', '031N0AK', '031N0JJ', '031N0JK', '031N0KJ', '031N0KK', '031N0ZJ', '031N0ZK', '035H0ZZ', '035H3ZZ', '035H4ZZ', '035J0ZZ', '035J3ZZ', '035J4ZZ', '035K0ZZ', '035K3ZZ', '035K4ZZ', '035L0ZZ', '035L3ZZ', '035L4ZZ', '035M0ZZ', '035M3ZZ', '035M4ZZ', '035N0ZZ', '035N3ZZ', '035N4ZZ', '037H046', '037H04Z', '037H056', '037H05Z', '037H066', '037H06Z', '037H076', '037H07Z', '037H0D6', '037H0DZ', '037H0E6', '037H0EZ', '037H0F6', '037H0FZ', '037H0G6', '037H0GZ', '037H0Z6', '037H0ZZ', '037H346', '037H34Z', '037H356', '037H35Z', '037H366', '037H36Z', '037H376', '037H37Z', '037H3D6', '037H3DZ', '037H3E6', '037H3EZ', '037H3F6', '037H3FZ', '037H3G6', '037H3GZ', '037H3Z6', '037H3ZZ', '037H446', '037H44Z', '037H456', '037H45Z', '037H466', '037H46Z', '037H476', '037H47Z', '037H4D6', '037H4DZ', '037H4E6', '037H4EZ', '037H4F6', '037H4FZ', '037H4G6', '037H4GZ', '037H4Z6', '037H4ZZ', '037J046', '037J04Z', '037J056', '037J05Z', '037J066', '037J06Z', '037J076', '037J07Z', '037J0D6', '037J0DZ', '037J0E6', '037J0EZ', '037J0F6', '037J0FZ', '037J0G6', '037J0GZ', '037J0Z6', '037J0ZZ', '037J346', '037J34Z', '037J356', '037J35Z', '037J366', '037J36Z', '037J376', '037J37Z', '037J3D6', '037J3DZ', '037J3E6', '037J3EZ', '037J3F6', '037J3FZ', '037J3G6', '037J3GZ', '037J3Z6', '037J3ZZ', '037J446', '037J44Z', '037J456', '037J45Z', '037J466', '037J46Z', '037J476', '037J47Z', '037J4D6', '037J4DZ', '037J4E6', '037J4EZ', '037J4F6', '037J4FZ', '037J4G6', '037J4GZ', '037J4Z6', '037J4ZZ', '037K046', '037K04Z', '037K056', '037K05Z', '037K066', '037K06Z', '037K076', '037K07Z', '037K0D6', '037K0DZ', '037K0E6', '037K0EZ', '037K0F6', '037K0FZ', '037K0G6', '037K0GZ', '037K0Z6', '037K0ZZ', '037K346', '037K34Z', '037K356', '037K35Z', '037K366', '037K36Z', '037K376', '037K37Z', '037K3D6', '037K3DZ', '037K3E6', '037K3EZ', '037K3F6', '037K3FZ', '037K3G6', '037K3GZ', '037K3Z6', '037K3ZZ', '037K446', '037K44Z', '037K456', '037K45Z', '037K466', '037K46Z', '037K476', '037K47Z', '037K4D6', '037K4DZ', '037K4E6', '037K4EZ', '037K4F6', '037K4FZ', '037K4G6', '037K4GZ', '037K4Z6', '037K4ZZ', '037L046', '037L04Z', '037L056', '037L05Z', '037L066', '037L06Z', '037L076', '037L07Z', '037L0D6', '037L0DZ', '037L0E6', '037L0EZ', '037L0F6', '037L0FZ', '037L0G6', '037L0GZ', '037L0Z6', '037L0ZZ', '037L346', '037L34Z', '037L356', '037L35Z', '037L366', '037L36Z', '037L376', '037L37Z', '037L3D6', '037L3DZ', '037L3E6', '037L3EZ', '037L3F6', '037L3FZ', '037L3G6', '037L3GZ', '037L3Z6', '037L3ZZ', '037L446', '037L44Z', '037L456', '037L45Z', '037L466', '037L46Z', '037L476', '037L47Z', '037L4D6', '037L4DZ', '037L4E6', '037L4EZ', '037L4F6', '037L4FZ', '037L4G6', '037L4GZ', '037L4Z6', '037L4ZZ', '037M046', '037M04Z', '037M056', '037M05Z', '037M066', '037M06Z', '037M076', '037M07Z', '037M0D6', '037M0DZ', '037M0E6', '037M0EZ', '037M0F6', '037M0FZ', '037M0G6', '037M0GZ', '037M0Z6', '037M0ZZ', '037M346', '037M34Z', '037M356', '037M35Z', '037M366', '037M36Z', '037M376', '037M37Z', '037M3D6', '037M3DZ', '037M3E6', '037M3EZ', '037M3F6', '037M3FZ', '037M3G6', '037M3GZ', '037M3Z6', '037M3ZZ', '037M446', '037M44Z', '037M456', '037M45Z', '037M466', '037M46Z', '037M476', '037M47Z', '037M4D6', '037M4DZ', '037M4E6', '037M4EZ', '037M4F6', '037M4FZ', '037M4G6', '037M4GZ', '037M4Z6', '037M4ZZ', '037N046', '037N04Z', '037N056', '037N05Z', '037N066', '037N06Z', '037N076', '037N07Z', '037N0D6', '037N0DZ', '037N0E6', '037N0EZ', '037N0F6', '037N0FZ', '037N0G6', '037N0GZ', '037N0Z6', '037N0ZZ', '037N346', '037N34Z', '037N356', '037N35Z', '037N366', '037N36Z', '037N376', '037N37Z', '037N3D6', '037N3DZ', '037N3E6', '037N3EZ', '037N3F6', '037N3FZ', '037N3G6', '037N3GZ', '037N3Z6', '037N3ZZ', '037N446', '037N44Z', '037N456', '037N45Z', '037N466', '037N46Z', '037N476', '037N47Z', '037N4D6', '037N4DZ', '037N4E6', '037N4EZ', '037N4F6', '037N4FZ', '037N4G6', '037N4GZ', '037N4Z6', '037N4ZZ', '039H00Z', '039H0ZX', '039H0ZZ', '039H30Z', '039H3ZX', '039H3ZZ', '039H40Z', '039H4ZX', '039H4ZZ', '039J00Z', '039J0ZX', '039J0ZZ', '039J30Z', '039J3ZX', '039J3ZZ', '039J40Z', '039J4ZX', '039J4ZZ', '039K00Z', '039K0ZX', '039K0ZZ', '039K30Z', '039K3ZX', '039K3ZZ', '039K40Z', '039K4ZX', '039K4ZZ', '039L00Z', '039L0ZX', '039L0ZZ', '039L30Z', '039L3ZX', '039L3ZZ', '039L40Z', '039L4ZX', '039L4ZZ', '039M00Z', '039M0ZX', '039M0ZZ', '039M30Z', '039M3ZX', '039M3ZZ', '039M40Z', '039M4ZX', '039M4ZZ', '039N00Z', '039N0ZX', '039N0ZZ', '039N30Z', '039N3ZX', '039N3ZZ', '039N40Z', '039N4ZX', '039N4ZZ', '03BH0ZX', '03BH0ZZ', '03BH3ZX', '03BH3ZZ', '03BH4ZX', '03BH4ZZ', '03BJ0ZX', '03BJ0ZZ', '03BJ3ZX', '03BJ3ZZ', '03BJ4ZX', '03BJ4ZZ', '03BK0ZX', '03BK0ZZ', '03BK3ZX', '03BK3ZZ', '03BK4ZX', '03BK4ZZ', '03BL0ZX', '03BL0ZZ', '03BL3ZX', '03BL3ZZ', '03BL4ZX', '03BL4ZZ', '03BM0ZX', '03BM0ZZ', '03BM3ZX', '03BM3ZZ', '03BM4ZX', '03BM4ZZ', '03BN0ZX', '03BN0ZZ', '03BN3ZX', '03BN3ZZ', '03BN4ZX', '03BN4ZZ', '03CH0Z6', '03CH0ZZ', '03CH3Z6', '03CH3Z7', '03CH3ZZ', '03CH4Z6', '03CH4ZZ', '03CJ0Z6', '03CJ0ZZ', '03CJ3Z6', '03CJ3Z7', '03CJ3ZZ', '03CJ4Z6', '03CJ4ZZ', '03CK0Z6', '03CK0ZZ', '03CK3Z6', '03CK3Z7', '03CK3ZZ', '03CK4Z6', '03CK4ZZ', '03CL0Z6', '03CL0ZZ', '03CL3Z6', '03CL3Z7', '03CL3ZZ', '03CL4Z6', '03CL4ZZ', '03CM0Z6', '03CM0ZZ', '03CM3Z6', '03CM3Z7', '03CM3ZZ', '03CM4Z6', '03CM4ZZ', '03CN0Z6', '03CN0ZZ', '03CN3Z6', '03CN3Z7', '03CN3ZZ', '03CN4Z6', '03CN4ZZ', '03HH03Z', '03HH0DZ', '03HH33Z', '03HH3DZ', '03HH43Z', '03HH4DZ', '03HJ03Z', '03HJ0DZ', '03HJ33Z', '03HJ3DZ', '03HJ43Z', '03HJ4DZ', '03HK03Z', '03HK0DZ', '03HK0MZ', '03HK33Z', '03HK3DZ', '03HK3MZ', '03HK43Z', '03HK4DZ', '03HK4MZ', '03HL03Z', '03HL0DZ', '03HL0MZ', '03HL33Z', '03HL3DZ', '03HL3MZ', '03HL43Z', '03HL4DZ', '03HL4MZ', '03HM03Z', '03HM0DZ', '03HM33Z', '03HM3DZ', '03HM43Z', '03HM4DZ', '03HN03Z', '03HN0DZ', '03HN33Z', '03HN3DZ', '03HN43Z', '03HN4DZ', '03LH0BZ', '03LH0CZ', '03LH0DZ', '03LH0ZZ', '03LH3BZ', '03LH3CZ', '03LH3DZ', '03LH3ZZ', '03LH4BZ', '03LH4CZ', '03LH4DZ', '03LH4ZZ', '03LJ0BZ', '03LJ0CZ', '03LJ0DZ', '03LJ0ZZ', '03LJ3BZ', '03LJ3CZ', '03LJ3DZ', '03LJ3ZZ', '03LJ4BZ', '03LJ4CZ', '03LJ4DZ', '03LJ4ZZ', '03LK0BZ', '03LK0CZ', '03LK0DZ', '03LK0ZZ', '03LK3BZ', '03LK3CZ', '03LK3DZ', '03LK3ZZ', '03LK4BZ', '03LK4CZ', '03LK4DZ', '03LK4ZZ', '03LL0BZ', '03LL0CZ', '03LL0DZ', '03LL0ZZ', '03LL3BZ', '03LL3CZ', '03LL3DZ', '03LL3ZZ', '03LL4BZ', '03LL4CZ', '03LL4DZ', '03LL4ZZ', '03LM0BZ', '03LM0CZ', '03LM0DZ', '03LM0ZZ', '03LM3BZ', '03LM3CZ', '03LM3DZ', '03LM3ZZ', '03LM4BZ', '03LM4CZ', '03LM4DZ', '03LM4ZZ', '03LN0BZ', '03LN0CZ', '03LN0DZ', '03LN0ZZ', '03LN3BZ', '03LN3CZ', '03LN3DZ', '03LN3ZZ', '03LN4BZ', '03LN4CZ', '03LN4DZ', '03LN4ZZ', '03NH0ZZ', '03NH3ZZ', '03NH4ZZ', '03NJ0ZZ', '03NJ3ZZ', '03NJ4ZZ', '03NK0ZZ', '03NK3ZZ', '03NK4ZZ', '03NL0ZZ', '03NL3ZZ', '03NL4ZZ', '03NM0ZZ', '03NM3ZZ', '03NM4ZZ', '03NN0ZZ', '03NN3ZZ', '03NN4ZZ', '03QH0ZZ', '03QH3ZZ', '03QH4ZZ', '03QJ0ZZ', '03QJ3ZZ', '03QJ4ZZ', '03QK0ZZ', '03QK3ZZ', '03QK4ZZ', '03QL0ZZ', '03QL3ZZ', '03QL4ZZ', '03QM0ZZ', '03QM3ZZ', '03QM4ZZ', '03QN0ZZ', '03QN3ZZ', '03QN4ZZ', '03RH07Z', '03RH0JZ', '03RH0KZ', '03RH47Z', '03RH4JZ', '03RH4KZ', '03RJ07Z', '03RJ0JZ', '03RJ0KZ', '03RJ47Z', '03RJ4JZ', '03RJ4KZ', '03RK07Z', '03RK0JZ', '03RK0KZ', '03RK47Z', '03RK4JZ', '03RK4KZ', '03RL07Z', '03RL0JZ', '03RL0KZ', '03RL47Z', '03RL4JZ', '03RL4KZ', '03RM07Z', '03RM0JZ', '03RM0KZ', '03RM47Z', '03RM4JZ', '03RM4KZ', '03RN07Z', '03RN0JZ', '03RN0KZ', '03RN47Z', '03RN4JZ', '03RN4KZ', '03SH0ZZ', '03SH3ZZ', '03SH4ZZ', '03SJ0ZZ', '03SJ3ZZ', '03SJ4ZZ', '03SK0ZZ', '03SK3ZZ', '03SK4ZZ', '03SL0ZZ', '03SL3ZZ', '03SL4ZZ', '03SM0ZZ', '03SM3ZZ', '03SM4ZZ', '03SN0ZZ', '03SN3ZZ', '03SN4ZZ', '03UH07Z', '03UH0JZ', '03UH0KZ', '03UH37Z', '03UH3JZ', '03UH3KZ', '03UH47Z', '03UH4JZ', '03UH4KZ', '03UJ07Z', '03UJ0JZ', '03UJ0KZ', '03UJ37Z', '03UJ3JZ', '03UJ3KZ', '03UJ47Z', '03UJ4JZ', '03UJ4KZ', '03UK07Z', '03UK0JZ', '03UK0KZ', '03UK37Z', '03UK3JZ', '03UK3KZ', '03UK47Z', '03UK4JZ', '03UK4KZ', '03UL07Z', '03UL0JZ', '03UL0KZ', '03UL37Z', '03UL3JZ', '03UL3KZ', '03UL47Z', '03UL4JZ', '03UL4KZ', '03UM07Z', '03UM0JZ', '03UM0KZ', '03UM37Z', '03UM3JZ', '03UM3KZ', '03UM47Z', '03UM4JZ', '03UM4KZ', '03UN07Z', '03UN0JZ', '03UN0KZ', '03UN37Z', '03UN3JZ', '03UN3KZ', '03UN47Z', '03UN4JZ', '03UN4KZ', '03VH0BZ', '03VH0CZ', '03VH0DZ', '03VH0ZZ', '03VH3BZ', '03VH3CZ', '03VH3DZ', '03VH3ZZ', '03VH4BZ', '03VH4CZ', '03VH4DZ', '03VH4ZZ', '03VJ0BZ', '03VJ0CZ', '03VJ0DZ', '03VJ0ZZ', '03VJ3BZ', '03VJ3CZ', '03VJ3DZ', '03VJ3ZZ', '03VJ4BZ', '03VJ4CZ', '03VJ4DZ', '03VJ4ZZ', '03VK0BZ', '03VK0CZ', '03VK0DZ', '03VK0ZZ', '03VK3BZ', '03VK3CZ', '03VK3DZ', '03VK3ZZ', '03VK4BZ', '03VK4CZ', '03VK4DZ', '03VK4ZZ', '03VL0BZ', '03VL0CZ', '03VL0DZ', '03VL0ZZ', '03VL3BZ', '03VL3CZ', '03VL3DZ', '03VL3ZZ', '03VL4BZ', '03VL4CZ', '03VL4DZ', '03VL4ZZ', '03VM0BZ', '03VM0CZ', '03VM0DZ', '03VM0ZZ', '03VM3BZ', '03VM3CZ', '03VM3DZ', '03VM3ZZ', '03VM4BZ', '03VM4CZ', '03VM4DZ', '03VM4ZZ', '03VN0BZ', '03VN0CZ', '03VN0DZ', '03VN0ZZ', '03VN3BZ', '03VN3CZ', '03VN3DZ', '03VN3ZZ', '03VN4BZ', '03VN4CZ', '03VN4DZ', '03VN4ZZ', '0G560ZZ', '0G563ZZ', '0G564ZZ', '0G570ZZ', '0G573ZZ', '0G574ZZ', '0G580ZZ', '0G583ZZ', '0G584ZZ', '0G9600Z', '0G960ZX', '0G960ZZ', '0G9630Z', '0G963ZX', '0G963ZZ', '0G9640Z', '0G964ZX', '0G964ZZ', '0G9700Z', '0G970ZX', '0G970ZZ', '0G9730Z', '0G973ZX', '0G973ZZ', '0G9740Z', '0G974ZX', '0G974ZZ', '0G9800Z', '0G980ZX', '0G980ZZ', '0G9830Z', '0G983ZX', '0G983ZZ', '0G9840Z', '0G984ZX', '0G984ZZ', '0GB60ZX', '0GB60ZZ', '0GB63ZX', '0GB63ZZ', '0GB64ZX', '0GB64ZZ', '0GB70ZX', '0GB70ZZ', '0GB73ZX', '0GB73ZZ', '0GB74ZX', '0GB74ZZ', '0GB80ZX', '0GB80ZZ', '0GB83ZX', '0GB83ZZ', '0GB84ZX', '0GB84ZZ', '0GC60ZZ', '0GC63ZZ', '0GC64ZZ', '0GC70ZZ', '0GC73ZZ', '0GC74ZZ', '0GC80ZZ', '0GC83ZZ', '0GC84ZZ', '0GN60ZZ', '0GN63ZZ', '0GN64ZZ', '0GN70ZZ', '0GN73ZZ', '0GN74ZZ', '0GN80ZZ', '0GN83ZZ', '0GN84ZZ', '0GQ60ZZ', '0GQ63ZZ', '0GQ64ZZ', '0GQ70ZZ', '0GQ73ZZ', '0GQ74ZZ', '0GQ80ZZ', '0GQ83ZZ', '0GQ84ZZ', '0GT60ZZ', '0GT64ZZ', '0GT70ZZ', '0GT74ZZ', '0GT80ZZ', '0GT84ZZ', 'B3060ZZ', 'B3061ZZ', 'B306YZZ', 'B3070ZZ', 'B3071ZZ', 'B307YZZ', 'B3080ZZ', 'B3081ZZ', 'B308YZZ', 'B3160ZZ', 'B3161ZZ', 'B316YZZ', 'B3170ZZ', 'B3171ZZ', 'B317YZZ', 'B3180ZZ', 'B3181ZZ', 'B318YZZ' } ICD9CM = { '0061', '0062', '0063', '0064', '0065', '3802', '3812', '3822', '3830', '3831', '3832', '3842', '3922', '3928', '8841' } SNOMEDCT = { '112823003', '15023006', '175363002', '175364008', '175365009', '175367001', '175373000', '175374006', '175376008', '175379001', '175380003', '175398004', '18674003', '22928005', '233259003', '233260008', '233296007', '233297003', '233298008', '233405004', '241219006', '276949008', '276950008', '276951007', '287606009', '302053004', '303161001', '31573003', '34214004', '39887009', '405326004', '405379009', '405407008', '405408003', '405409006', '405411002', '405412009', '405415006', '417884003', '418405008', '418838006', '419014003', '420026003', '420046008', '420171008', '425611003', '427486009', '428802000', '429287007', '431515004', '431519005', '431535003', '431659001', '432039002', '432785007', '433056003', '433061001', '433591001', '433683001', '433690006', '433711000', '433734009', '434159001', '434378006', '434433007', '43628009', '438615003', '440221006', '440453000', '440518005', '449242004', '46912008', '51382002', '53412000', '59012002', '59109003', '66951008', '74720005', '79507006', '80102005', '80104006', '87314005', '90931006', '9339002' } class CataractSurgery(ValueSet): """ **Clinical Focus:** This value set contains concepts that represent cataract surgical procedures. **Data Element Scope:** This value set may use the Quality Data Model (QDM) category related to Procedure. **Inclusion Criteria:** Includes only relevant concepts associated with cataract surgery. **Exclusion Criteria:** No exclusions. """ OID = '2.16.840.1.113883.3.526.3.1411' VALUE_SET_NAME = 'Cataract Surgery' EXPANSION_VERSION = 'eCQM Update 2020-05-07' CPT = { '66840', '66850', '66852', '66920', '66930', '66940', '66982', '66983', '66984' } SNOMEDCT = { '10178000', '110473004', '112963003', '112964009', '12163000', '231744001', '308694002', '308695001', '313999004', '31705006', '335636001', '336651000', '35717002', '361191005', '385468004', '39243005', '397544007', '404628003', '415089008', '417493007', '418430006', '419767009', '420260004', '420526005', '424945000', '446548003', '46309001', '46426006', '46562009', '50538003', '5130002', '51839008', '54885007', '65812008', '67760003', '69360005', '74490003', '75814005', '79611007', '82155009', '84149000', '85622008', '88282000', '89153001', '9137006' } class ChemotherapyAdministration(ValueSet): """ **Clinical Focus:** This value set contains concepts that represent chemotherapy administration. **Data Element Scope:** This value set may use Quality Data Model (QDM) category related to Procedure. **Inclusion Criteria:** Includes only relevant concepts associated with chemotherapy administration. **Exclusion Criteria:** No exclusions. """ OID = '2.16.840.1.113883.3.526.3.1027' VALUE_SET_NAME = 'Chemotherapy Administration' EXPANSION_VERSION = 'eCQM Update 2020-05-07' CPT = { '51720', '96401', '96405', '96406', '96409', '96413', '96416', '96420', '96422', '96425', '96440', '96446', '96450', '96521', '96522', '96523', '96542', '96549' } SNOMEDCT = { '169396008', '24977001', '265760000', '265761001', '265762008', '266719004', '268500004', '315601005', '31652009', '367336001', '38216008', '394894008', '394895009', '394935005', '4114003', '51534007', '6872008', '716872004', '77738002' } class CognitiveAssessment(ValueSet): """ **Clinical Focus:** This value set contains concepts that represent assessments performed for the evaluation of cognition. **Data Element Scope:** This value set may use the Quality Data Model (QDM) category related to Intervention. **Inclusion Criteria:** Includes only relevant concepts associated with general concepts for assessments used to evaluate cognition. **Exclusion Criteria:** Excludes concepts which explicitly reference specific standardized tools used to evaluate cognition. """ OID = '2.16.840.1.113883.3.526.3.1332' VALUE_SET_NAME = 'Cognitive Assessment' EXPANSION_VERSION = 'eCQM Update 2020-05-07' SNOMEDCT = { '113024001', '4719001' } class CounselingForNutrition(ValueSet): """ **Clinical Focus:** This value set contains concepts that represent nutrition counseling. **Data Element Scope:** This value set may use the Quality Data Model (QDM) category related to Intervention. **Inclusion Criteria:** Includes only relevant concepts associated with identifying counseling for nutrition, including codes for medical nutrition therapy, dietetics services, education about diet or different types of diets (e.g., low fat diet, high fiber diet **Exclusion Criteria:** No exclusions. """ OID = '2.16.840.1.113883.3.464.1003.195.12.1003' VALUE_SET_NAME = 'Counseling for Nutrition' EXPANSION_VERSION = 'eCQM Update 2020-05-07' CPT = { '97802', '97803', '97804' } SNOMEDCT = { '11816003', '183059007', '183060002', '183061003', '183062005', '183063000', '183065007', '183066008', '183067004', '183070000', '183071001', '226067002', '266724001', '275919002', '281085002', '284352003', '305849009', '305850009', '305851008', '306163007', '306164001', '306165000', '306626002', '306627006', '306628001', '313210009', '370847001', '386464006', '404923009', '408910007', '410171007', '410177006', '410200000', '428461000124101', '428691000124107', '429095004', '431482008', '441041000124100', '441201000124108', '441231000124100', '441241000124105', '441251000124107', '441261000124109', '441271000124102', '441281000124104', '441291000124101', '441301000124100', '441311000124102', '441321000124105', '441331000124108', '441341000124103', '441351000124101', '443288003', '445291000124103', '445301000124102', '445331000124105', '445641000124105', '609104008', '61310001', '698471002', '699827002', '699829004', '699830009', '699849008', '700154005', '700258004', '705060005', '710881000' } class CounselingForPhysicalActivity(ValueSet): """ **Clinical Focus:** This value set contains concepts that represent physical activity counseling. **Data Element Scope:** This value set may use the Quality Data Model (QDM) category related to Intervention. **Inclusion Criteria:** Includes only relevant concepts associated with identifying counseling or referrals related to physical activity, including codes related to weight management services. **Exclusion Criteria:** No exclusions. """ OID = '2.16.840.1.113883.3.464.1003.118.12.1035' VALUE_SET_NAME = 'Counseling for Physical Activity' EXPANSION_VERSION = 'eCQM Update 2020-05-07' SNOMEDCT = { '103736005', '183073003', '281090004', '304507003', '304549008', '304558001', '310882002', '386291006', '386292004', '386463000', '390864007', '390893007', '398636004', '398752005', '408289007', '410200000', '410289001', '410335001', '429778002', '435551000124105', '710849009' } class CtColonography(ValueSet): """ **Clinical Focus:** This value set contains concepts that represent identify a computed tomographic (CT) colonography. **Data Element Scope:** This value set may use the Quality Data Model (QDM) category related to Procedure. **Inclusion Criteria:** Includes only relevant concepts associated with patients that have had a CT colonography. This is a grouping of CPT and SNOMED CT codes. **Exclusion Criteria:** No exclusions. """ OID = '2.16.840.1.113883.3.464.1003.108.12.1038' VALUE_SET_NAME = 'CT Colonography' EXPANSION_VERSION = 'eCQM Update 2020-05-07' LOINC = { '60515-4', '72531-7', '79069-1', '79071-7', '79101-2', '82688-3' } class DialysisEducation(ValueSet): """ **Clinical Focus:** This value set contains concepts that represent patients received dialysis education. **Data Element Scope:** This value set may use the Quality Data Model (QDM) datatype related to Intervention, Performed. **Inclusion Criteria:** Includes only relevant concepts associated with patients who had dialysis education. This includes only relevant concepts associated with education at home. **Exclusion Criteria:** No exclusions. """ OID = '2.16.840.1.113883.3.464.1003.109.12.1016' VALUE_SET_NAME = 'Dialysis Education' EXPANSION_VERSION = 'eCQM Update 2020-05-07' SNOMEDCT = { '28812006', '385972005', '59596005', '66402002' } class DialysisServices(ValueSet): """ **Clinical Focus:** This value set contains concepts that represent dialysis services. **Data Element Scope:** This value set may use the Quality Data Model (QDM) category related to Procedure. **Inclusion Criteria:** Includes only relevant concepts associated with patients who had dialysis services. **Exclusion Criteria:** No exclusions. """ OID = '2.16.840.1.113883.3.464.1003.109.12.1013' VALUE_SET_NAME = 'Dialysis Services' EXPANSION_VERSION = 'eCQM Update 2020-05-07' CPT = { '1019320', '90935', '90937', '90940', '90945', '90947', '90957', '90958', '90959' } HCPCSLEVELII = { 'G0257' } SNOMEDCT = { '108241001', '10848006', '11932001', '14684005', '180273006', '225230008', '225231007', '233575001', '233576000', '233577009', '233578004', '233579007', '233580005', '233581009', '233582002', '233583007', '233584001', '233585000', '233586004', '233587008', '233588003', '233589006', '233590002', '238316008', '238317004', '238318009', '238319001', '238321006', '238322004', '238323009', '265764009', '288182009', '302497006', '34897002', '427053002', '428648006', '439278006', '439976001', '57274006', '676002', '67970008', '68341005', '71192002', '714749008' } class DietaryRecommendations(ValueSet): """ **Clinical Focus:** This value set contains concepts that represent dietary management. **Data Element Scope:** This value set may use the Quality Data Model (QDM) category or attribute related to Intervention or Procedure. **Inclusion Criteria:** Includes only relevant concepts associated with dietary management and nutritional education. **Exclusion Criteria:** No exclusions. """ OID = '2.16.840.1.113883.3.600.1515' VALUE_SET_NAME = 'Dietary Recommendations' EXPANSION_VERSION = 'eCQM Update 2020-05-07' HCPCSLEVELII = { 'S9452', 'S9470' } ICD10CM = { 'Z713' } SNOMEDCT = { '103699006', '11816003', '182922004', '182954008', '182955009', '182956005', '182960008', '183061003', '183065007', '183070000', '183071001', '281085002', '284071006', '284352003', '289176001', '289177005', '304491008', '306163007', '361231003', '370847001', '386464006', '410114009', '410171007', '410177006', '410270001', '413315001', '418995006', '424753004', '437211000124103', '437231000124109', '437391000124102', '437421000124105', '438961000124108', '443288003', '61310001' } class FollowUpForAboveNormalBmi(ValueSet): """ **Clinical Focus:** This value set contains concepts that represent interventions relevant for a follow up for a BMI above normal measurement. **Data Element Scope:** This value set may use the Quality Data Model (QDM) category Intervention or Procedure. **Inclusion Criteria:** Includes only relevant concepts associated with interventions relevant for a follow-up when BMI is above normal measurement. **Exclusion Criteria:** No exclusions. """ OID = '2.16.840.1.113883.3.600.1.1525' VALUE_SET_NAME = 'Follow Up for Above Normal BMI' EXPANSION_VERSION = 'eCQM Update 2020-05-07' CPT = { '43644', '43645', '43659', '43770', '43771', '43772', '43773', '43774', '43842', '43843', '43845', '43846', '43847', '43848', '43886', '43888', '97802', '97803', '97804', '98960', '99078', '99401', '99402' } HCPCSLEVELII = { 'G0270', 'G0271', 'G0447', 'G0473', 'S9449', 'S9451', 'S9452', 'S9470' } ICD10CM = { 'Z713', 'Z7182' } SNOMEDCT = { '304549008', '307818003', '361231003', '370847001', '386291006', '386292004', '386373004', '386463000', '386464006', '410177006', '413315001', '418995006', '424753004', '443288003' } class FollowUpForAdolescentDepression(ValueSet): """ **Clinical Focus:** This value set contains concepts that represent follow-up plans used to document a plan is in place for the treatment of depression that specifically pertains to the adolescent population. **Data Element Scope:** This value set may use the Quality Data Model (QDM) category or attribute related to Intervention. **Inclusion Criteria:** Includes only relevant concepts associated with emotional and coping support as well as mental health management in an attempt to follow up on previously evaluated and diagnosed depression or depressive disorder in the adolescent population. **Exclusion Criteria:** No exclusions. """ OID = '2.16.840.1.113883.3.526.3.1569' VALUE_SET_NAME = 'Follow Up for Adolescent Depression' EXPANSION_VERSION = 'eCQM Update 2020-05-07' SNOMEDCT = { '108313002', '1555005', '15558000', '18512000', '229065009', '28868002', '304891004', '372067001', '385721005', '385724002', '385725001', '385726000', '385727009', '385887004', '385889001', '385890005', '386472008', '401277000', '405780009', '410223002', '410224008', '410225009', '410226005', '410227001', '410228006', '410229003', '410230008', '410231007', '410232000', '410233005', '410234004', '425604002', '439141002', '5694008', '75516001', '76168009', '76740001', '81294000', '88848003', '91310009' } class FollowUpForAdultDepression(ValueSet): """ **Clinical Focus:** This value set contains concepts that represent follow-up plans used to document a plan is in place for the treatment of depression specifically pertaining to the adult population. **Data Element Scope:** This value set may use the Quality Data Model (QDM) category or attribute related to Intervention. **Inclusion Criteria:** Includes only relevant concepts associated with emotional and coping support as well as mental health management in an attempt to follow up on previously evaluated and diagnosed depression or depressive disorder in the adult population. **Exclusion Criteria:** No exclusions. """ OID = '2.16.840.1.113883.3.526.3.1568' VALUE_SET_NAME = 'Follow Up for Adult Depression' EXPANSION_VERSION = 'eCQM Update 2020-05-07' SNOMEDCT = { '108313002', '1555005', '15558000', '18512000', '229065009', '28868002', '304891004', '372067001', '385721005', '385724002', '385725001', '385726000', '385727009', '385887004', '385889001', '385890005', '386472008', '401277000', '405780009', '410223002', '410224008', '410225009', '410226005', '410227001', '410228006', '410229003', '410230008', '410231007', '410232000', '410233005', '410234004', '425604002', '439141002', '5694008', '75516001', '76168009', '76740001', '81294000', '88848003', '91310009' } class FollowUpForBelowNormalBmi(ValueSet): """ **Clinical Focus:** This value set contains concepts that represent a follow-up with a BMI below normal measurement. **Data Element Scope:** This value set may use the Quality Data Model (QDM) category or attribute related to Intervention or Procedure. **Inclusion Criteria:** Includes only relevant concepts associated with a follow-up when BMI is below normal measurement. **Exclusion Criteria:** No exclusions. """ OID = '2.16.840.1.113883.3.600.1.1528' VALUE_SET_NAME = 'Follow Up for Below Normal BMI' EXPANSION_VERSION = 'eCQM Update 2020-05-07' CPT = { '97802', '97803', '97804', '98960', '99078', '99401', '99402' } HCPCSLEVELII = { 'G0270', 'G0271', 'S9449', 'S9452', 'S9470' } ICD10CM = { 'Z713' } SNOMEDCT = { '386464006', '410177006', '413315001', '418995006', '424753004', '429095004', '443288003' } class Hemodialysis(ValueSet): """ **Clinical Focus:** This value set contains concepts that represent the administration of hemodialysis. **Data Element Scope:** This value set may use the Quality Data Model (QDM) category related to Procedure. **Inclusion Criteria:** Includes only relevant concepts associated with the administration of hemodialysis. **Exclusion Criteria:** No exclusions. """ OID = '2.16.840.1.113883.3.526.3.1083' VALUE_SET_NAME = 'Hemodialysis' EXPANSION_VERSION = 'eCQM Update 2020-05-07' CPT = { '90951', '90952', '90953', '90954', '90955', '90956', '90957', '90958', '90959', '90960', '90961', '90962', '90963', '90964', '90965', '90966', '90967', '90968', '90969', '90970', '99512' } SNOMEDCT = { '302497006' } class HospiceCareAmbulatory(ValueSet): """ **Clinical Focus:** This value set contains concepts that represent patients receiving hospice care outside of a hospital or long term care facility. **Data Element Scope:** This value set may use the Quality Data Model (QDM) datatype related to Procedure, Order or Intervention, Order. The intent of this value set is to identify all patients receiving hospice care outside of a hospital or long term care facility. **Inclusion Criteria:** Includes only relevant concepts associated with hospice care concepts. **Exclusion Criteria:** Excludes concepts for palliative care or comfort measures. """ OID = '2.16.840.1.113762.1.4.1108.15' VALUE_SET_NAME = 'Hospice care ambulatory' EXPANSION_VERSION = 'eCQM Update 2020-05-07' SNOMEDCT = { '385763009', '385765002' } class HospiceCareAmbulatory_1584(ValueSet): """ **Clinical Focus:** This value set contains concepts that represent patients receiving hospice care outside of a hospital or long term care facility. **Data Element Scope:** This value set may use the Quality Data Model (QDM) datatype related to Procedure, Order or Intervention, Order. The intent of this value set is to identify all patients receiving hospice care outside of a hospital or long term care facility. **Inclusion Criteria:** Includes only relevant concepts associated with hospice care concepts. **Exclusion Criteria:** Excludes concepts for palliative care or comfort measures. """ OID = '2.16.840.1.113883.3.526.3.1584' VALUE_SET_NAME = 'Hospice Care Ambulatory' EXPANSION_VERSION = 'eCQM Update 2020-05-07' SNOMEDCT = { '385763009', '385765002' } class HospitalServicesForUrologyCare(ValueSet): """ **Clinical Focus:** This set of values focuses on hospital care, specifically for urology care. **Data Element Scope:** The intent of this data element is to define hospital CPT services used for urology care. **Inclusion Criteria:** Included CPT codes **Exclusion Criteria:** None """ OID = '2.16.840.1.113762.1.4.1164.64' VALUE_SET_NAME = 'Hospital Services for urology care' EXPANSION_VERSION = 'eCQM Update 2020-05-07' CPT = { '99217', '99218', '99219', '99220', '99221', '99222', '99223', '99231', '99232', '99233', '99234', '99235', '99236', '99238', '99239', '99251', '99281', '99282', '99283', '99284' } class InfluenzaVaccination(ValueSet): """ **Clinical Focus:** This value set contains concepts that represent influenza vaccinations. **Data Element Scope:** This value set may use the Quality Data Model (QDM) category related to Procedure. **Inclusion Criteria:** Includes only relevant concepts associated with influenza vaccinations that are SNOMED CT, CPT, and HCPCS codes. **Exclusion Criteria:** Excludes CVX vaccine codes. """ OID = '2.16.840.1.113883.3.526.3.402' VALUE_SET_NAME = 'Influenza Vaccination' EXPANSION_VERSION = 'eCQM Update 2020-05-07' CPT = { '90630', '90653', '90654', '90655', '90656', '90657', '90658', '90661', '90662', '90666', '90667', '90668', '90673', '90674', '90682', '90685', '90686', '90687', '90688', '90689', '90694', '90756' } HCPCSLEVELII = { 'G0008', 'Q2034', 'Q2035', 'Q2036', 'Q2037', 'Q2038', 'Q2039' } SNOMEDCT = { '86198006' } class KidneyTransplant(ValueSet): """ **Clinical Focus:** This value set contains concepts that represent patients who have undergone kidney transplant. **Data Element Scope:** This value set may use the Quality Data Model (QDM) category related to Procedure. **Inclusion Criteria:** Includes only relevant concepts associated with kidney transplants. **Exclusion Criteria:** No exclusions. """ OID = '2.16.840.1.113883.3.464.1003.109.12.1012' VALUE_SET_NAME = 'Kidney Transplant' EXPANSION_VERSION = 'eCQM Update 2020-05-07' CPT = { '50300', '50320', '50340', '50360', '50365', '50370', '50380' } HCPCSLEVELII = { 'S2065' } ICD10PCS = { '0TY00Z0', '0TY00Z1', '0TY00Z2', '0TY10Z0', '0TY10Z1', '0TY10Z2' } SNOMEDCT = { '122531000119108', '128631000119109', '197747000', '213150003', '236436003', '236569000', '236570004', '236571000', '236572007', '236573002', '236574008', '236575009', '236576005', '236577001', '236578006', '236579003', '236580000', '236581001', '236582008', '236583003', '236584009', '236587002', '236588007', '236589004', '236614007', '277010001', '277011002', '426136000', '428575007', '429451003', '473195006', '58797008', '703048006', '707148007', '713825007' } class LaboratoryTestsForHypertension(ValueSet): """ **Clinical Focus:** This value set contains concepts that represent laboratory tests that are commonly used with patients diagnosed with hypertension. **Data Element Scope:** This value set may use the Quality Data Model (QDM) category related to Procedure. **Inclusion Criteria:** Includes only relevant concepts associated with laboratory testing for patients diagnosed with hypertension. **Exclusion Criteria:** No exclusions. """ OID = '2.16.840.1.113883.3.600.1482' VALUE_SET_NAME = 'Laboratory Tests for Hypertension' EXPANSION_VERSION = 'eCQM Update 2020-05-07' LOINC = { '24320-4', '24321-2', '24323-8', '24356-8', '24357-6', '24362-6', '2888-6', '57021-8', '57782-5', '58410-2' } class LifestyleRecommendation(ValueSet): """ **Clinical Focus:** This value set contains concepts that represent the type of interventions relevant to lifestyle needs. **Data Element Scope:** This value set may use the Quality Data Model (QDM) category related to Procedure or Intervention. **Inclusion Criteria:** Includes only relevant concepts associated with the type of lifestyle education, particularly that related to hyperyension. **Exclusion Criteria:** No exclusions. """ OID = '2.16.840.1.113883.3.526.3.1581' VALUE_SET_NAME = 'Lifestyle Recommendation' EXPANSION_VERSION = 'eCQM Update 2020-05-07' SNOMEDCT = { '313204009', '39155009', '443402002' } class OtherServicesRelatedToDialysis(ValueSet): """ **Clinical Focus:** This value set contains concepts that represent services related to dialysis. **Data Element Scope:** This value set may use the Quality Data Model (QDM) datatype related to Intervention, Performed. **Inclusion Criteria:** Includes only relevant concepts associated with other services related to dialysis. **Exclusion Criteria:** No exclusions. """ OID = '2.16.840.1.113883.3.464.1003.109.12.1015' VALUE_SET_NAME = 'Other Services Related to Dialysis' EXPANSION_VERSION = 'eCQM Update 2020-05-07' SNOMEDCT = { '233591003', '251000124108', '311000124103', '3257008', '385970002', '385971003', '385973000', '406168002', '717738008', '718019005', '718308002', '718330001', '718331002', '73257006' } class PalliativeOrHospiceCare(ValueSet): """ **Clinical Focus:** This value set contains concepts that represent identifying patients receiving palliative, comfort or hospice care. **Data Element Scope:** This value set may use the Quality Data Model (QDM) category related to Intervention or Procedure. **Inclusion Criteria:** Includes only relevant concepts associated with identifying patients receiving palliative, comfort or hospice care. **Exclusion Criteria:** No exclusions. """ OID = '2.16.840.1.113883.3.600.1.1579' VALUE_SET_NAME = 'Palliative or Hospice Care' EXPANSION_VERSION = 'eCQM Update 2020-05-07' SNOMEDCT = { '103735009', '133918004', '182964004', '305284002', '305381007', '305981001', '306237005', '306288008', '385736008', '385763009' } class PeritonealDialysis(ValueSet): """ **Clinical Focus:** This value set contains concepts that represent the administration of peritoneal dialysis. **Data Element Scope:** This value set may use the Quality Data Model (QDM) category related to Procedure. **Inclusion Criteria:** Includes only relevant concepts associated with the administration of peritoneal dialysis. **Exclusion Criteria:** No exclusions. """ OID = '2.16.840.1.113883.3.526.3.1084' VALUE_SET_NAME = 'Peritoneal Dialysis' EXPANSION_VERSION = 'eCQM Update 2020-05-07' CPT = { '90945', '90947', '90951', '90952', '90953', '90954', '90955', '90956', '90957', '90958', '90959', '90960', '90961', '90962', '90963', '90964', '90965', '90966', '90967', '90968', '90969', '90970' } SNOMEDCT = { '14684005', '225230008', '238318009', '238319001', '238321006', '238322004', '238323009', '428648006', '676002', '71192002' } class ProstateCancerTreatment(ValueSet): """ **Clinical Focus:** This value set contains concepts that represent prostate cancer treatments. **Data Element Scope:** This value set may use Quality Data Model (QDM) category related to Procedure. **Inclusion Criteria:** Includes only relevant concepts associated with interstitial prostate brachytherapy, external beam radiotherapy to the prostate and radical prostatectomy. **Exclusion Criteria:** No exclusions. """ OID = '2.16.840.1.113883.3.526.3.398' VALUE_SET_NAME = 'Prostate Cancer Treatment' EXPANSION_VERSION = 'eCQM Update 2020-05-07' CPT = { '55810', '55812', '55815', '55840', '55842', '55845', '55866', '55875', '77427', '77435', '77772', '77778', '77799' } SNOMEDCT = { '10492003', '113120007', '116244007', '118161009', '118162002', '118163007', '14473006', '168922004', '169327006', '169328001', '169329009', '169340001', '169349000', '169359004', '176106009', '176258007', '176260009', '176261008', '176262001', '176263006', '176267007', '176288003', '19149007', '21190008', '21372000', '228677009', '228684001', '228688003', '228690002', '228692005', '228693000', '228694006', '228695007', '228697004', '228698009', '228699001', '228701001', '228702008', '236252003', '24242005', '26294005', '271291003', '27877006', '28579000', '30426000', '312235007', '314202001', '359922007', '359926005', '36253005', '37851009', '384691004', '384692006', '38915000', '394902000', '394918006', '399124002', '399180008', '399315003', '41371003', '41416003', '427541000119103', '427985002', '433224001', '440093006', '440094000', '57525009', '62867004', '65381004', '65551008', '67598001', '68986004', '72388004', '764675000', '77613002', '81232004', '83154001', '84755001', '85768003', '87795007', '8782006', '90199006', '90470006', '91531008' } class RadiationTreatmentManagement(ValueSet): """ **Clinical Focus:** This value set contains concepts that represent radiation treatment management. **Data Element Scope:** This value set may use Quality Data Model (QDM) category related to Procedure. **Inclusion Criteria:** Includes only relevant concepts associated with radiation treatment management. **Exclusion Criteria:** No exclusions. """ OID = '2.16.840.1.113883.3.526.3.1026' VALUE_SET_NAME = 'Radiation Treatment Management' EXPANSION_VERSION = 'eCQM Update 2020-05-07' CPT = { '77427', '77431', '77432', '77435' } SNOMEDCT = { '84755001' } class RecommendationToIncreasePhysicalActivity(ValueSet): """ **Clinical Focus:** This value set contains concepts that represent exercise, education and nutrition. **Data Element Scope:** This value set may use the Quality Data Model (QDM) category related to Intervention or Procedure. **Inclusion Criteria:** Includes only relevant concepts associated with promoting exercise and nutrition regimens. **Exclusion Criteria:** No exclusions. """ OID = '2.16.840.1.113883.3.600.1518' VALUE_SET_NAME = 'Recommendation to Increase Physical Activity' EXPANSION_VERSION = 'eCQM Update 2020-05-07' HCPCSLEVELII = { 'S9451' } SNOMEDCT = { '281090004', '304507003', '304549008', '386291006', '386292004', '386373004', '386463000', '410289001' } class Referral(ValueSet): """ **Clinical Focus:** This value set contains concepts that represent a referral for a patient to a practitioner for evaluation, treatment or co-management of a patient's condition. **Data Element Scope:** This value set may use the Quality Data Model (QDM) category related to Intervention. **Inclusion Criteria:** Includes only relevant concepts associated with referrals and consultations. **Exclusion Criteria:** Excludes self referrals. """ OID = '2.16.840.1.113883.3.464.1003.101.12.1046' VALUE_SET_NAME = 'Referral' EXPANSION_VERSION = 'eCQM Update 2020-05-07' SNOMEDCT = { '103696004', '103697008', '103698003', '103699006', '103704003', '183515008', '183517000', '183528001', '183529009', '183530004', '183541002', '183555005', '183557002', '183561008', '183567007', '183569005', '183583007', '183591003', '183878008', '183879000', '183880002', '183881003', '183882005', '183884006', '183885007', '183886008', '183887004', '183888009', '183889001', '183890005', '183891009', '183892002', '183893007', '183894001', '183895000', '183896004', '183897008', '183899006', '183900001', '183901002', '183902009', '183903004', '183904005', '183905006', '183906007', '183907003', '183908008', '183909000', '183910005', '183911009', '183913007', '183914001', '183915000', '183916004', '266747000', '274410002', '306241009', '306242002', '306243007', '306245000', '306247008', '306250006', '306252003', '306253008', '306254002', '306255001', '306256000', '306257009', '306258004', '306259007', '306260002', '306261003', '306262005', '306263000', '306264006', '306265007', '306266008', '306267004', '306268009', '306269001', '306270000', '306271001', '306272008', '306273003', '306275005', '306276006', '306277002', '306278007', '306279004', '306280001', '306281002', '306282009', '306284005', '306285006', '306286007', '306287003', '306288008', '306289000', '306290009', '306291008', '306293006', '306294000', '306295004', '306296003', '306297007', '306298002', '306299005', '306300002', '306301003', '306302005', '306303000', '306304006', '306305007', '306306008', '306307004', '306308009', '306309001', '306310006', '306311005', '306312003', '306313008', '306314002', '306315001', '306316000', '306317009', '306318004', '306320001', '306338003', '306341007', '306342000', '306343005', '306351008', '306352001', '306353006', '306354000', '306355004', '306356003', '306357007', '306358002', '306359005', '306360000', '306361001', '306736002', '307063001', '307777008', '308439003', '308447003', '308449000', '308450000', '308451001', '308452008', '308453003', '308454009', '308455005', '308456006', '308459004', '308465004', '308469005', '308470006', '308471005', '308472003', '308473008', '308474002', '308475001', '308476000', '308477009', '308478004', '308479007', '308480005', '308481009', '308482002', '308483007', '308484001', '308485000', '309046007', '309623006', '309626003', '309627007', '309629005', '310515004', '312487009', '312488004', '390866009', '401266006', '406158007', '406159004', '408285001', '415277000', '416116000', '416999007', '425971006', '428441000124100', '428451000124103', '428461000124101', '428471000124108', '428481000124106', '428491000124109', '428541000124104', '429365000', '433151006', '448761000124106', '448771000124104', '54395008', '698563003', '698599008', '703974003', '703975002', '703976001', '716634006' } class ReferralForAdolescentDepression(ValueSet): """ **Clinical Focus:** This value set contains concepts that represent appropriate referrals specific to the child and adolescent age group for depression management. **Data Element Scope:** This value set may use the Quality Data Model (QDM) category related to Intervention. **Inclusion Criteria:** Includes only relevant concepts associated with appropriate referrals as specific to the child and adolescent age group for depression management. **Exclusion Criteria:** No exclusions. """ OID = '2.16.840.1.113883.3.526.3.1570' VALUE_SET_NAME = 'Referral for Adolescent Depression' EXPANSION_VERSION = 'eCQM Update 2020-05-07' SNOMEDCT = { '183524004', '183583007', '183851006', '183866009', '306136006', '306137002', '306226009', '306227000', '306252003', '306291008', '306294000', '308459004', '308477009', '309627007', '390866009', '703978000', '710914003', '711281004' } class ReferralForAdultDepression(ValueSet): """ **Clinical Focus:** This value set contains concepts that represent appropriate referrals specific to the adult age group for depression management. **Data Element Scope:** This value set may use the Quality Data Model (QDM) category related to Intervention. **Inclusion Criteria:** Includes only relevant concepts associated with appropriate referrals as specific to the adult age group for depression management. **Exclusion Criteria:** No exclusions. """ OID = '2.16.840.1.113883.3.526.3.1571' VALUE_SET_NAME = 'Referral for Adult Depression' EXPANSION_VERSION = 'eCQM Update 2020-05-07' SNOMEDCT = { '183524004', '183528001', '183583007', '183866009', '305922005', '306136006', '306137002', '306138007', '306204008', '306226009', '306227000', '306252003', '306294000', '308459004', '308477009', '390866009', '703978000', '710914003', '711281004' } class ReferralOrCounselingForAlcoholConsumption(ValueSet): """ **Clinical Focus:** This value set contains concepts that represent the type of interventions relevant to alcohol use. **Data Element Scope:** This value set may use the Quality Data Model (QDM) category related to Procedure or Intervention. **Inclusion Criteria:** Includes only relevant concepts associated with indicating the type of education provided, referral to community service or rehabilitation center for alcohol use. **Exclusion Criteria:** No exclusions. """ OID = '2.16.840.1.113883.3.526.3.1583' VALUE_SET_NAME = 'Referral or Counseling for Alcohol Consumption' EXPANSION_VERSION = 'eCQM Update 2020-05-07' SNOMEDCT = { '24165007', '38670004', '390857005', '408947007', '413473000', '417096006', '431260004' } class ReferralToPrimaryCareOrAlternateProvider(ValueSet): """ **Clinical Focus:** This value set contains concepts that represent referrals to an alternate or primary care provider. **Data Element Scope:** This value set may use the Quality Data Model (QDM) category related to Intervention. **Inclusion Criteria:** Includes only relevant concepts associated with the different types of services and providers. **Exclusion Criteria:** No exclusions. """ OID = '2.16.840.1.113883.3.526.3.1580' VALUE_SET_NAME = 'Referral to Primary Care or Alternate Provider' EXPANSION_VERSION = 'eCQM Update 2020-05-07' SNOMEDCT = { '134403003', '183516009', '183561008', '183856001', '306206005', '306253008', '308470006' } class ReferralsWhereWeightAssessmentMayOccur(ValueSet): """ **Clinical Focus:** This value set contains concepts that represent multiple types of providers and settings for weight assessment. **Data Element Scope:** This value set may use the Quality Data Model (QDM) category related to Intervention or Procedure. **Inclusion Criteria:** Includes only relevant concepts associated with multiple providers in different settings performing weight assessments. **Exclusion Criteria:** No exclusions. """ OID = '2.16.840.1.113883.3.600.1.1527' VALUE_SET_NAME = 'Referrals Where Weight Assessment May Occur' EXPANSION_VERSION = 'eCQM Update 2020-05-07' SNOMEDCT = { '183515008', '183524004', '183583007', '306136006', '306163007', '306164001', '306165000', '306166004', '306167008', '306168003', '306226009', '306227000', '306252003', '306344004', '306353006', '306354000', '308459004', '308470006', '308477009', '390864007', '390866009', '390893007', '408289007', '416790000' } class SalvageTherapy(ValueSet): """ **Clinical Focus:** This value set contains concepts that represent salvage therapy procedures. **Data Element Scope:** This value set may use Quality Data Model (QDM) category related to Procedure. **Inclusion Criteria:** Includes only relevant concepts associated with salvage therapy procedures. **Exclusion Criteria:** No exclusions. """ OID = '2.16.840.1.113883.3.526.3.399' VALUE_SET_NAME = 'Salvage Therapy' EXPANSION_VERSION = 'eCQM Update 2020-05-07' CPT = { '51597', '55860', '55862', '55865' } SNOMEDCT = { '236209003', '236211007' } class TobaccoUseCessationCounseling(ValueSet): """ **Clinical Focus:** This value set contains concepts that represent various tobacco cessation counseling interventions. **Data Element Scope:** This value set may use the Quality Data Model (QDM) category related to Intervention. **Inclusion Criteria:** Includes only relevant concepts associated with various cessation interventions which may include referral to tobacco-related services or providers, education about the benefits of stopping tobacco use, education about the negative side effects of using tobacco, and monitoring for tobacco cessation. **Exclusion Criteria:** No exclusions. """ OID = '2.16.840.1.113883.3.526.3.509' VALUE_SET_NAME = 'Tobacco Use Cessation Counseling' EXPANSION_VERSION = 'eCQM Update 2020-05-07' CPT = { '99406', '99407' } SNOMEDCT = { '171055003', '185795007', '185796008', '225323000', '225324006', '310429001', '315232003', '384742004', '395700008', '449841000124108', '449851000124105', '449861000124107', '449871000124100', '702388001', '710081004', '711028002', '713700008' } class WeightReductionRecommended(ValueSet): """ **Clinical Focus:** This value set contains concepts that represent management and maintenance of weight. **Data Element Scope:** This value set may use the Quality Data Model (QDM) category related to Intervention or Procedure. **Inclusion Criteria:** Includes only relevant concepts associated with interventions addressing healthy eating, goal setting, weight management and maintenance. **Exclusion Criteria:** No exclusions. """ OID = '2.16.840.1.113883.3.600.1510' VALUE_SET_NAME = 'Weight Reduction Recommended' EXPANSION_VERSION = 'eCQM Update 2020-05-07' HCPCSLEVELII = { 'S9449' } SNOMEDCT = { '170795002', '266724001', '268523001', '408289007', '410200000' }
python
import os import json import tempfile from model import VepException, VepResult from bgcore import tsv from bgcore.request import Request def _ctype(value): return value.split(",") class VepService(object): HOST = "beta.rest.ensembl.org" VEP_STRAND = { "+" : "1", "-" : "-1", "1" : "1", "-1" : "-1" } def __init__(self, cache_path, max_retries=3, max_freq=3): self.cache_path = cache_path self.results_path = None self.__restful = Request(max_retries=max_retries, max_freq=max_freq) def __parse_response(self, var_id, chr, start, end, strand, alt, response): root = json.load(response) if not isinstance(root, dict): raise Exception("Unexpected result from VEP web service:\n{0}".format(json.dumps(root))) results = [] found = set() tag = ":".join([chr, str(start), str(end), strand, alt]) for data in root["data"]: #chromosome = data["location"]["name"]; #start = data["location"]["start"]; for trans in data["transcripts"]: gene = trans.get("gene_id"); transcript = trans.get("transcript_id") tstart = trans.get("translation_start") tend = trans.get("translation_end") if tstart is not None and tend is not None and tstart != tend: protein_pos = "{0}-{1}".format(tstart, tend) elif tstart is not None: protein_pos = tstart elif tend is not None: protein_pos = tend else: protein_pos = None protein = trans.get("translation_stable_id") for allele in trans.get("alleles", []): consequences = allele.get("consequence_terms") #allele_string = allele["allele_string"] aa_change = allele.get("pep_allele_string") sift_score = allele.get("sift_score") polyphen_score = allele.get("polyphen_score") key = "{0}|{1}".format(tag, transcript) if key not in found: found.add(key) results += [VepResult( var_id=var_id, chr=chr, start=start, allele=allele, gene=gene, transcript=transcript, consequences=consequences, protein_pos = protein_pos, aa_change=aa_change, protein=protein, sift=sift_score, polyphen=polyphen_score)] return results def get(self, chr, start, end, strand, alt, var_id=None): strand = self.VEP_STRAND[strand] url = "http://{0}/vep/human/{1}:{2}-{3}:{4}/{5}/consequences".format( self.HOST, chr, start, end, strand, alt) response = self.__restful.get(url, headers={"Content-type" : "application/json"}) if response is None: return None return self.__parse_response(var_id, chr, start, end, strand, alt, response) def run(self, variants_path): """ Run the VEP service and save results in a temporary file. :param variants_path: File with variants. In BED format. http://www.ensembl.org/info/docs/variation/vep/vep_script.html#custom_formats :return: True if successfull or False otherwise """ if self.results_path is None: self.results_path = tempfile.mkstemp()[1] with open(self.results_path, "w") as rf: with open(variants_path, "r") as vf: column_types = (str, int, int, str, str, int) for fields in tsv.lines(vf, column_types): chr, start, end, allele, strand, var_id = fields alt = allele[allele.find("/") + 1:] results = self.get(chr, start, end, strand, alt, var_id) if results is None: continue for r in results: rf.write(tsv.line_text( var_id, chr, start, allele, r.gene, r.transcript, ",".join(sorted(r.consequences)), r.protein_pos, r.aa_change, r.protein, r.sift, r.polyphen, null_value="-")) def results(self): """ Iterator that parses the results temporary file and yields VepResult's """ with open(self.results_path, "r") as f: column_types = (int, str, int, str, str, str, _ctype, str, str, str, float, float) for fields in tsv.lines(f, column_types, null_value="-"): var_id, chr, start, allele, gene, transcript, consequences, protein_pos, aa_change, protein, sift, polyphen = fields yield VepResult(var_id=var_id, chr=chr, start=start, allele=allele, gene=gene, transcript=transcript, consequences=consequences, protein_pos = protein_pos, aa_change=aa_change, protein=protein, sift=sift, polyphen=polyphen) def close(self): """ Removes temporary files """ if self.results_path is not None: os.remove(self.results_path) self.results_path = None
python
from ._PlaceBox import * from ._RemoveBox import *
python
"""Implements logic to render and validate web forms for login and user registration.""" from flask_wtf import FlaskForm from wtforms import StringField, PasswordField, BooleanField, SubmitField, SelectField from wtforms.validators import DataRequired class LoginForm(FlaskForm): """Form for new users to log-in to site.""" username = StringField('Username', validators=[DataRequired()]) password = PasswordField('Password', validators=[DataRequired()]) remember_me = BooleanField('Remember Me') submit = SubmitField('Sign In') # For disabled RegistrationForm # ------------------------------ # from wtforms.fields.html5 import EmailField # from wtforms.validators import ValidationError, Email, EqualTo, Regexp, Length # from cinescout.models import User # Disabled as of v1.1.0 # class RegistrationForm(FlaskForm): # """Form for new users to register with site.""" # # Class data # username = StringField('Username', # validators=[DataRequired(), # Regexp('^\w+$', # message="Username must contain only alphanumeric or underscore characters.") # ]) # email = EmailField('Email', validators=[ DataRequired(), Email()]) # password = PasswordField('Password', validators=[DataRequired(), # EqualTo('password2', message="Passwords do not match."), # Length(min=8, # message="Password must be at least 8 characters long.") # ]) # password2 = PasswordField('Re-enter Password', # validators=[DataRequired()]) # submit = SubmitField('Register') # def validate_username(self, username): # """Checks that username has not already been used. # Args: # username: String representing username of user. # Raises: # ValidationError: if username already in use. # """ # user = User.query.filter_by(username=username.data).first() # if user: # raise ValidationError('Username already taken. Please use another.') # def validate_email(self, email): # """Checks that user is not creating multiple accounts with same # email. # Args: # email: String representing user's email. # Raises: # ValidationError: if email already in use. # """ # user = User.query.filter_by(email=email.data).first() # if user: # raise ValidationError('An account already exists with this email address. Please use another.')
python
spanish_columns = { "oer": "oer", "games": "partidos", "points_made": "puntos_a_favor", "total_possessions": "posesiones_totales", "minutes": "minutos", "assists": "asistencias", "steals": "robos", "turnovers": "perdidas", "2_point_percentage": "porcentaje_2_puntos", "2_point_made": "2_puntos_metidos", "2_point_attempted": "2_puntos_intentados", "3_point_percentage": "porcentaje_3_puntos", "3_point_made": "3_puntos_metidos", "3_point_attempted": "3_puntos_intentados", "field_goal_percentage": "porcentaje_tiros_campo", "field_goal_made": "tiros_campo_metidos", "field_goal_attempted": "tiros_campo_intentados", "free_throw_percentage": "porcentaje_tiros_libres", "free_throw_made": "tiros_libres_metidos", "free_throw_attempted": "tiros_libres_intentados", "offensive_rebounds": "rebotes_defensivos", "defensive_rebounds": "rebotes_ofensivos", "total_rebounds": "rebotes_totales", "fouls_made": "faltas_cometidas", "fouls_received": "faltas_recibidas", "blocks_made": "tapones_favor", "blocks_received": "tapones_contra", "dunks": "mates", "ranking": "valoracion", "point_balance": "+/-", "team": "equipo", "der": "der", "points_received": "puntos_contra", "mode": "modo", "points_made_volume": "volumen_puntos_favor", "total_possessions_volume": "volumen_posesiones_totales", "2_point_made_volume": "volumen_2_puntos_metidos", "2_point_attempted_volume": "volumen_2_puntos_intentados", "3_point_made_volume": "volumen_3_puntos_metidos", "3_point_attempted_volume": "volumen_3_puntos_intentados", "field_goal_made_volume": "volumen_tiros_campo_metidos", "field_goal_attempted_volume": "volumen_tiros_campo_intentados", "free_throw_made_volume": "volumen_tiros_libres_metidos", "free_throw_attempted_volume": "volumen_tiros_libres_intentados", "offensive_rebounds_volume": "volumen_rebotes_defensivos", "defensive_rebounds_volume": "volumen_rebotes_ofensivos", "total_rebounds_volume": "volumen_rebotes_totales", "oer_40_min": "oer_por_40_minutos", }
python
import decimal import numbers import itertools __all__ = [ 'TRUNCATE', 'ROUND', 'DECIMAL_PLACES', 'SIGNIFICANT_DIGITS', 'NO_PADDING', 'PAD_WITH_ZERO', 'decimal_to_precision', ] # rounding mode TRUNCATE = 0 ROUND = 1 # digits counting mode DECIMAL_PLACES = 2 SIGNIFICANT_DIGITS = 3 # padding mode NO_PADDING = 4 PAD_WITH_ZERO = 5 def decimal_to_precision(n, rounding_mode=ROUND, precision=None, counting_mode=DECIMAL_PLACES, padding_mode=NO_PADDING): assert precision is not None and isinstance(precision, numbers.Integral) assert rounding_mode in [TRUNCATE, ROUND] assert counting_mode in [DECIMAL_PLACES, SIGNIFICANT_DIGITS] assert padding_mode in [NO_PADDING, PAD_WITH_ZERO] context = decimal.getcontext() precision = min(context.prec - 2, precision) # all default except decimal.Underflow (raised when a number is rounded to zero) context.traps[decimal.Underflow] = True context.rounding = decimal.ROUND_HALF_UP # rounds 0.5 away from zero dec = decimal.Decimal(n) string = str(dec) precise = None def power_of_10(x): return decimal.Decimal('10') ** (-x) if rounding_mode == ROUND: if counting_mode == DECIMAL_PLACES: precise = str(dec.quantize(power_of_10(precision))) # ROUND_HALF_EVEN is default context elif counting_mode == SIGNIFICANT_DIGITS: q = precision - dec.adjusted() - 1 sigfig = power_of_10(q) if q < 0: string_to_precision = string[:precision] # string_to_precision is '' when we have zero precision below = sigfig * decimal.Decimal(string_to_precision if string_to_precision else '0') above = below + sigfig precise = str(min((below, above), key=lambda x: abs(x - dec))) else: precise = str(dec.quantize(sigfig)) elif rounding_mode == TRUNCATE: # Slice a string if counting_mode == DECIMAL_PLACES: before, after = string.split('.') if '.' in string else (string, '') precise = before + '.' + after[:precision] elif counting_mode == SIGNIFICANT_DIGITS: if precision == 0: return '0' dot = string.index('.') if '.' in string else 0 start = dot - dec.adjusted() end = start + precision # need to clarify these conditionals if dot >= end: end -= 1 precise = string[:end].ljust(dot, '0') precise = precise.rstrip('.') if padding_mode == NO_PADDING: return precise.rstrip('0').rstrip('.') if '.' in precise else precise elif padding_mode == PAD_WITH_ZERO: if '.' in precise: if counting_mode == DECIMAL_PLACES: before, after = precise.split('.') return before + '.' + after.ljust(precision, '0') elif counting_mode == SIGNIFICANT_DIGITS: fsfg = len(list(itertools.takewhile(lambda x: x == '.' or x == '0', precise))) if '.' in precise[fsfg:]: precision += 1 return precise[:fsfg] + precise[fsfg:].rstrip('0').ljust(precision, '0') else: if counting_mode == SIGNIFICANT_DIGITS: if precision > len(precise): return precise + '.' + (precision - len(precise)) * '0' elif counting_mode == DECIMAL_PLACES: if precision > 0: return precise + '.' + precision * '0' return precise
python
import os from setuptools import setup README = """ See the README on `GitHub <https://github.com/uw-it-aca/uw-restclients-coda>`_. """ version_path = 'uw_coda/VERSION' VERSION = open(os.path.join(os.path.dirname(__file__), version_path)).read() VERSION = VERSION.replace("\n", "") # allow setup.py to be run from any path os.chdir(os.path.normpath(os.path.join(os.path.abspath(__file__), os.pardir))) url = "https://github.com/uw-it-aca/uw-restclients-coda" setup( name='UW-RestClients-CoDa', version=VERSION, packages=['uw_coda'], author="UW-IT AXDD", author_email="[email protected]", include_package_data=True, install_requires=['UW-RestClients-Core'], license='Apache License, Version 2.0', description=('A restclient for accessing the Instructor Course Dashboards' 'application at the University of Washington'), long_description=README, url=url, classifiers=[ 'Intended Audience :: Developers', 'License :: OSI Approved :: Apache Software License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Programming Language :: Python :: 3.6', ], )
python
#!/usr/bin/env pytest # -*- coding: utf-8 -*- ################################################################################ # Project: OGR NextGIS Web Driver # Purpose: Tests OGR NGW Driver capabilities # Author: Dmitry Baryshnikov, [email protected] # Language: Python ################################################################################ # The MIT License (MIT) # # Copyright (c) 2018-2019, NextGIS <[email protected]> # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in all # copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE # SOFTWARE. ################################################################################ import sys sys.path.append('../pymod') import gdaltest from osgeo import gdal from osgeo import ogr from osgeo import osr import time import json import pytest import random from datetime import datetime def check_availability(url): # Sandbox cleans at 1:05 on monday (UTC) now = datetime.utcnow() if now.weekday() == 0: if now.hour >= 1 and now.hour < 3: return False version_url = url + '/api/component/pyramid/pkg_version' if gdaltest.gdalurlopen(version_url) is None: return False # Check quota quota_url = url + '/api/resource/quota' quota_conn = gdaltest.gdalurlopen(quota_url) try: quota_json = json.loads(quota_conn.read()) quota_conn.close() if quota_json is None: return False limit = quota_json['limit'] count = quota_json['count'] if limit is None or count is None: return True return limit - count > 10 except: return False def get_new_name(): return 'gdaltest_group_' + str(int(time.time())) + '_' + str(random.randint(10, 99)) ############################################################################### # Check driver existence. def test_ogr_ngw_1(): gdaltest.ngw_ds = None gdaltest.ngw_drv = None gdaltest.ngw_drv = gdal.GetDriverByName('NGW') if gdaltest.ngw_drv is None: pytest.skip() gdaltest.ngw_test_server = 'https://sandbox.nextgis.com' # 'http://dev.nextgis.com/sandbox' if check_availability(gdaltest.ngw_test_server) == False: gdaltest.ngw_drv = None pytest.skip() ############################################################################### # Check create datasource. def test_ogr_ngw_2(): if gdaltest.ngw_drv is None: pytest.skip() if check_availability(gdaltest.ngw_test_server) == False: gdaltest.ngw_drv = None pytest.skip() create_url = 'NGW:' + gdaltest.ngw_test_server + '/resource/0/' + get_new_name() gdal.PushErrorHandler() gdaltest.ngw_ds = gdaltest.ngw_drv.Create(create_url, 0, 0, 0, gdal.GDT_Unknown, \ options=['DESCRIPTION=GDAL Test group',]) gdal.PopErrorHandler() assert gdaltest.ngw_ds is not None, 'Create datasource failed.' assert gdaltest.ngw_ds.GetMetadataItem('description', '') == 'GDAL Test group', \ 'Did not get expected datasource description.' assert int(gdaltest.ngw_ds.GetMetadataItem('id', '')) > 0, \ 'Did not get expected datasource identifier.' gdaltest.group_id = gdaltest.ngw_ds.GetMetadataItem('id', '') ############################################################################### # Check rename datasource. def test_ogr_ngw_3(): if gdaltest.ngw_drv is None: pytest.skip() if check_availability(gdaltest.ngw_test_server) == False: gdaltest.ngw_drv = None pytest.skip() new_name = get_new_name() + '_2' ds_resource_id = gdaltest.ngw_ds.GetMetadataItem('id', '') rename_url = 'NGW:' + gdaltest.ngw_test_server + '/resource/' + ds_resource_id assert gdaltest.ngw_drv.Rename(new_name, rename_url) == gdal.CE_None, \ 'Rename datasource failed.' ############################################################################### # Check datasource metadata. def test_ogr_ngw_4(): if gdaltest.ngw_drv is None: pytest.skip() if check_availability(gdaltest.ngw_test_server) == False: gdaltest.ngw_drv = None pytest.skip() ds_resource_id = gdaltest.ngw_ds.GetMetadataItem('id', '') gdaltest.ngw_ds.SetMetadataItem('test_int.d', '777', 'NGW') gdaltest.ngw_ds.SetMetadataItem('test_float.f', '777.555', 'NGW') gdaltest.ngw_ds.SetMetadataItem('test_string', 'metadata test', 'NGW') gdaltest.ngw_ds = None url = 'NGW:' + gdaltest.ngw_test_server + '/resource/' + ds_resource_id gdaltest.ngw_ds = gdal.OpenEx(url, gdal.OF_UPDATE) # gdaltest.ngw_drv.Open(url, update=1) assert gdaltest.ngw_ds is not None, \ 'Open datasource failed.' md_item = gdaltest.ngw_ds.GetMetadataItem('test_int.d', 'NGW') assert md_item == '777', \ 'Did not get expected datasource metadata item. test_int.d is equal {}, but should {}.'.format(md_item, '777') md_item = gdaltest.ngw_ds.GetMetadataItem('test_float.f', 'NGW') assert float(md_item) == pytest.approx(777.555, abs=0.00001), \ 'Did not get expected datasource metadata item. test_float.f is equal {}, but should {}.'.format(md_item, '777.555') md_item = gdaltest.ngw_ds.GetMetadataItem('test_string', 'NGW') assert md_item == 'metadata test', \ 'Did not get expected datasource metadata item. test_string is equal {}, but should {}.'.format(md_item, 'metadata test') resource_type = gdaltest.ngw_ds.GetMetadataItem('resource_type', '') assert resource_type is not None, 'Did not get expected datasource metadata item. Resourse type should be present.' def create_fields(lyr): fld_defn = ogr.FieldDefn('STRFIELD', ogr.OFTString) lyr.CreateField(fld_defn) lyr.SetMetadataItem('FIELD_0_ALIAS', 'String field test') fld_defn = ogr.FieldDefn('DECFIELD', ogr.OFTInteger) lyr.CreateField(fld_defn) lyr.SetMetadataItem('FIELD_1_ALIAS', 'Integer field test') fld_defn = ogr.FieldDefn('BIGDECFIELD', ogr.OFTInteger64) lyr.CreateField(fld_defn) lyr.SetMetadataItem('FIELD_2_ALIAS', 'Integer64 field test') fld_defn = ogr.FieldDefn('REALFIELD', ogr.OFTReal) lyr.CreateField(fld_defn) lyr.SetMetadataItem('FIELD_3_ALIAS', 'Real field test') fld_defn = ogr.FieldDefn('DATEFIELD', ogr.OFTDate) lyr.CreateField(fld_defn) lyr.SetMetadataItem('FIELD_4_ALIAS', 'Date field test') fld_defn = ogr.FieldDefn('TIMEFIELD', ogr.OFTTime) lyr.CreateField(fld_defn) lyr.SetMetadataItem('FIELD_5_ALIAS', 'Time field test') fld_defn = ogr.FieldDefn('DATETIMEFLD', ogr.OFTDateTime) lyr.CreateField(fld_defn) lyr.SetMetadataItem('FIELD_6_ALIAS', 'Date & time field test') def fill_fields(f): f.SetField('STRFIELD', "fo_o") f.SetField('DECFIELD', 123) f.SetField('BIGDECFIELD', 12345678901234) f.SetField('REALFIELD', 1.23) f.SetField('DATETIMEFLD', '2014/12/04 12:34:56') def fill_fields2(f): f.SetField('STRFIELD', "русский") f.SetField('DECFIELD', 321) f.SetField('BIGDECFIELD', 32145678901234) f.SetField('REALFIELD', 21.32) f.SetField('DATETIMEFLD', '2019/12/31 21:43:56') def add_metadata(lyr): lyr.SetMetadataItem('test_int.d', '777', 'NGW') lyr.SetMetadataItem('test_float.f', '777,555', 'NGW') lyr.SetMetadataItem('test_string', 'metadata test', 'NGW') ############################################################################### # Check create vector layers. def test_ogr_ngw_5(): if gdaltest.ngw_drv is None: pytest.skip() if check_availability(gdaltest.ngw_test_server) == False: gdaltest.ngw_drv = None pytest.skip() sr = osr.SpatialReference() sr.ImportFromEPSG(3857) lyr = gdaltest.ngw_ds.CreateLayer('test_pt_layer', srs=sr, geom_type=ogr.wkbMultiPoint, options=['OVERWRITE=YES', 'DESCRIPTION=Test point layer']) assert lyr is not None, 'Create layer failed.' create_fields(lyr) # Test duplicated names. fld_defn = ogr.FieldDefn('STRFIELD', ogr.OFTString) assert lyr.CreateField(fld_defn) != 0, 'Expected not to create duplicated field' # Test forbidden field names. gdal.ErrorReset() gdal.PushErrorHandler('CPLQuietErrorHandler') fld_defn = ogr.FieldDefn('id', ogr.OFTInteger) lyr.CreateField(fld_defn) gdal.PopErrorHandler() assert gdal.GetLastErrorMsg() != '', 'Expecting a warning' add_metadata(lyr) lyr = gdaltest.ngw_ds.CreateLayer('test_ln_layer', srs=sr, geom_type=ogr.wkbMultiLineString, options=['OVERWRITE=YES', 'DESCRIPTION=Test point layer']) assert lyr is not None, 'Create layer failed.' create_fields(lyr) add_metadata(lyr) lyr = gdaltest.ngw_ds.CreateLayer('test_pl_layer', srs=sr, geom_type=ogr.wkbMultiPolygon, options=['OVERWRITE=YES', 'DESCRIPTION=Test point layer']) assert lyr is not None, 'Create layer failed.' create_fields(lyr) add_metadata(lyr) # Test overwrite lyr = gdaltest.ngw_ds.CreateLayer('test_pt_layer', srs=sr, geom_type=ogr.wkbPoint, options=['OVERWRITE=YES', 'DESCRIPTION=Test point layer']) assert lyr is not None, 'Create layer failed.' create_fields(lyr) add_metadata(lyr) lyr = gdaltest.ngw_ds.CreateLayer('test_ln_layer', srs=sr, geom_type=ogr.wkbLineString, options=['OVERWRITE=YES', 'DESCRIPTION=Test point layer']) assert lyr is not None, 'Create layer failed.' create_fields(lyr) add_metadata(lyr) lyr = gdaltest.ngw_ds.CreateLayer('test_pl_layer', srs=sr, geom_type=ogr.wkbPolygon, options=['OVERWRITE=YES', 'DESCRIPTION=Test point layer']) assert lyr is not None, 'Create layer failed.' create_fields(lyr) add_metadata(lyr) # Test without overwrite lyr = gdaltest.ngw_ds.CreateLayer('test_pl_layer', srs=sr, geom_type=ogr.wkbMultiPolygon, options=['OVERWRITE=NO', 'DESCRIPTION=Test point layer 1']) assert lyr is None, 'Create layer without overwrite should fail.' lyr = gdaltest.ngw_ds.CreateLayer('test_pl_layer', srs=sr, geom_type=ogr.wkbMultiPolygon, options=['DESCRIPTION=Test point layer 1']) assert lyr is None, 'Create layer without overwrite should fail.' ds_resource_id = gdaltest.ngw_ds.GetMetadataItem('id', '') gdaltest.ngw_ds = None url = 'NGW:' + gdaltest.ngw_test_server + '/resource/' + ds_resource_id gdaltest.ngw_ds = gdal.OpenEx(url, gdal.OF_UPDATE) # gdaltest.ngw_drv.Open(url, update=1) assert gdaltest.ngw_ds is not None, 'Open datasource failed.' for layer_name in ['test_pt_layer', 'test_ln_layer', 'test_pl_layer']: lyr = gdaltest.ngw_ds.GetLayerByName(layer_name) assert lyr is not None, 'Get layer {} failed.'.format(layer_name) md_item = lyr.GetMetadataItem('test_int.d', 'NGW') assert md_item == '777', \ 'Did not get expected layer metadata item. test_int.d is equal {}, but should {}.'.format(md_item, '777') md_item = lyr.GetMetadataItem('test_float.f', 'NGW') assert float(md_item) == pytest.approx(777.555, abs=0.00001), \ 'Did not get expected layer metadata item. test_float.f is equal {}, but should {}.'.format(md_item, '777.555') md_item = lyr.GetMetadataItem('test_string', 'NGW') assert md_item == 'metadata test', \ 'Did not get expected layer metadata item. test_string is equal {}, but should {}.'.format(md_item, 'metadata test') resource_type = lyr.GetMetadataItem('resource_type', '') assert resource_type is not None, 'Did not get expected layer metadata item. Resourse type should be present.' ############################################################################### # Check open single vector layer. def test_ogr_ngw_6(): if gdaltest.ngw_drv is None: pytest.skip() if check_availability(gdaltest.ngw_test_server) == False: gdaltest.ngw_drv = None pytest.skip() lyr = gdaltest.ngw_ds.GetLayerByName('test_pt_layer') lyr_resource_id = lyr.GetMetadataItem('id', '') url = 'NGW:' + gdaltest.ngw_test_server + '/resource/' + lyr_resource_id ds = gdal.OpenEx(url) assert ds is not None and ds.GetLayerCount() == 1, \ 'Failed to open single vector layer.' ############################################################################### # Check insert, update and delete features. def test_ogr_ngw_7(): if gdaltest.ngw_drv is None: pytest.skip() if check_availability(gdaltest.ngw_test_server) == False: gdaltest.ngw_drv = None pytest.skip() lyr = gdaltest.ngw_ds.GetLayerByName('test_pt_layer') f = ogr.Feature(lyr.GetLayerDefn()) fill_fields(f) f.SetGeometry(ogr.CreateGeometryFromWkt('POINT (1 2)')) ret = lyr.CreateFeature(f) assert ret == 0 and f.GetFID() >= 0, \ 'Create feature failed. Expected FID greater or equal 0, got {}.'.format(f.GetFID()) fill_fields2(f) f.SetGeometry(ogr.CreateGeometryFromWkt('POINT (3 4)')) ret = lyr.SetFeature(f) assert ret == 0, 'Failed to update feature #{}.'.format(f.GetFID()) lyr.DeleteFeature(f.GetFID()) # Expected fail to get feature gdal.PushErrorHandler() f = lyr.GetFeature(f.GetFID()) gdal.PopErrorHandler() assert f is None, 'Failed to delete feature #{}.'.format(f.GetFID()) ############################################################################### # Check insert, update features in batch mode. def test_ogr_ngw_8(): if gdaltest.ngw_drv is None: pytest.skip() if check_availability(gdaltest.ngw_test_server) == False: gdaltest.ngw_drv = None pytest.skip() ds_resource_id = gdaltest.ngw_ds.GetMetadataItem('id', '') gdaltest.ngw_ds = None url = 'NGW:' + gdaltest.ngw_test_server + '/resource/' + ds_resource_id gdaltest.ngw_ds = gdal.OpenEx(url, gdal.OF_UPDATE, open_options=['BATCH_SIZE=2']) lyr = gdaltest.ngw_ds.GetLayerByName('test_pt_layer') f1 = ogr.Feature(lyr.GetLayerDefn()) fill_fields(f1) f1.SetGeometry(ogr.CreateGeometryFromWkt('POINT (1 2)')) ret = lyr.CreateFeature(f1) assert ret == 0 and f1.GetFID() < 0 f2 = ogr.Feature(lyr.GetLayerDefn()) fill_fields2(f2) f2.SetGeometry(ogr.CreateGeometryFromWkt('POINT (2 3)')) ret = lyr.CreateFeature(f2) assert ret == 0 and f2.GetFID() < 0 f3 = ogr.Feature(lyr.GetLayerDefn()) fill_fields(f3) f3.SetGeometry(ogr.CreateGeometryFromWkt('POINT (3 4)')) ret = lyr.CreateFeature(f3) assert ret == 0 ret = lyr.SyncToDisk() assert ret == 0 lyr.ResetReading() feat = lyr.GetNextFeature() counter = 0 while feat is not None: counter += 1 assert feat.GetFID() >= 0, 'Expected FID greater or equal 0, got {}.'.format(feat.GetFID()) feat = lyr.GetNextFeature() assert counter >= 3, 'Expected 3 or greater feature count, got {}.'.format(counter) ############################################################################### # Check paging while GetNextFeature. def test_ogr_ngw_9(): if gdaltest.ngw_drv is None: pytest.skip() if check_availability(gdaltest.ngw_test_server) == False: gdaltest.ngw_drv = None pytest.skip() ds_resource_id = gdaltest.ngw_ds.GetMetadataItem('id', '') gdaltest.ngw_ds = None url = 'NGW:' + gdaltest.ngw_test_server + '/resource/' + ds_resource_id gdaltest.ngw_ds = gdal.OpenEx(url, gdal.OF_UPDATE, open_options=['PAGE_SIZE=2']) lyr = gdaltest.ngw_ds.GetLayerByName('test_pt_layer') lyr.ResetReading() feat = lyr.GetNextFeature() counter = 0 while feat is not None: counter += 1 assert feat.GetFID() >= 0, 'Expected FID greater or equal 0, got {}.'.format(feat.GetFID()) feat = lyr.GetNextFeature() assert counter >= 3, 'Expected 3 or greater feature count, got {}.'.format(counter) ############################################################################### # Check native data. def test_ogr_ngw_10(): if gdaltest.ngw_drv is None: pytest.skip() if check_availability(gdaltest.ngw_test_server) == False: gdaltest.ngw_drv = None pytest.skip() ds_resource_id = gdaltest.ngw_ds.GetMetadataItem('id', '') gdaltest.ngw_ds = None url = 'NGW:' + gdaltest.ngw_test_server + '/resource/' + ds_resource_id gdaltest.ngw_ds = gdal.OpenEx(url, gdal.OF_UPDATE, open_options=['NATIVE_DATA=YES']) lyr = gdaltest.ngw_ds.GetLayerByName('test_pt_layer') lyr.ResetReading() feat = lyr.GetNextFeature() feature_id = feat.GetFID() native_data = feat.GetNativeData() assert native_data is not None, 'Feature #{} native data should not be empty'.format(feature_id) # {"description":null,"attachment":null} assert feat.GetNativeMediaType() == 'application/json', 'Unsupported native media type' # Set description feat.SetNativeData('{"description":"Test feature description"}') ret = lyr.SetFeature(feat) assert ret == 0, 'Failed to update feature #{}.'.format(feature_id) feat = lyr.GetFeature(feature_id) native_data = feat.GetNativeData() assert native_data is not None and native_data.find('Test feature description') != -1, 'Expected feature description text, got {}'.format(native_data) ############################################################################### # Check ignored fields works ok def test_ogr_ngw_11(): if gdaltest.ngw_drv is None or gdaltest.ngw_ds is None: pytest.skip() if check_availability(gdaltest.ngw_test_server) == False: gdaltest.ngw_drv = None pytest.skip() lyr = gdaltest.ngw_ds.GetLayerByName('test_pt_layer') lyr.SetIgnoredFields(['STRFIELD']) feat = lyr.GetNextFeature() assert not feat.IsFieldSet('STRFIELD'), 'got STRFIELD despite request to ignore it.' assert feat.GetFieldAsInteger('DECFIELD') == 123, 'missing or wrong DECFIELD' fd = lyr.GetLayerDefn() fld = fd.GetFieldDefn(0) # STRFIELD assert fld.IsIgnored(), 'STRFIELD unexpectedly not marked as ignored.' fld = fd.GetFieldDefn(1) # DECFIELD assert not fld.IsIgnored(), 'DECFIELD unexpectedly marked as ignored.' assert not fd.IsGeometryIgnored(), 'geometry unexpectedly ignored.' assert not fd.IsStyleIgnored(), 'style unexpectedly ignored.' feat = None lyr = None ############################################################################### # Check attribute filter. def test_ogr_ngw_12(): if gdaltest.ngw_drv is None: pytest.skip() if check_availability(gdaltest.ngw_test_server) == False: gdaltest.ngw_drv = None pytest.skip() lyr = gdaltest.ngw_ds.GetLayerByName('test_pt_layer') lyr.SetAttributeFilter("STRFIELD = 'русский'") fc = lyr.GetFeatureCount() assert fc == 1, 'Expected feature count is 1, got {}.'.format(fc) lyr.SetAttributeFilter("STRFIELD = 'fo_o' AND DECFIELD = 321") fc = lyr.GetFeatureCount() assert fc == 0, 'Expected feature count is 0, got {}.'.format(fc) lyr.SetAttributeFilter('NGW:fld_STRFIELD=fo_o&fld_DECFIELD=123') fc = lyr.GetFeatureCount() assert fc == 2, 'Expected feature count is 2, got {}.'.format(fc) ############################################################################### # Check spatial filter. def test_ogr_ngw_13(): if gdaltest.ngw_drv is None: pytest.skip() if check_availability(gdaltest.ngw_test_server) == False: gdaltest.ngw_drv = None pytest.skip() lyr = gdaltest.ngw_ds.GetLayerByName('test_pt_layer') # Reset any attribute filters lyr.SetAttributeFilter(None) # Check intersecting POINT(3 4) lyr.SetSpatialFilter(ogr.CreateGeometryFromWkt('POLYGON ((2.5 3.5,2.5 6,6 6,6 3.5,2.5 3.5))')) fc = lyr.GetFeatureCount() assert fc == 1, 'Expected feature count is 1, got {}.'.format(fc) ############################################################################### # Check ExecuteSQL. def test_ogr_ngw_14(): if gdaltest.ngw_drv is None: pytest.skip() if check_availability(gdaltest.ngw_test_server) == False: gdaltest.ngw_drv = None pytest.skip() gdaltest.ngw_ds.ExecuteSQL('DELLAYER:test_ln_layer') lyr = gdaltest.ngw_ds.GetLayerByName('test_ln_layer') assert lyr is None, 'Expected fail to get layer test_ln_layer.' lyr = gdaltest.ngw_ds.GetLayerByName('test_pl_layer') f = ogr.Feature(lyr.GetLayerDefn()) fill_fields(f) f.SetGeometry(ogr.CreateGeometryFromWkt('POLYGON((0 0,0 1,1 0,0 0))')) ret = lyr.CreateFeature(f) assert ret == 0, 'Failed to create feature in test_pl_layer.' assert lyr.GetFeatureCount() == 1, 'Expected feature count is 1, got {}.'.format(lyr.GetFeatureCount()) gdaltest.ngw_ds.ExecuteSQL('DELETE FROM test_pl_layer') assert lyr.GetFeatureCount() == 0, 'Expected feature count is 0, got {}.'.format(lyr.GetFeatureCount()) gdaltest.ngw_ds.ExecuteSQL('ALTER TABLE test_pl_layer RENAME TO test_pl_layer777') lyr = gdaltest.ngw_ds.GetLayerByName('test_pl_layer777') assert lyr is not None, 'Get layer test_pl_layer777 failed.' # Create 2 new features f = ogr.Feature(lyr.GetLayerDefn()) fill_fields(f) f.SetGeometry(ogr.CreateGeometryFromWkt('POLYGON((0 0,0 1,1 0,0 0))')) ret = lyr.CreateFeature(f) assert ret == 0, 'Failed to create feature in test_pl_layer777.' f = ogr.Feature(lyr.GetLayerDefn()) fill_fields2(f) f.SetGeometry(ogr.CreateGeometryFromWkt('POLYGON((1 1,1 2,2 1,1 1))')) ret = lyr.CreateFeature(f) assert ret == 0, 'Failed to create feature in test_pl_layer777.' lyr = gdaltest.ngw_ds.ExecuteSQL("SELECT STRFIELD,DECFIELD FROM test_pl_layer777 WHERE STRFIELD = 'fo_o'") assert lyr is not None, 'ExecuteSQL: SELECT STRFIELD,DECFIELD FROM test_pl_layer777 WHERE STRFIELD = "fo_o"; failed.' assert lyr.GetFeatureCount() == 2, 'Expected feature count is 2, got {}.'.format(lyr.GetFeatureCount()) gdaltest.ngw_ds.ReleaseResultSet(lyr) ############################################################################### # Run test_ogrsf def test_ogr_ngw_test_ogrsf(): if gdaltest.ngw_drv is None or gdal.GetConfigOption('SKIP_SLOW') is not None: pytest.skip() if check_availability(gdaltest.ngw_test_server) == False: gdaltest.ngw_drv = None pytest.skip() if gdaltest.skip_on_travis(): pytest.skip() if gdaltest.ngw_ds is None: pytest.skip() url = 'NGW:' + gdaltest.ngw_test_server + '/resource/' + gdaltest.group_id import test_cli_utilities if test_cli_utilities.get_test_ogrsf_path() is None: pytest.skip() ret = gdaltest.runexternal(test_cli_utilities.get_test_ogrsf_path() + ' ' + url) assert ret.find('INFO') != -1 and ret.find('ERROR') == -1 ret = gdaltest.runexternal(test_cli_utilities.get_test_ogrsf_path() + ' ' + url + ' -oo PAGE_SIZE=100') assert ret.find('INFO') != -1 and ret.find('ERROR') == -1 ret = gdaltest.runexternal(test_cli_utilities.get_test_ogrsf_path() + ' ' + url + ' -oo BATCH_SIZE=5') assert ret.find('INFO') != -1 and ret.find('ERROR') == -1 ret = gdaltest.runexternal(test_cli_utilities.get_test_ogrsf_path() + ' ' + url + ' -oo BATCH_SIZE=5 -oo PAGE_SIZE=100') assert ret.find('INFO') != -1 and ret.find('ERROR') == -1 ############################################################################### # Cleanup def test_ogr_ngw_cleanup(): if gdaltest.ngw_drv is None: pytest.skip() if gdaltest.group_id is not None: delete_url = 'NGW:' + gdaltest.ngw_test_server + '/resource/' + gdaltest.group_id gdaltest.ngw_layer = None gdaltest.ngw_ds = None assert gdaltest.ngw_drv.Delete(delete_url) == gdal.CE_None, \ 'Failed to delete datasource ' + delete_url + '.' gdaltest.ngw_ds = None
python
# Copyright (c) 2016 Rackspace Hosting Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or # implied. # See the License for the specific language governing permissions and # limitations under the License. from neutron.api import extensions from neutron import manager from neutron import wsgi from oslo_log import log as logging import quark.utils as utils RESOURCE_NAME = 'job' RESOURCE_COLLECTION = RESOURCE_NAME + "s" EXTENDED_ATTRIBUTES_2_0 = { RESOURCE_COLLECTION: { "completed": {"allow_post": False, "is_visible": True, "default": False}} } attr_dict = EXTENDED_ATTRIBUTES_2_0[RESOURCE_COLLECTION] attr_dict[RESOURCE_NAME] = {'allow_post': True, 'allow_put': True, 'is_visible': True} LOG = logging.getLogger(__name__) class JobsController(wsgi.Controller): def __init__(self, plugin): self._resource_name = RESOURCE_NAME self._plugin = plugin @utils.exc_wrapper def index(self, request): context = request.context return {"jobs": self._plugin.get_jobs(context, **request.GET)} @utils.exc_wrapper def show(self, request, id): context = request.context return {"job": self._plugin.get_job(context, id)} @utils.exc_wrapper def create(self, request, body=None): context = request.context body = self._deserialize(request.body, request.get_content_type()) return {"job": self._plugin.create_job(context, body)} @utils.exc_wrapper def update(self, request, id, body=None): context = request.context body = self._deserialize(request.body, request.get_content_type()) return {"job": self._plugin.update_job(context, id, body)} @utils.exc_wrapper def delete(self, request, id): context = request.context return self._plugin.delete_job(context, id) class Jobs(extensions.ExtensionDescriptor): """Jobs support.""" @classmethod def get_name(cls): return "Asyncronous jobs for a tenant" @classmethod def get_alias(cls): return RESOURCE_COLLECTION @classmethod def get_description(cls): return "Provide a way to track asyncronous jobs" @classmethod def get_namespace(cls): return ("http://docs.openstack.org/network/ext/" "ip_addresses/api/v2.0") @classmethod def get_updated(cls): return "2016-05-15T10:00:00-00:00" def get_extended_resources(self, version): if version == "2.0": return EXTENDED_ATTRIBUTES_2_0 else: return {} @classmethod def get_resources(cls): """Returns Ext Resources.""" job_controller = JobsController( manager.NeutronManager.get_plugin()) resources = [] resources.append(extensions.ResourceExtension( Jobs.get_alias(), job_controller)) return resources
python
# coding: utf-8 # pylint: disable=W0201,C0111 from __future__ import division, unicode_literals, print_function # standard library import sys import os.path import time import datetime import traceback from copy import deepcopy from collections import OrderedDict from itertools import cycle from math import ceil import cgi # html lib from six import string_types, iteritems, itervalues from six.moves import range import numpy as np from pyNastran.gui.qt_version import qt_version from qtpy import QtCore, QtGui #, API from qtpy.QtWidgets import ( QMessageBox, QWidget, QMainWindow, QDockWidget, QFrame, QHBoxLayout, QAction) from qtpy.compat import getsavefilename, getopenfilename #from pyNastran.gui.gui_utils.vtk_utils import numpy_to_vtk_points, get_numpy_idtype_for_vtk import vtk from pyNastran.gui.qt_files.QVTKRenderWindowInteractor import QVTKRenderWindowInteractor import pyNastran from pyNastran.bdf.utils import write_patran_syntax_dict from pyNastran.utils.log import SimpleLogger from pyNastran.utils import print_bad_path, integer_types, object_methods from pyNastran.utils.numpy_utils import loadtxt_nice from pyNastran.gui.gui_utils.write_gif import ( setup_animation, update_animation_inputs, write_gif) from pyNastran.gui.qt_files.gui_qt_common import GuiCommon from pyNastran.gui.qt_files.scalar_bar import ScalarBar from pyNastran.gui.qt_files.alt_geometry_storage import AltGeometry from pyNastran.gui.qt_files.coord_properties import CoordProperties from pyNastran.gui.gui_interface.legend.interface import set_legend_menu from pyNastran.gui.gui_interface.clipping.interface import set_clipping_menu from pyNastran.gui.gui_interface.camera.interface import set_camera_menu from pyNastran.gui.gui_interface.preferences.interface import set_preferences_menu from pyNastran.gui.gui_interface.groups_modify.interface import on_set_modify_groups from pyNastran.gui.gui_interface.groups_modify.groups_modify import Group from gui_utils.menus.add_sidebar import Sidebar from pyNastran.gui.menus.application_log import PythonConsoleWidget, ApplicationLogWidget from pyNastran.gui.menus.manage_actors import EditGeometryProperties from pyNastran.gui.styles.area_pick_style import AreaPickStyle from pyNastran.gui.styles.zoom_style import ZoomStyle from pyNastran.gui.styles.probe_style import ProbeResultStyle from pyNastran.gui.styles.rotation_center_style import RotationCenterStyle #from pyNastran.gui.menus.multidialog import MultiFileDialog from pyNastran.gui.gui_utils.utils import load_csv, load_deflection_csv, load_user_geom #--------------------------------- from gui_utils.menus.wing_menu import WingWindow import gui_utils.vsp_g as vsp class Interactor(vtk.vtkGenericRenderWindowInteractor): def __init__(self): #vtk.vtkGenericRenderWindowInteractor() pass def HighlightProp(self): print('highlight') class PyNastranRenderWindowInteractor(QVTKRenderWindowInteractor): def __init__(self, parent=None): render_window = vtk.vtkRenderWindow() iren = Interactor() iren.SetRenderWindow(render_window) kwargs = { 'iren' : iren, 'rw' : render_window, } QVTKRenderWindowInteractor.__init__(self, parent=parent, iren=iren, rw=render_window) #self.Highlight # http://pyqt.sourceforge.net/Docs/PyQt5/multiinheritance.html class GuiCommon2(QMainWindow, GuiCommon): def __init__(self, **kwds): """ fmt_order, html_logging, inputs, parent=None, """ # this will reset the background color/label color if things break #super(QMainWindow, self).__init__(self) if qt_version == 4: QMainWindow.__init__(self) GuiCommon.__init__(self, **kwds) elif qt_version == 5: super(GuiCommon2, self).__init__(**kwds) elif qt_version == 'pyside': #super(GuiCommon2, self).__init__(**kwds) # fails # fails #QMainWindow.__init__(self) #GuiCommon.__init__(self, **kwds) #super(GuiCommon2, self).__init__(**kwds) #super(GuiCommon2, self).__init__(**kwds) #super(GuiCommon2, self).__init__(**kwds) QMainWindow.__init__(self) GuiCommon.__init__(self, **kwds) else: raise NotImplementedError(qt_version) fmt_order = kwds['fmt_order'] inputs = kwds['inputs'] self.stdout = vsp.cvar.cstdout self.errorMgr = vsp.ErrorMgrSingleton_getInstance() #self.app = inputs['app'] #del inputs['app'] if inputs['log'] is not None: html_logging = False else: html_logging = kwds['html_logging'] del kwds['html_logging'] #if qt_version == 4: # TODO: remove this??? #QMainWindow.__init__(self) #----------------------------------------------------------------------- self._active_background_image = None self.reset_settings = False self.fmts = fmt_order self.base_window_title = "pyNastran v%s" % pyNastran.__version__ #defaults self.wildcard_delimited = 'Delimited Text (*.txt; *.dat; *.csv)' # initializes tools/checkables self.set_tools() self.html_logging = html_logging self.execute_python = True self.scalar_bar = ScalarBar(self.is_horizontal_scalar_bar) self.color_function_black = vtk.vtkColorTransferFunction() self.color_function_black.AddRGBPoint(0.0, 0.0, 0.0, 0.0) self.color_function_black.AddRGBPoint(1.0, 0.0, 0.0, 0.0) # in,lb,s self.input_units = ['', '', ''] # '' means not set self.display_units = ['', '', ''] self.recent_files = [] #def dragEnterEvent(self, e): #print(e) #print('drag event') #if e.mimeData().hasFormat('text/plain'): #e.accept() #else: #e.ignore() #def dropEvent(self, e): #print(e) #print('drop event') def Render(self): #self.vtk_interactor.Render() self.vtk_interactor.GetRenderWindow().Render() @property def legend_shown(self): """determines if the legend is shown""" return self.scalar_bar.is_shown @property def scalarBar(self): return self.scalar_bar.scalar_bar def hide_legend(self): """hides the legend""" #self.scalar_bar.is_shown = False self.scalarBar.VisibilityOff() def show_legend(self): """shows the legend""" #self.scalar_bar.is_shown = True self.scalarBar.VisibilityOn() @property def color_function(self): return self.scalar_bar.color_function #def get_color_function(self): #return self.scalar_bar.color_function @property def window_title(self): return self.getWindowTitle() @window_title.setter def window_title(self, msg): #msg2 = "%s - " % self.base_window_title #msg2 += msg self.setWindowTitle(msg) @property def logo(self): """Gets the pyNastran icon path, which can be overwritten""" return self._logo @logo.setter def logo(self, logo): """Sets the pyNastran icon path, which can be overwritten""" self._logo = logo def init_ui(self): """ Initialize user iterface +--------------+ | Window Title | +--------------+----------------+ | Menubar | +-------------------------------+ | Toolbar | +---------------------+---------+ | | | | | | | | Results | | VTK Frame | Dock | | | | | | | +---------------------+---------+ | | | HTML Logging Dock | | | +-------------------------------+ """ #self.resize(1100, 700) self.statusBar().showMessage('Ready') # windows title and aplication icon self.setWindowTitle('Statusbar') if self._logo is not None: self.setWindowIcon(QtGui.QIcon(self._logo)) self.window_title = self.base_window_title #=========== Results widget =================== self.res_dock = QDockWidget("Components", self) self.res_dock.setObjectName("results_obj") #self.res_widget = QtGui.QTextEdit() #self.res_widget.setReadOnly(True) #self.res_dock.setWidget(self.res_widget) self.res_widget = Sidebar(self) #self.res_widget.update_results(data) #self.res_widget.setWidget(sidebar) self.res_dock.setWidget(self.res_widget) self.addDockWidget(QtCore.Qt.RightDockWidgetArea, self.res_dock) self.create_log_python_docks() #=============================================== self.run_vtk = True if self.run_vtk: self._create_vtk_objects() self._build_menubar() #self._hide_menubar() if self.run_vtk: self.build_vtk_frame() #compassRepresentation = vtk.vtkCompassRepresentation() #compassWidget = vtk.vtkCompassWidget() #compassWidget.SetInteractor(self.iren) #compassWidget.SetRepresentation(compassRepresentation) #compassWidget.EnabledOn() def create_log_python_docks(self): """ Creates the - HTML Log dock - Python Console dock """ #=========== Logging widget =================== if self.html_logging is True: self.log_dock_widget = ApplicationLogWidget(self) self.log_widget = self.log_dock_widget.log_widget self.addDockWidget(QtCore.Qt.BottomDockWidgetArea, self.log_dock_widget) else: self.log_widget = self.log if self.execute_python: self.python_dock_widget = PythonConsoleWidget(self) self.python_dock_widget.setObjectName("python_console") self.addDockWidget(QtCore.Qt.BottomDockWidgetArea, self.python_dock_widget) def _on_execute_python_button(self, clear=False): """executes the docked python console""" txt = str(self.python_dock_widget.enter_data.toPlainText()).rstrip() if len(txt) == 0: return self.log_command(txt) try: exec(txt) except TypeError as e: self.log_error('\n' + ''.join(traceback.format_stack())) #traceback.print_exc(file=self.log_error) self.log_error(str(e)) self.log_error(str(txt)) self.log_error(str(type(txt))) return except Exception as e: #self.log_error(traceback.print_stack(f)) self.log_error('\n' + ''.join(traceback.format_stack())) #traceback.print_exc(file=self.log_error) self.log_error(str(e)) self.log_error(str(txt)) return if clear: self.python_dock_widget.enter_data.clear() def load_batch_inputs(self, inputs): geom_script = inputs['geomscript'] if geom_script is not None: self.on_run_script(geom_script) if not inputs['format']: return form = inputs['format'].lower() input_filenames = inputs['input'] results_filename = inputs['output'] plot = True if results_filename: plot = False #print('input_filename =', input_filename) if input_filenames is not None: for input_filename in input_filenames: if not os.path.exists(input_filename): msg = '%s does not exist\n%s' % ( input_filename, print_bad_path(input_filename)) self.log.error(msg) if self.html_logging: print(msg) return for results_filenamei in results_filename: #print('results_filenamei =', results_filenamei) if results_filenamei is not None: if not os.path.exists(results_filenamei): msg = '%s does not exist\n%s' % ( results_filenamei, print_bad_path(results_filenamei)) self.log.error(msg) if self.html_logging: print(msg) return #is_geom_results = input_filename == results_filename and len(input_filenames) == 1 is_geom_results = False for i, input_filename in enumerate(input_filenames): if i == 0: name = 'main' else: name = input_filename #form = inputs['format'].lower() #if is_geom_results: # is_failed = self.on_load_geometry_and_results( # infile_name=input_filename, name=name, geometry_format=form, # plot=plot, raise_error=True) #else: is_failed = self.on_load_geometry( infile_name=input_filename, name=name, geometry_format=form, plot=plot, raise_error=True) self.name = 'main' #print('keys =', self.nid_maps.keys()) if is_failed: return if results_filename: # and not is_geom_results self.on_load_results(results_filename) post_script = inputs['postscript'] if post_script is not None: self.on_run_script(post_script) self.on_reset_camera() self.vtk_interactor.Modified() def set_tools(self, tools=None, checkables=None): """Creates the GUI tools""" if checkables is None: checkables = { # name, is_checked 'show_info' : True, 'show_debug' : True, 'show_gui' : True, 'show_command' : True, 'anti_alias_0' : True, 'anti_alias_1' : False, 'anti_alias_2' : False, 'anti_alias_4' : False, 'anti_alias_8' : False, 'rotation_center' : False, 'measure_distance' : False, 'probe_result' : False, 'area_pick' : False, 'zoom' : False, } if tools is None: file_tools = [ ('exit', '&Exit', 'texit.png', 'Ctrl+Q', 'Exit application', self.closeEvent), # QtGui.qApp.quit ('load_geometry', 'Load &Geometry...', 'load_geometry.png', 'Ctrl+O', 'Loads a geometry input file', self.on_load_geometry), ('load_results', 'Load &Results...', 'load_results.png', 'Ctrl+R', 'Loads a results file', self.on_load_results), ('load_csv_user_geom', 'Load CSV User Geometry...', '', None, 'Loads custom geometry file', self.on_load_user_geom), ('load_csv_user_points', 'Load CSV User Points...', 'user_points.png', None, 'Loads CSV points', self.on_load_csv_points), ('load_custom_result', 'Load Custom Results...', '', None, 'Loads a custom results file', self.on_load_custom_results), ('script', 'Run Python Script...', 'python48.png', None, 'Runs pyNastranGUI in batch mode', self.on_run_script), ] tools = file_tools + [ ('log_clear', 'Clear Application Log', '', None, 'Clear Application Log', self.clear_application_log), ('label_clear', 'Clear Current Labels', '', None, 'Clear current labels', self.clear_labels), ('label_reset', 'Clear All Labels', '', None, 'Clear all labels', self.reset_labels), ('legend', 'Modify Legend...', 'legend.png', None, 'Set Legend', self.set_legend), ('clipping', 'Set Clipping...', '', None, 'Set Clipping', self.set_clipping), #('axis', 'Show/Hide Axis', 'axis.png', None, 'Show/Hide Global Axis', self.on_show_hide_axes), ('wireframe', 'Wireframe Model', 'twireframe.png', 'w', 'Show Model as a Wireframe Model', self.on_wireframe), ('surface', 'Surface Model', 'tsolid.png', 's', 'Show Model as a Surface Model', self.on_surface), ('geo_properties', 'Edit Geometry Properties...', '', None, 'Change Model Color/Opacity/Line Width', self.edit_geometry_properties), ('modify_groups', 'Modify Groups...', '', None, 'Create/Edit/Delete Groups', self.on_set_modify_groups), ('create_groups_by_visible_result', 'Create Groups By Visible Result', '', None, 'Create Groups', self.create_groups_by_visible_result), ('create_groups_by_property_id', 'Create Groups By Property ID', '', None, 'Create Groups', self.create_groups_by_property_id), #('create_list', 'Create Lists through Booleans', '', None, 'Create List', self.create_list), ('show_info', 'Show INFO', 'show_info.png', None, 'Show "INFO" messages', self.on_show_info), ('show_debug', 'Show DEBUG', 'show_debug.png', None, 'Show "DEBUG" messages', self.on_show_debug), ('show_gui', 'Show GUI', 'show_gui.png', None, 'Show "GUI" messages', self.on_show_gui), ('show_command', 'Show COMMAND', 'show_command.png', None, 'Show "COMMAND" messages', self.on_show_command), ('magnify', 'Magnify', 'plus_zoom.png', 'M', 'Increase Magnfication', self.on_increase_magnification), ('shrink', 'Shrink', 'minus_zoom.png', 'm', 'Decrease Magnfication', self.on_decrease_magnification), #('cell_pick', 'Cell Pick', '', 'c', 'Centroidal Picking', self.on_cell_picker), #('node_pick', 'Node Pick', '', 'n', 'Nodal Picking', self.on_node_picker), ('rotate_clockwise', 'Rotate Clockwise', 'tclock.png', 'o', 'Rotate Clockwise', self.on_rotate_clockwise), ('rotate_cclockwise', 'Rotate Counter-Clockwise', 'tcclock.png', 'O', 'Rotate Counter-Clockwise', self.on_rotate_cclockwise), ('screenshot', 'Take a Screenshot...', 'tcamera.png', 'CTRL+I', 'Take a Screenshot of current view', self.on_take_screenshot), ('about', 'About pyNastran GUI...', 'tabout.png', 'CTRL+H', 'About pyNastran GUI and help on shortcuts', self.about_dialog), ('view', 'Camera View', 'view.png', None, 'Load the camera menu', self.view_camera), ('camera_reset', 'Reset Camera View', 'trefresh.png', 'r', 'Reset the camera view to default', self.on_reset_camera), ('wing_menu', 'Load the Wing...', 'wing.png', None, 'Load the Wing Menu', self.on_wing_window), #('reload', 'Reload Model...', 'treload.png', 'r', 'Remove the model and reload the same geometry file', self.on_reload), #('cycle_results', 'Cycle Results', 'cycle_results.png', 'CTRL+L', 'Changes the result case', self.on_cycle_results), #('rcycle_results', 'Cycle Results', 'rcycle_results.png', 'CTRL+K', 'Changes the result case', self.on_rcycle_results), ('back_view', 'Back View', 'back.png', 'x', 'Flips to +X Axis', lambda: self.update_camera('+x')), ('right_view', 'Right View', 'right.png', 'y', 'Flips to +Y Axis', lambda: self.update_camera('+y')), ('top_view', 'Top View', 'top.png', 'z', 'Flips to +Z Axis', lambda: self.update_camera('+z')), ('front_view', 'Front View', 'front.png', 'X', 'Flips to -X Axis', lambda: self.update_camera('-x')), ('left_view', 'Left View', 'left.png', 'Y', 'Flips to -Y Axis', lambda: self.update_camera('-y')), ('bottom_view', 'Bottom View', 'bottom.png', 'Z', 'Flips to -Z Axis', lambda: self.update_camera('-z')), ('edges', 'Show/Hide Edges', 'tedges.png', 'e', 'Show/Hide Model Edges', self.on_flip_edges), ('edges_black', 'Color Edges', '', 'b', 'Set Edge Color to Color/Black', self.on_set_edge_visibility), ('anti_alias_0', 'Off', '', None, 'Disable Anti-Aliasing', lambda: self.on_set_anti_aliasing(0)), ('anti_alias_1', '1x', '', None, 'Set Anti-Aliasing to 1x', lambda: self.on_set_anti_aliasing(1)), ('anti_alias_2', '2x', '', None, 'Set Anti-Aliasing to 2x', lambda: self.on_set_anti_aliasing(2)), ('anti_alias_4', '4x', '', None, 'Set Anti-Aliasing to 4x', lambda: self.on_set_anti_aliasing(4)), ('anti_alias_8', '8x', '', None, 'Set Anti-Aliasing to 8x', lambda: self.on_set_anti_aliasing(8)), # new ('rotation_center', 'Set the rotation center', 'trotation_center.png', 'f', 'Pick a node for the rotation center', self.on_rotation_center), ('measure_distance', 'Measure Distance', 'measure_distance.png', None, 'Measure the distance between two nodes', self.on_measure_distance), ('probe_result', 'Probe', 'tprobe.png', None, 'Probe the displayed result', self.on_probe_result), ('quick_probe_result', 'Quick Probe', '', 'p', 'Probe the displayed result', self.on_quick_probe_result), ('zoom', 'Zoom', 'zoom.png', None, 'Zoom In', self.on_zoom), ('text_size_increase', 'Increase Text Size', 'text_up.png', 'Ctrl+Plus', 'Increase Text Size', self.on_increase_text_size), ('text_size_decrease', 'Decrease Text Size', 'text_down.png', 'Ctrl+Minus', 'Decrease Text Size', self.on_decrease_text_size), ('set_preferences', 'Preferences...', 'preferences.png', None, 'Set Text Size', self.set_preferences_menu), # picking ('area_pick', 'Area Pick', 'tarea_pick.png', None, 'Get a list of nodes/elements', self.on_area_pick), ] if 'nastran' in self.fmts: tools += [ ('caero', 'Show/Hide CAERO Panels', '', None, 'Show/Hide CAERO Panel Outlines', self.toggle_caero_panels), ('caero_subpanels', 'Toggle CAERO Subpanels', '', None, 'Show/Hide CAERO Subanel Outlines', self.toggle_caero_sub_panels), ('conm2', 'Toggle CONM2s', '', None, 'Show/Hide CONM2s', self.toggle_conms), ] self.tools = tools self.checkables = checkables def on_increase_text_size(self): """used by the hidden_tools for Ctrl +""" self.on_set_font_size(self.font_size + 1) def on_decrease_text_size(self): """used by the hidden_tools for Ctrl -""" self.on_set_font_size(self.font_size - 1) def on_set_font_size(self, font_size, show_command=True): """changes the font size""" is_failed = True if not isinstance(font_size, int): self.log_error('font_size=%r must be an integer; type=%s' % ( font_size, type(font_size))) return is_failed if font_size < 6: font_size = 6 if self.font_size == font_size: return False self.font_size = font_size font = QtGui.QFont() font.setPointSize(self.font_size) self.setFont(font) #self.toolbar.setFont(font) self.menu_file.setFont(font) self.menu_view.setFont(font) self.menu_window.setFont(font) self.menu_help.setFont(font) if self._legend_window_shown: self._legend_window.set_font_size(font_size) if self._clipping_window_shown: self._clipping_window.set_font_size(font_size) if self._edit_geometry_properties_window_shown: self._edit_geometry_properties.set_font_size(font_size) if self._modify_groups_window_shown: self._modify_groups_window.set_font_size(font_size) if self._preferences_window_shown: self._preferences_window.set_font_size(font_size) #self.menu_scripts.setFont(font) self.log_command('settings.on_set_font_size(%s)' % font_size) return False def _create_menu_items(self, actions=None, create_menu_bar=True): if actions is None: actions = self.actions if create_menu_bar: self.menu_file = self.menubar.addMenu('&File') self.menu_view = self.menubar.addMenu('&View') self.menu_window = self.menubar.addMenu('&Window') self.menu_help = self.menubar.addMenu('&Help') self.menu_hidden = self.menubar.addMenu('&Hidden') self.menu_hidden.menuAction().setVisible(False) if self._script_path is not None and os.path.exists(self._script_path): scripts = [script for script in os.listdir(self._script_path) if '.py' in script] else: scripts = [] scripts = tuple(scripts) #if 0: #print('script_path =', script_path) #print('scripts =', scripts) #self.menu_scripts = self.menubar.addMenu('&Scripts') #for script in scripts: #fname = os.path.join(script_path, script) #tool = (script, script, 'python48.png', None, '', #lambda: self.on_run_script(fname) ) #tools.append(tool) #else: self.menu_scripts = None menu_window = ['toolbar', 'reswidget'] menu_view = [ 'screenshot', '', 'wireframe', 'surface', 'camera_reset', '', 'set_preferences', '', 'log_clear', 'label_clear', 'label_reset', '', 'legend', 'geo_properties', #['Anti-Aliasing', 'anti_alias_0', 'anti_alias_1', 'anti_alias_2', #'anti_alias_4', 'anti_alias_8',], ] if self.is_groups: menu_view += ['modify_groups', 'create_groups_by_property_id', 'create_groups_by_visible_result'] menu_view += [ '', 'clipping', #'axis', 'edges', 'edges_black',] if self.html_logging: self.actions['log_dock_widget'] = self.log_dock_widget.toggleViewAction() self.actions['log_dock_widget'].setStatusTip("Show/Hide application log") menu_view += ['', 'show_info', 'show_debug', 'show_gui', 'show_command'] menu_window += ['log_dock_widget'] if self.execute_python: self.actions['python_dock_widget'] = self.python_dock_widget.toggleViewAction() self.actions['python_dock_widget'].setStatusTip("Show/Hide Python Console") menu_window += ['python_dock_widget'] menu_file = [ 'load_geometry', '', #'load_results', '', #'load_custom_result', '', 'load_csv_user_points', 'load_csv_user_geom', 'script', '', 'exit'] toolbar_tools = [ 'wing_menu', #'reload', #'load_geometry', 'load_results', 'front_view', 'back_view', 'top_view', 'bottom_view', 'left_view', 'right_view', 'magnify', 'shrink', 'zoom', 'rotate_clockwise', 'rotate_cclockwise', 'rotation_center', 'measure_distance', 'probe_result', 'area_pick', 'wireframe', 'surface', 'edges' ] toolbar_tools += ['camera_reset', 'view', 'screenshot', '', 'exit'] hidden_tools = (#'cycle_results', 'rcycle_results', 'text_size_increase', 'text_size_decrease') menu_items = [] if create_menu_bar: menu_items = [ (self.menu_file, menu_file), (self.menu_view, menu_view), (self.menu_window, menu_window), (self.menu_help, ('about',)), (self.menu_scripts, scripts), (self.toolbar, toolbar_tools), (self.menu_hidden, hidden_tools), # (self.menu_scripts, ()), #(self._dummy_toolbar, ('cell_pick', 'node_pick')) ] return menu_items def _hide_menubar(self): self.toolbar.setVisible(False) #self.menuBar.setVisible(False) def _build_menubar(self): ## toolbar self.toolbar = self.addToolBar('Show toolbar') self.toolbar.setObjectName('main_toolbar') # the dummy toolbar stores actions but doesn't get shown # in other words, it can set shortcuts #self._dummy_toolbar = self.addToolBar('Dummy toolbar') #self._dummy_toolbar.setObjectName('dummy_toolbar') self.menubar = self.menuBar() actions = self._prepare_actions(self._icon_path, self.tools, self.checkables) menu_items = self._create_menu_items(actions) self._populate_menu(menu_items) def _populate_menu(self, menu_items): """populate menus and toolbar""" for menu, items in menu_items: if menu is None: continue for i in items: if not i: menu.addSeparator() else: if isinstance(i, list): sub_menu_name = i[0] sub_menu = menu.addMenu(sub_menu_name) for ii_count, ii in enumerate(i[1:]): if not isinstance(ii, string_types): raise RuntimeError('what is this...action ii() = %r' % ii()) action = self.actions[ii] if ii_count > 0: action.setChecked(False) sub_menu.addAction(action) continue elif not isinstance(i, string_types): raise RuntimeError('what is this...action i() = %r' % i()) try: action = self.actions[i] #if isinstance(i, string_types) else i() except: print(self.actions.keys()) raise menu.addAction(action) #self._create_plane_from_points(None) def _update_menu(self, menu_items): for menu, items in menu_items: menu.clear() self._populate_menu(menu_items) #def _create_plane_from_points(self, points): #origin, vx, vy, vz, x_limits, y_limits = self._fit_plane(points) ## We create a 100 by 100 point plane to sample #splane = vtk.vtkPlaneSource() #plane = splane.GetOutput() #dx = max(x_limits) - min(x_limits) #dy = max(y_limits) - min(y_limits) ##dx = 1. ##dy = 3. ## we need to offset the origin of the plane because the "origin" ## is at the lower left corner of the plane and not the centroid #offset = (dx * vx + dy * vy) / 2. #origin -= offset #splane.SetCenter(origin) #splane.SetNormal(vz) ## Point 1 defines the x-axis and the x-size ## Point 2 defines the y-axis and the y-size #splane.SetPoint1(origin + dx * vx) #splane.SetPoint2(origin + dy * vy) #actor = vtk.vtkLODActor() #mapper = vtk.vtkPolyDataMapper() ##mapper.InterpolateScalarsBeforeMappingOn() ##mapper.UseLookupTableScalarRangeOn() #if self.vtk_version <= 5: #mapper.SetInputData(plane) #else: #mapper.SetInput(plane) #actor.GetProperty().SetColor(1., 0., 0.) #actor.SetMapper(mapper) #self.rend.AddActor(actor) #splane.Update() #def _fit_plane(self, points): #origin = np.array([34.60272856552356, 16.92028913186242, 37.805958003209184]) #vx = np.array([1., 0., 0.]) #vy = np.array([0., 1., 0.]) #vz = np.array([0., 0., 1.]) #x_limits = [-1., 2.] #y_limits = [0., 1.] #return origin, vx, vy, vz, x_limits, y_limits def _prepare_actions(self, icon_path, tools, checkables=None): """ Prepare actions that will be used in application in a way that's independent of the menus & toolbar """ if checkables is None: checkables = [] #print('---------------------------') for tool in tools: (name, txt, icon, shortcut, tip, func) = tool if name in self.actions: self.log_error('trying to create a duplicate action %r' % name) continue #print("name=%s txt=%s icon=%s shortcut=%s tip=%s func=%s" #% (name, txt, icon, shortcut, tip, func)) #if icon is None: #print("missing_icon = %r!!!" % name) #icon = os.path.join(icon_path, 'no.png') if icon is None: print("missing_icon = %r!!!" % name) ico = None #print(print_bad_path(icon)) #elif not "/" in icon: #ico = QtGui.QIcon.fromTheme(icon) else: ico = QtGui.QIcon() pth = os.path.join(icon_path, icon) ico.addPixmap(QtGui.QPixmap(pth), QtGui.QIcon.Normal, QtGui.QIcon.Off) if name in checkables: is_checked = checkables[name] self.actions[name] = QAction(ico, txt, self, checkable=True) self.actions[name].setChecked(is_checked) else: self.actions[name] = QAction(ico, txt, self) if shortcut: self.actions[name].setShortcut(shortcut) #actions[name].setShortcutContext(QtCore.Qt.WidgetShortcut) if tip: self.actions[name].setStatusTip(tip) if func: self.actions[name].triggered.connect(func) self.actions['toolbar'] = self.toolbar.toggleViewAction() self.actions['toolbar'].setStatusTip("Show/Hide application toolbar") self.actions['reswidget'] = self.res_dock.toggleViewAction() self.actions['reswidget'].setStatusTip("Show/Hide results selection") return self.actions def _logg_msg(self, typ, msg): """ Add message to log widget trying to choose right color for it. Parameters ---------- typ : str {DEBUG, INFO, GUI ERROR, COMMAND, WARNING} msg : str message to be displayed """ if not self.html_logging: print(typ, msg) return if typ == 'DEBUG' and not self.show_debug: return elif typ == 'INFO' and not self.show_info: return elif typ == 'GUI' and not self.show_gui: return elif typ == 'COMMAND' and not self.show_command: return _fr = sys._getframe(4) # jump to get out of the logger code n = _fr.f_lineno filename = os.path.basename(_fr.f_globals['__file__']) #if typ in ['GUI', 'COMMAND']: msg = ' fname=%-25s:%-4s %s\n' % (filename, n, msg) tim = datetime.datetime.now().strftime('[%Y-%m-%d %H:%M:%S]') msg = cgi.escape(msg) #message colors dark_orange = '#EB9100' colors = { "GUI" : "blue", "COMMAND" : "green", "GUI ERROR" : "Crimson", "DEBUG" : dark_orange, 'WARNING' : "purple", # INFO - black } msg = msg.rstrip().replace('\n', '<br>') msg = tim + ' ' + (typ + ': ' + msg) if typ else msg if typ in colors: msg = '<font color="%s"> %s </font>' % (colors[typ], msg) self.log_mutex.lockForWrite() text_cursor = self.log_widget.textCursor() end = text_cursor.End #print("end", end) text_cursor.movePosition(end) #print(dir(text_cursor)) text_cursor.insertHtml(msg + r"<br />") self.log_widget.ensureCursorVisible() # new message will be visible self.log_mutex.unlock() def log_info(self, msg): """ Helper funtion: log a message msg with a 'INFO:' prefix """ if msg is None: msg = 'msg is None; must be a string' return self.log.simple_msg(msg, 'ERROR') self.log.simple_msg(msg, 'INFO') def log_debug(self, msg): """ Helper funtion: log a message msg with a 'DEBUG:' prefix """ if msg is None: msg = 'msg is None; must be a string' return self.log.simple_msg(msg, 'ERROR') self.log.simple_msg(msg, 'DEBUG') def log_command(self, msg): """ Helper funtion: log a message msg with a 'COMMAND:' prefix """ if msg is None: msg = 'msg is None; must be a string' return self.log.simple_msg(msg, 'ERROR') self.log.simple_msg(msg, 'COMMAND') def log_error(self, msg): """ Helper funtion: log a message msg with a 'GUI ERROR:' prefix """ if msg is None: msg = 'msg is None; must be a string' return self.log.simple_msg(msg, 'ERROR') self.log.simple_msg(msg, 'GUI ERROR') def log_warning(self, msg): """ Helper funtion: log a message msg with a 'WARNING:' prefix """ if msg is None: msg = 'msg is None; must be a string' return self.log.simple_msg(msg, 'ERROR') self.log.simple_msg(msg, 'WARNING') def create_coordinate_system(self, dim_max, label='', origin=None, matrix_3x3=None, Type='xyz'): """ Creates a coordinate system Parameters ---------- dim_max : float the max model dimension; 10% of the max will be used for the coord length label : str the coord id or other unique label (default is empty to indicate the global frame) origin : (3, ) ndarray/list/tuple the origin matrix_3x3 : (3, 3) ndarray a standard Nastran-style coordinate system Type : str a string of 'xyz', 'Rtz', 'Rtp' (xyz, cylindrical, spherical) that changes the axis names .. todo:: Type is not supported ('xyz' ONLY) .. todo:: Can only set one coordinate system .. seealso:: http://en.wikipedia.org/wiki/Homogeneous_coordinates http://www3.cs.stonybrook.edu/~qin/courses/graphics/camera-coordinate-system.pdf http://www.vtk.org/doc/nightly/html/classvtkTransform.html#ad58b847446d791391e32441b98eff151 """ coord_id = self.coord_id self.settings.dim_max = dim_max scale = 0.05 * dim_max transform = vtk.vtkTransform() if origin is None and matrix_3x3 is None: pass elif origin is not None and matrix_3x3 is None: #print('origin%s = %s' % (label, str(origin))) transform.Translate(*origin) elif matrix_3x3 is not None: # origin can be None m = np.eye(4, dtype='float32') m[:3, :3] = matrix_3x3 if origin is not None: m[:3, 3] = origin transform.SetMatrix(m.ravel()) else: raise RuntimeError('unexpected coordinate system') axes = vtk.vtkAxesActor() axes.DragableOff() axes.PickableOff() #axes.GetLength() # pi #axes.GetNormalizedShaftLength() # (0.8, 0.8, 0.8) #axes.GetNormalizedTipLength() # (0.2, 0.2, 0.2) #axes.GetOrigin() # (0., 0., 0.) #axes.GetScale() # (1., 1., 1.) #axes.GetShaftType() # 1 #axes.GetTotalLength() # (1., 1., 1.) axes.SetUserTransform(transform) axes.SetTotalLength(scale, scale, scale) if Type == 'xyz': if label: xlabel = u'x%s' % label ylabel = u'y%s' % label zlabel = u'z%s' % label axes.SetXAxisLabelText(xlabel) axes.SetYAxisLabelText(ylabel) axes.SetZAxisLabelText(zlabel) else: if Type == 'Rtz': # cylindrical #x = u'R' #y = u'θ' #z = u'z' x = 'R' y = 't' z = 'z' elif Type == 'Rtp': # spherical xlabel = u'R' #ylabel = u'θ' #z = u'Φ' x = 'R' y = 't' z = 'p' else: raise RuntimeError('invalid axis type; Type=%r' % Type) xlabel = '%s%s' % (x, label) ylabel = '%s%s' % (y, label) zlabel = '%s%s' % (z, label) axes.SetXAxisLabelText(xlabel) axes.SetYAxisLabelText(ylabel) axes.SetZAxisLabelText(zlabel) self.transform[coord_id] = transform self.axes[coord_id] = axes is_visible = False if label == '': label = 'Global XYZ' is_visible = True else: label = 'Coord %s' % label self.geometry_properties[label] = CoordProperties(label, Type, is_visible, scale) self.geometry_actors[label] = axes self.coord_id += 1 self.rend.AddActor(axes) return self.coord_id def create_global_axes(self, dim_max): self.create_coordinate_system( dim_max, label='', origin=None, matrix_3x3=None, Type='xyz') def create_corner_axis(self): """creates the axes that sits in the corner""" if not self.run_vtk: return axes = vtk.vtkAxesActor() self.corner_axis = vtk.vtkOrientationMarkerWidget() self.corner_axis.SetOrientationMarker(axes) self.corner_axis.SetInteractor(self.vtk_interactor) self.corner_axis.SetEnabled(1) self.corner_axis.InteractiveOff() #def on_show_hide_axes(self): #""" #show/hide axes #""" #if not self.run_vtk: #return ## this method should handle all the coords when ## there are more then one #if self._is_axes_shown: #for axis in itervalues(self.axes): #axis.VisibilityOff() #else: #for axis in itervalues(self.axes): #axis.VisibilityOn() #self._is_axes_shown = not self._is_axes_shown def create_vtk_actors(self): self.rend = vtk.vtkRenderer() # vtk actors self.grid = vtk.vtkUnstructuredGrid() #self.emptyResult = vtk.vtkFloatArray() #self.vectorResult = vtk.vtkFloatArray() # edges self.edge_actor = vtk.vtkLODActor() self.edge_actor.DragableOff() self.edge_mapper = vtk.vtkPolyDataMapper() self.create_cell_picker() def create_alternate_vtk_grid(self, name, color=None, line_width=5, opacity=1.0, point_size=1, bar_scale=0.0, representation=None, is_visible=True, follower_nodes=None, is_pickable=False): """ Creates an AltGeometry object Parameters ---------- line_width : int the width of the line for 'surface' and 'main' color : [int, int, int] the RGB colors opacity : float 0.0 -> solid 1.0 -> transparent point_size : int the point size for 'point' bar_scale : float the scale for the CBAR / CBEAM elements representation : str main - change with main mesh wire - always wireframe point - always points surface - always surface bar - can use bar scale is_visible : bool; default=True is this actor currently visable is_pickable : bool; default=False can you pick a node/cell on this actor follower_nodes : List[int] the nodes that are brought along with a deflection """ self.alt_grids[name] = vtk.vtkUnstructuredGrid() self.geometry_properties[name] = AltGeometry( self, name, color=color, line_width=line_width, opacity=opacity, point_size=point_size, bar_scale=bar_scale, representation=representation, is_visible=is_visible, is_pickable=is_pickable) if follower_nodes is not None: self.follower_nodes[name] = follower_nodes def duplicate_alternate_vtk_grid(self, name, name_duplicate_from, color=None, line_width=5, opacity=1.0, point_size=1, bar_scale=0.0, is_visible=True, follower_nodes=None, is_pickable=False): """ Copies the VTK actor Parameters ---------- line_width : int the width of the line for 'surface' and 'main' color : [int, int, int] the RGB colors opacity : float 0.0 -> solid 1.0 -> transparent point_size : int the point size for 'point' bar_scale : float the scale for the CBAR / CBEAM elements is_visible : bool; default=True is this actor currently visable is_pickable : bool; default=False can you pick a node/cell on this actor follower_nodes : List[int] the nodes that are brought along with a deflection """ self.alt_grids[name] = vtk.vtkUnstructuredGrid() if name_duplicate_from == 'main': grid_copy_from = self.grid representation = 'toggle' else: grid_copy_from = self.alt_grids[name_duplicate_from] props = self.geometry_properties[name_duplicate_from] representation = props.representation self.alt_grids[name].DeepCopy(grid_copy_from) #representation : str #main - change with main mesh #wire - always wireframe #point - always points #surface - always surface #bar - can use bar scale self.geometry_properties[name] = AltGeometry( self, name, color=color, line_width=line_width, opacity=opacity, point_size=point_size, bar_scale=bar_scale, representation=representation, is_visible=is_visible, is_pickable=is_pickable) if follower_nodes is not None: self.follower_nodes[name] = follower_nodes def _create_vtk_objects(self): """creates some of the vtk objects""" #Frame that VTK will render on self.vtk_frame = QFrame() #Qt VTK QVTKRenderWindowInteractor self.vtk_interactor = QVTKRenderWindowInteractor(parent=self.vtk_frame) #self.vtk_interactor = PyNastranRenderWindowInteractor(parent=self.vtk_frame) self.iren = self.vtk_interactor #self.set_anti_aliasing(2) #self._camera_event_name = 'LeftButtonPressEvent' self._camera_mode = 'default' self.setup_mouse_buttons(mode='default') def setup_mouse_buttons(self, mode=None, revert=False, left_button_down=None, left_button_up=None, right_button_down=None, end_pick=None, style=None, force=False): """ Remaps the mouse buttons temporarily Parameters ---------- mode : str lets you know what kind of mapping this is revert : bool; default=False does the button revert when it's finished left_button_down : function (default=None) the callback function (None -> depends on the mode) left_button_up : function (default=None) the callback function (None -> depends on the mode) right_button_down : function (default=None) the callback function (None -> depends on the mode) style : vtkInteractorStyle (default=None) a custom vtkInteractorStyle None -> keep the same style, but overwrite the left mouse button force : bool; default=False override the mode=camera_mode check """ assert isinstance(mode, string_types), mode assert revert in [True, False], revert #print('setup_mouse_buttons mode=%r _camera_mode=%r' % (mode, self._camera_mode)) if mode == self._camera_mode and not force: #print('auto return from set mouse mode') return self._camera_mode = mode if mode is None: # same as default #print('auto return 2 from set mouse mode') return elif mode == 'default': #print('set mouse mode as default') # standard rotation # Disable default left mouse click function (Rotate) self.vtk_interactor.RemoveObservers('LeftButtonPressEvent') self.vtk_interactor.RemoveObservers('EndPickEvent') self.vtk_interactor.AddObserver('EndPickEvent', self._probe_picker) # there should be a cleaner way to revert the trackball Rotate command # it apparently requires an (obj, event) argument instead of a void... self.set_style_as_trackball() # the more correct-ish way to reset the 'LeftButtonPressEvent' to Rotate # that doesn't work... # # Re-assign left mouse click event to custom function (Point Picker) #self.vtk_interactor.AddObserver('LeftButtonPressEvent', self.style.Rotate) elif mode == 'measure_distance': # 'rotation_center', # hackish b/c the default setting is so bad self.vtk_interactor.RemoveObservers('LeftButtonPressEvent') self.vtk_interactor.AddObserver('LeftButtonPressEvent', left_button_down) self.vtk_interactor.RemoveObservers('EndPickEvent') self.vtk_interactor.AddObserver('EndPickEvent', left_button_down) elif mode == 'probe_result': # hackish b/c the default setting is so bad self.vtk_interactor.RemoveObservers('LeftButtonPressEvent') self.vtk_interactor.AddObserver('LeftButtonPressEvent', left_button_down) self.vtk_interactor.RemoveObservers('EndPickEvent') self.vtk_interactor.AddObserver('EndPickEvent', left_button_down) #self.vtk_interactor.AddObserver('LeftButtonPressEvent', func, 1) # on press down #self.vtk_interactor.AddObserver('LeftButtonPressEvent', func, -1) # on button up elif mode == 'zoom': assert style is not None, style self.vtk_interactor.SetInteractorStyle(style) # on press down self.vtk_interactor.AddObserver('LeftButtonPressEvent', left_button_down) # on button up self.vtk_interactor.AddObserver('LeftButtonReleaseEvent', left_button_up, -1) if right_button_down: self.vtk_interactor.AddObserver('RightButtonPressEvent', right_button_down) #elif mode == 'node_pick': #self.vtk_interactor.RemoveObservers('LeftButtonPressEvent') #self.vtk_interactor.AddObserver('LeftButtonPressEvent', self.on_node_pick_event) #elif mode == 'cell_pick': #self.vtk_interactor.RemoveObservers('LeftButtonPressEvent') #self.vtk_interactor.AddObserver('LeftButtonPressEvent', self.on_cell_pick_event) elif mode == 'cell_pick': #aaa #print('set mouse mode as cell_pick') self.vtk_interactor.SetPicker(self.cell_picker) elif mode == 'node_pick': #bbb #print('set mouse mode as node_pick') self.vtk_interactor.SetPicker(self.node_picker) elif mode == 'style': self.vtk_interactor.RemoveObservers('LeftButtonPressEvent') self.vtk_interactor.RemoveObservers('RightButtonPressEvent') self.vtk_interactor.SetInteractorStyle(style) #elif mode == 'area_cell_pick': #self.vtk_interactor.RemoveObservers('LeftButtonPressEvent') #self.vtk_interactor.AddObserver('LeftButtonPressEvent', #self.on_area_cell_pick_event) #elif mode == 'area_node_pick': #self.vtk_interactor.RemoveObservers('LeftButtonPressEvent') #self.vtk_interactor.AddObserver('LeftButtonPressEvent', #self.on_area_cell_pick_event) #elif mode == 'polygon_cell_pick': #self.vtk_interactor.RemoveObservers('LeftButtonPressEvent') #self.vtk_interactor.AddObserver('LeftButtonPressEvent', #self.on_polygon_cell_pick_event) #elif mode == 'polygon_node_pick': #self.vtk_interactor.RemoveObservers('LeftButtonPressEvent') #self.vtk_interactor.AddObserver('LeftButtonPressEvent', #self.on_polygon_cell_pick_event) #elif mode == 'pan': #pass else: raise NotImplementedError('camera_mode = %r' % self._camera_mode) self.revert = revert def on_measure_distance(self): self.revert_pressed('measure_distance') measure_distance_button = self.actions['measure_distance'] is_checked = measure_distance_button.isChecked() if not is_checked: # revert on_measure_distance self._measure_distance_pick_points = [] self.setup_mouse_buttons(mode='default') return self._measure_distance_pick_points = [] self.setup_mouse_buttons('measure_distance', left_button_down=self._measure_distance_picker) def _measure_distance_picker(self, obj, event): picker = self.cell_picker pixel_x, pixel_y = self.vtk_interactor.GetEventPosition() picker.Pick(pixel_x, pixel_y, 0, self.rend) cell_id = picker.GetCellId() #print('_measure_distance_picker', cell_id) if cell_id < 0: #self.picker_textActor.VisibilityOff() pass else: world_position = picker.GetPickPosition() closest_point = self._get_closest_node_xyz(cell_id, world_position) if len(self._measure_distance_pick_points) == 0: self._measure_distance_pick_points.append(closest_point) self.log_info('point1 = %s' % str(closest_point)) else: self.log_info('point2 = %s' % str(closest_point)) p1 = self._measure_distance_pick_points[0] dxyz = closest_point - p1 mag = np.linalg.norm(dxyz) self._measure_distance_pick_points = [] self.log_info('dxyz=%s mag=%s' % (str(dxyz), str(mag))) measure_distance_button = self.actions['measure_distance'] measure_distance_button.setChecked(False) self.setup_mouse_buttons(mode='default') def on_escape_null(self): """ The default state for Escape key is nothing. """ pass def on_escape(self): """ Escape key should cancel: - on_rotation_center TODO: not done... """ pass def on_rotation_center(self): """ http://osdir.com/ml/lib.vtk.user/2002-09/msg00079.html """ self.revert_pressed('rotation_center') is_checked = self.actions['rotation_center'].isChecked() if not is_checked: # revert on_rotation_center self.setup_mouse_buttons(mode='default') return style = RotationCenterStyle(parent=self) self.setup_mouse_buttons('style', revert=True, style=style) def set_focal_point(self, focal_point): """ Parameters ---------- focal_point : (3, ) float ndarray The focal point [ 188.25109863 -7. -32.07858658] """ camera = self.rend.GetActiveCamera() self.log_command("set_focal_point(focal_point=%s)" % str(focal_point)) # now we can actually modify the camera camera.SetFocalPoint(focal_point[0], focal_point[1], focal_point[2]) camera.OrthogonalizeViewUp() self.vtk_interactor.Render() def revert_pressed(self, active_name): if active_name != 'probe_result': probe_button = self.actions['probe_result'] is_checked = probe_button.isChecked() if is_checked: # revert probe_result probe_button.setChecked(False) self.setup_mouse_buttons(mode='default') return if active_name != 'rotation_center': rotation_button = self.actions['rotation_center'] is_checked = rotation_button.isChecked() if is_checked: # revert rotation_center rotation_button.setChecked(False) self.setup_mouse_buttons(mode='default') return if active_name != 'measure_distance': measure_distance_button = self.actions['measure_distance'] is_checked = measure_distance_button.isChecked() if is_checked: # revert on_measure_distance measure_distance_button.setChecked(False) self._measure_distance_pick_points = [] self.setup_mouse_buttons(mode='default') return if active_name != 'zoom': zoom_button = self.actions['zoom'] is_checked = zoom_button.isChecked() if is_checked: # revert on_measure_distance zoom_button.setChecked(False) self._zoom = [] self.setup_mouse_buttons(mode='default') return def on_probe_result(self): self.revert_pressed('probe_result') is_checked = self.actions['probe_result'].isChecked() if not is_checked: # revert probe_result self.setup_mouse_buttons(mode='default') return self.setup_mouse_buttons('probe_result', left_button_down=self._probe_picker) #style = ProbeResultStyle(parent=self) #self.vtk_interactor.SetInteractorStyle(style) def on_quick_probe_result(self): self.revert_pressed('probe_result') is_checked = self.actions['probe_result'].isChecked() self.setup_mouse_buttons('probe_result', left_button_down=self._probe_picker, revert=True) def on_area_pick_callback(self, eids, nids): """prints the message when area_pick succeeds""" msg = '' if eids is not None and len(eids): msg += write_patran_syntax_dict({'Elem' : eids}) if nids is not None and len(nids): msg += '\n' + write_patran_syntax_dict({'Node' : nids}) if msg: self.log_info('\n%s' % msg.lstrip()) def on_area_pick(self, is_eids=True, is_nids=True, callback=None, force=False): """creates a Rubber Band Zoom""" self.revert_pressed('area_pick') is_checked = self.actions['area_pick'].isChecked() if not is_checked: # revert area_pick self.setup_mouse_buttons(mode='default') if not force: return self.log_info('on_area_pick') self._picker_points = [] if callback is None: callback = self.on_area_pick_callback style = AreaPickStyle(parent=self, is_eids=is_eids, is_nids=is_nids, callback=callback) self.setup_mouse_buttons(mode='style', revert=True, style=style) #, style_name='area_pick' def on_area_pick_not_square(self): self.revert_pressed('area_pick') is_checked = self.actions['area_pick'].isChecked() if not is_checked: # revert area_pick self.setup_mouse_buttons(mode='default') return self.log_info('on_area_pick') self.vtk_interactor.SetPicker(self.area_picker) def _area_picker_up(*args): pass style = vtk.vtkInteractorStyleDrawPolygon() self.setup_mouse_buttons('area_pick', #left_button_down=self._area_picker, left_button_up=_area_picker_up, #end_pick=self._area_picker_up, style=style) #self.area_picker = vtk.vtkAreaPicker() # vtkRenderedAreaPicker? #self.rubber_band_style = vtk.vtkInteractorStyleRubberBandPick() #vtk.vtkInteractorStyleRubberBand2D #vtk.vtkInteractorStyleRubberBand3D #vtk.vtkInteractorStyleRubberBandZoom #vtk.vtkInteractorStyleAreaSelectHover #vtk.vtkInteractorStyleDrawPolygon def on_zoom(self): """creates a Rubber Band Zoom""" #self.revert_pressed('zoom') is_checked = self.actions['zoom'].isChecked() if not is_checked: # revert zoom self.setup_mouse_buttons(mode='default') return style = ZoomStyle(parent=self) self.setup_mouse_buttons(mode='style', revert=True, style=style) #self.vtk_interactor.SetInteractorStyle(style) def _probe_picker(self, obj, event): """pick a point and apply the label based on the current displayed result""" picker = self.cell_picker pixel_x, pixel_y = self.vtk_interactor.GetEventPosition() picker.Pick(pixel_x, pixel_y, 0, self.rend) cell_id = picker.GetCellId() #print('_probe_picker', cell_id) if cell_id < 0: pass else: world_position = picker.GetPickPosition() if 0: camera = self.rend.GetActiveCamera() #focal_point = world_position out = self.get_result_by_xyz_cell_id(world_position, cell_id) _result_name, result_value, node_id, node_xyz = out focal_point = node_xyz self.log_info('focal_point = %s' % str(focal_point)) self.setup_mouse_buttons(mode='default') # now we can actually modify the camera camera.SetFocalPoint(focal_point[0], focal_point[1], focal_point[2]) camera.OrthogonalizeViewUp() probe_result_button = self.actions['probe_result'] probe_result_button.setChecked(False) world_position = picker.GetPickPosition() cell_id = picker.GetCellId() #ds = picker.GetDataSet() #select_point = picker.GetSelectionPoint() self.log_command("annotate_cell_picker()") self.log_info("XYZ Global = %s" % str(world_position)) #self.log_info("cell_id = %s" % cell_id) #self.log_info("data_set = %s" % ds) #self.log_info("selPt = %s" % str(select_point)) #method = 'get_result_by_cell_id()' # self.model_type #print('pick_state =', self.pick_state) icase = self.icase key = self.case_keys[icase] location = self.get_case_location(key) if location == 'centroid': out = self._cell_centroid_pick(cell_id, world_position) elif location == 'node': out = self._cell_node_pick(cell_id, world_position) else: raise RuntimeError('invalid pick location=%r' % location) return_flag, duplicate_key, result_value, result_name, xyz = out if return_flag is True: return # prevent duplicate labels with the same value on the same cell if duplicate_key is not None and duplicate_key in self.label_ids[icase]: return self.label_ids[icase].add(duplicate_key) #if 0: #result_value2, xyz2 = self.convert_units(case_key, result_value, xyz) #result_value = result_value2 #xyz2 = xyz #x, y, z = world_position x, y, z = xyz text = '(%.3g, %.3g, %.3g); %s' % (x, y, z, result_value) text = str(result_value) assert icase in self.label_actors, icase self._create_annotation(text, self.label_actors[icase], x, y, z) self.vtk_interactor.Render() if self.revert: self.setup_mouse_buttons(mode='default') #def remove_picker(self): #self.vtk_interactor. def set_node_picker(self): self.vtk_interactor.SetPicker(self.node_picker) def set_cell_picker(self): self.vtk_interactor.SetPicker(self.cell_picker) @property def render_window(self): return self.vtk_interactor.GetRenderWindow() def set_background_image(self, image_filename='GeologicalExfoliationOfGraniteRock.jpg'): """adds a background image""" if not os.path.exists(image_filename): return fmt = os.path.splitext(image_filename)[1].lower() if fmt not in ['.jpg', '.jpeg', '.png', '.tif', '.tiff', '.bmp']: msg = 'invalid image type=%r; filename=%r' % (fmt, image_filename) raise NotImplementedError(msg) #image_reader = vtk.vtkJPEGReader() #image_reader = vtk.vtkPNGReader() #image_reader = vtk.vtkTIFFReader() #image_reader = vtk.vtkBMPReader() #image_reader = vtk.vtkPostScriptReader() # doesn't exist? has_background_image = self._active_background_image is not None self._active_background_image = image_filename #if has_background_image: #self.image_reader.Delete() if fmt in ['.jpg', '.jpeg']: self.image_reader = vtk.vtkJPEGReader() elif fmt == '.png': self.image_reader = vtk.vtkPNGReader() elif fmt in ['.tif', '.tiff']: self.image_reader = vtk.vtkTIFFReader() elif fmt == '.bmp': self.image_reader = vtk.vtkBMPReader() #elif fmt == '.ps': # doesn't exist? #self.image_reader = vtk.vtkPostScriptReader() else: msg = 'invalid image type=%r; filename=%r' % (fmt, image_filename) raise NotImplementedError(msg) if not self.image_reader.CanReadFile(image_filename): print("Error reading file %s" % image_filename) return self.image_reader.SetFileName(image_filename) self.image_reader.Update() image_data = self.image_reader.GetOutput() if has_background_image: if vtk.VTK_MAJOR_VERSION <= 5: self.image_actor.SetInput(image_data) else: self.image_actor.SetInputData(image_data) self.Render() return # Create an image actor to display the image self.image_actor = vtk.vtkImageActor() if vtk.VTK_MAJOR_VERSION <= 5: self.image_actor.SetInput(image_data) else: self.image_actor.SetInputData(image_data) self.background_rend = vtk.vtkRenderer() self.background_rend.SetLayer(0) self.background_rend.InteractiveOff() self.background_rend.AddActor(self.image_actor) self.rend.SetLayer(1) render_window = self.vtk_interactor.GetRenderWindow() render_window.SetNumberOfLayers(2) render_window.AddRenderer(self.background_rend) # Set up the background camera to fill the renderer with the image origin = image_data.GetOrigin() spacing = image_data.GetSpacing() extent = image_data.GetExtent() camera = self.background_rend.GetActiveCamera() camera.ParallelProjectionOn() xc = origin[0] + 0.5*(extent[0] + extent[1]) * spacing[0] yc = origin[1] + 0.5*(extent[2] + extent[3]) * spacing[1] # xd = (extent[1] - extent[0] + 1) * spacing[0] yd = (extent[3] - extent[2] + 1) * spacing[1] d = camera.GetDistance() camera.SetParallelScale(0.5 * yd) camera.SetFocalPoint(xc, yc, 0.0) camera.SetPosition(xc, yc, d) def build_vtk_frame(self): vtk_hbox = QHBoxLayout() vtk_hbox.setContentsMargins(2, 2, 2, 2) vtk_hbox.addWidget(self.vtk_interactor) self.vtk_frame.setLayout(vtk_hbox) self.vtk_frame.setFrameStyle(QFrame.NoFrame | QFrame.Plain) # this is our main, 'central' widget self.setCentralWidget(self.vtk_frame) #============================================================= # +-----+-----+ # | | | # | A | B | # | | | # +-----+-----+ # xmin, xmax, ymin, ymax nframes = 1 #nframes = 2 if nframes == 2: # xmin, ymin, xmax, ymax frame1 = [0., 0., 0.5, 1.0] frame2 = [0.5, 0., 1., 1.0] #frames = [frame1, frame2] self.rend.SetViewport(*frame1) self.vtk_interactor.GetRenderWindow().AddRenderer(self.rend) if nframes == 2: rend = vtk.vtkRenderer() rend.SetViewport(*frame2) self.vtk_interactor.GetRenderWindow().AddRenderer(rend) self.set_background_image() self.vtk_interactor.GetRenderWindow().Render() #self.load_nastran_geometry(None, None) #for cid, axes in iteritems(self.axes): #self.rend.AddActor(axes) self.add_geometry() if nframes == 2: rend.AddActor(self.geom_actor) # initialize geometry_actors self.geometry_actors['main'] = self.geom_actor # bar scale set so you can't edit the bar scale white = (255, 255, 255) geom_props = AltGeometry( self, 'main', color=white, line_width=1, opacity=1.0, point_size=1, bar_scale=0.0, representation='main', is_visible=True) self.geometry_properties['main'] = geom_props #self.addAltGeometry() self.rend.GetActiveCamera().ParallelProjectionOn() self.rend.SetBackground(*self.background_color) self.rend.ResetCamera() self.set_style_as_trackball() self.build_lookup_table() text_size = 14 self.create_text([5, 50], 'Max ', text_size) # text actor 0 self.create_text([5, 35], 'Min ', text_size) # text actor 1 self.create_text([5, 20], 'Word1', text_size) # text actor 2 self.create_text([5, 5], 'Word2', text_size) # text actor 3 self.get_edges() if self.is_edges: prop = self.edge_actor.GetProperty() prop.EdgeVisibilityOn() else: prop = self.edge_actor.GetProperty() prop.EdgeVisibilityOff() #def _script_helper(self, python_file=False): #if python_file in [None, False]: #self.on_run_script(python_file) def set_style_as_trackball(self): """sets the default rotation style""" #self._simulate_key_press('t') # change mouse style to trackball self.style = vtk.vtkInteractorStyleTrackballCamera() self.vtk_interactor.SetInteractorStyle(self.style) def on_run_script(self, python_file=False): """pulldown for running a python script""" is_failed = True if python_file in [None, False]: title = 'Choose a Python Script to Run' wildcard = "Python (*.py)" infile_name = self._create_load_file_dialog( wildcard, title, self._default_python_file)[1] if not infile_name: return is_failed # user clicked cancel #python_file = os.path.join(script_path, infile_name) python_file = os.path.join(infile_name) if not os.path.exists(python_file): msg = 'python_file = %r does not exist' % python_file self.log_error(msg) return is_failed lines = open(python_file, 'r').read() try: exec(lines) except Exception as e: #self.log_error(traceback.print_stack(f)) self.log_error('\n' + ''.join(traceback.format_stack())) #traceback.print_exc(file=self.log_error) self.log_error(str(e)) return is_failed is_failed = False self._default_python_file = python_file self.log_command('self.on_run_script(%r)' % python_file) return is_failed def on_show_info(self): """sets a flag for showing/hiding INFO messages""" self.show_info = not self.show_info def on_show_debug(self): """sets a flag for showing/hiding DEBUG messages""" self.show_debug = not self.show_debug def on_show_gui(self): """sets a flag for showing/hiding GUI messages""" self.show_gui = not self.show_gui def on_show_command(self): """sets a flag for showing/hiding COMMAND messages""" self.show_command = not self.show_command def on_reset_camera(self): self.log_command('on_reset_camera()') self._simulate_key_press('r') self.vtk_interactor.Render() def on_surface(self): if self.is_wireframe: self.log_command('on_surface()') for name, actor in iteritems(self.geometry_actors): #if name != 'main': #print('name: %s\nrep: %s' % ( #name, self.geometry_properties[name].representation)) representation = self.geometry_properties[name].representation if name == 'main' or representation in ['main', 'toggle']: prop = actor.GetProperty() prop.SetRepresentationToSurface() self.is_wireframe = False self.vtk_interactor.Render() def on_wireframe(self): if not self.is_wireframe: self.log_command('on_wireframe()') for name, actor in iteritems(self.geometry_actors): #if name != 'main': #print('name: %s\nrep: %s' % ( #name, self.geometry_properties[name].representation)) representation = self.geometry_properties[name].representation if name == 'main' or representation in ['main', 'toggle']: prop = actor.GetProperty() prop.SetRepresentationToWireframe() #prop.SetRepresentationToPoints() #prop.GetPointSize() #prop.SetPointSize(5.0) #prop.ShadingOff() self.vtk_interactor.Render() self.is_wireframe = True def _update_camera(self, camera=None): if camera is None: camera = self.GetCamera() camera.Modified() self.vtk_interactor.Render() def zoom(self, value): camera = self.GetCamera() camera.Zoom(value) camera.Modified() self.vtk_interactor.Render() self.log_command('zoom(%s)' % value) def rotate(self, rotate_deg): camera = self.GetCamera() camera.Roll(-rotate_deg) camera.Modified() self.vtk_interactor.Render() self.log_command('rotate(%s)' % rotate_deg) def on_rotate_clockwise(self): """rotate clockwise""" self.rotate(15.0) def on_rotate_cclockwise(self): """rotate counter clockwise""" self.rotate(-15.0) def on_increase_magnification(self): """zoom in""" self.zoom(1.1) def on_decrease_magnification(self): """zoom out""" self.zoom(1.0 / 1.1) def on_flip_edges(self): """turn edges on/off""" self.is_edges = not self.is_edges self.edge_actor.SetVisibility(self.is_edges) #self.edge_actor.GetProperty().SetColor(0, 0, 0) # cart3d edge color isn't black... self.edge_actor.Modified() #self.widget.Update() #self._update_camera() self.Render() #self.refresh() self.log_command('on_flip_edges()') def on_set_edge_visibility(self): #self.edge_actor.SetVisibility(self.is_edges_black) self.is_edges_black = not self.is_edges_black if self.is_edges_black: prop = self.edge_actor.GetProperty() prop.EdgeVisibilityOn() self.edge_mapper.SetLookupTable(self.color_function_black) else: prop = self.edge_actor.GetProperty() prop.EdgeVisibilityOff() self.edge_mapper.SetLookupTable(self.color_function) self.edge_actor.Modified() prop.Modified() self.vtk_interactor.Render() self.log_command('on_set_edge_visibility()') def get_edges(self): """Create the edge actor""" edges = vtk.vtkExtractEdges() edge_mapper = self.edge_mapper edge_actor = self.edge_actor if self.vtk_version[0] >= 6: edges.SetInputData(self.grid_selected) edge_mapper.SetInputConnection(edges.GetOutputPort()) else: edges.SetInput(self.grid_selected) edge_mapper.SetInput(edges.GetOutput()) edge_actor.SetMapper(edge_mapper) edge_actor.GetProperty().SetColor(0., 0., 0.) edge_mapper.SetLookupTable(self.color_function) edge_mapper.SetResolveCoincidentTopologyToPolygonOffset() prop = edge_actor.GetProperty() prop.SetColor(0., 0., 0.) edge_actor.SetVisibility(self.is_edges) self.rend.AddActor(edge_actor) def post_group_by_name(self, name): """posts a group with a specific name""" group = self.groups[name] self.post_group(group) self.group_active = name def post_group(self, group): """posts a group object""" eids = group.element_ids self.show_eids(eids) def get_all_eids(self): """get the list of all the element IDs""" return self.element_ids #name, result = self.get_name_result_data(0) #if name != 'ElementID': #name, result = self.get_name_result_data(1) #assert name == 'ElementID', name #return result def show_eids(self, eids): """shows the specified element IDs""" all_eids = self.get_all_eids() # remove eids that are out of range eids = np.intersect1d(all_eids, eids) # update for indices ishow = np.searchsorted(all_eids, eids) #eids_off = np.setdiff1d(all_eids, eids) #j = np.setdiff1d(all_eids, eids_off) self.show_ids_mask(ishow) def hide_eids(self, eids): """hides the specified element IDs""" all_eids = self.get_all_eids() # remove eids that are out of range eids = np.intersect1d(all_eids, eids) # A-B eids = np.setdiff1d(all_eids, eids) # update for indices ishow = np.searchsorted(all_eids, eids) self.show_ids_mask(ishow) def create_groups_by_visible_result(self, nlimit=50): """ Creates group by the active result This should really only be called for integer results < 50-ish. """ #self.scalar_bar.title case_key = self.case_keys[self.icase] # int for object result_name = self.result_name obj, (i, name) = self.result_cases[case_key] default_title = obj.get_default_title(i, name) location = obj.get_location(i, name) if obj.data_format != '%i': self.log.error('not creating result=%r; must be an integer result' % result_name) return 0 if location != 'centroid': self.log.error('not creating result=%r; must be a centroidal result' % result_name) return 0 word = default_title prefix = default_title ngroups = self._create_groups_by_name(word, prefix, nlimit=nlimit) self.log_command('create_groups_by_visible_result()' ' # created %i groups for result_name=%r' % (ngroups, result_name)) def create_groups_by_property_id(self): """ Creates a group for each Property ID. As this is somewhat Nastran specific, create_groups_by_visible_result exists as well. """ self._create_groups_by_name('PropertyID', 'property') self.log_command('create_groups_by_property_id()') def _create_groups_by_name(self, name, prefix, nlimit=50): """ Helper method for `create_groups_by_visible_result` and `create_groups_by_property_id` """ #eids = self.find_result_by_name('ElementID') #elements_pound = eids.max() eids = self.groups['main'].element_ids elements_pound = self.groups['main'].elements_pound result = self.find_result_by_name(name) ures = np.unique(result) ngroups = len(ures) if ngroups > nlimit: self.log.error('not creating result; %i new groups would be created; ' 'increase nlimit=%i if you really want to' % (ngroups, nlimit)) return 0 for uresi in ures: ids = np.where(uresi == result)[0] name = '%s %s' % (prefix, uresi) element_str = '' group = Group( name, element_str, elements_pound, editable=True) group.element_ids = eids[ids] self.log_info('creating group=%r' % name) self.groups[name] = group return ngroups def create_group_with_name(self, name, eids): elements_pound = self.groups['main'].elements_pound element_str = '' group = Group( name, element_str, elements_pound, editable=True) # TODO: make sure all the eids exist group.element_ids = eids self.log_command('create_group_with_name(%r, %r)' % (name, eids)) self.groups[name] = group def find_result_by_name(self, desired_name): for icase in range(self.ncases): name, result = self.get_name_result_data(icase) if name == desired_name: return result raise RuntimeError('cannot find name=%r' % desired_name) def show_ids_mask(self, ids_to_show): """masks the specific 0-based element ids""" #print('ids_to_show = ', ids_to_show) prop = self.geom_actor.GetProperty() if len(ids_to_show) == self.nelements: #prop.BackfaceCullingOn() pass else: prop.BackfaceCullingOff() if 0: # pragma: no cover self._show_ids_mask(ids_to_show) elif 1: # doesn't work for the BWB_saero.bdf flip_flag = True is self._show_flag assert self._show_flag is True, self._show_flag self._update_ids_mask_show(ids_to_show) self._show_flag = True elif 1: # pragma: no cover # works flip_flag = True is self._show_flag assert self._show_flag is True, self._show_flag self._update_ids_mask_show_true(ids_to_show, flip_flag, render=False) self._update_ids_mask_show_true(ids_to_show, False, render=True) self._show_flag = True else: # pragma: no cover # old; works; slow flip_flag = True is self._show_flag self._update_ids_mask(ids_to_show, flip_flag, show_flag=True, render=False) self._update_ids_mask(ids_to_show, False, show_flag=True, render=True) self._show_flag = True def hide_ids_mask(self, ids_to_hide): """masks the specific 0-based element ids""" #print('hide_ids_mask = ', hide_ids_mask) prop = self.geom_actor.GetProperty() if len(self.ids_to_hide) == 0: prop.BackfaceCullingOn() else: prop.BackfaceCullingOff() #if 0: # pragma: no cover #self._hide_ids_mask(ids_to_hide) #else: # old; works; slow flip_flag = False is self._show_flag self._update_ids_mask(ids_to_hide, flip_flag, show_flag=False, render=False) self._update_ids_mask(ids_to_hide, False, show_flag=False, render=True) self._show_flag = False def _show_ids_mask(self, ids_to_show): """ helper method for ``show_ids_mask`` .. todo:: doesn't work """ all_i = np.arange(self.nelements, dtype='int32') ids_to_hide = np.setdiff1d(all_i, ids_to_show) self._hide_ids_mask(ids_to_hide) def _hide_ids_mask(self, ids_to_hide): """ helper method for ``hide_ids_mask`` .. todo:: doesn't work """ #print('_hide_ids_mask = ', ids_to_hide) ids = self.numpy_to_vtk_idtype(ids_to_hide) #self.selection_node.GetProperties().Set(vtk.vtkSelectionNode.INVERSE(), 1) if 1: # sane; doesn't work self.selection_node.SetSelectionList(ids) ids.Modified() self.selection_node.Modified() self.selection.Modified() self.grid_selected.Modified() self.grid_selected.ShallowCopy(self.extract_selection.GetOutput()) self.update_all(render=True) else: # pragma: no cover # doesn't work self.selection.RemoveAllNodes() self.selection_node = vtk.vtkSelectionNode() self.selection_node.SetFieldType(vtk.vtkSelectionNode.CELL) self.selection_node.SetContentType(vtk.vtkSelectionNode.INDICES) #self.selection_node.GetProperties().Set(vtk.vtkSelectionNode.INVERSE(), 1) self.selection.AddNode(self.selection_node) self.selection_node.SetSelectionList(ids) #self.selection.RemoveAllNodes() #self.selection.AddNode(self.selection_node) self.grid_selected.ShallowCopy(self.extract_selection.GetOutput()) self.selection_node.SetSelectionList(ids) self.update_all(render=True) def numpy_to_vtk_idtype(self, ids): #self.selection_node.GetProperties().Set(vtk.vtkSelectionNode.INVERSE(), 1) from pyNastran.gui.gui_utils.vtk_utils import numpy_to_vtkIdTypeArray dtype = get_numpy_idtype_for_vtk() ids = np.asarray(ids, dtype=dtype) vtk_ids = numpy_to_vtkIdTypeArray(ids, deep=0) return vtk_ids def _update_ids_mask_show_false(self, ids_to_show, flip_flag=True, render=True): ids = self.numpy_to_vtk_idtype(ids_to_show) ids.Modified() if flip_flag: self.selection.RemoveAllNodes() self.selection_node = vtk.vtkSelectionNode() self.selection_node.SetFieldType(vtk.vtkSelectionNode.CELL) self.selection_node.SetContentType(vtk.vtkSelectionNode.INDICES) self.selection_node.SetSelectionList(ids) self.selection_node.GetProperties().Set(vtk.vtkSelectionNode.INVERSE(), 1) self.selection.AddNode(self.selection_node) else: self.selection_node.SetSelectionList(ids) # dumb; works self.grid_selected.ShallowCopy(self.extract_selection.GetOutput()) self.update_all(render=render) def _update_ids_mask_show(self, ids_to_show): """helper method for ``show_ids_mask``""" ids = self.numpy_to_vtk_idtype(ids_to_show) ids.Modified() self.selection.RemoveAllNodes() self.selection_node = vtk.vtkSelectionNode() self.selection_node.SetFieldType(vtk.vtkSelectionNode.CELL) self.selection_node.SetContentType(vtk.vtkSelectionNode.INDICES) self.selection_node.SetSelectionList(ids) self.selection_node.Modified() self.selection.Modified() self.selection.AddNode(self.selection_node) # seems to also work self.extract_selection.Update() self.grid_selected.ShallowCopy(self.extract_selection.GetOutput()) self.update_all(render=True) #if 0: #self.grid_selected.Modified() #self.vtk_interactor.Render() #render_window = self.vtk_interactor.GetRenderWindow() #render_window.Render() def _update_ids_mask_show_true(self, ids_to_show, flip_flag=True, render=True): # pragma: no cover ids = self.numpy_to_vtk_idtype(ids_to_show) ids.Modified() if flip_flag: self.selection.RemoveAllNodes() self.selection_node = vtk.vtkSelectionNode() self.selection_node.SetFieldType(vtk.vtkSelectionNode.CELL) self.selection_node.SetContentType(vtk.vtkSelectionNode.INDICES) self.selection_node.SetSelectionList(ids) self.selection.AddNode(self.selection_node) else: self.selection_node.SetSelectionList(ids) # dumb; works self.grid_selected.ShallowCopy(self.extract_selection.GetOutput()) self.update_all(render=render) def _update_ids_mask(self, ids_to_show, flip_flag=True, show_flag=True, render=True): print('flip_flag=%s show_flag=%s' % (flip_flag, show_flag)) ids = self.numpy_to_vtk_idtype(ids_to_show) ids.Modified() if flip_flag: self.selection.RemoveAllNodes() self.selection_node = vtk.vtkSelectionNode() self.selection_node.SetFieldType(vtk.vtkSelectionNode.CELL) self.selection_node.SetContentType(vtk.vtkSelectionNode.INDICES) self.selection_node.SetSelectionList(ids) if not show_flag: self.selection_node.GetProperties().Set(vtk.vtkSelectionNode.INVERSE(), 1) self.selection.AddNode(self.selection_node) else: self.selection_node.SetSelectionList(ids) #self.grid_selected.Update() # not in vtk 6 #ids.Update() #self.shown_ids.Modified() if 0: # pragma: no cover # doesn't work... if vtk.VTK_MAJOR_VERSION <= 5: self.extract_selection.SetInput(0, self.grid) self.extract_selection.SetInput(1, self.selection) else: self.extract_selection.SetInputData(0, self.grid) self.extract_selection.SetInputData(1, self.selection) else: # dumb; works self.grid_selected.ShallowCopy(self.extract_selection.GetOutput()) #if 0: #self.selection_node.GetProperties().Set(vtk.vtkSelectionNode.INVERSE(), 1) #self.extract_selection.Update() self.update_all(render=render) def update_all_2(self, render=True): # pragma: no cover self.grid_selected.Modified() self.selection_node.Modified() self.selection.Modified() self.extract_selection.Update() self.extract_selection.Modified() self.grid_selected.Modified() self.grid_mapper.Update() self.grid_mapper.Modified() self.iren.Modified() self.rend.Render() self.rend.Modified() self.geom_actor.Modified() if render: self.vtk_interactor.Render() render_window = self.vtk_interactor.GetRenderWindow() render_window.Render() def update_all(self, render=True): self.grid_selected.Modified() #selection_node.Update() self.selection_node.Modified() #selection.Update() self.selection.Modified() self.extract_selection.Update() self.extract_selection.Modified() #grid_selected.Update() self.grid_selected.Modified() self.grid_mapper.Update() self.grid_mapper.Modified() #selected_actor.Update() #selected_actor.Modified() #right_renderer.Modified() #right_renderer.Update() self.iren.Modified() #interactor.Update() #----------------- self.rend.Render() #interactor.Start() self.rend.Modified() self.geom_actor.Modified() if render: self.vtk_interactor.Render() render_window = self.vtk_interactor.GetRenderWindow() render_window.Render() def _setup_element_mask(self, create_grid_selected=True): """ starts the masking self.grid feeds in the geometry """ ids = vtk.vtkIdTypeArray() ids.SetNumberOfComponents(1) # the "selection_node" is really a "selection_element_ids" # furthermore, it's an inverse model, so adding elements # hides more elements self.selection_node = vtk.vtkSelectionNode() self.selection_node.SetFieldType(vtk.vtkSelectionNode.CELL) self.selection_node.SetContentType(vtk.vtkSelectionNode.INDICES) self.selection_node.GetProperties().Set(vtk.vtkSelectionNode.INVERSE(), 1) # added self.selection_node.SetSelectionList(ids) self.selection = vtk.vtkSelection() self.selection.AddNode(self.selection_node) self.extract_selection = vtk.vtkExtractSelection() if vtk.VTK_MAJOR_VERSION <= 5: self.extract_selection.SetInput(0, self.grid) self.extract_selection.SetInput(1, self.selection) else: self.extract_selection.SetInputData(0, self.grid) self.extract_selection.SetInputData(1, self.selection) self.extract_selection.Update() # In selection if create_grid_selected: self.grid_selected = vtk.vtkUnstructuredGrid() self.grid_selected.ShallowCopy(self.extract_selection.GetOutput()) #if 0: self.selection_node.GetProperties().Set(vtk.vtkSelectionNode.INVERSE(), 1) self.extract_selection.Update() def create_text(self, position, label, text_size=18): """creates the lower left text actors""" text_actor = vtk.vtkTextActor() text_actor.SetInput(label) text_prop = text_actor.GetTextProperty() #text_prop.SetFontFamilyToArial() text_prop.SetFontSize(int(text_size)) text_prop.SetColor(self.text_color) text_actor.SetDisplayPosition(*position) text_actor.VisibilityOff() # assign actor to the renderer self.rend.AddActor(text_actor) self.text_actors[self.itext] = text_actor self.itext += 1 def turn_text_off(self): """turns all the text actors off""" for text in itervalues(self.text_actors): text.VisibilityOff() def turn_text_on(self): """turns all the text actors on""" for text in itervalues(self.text_actors): text.VisibilityOn() def build_lookup_table(self): scalar_range = self.grid_selected.GetScalarRange() self.grid_mapper.SetScalarRange(scalar_range) self.grid_mapper.SetLookupTable(self.color_function) self.rend.AddActor(self.scalarBar) def _create_load_file_dialog(self, qt_wildcard, title, default_filename=None): if default_filename is None: default_filename = self.last_dir fname, wildcard_level = getopenfilename( parent=self, caption=title, basedir=default_filename, filters=qt_wildcard, selectedfilter='', options=None) return wildcard_level, fname #def _create_load_file_dialog2(self, qt_wildcard, title): ## getOpenFileName return QString and we want Python string ##title = 'Load a Tecplot Geometry/Results File' #last_dir = '' ##qt_wildcard = ['Tecplot Hex Binary (*.tec; *.dat)'] #dialog = MultiFileDialog() #dialog.setWindowTitle(title) #dialog.setDirectory(self.last_dir) #dialog.setFilters(qt_wildcard.split(';;')) #if dialog.exec_() == QtGui.QDialog.Accepted: #outfiles = dialog.selectedFiles() #wildcard_level = dialog.selectedFilter() #return str(wildcard_level), str(fname) #return None, None def start_logging(self): if self.html_logging is True: log = SimpleLogger('debug', 'utf-8', lambda x, y: self._logg_msg(x, y)) # logging needs synchronizing, so the messages from different # threads would not be interleave self.log_mutex = QtCore.QReadWriteLock() else: log = SimpleLogger( level='debug', encoding='utf-8', #log_func=lambda x, y: print(x, y) # no colorama ) self.log = log def build_fmts(self, fmt_order, stop_on_failure=False): fmts = [] for fmt in fmt_order: if hasattr(self, 'get_%s_wildcard_geometry_results_functions' % fmt): func = 'get_%s_wildcard_geometry_results_functions' % fmt data = getattr(self, func)() msg = 'macro_name, geo_fmt, geo_func, res_fmt, res_func = data\n' msg += 'data = %s' if isinstance(data, tuple): assert len(data) == 5, msg % str(data) macro_name, geo_fmt, geo_func, res_fmt, res_func = data fmts.append((fmt, macro_name, geo_fmt, geo_func, res_fmt, res_func)) elif isinstance(data, list): for datai in data: assert len(datai) == 5, msg % str(datai) macro_name, geo_fmt, geo_func, res_fmt, res_func = datai fmts.append((fmt, macro_name, geo_fmt, geo_func, res_fmt, res_func)) else: raise TypeError(data) else: if stop_on_failure: func = 'get_%s_wildcard_geometry_results_functions does not exist' % fmt raise RuntimeError(func) if len(fmts) == 0: RuntimeError('No formats...expected=%s' % fmt_order) self.fmts = fmts self.supported_formats = [fmt[0] for fmt in fmts] print('supported_formats = %s' % self.supported_formats) if len(fmts) == 0: raise RuntimeError('no modules were loaded...') def on_load_geometry_button(self, infile_name=None, geometry_format=None, name='main', plot=True, raise_error=False): """action version of ``on_load_geometry``""" self.on_load_geometry(infile_name=infile_name, geometry_format=geometry_format, name=name, plot=True, raise_error=raise_error) def _load_geometry_filename(self, geometry_format, infile_name): """gets the filename and format""" wildcard = '' is_failed = False if geometry_format and geometry_format.lower() not in self.supported_formats: is_failed = True msg = 'The import for the %r module failed.\n' % geometry_format self.log_error(msg) return is_failed, None if infile_name: geometry_format = geometry_format.lower() print("geometry_format = %r" % geometry_format) for fmt in self.fmts: fmt_name, _major_name, _geom_wildcard, geom_func, res_wildcard, _resfunc = fmt if geometry_format == fmt_name: load_function = geom_func if res_wildcard is None: has_results = False else: has_results = True break else: self.log_error('---invalid format=%r' % geometry_format) is_failed = True return is_failed, None formats = [geometry_format] filter_index = 0 else: # load a pyqt window formats = [] load_functions = [] has_results_list = [] wildcard_list = [] # setup the selectable formats for fmt in self.fmts: fmt_name, _major_name, geom_wildcard, geom_func, res_wildcard, _res_func = fmt formats.append(_major_name) wildcard_list.append(geom_wildcard) load_functions.append(geom_func) if res_wildcard is None: has_results_list.append(False) else: has_results_list.append(True) # the list of formats that will be selectable in some odd syntax # that pyqt uses wildcard = ';;'.join(wildcard_list) # get the filter index and filename if infile_name is not None and geometry_format is not None: filter_index = formats.index(geometry_format) else: title = 'Choose a Geometry File to Load' wildcard_index, infile_name = self._create_load_file_dialog(wildcard, title) if not infile_name: # user clicked cancel is_failed = True return is_failed, None filter_index = wildcard_list.index(wildcard_index) geometry_format = formats[filter_index] load_function = load_functions[filter_index] has_results = has_results_list[filter_index] return is_failed, (infile_name, load_function, filter_index, formats) def on_load_geometry(self, infile_name=None, geometry_format=None, name='main', plot=True, raise_error=True): """ Loads a baseline geometry Parameters ---------- infile_name : str; default=None -> popup path to the filename geometry_format : str; default=None the geometry format for programmatic loading name : str; default='main' the name of the actor; don't use this plot : bool; default=True Should the baseline geometry have results created and plotted/rendered? If you're calling the on_load_results method immediately after, set it to False raise_error : bool; default=True stop the code if True """ is_failed, out = self._load_geometry_filename( geometry_format, infile_name) if is_failed: return infile_name, load_function, filter_index, formats = out if load_function is not None: self.last_dir = os.path.split(infile_name)[0] if self.name == '': name = 'main' else: print('name = %r' % name) if name != self.name: #scalar_range = self.grid_selected.GetScalarRange() #self.grid_mapper.SetScalarRange(scalar_range) self.grid_mapper.ScalarVisibilityOff() #self.grid_mapper.SetLookupTable(self.color_function) self.name = str(name) self._reset_model(name) # reset alt grids names = self.alt_grids.keys() for name in names: self.alt_grids[name].Reset() self.alt_grids[name].Modified() if not os.path.exists(infile_name) and geometry_format: msg = 'input file=%r does not exist' % infile_name self.log_error(msg) self.log_error(print_bad_path(infile_name)) return # clear out old data if self.model_type is not None: clear_name = 'clear_' + self.model_type try: dy_method = getattr(self, clear_name) # 'self.clear_nastran()' dy_method() except: print("method %r does not exist" % clear_name) self.log_info("reading %s file %r" % (geometry_format, infile_name)) try: time0 = time.time() has_results = load_function(infile_name, name=name, plot=plot) # self.last_dir, dt = time.time() - time0 print('dt_load = %.2f sec = %.2f min' % (dt, dt / 60.)) #else: #name = load_function.__name__ #self.log_error(str(args)) #self.log_error("'plot' needs to be added to %r; " #"args[-1]=%r" % (name, args[-1])) #has_results = load_function(infile_name) # , self.last_dir #form, cases = load_function(infile_name) # , self.last_dir except Exception as e: msg = traceback.format_exc() self.log_error(msg) if raise_error or self.dev: raise #return #self.vtk_panel.Update() self.rend.ResetCamera() # the model has been loaded, so we enable load_results if filter_index >= 0: self.format = formats[filter_index].lower() enable = has_results #self.load_results.Enable(enable) else: # no file specified return #print("on_load_geometry(infile_name=%r, geometry_format=None)" % infile_name) self.infile_name = infile_name self.out_filename = None #if self.out_filename is not None: #msg = '%s - %s - %s' % (self.format, self.infile_name, self.out_filename) #else: if name == 'main': msg = '%s - %s' % (self.format, self.infile_name) self.window_title = msg self.update_menu_bar() main_str = '' else: main_str = ', name=%r' % name self.log_command("on_load_geometry(infile_name=%r, geometry_format=%r%s)" % ( infile_name, self.format, main_str)) def _reset_model(self, name): """resets the grids; sets up alt_grids""" if hasattr(self, 'main_grids') and name not in self.main_grids: grid = vtk.vtkUnstructuredGrid() grid_mapper = vtk.vtkDataSetMapper() if self.vtk_version[0] <= 5: grid_mapper.SetInputConnection(grid.GetProducerPort()) else: grid_mapper.SetInputData(grid) geom_actor = vtk.vtkLODActor() geom_actor.DragableOff() geom_actor.SetMapper(grid_mapper) self.rend.AddActor(geom_actor) self.grid = grid self.grid_mapper = grid_mapper self.geom_actor = geom_actor self.grid.Modified() # link the current "main" to the scalar bar scalar_range = self.grid_selected.GetScalarRange() self.grid_mapper.ScalarVisibilityOn() self.grid_mapper.SetScalarRange(scalar_range) self.grid_mapper.SetLookupTable(self.color_function) self.edge_actor = vtk.vtkLODActor() self.edge_actor.DragableOff() self.edge_mapper = vtk.vtkPolyDataMapper() # create the edges self.get_edges() else: self.grid.Reset() self.grid.Modified() # reset alt grids alt_names = self.alt_grids.keys() for alt_name in alt_names: self.alt_grids[alt_name].Reset() self.alt_grids[alt_name].Modified() def _update_menu_bar_to_format(self, fmt, method): self.menu_bar_format = fmt tools, menu_items = getattr(self, method)() actions = self._prepare_actions(self._icon_path, tools, self.checkables) self._update_menu(menu_items) def update_menu_bar(self): # the format we're switching to method_new = '_create_%s_tools_and_menu_items' % self.format method_cleanup = '_cleanup_%s_tools_and_menu_items' % self.menu_bar_format # the current state of the format #method_new = '_create_%s_tools_and_menu_items' % self.menu_bar_format self.menu_bar_format = 'cwo' if self.menu_bar_format is None: self._update_menu_bar_to_format(self.format, method_new) else: print('need to add %r' % method_new) if self.menu_bar_format != self.format: if hasattr(self, method_cleanup): #if hasattr(self, method_old): self.menu_bar_format = None getattr(self, method_cleanup)() if hasattr(self, method_new): self._update_menu_bar_to_format(self.format, method_new) #self._update_menu_bar_to_format(self.format) #actions = self._prepare_actions(self._icon_path, self.tools, self.checkables) #menu_items = self._create_menu_items(actions) #menu_items = self._create_menu_items() #self._populate_menu(menu_items) def on_load_custom_results(self, out_filename=None, restype=None): """will be a more generalized results reader""" is_failed = True geometry_format = self.format if self.format is None: msg = 'on_load_results failed: You need to load a file first...' self.log_error(msg) return is_failed if out_filename in [None, False]: title = 'Select a Custom Results File for %s' % (self.format) #print('wildcard_level =', wildcard_level) #self.wildcard_delimited = 'Delimited Text (*.txt; *.dat; *.csv)' fmts = [ 'Node - Delimited Text (*.txt; *.dat; *.csv)', 'Element - Delimited Text (*.txt; *.dat; *.csv)', 'Nodal Deflection - Delimited Text (*.txt; *.dat; *.csv)', 'Patran nod (*.nod)', ] fmt = ';;'.join(fmts) wildcard_level, out_filename = self._create_load_file_dialog(fmt, title) if not out_filename: return is_failed # user clicked cancel iwildcard = fmts.index(wildcard_level) else: fmts = [ 'node', 'element', 'deflection', 'patran_nod', ] iwildcard = fmts.index(restype.lower()) if out_filename == '': return is_failed if not os.path.exists(out_filename): msg = 'result file=%r does not exist' % out_filename self.log_error(msg) return is_failed try: if iwildcard == 0: self._on_load_nodal_elemental_results('Nodal', out_filename) restype = 'Node' elif iwildcard == 1: self._on_load_nodal_elemental_results('Elemental', out_filename) restype = 'Element' elif iwildcard == 2: self._load_deflection(out_filename) restype = 'Deflection' elif iwildcard == 3: self._load_patran_nod(out_filename) restype = 'Patran_nod' else: raise NotImplementedError('wildcard_level = %s' % wildcard_level) except Exception as e: msg = traceback.format_exc() self.log_error(msg) return is_failed self.log_command("on_load_custom_results(%r, restype=%r)" % (out_filename, restype)) is_failed = False return is_failed def _on_load_nodal_elemental_results(self, result_type, out_filename=None): """ Loads a CSV/TXT results file. Must have called on_load_geometry first. Parameters ---------- result_type : str 'Nodal', 'Elemental' out_filename : str / None the path to the results file """ try: self._load_csv(result_type, out_filename) except Exception as e: msg = traceback.format_exc() self.log_error(msg) #return raise #if 0: #self.out_filename = out_filename #msg = '%s - %s - %s' % (self.format, self.infile_name, out_filename) #self.window_title = msg #self.out_filename = out_filename #def _load_force(self, out_filename): #"""loads a deflection file""" #self._load_deflection_force(out_filename, is_deflection=True, is_force=False) def _load_deflection(self, out_filename): """loads a force file""" self._load_deflection_force(out_filename, is_deflection=False, is_force=True) def _load_deflection_force(self, out_filename, is_deflection=False, is_force=False): out_filename_short = os.path.basename(out_filename) A, fmt_dict, headers = load_deflection_csv(out_filename) #nrows, ncols, fmts header0 = headers[0] result0 = A[header0] nrows = result0.shape[0] assert nrows == self.nnodes, 'nrows=%s nnodes=%s' % (nrows, self.nnodes) result_type = 'node' self._add_cases_to_form(A, fmt_dict, headers, result_type, out_filename_short, update=True, is_scalar=False, is_deflection=is_deflection, is_force=is_deflection) def _load_csv(self, result_type, out_filename): """ common method between: - on_add_nodal_results(filename) - on_add_elemental_results(filename) Parameters ---------- result_type : str ??? out_filename : str the CSV filename to load """ out_filename_short = os.path.relpath(out_filename) A, fmt_dict, headers = load_csv(out_filename) #nrows, ncols, fmts header0 = headers[0] result0 = A[header0] nrows = result0.size if result_type == 'Nodal': assert nrows == self.nnodes, 'nrows=%s nnodes=%s' % (nrows, self.nnodes) result_type2 = 'node' #ids = self.node_ids elif result_type == 'Elemental': assert nrows == self.nelements, 'nrows=%s nelements=%s' % (nrows, self.nelements) result_type2 = 'centroid' #ids = self.element_ids else: raise NotImplementedError('result_type=%r' % result_type) #num_ids = len(ids) #if num_ids != nrows: #A2 = {} #for key, matrix in iteritems(A): #fmt = fmt_dict[key] #assert fmt not in ['%i'], 'fmt=%r' % fmt #if len(matrix.shape) == 1: #matrix2 = np.full(num_ids, dtype=matrix.dtype) #iids = np.searchsorted(ids, ) #A = A2 self._add_cases_to_form(A, fmt_dict, headers, result_type2, out_filename_short, update=True, is_scalar=True) def on_load_results(self, out_filename=None): """ Loads a results file. Must have called on_load_geometry first. Parameters ---------- out_filename : str / None the path to the results file """ geometry_format = self.format if self.format is None: msg = 'on_load_results failed: You need to load a file first...' self.log_error(msg) raise RuntimeError(msg) if out_filename in [None, False]: title = 'Select a Results File for %s' % self.format wildcard = None load_function = None for fmt in self.fmts: fmt_name, _major_name, _geowild, _geofunc, _reswild, _resfunc = fmt if geometry_format == fmt_name: wildcard = _reswild load_function = _resfunc break else: msg = 'format=%r is not supported' % geometry_format self.log_error(msg) raise RuntimeError(msg) if wildcard is None: msg = 'format=%r has no method to load results' % geometry_format self.log_error(msg) return out_filename = self._create_load_file_dialog(wildcard, title)[1] else: for fmt in self.fmts: fmt_name, _major_name, _geowild, _geofunc, _reswild, _resfunc = fmt print('fmt_name=%r geometry_format=%r' % (fmt_name, geometry_format)) if fmt_name == geometry_format: load_function = _resfunc break else: msg = ('format=%r is not supported. ' 'Did you load a geometry model?' % geometry_format) self.log_error(msg) raise RuntimeError(msg) if out_filename == '': return if isinstance(out_filename, string_types): out_filename = [out_filename] for out_filenamei in out_filename: if not os.path.exists(out_filenamei): msg = 'result file=%r does not exist' % out_filenamei self.log_error(msg) return #raise IOError(msg) self.last_dir = os.path.split(out_filenamei)[0] try: load_function(out_filenamei) except Exception: # as e msg = traceback.format_exc() self.log_error(msg) #return raise self.out_filename = out_filenamei msg = '%s - %s - %s' % (self.format, self.infile_name, out_filenamei) self.window_title = msg print("on_load_results(%r)" % out_filenamei) self.out_filename = out_filenamei self.log_command("on_load_results(%r)" % out_filenamei) def setup_gui(self): """ Setup the gui 1. starts the logging 2. reapplies the settings 3. create pickers 4. create main vtk actors 5. shows the Qt window """ assert self.fmts != [], 'supported_formats=%s' % self.supported_formats self.start_logging() settings = QtCore.QSettings() self.create_vtk_actors() # build GUI and restore saved application state #nice_blue = (0.1, 0.2, 0.4) qpos_default = self.pos() pos_default = qpos_default.x(), qpos_default.y() self.reset_settings = False #if self.reset_settings or qt_version in [5, 'pyside']: #self.settings.reset_settings() #else: self.settings.load(settings) self.init_ui() if self.reset_settings: self.res_dock.toggleViewAction() self.init_cell_picker() main_window_state = settings.value("mainWindowState") self.create_corner_axis() #------------- # loading self.show() def setup_post(self, inputs): """interface for user defined post-scripts""" self.load_batch_inputs(inputs) shots = inputs['shots'] if shots is None: shots = [] if shots: #for shot in shots: self.on_take_screenshot(shots) sys.exit('took screenshot %r' % shots) self.color_order = [ (1.0, 0.145098039216, 1.0), (0.0823529411765, 0.0823529411765, 1.0), (0.0901960784314, 1.0, 0.941176470588), (0.501960784314, 1.0, 0.0941176470588), (1.0, 1.0, 0.117647058824), (1.0, 0.662745098039, 0.113725490196) ] if inputs['user_points'] is not None: for fname in inputs['user_points']: self.on_load_user_points(fname) if inputs['user_geom'] is not None: for fname in inputs['user_geom']: self.on_load_user_geom(fname) #self.set_anti_aliasing(16) def on_load_user_geom(self, csv_filename=None, name=None, color=None): """ Loads a User Geometry CSV File of the form: # id x y z GRID, 1, 0.2, 0.3, 0.3 GRID, 2, 1.2, 0.3, 0.3 GRID, 3, 2.2, 0.3, 0.3 GRID, 4, 5.2, 0.3, 0.3 grid, 5, 5.2, 1.3, 2.3 # case insensitive # ID, nodes BAR, 1, 1, 2 TRI, 2, 1, 2, 3 # this is a comment QUAD, 3, 1, 5, 3, 4 QUAD, 4, 1, 2, 3, 4 # this is after a blank line #RESULT,4,CENTROID,AREA(%f),PROPERTY_ID(%i) # in element id sorted order: value1, value2 #1.0, 2.0 # bar #1.0, 2.0 # tri #1.0, 2.0 # quad #1.0, 2.0 # quad #RESULT,NODE,NODEX(%f),NODEY(%f),NODEZ(%f) # same difference #RESULT,VECTOR3,GEOM,DXYZ # 3xN Parameters ---------- csv_filename : str (default=None -> load a dialog) the path to the user geometry CSV file name : str (default=None -> extract from fname) the name for the user points color : (float, float, float) RGB values as 0.0 <= rgb <= 1.0 """ if csv_filename in [None, False]: title = 'Load User Geometry' csv_filename = self._create_load_file_dialog(self.wildcard_delimited, title)[1] if not csv_filename: return if color is None: # we mod the num_user_points so we don't go outside the range icolor = self.num_user_points % len(self.color_order) color = self.color_order[icolor] if name is None: name = os.path.basename(csv_filename).rsplit('.', 1)[0] self._add_user_geometry(csv_filename, name, color) self.log_command('on_load_user_geom(%r, %r, %s)' % ( csv_filename, name, str(color))) def _add_user_geometry(self, csv_filename, name, color): """helper method for ``on_load_user_geom``""" if name in self.geometry_actors: msg = 'Name: %s is already in geometry_actors\nChoose a different name.' % name raise ValueError(msg) if len(name) == 0: msg = 'Invalid Name: name=%r' % name raise ValueError(msg) point_name = name + '_point' geom_name = name + '_geom' grid_ids, xyz, bars, tris, quads = load_user_geom(csv_filename) nbars = len(bars) ntris = len(tris) nquads = len(quads) nelements = nbars + ntris + nquads self.create_alternate_vtk_grid(point_name, color=color, opacity=1.0, point_size=5, representation='point') if nelements > 0: nid_map = {} i = 0 for nid in grid_ids: nid_map[nid] = i i += 1 self.create_alternate_vtk_grid(geom_name, color=color, opacity=1.0, line_width=5, representation='toggle') # allocate nnodes = len(grid_ids) #self.alt_grids[point_name].Allocate(npoints, 1000) #if nelements > 0: #self.alt_grids[geom_name].Allocate(npoints, 1000) # set points points = numpy_to_vtk_points(xyz, dtype='<f') if nelements > 0: geom_grid = self.alt_grids[geom_name] for i in range(nnodes): elem = vtk.vtkVertex() elem.GetPointIds().SetId(0, i) self.alt_grids[point_name].InsertNextCell(elem.GetCellType(), elem.GetPointIds()) geom_grid.InsertNextCell(elem.GetCellType(), elem.GetPointIds()) else: for i in range(nnodes): elem = vtk.vtkVertex() elem.GetPointIds().SetId(0, i) self.alt_grids[point_name].InsertNextCell(elem.GetCellType(), elem.GetPointIds()) if nbars: for i, bar in enumerate(bars[:, 1:]): g1 = nid_map[bar[0]] g2 = nid_map[bar[1]] elem = vtk.vtkLine() elem.GetPointIds().SetId(0, g1) elem.GetPointIds().SetId(1, g2) geom_grid.InsertNextCell(elem.GetCellType(), elem.GetPointIds()) if ntris: for i, tri in enumerate(tris[:, 1:]): g1 = nid_map[tri[0]] g2 = nid_map[tri[1]] g3 = nid_map[tri[2]] elem = vtk.vtkTriangle() elem.GetPointIds().SetId(0, g1) elem.GetPointIds().SetId(1, g2) elem.GetPointIds().SetId(2, g3) geom_grid.InsertNextCell(5, elem.GetPointIds()) if nquads: for i, quad in enumerate(quads[:, 1:]): g1 = nid_map[quad[0]] g2 = nid_map[quad[1]] g3 = nid_map[quad[2]] g4 = nid_map[quad[3]] elem = vtk.vtkQuad() point_ids = elem.GetPointIds() point_ids.SetId(0, g1) point_ids.SetId(1, g2) point_ids.SetId(2, g3) point_ids.SetId(3, g4) geom_grid.InsertNextCell(9, elem.GetPointIds()) self.alt_grids[point_name].SetPoints(points) if nelements > 0: self.alt_grids[geom_name].SetPoints(points) # create actor/mapper self._add_alt_geometry(self.alt_grids[point_name], point_name) if nelements > 0: self._add_alt_geometry(self.alt_grids[geom_name], geom_name) # set representation to points #self.geometry_properties[point_name].representation = 'point' #self.geometry_properties[geom_name].representation = 'toggle' #actor = self.geometry_actors[name] #prop = actor.GetProperty() #prop.SetRepresentationToPoints() #prop.SetPointSize(4) def on_load_csv_points(self, csv_filename=None, name=None, color=None): """ Loads a User Points CSV File of the form: 1.0, 2.0, 3.0 1.5, 2.5, 3.5 Parameters ----------- csv_filename : str (default=None -> load a dialog) the path to the user points CSV file name : str (default=None -> extract from fname) the name for the user points color : (float, float, float) RGB values as 0.0 <= rgb <= 1.0 .. note:: no header line is required .. note:: nodes are in the global frame .. todo:: support changing the name .. todo:: support changing the color .. todo:: support overwriting points """ if csv_filename in [None, False]: title = 'Load User Points' csv_filename = self._create_load_file_dialog(self.wildcard_delimited, title)[1] if not csv_filename: return if color is None: # we mod the num_user_points so we don't go outside the range icolor = self.num_user_points % len(self.color_order) color = self.color_order[icolor] if name is None: sline = os.path.basename(csv_filename).rsplit('.', 1) name = sline[0] is_failed = self._add_user_points_from_csv(csv_filename, name, color) if not is_failed: self.num_user_points += 1 self.log_command('on_load_csv_points(%r, %r, %s)' % ( csv_filename, name, str(color))) return is_failed def create_cell_picker(self): """creates the vtk picker objects""" self.cell_picker = vtk.vtkCellPicker() self.node_picker = vtk.vtkPointPicker() self.area_picker = vtk.vtkAreaPicker() # vtkRenderedAreaPicker? self.rubber_band_style = vtk.vtkInteractorStyleRubberBandPick() #vtk.vtkInteractorStyleRubberBand2D #vtk.vtkInteractorStyleRubberBand3D #vtk.vtkInteractorStyleRubberBandZoom #vtk.vtkInteractorStyleAreaSelectHover #vtk.vtkInteractorStyleDrawPolygon #vtk.vtkAngleWidget #vtk.vtkAngleRepresentation2D #vtk.vtkAngleRepresentation3D #vtk.vtkAnnotation #vtk.vtkArrowSource #vtk.vtkGlyph2D #vtk.vtkGlyph3D #vtk.vtkHedgeHog #vtk.vtkLegendBoxActor #vtk.vtkLegendScaleActor #vtk.vtkLabelPlacer self.cell_picker.SetTolerance(0.001) self.node_picker.SetTolerance(0.001) def mark_elements_by_different_case(self, eids, icase_result, icase_to_apply): """ Marks a series of elements with custom text labels Parameters ---------- eids : int, List[int] the elements to apply a message to icase_result : int the case to draw the result from icase_to_apply : int the key in label_actors to slot the result into TODO: fix the following correct : applies to the icase_to_apply incorrect : applies to the icase_result Examples -------- .. code-block:: eids = [16563, 16564, 8916703, 16499, 16500, 8916699, 16565, 16566, 8916706, 16502, 16503, 8916701] icase_result = 22 icase_to_apply = 25 self.mark_elements_by_different_case(eids, icase_result, icase_to_apply) """ if icase_result not in self.label_actors: msg = 'icase_result=%r not in label_actors=[%s]' % ( icase_result, ', '.join(self.label_actors)) self.log_error(msg) return if icase_to_apply not in self.label_actors: msg = 'icase_to_apply=%r not in label_actors=[%s]' % ( icase_to_apply, ', '.join(self.label_actors)) self.log_error(msg) return eids = np.unique(eids) neids = len(eids) #centroids = np.zeros((neids, 3), dtype='float32') ieids = np.searchsorted(self.element_ids, eids) #print('ieids = ', ieids) for cell_id in ieids: centroid = self.cell_centroid(cell_id) result_name, result_values, xyz = self.get_result_by_cell_id( cell_id, centroid, icase_result) texti = '%s' % result_values xi, yi, zi = centroid self._create_annotation(texti, self.label_actors[icase_to_apply], xi, yi, zi) self.log_command('mark_elements_by_different_case(%s, %s, %s)' % ( eids, icase_result, icase_to_apply)) self.vtk_interactor.Render() def mark_nodes(self, nids, icase, text): """ Marks a series of nodes with custom text labels Parameters ---------- nids : int, List[int] the nodes to apply a message to icase : int the key in label_actors to slot the result into text : str, List[str] the text to display 0 corresponds to the NodeID result self.mark_nodes(1, 0, 'max') self.mark_nodes(6, 0, 'min') self.mark_nodes([1, 6], 0, 'max') self.mark_nodes([1, 6], 0, ['max', 'min']) """ if icase not in self.label_actors: msg = 'icase=%r not in label_actors=[%s]' % ( icase, ', '.join(self.label_actors)) self.log_error(msg) return i = np.searchsorted(self.node_ids, nids) if isinstance(text, string_types): text = [text] * len(i) else: assert len(text) == len(i) xyz = self.xyz_cid0[i, :] for (xi, yi, zi), texti in zip(xyz, text): self._create_annotation(texti, self.label_actors[icase], xi, yi, zi) self.vtk_interactor.Render() def __mark_nodes_by_result(self, nids, icases): """ # mark the node 1 with the NodeID (0) result self.mark_nodes_by_result_case(1, 0) # mark the nodes 1 and 2 with the NodeID (0) result self.mark_nodes_by_result_case([1, 2], 0) # mark the nodes with the NodeID (0) and ElementID (1) result self.mark_nodes_by_result_case([1, 2], [0, 1]) """ i = np.searchsorted(self.node_ids, nids) if isinstance(icases, int): icases = [icases] for icase in icases: if icase not in self.label_actors: msg = 'icase=%r not in label_actors=[%s]' % ( icase, ', '.join(self.label_actors)) self.log_error(msg) continue for node_id in i: #xyz = self.xyz_cid0[i, :] out = self.get_result_by_xyz_node_id(world_position, node_id) _result_name, result_value, node_id, node_xyz = out self._create_annotation(texti, self.label_actors[icase], xi, yi, zi) self.vtk_interactor.Render() def _cell_centroid_pick(self, cell_id, world_position): duplicate_key = None icase = self.icase if self.pick_state == 'node/centroid': return_flag = False duplicate_key = cell_id result_name, result_value, xyz = self.get_result_by_cell_id(cell_id, world_position) assert icase in self.label_actors, icase else: #cell = self.grid.GetCell(cell_id) # get_nastran_centroidal_pick_state_nodal_by_xyz_cell_id() method = 'get_centroidal_%s_result_pick_state_%s_by_xyz_cell_id' % ( self.format, self.pick_state) if hasattr(self, method): methodi = getattr(self, method) return_flag, value = methodi(world_position, cell_id) if return_flag is True: return return_flag, None, None, None, None else: msg = "pick_state is set to 'nodal', but the result is 'centroidal'\n" msg += ' cannot find: self.%s(xyz, cell_id)' % method self.log_error(msg) return return_flag, None, None, None self.log_info("%s = %s" % (result_name, result_value)) return return_flag, duplicate_key, result_value, result_name, xyz def _get_closest_node_xyz(self, cell_id, world_position): duplicate_key = None (result_name, result_value, node_id, xyz) = self.get_result_by_xyz_cell_id( world_position, cell_id) assert self.icase in self.label_actors, result_name assert not isinstance(xyz, int), xyz return xyz def _cell_node_pick(self, cell_id, world_position): duplicate_key = None icase = self.icase if self.pick_state == 'node/centroid': return_flag = False (result_name, result_value, node_id, xyz) = self.get_result_by_xyz_cell_id( world_position, cell_id) assert icase in self.label_actors, result_name assert not isinstance(xyz, int), xyz duplicate_key = node_id else: method = 'get_nodal_%s_result_pick_state_%s_by_xyz_cell_id' % ( self.format, self.pick_state) if hasattr(self, method): methodi = getattr(self, method) return_flag, value = methodi(world_position, cell_id) if return_flag is True: return return_flag, None, None, None, None else: msg = "pick_state is set to 'centroidal', but the result is 'nodal'\n" msg += ' cannot find: self.%s(xyz, cell_id)' % method self.log_error(msg) return return_flag, None, None, None msg = "%s = %s" % (result_name, result_value) if self.result_name in ['Node_ID', 'Node ID', 'NodeID']: x1, y1, z1 = xyz x2, y2, z2 = world_position msg += '; xyz=(%s, %s, %s); pierce_xyz=(%s, %s, %s)' % (x1, y1, z1, x2, y2, z2) self.log_info(msg) return return_flag, duplicate_key, result_value, result_name, xyz def init_cell_picker(self): self.is_pick = False if not self.run_vtk: return self.vtk_interactor.SetPicker(self.node_picker) self.vtk_interactor.SetPicker(self.cell_picker) self.setup_mouse_buttons(mode='probe_result') self.setup_mouse_buttons(mode='default') def convert_units(self, result_name, result_value, xyz): #self.input_units #self.display_units return result_value, xyz def _create_annotation(self, text, slot, x, y, z): """ Creates the actual annotation and appends it to slot Parameters ---------- text : str the text to display x, y, z : float the position of the label slot : List[annotation] where to place the annotation self.label_actors[icase] : List[annotation] icase : icase the key in label_actors to slot the result into annotation : vtkBillboardTextActor3D the annotation object ??? """ if not isinstance(slot, list): msg = 'slot=%r type=%s' % (slot, type(slot)) raise TypeError(msg) # http://nullege.com/codes/show/src%40p%40y%40pymatgen-2.9.6%40pymatgen%40vis%40structure_vtk.py/395/vtk.vtkVectorText/python #self.convert_units(icase, result_value, x, y, z) text_actor = vtk.vtkBillboardTextActor3D() label = text text_actor.SetPosition(x, y, z) text_actor.SetInput(label) text_actor.PickableOff() text_actor.DragableOff() #text_actor.SetPickable(False) #text_actor.SetPosition(actor.GetPosition()) text_prop = text_actor.GetTextProperty() text_prop.SetFontSize(self.annotation_size) text_prop.SetFontFamilyToArial() text_prop.BoldOn() text_prop.ShadowOn() text_prop.SetColor(self.annotation_color) text_prop.SetJustificationToCentered() # finish adding the actor self.rend.AddActor(text_actor) #self.label_actors[icase].append(text_actor) slot.append(text_actor) #print('added label actor %r; icase=%s' % (text, icase)) #print(self.label_actors) #self.picker_textMapper.SetInput("(%.6f, %.6f, %.6f)"% pickPos) #camera.GetPosition() #camera.GetClippingRange() #camera.GetFocalPoint() def _on_multi_pick(self, a): """ vtkFrustumExtractor vtkAreaPicker """ pass def _on_cell_picker(self, a): self.vtk_interactor.SetPicker(self.cell_picker) picker = self.cell_picker world_position = picker.GetPickPosition() cell_id = picker.GetCellId() select_point = picker.GetSelectionPoint() # get x,y pixel coordinate self.log_info("world_position = %s" % str(world_position)) self.log_info("cell_id = %s" % cell_id) self.log_info("select_point = %s" % str(select_point)) def _on_node_picker(self, a): self.vtk_interactor.SetPicker(self.node_picker) picker = self.node_picker world_position = picker.GetPickPosition() node_id = picker.GetPointId() select_point = picker.GetSelectionPoint() # get x,y pixel coordinate self.log_info("world_position = %s" % str(world_position)) self.log_info("node_id = %s" % node_id) self.log_info("select_point = %s" % str(select_point)) #def on_cell_picker(self): #self.log_command("on_cell_picker()") #picker = self.cell_picker #world_position = picker.GetPickPosition() #cell_id = picker.GetCellId() ##ds = picker.GetDataSet() #select_point = picker.GetSelectionPoint() # get x,y pixel coordinate #self.log_info("world_position = %s" % str(world_position)) #self.log_info("cell_id = %s" % cell_id) #self.log_info("select_point = %s" % str(select_point)) #self.log_info("data_set = %s" % ds) #def get_2d_point(self, point3d, view_matrix, #projection_matrix, #width, height): #view_projection_matrix = projection_matrix * view_matrix ## transform world to clipping coordinates #point3d = view_projection_matrix.multiply(point3d) #win_x = math.round(((point3d.getX() + 1) / 2.0) * width) ## we calculate -point3D.getY() because the screen Y axis is ## oriented top->down #win_y = math.round(((1 - point3d.getY()) / 2.0) * height) #return Point2D(win_x, win_y) #def get_3d_point(self, point2D, width, height, view_matrix, projection_matrix): #x = 2.0 * win_x / client_width - 1 #y = -2.0 * win_y / client_height + 1 #view_projection_inverse = inverse(projection_matrix * view_vatrix) #point3d = Point3D(x, y, 0) #return view_projection_inverse.multiply(point3d) def show_only(self, names): """ Show these actors only names : str, List[str] names to show If they're hidden, show them. If they're shown and shouldn't be, hide them. ..todo :: update the GeomeryProperties """ raise NotImplementedError('show_only') def hide_actors(self, except_names=None): """ Hide all the actors except_names : str, List[str], None list of names to exclude None : hide all ..note :: If an actor is hidden and in the except_names, it will still be hidden. ..todo :: update the GeomeryProperties """ if except_names is None: except_names = [] elif isinstance(except_names, string_types): except_names = [except_names] # hide everything but the main grid for key, actor in iteritems(self.geometry_actors): if key not in except_names: actor.VisibilityOff() self.hide_axes() self.hide_legend() #self.settings.set_background_color_to_white() def hide_axes(self, cids=None): """ ..todo :: support cids ..todo :: fix the coords """ for axis in self.axes.itervalues(): axis.VisibilityOff() self.corner_axis.EnabledOff() def show_axes(self, cids=None): """ ..todo :: support cids ..todo :: fix the coords """ for axis in self.axes.itervalues(): axis.VisibilityOn() self.corner_axis.EnabledOn() def on_take_screenshot(self, fname=None, magnify=None, show_msg=True): """ Take a screenshot of a current view and save as a file Parameters ---------- fname : str; default=None None : pop open a window str : bypass the popup window magnify : int; default=None None : use self.magnify int : resolution increase factor show_msg : bool; default=True log the command """ if fname is None or fname is False: filt = '' default_filename = '' title = '' if self.title is not None: title = self.title if self.out_filename is None: default_filename = '' if self.infile_name is not None: base, ext = os.path.splitext(os.path.basename(self.infile_name)) default_filename = self.infile_name default_filename = base + '.png' else: base, ext = os.path.splitext(os.path.basename(self.out_filename)) default_filename = title + '_' + base + '.png' file_types = ( 'PNG Image *.png (*.png);; ' 'JPEG Image *.jpg *.jpeg (*.jpg, *.jpeg);; ' 'TIFF Image *.tif *.tiff (*.tif, *.tiff);; ' 'BMP Image *.bmp (*.bmp);; ' 'PostScript Document *.ps (*.ps)') title = 'Choose a filename and type' fname, flt = getsavefilename(parent=self, caption=title, basedir='', filters=file_types, selectedfilter=filt, options=None) if fname in [None, '']: return #print("fname=%r" % fname) #print("flt=%r" % flt) else: base, ext = os.path.splitext(os.path.basename(fname)) if ext.lower() in ['png', 'jpg', 'jpeg', 'tif', 'tiff', 'bmp', 'ps']: flt = ext.lower() else: flt = 'png' if fname: render_large = vtk.vtkRenderLargeImage() if self.vtk_version[0] >= 6: render_large.SetInput(self.rend) else: render_large.SetInput(self.rend) line_widths0, point_sizes0, axes_actor = self._screenshot_setup(magnify, render_large) nam, ext = os.path.splitext(fname) ext = ext.lower() for nam, exts, obj in (('PostScript', ['.ps'], vtk.vtkPostScriptWriter), ("BMP", ['.bmp'], vtk.vtkBMPWriter), ('JPG', ['.jpg', '.jpeg'], vtk.vtkJPEGWriter), ("TIFF", ['.tif', '.tiff'], vtk.vtkTIFFWriter)): if flt == nam: fname = fname if ext in exts else fname + exts[0] writer = obj() break else: fname = fname if ext == '.png' else fname + '.png' writer = vtk.vtkPNGWriter() if self.vtk_version[0] >= 6: writer.SetInputConnection(render_large.GetOutputPort()) else: writer.SetInputConnection(render_large.GetOutputPort()) writer.SetFileName(fname) writer.Write() #self.log_info("Saved screenshot: " + fname) if show_msg: self.log_command('on_take_screenshot(%r, magnify=%s)' % (fname, magnify)) self._screenshot_teardown(line_widths0, point_sizes0, axes_actor) def _screenshot_setup(self, magnify, render_large): if magnify is None: magnify_min = 1 magnify = self.magnify if self.magnify > magnify_min else magnify_min else: magnify = magnify if not isinstance(magnify, integer_types): msg = 'magnify=%r type=%s' % (magnify, type(magnify)) raise TypeError(msg) self.settings.update_text_size(magnify=magnify) render_large.SetMagnification(magnify) # multiply linewidth by magnify line_widths0 = {} point_sizes0 = {} for key, geom_actor in iteritems(self.geometry_actors): if isinstance(geom_actor, vtk.vtkActor): prop = geom_actor.GetProperty() line_width0 = prop.GetLineWidth() point_size0 = prop.GetPointSize() line_widths0[key] = line_width0 point_sizes0[key] = point_size0 line_width = line_width0 * magnify point_size = point_size0 * magnify prop.SetLineWidth(line_width) prop.SetPointSize(point_size) prop.Modified() elif isinstance(geom_actor, vtk.vtkAxesActor): pass else: raise NotImplementedError(geom_actor) # hide corner axis axes_actor = self.corner_axis.GetOrientationMarker() axes_actor.SetVisibility(False) return line_widths0, point_sizes0, axes_actor def _screenshot_teardown(self, line_widths0, point_sizes0, axes_actor): self.settings.update_text_size(magnify=1.0) # show corner axes axes_actor.SetVisibility(True) # set linewidth back for key, geom_actor in iteritems(self.geometry_actors): if isinstance(geom_actor, vtk.vtkActor): prop = geom_actor.GetProperty() prop.SetLineWidth(line_widths0[key]) prop.SetPointSize(point_sizes0[key]) prop.Modified() elif isinstance(geom_actor, vtk.vtkAxesActor): pass else: raise NotImplementedError(geom_actor) def make_gif(self, gif_filename, scale, istep=None, min_value=None, max_value=None, animate_scale=True, animate_phase=False, animate_time=False, icase=None, icase_start=None, icase_end=None, icase_delta=None, time=2.0, animation_profile='0 to scale', nrepeat=0, fps=30, magnify=1, make_images=True, delete_images=False, make_gif=True, stop_animation=False, animate_in_gui=True): """ Makes an animated gif Parameters ---------- gif_filename : str path to the output gif & png folder scale : float the deflection scale factor; true scale istep : int; default=None the png file number (let's you pick a subset of images) useful for when you press ``Step`` stop_animation : bool; default=False stops the animation; don't make any images/gif animate_in_gui : bool; default=True animates the model; don't make any images/gif stop_animation overrides animate_in_gui animate_in_gui overrides make_gif Pick One -------- animate_scale : bool; default=True does a deflection plot (single subcase) animate_phase : bool; default=False does a complex deflection plot (single subcase) animate_time : bool; default=False does a deflection plot (multiple subcases) istep : int the png file number (let's you pick a subset of images) useful for when you press ``Step`` time : float; default=2.0 the runtime of the gif (seconds) fps : int; default=30 the frames/second Case Selection -------------- icase : int; default=None None : unused int : the result case to plot the deflection for active if animate_scale=True or animate_phase=True icase_start : int; default=None starting case id None : unused int : active if animate_time=True icase_end : int; default=None starting case id None : unused int : active if animate_time=True icase_delta : int; default=None step size None : unused int : active if animate_time=True Time Plot Options ----------------- max_value : float; default=None the max value on the plot min_value : float; default=None the min value on the plot Options ------- animation_profile : str; default='0 to scale' animation profile to follow '0 to Scale', '0 to Scale to 0', #'0 to Scale to -Scale to 0', '-Scale to Scale', '-scale to scale to -scale', nrepeat : int; default=0 0 : loop infinitely 1 : loop 1 time 2 : loop 2 times Final Control Options --------------------- make_images : bool; default=True make the images delete_images : bool; default=False cleanup the png files at the end make_gif : bool; default=True actually make the gif at the end Other local variables --------------------- duration : float frame time (seconds) For one sided data ------------------ - scales/phases should be one-sided - time should be one-sided - analysis_time should be one-sided - set onesided=True For two-sided data ------------------ - scales/phases should be one-sided - time should be two-sided - analysis_time should be one-sided - set onesided=False """ if stop_animation: return self.stop_animation() phases, icases, isteps, scales, analysis_time, onesided = setup_animation( scale, istep=istep, animate_scale=animate_scale, animate_phase=animate_phase, animate_time=animate_time, icase=icase, icase_start=icase_start, icase_end=icase_end, icase_delta=icase_delta, time=time, animation_profile=animation_profile, fps=fps) parent = self #animate_in_gui = True self.stop_animation() if len(icases) == 1: pass elif animate_in_gui: class vtkAnimationCallback(object): """ http://www.vtk.org/Wiki/VTK/Examples/Python/Animation """ def __init__(self): self.timer_count = 0 self.cycler = cycle(range(len(icases))) self.icase0 = -1 self.ncases = len(icases) def execute(self, obj, event): iren = obj i = self.timer_count % self.ncases #j = next(self.cycler) istep = isteps[i] icase = icases[i] scale = scales[i] phase = phases[i] if icase != self.icase0: #self.cycle_results(case=icase) parent.cycle_results_explicit(icase, explicit=True) try: parent.update_grid_by_icase_scale_phase(icase, scale, phase=phase) except AttributeError: parent.log_error('Invalid Case %i' % icase) parent.stop_animation() self.icase0 = icase parent.vtk_interactor.Render() self.timer_count += 1 # Sign up to receive TimerEvent callback = vtkAnimationCallback() observer_name = self.iren.AddObserver('TimerEvent', callback.execute) self.observers['TimerEvent'] = observer_name # total_time not needed # fps # -> frames_per_second = 1/fps delay = int(1. / fps * 1000) timer_id = self.iren.CreateRepeatingTimer(delay) # time in milliseconds return is_failed = True try: is_failed = self.make_gif_helper( gif_filename, icases, scales, phases=phases, isteps=isteps, max_value=max_value, min_value=min_value, time=time, analysis_time=analysis_time, fps=fps, magnify=magnify, onesided=onesided, nrepeat=nrepeat, make_images=make_images, delete_images=delete_images, make_gif=make_gif) except Exception as e: self.log_error(str(e)) raise #self.log_error(traceback.print_stack(f)) #self.log_error('\n' + ''.join(traceback.format_stack())) #traceback.print_exc(file=self.log_error) if not is_failed: msg = ( 'make_gif(%r, %s, istep=%s,\n' ' min_value=%s, max_value=%s,\n' ' animate_scale=%s, animate_phase=%s, animate_time=%s,\n' ' icase=%s, icase_start=%s, icase_end=%s, icase_delta=%s,\n' " time=%s, animation_profile=%r,\n" ' nrepeat=%s, fps=%s, magnify=%s,\n' ' make_images=%s, delete_images=%s, make_gif=%s, stop_animation=%s,\n' ' animate_in_gui=%s)\n' % ( gif_filename, scale, istep, min_value, max_value, animate_scale, animate_phase, animate_time, icase, icase_start, icase_end, icase_delta, time, animation_profile, nrepeat, fps, magnify, make_images, delete_images, make_gif, stop_animation, animate_in_gui) ) self.log_command(msg) return is_failed def stop_animation(self): """removes the animation timer""" is_failed = False if 'TimerEvent' in self.observers: observer_name = self.observers['TimerEvent'] self.iren.RemoveObserver(observer_name) del self.observers['TimerEvent'] self.setup_mouse_buttons(mode='default', force=True) return is_failed def make_gif_helper(self, gif_filename, icases, scales, phases=None, isteps=None, max_value=None, min_value=None, time=2.0, analysis_time=2.0, fps=30, magnify=1, onesided=True, nrepeat=0, make_images=True, delete_images=False, make_gif=True): """ Makes an animated gif Parameters ---------- gif_filename : str path to the output gif & png folder icases : int / List[int] the result case to plot the deflection for scales : List[float] List[float] : the deflection scale factors; true scale phases : List[float]; default=None List[float] : the phase angles (degrees) None -> animate scale max_value : float; default=None the max value on the plot (not supported) min_value : float; default=None the min value on the plot (not supported) isteps : List[int] the png file numbers (let's you pick a subset of images) useful for when you press ``Step`` time : float; default=2.0 the runtime of the gif (seconds) analysis_time : float; default=2.0 The time we actually need to simulate (seconds). We don't need to take extra pictures if they're just copies. fps : int; default=30 the frames/second Options ------- onesided : bool; default=True should the animation go up and back down nrepeat : int; default=0 0 : loop infinitely 1 : loop 1 time 2 : loop 2 times Final Control Options --------------------- make_images : bool; default=True make the images delete_images : bool; default=False cleanup the png files at the end make_gif : bool; default=True actually make the gif at the end Other local variables --------------------- duration : float frame time (seconds) For one sided data ------------------ - scales/phases should be one-sided - time should be one-sided - analysis_time should be one-sided - set onesided=True For two-sided data ------------------ - scales/phases should be one-sided - time should be two-sided - analysis_time should be one-sided - set onesided=False """ assert fps >= 1, fps nframes = ceil(analysis_time * fps) assert nframes >= 2, nframes duration = time / nframes nframes = int(nframes) png_dirname = os.path.dirname(os.path.abspath(gif_filename)) if not os.path.exists(png_dirname): os.makedirs(png_dirname) phases, icases, isteps, scales = update_animation_inputs( phases, icases, isteps, scales, analysis_time, fps) if gif_filename is not None: png_filenames = [] fmt = gif_filename[:-4] + '_%%0%ii.png' % (len(str(nframes))) icase0 = -1 is_failed = True if make_images: for istep, icase, scale, phase in zip(isteps, icases, scales, phases): if icase != icase0: #self.cycle_results(case=icase) self.cycle_results_explicit(icase, explicit=True, min_value=min_value, max_value=max_value) self.update_grid_by_icase_scale_phase(icase, scale, phase=phase) if gif_filename is not None: png_filename = fmt % istep self.on_take_screenshot(fname=png_filename, magnify=magnify) png_filenames.append(png_filename) else: for istep in isteps: png_filename = fmt % istep png_filenames.append(png_filename) assert os.path.exists(png_filename), 'png_filename=%s' % png_filename if png_filenames: is_failed = write_gif( gif_filename, png_filenames, time=time, onesided=onesided, nrepeat=nrepeat, delete_images=delete_images, make_gif=make_gif) return is_failed def add_geometry(self): """ #(N,) for stress, x-disp #(N,3) for warp vectors/glyphs grid_result = vtk.vtkFloatArray() point_data = self.grid.GetPointData() cell_data = self.grid.GetCellData() self.grid.GetCellData().SetScalars(grid_result) self.grid.GetPointData().SetScalars(grid_result) self.grid_mapper <-input-> self.grid vtkDataSetMapper() <-input-> vtkUnstructuredGrid() self.grid_mapper <--map--> self.geom_actor <-add-> self.rend vtkDataSetMapper() <--map--> vtkActor() <-add-> vtkRenderer() """ if self.is_groups: # solid_bending: eids 1-182 self._setup_element_mask() #eids = np.arange(172) #eids = arange(172) #self.update_element_mask(eids) else: self.grid_selected = self.grid #print('grid_selected =', self.grid_selected) self.grid_mapper = vtk.vtkDataSetMapper() if self.vtk_version[0] <= 5: #self.grid_mapper.SetInput(self.grid_selected) ## OLD self.grid_mapper.SetInputConnection(self.grid_selected.GetProducerPort()) else: self.grid_mapper.SetInputData(self.grid_selected) #if 0: #self.warp_filter = vtk.vtkWarpVector() #self.warp_filter.SetScaleFactor(50.0) #self.warp_filter.SetInput(self.grid_mapper.GetUnstructuredGridOutput()) #self.geom_filter = vtk.vtkGeometryFilter() #self.geom_filter.SetInput(self.warp_filter.GetUnstructuredGridOutput()) #self.geom_mapper = vtk.vtkPolyDataMapper() #self.geom_actor.setMapper(self.geom_mapper) #if 0: #from vtk.numpy_interface import algorithms #arrow = vtk.vtkArrowSource() #arrow.PickableOff() #self.glyph_transform = vtk.vtkTransform() #self.glyph_transform_filter = vtk.vtkTransformPolyDataFilter() #self.glyph_transform_filter.SetInputConnection(arrow.GetOutputPort()) #self.glyph_transform_filter.SetTransform(self.glyph_transform) #self.glyph = vtk.vtkGlyph3D() #self.glyph.setInput(xxx) #self.glyph.SetSource(self.glyph_transform_filter.GetOutput()) #self.glyph.SetVectorModeToUseVector() #self.glyph.SetColorModeToColorByVector() #self.glyph.SetScaleModeToScaleByVector() #self.glyph.SetScaleFactor(1.0) #self.append_filter = vtk.vtkAppendFilter() #self.append_filter.AddInputConnection(self.grid.GetOutput()) #self.warpVector = vtk.vtkWarpVector() #self.warpVector.SetInput(self.grid_mapper.GetUnstructuredGridOutput()) #grid_mapper.SetInput(Filter.GetOutput()) self.geom_actor = vtk.vtkLODActor() self.geom_actor.DragableOff() self.geom_actor.SetMapper(self.grid_mapper) #geometryActor.AddPosition(2, 0, 2) #geometryActor.GetProperty().SetDiffuseColor(0, 0, 1) # blue #self.geom_actor.GetProperty().SetDiffuseColor(1, 0, 0) # red #if 0: #id_filter = vtk.vtkIdFilter() #ids = np.array([1, 2, 3], dtype='int32') #id_array = numpy_to_vtk( #num_array=ids, #deep=True, #array_type=vtk.VTK_INT, #) #id_filter.SetCellIds(id_array.GetOutputPort()) #id_filter.CellIdsOff() #self.grid_mapper.SetInputConnection(id_filter.GetOutputPort()) self.rend.AddActor(self.geom_actor) self.build_glyph() def build_glyph(self): """builds the glyph actor""" grid = self.grid glyphs = vtk.vtkGlyph3D() #if filter_small_forces: #glyphs.SetRange(0.5, 1.) glyphs.SetVectorModeToUseVector() #apply_color_to_glyph = False #if apply_color_to_glyph: #glyphs.SetScaleModeToScaleByScalar() glyphs.SetScaleModeToScaleByVector() glyphs.SetColorModeToColorByScale() #glyphs.SetColorModeToColorByScalar() # super tiny #glyphs.SetColorModeToColorByVector() # super tiny glyphs.ScalingOn() glyphs.ClampingOn() #glyphs.Update() glyph_source = vtk.vtkArrowSource() #glyph_source.InvertOn() # flip this arrow direction if self.vtk_version[0] == 5: glyphs.SetInput(grid) elif self.vtk_version[0] in [6, 7, 8]: glyphs.SetInputData(grid) else: raise NotImplementedError(vtk.VTK_VERSION) glyphs.SetSourceConnection(glyph_source.GetOutputPort()) #glyphs.SetScaleModeToDataScalingOff() #glyphs.SetScaleFactor(10.0) # bwb #glyphs.SetScaleFactor(1.0) # solid-bending glyph_mapper = vtk.vtkPolyDataMapper() glyph_mapper.SetInputConnection(glyphs.GetOutputPort()) glyph_mapper.ScalarVisibilityOff() arrow_actor = vtk.vtkLODActor() arrow_actor.SetMapper(glyph_mapper) prop = arrow_actor.GetProperty() prop.SetColor(1., 0., 0.) self.rend.AddActor(arrow_actor) #self.grid.GetPointData().SetActiveVectors(None) arrow_actor.SetVisibility(False) self.glyph_source = glyph_source self.glyphs = glyphs self.glyph_mapper = glyph_mapper self.arrow_actor = arrow_actor def _add_alt_actors(self, grids_dict, names_to_ignore=None): if names_to_ignore is None: names_to_ignore = ['main'] names = set(list(grids_dict.keys())) names_old = set(list(self.geometry_actors.keys())) names_old = names_old - set(names_to_ignore) #print('names_old1 =', names_old) #names_to_clear = names_old - names #self._remove_alt_actors(names_to_clear) #print('names_old2 =', names_old) #print('names =', names) for name in names: #print('adding %s' % name) grid = grids_dict[name] self._add_alt_geometry(grid, name) def _remove_alt_actors(self, names=None): if names is None: names = list(self.geometry_actors.keys()) names.remove('main') for name in names: actor = self.geometry_actors[name] self.rend.RemoveActor(actor) del actor def _add_alt_geometry(self, grid, name, color=None, line_width=None, opacity=None, representation=None): """ NOTE: color, line_width, opacity are ignored if name already exists """ is_pickable = self.geometry_properties[name].is_pickable quad_mapper = vtk.vtkDataSetMapper() if name in self.geometry_actors: alt_geometry_actor = self.geometry_actors[name] if self.vtk_version[0] >= 6: alt_geometry_actor.GetMapper().SetInputData(grid) else: alt_geometry_actor.GetMapper().SetInput(grid) else: if self.vtk_version[0] >= 6: quad_mapper.SetInputData(grid) else: quad_mapper.SetInput(grid) alt_geometry_actor = vtk.vtkActor() if not is_pickable: alt_geometry_actor.PickableOff() alt_geometry_actor.DragableOff() alt_geometry_actor.SetMapper(quad_mapper) self.geometry_actors[name] = alt_geometry_actor #geometryActor.AddPosition(2, 0, 2) if name in self.geometry_properties: geom = self.geometry_properties[name] else: geom = AltGeometry(self, name, color=color, line_width=line_width, opacity=opacity, representation=representation) self.geometry_properties[name] = geom color = geom.color_float opacity = geom.opacity point_size = geom.point_size representation = geom.representation line_width = geom.line_width #print('color_2014[%s] = %s' % (name, str(color))) assert isinstance(color[0], float), color assert color[0] <= 1.0, color prop = alt_geometry_actor.GetProperty() #prop.SetInterpolationToFlat() # 0 #prop.SetInterpolationToGouraud() # 1 #prop.SetInterpolationToPhong() # 2 prop.SetDiffuseColor(color) prop.SetOpacity(opacity) #prop.Update() #print('prop.GetInterpolation()', prop.GetInterpolation()) # 1 if representation == 'point': prop.SetRepresentationToPoints() prop.SetPointSize(point_size) elif representation in ['surface', 'toggle']: prop.SetRepresentationToSurface() prop.SetLineWidth(line_width) elif representation == 'wire': prop.SetRepresentationToWireframe() prop.SetLineWidth(line_width) self.rend.AddActor(alt_geometry_actor) vtk.vtkPolyDataMapper().SetResolveCoincidentTopologyToPolygonOffset() if geom.is_visible: alt_geometry_actor.VisibilityOn() else: alt_geometry_actor.VisibilityOff() #print('current_actors = ', self.geometry_actors.keys()) if hasattr(grid, 'Update'): grid.Update() alt_geometry_actor.Modified() def on_update_scalar_bar(self, title, min_value, max_value, data_format): self.title = str(title) self.min_value = float(min_value) self.max_value = float(max_value) try: data_format % 1 except: msg = ("failed applying the data formatter format=%r and " "should be of the form: '%i', '%8f', '%.2f', '%e', etc.") self.log_error(msg) return self.data_format = data_format self.log_command('on_update_scalar_bar(%r, %r, %r, %r)' % ( title, min_value, max_value, data_format)) def ResetCamera(self): self.GetCamera().ResetCamera() def GetCamera(self): return self.rend.GetActiveCamera() def update_camera(self, code): camera = self.GetCamera() #print("code =", code) if code == '+x': # set x-axis # +z up # +y right # looking forward camera.SetFocalPoint(0., 0., 0.) camera.SetViewUp(0., 0., 1.) camera.SetPosition(1., 0., 0.) elif code == '-x': # set x-axis # +z up # +y to the left (right wing) # looking aft camera.SetFocalPoint(0., 0., 0.) camera.SetViewUp(0., 0., 1.) camera.SetPosition(-1., 0., 0.) elif code == '+y': # set y-axis # +z up # +x aft to left # view from right wing camera.SetFocalPoint(0., 0., 0.) camera.SetViewUp(0., 0., 1.) camera.SetPosition(0., 1., 0.) elif code == '-y': # set y-axis # +z up # +x aft to right # view from left wing camera.SetFocalPoint(0., 0., 0.) camera.SetViewUp(0., 0., 1.) camera.SetPosition(0., -1., 0.) elif code == '+z': # set z-axis # +x aft # +y up (right wing up) # top view camera.SetFocalPoint(0., 0., 0.) camera.SetViewUp(0., 1., 0.) camera.SetPosition(0., 0., 1.) elif code == '-z': # set z-axis # +x aft # -y down (left wing up) # bottom view camera.SetFocalPoint(0., 0., 0.) camera.SetViewUp(0., -1., 0.) camera.SetPosition(0., 0., -1.) else: self.log_error('invalid camera code...%r' % code) return self._update_camera(camera) self.rend.ResetCamera() self.log_command('update_camera(%r)' % code) def _simulate_key_press(self, key): """ A little hack method that simulates pressing the key for the VTK interactor. There is no easy way to instruct VTK to e.g. change mouse style to 'trackball' (as by pressing 't' key), (see http://public.kitware.com/pipermail/vtkusers/2011-November/119996.html) therefore we trick VTK to think that a key has been pressed. Parameters ---------- key : str a key that VTK should be informed about, e.g. 't' """ print("key_key_press = ", key) if key == 'f': # change focal point #print('focal_point!') return self.vtk_interactor._Iren.SetEventInformation(0, 0, 0, 0, key, 0, None) self.vtk_interactor._Iren.KeyPressEvent() self.vtk_interactor._Iren.CharEvent() #if key in ['y', 'z', 'X', 'Y', 'Z']: #self.update_camera(key) def _set_results(self, form, cases): assert len(cases) > 0, cases if isinstance(cases, OrderedDict): self.case_keys = list(cases.keys()) else: self.case_keys = sorted(cases.keys()) assert isinstance(cases, dict), type(cases) self.result_cases = cases if len(self.case_keys) > 1: self.icase = -1 self.ncases = len(self.result_cases) # number of keys in dictionary elif len(self.case_keys) == 1: self.icase = -1 self.ncases = 1 else: self.icase = -1 self.ncases = 0 self.set_form(form) def _finish_results_io2(self, form, cases, reset_labels=True): """ Adds results to the Sidebar Parameters ---------- form : List[pairs] There are two types of pairs header_pair : (str, None, List[pair]) defines a heading str : the sidebar label None : flag that there are sub-results List[pair] : more header/result pairs result_pair : (str, int, List[]) str : the sidebar label int : the case id List[] : flag that there are no sub-results cases : dict[case_id] = result case_id : int the case id result : GuiResult the class that stores the result reset_labels : bool; default=True should the label actors be reset form = [ 'Model', None, [ ['NodeID', 0, []], ['ElementID', 1, []] ['PropertyID', 2, []] ], 'time=0.0', None, [ ['Stress', 3, []], ['Displacement', 4, []] ], 'time=1.0', None, [ ['Stress', 5, []], ['Displacement', 6, []] ], ] cases = { 0 : GuiResult(...), # NodeID 1 : GuiResult(...), # ElementID 2 : GuiResult(...), # PropertyID 3 : GuiResult(...), # Stress; t=0.0 4 : GuiResult(...), # Displacement; t=0.0 5 : GuiResult(...), # Stress; t=1.0 6 : GuiResult(...), # Displacement; t=1.0 } case_keys = [0, 1, 2, 3, 4, 5, 6] """ self.turn_text_on() self._set_results(form, cases) # assert len(cases) > 0, cases # if isinstance(cases, OrderedDict): # self.case_keys = cases.keys() # else: # self.case_keys = sorted(cases.keys()) # assert isinstance(cases, dict), type(cases) self.on_update_geometry_properties(self.geometry_properties, write_log=False) # self.result_cases = cases #print("cases =", cases) #print("case_keys =", self.case_keys) self.reset_labels(reset_minus1=reset_labels) self.cycle_results_explicit() # start at nCase=0 if self.ncases: self.scalarBar.VisibilityOn() self.scalarBar.Modified() #data = [ # ('A', []), # ('B', []), # ('C', []), #] data = [] for key in self.case_keys: assert isinstance(key, integer_types), key obj, (i, name) = self.result_cases[key] t = (i, []) data.append(t) self.res_widget.update_results(form, self.name) key = self.case_keys[0] location = self.get_case_location(key) method = 'centroid' if location else 'nodal' data2 = [(method, None, [])] self.res_widget.update_methods(data2) if self.is_groups: if self.element_ids is None: raise RuntimeError('implement self.element_ids for this format') #eids = np.arange(172) #eids = [] #self.hide_elements_mask(eids) elements_pound = self.element_ids[-1] main_group = Group( 'main', '', elements_pound, editable=False) main_group.element_ids = self.element_ids self.groups['main'] = main_group self.post_group(main_group) #self.show_elements_mask(np.arange(self.nelements)) def get_result_by_cell_id(self, cell_id, world_position, icase=None): """should handle multiple cell_ids""" if icase is None: icase = self.icase case_key = self.case_keys[icase] # int for object result_name = self.result_name case = self.result_cases[case_key] (obj, (i, res_name)) = case subcase_id = obj.subcase_id case = obj.get_result(i, res_name) try: result_values = case[cell_id] except IndexError: msg = ('case[cell_id] is out of bounds; length=%s\n' 'result_name=%r cell_id=%r case_key=%r\n' % ( len(case), result_name, cell_id, case_key)) raise IndexError(msg) cell = self.grid_selected.GetCell(cell_id) nnodes = cell.GetNumberOfPoints() points = cell.GetPoints() cell_type = cell.GetCellType() if cell_type in [5, 9, 22, 23, 28]: # CTRIA3, CQUAD4, CTRIA6, CQUAD8, CQUAD node_xyz = np.zeros((nnodes, 3), dtype='float32') for ipoint in range(nnodes): point = points.GetPoint(ipoint) node_xyz[ipoint, :] = point xyz = node_xyz.mean(axis=0) elif cell_type in [10, 12, 13, 14]: # CTETRA4, CHEXA8, CPENTA6, CPYRAM5 # TODO: No idea how to get the center of the face # vs. a point on a face that's not exposed #faces = cell.GetFaces() #nfaces = cell.GetNumberOfFaces() #for iface in range(nfaces): #face = cell.GetFace(iface) #points = face.GetPoints() #faces xyz = world_position elif cell_type in [24, 25, 26, 27]: # CTETRA10, CHEXA20, CPENTA15, CPYRAM13 xyz = world_position elif cell_type in [3]: # CBAR, CBEAM, CELASx, CDAMPx, CBUSHx node_xyz = np.zeros((nnodes, 3), dtype='float32') for ipoint in range(nnodes): point = points.GetPoint(ipoint) node_xyz[ipoint, :] = point xyz = node_xyz.mean(axis=0) elif cell_type in [21]: # CBEND # 21-QuadraticEdge node_xyz = np.zeros((nnodes, 3), dtype='float32') for ipoint in range(nnodes): point = points.GetPoint(ipoint) node_xyz[ipoint, :] = point xyz = node_xyz.mean(axis=0) else: #self.log.error(msg) msg = 'cell_type=%s nnodes=%s; icase=%s result_values=%s' % ( cell_type, nnodes, icase, result_values) self.log.error(msg) #VTK_LINE = 3 #VTK_TRIANGLE = 5 #VTK_QUADRATIC_TRIANGLE = 22 #VTK_QUAD = 9 #VTK_QUADRATIC_QUAD = 23 #VTK_TETRA = 10 #VTK_QUADRATIC_TETRA = 24 #VTK_WEDGE = 13 #VTK_QUADRATIC_WEDGE = 26 #VTK_HEXAHEDRON = 12 #VTK_QUADRATIC_HEXAHEDRON = 25 #VTK_PYRAMID = 14 #VTK_QUADRATIC_PYRAMID = 27 raise NotImplementedError(msg) return result_name, result_values, xyz def cell_centroid(self, cell_id): """gets the cell centroid""" cell = self.grid_selected.GetCell(cell_id) nnodes = cell.GetNumberOfPoints() points = cell.GetPoints() centroid = np.zeros(3, dtype='float32') for ipoint in range(nnodes): point = np.array(points.GetPoint(ipoint), dtype='float32') centroid += point centroid /= nnodes return centroid def get_result_by_xyz_cell_id(self, node_xyz, cell_id): """won't handle multiple cell_ids/node_xyz""" case_key = self.case_keys[self.icase] result_name = self.result_name cell = self.grid_selected.GetCell(cell_id) nnodes = cell.GetNumberOfPoints() points = cell.GetPoints() #node_xyz = array(node_xyz, dtype='float32') #point0 = array(points.GetPoint(0), dtype='float32') #dist_min = norm(point0 - node_xyz) point0 = points.GetPoint(0) dist_min = vtk.vtkMath.Distance2BetweenPoints(point0, node_xyz) point_min = point0 imin = 0 for ipoint in range(1, nnodes): #point = array(points.GetPoint(ipoint), dtype='float32') #dist = norm(point - node_xyz) point = points.GetPoint(ipoint) dist = vtk.vtkMath.Distance2BetweenPoints(point, node_xyz) if dist < dist_min: dist_min = dist imin = ipoint point_min = point node_id = cell.GetPointId(imin) xyz = np.array(point_min, dtype='float32') case = self.result_cases[case_key] assert isinstance(case_key, integer_types), case_key (obj, (i, res_name)) = case subcase_id = obj.subcase_id case = obj.get_result(i, res_name) result_values = case[node_id] assert not isinstance(xyz, int), xyz return result_name, result_values, node_id, xyz @property def result_name(self): """ creates the self.result_name variable .. python :: #if len(key) == 5: #(subcase_id, result_type, vector_size, location, data_format) = key #elif len(key) == 6: #(subcase_id, j, result_type, vector_size, location, data_format) = key else: (subcase_id, j, result_type, vector_size, location, data_format, label2) = key """ # case_key = (1, 'ElementID', 1, 'centroid', '%.0f') case_key = self.case_keys[self.icase] assert isinstance(case_key, integer_types), case_key obj, (i, name) = self.result_cases[case_key] return name def finish_io(self, cases): self.result_cases = cases self.case_keys = sorted(cases.keys()) #print("case_keys = ", self.case_keys) if len(self.result_cases) == 0: self.ncases = 1 self.icase = 0 elif len(self.result_cases) == 1: self.ncases = 1 self.icase = 0 else: self.ncases = len(self.result_cases) - 1 # number of keys in dictionary self.icase = -1 self.cycle_results() # start at nCase=0 if self.ncases: self.scalarBar.VisibilityOn() self.scalarBar.Modified() def _finish_results_io(self, cases): self.result_cases = cases self.case_keys = sorted(cases.keys()) if len(self.case_keys) > 1: self.icase = -1 self.ncases = len(self.result_cases) # number of keys in dictionary elif len(self.case_keys) == 1: self.icase = -1 self.ncases = 1 else: self.icase = -1 self.ncases = 0 self.reset_labels() self.cycle_results_explicit() # start at nCase=0 if self.ncases: self.scalarBar.VisibilityOn() self.scalarBar.Modified() #data = [ # ('A',[]), # ('B',[]), # ('C',[]), #] #self.case_keys = [ # (1, 'ElementID', 1, 'centroid', '%.0f'), (1, 'Region', 1, 'centroid', '%.0f') #] data = [] for i, key in enumerate(self.case_keys): t = (key[1], i, []) data.append(t) i += 1 self.res_widget.update_results(data) data2 = [('node/centroid', None, [])] self.res_widget.update_methods(data2) def clear_application_log(self, force=False): """ Clears the application log Parameters ---------- force : bool; default=False clears the dialog without asking """ # popup menu if force: self.log_widget.clear() self.log_command('clear_application_log(force=%s)' % force) else: widget = QWidget() title = 'Clear Application Log' msg = 'Are you sure you want to clear the Application Log?' result = QMessageBox.question(widget, title, msg, QMessageBox.Yes | QMessageBox.No, QMessageBox.No) if result == QMessageBox.Yes: self.log_widget.clear() self.log_command('clear_application_log(force=%s)' % force) def delete_actor(self, name): """deletes an actor and associated properties""" if name != 'main': if name in self.geometry_actors: actor = self.geometry_actors[name] self.rend.RemoveActor(actor) del self.geometry_actors[name] if name in self.geometry_properties: prop = self.geometry_properties[name] del self.geometry_properties[name] self.Render() def reset_labels(self, reset_minus1=True): """ Wipe all labels and regenerate the key slots based on the case keys. This is used when changing the model. """ self._remove_labels() reset_minus1 = True # new geometry if reset_minus1: self.label_actors = {-1 : []} else: for idi in self.label_actors: if idi == -1: continue self.label_actors[idi] = [] self.label_ids = {} #self.case_keys = [ #(1, 'ElementID', 1, 'centroid', '%.0f'), #(1, 'Region', 1, 'centroid', '%.0f') #] for icase in self.case_keys: #result_name = self.get_result_name(icase) self.label_actors[icase] = [] self.label_ids[icase] = set([]) #print(self.label_actors) #print(self.label_ids) def _remove_labels(self): """ Remove all labels from the current result case. This happens when the user explictly selects the clear label button. """ if len(self.label_actors) == 0: self.log.warning('No actors to remove') return # existing geometry for icase, actors in iteritems(self.label_actors): if icase == -1: continue for actor in actors: self.rend.RemoveActor(actor) del actor self.label_actors[icase] = [] self.label_ids[icase] = set([]) def clear_labels(self): """ This clears out all labels from all result cases. """ if len(self.label_actors) == 0: self.log.warning('No actors to clear') return # existing geometry #icase = self.case_keys[self.icase] icase = self.icase result_name = self.result_name actors = self.label_actors[icase] for actor in actors: self.rend.RemoveActor(actor) del actor self.label_actors[icase] = [] self.label_ids[icase] = set([]) def resize_labels(self, case_keys=None, show_msg=True): """ This resizes labels for all result cases. TODO: not done... """ if case_keys is None: names = 'None) # None -> all' case_keys = sorted(self.label_actors.keys()) else: mid = '%s,' * len(case_keys) names = '[' + mid[:-1] + '])' count = 0 for icase in case_keys: actors = self.label_actors[icase] for actor in actors: actor.VisibilityOff() count += 1 if count and show_msg: self.log_command('resize_labels(%s)' % names) def hide_labels(self, case_keys=None, show_msg=True): if case_keys is None: names = 'None) # None -> all' case_keys = sorted(self.label_actors.keys()) else: mid = '%s,' * len(case_keys) names = '[' + mid[:-1] + '])' count = 0 for icase in case_keys: actors = self.label_actors[icase] for actor in actors: actor.VisibilityOff() #prop = actor.GetProperty() count += 1 if count and show_msg: self.log_command('hide_labels(%s)' % names) def show_labels(self, case_keys=None, show_msg=True): if case_keys is None: names = 'None) # None -> all' case_keys = sorted(self.label_actors.keys()) else: mid = '%s,' * len(case_keys) names = mid[:-1] % case_keys + ')' count = 0 for icase in case_keys: try: actors = self.label_actors[icase] except KeyError: msg = 'Cant find label_actors for icase=%r; keys=%s' % ( icase, self.label_actors.keys()) self.log.error(msg) continue for actor in actors: actor.VisibilityOn() count += 1 if count and show_msg: # yes the ) is intentionally left off because it's already been added self.log_command('show_labels(%s)' % names) def update_scalar_bar(self, title, min_value, max_value, norm_value, data_format, nlabels=None, labelsize=None, ncolors=None, colormap='jet', is_low_to_high=True, is_horizontal=True, is_shown=True): """ Updates the Scalar Bar Parameters ---------- title : str the scalar bar title min_value : float the blue value max_value : the red value data_format : str '%g','%f','%i', etc. nlabels : int (default=None -> auto) the number of labels labelsize : int (default=None -> auto) the label size ncolors : int (default=None -> auto) the number of colors colormap : varies str : the name ndarray : (N, 3) float ndarry red-green-blue array is_low_to_high : bool; default=True flips the order of the RGB points is_horizontal : bool; default=True makes the scalar bar horizontal is_shown : bool show the scalar bar """ #print("update_scalar_bar min=%s max=%s norm=%s" % (min_value, max_value, norm_value)) self.scalar_bar.update(title, min_value, max_value, norm_value, data_format, nlabels=nlabels, labelsize=labelsize, ncolors=ncolors, colormap=colormap, is_low_to_high=is_low_to_high, is_horizontal=is_horizontal, is_shown=is_shown) #--------------------------------------------------------------------------------------- # CAMERA MENU def view_camera(self): set_camera_menu(self) #def _apply_camera(self, data): #name = data['name'] #self.cameras = deepcopy(data['cameras']) #self.on_set_camera(name) def on_set_camera(self, name, show_log=True): camera_data = self.cameras[name] #position, clip_range, focal_point, view_up, distance = camera_data self.on_set_camera_data(camera_data, show_log=show_log) def get_camera_data(self): camera = self.rend.GetActiveCamera() position = camera.GetPosition() focal_point = camera.GetFocalPoint() view_angle = camera.GetViewAngle() view_up = camera.GetViewUp() clip_range = camera.GetClippingRange() # TODO: do I need this??? parallel_scale = camera.GetParallelScale() # TODO: do I need this??? #parallel_proj = GetParralelProjection() parallel_proj = 32. distance = camera.GetDistance() # clip_range, view_up, distance camera_data = [ position, focal_point, view_angle, view_up, clip_range, parallel_scale, parallel_proj, distance ] return camera_data def on_set_camera_data(self, camera_data, show_log=True): """ Sets the current camera Parameters ---------- position : (float, float, float) where am I is xyz space focal_point : (float, float, float) where am I looking view_angle : float field of view (angle); perspective only? view_up : (float, float, float) up on the screen vector clip_range : (float, float) start/end distance from camera where clipping starts parallel_scale : float ??? parallel_projection : bool (0/1) flag? TODO: not used distance : float distance to the camera i_vector = focal_point - position j'_vector = view_up use: i x j' -> k k x i -> j or it's like k' """ #position, clip_range, focal_point, view_up, distance = camera_data (position, focal_point, view_angle, view_up, clip_range, parallel_scale, parallel_proj, distance) = camera_data camera = self.rend.GetActiveCamera() camera.SetPosition(position) camera.SetFocalPoint(focal_point) camera.SetViewAngle(view_angle) camera.SetViewUp(view_up) camera.SetClippingRange(clip_range) camera.SetParallelScale(parallel_scale) #parallel_proj camera.SetDistance(distance) camera.Modified() self.vtk_interactor.Render() if show_log: self.log_command( 'on_set_camera_data([%s, %s, %s, %s, %s, %s, %s, %s])' % (position, focal_point, view_angle, view_up, clip_range, parallel_scale, parallel_proj, distance)) #--------------------------------------------------------------------------------------- # PICKER @property def node_picker_size(self): """Gets the node picker size""" return self.node_picker.GetTolerance() @node_picker_size.setter def node_picker_size(self, size): """Sets the node picker size""" assert size >= 0., size self.node_picker.SetTolerance(size) @property def element_picker_size(self): """Gets the element picker size""" return self.cell_picker.GetTolerance() @element_picker_size.setter def element_picker_size(self, size): """Sets the element picker size""" assert size >= 0., size self.cell_picker.SetTolerance(size) #--------------------------------------------------------------------------------------- def set_preferences_menu(self): """ Opens a dialog box to set: +--------+----------+ | Min | Float | +--------+----------+ """ set_preferences_menu(self) #--------------------------------------------------------------------------------------- # CLIPPING MENU def set_clipping(self): """ Opens a dialog box to set: +--------+----------+ | Min | Float | +--------+----------+ | Max | Float | +--------+----------+ """ set_clipping_menu(self) def _apply_clipping(self, data): min_clip = data['clipping_min'] max_clip = data['clipping_max'] self.on_update_clipping(min_clip, max_clip) def on_update_clipping(self, min_clip=None, max_clip=None): camera = self.GetCamera() _min_clip, _max_clip = camera.GetClippingRange() if min_clip is None: min_clip = _min_clip if max_clip is None: max_clip = _max_clip camera.SetClippingRange(min_clip, max_clip) self.log_command('self.on_update_clipping(min_value=%s, max_clip=%s)' % (min_clip, max_clip)) #--------------------------------------------------------------------------------------- def on_set_anti_aliasing(self, scale=0): assert isinstance(scale, int), 'scale=%r; type=%r' % (scale, type(scale)) renwin = self.render_window renwin.LineSmoothingOn() renwin.PolygonSmoothingOn() renwin.PointSmoothingOn() renwin.SetMultiSamples(scale) self.vtk_interactor.Render() self.log_command('on_set_anti_aliasing(%r)' % (scale)) #--------------------------------------------------------------------------------------- # LEGEND MENU def set_legend(self): """ Opens a dialog box to set: +--------+----------+ | Name | String | +--------+----------+ | Min | Float | +--------+----------+ | Max | Float | +--------+----------+ | Format | pyString | +--------+----------+ """ set_legend_menu(self) def update_legend(self, icase, name, min_value, max_value, data_format, scale, phase, nlabels, labelsize, ncolors, colormap, is_low_to_high, is_horizontal_scalar_bar): if not self._legend_window_shown: return self._legend_window._updated_legend = True key = self.case_keys[icase] assert isinstance(key, integer_types), key (obj, (i, name)) = self.result_cases[key] #subcase_id = obj.subcase_id #case = obj.get_result(i, name) #result_type = obj.get_title(i, name) #vector_size = obj.get_vector_size(i, name) #location = obj.get_location(i, name) #data_format = obj.get_data_format(i, name) #scale = obj.get_scale(i, name) #label2 = obj.get_header(i, name) default_data_format = obj.get_default_data_format(i, name) default_min, default_max = obj.get_default_min_max(i, name) default_scale = obj.get_default_scale(i, name) default_title = obj.get_default_title(i, name) default_phase = obj.get_default_phase(i, name) out_labels = obj.get_default_nlabels_labelsize_ncolors_colormap(i, name) default_nlabels, default_labelsize, default_ncolors, default_colormap = out_labels is_normals = obj.is_normal_result(i, name) assert isinstance(scale, float), 'scale=%s' % scale self._legend_window.update_legend( icase, name, min_value, max_value, data_format, scale, phase, nlabels, labelsize, ncolors, colormap, default_title, default_min, default_max, default_data_format, default_scale, default_phase, default_nlabels, default_labelsize, default_ncolors, default_colormap, is_low_to_high, is_horizontal_scalar_bar, is_normals, font_size=self.font_size) #self.scalar_bar.set_visibility(self._legend_shown) #self.vtk_interactor.Render() def _apply_legend(self, data): title = data['name'] min_value = data['min'] max_value = data['max'] scale = data['scale'] phase = data['phase'] data_format = data['format'] is_low_to_high = data['is_low_to_high'] is_discrete = data['is_discrete'] is_horizontal = data['is_horizontal'] is_shown = data['is_shown'] nlabels = data['nlabels'] labelsize = data['labelsize'] ncolors = data['ncolors'] colormap = data['colormap'] #print('is_shown1 =', is_shown) self.on_update_legend(title=title, min_value=min_value, max_value=max_value, scale=scale, phase=phase, data_format=data_format, is_low_to_high=is_low_to_high, is_discrete=is_discrete, is_horizontal=is_horizontal, nlabels=nlabels, labelsize=labelsize, ncolors=ncolors, colormap=colormap, is_shown=is_shown) def on_update_legend(self, title='Title', min_value=0., max_value=1., scale=0.0, phase=0.0, data_format='%.0f', is_low_to_high=True, is_discrete=True, is_horizontal=True, nlabels=None, labelsize=None, ncolors=None, colormap='jet', is_shown=True): """ Updates the legend/model Parameters ---------- scale : float displacemnt scale factor; true scale """ #print('is_shown2 =', is_shown) #assert is_shown == False, is_shown key = self.case_keys[self.icase] name_vector = None plot_value = self.result_cases[key] # scalar vector_size1 = 1 update_3d = False assert isinstance(key, integer_types), key (obj, (i, res_name)) = self.result_cases[key] subcase_id = obj.subcase_id #print('plot_value =', plot_value) result_type = obj.get_title(i, res_name) vector_size = obj.get_vector_size(i, res_name) if vector_size == 3: plot_value = obj.get_plot_value(i, res_name) # vector update_3d = True #print('setting scale=%s' % scale) assert isinstance(scale, float), scale obj.set_scale(i, res_name, scale) obj.set_phase(i, res_name, phase) else: scalar_result = obj.get_scalar(i, res_name) location = obj.get_location(i, res_name) obj.set_min_max(i, res_name, min_value, max_value) obj.set_data_format(i, res_name, data_format) obj.set_nlabels_labelsize_ncolors_colormap( i, res_name, nlabels, labelsize, ncolors, colormap) #data_format = obj.get_data_format(i, res_name) #obj.set_format(i, res_name, data_format) #obj.set_data_format(i, res_name, data_format) subtitle, label = self.get_subtitle_label(subcase_id) name_vector = (vector_size1, subcase_id, result_type, label, min_value, max_value, scale) assert vector_size1 == 1, vector_size1 #if isinstance(key, integer_types): # vector 3 #norm_plot_value = norm(plot_value, axis=1) #min_value = norm_plot_value.min() #max_value = norm_plot_value.max() #print('norm_plot_value =', norm_plot_value) if update_3d: self.is_horizontal_scalar_bar = is_horizontal self._set_case(self.result_name, self.icase, explicit=False, cycle=False, skip_click_check=True, min_value=min_value, max_value=max_value, is_legend_shown=is_shown) return subtitle, label = self.get_subtitle_label(subcase_id) scale1 = 0.0 # if vector_size == 3: name = (vector_size1, subcase_id, result_type, label, min_value, max_value, scale1) if obj.is_normal_result(i, res_name): return norm_value = float(max_value - min_value) # if name not in self._loaded_names: #if isinstance(key, integer_types): # vector 3 #norm_plot_value = norm(plot_value, axis=1) #grid_result = self.set_grid_values(name, norm_plot_value, vector_size1, #min_value, max_value, norm_value, #is_low_to_high=is_low_to_high) #else: grid_result = self.set_grid_values(name, scalar_result, vector_size1, min_value, max_value, norm_value, is_low_to_high=is_low_to_high) grid_result_vector = None #if name_vector and 0: #vector_size = 3 #grid_result_vector = self.set_grid_values(name_vector, plot_value, vector_size, #min_value, max_value, norm_value, #is_low_to_high=is_low_to_high) self.update_scalar_bar(title, min_value, max_value, norm_value, data_format, nlabels=nlabels, labelsize=labelsize, ncolors=ncolors, colormap=colormap, is_low_to_high=is_low_to_high, is_horizontal=is_horizontal, is_shown=is_shown) revert_displaced = True self._final_grid_update(name, grid_result, None, None, None, 1, subcase_id, result_type, location, subtitle, label, revert_displaced=revert_displaced) if grid_result_vector is not None: self._final_grid_update(name_vector, grid_result_vector, obj, i, res_name, vector_size, subcase_id, result_type, location, subtitle, label, revert_displaced=False) #if 0: #xyz_nominal, vector_data = obj.get_vector_result(i, res_name) #self._update_grid(vector_data) #self.grid.Modified() #self.geom_actor.Modified() #self.vtk_interactor.Render() #revert_displaced = False #self._final_grid_update(name, grid_result, None, None, None, #1, subcase_id, result_type, location, subtitle, label, #revert_displaced=revert_displaced) #self.is_horizontal_scalar_bar = is_horizontal icase = i msg = ('self.on_update_legend(title=%r, min_value=%s, max_value=%s,\n' ' scale=%r, phase=%r,\n' ' data_format=%r, is_low_to_high=%s, is_discrete=%s,\n' ' nlabels=%r, labelsize=%r, ncolors=%r, colormap=%r,\n' ' is_horizontal=%r, is_shown=%r)' % (title, min_value, max_value, scale, phase, data_format, is_low_to_high, is_discrete, nlabels, labelsize, ncolors, colormap, is_horizontal, is_shown)) self.log_command(msg) #if is_shown: #pass #--------------------------------------------------------------------------------------- # WingWindow def on_add_menu(self, text): self.log_info('on_add_menu(text=%r)' % text) self.on_wing_window() def on_wing_window(self): if not hasattr(self, '_edit_geometry_window_shown'): self._edit_geometry_window_shown = False #data = deepcopy(self.geometry_properties) transform = { 'xyz' : [0., 0., 0.], 'is_absolute' : False, 'rot origin(X)' : 0., } symmetry = {} data = { 'name' : 'WingGeom', 'color' : (0, 0, 255), #'font_size' : 8, 'num_U' : 16, 'num_W' : 33, 'Density' : 1.0, 'Thin Shell' : False, 'Mass/Area' : 1.0, #'Priority' : 0, 'Negative Volume' : False, 'transform' : transform, 'symmetry' : symmetry, } data['font_size'] = self.font_size if not self._edit_geometry_window_shown: self._edit_geometry = WingWindow(data, win_parent=self) self._edit_geometry.show() self._edit_geometry_window_shown = True self._edit_geometry.exec_() else: self._edit_geometry.activateWindow() if 'clicked_ok' not in data: self._edit_geometry.activateWindow() return if data['clicked_ok']: #self.on_update_geometry_properties(data) #self._save_geometry_properties(data) del self._edit_geometry self._edit_geometry_window_shown = False elif data['clicked_cancel']: #self.on_update_geometry_properties(self.geometry_properties) del self._edit_geometry self._edit_geometry_window_shown = False #--------------------------------------------------------------------------------------- # EDIT ACTOR PROPERTIES def edit_geometry_properties(self): """ Opens a dialog box to set: +--------+----------+ | Name | String | +--------+----------+ | Min | Float | +--------+----------+ | Max | Float | +--------+----------+ | Format | pyString | +--------+----------+ """ if not hasattr(self, 'case_keys'): self.log_error('No model has been loaded.') return if not len(self.geometry_properties): self.log_error('No secondary geometries to edit.') return #print('geometry_properties.keys() =', self.geometry_properties.keys()) #key = self.case_keys[self.icase] #case = self.result_cases[key] data = deepcopy(self.geometry_properties) data['font_size'] = self.font_size if not self._edit_geometry_properties_window_shown: self._edit_geometry_properties = EditGeometryProperties(data, win_parent=self) self._edit_geometry_properties.show() self._edit_geometry_properties_window_shown = True self._edit_geometry_properties.exec_() else: self._edit_geometry_properties.activateWindow() if 'clicked_ok' not in data: self._edit_geometry_properties.activateWindow() return if data['clicked_ok']: self.on_update_geometry_properties(data) self._save_geometry_properties(data) del self._edit_geometry_properties self._edit_geometry_properties_window_shown = False elif data['clicked_cancel']: self.on_update_geometry_properties(self.geometry_properties) del self._edit_geometry_properties self._edit_geometry_properties_window_shown = False def _save_geometry_properties(self, out_data): for name, group in iteritems(out_data): if name in ['clicked_ok', 'clicked_cancel']: continue if name not in self.geometry_properties: # we've deleted the actor continue geom_prop = self.geometry_properties[name] if isinstance(geom_prop, CoordProperties): pass elif isinstance(geom_prop, AltGeometry): geom_prop.color = group.color geom_prop.line_width = group.line_width geom_prop.opacity = group.opacity geom_prop.point_size = group.point_size else: raise NotImplementedError(geom_prop) def on_update_geometry_properties_override_dialog(self, geometry_properties): """ Update the goemetry properties and overwite the options in the edit geometry properties dialog if it is open. Parameters ----------- geometry_properties : dict {str : CoordProperties or AltGeometry} Dictionary from name to properties object. Only the names included in ``geometry_properties`` are modified. """ if self._edit_geometry_properties_window_shown: # Override the output state in the edit geometry properties diaglog # if the button is pushed while the dialog is open. This prevent the # case where you close the dialog and the state reverts back to # before you hit the button. for name, prop in iteritems(geometry_properties): self._edit_geometry_properties.out_data[name] = prop if self._edit_geometry_properties.active_key == name: index = self._edit_geometry_properties.table.currentIndex() self._edit_geometry_properties.update_active_key(index) self.on_update_geometry_properties(geometry_properties) def on_set_modify_groups(self): """ Opens a dialog box to set: +--------+----------+ | Name | String | +--------+----------+ | Min | Float | +--------+----------+ | Max | Float | +--------+----------+ | Format | pyString | +--------+----------+ """ on_set_modify_groups(self) def _apply_modify_groups(self, data): """called by on_set_modify_groups when apply is clicked""" self.on_update_modify_groups(data) imain = self._modify_groups_window.imain name = self._modify_groups_window.keys[imain] self.post_group_by_name(name) def on_update_modify_groups(self, out_data): """ Applies the changed groups to the different groups if something changed. """ #self.groups = out_data data = {} for group_id, group in sorted(iteritems(out_data)): if not isinstance(group, Group): continue data[group.name] = group self.groups = data def on_update_geometry_properties(self, out_data, name=None, write_log=True): """ Applies the changed properties to the different actors if something changed. Note that some of the values are limited. This prevents points/lines from being shrunk to 0 and also the actor being actually "hidden" at the same time. This prevents confusion when you try to show the actor and it's not visible. """ lines = [] if name is None: for namei, group in iteritems(out_data): if namei in ['clicked_ok', 'clicked_cancel']: continue self._update_ith_geometry_properties(namei, group, lines, render=False) else: group = out_data[name] self._update_ith_geometry_properties(name, group, lines, render=False) self.vtk_interactor.Render() if write_log and lines: msg = 'out_data = {\n' msg += ''.join(lines) msg += '}\n' msg += 'self.on_update_geometry_properties(out_data)' self.log_command(msg) def _update_ith_geometry_properties(self, namei, group, lines, render=True): """updates a geometry""" if namei not in self.geometry_actors: # we've deleted the actor return actor = self.geometry_actors[namei] if isinstance(actor, vtk.vtkActor): alt_prop = self.geometry_properties[namei] label_actors = alt_prop.label_actors lines += self._update_geometry_properties_actor(namei, group, actor, label_actors) elif isinstance(actor, vtk.vtkAxesActor): changed = False is_visible1 = bool(actor.GetVisibility()) is_visible2 = group.is_visible if is_visible1 != is_visible2: actor.SetVisibility(is_visible2) alt_prop = self.geometry_properties[namei] alt_prop.is_visible = is_visible2 actor.Modified() changed = True if changed: lines.append(' %r : CoordProperties(is_visible=%s),\n' % ( namei, is_visible2)) else: raise NotImplementedError(actor) if render: self.vtk_interactor.Render() def _update_geometry_properties_actor(self, name, group, actor, label_actors): """ Updates an actor Parameters ---------- name : str the geometry proprety to update group : AltGeometry() a storage container for all the actor's properties actor : vtkActor() the actor where the properties will be applied linewidth1 : int the active linewidth linewidth2 : int the new linewidth """ lines = [] changed = False #mapper = actor.GetMapper() prop = actor.GetProperty() backface_prop = actor.GetBackfaceProperty() if name == 'main' and backface_prop is None: # don't edit these # we're lying about the colors to make sure the # colors aren't reset for the Normals color1 = prop.GetDiffuseColor() color2 = color1 assert color1[1] <= 1.0, color1 else: color1 = prop.GetDiffuseColor() assert color1[1] <= 1.0, color1 color2 = group.color_float #print('line2646 - name=%s color1=%s color2=%s' % (name, str(color1), str(color2))) #color2 = group.color opacity1 = prop.GetOpacity() opacity2 = group.opacity opacity2 = max(0.1, opacity2) line_width1 = prop.GetLineWidth() line_width2 = group.line_width line_width2 = max(1, line_width2) point_size1 = prop.GetPointSize() point_size2 = group.point_size point_size2 = max(1, point_size2) representation = group.representation alt_prop = self.geometry_properties[name] #representation = alt_prop.representation #is_visible1 = alt_prop.is_visible is_visible1 = bool(actor.GetVisibility()) is_visible2 = group.is_visible #print('is_visible1=%s is_visible2=%s' % (is_visible1, is_visible2)) bar_scale1 = alt_prop.bar_scale bar_scale2 = group.bar_scale # bar_scale2 = max(0.0, bar_scale2) #print('name=%s color1=%s color2=%s' % (name, str(color1), str(color2))) if color1 != color2: #print('color_2662[%s] = %s' % (name, str(color1))) assert isinstance(color1[0], float), color1 prop.SetDiffuseColor(color2) changed = True if line_width1 != line_width2: line_width2 = max(1, line_width2) prop.SetLineWidth(line_width2) changed = True if opacity1 != opacity2: #if backface_prop is not None: #backface_prop.SetOpacity(opacity2) prop.SetOpacity(opacity2) changed = True if point_size1 != point_size2: prop.SetPointSize(point_size2) changed = True if representation == 'bar' and bar_scale1 != bar_scale2: #print('name=%s rep=%r bar_scale1=%s bar_scale2=%s' % ( #name, representation, bar_scale1, bar_scale2)) self.set_bar_scale(name, bar_scale2) if is_visible1 != is_visible2: actor.SetVisibility(is_visible2) alt_prop.is_visible = is_visible2 #prop.SetViPointSize(is_visible2) actor.Modified() for label_actor in label_actors: label_actor.SetVisibility(is_visible2) label_actor.Modified() changed = True if changed: lines.append(' %r : AltGeometry(self, %r, color=(%s, %s, %s), ' 'line_width=%s, opacity=%s, point_size=%s, bar_scale=%s, ' 'representation=%r, is_visible=%s),\n' % ( name, name, color2[0], color2[1], color2[2], line_width2, opacity2, point_size2, bar_scale2, representation, is_visible2)) prop.Modified() return lines def set_bar_scale(self, name, bar_scale): """ Parameters ---------- name : str the parameter to scale (e.g. TUBE_y, TUBE_z) bar_scale : float the scaling factor """ #print('set_bar_scale - GuiCommon2; name=%s bar_scale=%s' % (name, bar_scale)) if bar_scale <= 0.0: return assert bar_scale > 0.0, 'bar_scale=%r' % bar_scale # bar_y : (nbars, 6) float ndarray # the xyz coordinates for (node1, node2) of the y/z axis of the bar # xyz1 is the centroid # xyz2 is the end point of the axis with a length_xyz with a bar_scale of 1.0 bar_y = self.bar_lines[name] #dy = c - yaxis #dz = c - zaxis #print('bary:\n%s' % bar_y) xyz1 = bar_y[:, :3] xyz2 = bar_y[:, 3:] dxyz = xyz2 - xyz1 # vectorized version of L = sqrt(dx^2 + dy^2 + dz^2) length_xyz = np.linalg.norm(dxyz, axis=1) izero = np.where(length_xyz == 0.0)[0] if len(izero): bad_eids = self.bar_eids[name][izero] self.log.error('The following elements have zero length...%s' % bad_eids) # v = dxyz / length_xyz * bar_scale # xyz2 = xyz1 + v nnodes = len(length_xyz) grid = self.alt_grids[name] points = grid.GetPoints() for i in range(nnodes): p = points.GetPoint(2*i+1) #print(p) node = xyz1[i, :] + length_xyz[i] * bar_scale * dxyz[i, :] #print(p, node) points.SetPoint(2 * i + 1, *node) if hasattr(grid, 'Update'): #print('update....') grid.Update() grid.Modified() #print('update2...') def _add_user_points_from_csv(self, csv_points_filename, name, color, point_size=4): """ Helper method for adding csv nodes to the gui Parameters ---------- csv_points_filename : str CSV filename that defines one xyz point per line name : str name of the geometry actor color : List[float, float, float] RGB values; [0. to 1.] point_size : int; default=4 the nominal point size """ is_failed = True try: assert os.path.exists(csv_points_filename), print_bad_path(csv_points_filename) # read input file try: user_points = np.loadtxt(csv_points_filename, delimiter=',') except ValueError: user_points = loadtxt_nice(csv_points_filename, delimiter=',') # can't handle leading spaces? #raise except ValueError as e: #self.log_error(traceback.print_stack(f)) self.log_error('\n' + ''.join(traceback.format_stack())) #traceback.print_exc(file=self.log_error) self.log_error(str(e)) return is_failed self._add_user_points(user_points, name, color, csv_points_filename, point_size=point_size) is_failed = False return False def _add_user_points(self, user_points, name, color, csv_points_filename='', point_size=4): """ Helper method for adding csv nodes to the gui Parameters ---------- user_points : (n, 3) float ndarray the points to add name : str name of the geometry actor color : List[float, float, float] RGB values; [0. to 1.] point_size : int; default=4 the nominal point size """ if name in self.geometry_actors: msg = 'Name: %s is already in geometry_actors\nChoose a different name.' % name raise ValueError(msg) if len(name) == 0: msg = 'Invalid Name: name=%r' % name raise ValueError(msg) # create grid self.create_alternate_vtk_grid(name, color=color, line_width=5, opacity=1.0, point_size=point_size, representation='point') npoints = user_points.shape[0] if npoints == 0: raise RuntimeError('npoints=0 in %r' % csv_points_filename) if len(user_points.shape) == 1: user_points = user_points.reshape(1, npoints) # allocate grid self.alt_grids[name].Allocate(npoints, 1000) # set points points = vtk.vtkPoints() points.SetNumberOfPoints(npoints) for i, point in enumerate(user_points): points.InsertPoint(i, *point) elem = vtk.vtkVertex() elem.GetPointIds().SetId(0, i) self.alt_grids[name].InsertNextCell(elem.GetCellType(), elem.GetPointIds()) self.alt_grids[name].SetPoints(points) # create actor/mapper self._add_alt_geometry(self.alt_grids[name], name) # set representation to points self.geometry_properties[name].representation = 'point' actor = self.geometry_actors[name] prop = actor.GetProperty() prop.SetRepresentationToPoints() prop.SetPointSize(point_size)
python
# # Copyright (c) 2010 Testrepository Contributors # # Licensed under either the Apache License, Version 2.0 or the BSD 3-clause # license at the users choice. A copy of both licenses are available in the # project source as Apache-2.0 and BSD. You may not use this file except in # compliance with one of these two licences. # # Unless required by applicable law or agreed to in writing, software # distributed under these licenses is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # license you chose for the specific language governing permissions and # limitations under that license. """Tests for matchers used by or for testing testrepository.""" import sys from testtools import TestCase class TestWildcard(TestCase): def test_wildcard_equals_everything(self): from testrepository.tests import Wildcard self.assertTrue(Wildcard == 5) self.assertTrue(Wildcard == 'orange') self.assertTrue('orange' == Wildcard) self.assertTrue(5 == Wildcard) def test_wildcard_not_equals_nothing(self): from testrepository.tests import Wildcard self.assertFalse(Wildcard != 5) self.assertFalse(Wildcard != 'orange')
python
import re import h5py import numpy as np from nltk.tokenize import word_tokenize from nltk.stem import WordNetLemmatizer from nltk.corpus import stopwords from os.path import join,exists from os import listdir from paper import paper def html_reader(input_dir): """ read the html file at input_dir, and parse the html file, return a paper object ------------------------------------------------------------------------------- parameter: input_dir: str, dir of the html file ------------------------------------------------------------------------------ return: paper: paper.paper object """ #read data from the html file with open(input_dir,'r') as html_file: content = html_file.read() content = (content.split('\n'))[4:-4] num = re.compile("(.*\t\d.*)|(\d*\d\.\d*)") information = [] for i in range(len(content)): if num.match(content[i])==None: information.append(content[i]) information = information[:-1] #data parsing Date = re.compile('( ?CACM|June)') Meta = re.compile("(CA\d\d\d\d\d\d|June)") #get date and meta index for i in range(len(information)): if Date.match(information[i])!=None: index_date = i if Meta.match(information[i])!=None: index_meta =i content = information[:index_date] others = information[index_date+2:index_meta] for i in range(len(content)): if content[i]=="": title = content[:i] abstract = content[i+1:] break #get author and other author = [] other = [] for i in range(len(others)): if others[i]=="": if re.match("[A-Z].*, ?[A-Z].*\..*",others[0]) != None: author = others[:i] other = others[i+1:] else: other = others break for i in range(len(author)): if re.match("[A-Z].*, ?[A-Z].*\..*",author[i]) != None: name = author[i].split(",") author[i] = (name[1]+name[0]) author[i] = author[i].replace(" ","") author[i] = author[i].replace("\t","") author[i] = author[i].lower() #parse date date = [] date.append(re.search("19\d\d", information[index_date]).group()) date.append(re.search("(January|February|March|April|May|June|JUly|July|August|September|October|November|December)",information[index_date]).group().lower()) #parse meta data meta = [] meta.append(re.search("CA\d\d\d\d\d\d\w?",information[index_meta]).group().lower())#0 meta.append(re.search("[a-z0-9] [A-Z]{2}[A-Z]?",information[index_meta]).group()[2:].lower())#1 meta.append(re.search("(January|February|March|April|May|June|JUly|July|August|September|October|November|December)",information[index_meta]).group().lower())#2 meta.append(re.search("\w \d\d?",information[index_meta]).group()[2:])#3 meta.append(re.search("\d?\d:\d\d",information[index_meta]).group())#4 meta.append(re.search("(AM|PM)",information[index_meta]).group().lower())#5 meta.append(re.search("19\d\d",information[index_meta]).group())#6 #build corpus corpus = set() lemmatizer = WordNetLemmatizer() for i in range(len(title)): title[i] = re.sub("\(|\)|-|\d\d?\d?|:|/|\.|`|\?"," ",title[i]) words = word_tokenize(title[i]) for word in words: normal_word = word.lower() if normal_word not in stopwords.words("english"): corpus.add(lemmatizer.lemmatize(normal_word)) for i in range(len(abstract)): abstract[i] = re.sub("\(|\)|-|\d\d?\d?|:|/|\.|`|\?|,"," ",abstract[i]) words = word_tokenize(abstract[i]) for word in words: normal_word = word.lower() if normal_word not in stopwords.words("english"): corpus.add(lemmatizer.lemmatize(normal_word)) for i in range(len(other)): other[i] = re.sub("\(|\)|-|\d\d?\d?|:|/|\.|`|\?|,"," ",other[i]) words = word_tokenize(other[i]) for word in words: normal_word = word.lower() if normal_word not in stopwords.words("english"): corpus.add(lemmatizer.lemmatize(normal_word)) corpus = list(corpus) return paper(author= author, other= other, metadata= meta,date = date,title = title,abstract = abstract,id=int(input_dir[-9:-5]),corpus = corpus) def convert(num): """ format the number like "0001","0012","0123","1234" ------------------------------------------------------------------------- parameter: num: int, the number to be formatted ------------------------------------------------------------------------- return: num:str, the formatted number """ if len(str(num))==1: return "000%i"%num elif len(str(num)) == 2: return "00%i"%num elif len(str(num)) == 3: return "0%i"%num elif len(str(num)) == 4: return "%i"%num
python
from .experiment import Experiment # noqa: F401 from .trial import Trial # noqa: F401
python
import os import argparse import imageio parser = argparse.ArgumentParser() parser.add_argument('--name', required=True, type=str) args = parser.parse_args() for file in sorted(os.listdir(os.path.join('outputs', args.name, 'particles'))): i = int(file.replace('.bin', '')) print('frame %d' % i, flush=True) os.system('python utils/render.py --name %s --frame %d --imshow 0' % (args.name, i))
python
# -*- coding: utf-8 -*- # Generated by Django 1.11.10 on 2018-02-20 14:37 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('payment', '0014_add_indices'), ] operations = [ migrations.AddIndex( model_name='payment', index=models.Index(fields=['modified'], name='payment_pay_modifie_c1f247_idx'), ), ]
python
########################################################### # compare.py -Script that compares any two painting's hex # hex values for similarity or rank in the # frequency list and quantifies it with a # percentage # Author: Shaedil Dider ########################################################### import colors from statistics import mean # Extract the two color sets and put them in a variable # Process them into RGB>LAB values using colors library # Comparison algorithm using delta E algorithm # https://stackoverflow.com/a/52453462/6273236 def compare_color_sets(first_file, second_file): color_set1 = eval(open("./dataset/" + first_file).read()) color_set2 = eval(open("./dataset/" + second_file).read()) converted_set1 = convert_color_set_to_LAB(color_set1) converted_set2 = convert_color_set_to_LAB(color_set2) mean_similarity = calculate_mean_simularity(converted_set1, converted_set2) print_level_of_perceptibility(mean_similarity) def convert_color_set_to_LAB(input_color_set): color_set_in_LAB = [] for each_color_scheme in input_color_set: each_color_scheme_in_RBG = colors.hexToRGB(each_color_scheme) each_color_scheme_in_LAB = colors.rgb2lab(each_color_scheme_in_RBG) color_set_in_LAB.append(each_color_scheme_in_LAB) return color_set_in_LAB.sort() def calculate_mean_simularity(color_set_in_LAB1, color_set_in_LAB2): similarities = [] for color1, color2 in zip(color_set_in_LAB1, color_set_in_LAB2): similarity_between_colors = colors.deltaE(color1, color2) similarities.append(similarity_between_colors) return mean(similarities) def print_level_of_perceptibility(mean_similarity): if mean_similarity <= 1.0: print("Delta E: <= 1.0") print( "Perception: The difference in the color set of the paintings are not perceptible by human eyes" ) elif mean_similarity <= 2.0: print("Delta E: 1 - 2") print( "Perception: The difference in the color set of the paintings are perceptible through close observation" ) elif mean_similarity <= 11.0: print("Delta E: 2 - 10") print( "Perception: The difference in the color set of the paintings are perceptible at a glance" ) elif mean_similarity <= 49.0: print("Delta E: 11 - 49") print( "Preception: The color set of the paintings are more similar than opposite" ) else: print("Delta E: 49 - 100") print("Perception: The color set of the paintings are exact opposites")
python
from selenium import webdriver from utils.logging import init_logger from utils.s3_manager.manage import S3Manager class SeleniumCrawler: def __init__(self, base_url, bucket_name, key, head=False): self.logger = init_logger() self.bucket_name = bucket_name self.s3_manager = S3Manager(bucket_name=self.bucket_name) self.prefix = key self.chrome_path = "C:/chromedriver" options = webdriver.ChromeOptions() if head is False: options.add_argument('headless') self.driver = webdriver.Chrome(executable_path=self.chrome_path, chrome_options=options) self.base_url = base_url # TODO: click elements sequentially def click_element_by_xpath(self, xpath: str): ele = self.driver.find_element_by_xpath(xpath=xpath) ele.click() def click_element_by_class_name(self, name: str): ele = self.driver.find_element_by_class_name(name=name) ele.click() def click_element_by_tag_name(self, name: str): ele = self.driver.find_element_by_tag_name(name=name) ele.click() def process(self): pass
python
from ._accuracy_per_cell_type import accuracy_per_cell_type from ._cd_ratio import cd_ratio from ._cumulative_node import cumulative_node from ._cumulative_node_group import cumulative_node_group from ._dists_distr import dists_distr from ._mean_node_per_cell_type import mean_node_per_cell_type from ._metric_heatmap import metric_heatmap from ._node_distr import node_distr from ._river_plot import river_plot from ._river_plot_2_omics import river_plot_2_omics from ._pairwise_distance import pairwise_distance from ._silhouette import silhouette from ._metrics_scatterplot import metrics_scatterplot import scanpy # check if scanpy version is below 1.8.0 or higher if int(''.join(scanpy.__version__.split('.'))) < 180: from ._umap_barcodes import umap_barcodes else: from ._umap_barcodes_2 import umap_barcodes
python
import socket class Triton200: """ Create an instance of the Triton200 class. Supported modes: IP :param str ip_address: The IP address of the Triton 200. :param int port_number: The associated port number of the Triton 200 (default: 33576) :param int timeout: How long to wait for a response (default: 10000) :param int bytes_to_read: How many bytes to accept from the response (default: 2048) """ def __init__(self, ip_address, port_number=33576, timeout=10000, bytes_to_read=2048): self._address = (str(ip_address), int(port_number)) self._timeout = timeout self._bytes_to_read = bytes_to_read self._temperature_channel = Triton200.RUO2_CHANNEL self._temperature_setpoint = 0.0 self._heater_range = 0.0 self._heater_channel = '1' self._turbo_channel = '1' @property def temperature_channel(self): """ :returns str: The temperature channel, either the cernox (5) or the RuO2 (6) """ return self._temperature_channel @temperature_channel.setter def temperature_channel(self, value): self._temperature_channel = str(value) @property def temperature_setpoint(self): return self._temperature_setpoint @temperature_setpoint.setter def temperature_setpoint(self, value): if not isinstance(value, float): raise RuntimeError("Make sure the temperature set point is a number.") elif 0 <= value < 10: self._temperature_setpoint = value else: print("Keep an eye on the turbo pump if you ramp!!!") self._temperature_setpoint = value @property def temperature(self): """The temperature reading from the current temperature channel.""" noun = 'DEV:T' + str(self.temperature_channel) + ':TEMP:SIG:TEMP' command = 'READ:' + noun + '\r\n' response = self.query_and_receive(command) return self.extract_value(response, noun, 'K') def update_heater(self): """ Associates the heater with the current temperature channel and changes the heater current to preset values given the temperature set point. """ heater_range = ['0.316', '1', '3.16', '10', '31.6', '100'] command = 'SET:DEV:T' + str(self.temperature_channel) + ':TEMP:LOOP:HTR:H' + str(self._heater_channel) + '\r\n' response = self.query_and_receive(command) if not response: raise RuntimeError("Changing of heater focus unsuccessful.") heater_index = ((self.temperature_setpoint > 0.030) + (self.temperature_setpoint > 0.050) + (self.temperature_setpoint > 0.300) + (self.temperature_setpoint > 1.000) + (self.temperature_setpoint > 1.500)) heater_current = heater_range[heater_index] command = 'SET:DEV:T' + str(self.temperature_channel) + ':TEMP:LOOP:RANGE:' + heater_current + '\r\n' response = self.query_and_receive(command) if not response: raise RuntimeError("Changing of heater range unsuccessful.") def controlled_ramp_on(self): """Starts a temperature sweep for the current temperature channel.""" command = 'SET:DEV:T' + str(self.temperature_channel) + 'TEMP:LOOP:RAMP:ENAB:ON\r\n' response = self.query_and_receive(command) if not response: raise RuntimeError("Enabling of temperature ramp unsuccessful.") def controlled_ramp_off(self): """Stops a temperature sweep for the current temperature channel.""" command = 'SET:DEV:T' + str(self.temperature_channel) + 'TEMP:LOOP:RAMP:ENAB:OFF\r\n' response = self.query_and_receive(command) if not response: raise RuntimeError("Disabling of temperature ramp unsuccessful.") def turbo_on(self): """Turns on a turbo pump. WARNING: Do not use this unless you know what you are doing.""" command = 'SET:DEV:TURB' + self._turbo_channel + ':PUMP:SIG:STATE:ON\r\n' response = self.query_and_receive(command) if not response: raise RuntimeError("Enabling of turbo pump unsuccessful.") def turbo_off(self): """Turns off a turbo pump. WARNING: Do not use this unless you know what you are doing.""" command = 'SET:DEV:TURB' + self._turbo_channel + ':PUMP:SIG:STATE:OFF\r\n' response = self.query_and_receive(command) if not response: raise RuntimeError("Disabling of turbo pump unsuccessful.") def query_and_receive(self, command): """ Queries the Oxford Triton 200 with the given command. :param command: Specifies a read/write of a property. """ with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s: s.connect(self._address) s.settimeout(self._timeout) s.sendall(command.encode()) response = s.recv(self._bytes_to_read).decode() return response @staticmethod def extract_value(response, noun, unit): expected_response = 'STAT:' + noun + ':' value = float(response.replace(expected_response, '').strip('\n').replace(unit, '')) return value
python
import random import itertools import json import networkx as nx import sys, getopt import dcop_instance as dcop def generate(G : nx.Graph, dsize = 2, p2=1.0, cost_range=(0, 10), def_cost = 0, int_cost=True, outfile='') : assert (0.0 < p2 <= 1.0) agts = {} vars = {} doms = {'0': list(range(0, dsize))} cons = {} for i in range(0, len(G.nodes())): agts[str(i)] = None vars[str(i)] = {'dom': '0', 'agt': str(i)} cid = 0 for e in G.edges(): arity = len(e) cons[str(cid)] = {'arity': arity, 'def_cost': def_cost, 'scope': [str(x) for x in e], 'values': []} for assignments in itertools.product(*([[0, 1], ] * arity)): val = {'tuple': []} val['tuple'] = list(assignments) if int_cost: val['cost'] = random.randint(*cost_range) else: val['cost'] = random.uniform(*cost_range) cons[str(cid)]['values'].append(val) cid += 1 return agts, vars, doms, cons def main(argv): agts = 10 max_arity = 2 max_cost = 10 out_file = '' name = '' def rise_exception(): print('Input Error. Usage:\nmain.py -a -r -c -n -o <outputfile>') sys.exit(2) try: opts, args = getopt.getopt(argv, "a:r:c:n:o:h", ["agts=", "max_arity=", "max_cost=", "name=", "ofile=", "help"]) except getopt.GetoptError: rise_exception() if len(opts) != 5: rise_exception() for opt, arg in opts: if opt in ('-h', '--help'): print('main.py -i <inputfile> -o <outputfile>') sys.exit() elif opt in ('-a', '--agts'): agts = int(arg) elif opt in ('-r', '--max_arity'): max_arity = int(arg) elif opt in ('-c', '--max_cost'): max_cost = int(arg) elif opt in ("-n", "--name"): name = arg elif opt in ("-o", "--ofile"): out_file = arg return agts, max_arity, max_cost, name, out_file if __name__ == '__main__': nagts, maxarity, maxcost, name, outfile = main(sys.argv[1:]) G = nx.grid_graph([nagts, nagts]).to_undirected() while not nx.is_connected(G): G = nx.grid_graph(nagts).to_undirected() # Normalize Graph Gn = nx.empty_graph(nagts) map_nodes = {} nid = 0 for n in G.nodes(): map_nodes[n] = nid nid += 1 for e in G.edges(): Gn.add_edge(map_nodes[e[0]], map_nodes[e[1]]) agts, vars, doms, cons = generate(Gn, cost_range=(0,maxcost)) print('Creating DCOP instance' + name, ' G nodes: ', len(Gn.nodes()), ' G edges:', len(Gn.edges())) dcop.create_xml_instance(name, agts, vars, doms, cons, outfile+'.xml') dcop.create_wcsp_instance(name, agts, vars, doms, cons, outfile+'.wcsp') dcop.create_json_instance(name, agts, vars, doms, cons, outfile+'.json')
python
#!/usr/bin/python3 """Explode an LLVM IR dump. Given a debug dump generated from the -print-debug-all option, split out the dumps into multiple files, one for each phase/procedure. Example usage: clang -c -O3 -mllvm -print-before-all mumble.c 1> err.txt 2>&1 rm -rf /tmp/dumps ; mkdir /tmp/dumps explode-llvm-ir-dumps.py -i err.txt -o /tmp/dumps Right at the moment (this could change in the future), the output of -print-before-all includes both function-scope dumps and module-scope dumps. The expected pattern will be something like mod dump 1 pass X mod dump 2 pass Y func 1 dump for pass A func 1 dump for pass B loop L1 dump for pass LP loop L2 dump for pass LP func 1 dump for pass C func 2 dump for pass A func 2 dump for pass B func 2 dump for pass C mod dump 3 pass Z Typically what we're interested in doing is tracking a function over time through the various dumps, so we emit an index ("index.txt") containing a chronological listing of the dumps that mention a function (the assumption being that a module dump mentions all functions). """ from collections import defaultdict import getopt import os import re import sys import script_utils as u # Dry run mode flag_dryrun = False # Echo commands mode flag_echo = False # Input file, output dir flag_infile = None flag_outdir = None # Passes, functions passes = {} functions = {} loops = {} # Key is dump name (func:pass) and value is counter (how many # dumps we've seen for this dumpname, since a given pass can # happen more than once for a given function). dumps = defaultdict(int) # Complete listing of dump files in chronological order. alldumps = [] # Keyed by function, value is a list of indices into the alldumps array. funcdumps = defaultdict(list) def docmd(cmd): """Execute a command.""" if flag_echo or flag_dryrun: sys.stderr.write("executing: " + cmd + "\n") if flag_dryrun: return u.docmd(cmd) def dochdir(thedir): """Switch to dir.""" if flag_echo or flag_dryrun: sys.stderr.write("cd " + thedir + "\n") try: os.chdir(thedir) except OSError as err: u.error("chdir failed: %s" % err) def do_clean(subdir): """Clean this libgo dir.""" flavs = (".o", "gox", ".a", ".so", ".lo", ".la") here = os.getcwd() dochdir(subdir) if flag_dryrun: u.verbose(0, "... cleaning %s" % subdir) else: cmd = "find . -depth " first = True for item in flavs: if not first: cmd += " -o " first = False cmd += "-name '*%s' -print" % item lines = u.docmdlines(cmd) lines.reverse() debris = lines for d in debris: if not d: continue u.verbose(1, "toclean '%s'" % d) os.unlink(d) dochdir(here) def sanitize_pass(passname): """Sanitize passname to remove embedded spaces, etc.""" passname = passname.replace(" ", "_") passname = passname.replace("(", ".LP") passname = passname.replace(")", ".RP") passname = passname.replace("/", ".SL") passname = passname.replace("'", ".SQ") return passname def emitdump(passname, funcname, looplab, lines): """Emit single dump for module/pass or fn/pass.""" u.verbose(2, "emitdump(%s,%s,%s,lines=%d)" % (passname, funcname, looplab, len(lines))) if not lines: return tag = funcname if not funcname: tag = "__module__" if looplab: dump = "%s:L%s:%s" % (tag, looplab, passname) else: dump = "%s:%s" % (tag, passname) dumpver = dumps[dump] dumps[dump] += 1 dumpname = "%s:%d" % (dump, dumpver) ofname = os.path.join(flag_outdir, dumpname) try: with open(ofname, "w") as wf: for line in lines: wf.write(line) except IOError: u.error("open failed for %s" % ofname) u.verbose(1, "emitted dump %d of %d " "lines to %s" % (dumpver, len(lines), ofname)) # book-keeping dumpidx = len(alldumps) alldumps.append(dumpname) if funcname: funcdumps[funcname].append(dumpidx) return dumpname def process(rf): """Read lines from input file.""" # Note: dumps are emitted lazily, e.g. we read through all of dump K # and into dump K+1 before emitting dump K. lnum = 0 dumpre = re.compile(r"^\*\*\* IR Dump Before (\S.+)\s+\*\*\*\s*") fnre = re.compile(r"^define\s\S.+\s\@(\S+)\(.+\).+\{\s*$") modre = re.compile(r"^target datalayout =.*$") loopre = re.compile(r"^\; Preheader\:\s*$") labre = re.compile(r"^(\S+)\:.*$") # Info on previous dump curpass = None curfunc = None curloop = None curdumplines = [] # Current dump flavor: one of 'module', 'function', 'loop', or 'unknown' dumpflavor = "unknown" # Lines in current dump dumplines = [] # State information on the current loop. passname = None looplabel = None while True: lnum += 1 line = rf.readline() if not line: break if dumpflavor == "unknown": mloop = loopre.match(line) if mloop: # Emit previous dump if curpass: emitdump(curpass, curfunc, curloop, curdumplines) # This is a loop dump. Note: keep curfunc. dumpflavor = "loop" u.verbose(1, "line %d: now in loop dump " "for fn %s pass %s" % (lnum, curfunc, curpass)) mmod = modre.match(line) if mmod: # Emit previous dump if curpass: emitdump(curpass, curfunc, curloop, curdumplines) # This is a module dump. Discard func. dumpflavor = "module" curfunc = None u.verbose(1, "line %d: now in module dump " "for pass %s" % (lnum, curpass)) mfn = fnre.match(line) if mfn: # Emit previous dump. if curpass: emitdump(curpass, curfunc, curloop, curdumplines) curfunc = mfn.group(1) functions[curfunc] = 1 u.verbose(1, "line %d: now in fn %s" % (lnum, curfunc)) if dumpflavor == "loop" and not looplabel: mlab = labre.match(line) if mlab: looplabel = mlab.group(1) loops[looplabel] = 1 u.verbose(1, "line %d: loop label is %s" % (lnum, looplabel)) mdmp = dumpre.match(line) if mdmp: curpass = passname curloop = looplabel if curloop: u.verbose(1, "line %d: curloop now %s" % (lnum, curloop)) looplabel = None passname = sanitize_pass(mdmp.group(1)) u.verbose(1, "line %d: passname is %s" % (lnum, passname)) curdumplines = dumplines dumplines = [] passes[passname] = 1 dumpflavor = "unknown" dumplines.append(line) # emit final dump if curpass: emitdump(curpass, curfunc, curloop, curdumplines) def emitstats(): """Emit stats and index.""" indname = os.path.join(flag_outdir, "index.txt") totaldumps = 0 for _, v in dumps.items(): totaldumps += v u.verbose(0, "... captured %d total dumps, %d functions, " "%d loops, %d passes" % (totaldumps, len(functions), len(loops), len(passes))) try: with open(indname, "w") as wf: sfuncs = sorted(functions.keys()) for f in sfuncs: wf.write("\n\nfunction '%s':\n" % f) indices = funcdumps[f] for idx in indices: dumpname = alldumps[idx] wf.write(" %s\n" % dumpname) except IOError: u.error("open failed for %s" % indname) u.verbose(0, "... emitted dump catalog to %s" % indname) def perform(): """Top level driver routine.""" try: with open(flag_infile, "r") as rf: process(rf) except IOError: u.error("open failed for %s" % flag_infile) emitstats() def usage(msgarg): """Print usage and exit.""" me = os.path.basename(sys.argv[0]) if msgarg: sys.stderr.write("error: %s\n" % msgarg) print("""\ usage: %s [options] options: -d increase debug msg verbosity level -o X write dumps to dir X -D dryrun mode (echo commands but do not execute) """ % me) sys.exit(1) def parse_args(): """Command line argument parsing.""" global flag_dryrun, flag_echo, flag_outdir, flag_infile try: optlist, args = getopt.getopt(sys.argv[1:], "deo:i:D") except getopt.GetoptError as err: # unrecognized option usage(str(err)) if args: usage("unknown extra args") for opt, arg in optlist: if opt == "-d": u.increment_verbosity() elif opt == "-e": flag_echo = True elif opt == "-D": flag_dryrun = True elif opt == "-o": flag_outdir = arg if not os.path.exists(flag_outdir): usage("argument to -o flag '%s' not accessible" % arg) if not os.path.isdir(flag_outdir): usage("argument to -o flag '%s' not a directory" % arg) elif opt == "-i": flag_infile = arg if not os.path.exists(flag_infile): usage("argument to -i flag '%s' not accessible" % arg) if not flag_outdir: usage("supply out dir path with -o") if not flag_infile: usage("supply input file path with -i") parse_args() u.setdeflanglocale() perform()
python
# https://github.com/RaRe-Technologies/gensim/blob/develop/docs/notebooks/Corpora_and_Vector_Spaces.ipynb from gensim import corpora # This is a tiny corpus of nine documents, each consisting of only a single sentence documents = ["Human machine interface for lab abc computer applications", "A survey of user opinion of computer system response time", "The EPS user interface management system", "System and human system engineering testing of EPS", "Relation of user perceived response time to error measurement", "The generation of random binary unordered trees", "The intersection graph of paths in trees", "Graph minors IV Widths of trees and well quasi ordering", "Graph minors A survey"] # remove common words and tokenize stoplist = set('for a of the and to in'.split()) texts = [[word for word in document.lower().split() if word not in stoplist] for document in documents] # remove words that appear only once from collections import defaultdict frequency = defaultdict(int) for text in texts: for token in text: frequency[token] += 1 texts = [[token for token in text if frequency[token] > 1] for text in texts] from pprint import pprint # pretty printer pprint(texts) ## bag of words import os TEMP_FOLDER = "strings_to_vectors" dictionary = corpora.Dictionary(texts) dictionary.save(os.path.join(TEMP_FOLDER, 'x.dict')) print(dictionary) # there are twelve distinct words in the processed corpus, which means each document will be represented by twelve numbers (ie., by a 12-D vector) print(dictionary.token2id) # convert tokenized documents to vectors newdoc = "Human computer interaction" # The function doc2bow() simply counts the number of occurrences of each distinct word, converts the word to its integer word id and returns the result as a bag-of-words--a sparse vector, in the form of [(word_id, word_count), ...] newvec = dictionary.doc2bow(newdoc.lower().split()) print(newvec) # the word "interaction" does not appear in the dictionary and is ignored # The token_id is 0 for "human" and 2 for "computer" corpus = [dictionary.doc2bow(text) for text in texts] corpora.MmCorpus.serialize(os.path.join(TEMP_FOLDER, 'x.mm'), corpus) for c in corpus: print(c) # Corpus Streaming – One Document at a Time class MyCorpus(object): def __iter__(self): for line in open(os.path.join(TEMP_FOLDER, 'mycorpus.txt')): # assume there is one document per line, tokens separated by whitespace yield dictionary.doc2bow(line.lower().split()) corpusmemoryfriendly = MyCorpus() for vector in corpusmemoryfriendly: print(vector)
python
# Copyright (c) 2013 by Gilbert Ramirez <[email protected]> # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # as published by the Free Software Foundation; either version 2 # of the License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. from dftestlib import dftest class testIPv4(dftest.DFTest): trace_file = "nfs.pcap" def test_uint64_1(self): dfilter = "nfs.fattr3.size == 264032" self.assertDFilterCount(dfilter, 1) def test_eq_1(self): dfilter = "ip.src == 172.25.100.14" self.assertDFilterCount(dfilter, 1) def test_eq_2(self): dfilter = "ip.src == 255.255.255.255" self.assertDFilterCount(dfilter, 0) def test_ne_1(self): dfilter = "ip.src != 172.25.100.14" self.assertDFilterCount(dfilter, 1) def test_ne_2(self): dfilter = "ip.src != 255.255.255.255" self.assertDFilterCount(dfilter, 2) def test_gt_1(self): dfilter = "ip.dst > 198.95.230.200" self.assertDFilterCount(dfilter, 0) def test_gt_2(self): dfilter = "ip.dst > 198.95.230.20" self.assertDFilterCount(dfilter, 0) def test_gt_3(self): dfilter = "ip.dst > 198.95.230.10" self.assertDFilterCount(dfilter, 1) def test_ge_1(self): dfilter = "ip.dst >= 198.95.230.200" self.assertDFilterCount(dfilter, 0) def test_ge_2(self): dfilter = "ip.dst >= 198.95.230.20" self.assertDFilterCount(dfilter, 1) def test_ge_3(self): dfilter = "ip.dst >= 198.95.230.10" self.assertDFilterCount(dfilter, 1) def test_lt_1(self): dfilter = "ip.src < 172.25.100.140" self.assertDFilterCount(dfilter, 1) def test_lt_2(self): dfilter = "ip.src < 172.25.100.14" self.assertDFilterCount(dfilter, 0) def test_lt_3(self): dfilter = "ip.src < 172.25.100.10" self.assertDFilterCount(dfilter, 0) def test_le_1(self): dfilter = "ip.src <= 172.25.100.140" self.assertDFilterCount(dfilter, 1) def test_le_2(self): dfilter = "ip.src <= 172.25.100.14" self.assertDFilterCount(dfilter, 1) def test_le_3(self): dfilter = "ip.src <= 172.25.100.10" self.assertDFilterCount(dfilter, 0) def test_cidr_eq_1(self): dfilter = "ip.src == 172.25.100.14/32" self.assertDFilterCount(dfilter, 1) def test_cidr_eq_2(self): dfilter = "ip.src == 172.25.100.0/24" self.assertDFilterCount(dfilter, 1) def test_cidr_eq_3(self): dfilter = "ip.src == 172.25.0.0/16" self.assertDFilterCount(dfilter, 1) def test_cidr_eq_4(self): dfilter = "ip.src == 172.0.0.0/8" self.assertDFilterCount(dfilter, 1) def test_cidr_ne_1(self): dfilter = "ip.src != 172.25.100.14/32" self.assertDFilterCount(dfilter, 1) def test_cidr_ne_2(self): dfilter = "ip.src != 172.25.100.0/24" self.assertDFilterCount(dfilter, 1) def test_cidr_ne_3(self): dfilter = "ip.src != 172.25.0.0/16" self.assertDFilterCount(dfilter, 1) def test_cidr_ne_4(self): dfilter = "ip.src != 200.0.0.0/8" self.assertDFilterCount(dfilter, 2)
python
# Author: Deepak Pathak (c) 2016 from __future__ import absolute_import from __future__ import division from __future__ import print_function # from __future__ import unicode_literals import numpy as np from PIL import Image import time import argparse import os import pyflow parser = argparse.ArgumentParser( description='Demo for python wrapper of Coarse2Fine Optical Flow') parser.add_argument( '-viz', dest='viz', action='store_true', help='Visualize (i.e. save) output of flow.') args = parser.parse_args() examples_dir = "./examples" im1 = np.array(Image.open(os.path.join(examples_dir, 'car1.jpg'))) im2 = np.array(Image.open(os.path.join(examples_dir, 'car2.jpg'))) im1 = im1.astype(float) / 255. im2 = im2.astype(float) / 255. # Flow Options: alpha = 0.012 # default 0.012 ratio = 0.75 # default 0.75 minWidth = 20 # default 20 nOuterFPIterations = 7 # default 7 nInnerFPIterations = 1 # default 1 nSORIterations = 30 # default 30 colType = 0 # 0 or default:RGB, 1:GRAY (but pass gray image with shape (h,w,1)) threshold = 0.000005 s = time.time() u, v, im2W = pyflow.coarse2fine_flow( im1, im2, alpha, ratio, minWidth, nOuterFPIterations, nInnerFPIterations, nSORIterations, colType, verbose = True, threshold = threshold) e = time.time() print('Time Taken: %.2f seconds for image of size (%d, %d, %d)' % ( e - s, im1.shape[0], im1.shape[1], im1.shape[2])) flow = np.concatenate((u[..., None], v[..., None]), axis=2) np.save(os.path.join(examples_dir, 'outFlow.npy'), flow) always_viz = True if args.viz or always_viz: import cv2 hsv = np.zeros(im1.shape, dtype=np.uint8) hsv[:, :, 0] = 255 hsv[:, :, 1] = 255 mag, ang = cv2.cartToPolar(flow[..., 0], flow[..., 1]) hsv[..., 0] = ang * 180 / np.pi / 2 hsv[..., 2] = cv2.normalize(mag, None, 0, 255, cv2.NORM_MINMAX) rgb = cv2.cvtColor(hsv, cv2.COLOR_HSV2BGR) cv2.imwrite(os.path.join(examples_dir, 'outFlow_new.png'), rgb) cv2.imwrite(os.path.join(examples_dir, 'img2Warped_new.jpg'), im2W[:, :, ::-1] * 255)
python
from rect import Rect from math import floor class HashMap(object): """ Hashmap is a broad-phase collision detection strategy, which is quick enough to build each frame. """ def __init__(self, cell_size): self.cell_size = cell_size self.grid = {} @classmethod def from_objects(cls, cell_size, objects): """ Build a HashMap from a list of objects which have a .rect attribute. """ h = cls(cell_size) g = h.grid for o in objects: point = o.rect.left, o.rect.bottom k = "%s%s" % (int((floor(point[0]/cell_size))*cell_size), int((floor(point[1]/cell_size))*cell_size)) g.setdefault(k,[]).append(o) return h def key(self, point): cell_size = self.cell_size return "%s%s" % (int((floor(point[0]/cell_size))*cell_size), int((floor(point[1]/cell_size))*cell_size)) def insert(self, obj, rect): """ Insert obj into the hashmap, based on rect. """ self.grid.setdefault(self.key((rect.left, rect.bottom)), []).append(obj) def query(self, point): """ Return all objects in and around the cell specified by point. """ objects = [] x,y = point s = self.cell_size for p in (x-s,y-s),(x-s,y),(x-s,y+s),(x,y-s),(x,y),(x,y+s),(x+s,y-s),(x+s,y),(x+s,y+s): objects.extend(self.grid.setdefault(self.key(p), [])) return objects
python
#!/usr/bin/env python # -*- coding: utf-8 -*- """ drawmap.py @Purpose: draw a current map from a hdf mohid or netcdfoutput @version: 1.0 @python version: 3.9 @author: Pedro Montero @license: INTECMAR @requires: matplotlib, numpy, toolkits.basemap @date 2021/10/13 @history: """ import os from common.readers.reader_factory import read_factory from common import read_input from common.boundarybox import BoundaryBox from drawcurrents import drawcurrents def read_inputs(input_file): """Read keywords for options""" input_keys = ['path_in', 'file_in', 'path_out' 'file_out', 'nx', 'ny', 'resolution', 'scale', 'n_time', 'n_level', 'title', 'style', 'limits'] return read_input(input_file, input_keys) def main(): """ Main program: :return: """ # Start print("________________________________________\n") print(" DRAWMAP") print("________________________________________\n") # Read input file inputs = read_inputs('drawmap.json') draw_map_1(inputs, 0) #draw_map_24(inputs) def draw_map_1(inputs, n ): """draw 1 maps of a day""" draw_map = DrawMap(inputs) draw_map.read_head() draw_map.create_title(n) draw_map.reader_uv_by_time(n) print(draw_map.title_full) draw_map.draw() def draw_map_24(inputs): """draw 24+1 maps of a day""" draw_map = DrawMap(inputs) draw_map.read_head() for n in range(draw_map.reader.ini_ntime, 25+draw_map.reader.ini_ntime): draw_map.create_title(n) draw_map.reader_uv_by_time(n) print(draw_map.title_full) draw_map.draw() class DrawMap: """Class to draw a map with all options""" def __init__(self, inputs): self.file_path_in = inputs['path_in'] self.file_path_out = inputs['path_out'] self.file_in = inputs['file_in'] self.file_name = os.path.join(self.file_path_in, self.file_in) self.file_hdf_out = inputs['file_out'] self.file_out = os.path.join(self.file_path_out, self.file_hdf_out) self.nx = inputs['nx'] self.ny = inputs['ny'] self.scale = inputs['scale'] self.resolution = inputs['resolution'] self.style = inputs['style'] self.title = inputs['title'] self.level = inputs['n_level'] self.time = inputs['n_time'] limits = inputs['limits'] self.boundary_box = BoundaryBox(limits[0], limits[1], limits[2], limits[3]) self.u_name = inputs['u'] self.v_name = inputs['v'] self.reader = None def read_head(self): print('Opening: {0}'.format(self.file_name)) factory = read_factory(self.file_name) self.reader = factory.get_reader() with self.reader.open(): lat = self.reader.latitudes lon = self.reader.longitudes if self.reader.coordinates_rank == 1: self.lats = lat[0:self.reader.n_latitudes - 1] self.lons = lon[0:self.reader.n_longitudes - 1] elif self.reader.coordinates_rank == 2: self.lats = lat[0:self.reader.n_longitudes - 1, 0:self.reader.n_latitudes - 1] self.lons = lon[0:self.reader.n_longitudes - 1, 0:self.reader.n_latitudes - 1] def create_title(self, n_time): with self.reader.open(): data = self.reader.get_date(n_time) data_str = data.strftime("%Y-%m-%d %H:%M UTC") data_comp = data.strftime("%Y%m%d%H%M") self.title_full = self.title + " " + data_str self.file_out_full = self.file_out + '_' + data_comp + '.png' def reader_uv_by_time(self, n_time): with self.reader.open(): u = self.reader.get_variable(self.u_name, n_time) v = self.reader.get_variable(self.v_name, n_time) if len(u.shape) == 3: self.us = u[self.level, :-1, :- 1] self.vs = v[self.level, :-1, :-1] elif len(u.shape) == 2: self.us = u[:-1, :-1] self.vs = v[:-1, :-1] self.mod = pow((pow(self.us, 2) + pow(self.vs, 2)), .5) def reader_uv(self): self.reader_uv_by_time(self.time) def draw(self): drawcurrents(self.reader.coordinates_rank, self.nx, self.ny, self.scale, self.resolution, self.level, self.time, self.lats, self.lons, self.us, self.vs, self.mod, self.file_out_full, self.title_full, self.style, self.boundary_box) if __name__ == '__main__': main()
python
a,b=map(int,input().split()) print(-~(a+b)//2)
python
# script to create relationship classes in a GeMS database # # Somebody who uses relationship classes more than I should look at this. # Particularly, are the Forward and Backward labels named as usefully as possible? # Are there other issues? # # Note that Validate Database script can be used to maintain referential integrity, # thus I don't suggest use of relationship classes to accomplish this. # Ralph Haugerud, USGS # Use this mostly in order to see related records in Identify tool in ArcMap or in # the feature attribute pop-up in ArcGIS Pro. Note that the related table must in the map # in order for the related records to be displayed # Evan Thoms, USGS # GeMS_RelationshipClasses_AGP2.py # 6 June 2019: updated to work with Python 3 in ArcGIS Pro. Evan Thoms # ran the script through 2to3. No other edits necessary # renamed from GeMS_RelationshipClasses1_Arc10.py to GeMS_RelationshipClasses_AGP2.py # 7 November 2019: In response to issue raised at repo, completely rewritten to # 1) not create feature dataset just for the relationship classes. Found the # feature dataset could be written, but could not write relationship classes there. # Perhaps because it only had a name and no other properties, although this is probably # not best practices anyway. Relationship classes are now written in the workspace # in which the feature class is found # 2) create relationship classes based on controlled fields, not a list of explicit # relationship classes. Could result in many superfluous relationship classes # 3) attempt to work with table and field names regardless of case import arcpy import sys import os from GeMS_utilityFunctions import * versionString = 'GeMS_RelationshipClasses1_AGP2.py, version of 3 March 2021' rawurl = 'https://raw.githubusercontent.com/usgs/gems-tools-pro/master/Scripts/GeMS_RelationshipClasses_AGP2.py' checkVersion(versionString, rawurl, 'gems-tools-pro') def fname_find(field_string, table): # finds a field name regardless of the case of the search string (field_string) fields = arcpy.ListFields(table) for field in fields: if field.name.lower() == field_string.lower(): return field.name def tname_find(table_string): #find a table name regardless of case of search string (table_string) #searches the dictionary of table name: [root, path] for key in tab_dict: if key.lower() == table_string.lower(): return key def rc_handler(key, value, foreign_search, primary_search, origin_search): try: #sanitize the field and table names in case everything is in lower or upper case origin = tname_find(origin_search) d_key = fname_find(foreign_search, value[1]) o_key = fname_find(primary_search, tab_dict[origin][1]) #check for existing relationship class rc_name = '{}_{}'.format(key, d_key) if arcpy.Exists(rc_name): arcpy.Delete_management(rc_name) #create the relationship class addMsgAndPrint('Building {}'.format(rc_name)) #print(tab_dict[origin][1],value[1],rc_name,'SIMPLE','{} in {}'.format(o_key, key),'{} in {}'.format(d_key, origin), #'NONE','ONE_TO_MANY','NONE',o_key,d_key, sep=' | ') arcpy.CreateRelationshipClass_management(tab_dict[origin][1], value[1], rc_name, 'SIMPLE', '{} in {}'.format(o_key, key), '{} in {}'.format(d_key, origin), 'NONE', 'ONE_TO_MANY', 'NONE', o_key, d_key) except: print('Could not create relationship class {}'.format(rc_name)) inGdb = sys.argv[1] #make a dictionary of feature classes: [workspace, full path] walkfc = arcpy.da.Walk(inGdb, datatype='FeatureClass') fc_dict = {} for root, dirs, files in walkfc: for file in files: fc_path = os.path.join(root, file) if arcpy.Describe(fc_path).featureType != 'Annotation': fc_dict[file] = [root, fc_path] #make a dictionary of tables: [workspace, full path] walktab = arcpy.da.Walk(inGdb, datatype='Table') tab_dict = {} for root, dirs, files in walktab: for file in files: if file.find('.') == -1: tab_dict[file] = [root, os.path.join(root, file)] #run through the feature classes and create appropriate relationship classes for key, value in fc_dict.items(): arcpy.env.workspace = value[0] for field in arcpy.ListFields(value[1]): field_name = field.name.lower() if field_name == 'type' or field_name.find('confidence')> 0 and field.type == 'String': rc_handler(key, value, field.name, 'Term', 'Glossary') if field_name.find('source_id') > 0: rc_handler(key, value, field.name, 'DataSource_ID', 'DataSources') if field_name == 'geomaterial': rc_handler(key, value, field.name, 'GeoMaterial', 'GeoMaterialDict') if field_name == 'mapunit': rc_handler(key, value, field.name, 'MapUnit', 'DescriptionOfMapUnits') addMsgAndPrint('Done')
python
from PyQt5.QtGui import * from PyQt5.QtCore import * from PyQt5.QtWidgets import * import sys class MainWindow(QMainWindow): def __init__(self): super().__init__() self.setWindowTitle('Paint') self.setWindowIcon(QIcon('Images/Paint.png')) self.setMaximumSize(860, 720) self.setMinimumSize(860, 720) self.UI() def UI(self): self.Image = QImage(self.size(), QImage.Format_RGB32) self.Image.fill(Qt.white) self.Drawing = False self.BrushSize = 2 self.BrushColor = Qt.black self.LastPoint = QPoint() self.MainMenu = self.menuBar() self.FileMenu = self.MainMenu.addMenu('File') self.BrushSizeMenu = self.MainMenu.addMenu('Brush Size') self.BrushColorMenu = self.MainMenu.addMenu('Brush Color') self.OpenAction = QAction(QIcon('Images/Open.png'), 'Open', self) self.OpenAction.setShortcut(QKeySequence.Open) self.OpenAction.triggered.connect(self.Open) self.FileMenu.addAction(self.OpenAction) self.SaveAction = QAction(QIcon('Images/Save.png'), 'Save', self) self.SaveAction.setShortcut(QKeySequence.Save) self.SaveAction.triggered.connect(self.Save) self.FileMenu.addAction(self.SaveAction) self.ClearAction = QAction(QIcon('Images/Clear.png'), 'Clear', self) self.ClearAction.triggered.connect(self.Clear) self.FileMenu.addAction(self.ClearAction) self.QuitAction = QAction(QIcon('Images/Quit.png'), 'Quit', self) self.QuitAction.setShortcut(QKeySequence.Close) self.QuitAction.triggered.connect(self.closeEvent) self.FileMenu.addAction(self.QuitAction) self.OnepxAction = QAction(QIcon('Images/1.png'), 'One', self) self.OnepxAction.triggered.connect(self.One) self.BrushSizeMenu.addAction(self.OnepxAction) self.TwopxAction = QAction(QIcon('Images/2.png'), 'Two', self) self.TwopxAction.triggered.connect(self.Two) self.BrushSizeMenu.addAction(self.TwopxAction) self.ThreepxAction = QAction(QIcon('Images/3.png'), 'Three', self) self.ThreepxAction.triggered.connect(self.Three) self.BrushSizeMenu.addAction(self.ThreepxAction) self.FourpxAction = QAction(QIcon('Images/4.png'), 'Four', self) self.FourpxAction.triggered.connect(self.Four) self.BrushSizeMenu.addAction(self.FourpxAction) self.FivepxAction = QAction(QIcon('Images/5.png'), 'Five', self) self.FivepxAction.triggered.connect(self.Five) self.BrushSizeMenu.addAction(self.FivepxAction) self.SixpxAction = QAction(QIcon('Images/6.png'), 'Six', self) self.SixpxAction.triggered.connect(self.Six) self.BrushSizeMenu.addAction(self.SixpxAction) self.SevenpxAction = QAction(QIcon('Images/7.png'), 'Seven', self) self.SevenpxAction.triggered.connect(self.Seven) self.BrushSizeMenu.addAction(self.SevenpxAction) self.EightpxAction = QAction(QIcon('Images/7.png'), 'Eight', self) self.EightpxAction.triggered.connect(self.Eight) self.BrushSizeMenu.addAction(self.EightpxAction) self.NinepxAction = QAction(QIcon('Images/9.png'), 'Nine', self) self.NinepxAction.triggered.connect(self.Nine) self.BrushSizeMenu.addAction(self.NinepxAction) self.MessageAction = QAction(QIcon('Images/Colors'), 'Standard Colors', self) self.MessageAction.setText('Standard Colors') self.BrushColorMenu.addAction(self.MessageAction) self.BrushColorMenu.addSeparator() # self.WhiteAction = QAction(QIcon('Images/White.png'), 'White',self) # self.WhiteAction.triggered.connect(self.White) # self.BrushColorMenu.addAction(self.WhiteAction) self.BlackAction = QAction(QIcon('Images/Black.png'), 'Black', self) self.BlackAction.triggered.connect(self.Black) self.BrushColorMenu.addAction(self.BlackAction) self.DarkGrayAction = QAction(QIcon('Images/Dark Gray.png'), 'Dark Gray', self) self.DarkGrayAction.triggered.connect(self.DarkGray) self.BrushColorMenu.addAction(self.DarkGrayAction) self.GrayAction = QAction(QIcon('Images/Gray.png'), 'Gray', self) self.GrayAction.triggered.connect(self.Gray) self.BrushColorMenu.addAction(self.GrayAction) self.LightGrayAction = QAction(QIcon('Images/Light Gray.png'), 'Light Gray', self) self.LightGrayAction.triggered.connect(self.LightGray) self.BrushColorMenu.addAction(self.LightGrayAction) self.DarkRedAction = QAction(QIcon('Images/Dark Red.png'), 'Dark Red', self) self.DarkRedAction.triggered.connect(self.DarkRed) self.BrushColorMenu.addAction(self.DarkRedAction) self.BrownAction = QAction(QIcon('Images/Brown.png'), 'Brown', self) self.BrownAction.triggered.connect(self.Brown) self.BrushColorMenu.addAction(self.BrownAction) self.RedAction = QAction(QIcon('Images/Red.png'), 'Red', self) self.RedAction.triggered.connect(self.Red) self.BrushColorMenu.addAction(self.RedAction) self.PinkAction = QAction(QIcon('Images/Pink.png'), 'Pink', self) self.PinkAction.triggered.connect(self.Pink) self.BrushColorMenu.addAction(self.PinkAction) self.DarkYellowAction = QAction(QIcon('Images/Dark Yellow.png'), 'Dark Yellow', self) self.DarkYellowAction.triggered.connect(self.DarkYellow) self.BrushColorMenu.addAction(self.DarkYellowAction) self.YellowAction = QAction(QIcon('Images/Yellow.png'), 'Yellow', self) self.YellowAction.triggered.connect(self.Yellow) self.BrushColorMenu.addAction(self.YellowAction) self.LightYellowAction = QAction(QIcon('Images/Light Yellow.png'), 'Light Yellow', self) self.LightYellowAction.triggered.connect(self.LightYellow) self.BrushColorMenu.addAction(self.LightYellowAction) self.OrangeAction = QAction(QIcon('Images/Orange.png'), 'Orange', self) self.OrangeAction.triggered.connect(self.Orange) self.BrushColorMenu.addAction(self.OrangeAction) self.DarkGreenAction = QAction(QIcon('Images/Dark Green.png'), 'Dark Green', self) self.DarkGreenAction.triggered.connect(self.DarkGreen) self.BrushColorMenu.addAction(self.DarkGreenAction) self.GreenAction = QAction(QIcon('Images/Green.png'), 'Green', self) self.GreenAction.triggered.connect(self.Green) self.BrushColorMenu.addAction(self.GreenAction) self.LightGreenAction = QAction(QIcon('Images/Light Green.png'), 'Light Green', self) self.LightGreenAction.triggered.connect(self.LightGreen) self.BrushColorMenu.addAction(self.LightGreenAction) self.LightBlueAction = QAction(QIcon('Images/Light Blue.png'), 'Light Blue', self) self.LightBlueAction.triggered.connect(self.LightBlue) self.BrushColorMenu.addAction(self.LightBlueAction) self.BlueAction = QAction(QIcon('Images/Blue.png'), 'Blue', self) self.BlueAction.triggered.connect(self.Blue) self.BrushColorMenu.addAction(self.BlueAction) self.DarkBlueAction = QAction(QIcon('Images/Dark Blue.png'), 'Dark Blue', self) self.DarkBlueAction.triggered.connect(self.DarkBlue) self.BrushColorMenu.addAction(self.DarkBlueAction) self.MarineBlueAction = QAction(QIcon('Images/Marine Blue.png'), 'Marine Blue', self) self.MarineBlueAction.triggered.connect(self.MarineBlue) self.BrushColorMenu.addAction(self.MarineBlueAction) self.VioletAction = QAction(QIcon('Images/Purple.png'), 'Purple', self) self.VioletAction.triggered.connect(self.Purple) self.BrushColorMenu.addAction(self.VioletAction) self.BrushColorMenu.addSeparator() self.SelectColorAction = QAction(QIcon('Images/Color Picker.png'), 'Select Color', self) self.SelectColorAction.triggered.connect(self.ColorDialog) self.BrushColorMenu.addAction(self.SelectColorAction) def mousePressEvent(self, event): if event.button() == Qt.LeftButton: self.Drawing = True self.LastPoint = event.pos() # print(self.LastPoint) def mouseMoveEvent(self, event): if (event.buttons() == Qt.LeftButton) and self.Drawing: Painter = QPainter(self.Image) Painter.setPen(QPen(self.BrushColor, self.BrushSize, Qt.SolidLine, Qt.RoundCap, Qt.RoundJoin)) Painter.drawLine(self.LastPoint, event.pos()) self.LastPoint = event.pos() self.update() def mouseReleaseEvent(self, event): if event.button == Qt.LeftButton: self.Drawing = False def paintEvent(self, event): canvasPainter = QPainter(self) canvasPainter.drawImage(self.rect(), self.Image, self.Image.rect()) def Save(self): filePath, _ = QFileDialog.getSaveFileName(self, 'Save Image', '', '*.PNG') if filePath == '': return self.Image.save(filePath) def Clear(self): self.Image.fill(Qt.white) self.update() def closeEvent(self, event): text = '''Are you sure you want to Quit?\nAny unsaved work will be lost.''' reply = QMessageBox.question( self, 'Warning!', text, QMessageBox.Save | QMessageBox.Cancel | QMessageBox.Close ) if reply == QMessageBox.Close: QApplication.quit() elif reply == QMessageBox.Save: self.Save() elif reply == QMessageBox.Cancel: pass else: pass def keyPressEvent(self, event): if event.key() == Qt.Key_Escape: QApplication.quit() def ColorDialog(self): self.Dailog = QColorDialog() self.Dailog.exec_() self.Value = self.Dailog.selectedColor() print(self.Value) self.BrushColor = self.Value def Open(self, event): filename = QFileDialog.getOpenFileName() imagepath = filename[0] print(imagepath) image = QImage(imagepath) painter = QPainter(self.Image) painter.setPen(QPen(Qt.NoPen)) height = image.height() width = image.width() painter.drawImage(QRect(0, 0, height * 2, width * 2), image) def One(self): self.BrushSize = 1 def Two(self): self.BrushSize = 2 def Three(self): self.BrushSize = 3 def Four(self): self.BrushSize = 4 def Five(self): self.BrushSize = 5 def Six(self): self.BrushSize = 6 def Seven(self): self.BrushSize = 7 def Eight(self): self.BrushSize = 8 def Nine(self): self.BrushSize = 9 def Black(self): self.BrushColor = Qt.black def Red(self): self.BrushColor = Qt.red def Yellow(self): self.BrushColor = Qt.yellow def LightBlue(self): self.BrushColor = QColor(173, 216, 230) def DarkBlue(self): self.BrushColor = Qt.darkBlue def Orange(self): self.BrushColor = QColor(255, 165, 0) def LightGreen(self): self.BrushColor = QColor(144, 238, 144) def DarkGreen(self): self.BrushColor = Qt.darkGreen def Purple(self): self.BrushColor = QColor(128, 0, 128) def Brown(self): self.BrushColor = QColor(165, 42, 42) def White(self): self.BrushColor = Qt.white def MarineBlue(self): self.BrushColor = QColor(0, 119, 190) def LightGray(self): self.BrushColor = Qt.lightGray def DarkGray(self): self.BrushColor = Qt.darkGray def Gray(self): self.BrushColor = Qt.gray def DarkRed(self): self.BrushColor = Qt.darkRed def Pink(self): self.BrushColor = QColor(247, 120, 193) def DarkYellow(self): self.BrushColor = Qt.darkYellow def LightYellow(self): self.BrushColor = QColor(244, 247, 155) def Green(self): self.BrushColor = Qt.green def Blue(self): self.BrushColor = Qt.blue App = QApplication(sys.argv) Main = MainWindow() Main.resize(640, 480) Main.show() sys.exit(App.exec_())
python
# Run detection in real-time setting on a COCO-format dataset import argparse, json, pickle from os.path import join, isfile from time import perf_counter from tqdm import tqdm import numpy as np import torch from pycocotools.coco import COCO from mmcv.runner import load_checkpoint import sys; sys.path.insert(0, '..'); sys.path.insert(0, '.') from util import mkdir2, print_stats from det import imread, parse_det_result, vis_det, eval_ccf from det.det_apis import \ init_detector, inference_detector, \ ImageTransform, ImageTransformGPU, _prepare_data import train.models def parse_args(): parser = argparse.ArgumentParser() parser.add_argument('--data-root', type=str, required=True) parser.add_argument('--annot-path', type=str, required=True) parser.add_argument('--in-scale', type=float, default=None) parser.add_argument('--fps', type=float, default=30) parser.add_argument('--no-mask', action='store_true', default=False) parser.add_argument('--no-class-mapping', action='store_true', default=False) parser.add_argument('--cpu-pre', action='store_true', default=False) parser.add_argument('--out-dir', type=str, required=True) parser.add_argument('--vis-dir', type=str, default=None) parser.add_argument('--vis-scale', type=float, default=1) parser.add_argument('--config', type=str, default=None) parser.add_argument('--weights', type=str, default=None) parser.add_argument('--weights-base', type=str, default=None) parser.add_argument('--n-history', type=int, default=None) parser.add_argument('--n-future', type=int, default=None) parser.add_argument('--no-eval', action='store_true', default=False) parser.add_argument('--overwrite', action='store_true', default=False) opts = parser.parse_args() return opts def main(): assert torch.cuda.device_count() == 1 # mmdet only supports single GPU testing opts = parse_args() mkdir2(opts.out_dir) vis_out = bool(opts.vis_dir) if vis_out: mkdir2(opts.vis_dir) db = COCO(opts.annot_path) class_names = [c['name'] for c in db.dataset['categories']] n_class = len(class_names) coco_mapping = None if opts.no_class_mapping else db.dataset.get('coco_mapping', None) if coco_mapping is not None: coco_mapping = np.asarray(coco_mapping) seqs = db.dataset['sequences'] seq_dirs = db.dataset['seq_dirs'] model = init_detector(opts) if opts.weights_base is not None: # for distillation purpose load_checkpoint(model, opts.weights_base) if opts.cpu_pre: img_transform = ImageTransform( size_divisor=model.cfg.data.test.size_divisor, **model.cfg.img_norm_cfg) else: img_transform = ImageTransformGPU( size_divisor=model.cfg.data.test.size_divisor, **model.cfg.img_norm_cfg) device = next(model.parameters()).device # model device n_history = model.cfg.data.train.n_history if opts.n_history is None else opts.n_history n_future = model.cfg.data.train.n_future if opts.n_future is None else opts.n_future results_ccf = [] # instance based runtime_all = [] for sid, seq in enumerate(tqdm(seqs)): # print(seq) frame_list = [img for img in db.imgs.values() if img['sid'] == sid] n_frame = len(frame_list) # load all frames in advance frames = [] for img in frame_list: img_path = join(opts.data_root, seq_dirs[sid], img['name']) frames.append(imread(img_path)) with torch.no_grad(): preprocessed = [] for i in range(n_history): data = _prepare_data(frames[i], img_transform, model.cfg, device) preprocessed.append(data) for ii in range(n_history, n_frame - n_future): # target frame iid = frame_list[ii + n_future]['id'] img_name = frame_list[ii + n_future]['name'] I = frames[ii + n_future] t_start = perf_counter() # input frame data = _prepare_data(frames[ii], img_transform, model.cfg, device) # if n_history == 0: # data_merge = data # # print(data['img']) # # print(data['img'][0].shape) # # print(data['img'][0][0][0][300][300:305]) # # import sys # # sys.exit() # else: preprocessed.append(data) # print(preprocessed[0]['img'][0].data_ptr()) # print(preprocessed[2]['img'][0].data_ptr()) # print(torch.all(preprocessed[0]['img'][0] == preprocessed[2]['img'][0])) imgs = [d['img'][0] for d in preprocessed] imgs = torch.cat(imgs, 0) imgs = imgs.unsqueeze(0) data_merge = { 'img': [imgs], 'img_meta': data['img_meta'], } # print(data_merge['img'][0][0][2][0][300][300:305]) # import sys # sys.exit() result = model(return_loss=False, rescale=True, numpy_res=True, **data_merge) bboxes, scores, labels, masks = \ parse_det_result(result, coco_mapping, n_class) # if ii == 2: # print(ii, scores) # import sys # sys.exit() # if n_history != 0: del preprocessed[0] t_end = perf_counter() runtime_all.append(t_end - t_start) if vis_out: vis_path = join(opts.vis_dir, seq, img_name[:-3] + 'jpg') if opts.overwrite or not isfile(vis_path): vis_det( I, bboxes, labels, class_names, masks, scores, out_scale=opts.vis_scale, out_file=vis_path ) # convert to coco fmt n = len(bboxes) if n: bboxes[:, 2:] -= bboxes[:, :2] for i in range(n): result_dict = { 'image_id': iid, 'bbox': bboxes[i], 'score': scores[i], 'category_id': labels[i], } if masks is not None: result_dict['segmentation'] = masks[i] results_ccf.append(result_dict) out_path = join(opts.out_dir, 'time_info.pkl') if opts.overwrite or not isfile(out_path): pickle.dump({ 'runtime_all': runtime_all, 'n_total': len(runtime_all), }, open(out_path, 'wb')) # convert to ms for display s2ms = lambda x: 1e3*x print_stats(runtime_all, 'Runtime (ms)', cvt=s2ms) out_path = join(opts.out_dir, 'results_ccf.pkl') if opts.overwrite or not isfile(out_path): pickle.dump(results_ccf, open(out_path, 'wb')) if not opts.no_eval: eval_summary = eval_ccf(db, results_ccf) out_path = join(opts.out_dir, 'eval_summary.pkl') if opts.overwrite or not isfile(out_path): pickle.dump(eval_summary, open(out_path, 'wb')) if vis_out: print(f'python vis/make_videos.py "{opts.vis_dir}"') if __name__ == '__main__': main()
python
import os import glob from imageai.Detection.Custom import DetectionModelTrainer execution_path = os.getcwd() models_path = os.path.join(execution_path, "doge-identification/models/") data_path = os.path.join(execution_path, "doge-identification/") # This will force tensorflow to run on the cpu os.environ["CUDA_VISIBLE_DEVICES"] = "-1" list_of_files = glob.glob(models_path + "*.h5") latest_model_path = max(list_of_files, key=os.path.getctime) path, newest_model = os.path.split(latest_model_path) print("Newest Model: ", newest_model) trainer = DetectionModelTrainer() trainer.setModelTypeAsYOLOv3() trainer.setDataDirectory(data_directory=data_path) metrics = trainer.evaluateModel( model_path=latest_model_path, json_path=os.path.join(execution_path, "doge-identification/json/detection_config.json"), iou_threshold=0.5, object_threshold=0.3, nms_threshold=0.5)
python
# This file is part of the CERN Indico plugins. # Copyright (C) 2014 - 2020 CERN # # The CERN Indico plugins are free software; you can redistribute # them and/or modify them under the terms of the MIT License; see # the LICENSE file for more details. from __future__ import unicode_literals from wtforms.fields import StringField from wtforms.validators import DataRequired from indico.web.forms.base import IndicoForm from indico.web.forms.fields import IndicoPasswordField from indico_livesync_cern import _ class SettingsForm(IndicoForm): username = StringField(_("Username"), validators=[DataRequired()], description=_("The username to access the category ID/title mapping")) password = IndicoPasswordField(_('Password'), [DataRequired()], toggle=True, description=_("The password to access the category ID/title mapping"))
python
"""Error handlers.""" from werkzeug.http import HTTP_STATUS_CODES from flask import jsonify from muckr_api.extensions import database class APIError(Exception): def __init__(self, status_code, message=None, details=None): super().__init__() error = HTTP_STATUS_CODES.get(status_code, "Unknown error") self.status_code = status_code self.payload = {"error": error} if message is not None: self.payload["message"] = message if details is not None: self.payload["details"] = details def handle(self): response = jsonify(self.payload) response.status_code = self.status_code response.mimetype = "application/json" return response def handle_error(error): # If a HTTPException, pull the `code` attribute; default to 500 status_code = getattr(error, "code", 500) if status_code == 500: database.session.rollback() return APIError(status_code).handle()
python
from django.conf.urls import url from .views import Dashboard urlpatterns = [ url(r'^$', Dashboard.as_view()), ]
python
############################################################################## # # Copyright (c) 2002 Zope Foundation and Contributors. # # This software is subject to the provisions of the Zope Public License, # Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution. # THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED # WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED # WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS # FOR A PARTICULAR PURPOSE. # ############################################################################## class RequestCache(dict): # stats info needed for testing _hits = 0 _misses = 0 _sets = 0 def get(self, key, default=None): try: value = self[key] except KeyError: return default return value def __getitem__(self, key): try: value = super(RequestCache, self).__getitem__(key) except KeyError as e: self._misses += 1 raise e self._hits += 1 return value def __setitem__(self, key, value): super(RequestCache, self).__setitem__(key, value) self._sets += 1 def clear(self): super(RequestCache, self).clear() self._hits = 0 self._misses = 0 self._sets = 0 def stats(self): stats = {'hits': self._hits, 'misses': self._misses, 'sets': self._sets} return stats def __str__(self): return ('<RequestCache {0} items (hits: {1}, misses: {2},', ' sets: {3})>').format(len(self), self._hits, self._misses, self._sets)
python
from typing import List import msgpack from pydantic import BaseModel import ormsgpack class Member(BaseModel): id: int active: bool class Object(BaseModel): id: int name: str members: List[Member] objects_as_pydantic = [ Object( id=i, name=str(i) * 3, members=[Member(id=j, active=True) for j in range(0, 10)] ) for i in range(100000, 102000) ] def default(__obj): if isinstance(__obj, BaseModel): return __obj.dict() def test_pydantic_msgpack(benchmark): benchmark.group = "pydantic" benchmark(msgpack.packb, objects_as_pydantic, default=default) def test_pydantic_ormsgpack(benchmark): benchmark.group = "pydantic" benchmark( ormsgpack.packb, objects_as_pydantic, option=ormsgpack.OPT_SERIALIZE_PYDANTIC )
python
#!/usr/bin/env python from breakmywork.application import main main()
python
import inferpy as inf def test_parameter_in_pmodel(): # test that random variables in pmodel works even if no name has been provided @inf.probmodel def model(): inf.Parameter(0) v = list(model().params.values())[0] assert v.name.startswith('parameter') # assert also is_datamodel is false assert not v.is_datamodel def test_parameter_in_datamodel(): with inf.datamodel(10): x = inf.Parameter(0) # assert that is_datamodel is true assert x.is_datamodel def test_run_in_session(): x = inf.Parameter(0) assert inf.get_session().run(x) == 0
python
import FWCore.ParameterSet.Config as cms from Configuration.Eras.Era_Phase2C11I13_cff import Phase2C11I13 from Configuration.Eras.Modifier_phase2_3DPixels_cff import phase2_3DPixels from Configuration.Eras.Modifier_phase2_GE0_cff import phase2_GE0 Phase2C11I13T25M9 = cms.ModifierChain(Phase2C11I13, phase2_3DPixels, phase2_GE0)
python
import numpy as np class RandomParameters: """ Example params are in JSON format: { "booster": ["gbtree", "gblinear"], "objective": ["binary:logistic"], "eval_metric": ["auc", "logloss"], "eta": [0.0025, 0.005, 0.0075, 0.01, 0.025, 0.05, 0.075, 0.1] } """ @staticmethod def get(params, seed=1): np.random.seed(seed) generated_params = {"seed": seed} for k in params: generated_params[k] = np.random.permutation(params[k])[0].item() return generated_params
python
import sys,os,pygame
python
# Generated by Django 3.0.6 on 2020-05-25 00:02 import datetime from django.conf import settings from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ] operations = [ migrations.CreateModel( name='Cats', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('name', models.CharField(max_length=200)), ('birthday', models.DateField()), ('owner', models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, to=settings.AUTH_USER_MODEL)), ], ), migrations.CreateModel( name='GSBrand', fields=[ ('brand', models.CharField(max_length=100, primary_key=True, serialize=False)), ('concentration', models.DecimalField(decimal_places=2, max_digits=2)), ], ), migrations.CreateModel( name='WarriorAdmin', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('warrior_admin', models.CharField(max_length=200)), ], ), migrations.CreateModel( name='UserExtension', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('userid', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)), ('warrior_admin', models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, to='InjectionLog.WarriorAdmin')), ], ), migrations.CreateModel( name='InjectionLog', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('date_added', models.DateField(default=datetime.date.today, editable=False)), ('cat_weight', models.DecimalField(decimal_places=2, max_digits=2)), ('injection_time', models.TimeField()), ('injection_amount', models.DecimalField(decimal_places=1, max_digits=2)), ('cat_behavior_today', models.IntegerField(default=3)), ('injection_notes', models.TextField(null=True)), ('gaba_dose', models.IntegerField(null=True)), ('other_notes', models.TextField(null=True)), ('cat_name', models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, to='InjectionLog.Cats')), ('gs_brand', models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, to='InjectionLog.GSBrand')), ('owner', models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, to=settings.AUTH_USER_MODEL)), ], ), ]
python
from tests.save_restore_cursor import SaveRestoreCursorTests import esccmd from escutil import knownBug class DECSETTiteInhibitTests(SaveRestoreCursorTests): def __init__(self): SaveRestoreCursorTests.__init__(self) def saveCursor(self): esccmd.DECSET(esccmd.SaveRestoreCursor) def restoreCursor(self): esccmd.DECRESET(esccmd.SaveRestoreCursor) @knownBug(terminal="iTerm2", reason="Not implemented") def test_SaveRestoreCursor_Basic(self): SaveRestoreCursorTests.test_SaveRestoreCursor_Basic(self) @knownBug(terminal="iTerm2", reason="Not implemented") def test_SaveRestoreCursor_MoveToHomeWhenNotSaved(self): SaveRestoreCursorTests.test_SaveRestoreCursor_MoveToHomeWhenNotSaved(self) @knownBug(terminal="iTerm2", reason="Not implemented") def test_SaveRestoreCursor_ResetsOriginMode(self): SaveRestoreCursorTests.test_SaveRestoreCursor_ResetsOriginMode(self) @knownBug(terminal="iTerm2", reason="Not implemented") def test_SaveRestoreCursor_WorksInLRM(self, shouldWork=True): SaveRestoreCursorTests.test_SaveRestoreCursor_WorksInLRM(self) @knownBug(terminal="iTerm2", reason="Not implemented") def test_SaveRestoreCursor_AltVsMain(self): SaveRestoreCursorTests.test_SaveRestoreCursor_AltVsMain(self) @knownBug(terminal="iTerm2", reason="Not implemented") def test_SaveRestoreCursor_Protection(self): SaveRestoreCursorTests.test_SaveRestoreCursor_Protection(self) @knownBug(terminal="iTerm2", reason="Not implemented") def test_SaveRestoreCursor_Wrap(self): SaveRestoreCursorTests.test_SaveRestoreCursor_Wrap(self) @knownBug(terminal="iTerm2", reason="Not implemented", noop=True) def test_SaveRestoreCursor_ReverseWrapNotAffected(self): SaveRestoreCursorTests.test_SaveRestoreCursor_ReverseWrapNotAffected(self) @knownBug(terminal="iTerm2", reason="Not implemented", noop=True) def test_SaveRestoreCursor_InsertNotAffected(self): SaveRestoreCursorTests.test_SaveRestoreCursor_InsertNotAffected(self)
python
from domain.rules import game_loops connect_game = game_loops.Game_Loops() ''' here we call the game loop function''' connect_game.connect_four_game()
python
from flask import Flask, request, render_template, url_for, send_file import qrcode from PIL import Image app = Flask(__name__) @app.route('/') def index(): return render_template('index.html') @app.route('/result', methods=["POST", "GET"]) def result(): if request.method == "POST": input = request.form data = input["text-input"] filename = str(input["filename-input"] + ".png") # Convert qr = qrcode.QRCode( version = 5, error_correction=qrcode.constants.ERROR_CORRECT_H, box_size = 10, border = 5 ) # adding data qr.add_data(data) img = qr.make_image(fill="black", back_color="white") # saving result img.save(filename) return send_file(filename, mimetype="image") if __name__ == "__main__": app.run(debug=True)
python
# python peripherals import os import numpy import random import queue from multiprocessing import Process, Queue, cpu_count # torch import torch from torch.utils.data import Dataset # deep_signature from deep_signature.data_generation import curve_generation from deep_signature.data_generation import dataset_generation from deep_signature.data_manipulation import curve_processing class DeepSignaturePairsDataset(Dataset): def __init__(self): self._pairs = None self._labels = None def load_dataset(self, negative_pairs_dir_path, positive_pairs_dir_path): negative_pairs = numpy.load(file=os.path.normpath(os.path.join(negative_pairs_dir_path, 'negative_pairs.npy')), allow_pickle=True) positive_pairs = numpy.load(file=os.path.normpath(os.path.join(positive_pairs_dir_path, 'positive_pairs.npy')), allow_pickle=True) full_pairs_count = negative_pairs.shape[0] + positive_pairs.shape[0] random.shuffle(negative_pairs) random.shuffle(positive_pairs) self._pairs = numpy.empty((full_pairs_count, negative_pairs.shape[1], negative_pairs.shape[2], negative_pairs.shape[3])) self._pairs[:negative_pairs.shape[0], :] = negative_pairs self._pairs[negative_pairs.shape[0]:, :] = positive_pairs negaitve_labels = numpy.zeros(negative_pairs.shape[0]) positive_labels = numpy.ones(positive_pairs.shape[0]) self._labels = numpy.empty(full_pairs_count) self._labels[:negative_pairs.shape[0]] = negaitve_labels self._labels[negative_pairs.shape[0]:] = positive_labels def __len__(self): return self._labels.shape[0] def __getitem__(self, idx): pair = self._pairs[idx, :] for i in range(2): if not curve_processing.is_ccw(curve=pair[i]): pair[i] = numpy.flip(pair[i], axis=0) for i in range(2): radians = curve_processing.calculate_secant_angle(curve=pair[i]) pair[i] = curve_processing.rotate_curve(curve=pair[i], radians=radians) pair_torch = torch.from_numpy(pair).cuda().double() label_torch = torch.from_numpy(numpy.array([self._labels[idx]])).cuda().double() return { 'input': pair_torch, 'labels': label_torch } class DeepSignatureTupletsDataset(Dataset): def __init__(self): self._tuplets = None def load_dataset(self, dir_path): self._tuplets = numpy.load(file=os.path.normpath(os.path.join(dir_path, 'tuplets.npy')), allow_pickle=True) def __len__(self): return self._tuplets.shape[0] def __getitem__(self, index): item = {} tuplet = self._tuplets[index] for key in tuplet.keys(): item[key] = torch.from_numpy(numpy.array(self._tuplets[index][key]).astype('float64')).cuda().double() return item class EuclideanTuple: @staticmethod def _generate_curvature_tuple(curves, sampling_ratio, multimodality, supporting_points_count, offset_length, negative_examples_count): return dataset_generation.EuclideanCurvatureTupletsDatasetGenerator.generate_tuple( curves=curves, sampling_ratio=sampling_ratio, multimodality=multimodality, supporting_points_count=supporting_points_count, offset_length=offset_length, negative_examples_count=negative_examples_count) @staticmethod def _generate_arclength_tuple(curves, min_offset, max_offset, multimodality, supporting_points_count, anchor_points_count): return dataset_generation.EuclideanArcLengthTupletsDatasetGenerator.generate_tuple( curves=curves, min_offset=min_offset, max_offset=max_offset, multimodality=multimodality, supporting_points_count=supporting_points_count, anchor_points_count=anchor_points_count) class EquiaffineTuple: @staticmethod def _generate_curvature_tuple(curves, sampling_ratio, multimodality, supporting_points_count, offset_length, negative_examples_count): return dataset_generation.EquiaffineCurvatureTupletsDatasetGenerator.generate_tuple( curves=curves, sampling_ratio=sampling_ratio, multimodality=multimodality, supporting_points_count=supporting_points_count, offset_length=offset_length, negative_examples_count=negative_examples_count) @staticmethod def _generate_arclength_tuple(curves, min_offset, max_offset, multimodality, supporting_points_count, anchor_points_count): return dataset_generation.EquiaffineArcLengthTupletsDatasetGenerator.generate_tuple( curves=curves, min_offset=min_offset, max_offset=max_offset, multimodality=multimodality, supporting_points_count=supporting_points_count, anchor_points_count=anchor_points_count) class AffineTuple: @staticmethod def _generate_curvature_tuple(curves, sampling_ratio, multimodality, supporting_points_count, offset_length, negative_examples_count): return dataset_generation.AffineCurvatureTupletsDatasetGenerator.generate_tuple( curves=curves, sampling_ratio=sampling_ratio, multimodality=multimodality, supporting_points_count=supporting_points_count, offset_length=offset_length, negative_examples_count=negative_examples_count) @staticmethod def _generate_arclength_tuple(curves, min_offset, max_offset, multimodality, supporting_points_count, anchor_points_count): return dataset_generation.AffineArcLengthTupletsDatasetGenerator.generate_tuple( curves=curves, min_offset=min_offset, max_offset=max_offset, multimodality=multimodality, supporting_points_count=supporting_points_count, anchor_points_count=anchor_points_count) class DeepSignatureTupletsOnlineDataset(Dataset): def __init__(self, dataset_size, dir_path, multimodality, replace, buffer_size, num_workers): self._curves = curve_generation.CurvesGenerator.load_curves(dir_path) self._dataset_size = dataset_size self._multimodality = multimodality self._replace = replace self._buffer_size = buffer_size self._num_workers = num_workers self._q = Queue(maxsize=dataset_size) self._args = [self._curves, self._multimodality, self._q] self._items = [] def __len__(self): return self._dataset_size def __getitem__(self, index): item = {} mod_index = numpy.mod(index, self._buffer_size) tuplet = self._items[mod_index] for key in tuplet.keys(): if key == 'input': item[key] = torch.from_numpy(numpy.array(tuplet[key]).astype('float64')).cuda().double() else: item[key] = tuplet[key] if self._replace is True: try: new_tuplet = self._q.get_nowait() rand_index = int(numpy.random.randint(self._buffer_size, size=1)) self._items[rand_index] = new_tuplet except queue.Empty: pass return item def start(self): self._workers = [Process(target=self._map_func, args=self._args) for i in range(self._num_workers)] for i, worker in enumerate(self._workers): worker.start() print(f'\rWorker Started {i+1} / {self._num_workers}', end='') print(f'\nItem {len(self._items)} / {self._buffer_size}', end='') while True: if self._q.empty() is False: self._items.append(self._q.get()) print(f'\rItem {len(self._items)} / {self._buffer_size}', end='') if len(self._items) == self._buffer_size: break def stop(self): for i, worker in enumerate(self._workers): worker.terminate() class DeepSignatureCurvatureTupletsOnlineDataset(DeepSignatureTupletsOnlineDataset): def __init__(self, dataset_size, dir_path, multimodality, replace, buffer_size, num_workers, sampling_ratio, supporting_points_count, offset_length, negative_examples_count): DeepSignatureTupletsOnlineDataset.__init__( self, dataset_size=dataset_size, dir_path=dir_path, multimodality=multimodality, replace=replace, buffer_size=buffer_size, num_workers=num_workers) self._sampling_ratio = sampling_ratio self._args.append(sampling_ratio) self._supporting_points_count = supporting_points_count self._args.append(supporting_points_count) self._offset_length = offset_length self._args.append(offset_length) self._negative_examples_count = negative_examples_count self._args.append(negative_examples_count) @classmethod def _map_func(cls, curves, multimodality, q, sampling_ratio, supporting_points_count, offset_length, negative_examples_count): while True: q.put(cls._generate_curvature_tuple( curves=curves, sampling_ratio=sampling_ratio, multimodality=multimodality, supporting_points_count=supporting_points_count, offset_length=offset_length, negative_examples_count=negative_examples_count)) class DeepSignatureEuclideanCurvatureTupletsOnlineDataset(DeepSignatureCurvatureTupletsOnlineDataset, EuclideanTuple): pass class DeepSignatureEquiaffineCurvatureTupletsOnlineDataset(DeepSignatureCurvatureTupletsOnlineDataset, EquiaffineTuple): pass class DeepSignatureAffineCurvatureTupletsOnlineDataset(DeepSignatureCurvatureTupletsOnlineDataset, AffineTuple): pass class DeepSignatureArclengthTupletsOnlineDataset(DeepSignatureTupletsOnlineDataset): def __init__(self, dataset_size, dir_path, multimodality, replace, buffer_size, num_workers, supporting_points_count, min_offset, max_offset, anchor_points_count): DeepSignatureTupletsOnlineDataset.__init__( self, dataset_size=dataset_size, dir_path=dir_path, multimodality=multimodality, replace=replace, buffer_size=buffer_size, num_workers=num_workers) self._supporting_points_count = supporting_points_count self._args.append(supporting_points_count) self._min_offset = min_offset self._args.append(min_offset) self._max_offset = max_offset self._args.append(max_offset) self._anchor_points_count = anchor_points_count self._args.append(anchor_points_count) @classmethod def _map_func(cls, curves, multimodality, q, supporting_points_count, min_offset, max_offset, anchor_points_count): while True: q.put(cls._generate_arclength_tuple( curves=curves, min_offset=min_offset, max_offset=max_offset, multimodality=multimodality, supporting_points_count=supporting_points_count, anchor_points_count=anchor_points_count)) class DeepSignatureEuclideanArclengthTupletsOnlineDataset(DeepSignatureArclengthTupletsOnlineDataset, EuclideanTuple): pass class DeepSignatureEquiaffineArclengthTupletsOnlineDataset(DeepSignatureArclengthTupletsOnlineDataset, EquiaffineTuple): pass class DeepSignatureAffineArclengthTupletsOnlineDataset(DeepSignatureArclengthTupletsOnlineDataset, AffineTuple): pass
python
""" This file demonstrates writing tests using the unittest module. These will pass when you run "manage.py test". Replace this with more appropriate tests for your application. """ # standard library # django from django.contrib import admin from django.core.urlresolvers import NoReverseMatch from django.core.urlresolvers import resolve from django.core.urlresolvers import reverse from django.db import models from django.test import TestCase # urls from project.urls import urlpatterns # utils from base.utils import camel_to_underscore from base.utils import get_our_models # Third-party app imports from model_mommy import mommy from model_mommy import random_gen class BaseTestCase(TestCase): def setUp(self): super(BaseTestCase, self).setUp() self.password = random_gen.gen_text() self.user = mommy.prepare('users.User') self.user.set_password(self.password) self.user.save() self.login() def login(self, user=None, password=None): if user is None: user = self.user password = self.password return self.client.login(email=user.email, password=password) class IntegrityOnDeleteTestCase(BaseTestCase): def create_full_object(self, model): kwargs = {} for f in model._meta.fields: if isinstance(f, models.fields.related.ForeignKey) and f.null: kwargs[f.name] = mommy.make(f.rel.to) return mommy.make(model, **kwargs), kwargs def test_integrity_on_delete(self): for model in get_our_models(): obj, related_nullable_objects = self.create_full_object(model) obj_count = model.objects.count() for relation_name, rel_obj in related_nullable_objects.items(): try: # check if the test should be skipped if relation_name in obj.exclude_on_on_delete_test: continue except AttributeError: pass rel_obj.delete() error_msg = ( '<{}> object, was deleted after deleting a nullable ' 'related <{}> object, the relation was "{}"' ).format(model.__name__, rel_obj.__class__.__name__, relation_name) self.assertEqual(obj_count, model.objects.count(), error_msg) # feedback that the test passed print('.', end='') def reverse_pattern(pattern, namespace, args=None, kwargs=None): try: if namespace: return reverse('{}:{}'.format( namespace, pattern.name, args=args, kwargs=kwargs) ) else: return reverse(pattern.name, args=args, kwargs=kwargs) except NoReverseMatch: return None class UrlsTest(BaseTestCase): def setUp(self): super(UrlsTest, self).setUp() # we are going to send parameters, so one thing we'll do is to send # tie id 1 self.user.delete() self.user.id = 1 # give the user all the permissions, so we test every page self.user.is_superuser = True self.user.save() self.login() self.default_params = {} for model in get_our_models(): model_name = camel_to_underscore(model.__name__) method_name = 'create_{}'.format(model_name) param_name = '{}_id'.format(model_name) obj = mommy.make(model) self.assertIsNotNone(obj, '{} returns None'.format(method_name)) self.default_params[param_name] = obj.id def reverse_pattern(self, pattern, namespace): url = reverse_pattern(pattern, namespace) if url is None: reverse_pattern(pattern, namespace, args=(1,)) if url is None: reverse_pattern(pattern, namespace, args=(1, 1)) if url is None: return None view_params = resolve(url).kwargs for param in view_params: try: view_params[param] = self.default_params[param] except KeyError: pass return reverse_pattern(pattern, namespace, kwargs=view_params) def test_responses(self): ignored_namespaces = [] def test_url_patterns(patterns, namespace=''): if namespace in ignored_namespaces: return for pattern in patterns: self.login() if hasattr(pattern, 'name'): url = self.reverse_pattern(pattern, namespace) if not url: continue try: response = self.client.get(url) except: print("Url {} failed: ".format(url)) raise msg = 'url "{}" returned {}'.format( url, response.status_code ) self.assertIn( response.status_code, (200, 302, 403), msg ) # feedback that the test passed print('.', end='') else: test_url_patterns(pattern.url_patterns, pattern.namespace) test_url_patterns(urlpatterns) for model, model_admin in admin.site._registry.items(): patterns = model_admin.get_urls() test_url_patterns(patterns, namespace='admin')
python
import pandas as pd from modules.locale_generator.data import LocaleOutData from helper.utils.utils import read_sheet_map_file class LocaleProcessor: def __init__(self, language_name, english_column_name): self.language_name = language_name self.english_column_name = english_column_name self.additional_replacer_list = read_sheet_map_file() def add_translation_if_present(self, df_row): if self.language_name in list(df_row.index): if pd.notnull(df_row[self.language_name]) and len(str(df_row[self.language_name]).strip()) != 0: df_row['value'] = df_row[self.language_name] return df_row def replace_tags_in_df(self, df): for i, df_row in df.iterrows(): if df_row['Key'] in self.additional_replacer_list.keys(): if 'replacements' in self.additional_replacer_list[df_row['Key']].keys(): for from_text, to in self.additional_replacer_list[df_row['Key']]['replacements'].items(): if pd.notnull(df_row[self.language_name]) and len(str(df_row[self.language_name]).strip()) != 0: tmp = df_row[self.language_name] df_row[self.language_name] = df_row[self.language_name].replace(from_text, to) df.loc[i, self.language_name] = df_row[self.language_name] if tmp == df_row[self.language_name]: print("In", df_row['Key'], "=> ", from_text, 'is not changed') print("Out", df_row[self.language_name], "=> ", from_text, 'is not changed') return df def clean_translation_excel(self, df, language_name): columns = [self.english_column_name, language_name] filtered_sheet = df[columns] sheet_no_na = filtered_sheet.dropna(subset=[self.english_column_name], inplace=False) for i, row in sheet_no_na.iterrows(): if pd.notna(row[language_name]): row[language_name] = str(row[language_name]).strip() if pd.notna(row[self.english_column_name]): row[self.english_column_name] = str(row[self.english_column_name]).strip() return sheet_no_na def clean_meta_df(self, df): for i, row in df.iterrows(): if pd.notna(row[self.english_column_name]): row[self.english_column_name] = str(row[self.english_column_name]).strip() return df def clean_merged_excel(self, df, language_name): excel_df = df.copy() for i, row in excel_df.iterrows(): if pd.notna(row[language_name]): row[language_name] = str(row[language_name]).strip() excel_df = excel_df.drop_duplicates(subset=['Key', self.english_column_name], keep='last') return excel_df def process_with_meta_info(self, excel_df, meta_excel_df): tmp_df = meta_excel_df[['Key', self.language_name]] del meta_excel_df[self.language_name] excel_df = self.clean_translation_excel(excel_df, self.language_name) meta_excel_df = self.clean_meta_df(meta_excel_df) merged_excel_df = pd.merge(meta_excel_df, excel_df, on=self.english_column_name, how='inner') merged_excel_df = self.clean_merged_excel(merged_excel_df, self.language_name) return merged_excel_df def merge_excel_and_json(self, excel_df, json_df): merged_df = pd.merge(excel_df, json_df, on="Key", how='right') merged_df = merged_df.apply(self.add_translation_if_present, axis=1) select_columns = ['Key', 'value'] filtered_merged_df = merged_df[select_columns] final_df = filtered_merged_df.drop_duplicates(subset=['Key'], keep='first', inplace=False) return final_df def process(self, meta_excel_df, input_excel_df, json_df): excel_df = self.process_with_meta_info(input_excel_df, meta_excel_df) excel_df = self.replace_tags_in_df(excel_df) final_df = self.merge_excel_and_json(excel_df, json_df) return LocaleOutData(json_df, excel_df, final_df)
python
from unittest import mock from bgmi.downloader.deluge import DelugeRPC from bgmi.website.model import Episode _token = "token:2334" @mock.patch("bgmi.config.DELUGE_RPC_PASSWORD", _token) @mock.patch("bgmi.downloader.deluge.DelugeRPC._call") def test_init(call): DelugeRPC( download_obj=Episode(name="n", title="t", download="d"), save_path="save_path", ) call.assert_called_with("auth.login", [_token]) @mock.patch("bgmi.downloader.deluge.DelugeRPC._call") def test_download_magnet(call): DelugeRPC( download_obj=Episode(name="n", title="t", download="magnet://233"), save_path="save_path_1", ).download() call.assert_called_with( "web.add_torrents", [ [ { "path": "magnet://233", "options": { "add_paused": False, "compact_allocation": False, "move_completed": False, "download_location": "save_path_1", "max_connections": -1, "max_download_speed": -1, "max_upload_slots": -1, "max_upload_speed": -1, }, } ] ], ) @mock.patch("bgmi.config.DELUGE_RPC_PASSWORD", _token) @mock.patch("bgmi.downloader.deluge.DelugeRPC._call") def test_download_torrent(call: mock.Mock): call.return_value = {"result": "rr"} DelugeRPC( download_obj=Episode(name="n", title="t", download="d.torrent"), save_path="save_path_1", ).download() call.assert_has_calls( [ mock.call("auth.login", [_token]), mock.call("web.download_torrent_from_url", ["d.torrent"]), mock.call( "web.add_torrents", [ [ { "path": "rr", "options": { "add_paused": False, "compact_allocation": False, "move_completed": False, "download_location": "save_path_1", "max_connections": -1, "max_download_speed": -1, "max_upload_slots": -1, "max_upload_speed": -1, }, } ] ], ), ] )
python
''' a = input("First number") b = input("Second number") a = int(a) b = int(b) print(a+b) print(a-b) print(a*b) print(a/b) result = a/b print(type(result)) print(result) print(a**2) ''' # Логические операции a = True b = False # Отрицание print(not a) # Логическое И print(a and b) # Логическое ИЛИ print(a or b) a = 10 print(a>100) print(a<100) print(a<=100) print(a>=100) print(a==100) print(a!=100)
python
from mypackage import shazam shazam()
python
# query_parser_test.py # Author: Thomas MINIER - MIT License 2017-2018 import pytest from query_engine.sage_engine import SageEngine from query_engine.optimizer.query_parser import parse_query from database.hdt_file_connector import HDTFileConnector from tests.utils import DummyDataset import math hdtDoc = HDTFileConnector('tests/data/watdiv.10M.hdt') dataset = DummyDataset(hdtDoc, 'watdiv100') engine = SageEngine() queries = [ (""" SELECT * WHERE { ?s <http://schema.org/eligibleRegion> <http://db.uwaterloo.ca/~galuc/wsdbm/Country9> . ?s <http://purl.org/goodrelations/includes> ?includes . ?s <http://purl.org/goodrelations/validThrough> ?validity . } """, 2180), (""" SELECT * FROM <http://localhost:8000/sparql/watdiv100> WHERE { ?s <http://schema.org/eligibleRegion> <http://db.uwaterloo.ca/~galuc/wsdbm/Country9> . ?s <http://purl.org/goodrelations/includes> ?includes . ?s <http://purl.org/goodrelations/validThrough> ?validity . } """, 2180), (""" SELECT * WHERE { { ?s <http://schema.org/eligibleRegion> <http://db.uwaterloo.ca/~galuc/wsdbm/Country9> . ?s <http://purl.org/goodrelations/includes> ?includes . ?s <http://purl.org/goodrelations/validThrough> ?validity . } UNION { ?s <http://schema.org/eligibleRegion> <http://db.uwaterloo.ca/~galuc/wsdbm/Country9> . ?s <http://purl.org/goodrelations/includes> ?includes . ?s <http://purl.org/goodrelations/validThrough> ?validity . } } """, 2180 * 2), (""" SELECT * WHERE { <http://db.uwaterloo.ca/~galuc/wsdbm/Offer1000> <http://purl.org/goodrelations/price> ?price . FILTER(?price = "232") } """, 1), (""" SELECT * WHERE { <http://db.uwaterloo.ca/~galuc/wsdbm/Offer1000> <http://purl.org/goodrelations/price> ?price . FILTER(?price = "232" && 1 + 2 = 3) } """, 1), (""" SELECT * WHERE { ?s <http://schema.org/eligibleRegion> <http://db.uwaterloo.ca/~galuc/wsdbm/Country9> . GRAPH <http://localhost:8000/sparql/watdiv100> { ?s <http://purl.org/goodrelations/includes> ?includes . ?s <http://purl.org/goodrelations/validThrough> ?validity . } } """, 2180)] class TestQueryParser(object): @pytest.mark.parametrize("query,cardinality", queries) def test_query_parser(self, query, cardinality): iterator, cards = parse_query(query, dataset, 'watdiv100', 'http://localhost:8000/sparql/') assert len(cards) > 0 (results, saved, done) = engine.execute(iterator, math.inf) assert len(results) == cardinality assert done
python
import sys import time from http.client import HTTPSConnection from typing import List def main(argv: List[str]): time.sleep(3) for i in range(3): for j in argv: connection = HTTPSConnection(j) connection.request('GET', '/') connection.getresponse().read() time.sleep(5) if __name__ == '__main__': main(sys.argv[1:])
python
# -*- encoding: utf-8 -*- # Copyright (c) 2015 b<>com # # 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 collections import OrderedDict from unittest import TestCase from mock import patch import msgpack from watcher_metering.agent.measurement import Measurement from watcher_metering.agent.puller import MetricPuller class FakeMetricPuller(MetricPuller): @classmethod def get_name(cls): return 'dummy' @classmethod def get_default_probe_id(cls): return 'dummy.data.puller' @classmethod def get_default_interval(cls): return 1 def do_pull(self): return class TestMetricPuller(TestCase): @patch.object(Measurement, "as_dict") def test_puller_send_measurements(self, m_as_dict): data_puller = FakeMetricPuller( title=FakeMetricPuller.get_entry_name(), probe_id=FakeMetricPuller.get_default_probe_id(), interval=FakeMetricPuller.get_default_interval(), ) measurement_dict = OrderedDict( name="dummy.data.puller", unit="", type_="", value=13.37, resource_id="test_hostname", host="test_hostname", timestamp="2015-08-04T15:15:45.703542", ) m_as_dict.return_value = measurement_dict measurement = Measurement(**measurement_dict) with patch.object(MetricPuller, 'notify') as m_notify: data_puller.send_measurements([measurement]) expected_encoded_msg = msgpack.dumps(measurement_dict) self.assertTrue(m_notify.called) m_notify.assert_called_once_with(expected_encoded_msg)
python
#! /usr/bin/env python3 # -*- coding: utf-8 -*- import sys from common.Utilities import execute_command, get_file_extension_list, error_exit from ast import ASTGenerator, AST import Mapper import Finder import Logger import Extractor import Emitter def merge_var_info(var_expr_map, var_value_map): Logger.trace(__name__ + ":" + sys._getframe().f_code.co_name, locals()) var_info = dict() # print(var_expr_map) # print(var_value_map) for var_name in var_value_map: if var_name in var_expr_map: info = dict() # print(var_name) info["data_type"] = var_expr_map[var_name]['data_type'] # print(info["data_type"]) info["value_list"] = var_value_map[var_name]['value_list'] # print(info["value_list"]) info["expr_list"] = var_expr_map[var_name]['expr_list'] var_info[var_name] = info # print(var_info) return var_info def merge_var_map(map_a, map_b): Logger.trace(__name__ + ":" + sys._getframe().f_code.co_name, locals()) var_map = dict() for var_name in map_a: if var_name in map_b: var_map[var_name] = map_b[var_name] else: var_map[var_name] = map_a[var_name] for var_name in map_b: if var_name not in map_a: var_map[var_name] = map_b[var_name] # print(var_info) return var_map def merge_macro_info(info_a, info_b): Logger.trace(__name__ + ":" + sys._getframe().f_code.co_name, locals()) macro_info = dict() for macro_name in info_a: info = info_a[macro_name] if macro_name in info_b.keys(): error_exit("MULTIPLE USAGE OF MACRO") macro_info[macro_name] = info for macro_name in info_b: info = info_b[macro_name] macro_info[macro_name] = info return macro_info def merge_header_info(info_a, info_b): Logger.trace(__name__ + ":" + sys._getframe().f_code.co_name, locals()) header_info = dict() for header_name in info_a: info = info_a[header_name] if header_name in info_b.keys(): error_exit("MULTIPLE USAGE OF HEADER") header_info[header_name] = info for header_name in info_b: info = info_b[header_name] header_info[header_name] = info return header_info def merge_data_type_info(info_a, info_b): Logger.trace(__name__ + ":" + sys._getframe().f_code.co_name, locals()) header_info = dict() for header_name in info_a: info = info_a[header_name] if header_name in info_b.keys(): error_exit("MULTIPLE USAGE OF DATA TYPE") header_info[header_name] = info for header_name in info_b: info = info_b[header_name] header_info[header_name] = info return header_info def merge_ast_script(ast_script, ast_node_a, ast_node_b, mapping_ba): Logger.trace(__name__ + ":" + sys._getframe().f_code.co_name, locals()) Emitter.normal("\t\tmerging AST script") merged_ast_script = list() inserted_node_list = list() deleted_node_list = list() replace_node_list = list() try: ast_tree_a = AST.load_from_map(ast_node_a) ast_tree_b = AST.load_from_map(ast_node_b) except: return None # print(ast_script) for script_line in ast_script: # print(script_line) if "Insert" in script_line: # print(script_line) node_id_a = int(((script_line.split(" into ")[0]).split("(")[1]).split(")")[0]) node_id_b = int(((script_line.split(" into ")[1]).split("(")[1]).split(")")[0]) if node_id_b in inserted_node_list or node_id_b == 0: inserted_node_list.append(node_id_a) continue replace_node = Finder.search_ast_node_by_id(ast_node_b, node_id_a) # print(replace_node) target_node_id_a = mapping_ba[node_id_b] target_node = Finder.search_ast_node_by_id(ast_node_a, target_node_id_a) # print(target_node) insert_position = int((script_line.split(" at ")[1])) del_op = "Delete " + str(target_node['type']) + "(" + str(target_node_id_a) + ")\n" # print(del_op) possible_replacement_node = Finder.search_ast_node_by_id(ast_node_a, target_node_id_a) parent_node = Finder.search_ast_node_by_id(ast_node_a, int(possible_replacement_node['parent_id'])) # print(parent_node) del_parent_op = "Delete " + str(parent_node['type']) + "(" + str(parent_node['id']) + ")\n" # print(del_parent_op) # print(ast_script) if del_op in ast_script: replace_node_str = str(replace_node['type']) + "(" + str(node_id_a) + ")" target_node_str = str(possible_replacement_node['type']) + "(" + str(target_node_id_a) + ")" script_line = "Replace " + target_node_str + " with " + replace_node_str inserted_node_list.append(node_id_a) elif del_parent_op in ast_script: replace_node_str = str(replace_node['type']) + "(" + str(node_id_a) + ")" # print(replace_node_str) target_node_str = str(possible_replacement_node['type']) + "(" + str(target_node_id_a) + ")" # print(target_node_str) script_line = "Replace " + target_node_str + " with " + replace_node_str # print(script_line) elif len(target_node['children']) > insert_position: possible_replacement_node = target_node['children'][insert_position] # print(possible_replacement_node) replacement_node_id = possible_replacement_node['id'] del_op = "Delete " + str(possible_replacement_node['type']) + "(" + str(replacement_node_id) + ")\n" # print(del_op) if del_op in ast_script: # print(del_op) replace_node_str = str(replace_node['type']) + "(" + str(node_id_a) + ")" target_node_str = str(possible_replacement_node['type']) + "(" + str(replacement_node_id) + ")" script_line = "Replace " + target_node_str + " with " + replace_node_str # print(script_line) deleted_node_list.append(replacement_node_id) child_id_list = Extractor.extract_child_id_list(possible_replacement_node) deleted_node_list = deleted_node_list + child_id_list if node_id_b not in inserted_node_list: merged_ast_script.append(script_line) inserted_node_list.append(node_id_a) elif "Delete" in script_line: node_id = int((script_line.split("(")[1]).split(")")[0]) node = Finder.search_ast_node_by_id(ast_node_a, node_id) child_id_list = Extractor.extract_child_id_list(node) deleted_node_list = deleted_node_list + child_id_list if node_id not in deleted_node_list: deleted_node_list.append(node_id) merged_ast_script.append(script_line) elif "Move" in script_line: # print(script_line) move_position = int((script_line.split(" at ")[1])) move_node_str = (script_line.split(" into ")[0]).replace("Move ", "") move_node_id_b = int((move_node_str.split("(")[1]).split(")")[0]) move_node_id_a = mapping_ba[move_node_id_b] move_node_b = Finder.search_ast_node_by_id(ast_node_b, move_node_id_b) move_node_a = Finder.search_ast_node_by_id(ast_node_a, move_node_id_a) move_node_type_b = move_node_b['type'] move_node_type_a = move_node_a['type'] if move_node_type_b == "CaseStmt": continue target_node_id_b = int(((script_line.split(" into ")[1]).split("(")[1]).split(")")[0]) if target_node_id_b in inserted_node_list: continue # print(move_node_type_b) # print(move_node_type_a) target_node_id_a = mapping_ba[target_node_id_b] # print(target_node_id_a) target_node_a = Finder.search_ast_node_by_id(ast_node_a, target_node_id_a) target_node_str = target_node_a['type'] + "(" + str(target_node_a['id']) + ")" # print(target_node_a) # print(move_node_type_a) # print(move_node_type_b) if move_node_type_a != move_node_type_b: script_line = "Insert " + move_node_str + " into " + target_node_str + " at " + str(move_position) if len(target_node_a['children']) <= move_position: script_line = "Insert " + move_node_str + " into " + target_node_str + " at " + str(move_position) elif len(target_node_a['children']) > move_position: possible_replacement_node = target_node_a['children'][move_position] # print(possible_replacement_node) replacement_node_id = possible_replacement_node['id'] del_op = "Delete " + str(possible_replacement_node['type']) + "(" + str(replacement_node_id) + ")\n" # print(del_op) if del_op in ast_script: # print(del_op) replace_node_str = str(move_node_b['type']) + "(" + str(move_node_b['id']) + ")" target_node_str = str(possible_replacement_node['type']) + "(" + str(replacement_node_id) + ")" script_line = "Replace " + target_node_str + " with " + replace_node_str # print(script_line) deleted_node_list.append(replacement_node_id) child_id_list = Extractor.extract_child_id_list(possible_replacement_node) deleted_node_list = deleted_node_list + child_id_list else: replacing_node = target_node_a['children'][move_position] replacing_node_id = replacing_node['id'] replacing_node_str = replacing_node['type'] + "(" + str(replacing_node['id']) + ")" script_line = "Replace " + replacing_node_str + " with " + move_node_str deleted_node_list.append(replacing_node_id) child_id_list = Extractor.extract_child_id_list(replacing_node) deleted_node_list = deleted_node_list + child_id_list # print(replacing_node_id) inserted_node_list.append(replacing_node_id) # print(script_line) merged_ast_script.append(script_line) elif "Update" in script_line: # print(script_line) # update_line = str(script_line).replace("Update", "Replace").replace(" to ", " with ") # print(update_line) merged_ast_script.append(script_line) second_merged_ast_script = list() for script_line in merged_ast_script: # print(script_line) if "Replace" in script_line: # print(script_line) node_id_a = int(((script_line.split(" with ")[0]).split("(")[1]).split(")")[0]) node_id_b = int(((script_line.split(" with ")[1]).split("(")[1]).split(")")[0]) node_a = Finder.search_ast_node_by_id(ast_node_a, node_id_a) parent_node_id_a = int(node_a['parent_id']) parent_node_a = Finder.search_ast_node_by_id(ast_node_a, parent_node_id_a) if len(parent_node_a['children']) > 0: count = 0 for child_node in parent_node_a['children']: replace_op = "Replace " + child_node['type'] + "(" + str(child_node['id']) + ")" count += sum(replace_op in s for s in merged_ast_script) if count > 1: node_b = Finder.search_ast_node_by_id(ast_node_b, node_id_b) parent_node_id_b = int(node_b['parent_id']) parent_node_b = Finder.search_ast_node_by_id(ast_node_b, parent_node_id_b) parent_node_str_a = parent_node_a['type'] + "(" + str(parent_node_a['id']) + ")" parent_node_str_b = parent_node_b['type'] + "(" + str(parent_node_b['id']) + ")" new_op = "Replace " + parent_node_str_a + " with " + parent_node_str_b + "\n" if new_op not in second_merged_ast_script: second_merged_ast_script.append(new_op) else: second_merged_ast_script.append(script_line) else: second_merged_ast_script.append(script_line) elif "Update" in script_line: update_line = str(script_line).replace("Update", "Replace").replace(" to ", " with ") # print(update_line) second_merged_ast_script.append(update_line) else: second_merged_ast_script.append(script_line) return second_merged_ast_script
python
# CONTADOR DE CÉDULAS value = int(input('Digite o valor a ser sacado: ')) total = value # Pegando o valor a ser sacado ced = 50 # Começando na cedula de 50 totced = 0 # Total de cedula por valor while True: if total >= ced: # Enquanto puder retirar o valor da cedula do valor total total -= ced # Retirando o valor da cedula do valor total totced += 1 # Contando o número de cédulas por valor else: # Quando não puder mais tirar do valor até então usado if totced > 0: # Printar apenas as cédulas usadas, se usar 0 de algum valor, não printará print(f'{totced} cédulas de R${ced:.2f}') if ced == 50: # Quando não puder mais decrementar 50 ced = 20 elif ced == 20: # Quando não puder mais decrementar 20 ced = 10 elif ced == 10: # Quando não puder mais decrementar 10 ced = 1 totced = 0 # Reiniciando a contagem de cédulas if total == 0: break
python
""" Generate static HTML files for eduid-IdP in all supported languages. """ import os import sys import six import pkg_resources from six.moves import configparser from jinja2 import Environment, PackageLoader from babel.support import Translations __version__ = '0.1' __copyright__ = 'SUNET' __organization__ = 'SUNET' __license__ = 'BSD' __authors__ = ['Fredrik Thulin'] __all__ = [ ] _CONFIG_DEFAULTS = {'gettext_domain': 'eduid_IdP_html', } def translate_templates(env, loader, settings, verbose=False, debug=False): """ Translate all templates available through `loader'. Returns a big dict with all the translated templates, in all languages : {'login.jinja2': {'en': string, 'sv': string, ...}, 'error.jinja2': ... } :param env: jinja2.Environment() :param loader: jinja2.BaseLoader() :param settings: dict with settings and variables available to the Jinja2 templates :param verbose: boolean, output to stdout or not :param debug: boolean, output debug information to stderr or not :return: dict with translated templates """ languages = {} res = {} locale_dir = pkg_resources.resource_filename(__name__, 'locale') for lang in pkg_resources.resource_listdir(__name__, 'locale'): lang_dir = os.path.join(locale_dir, lang) if not os.path.isdir(lang_dir): if debug: sys.stderr.write("Not a directory: {!r}\n".format(lang_dir)) continue if verbose: languages[lang] = 1 translations = Translations.load(locale_dir, [lang], settings['gettext_domain']) env.install_gettext_translations(translations) for template_file in loader.list_templates(): if template_file.endswith('.swp'): continue template = env.get_template(template_file) translated = template.render(settings=settings) if not template_file in res: res[template_file] = {} res[template_file][lang] = translated.encode('utf-8') if debug: sys.stderr.write("Lang={!s} :\n{!s}\n\n".format(lang, translated.encode('utf-8'))) if verbose: print("\nLanguages : {!r}\nGenerated templates : {!r}\n".format( sorted(languages.keys()), sorted(res.keys()))) return res def load_settings(resource_name='settings.ini'): """ Load settings from INI-file (package resource). All options from all sections are collapsed to one flat namespace. :param resource_name: string, name of package resource to load. :return: dict with settings """ config = configparser.ConfigParser(_CONFIG_DEFAULTS) if six.PY2: config_fp = pkg_resources.resource_stream(__name__, resource_name) config.readfp(config_fp, resource_name) else: config_str = pkg_resources.resource_string(__name__, resource_name) config.read_string(config_str.decode('utf8'), resource_name) settings = {} for section in config.sections(): for option in config.options(section): settings[option] = config.get(section, option) return settings def save_to_files(translated, output_dir, verbose): """ Save translated templates to files (with a .html extension). :param translated: dict (result of translate_templates() probably) :param output_dir: string, output path :param verbose: boolean, print status output to stdout or not """ for template in translated.keys(): template_html_fn = template if template_html_fn.endswith('.jinja2'): # remove '.jinja2' extension template_html_fn = template_html_fn[:len(template_html_fn) - len('.jinja2')] template_html_fn += '.html' for lang in translated[template].keys(): lang_dir = os.path.join(output_dir, lang) try: os.stat(lang_dir) except OSError: os.mkdir(lang_dir) output_fn = os.path.join(lang_dir, template_html_fn) fp = open(output_fn, 'w') if six.PY2: fp.write(translated[template][lang]) else: fp.write(translated[template][lang].decode('utf8')) fp.write("\n") # eof newline disappears in Jinja2 rendering if verbose: print("Wrote {!r}".format(output_fn)) if verbose: print("\n") def main(verbose=False, output_dir=None): """ Code executed when this module is started as a script. :param verbose: boolean, print status output to stdout/stderr or not :param output_dir: string, output path :return: boolean """ settings = load_settings() if not settings: return False loader = PackageLoader(__name__) env = Environment(loader=loader, extensions=['jinja2.ext.i18n', 'jinja2.ext.autoescape', 'jinja2.ext.with_', ], ) translated = translate_templates(env, loader, settings, verbose) if output_dir: save_to_files(translated, output_dir, verbose) return True if __name__ == '__main__': if not main(verbose=True, output_dir="/tmp/foo"): sys.exit(1) sys.exit(0)
python
import pywikibot from openpyxl import load_workbook site = pywikibot.Site() ''' page = pywikibot.Page(site, u"Project:Sandbox") text = page.text #page.text = u"DarijaBot kheddam daba" page.save(page.text+u"\n\nawwal edit dial DarijaBot") ''' sandbox = pywikibot.Page(site, 'User:' + site.user() + '/Project:Sandbox') sandbox.text = page.text+u"\n\nawwal edit dial DarijaBot" sandbox.save()
python
import numpy as np from .agent import Agent class RandomAgent(Agent): def __init__(self, actions): super(RandomAgent, self).__init__(actions) def act(self, obs): return np.random.randint(0, self.num_actions)
python
from rA9.neurons.LIF import LIF def LIF_recall(tau, Vth, dt, x, v_current): model = LIF(tau_m=tau, Vth=Vth, dt=dt) spike_list, v_current = model.forward(x, v_current=v_current) return spike_list, v_current def LIF_backward(tau, Vth, x, spike_list, e_grad, time): model = LIF(tau_m=tau, Vth=Vth) return model.backward(time=time, spike_list=spike_list, weights=x, e_gradient=e_grad)
python
from meido.libs.yuntongxun.sms import CCP from celery_tasks.main import app @app.task(name='send_sms_code') def send_sms_code(mobile, sms_code): ccp = CCP() ccp.send_template_sms(mobile, [sms_code, '5'], 1) @app.task() def test_print(): print(2222)
python
#!/usr/bin/env python3 def naive_search(l,x): for i in range(len(l)): if l[i]==x: return i n = int(input()) l = list(range(n)) cnt = 0 for x in range(n): i = naive_search(l,x) cnt += 1 print("#query=%d"%cnt)
python
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Module that contains artellapipe-tools-welcome view implementation """ from __future__ import print_function, division, absolute_import import os import random from functools import partial from Qt.QtCore import Qt, QSize, QTimer, QByteArray, QBuffer from Qt.QtWidgets import QSizePolicy, QLabel, QFrame, QGraphicsOpacityEffect, QRadioButton from Qt.QtGui import QMovie from tpDcc.managers import resources from tpDcc.libs.qt.core import base, qtutils, animation from tpDcc.libs.qt.widgets import layouts, buttons, stack from artellapipe.tools.welcome.widgets import widget, frame, shortcuts, final class WelcomeView(base.BaseWidget): def __init__(self, project, parent=None): self._radio_buttons = list() self._offset = 0 self._project = project self._toolset = parent self._logo_gif_file = None self._logo_gif_byte_array = None self._logo_gif_buffer = None self._logo_movie = None super(WelcomeView, self).__init__(parent=parent) self._init() def ui(self): super(WelcomeView, self).ui() self.resize(685, 290) self.setAttribute(Qt.WA_TranslucentBackground) if qtutils.is_pyside2(): self.setWindowFlags(self.windowFlags() | Qt.FramelessWindowHint) else: self.setWindowFlags(Qt.Window | Qt.FramelessWindowHint) main_frame = frame.WelcomeFrame(pixmap=self._get_welcome_pixmap()) frame_layout = layouts.VerticalLayout(spacing=2, margins=(10, 0, 10, 0)) main_frame.setLayout(frame_layout) top_layout = layouts.HorizontalLayout(spacing=2, margins=(2, 2, 2, 2)) frame_layout.addLayout(top_layout) self._close_btn = buttons.BaseButton('', parent=self) self._close_btn.setIcon(resources.icon('close', theme='window')) self._close_btn.setStyleSheet('QWidget {background-color: rgba(255, 255, 255, 0); border:0px;}') self._close_btn.setIconSize(QSize(25, 25)) top_layout.addStretch() self._logo = QLabel('', parent=self) top_layout.addWidget(self._logo) top_layout.addStretch() top_layout.addWidget(self._close_btn) base_frame = QFrame() base_frame.setObjectName('baseFrame') base_frame.setFrameShape(QFrame.NoFrame) base_frame.setFrameShadow(QFrame.Plain) # base_frame.setAttribute(Qt.WA_TranslucentBackground) base_frame.setStyleSheet('QFrame#baseFrame { background-color: rgba(100, 100, 100, 80); }') base_frame.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding) base_layout = layouts.VerticalLayout(spacing=2, margins=(2, 2, 2, 2)) base_frame.setLayout(base_layout) frame_layout.addWidget(base_frame) self._stack = stack.SlidingOpacityStackedWidget(parent=self) self._stack.setAutoFillBackground(False) self._stack.setAttribute(Qt.WA_TranslucentBackground) base_layout.addWidget(self._stack) bottom_layout = layouts.HorizontalLayout(spacing=2, margins=(2, 2, 2, 2)) frame_layout.addLayout(bottom_layout) self._left_btn = buttons.BaseButton('Skip', parent=self) self._left_btn.setMinimumSize(QSize(100, 30)) self._left_btn.setStyleSheet( """ QPushButton\n{\n\nbackground-color: rgb(250,250,250,30);\ncolor: rgb(250, 250, 250); \nborder-radius: 5px;\nborder: 0px;\npadding-left: 15px;\npadding-right: 15px;\n}\n\nQPushButton:hover\n{\n background-color: rgb(250,250,250,20);\n}\n\nQPushButton:pressed\n{\n\nbackground-color: rgb(0,0,0,30);\n} """ ) self._right_btn = buttons.BaseButton('Next', parent=self) self._right_btn.setMinimumSize(QSize(100, 30)) self._right_btn.setStyleSheet( """ QPushButton\n{\n\nbackground-color: rgb(250,250,250,30);\ncolor: rgb(250, 250, 250); \nborder-radius: 5px;\nborder: 0px;\npadding-left: 15px;\npadding-right: 15px;\n}\n\nQPushButton:hover\n{\n background-color: rgb(250,250,250,20);\n}\n\nQPushButton:pressed\n{\n\nbackground-color: rgb(0,0,0,30);\n} """ ) self.setStyleSheet( "QRadioButton::indicator {\nbackground-color: rgb(250,250,250,120);\n}\n" "QRadioButton::indicator::unchecked {\nbackground-color: rgb(255,255,255,70);\nborder-radius: 4px;\n" "width: 8px;\n height: 8px;\n}\nQRadioButton::indicator::checked {" "\nbackground: qlineargradient(x1: 0, y1: 1, x2: 1, y2: 1, stop: 0 rgba(" + self._project.dev_color0 + "), " "stop: 1 rgba(" + self._project.dev_color1 + "));\n border-radius: 5px;\n width: 10px;\n height: 10px;\n}") self._radio_layout = layouts.HorizontalLayout(spacing=2, margins=(2, 2, 2, 2)) bottom_layout.addStretch() bottom_layout.addWidget(self._left_btn) bottom_layout.addStretch() bottom_layout.addLayout(self._radio_layout) bottom_layout.addStretch() bottom_layout.addWidget(self._right_btn) bottom_layout.addStretch() self.main_layout.addWidget(main_frame) def setup_signals(self): self._right_btn.clicked.connect(lambda: self._on_button_clicked(+1)) self._left_btn.clicked.connect(lambda: self._on_button_clicked(-1)) def mousePressEvent(self, event): """ Overrides base ArtellaDialog mousePressEvent function :param event: QMouseEvent """ self._offset = event.pos() def mouseMoveEvent(self, event): """ Overrides base ArtellaDialog mouseMoveEvent function :param event: QMouseEvent """ x = event.globalX() y = event.globalY() x_w = self._offset.x() y_w = self._offset.y() self._toolset.attacher.move(x - x_w, y - y_w) def _init(self): """ Initializes Welcome dialog """ self._tab_opacity_effect = QGraphicsOpacityEffect(self) self._tab_opacity_effect.setOpacity(0) self._stack.setGraphicsEffect(self._tab_opacity_effect) self._setup_logo() self._setup_pages() self._set_index(0) def _setup_logo(self): """ Internal function that setup project logo """ logo_gif = resources.get('images', '{}_logo.gif'.format(self._project.name.lower())) if not logo_gif or not os.path.isfile(logo_gif): return self._logo_gif_file = open(logo_gif, 'rb').read() self._logo_gif_byte_array = QByteArray(self._logo_gif_file) self._logo_gif_buffer = QBuffer(self._logo_gif_byte_array) self._logo_movie = QMovie() self._logo_movie.setDevice(self._logo_gif_buffer) self._logo_movie.setCacheMode(QMovie.CacheAll) self._logo_movie.setScaledSize(QSize(60, 60)) self._logo_movie.setSpeed(100) self._logo_movie.jumpToFrame(0) self._logo_movie.start() self._logo.setAttribute(Qt.WA_NoSystemBackground) self._logo.setMovie(self._logo_movie) def _setup_pages(self): """ Internal callback function that set the pages of the stack Overrides to add new pages """ self._welcome_widget = widget.WelcomeWidget(project=self._project, parent=self) self._shortcuts_widget = shortcuts.ShortcutsWidget(project=self._project, parent=self) self._final_widget = final.FinalWidget(project=self._project, parent=self) self._final_widget.showChangelog.connect(self._on_show_changelog) self._add_page(self._welcome_widget) self._add_page(self._shortcuts_widget) self._add_page(self._final_widget) def _get_welcome_pixmap(self): """ Returns pixmap to be used as splash background :return: Pixmap """ welcome_path = resources.get('images', 'welcome.png', key='project') if not os.path.isfile(welcome_path): welcome_Dir = os.path.dirname(welcome_path) welcome_files = [ f for f in os.listdir(welcome_Dir) if f.startswith('welcome') and os.path.isfile( os.path.join(welcome_Dir, f))] if welcome_files: welcome_index = random.randint(0, len(welcome_files) - 1) welcome_name, splash_extension = os.path.splitext(welcome_files[welcome_index]) welcome_pixmap = resources.pixmap( welcome_name, extension=splash_extension[1:], key='project') else: welcome_pixmap = resources.pixmap('welcome') else: welcome_pixmap = resources.pixmap('welcome', key='project') return welcome_pixmap.scaled(QSize(800, 270)) def _add_page(self, widget): """ Adds a new widget into the stack :param widget: QWidget """ total_pages = len(self._radio_buttons) new_radio = QRadioButton(parent=self) if total_pages == 0: new_radio.setChecked(True) new_radio.clicked.connect(partial(self._set_index, total_pages)) self._stack.addWidget(widget) self._radio_layout.addWidget(new_radio) self._radio_buttons.append(new_radio) def _increment_index(self, input): """ Internal function that increases index of the stack widget :param input: int """ current = self._stack.currentIndex() self._set_index(current + input) def _set_index(self, index): """ Internal function that updates stack index and UI :param index: int """ animation.fade_animation(start='current', end=0, duration=400, object=self._tab_opacity_effect) if index <= 0: index = 0 if index >= self._stack.count() - 1: index = self._stack.count() - 1 self._radio_buttons[index].setChecked(True) self.props_timer = QTimer(singleShot=True) self.props_timer.timeout.connect(self._on_fade_up_tab) self.props_timer.timeout.connect(lambda: self._stack.setCurrentIndex(index)) self.props_timer.start(450) prev_text = 'Previous' next_text = 'Next' skip_text = 'Skip' close_text = 'Finish' if index == 0: self._left_btn.setText(skip_text) self._right_btn.setText(next_text) elif index < self._stack.count() - 1: self._left_btn.setText(prev_text) self._right_btn.setText(next_text) elif index == self._stack.count() - 1: self._left_btn.setText(prev_text) self._right_btn.setText(close_text) def _launch_project(self): """ Internal function that closes Welcome dialog and launches project tools """ self._toolset.attacher.fade_close() def _on_fade_up_tab(self): """ Internal callback function that is called when stack index changes """ animation.fade_animation(start='current', end=1, duration=400, object=self._tab_opacity_effect) def _on_button_clicked(self, input): """ Internal callback function that is called when Next and and Skip buttons are pressed :param input: int """ current = self._stack.currentIndex() action = 'flip' if current == 0: if input == -1: action = 'close' elif current == self._stack.count() - 1: if input == 1: action = 'close' if action == 'flip': self._increment_index(input) elif action == 'close': self._launch_project() def _on_show_changelog(self, changelog_window): """ Internal callback function that is called when show changelog button is pressed in the final widget """ self.close_tool_attacher() # changelog_window.show()
python
from flask_cors import cross_origin from app.blueprints.base_blueprint import ( Blueprint, BaseBlueprint, request, Security, Auth, ) from app.controllers.user_employment_controller import UserEmploymentController url_prefix = "{}/user_employment_history".format(BaseBlueprint.base_url_prefix) user_employment_blueprint = Blueprint( "user_employment", __name__, url_prefix=url_prefix ) user_employment_controller = UserEmploymentController(request) @user_employment_blueprint.route("/user/<int:user_id>", methods=["GET"]) # @cross_origin(supports_credentials=True) @Auth.has_permission(["view_user_employment_history"]) # @swag_from('documentation/get_all_user_employment_history.yml') def list_user_employment_history(user_id): return user_employment_controller.list_user_employment_history(user_id) @user_employment_blueprint.route( "/user-single/<int:user_employment_id>", methods=["GET"] ) # @cross_origin(supports_credentials=True) @Auth.has_permission(["view_user_employment_history"]) # @swag_from('documentation/get_user_employment_by_id.yml') def get_user_employment(user_employment_id): return user_employment_controller.get_user_employment(user_employment_id) @user_employment_blueprint.route("/", methods=["POST"]) # @cross_origin(supports_credentials=True) @Security.validator( [ "user_id|required:int", "institution_name|required:string", "job_title|required:string", "start_date|required:date", "end_date|required:date", "is_current|required", "skills|optional:list_int", ] ) @Auth.has_permission(["create_user_employment_history"]) # @swag_from('documentation/create_user_employment.yml') def create_user_employment(): return user_employment_controller.create_user_employment() @user_employment_blueprint.route("/<int:update_id>", methods=["PUT", "PATCH"]) # @cross_origin(supports_credentials=True) @Security.validator( [ "user_id|required:int", "user_employment_id|required:int", "institution_name|required:string", "job_title|required:string", "start_date|required:date", "end_date|required:date", "is_current|required", "skills|optional:list_int", ] ) @Auth.has_permission(["update_user_employment_history"]) # @swag_from("documentation/update_user_employment.yml") def update_user_employment(update_id): return user_employment_controller.update_user_employment(update_id) @user_employment_blueprint.route("/<int:user_employment_id>", methods=["DELETE"]) # @cross_origin(supports_credentials=True) @Auth.has_permission(["delete_user_employment_history"]) # @swag_from("documentation/delete_user_employment.yml") def delete_user_employment(user_employment_id): return user_employment_controller.delete_user_employment(user_employment_id)
python
from django.test import TestCase from django.contrib.auth.models import User from .models import Thread, Message # Create your tests here. class ThreadTestCase(TestCase): def setUp(self): self.user1 = User.objects.create_user("user1", None, "test1234") self.user2 = User.objects.create_user("user2", None, "test1234") self.user3 = User.objects.create_user("user3", None, "test1234") self.thread = Thread.objects.create() def test_add_users_to_thread(self): self.thread.users.add(self.user1, self.user2) self.assertEqual(len(self.thread.users.all()), 2) def test_filter_thread_by_users(self): self.thread.users.add(self.user1, self.user2) threads = Thread.objects.filter(users=self.user1).filter(users=self.user2) self.assertEqual(self.thread, threads[0]) def test_filter_non_existent_thread(self): threads = Thread.objects.filter(users=self.user1).filter(users=self.user2) self.assertEqual(len(threads), 0) def test_add_message_to_thread(self): self.thread.users.add(self.user1, self.user2) message1 = Message.objects.create(user=self.user1, content="Hola!") message2 = Message.objects.create(user=self.user2, content="Que tal?") self.thread.messages.add(message1, message2) self.assertEqual(len(self.thread.messages.all()), 2) for message in self.thread.messages.all(): print("({}): {}".format(message.user, message.content)) def test_add_message_from_user_not_in_thread(self): self.thread.users.add(self.user1, self.user2) message1 = Message.objects.create(user=self.user1, content="Hola!") message2 = Message.objects.create(user=self.user2, content="Que tal?") message3 = Message.objects.create(user=self.user3, content="Soy un espía") self.thread.messages.add(message1, message2, message3) self.assertEqual(len(self.thread.messages.all()), 2) def test_find_thread_with_custom_manager(self): self.thread.users.add(self.user1, self.user2) thread = Thread.objects.find(self.user1, self.user2) self.assertEqual(self.thread, thread) def test_find_or_create_thread_with_custom_manager(self): self.thread.users.add(self.user1, self.user2) thread = Thread.objects.find_or_create(self.user1, self.user2) self.assertEqual(self.thread, thread) thread = Thread.objects.find_or_create(self.user1, self.user3) self.assertIsNotNone(thread)
python
#!/usr/bin/env python import argparse import sys import Tools from Bio import SeqIO from Bio import SeqRecord from Bio import Seq ap = argparse.ArgumentParser(description="Take an inversion bed file, and print the sequences in inverted format with some flanking part of the genome.") ap.add_argument("bed", help="Input BED file. This should be in the insertion bed format.") ap.add_argument("genome", help="Input genome with a .fai file.") ap.add_argument("contexts", help="Output file.") ap.add_argument("--window", help="Amount to store on sides.", type=int, default=1000) ap.add_argument("--bponly", help="Print only the breakpoints, value specifies amount of sequence about each breakpoint to print.", type=int, default=None) ap.add_argument("--noreverse", help="Assume the breakpoints are from assembled contigs and there is no need to reverse the alignment.", default=False, action='store_true') args = ap.parse_args() bedFile = open(args.bed) contextFile = open(args.contexts, 'w') fai = Tools.ReadFAIFile(args.genome+".fai") genomeFile = open(args.genome) for line in bedFile: vals = line.split() chrom = vals[0] start = int(vals[1]) end = int(vals[2]) prefixCoords = (max(0, start - args.window), start) suffixCoords = (end, min(fai[chrom][0], end+args.window)) invSeq = Seq.Seq(Tools.ExtractSeq((chrom, start, end), genomeFile, fai)) prefix = Tools.ExtractSeq((chrom, prefixCoords[0],prefixCoords[1]), genomeFile, fai) suffix = Tools.ExtractSeq((chrom, suffixCoords[0],suffixCoords[1]), genomeFile, fai) if (args.noreverse == False): invSeqStr = invSeq.reverse_complement().tostring() else: invSeqStr = invSeq.tostring() context = prefix + invSeqStr + suffix seqname = "/".join(vals[0:3]) if (args.bponly is None): SeqIO.write(SeqRecord.SeqRecord(Seq.Seq(context), id=seqname, name="",description=""), contextFile, "fasta") else: bp1 = len(prefix) bp2 = len(prefix) + len(invSeqStr) bp1Seq = context[bp1-args.bponly:bp1+args.bponly] bp2Seq = context[bp2-args.bponly:bp2+args.bponly] bp1Name = seqname + "_1" bp2Name = seqname + "_2" SeqIO.write(SeqRecord.SeqRecord(Seq.Seq(bp1Seq), id=bp1Name, name="",description=""), contextFile, "fasta") SeqIO.write(SeqRecord.SeqRecord(Seq.Seq(bp2Seq), id=bp2Name, name="",description=""), contextFile, "fasta") contextFile.close()
python
from django.contrib.auth.mixins import LoginRequiredMixin, UserPassesTestMixin from django.views.generic import ListView from django.http import JsonResponse from api.models import Country, City class CountryView(LoginRequiredMixin, UserPassesTestMixin, ListView): model = Country response_class = JsonResponse def handle_no_permission(self): return JsonResponse({'detail': 'Access Denied'}, status=403) def test_func(self): return self.request.user.username.startswith('t') def render_to_response(self, context, **response_kwargs): features = [obj.as_dict for obj in self.get_queryset()] return JsonResponse({'type': 'FeatureCollection', 'features': features}, safe=False) class CityView(ListView): model = City response_class = JsonResponse def render_to_response(self, context, **response_kwargs): features = [obj.as_dict for obj in self.get_queryset()] return JsonResponse({'type': 'FeatureCollection', 'features': features}, safe=False)
python
from .triplet_generators import generator_from_neighbour_matrix, \ TripletGenerator, UnsupervisedTripletGenerator, SupervisedTripletGenerator from .generators import KerasSequence
python
import setuptools with open("./README.md", "r") as f: description = f.read() setuptools.setup( name="blive", version="0.0.5", author="cam", author_email="[email protected]", long_description=description, long_description_content_type="text/markdown", url="https://github.com/yulinfeng000/blive", packages=setuptools.find_packages(), classifiers=[ "Programming Language :: Python :: 3", "License :: OSI Approved :: MIT License", ], install_requires=["aiohttp","loguru","requests","APScheduler","brotli"] )
python
from .md5_database import MD5DB from .paper_database import paperDB
python
import socket def resolv(hostname): try: return socket.gethostbyname(hostname) except socket.gaierror as e: raise Exception('Cloud not resolv "%s": %s' % (hostname, e)) class FilterModule(object): filter_map = { 'resolv': resolv, } def filters(self): return {'resolv': resolv}
python
import unittest import mutable_test class TestRemoveShared(unittest.TestCase): '''Tests for function duplicates.remove_shared.''' def test_general_case(self): ''' Test remove_shared where there are items that appear in both lists, and items that appear in only one or the other list. ''' list_1 = [1, 2, 3, 4, 5, 6] list_2 = [2, 4, 5, 7] list_1_expected = [1, 3, 6] list_2_expected = [2, 4, 5, 7] mutable_test.remove_shared(list_1, list_2) self.assertEqual(list_1, list_1_expected) self.assertEqual(list_2, list_2_expected) if __name__ == '__main__': unittest.main(exit=False)
python
import numpy as np from .preprocessing import * from .sequence_alignment import * class SemAlign(object): def __init__(self, embeddings_path, kernel_size=1, delimiter=',', verbose=True): self.lookup = load_embeddings(embeddings_path, delimiter) self.kernel_size = kernel_size self.verbose = verbose def align(self, text_str1, text_str2, k=1, w=(0.25,0.25)): # Preprocess strings tokens_list = preprocess_strs([text_str1, text_str2]) # Gather embeddings for tokens in each string token_embeddings = [get_embeddings(_, self.lookup) for _ in tokens_list] # Search for sequence alignments for each search str along text file all_alignments = [] alignment_scores = [] # Apply sequence kernels of radius len(search_phrase) to search phrase and text text1 = apply_sequence_kernel(token_embeddings[0], self.kernel_size) text2 = apply_sequence_kernel(token_embeddings[1], self.kernel_size) # Calculate cosine similarity between search phrase and text cos_dist = distance_matrix(text1, text2) # Calculate scoring matrix for sequence alignment score = scoring_matrix(cos_dist, wi=w[0], wj=w[1]) # Find first k alignments of len > 1 alignments = traceback(score, k=None) for j, _ in enumerate(alignments): all_alignments.append(_) alignment_scores.append(score_alignment(_, token_embeddings[0], text2, 1-(j/len(alignments)))) # Sort sorted_scores = np.argsort(alignment_scores)[::-1] # Display results if self.verbose: if k>1: print("Top ", k,':') for i in range(k): alignment = all_alignments[sorted_scores[i]] ss1 = [] ss2 = [] l = -1 j = -1 for _ in reversed(alignment): if _[0] != l: ss1.append(tokens_list[0][_[0]]) l = _[0] else: ss1.append('GAP') if _[1] != j: ss2.append(tokens_list[1][_[1]]) j = _[1] else: ss2.append('GAP') print('Match', i+1, ':', 'Score:',alignment_scores[sorted_scores[i]]) print(ss1) print(ss2,'\n') # Compile Top results alignments = np.array(alignments) alignment_scores = np.array(alignment_scores) top_alignments = alignments[sorted_scores[:k].astype('int')] top_scores = alignment_scores[sorted_scores[:k].astype('int')] return top_alignments, top_scores
python
from enum import Enum, auto class Color(Enum): BLACK = 0 WHITE = 1 RED = 2 BLUE = 3 # class TestEnum(Enum): # ONE = 0 # ONE = 1 class TestNewEnum(Enum): ZERO = auto() ONE = auto() TWO = auto() if __name__ == "__main__": print(Color.BLACK) print(Color.BLACK.name) print(Color.BLACK.value) for it in Color: print(it) for it in TestNewEnum: print(repr(it))
python
# Update the paths according to your environemnt OPT = "/data/guide/Trident/llvm-2.9-build/bin/opt" LLVMGCC = "/data/Trident/llvm-gcc4.2-2.9-x86_64-linux/bin/llvm-gcc" LLVMLINK = "/data/guide/Trident/llvm-2.9-build/bin/llvm-link" LLVMPASS_FOLDER = "/data/guide/Trident/llvm-2.9-build/lib/" LLI = "/data/guide/Trident/llvm-2.9-build/bin/lli" PYTHON = "python"
python
def pour(jug1, jug2): capacityA = 5 capacityB = 7 Measure = 4 print("%d \t %d" % (jug1, jug2)) if jug2 is Measure: # jug2 has "measure" amount of water stop return elif jug2 is capacityB: pour(0, jug1) elif jug1 != 0 and jug2 is 0: pour(0, jug1) elif jug1 is Measure: # jug1 has "measure" amount of water, pour that to jug2 pour(jug1, 0) elif jug1 < capacityA: pour(capacityA, jug2) elif jug1 < (capacityB-jug2): pour(0, (jug1+jug2)) else: pour(jug1-(capacityB-jug2), (capacityB-jug2)+jug2) print(''' capacityA = 5 capacityB = 7 Measure = 4 ''') print("Jug 1 \t Jug 2") pour(0, 0)
python
def isExistingClassification(t): pass def getSrcNodeName(dst): """ Get the name of the node connected to the argument dst plug. """ pass def getCollectionsRecursive(parent): pass def disconnect(src, dst): pass def findVolumeShader(shadingEngine, search='False'): """ Returns the volume shader (as MObject) of the given shading engine (as MObject). """ pass def transferPlug(src, dst): """ Transfer the connection or value set on plug 'src' on to the plug 'dst'. """ pass def findSurfaceShader(shadingEngine, search='False'): """ Returns the surface shader (as MObject) of the given shading engine (as MObject). """ pass def findPlug(userNode, attr): """ Return plug corresponding to attr on argument userNode. If the argument userNode is None, or the attribute is not found, None is returned. """ pass def disconnectSrc(src): """ Disconnect a source (readable) plug from all its destinations. Note that a single plug can be both source and destination, so this interface makes the disconnection intent explicit. """ pass def isSurfaceShaderNode(obj): pass def getSrcUserNode(dst): """ Get the user node connected to the argument dst plug. Note: Only applies to MPxNode derived nodes If the dst plug is unconnected, None is returned. """ pass def plugSrc(dstPlug): """ Return the source of a connected destination plug. If the destination is unconnected, returns None. """ pass def getOverridesRecursive(parent): pass def nameToUserNode(name): pass def isShadingType(typeName): pass def canOverrideNode(node): pass def createSrcMsgAttr(longName, shortName): """ Create a source (a.k.a. output, or readable) message attribute. """ pass def deleteNode(node): """ Remove the argument node from the graph. This function is undoable. """ pass def connect(src, dst): """ Connect source plug to destination plug. If the dst plug is None, the src plug will be disconnected from all its destinations (if any). If the src plug is None, the dst plug will be disconnected from its source (if any). If both are None, this function does nothing. If the destination is already connected, it will be disconnected. """ pass def isExistingType(t): pass def getDstUserNodes(src): """ Get the user nodes connected to the argument src plug. Note: Only applies to MPxNode derived nodes If the src plug is unconnected, None is returned. """ pass def plugDst(srcPlug): """ Return the destinations of a connected source plug. If the source is unconnected, returns None. """ pass def _recursiveSearch(colList): """ # Fonctions to compute the number of operations when layer are switched """ pass def getTotalNumberOperations(model): pass def _isDestination(plug): """ Returns True if the given plug is a destination plug, and False otherwise. If the plug is a compond attribute it returns True if any of it's children is a destination plug. """ pass def isShadingNode(obj): pass def disconnectDst(dst): """ Disconnect a destination (writable) plug from its source. Note that a single plug can be both source and destination, so this interface makes the disconnection intent explicit. """ pass def findDisplacementShader(shadingEngine, search='False'): """ Returns the displacement shader (as MObject) of the given shading engine (as MObject). """ pass def _findShader(shadingEngine, attribute, classification='None'): """ Returns the shader connected to given attribute on given shading engine. Optionally search for nodes from input connections to the shading engines satisfying classification if plug to attribute is not a destination and a classification string is specified. """ pass def isInheritedType(parentTypeName, childTypeName): pass def getSrcNode(dst): """ Get the node connected to the argument dst plug. """ pass def createGenericAttr(longName, shortName): pass def nameToExistingUserNode(name): pass def _transferConnectedPlug(src, dst): pass def connectMsgToDst(userNode, dst): """ Connect the argument userNode's message attribute to the argument dst plug. If the userNode is None the dst plug is disconnected from its sources. If the dst plug is None the userNode's message plug is disconnected from its destinations """ pass def isSurfaceShaderType(typeName): pass def notUndoRedoing(f): """ Decorator that will call the decorated method only if not currently in undoing or redoing. Particularly useful to prevent callbacks from generating commands since that would clear the redo stack. """ pass def createDstMsgAttr(longName, shortName): """ Create a destination (a.k.a. input, or writable) message attribute. """ pass kNoSuchNode = [] kSupportedVectorTypes = set() kSupportedSimpleTypes = set() kPlugTypeMismatch = []
python
import scanpy as sc import numpy as np import pandas as pd from scdcdm.util import cell_composition_data as ccd #%% adata_ref = sc.datasets.pbmc3k_processed() # this is an earlier version of the dataset from the pbmc3k tutorial print(adata_ref.X.shape) #%% cell_counts = adata_ref.obs["louvain"].value_counts() print(cell_counts) #%% df = pd.DataFrame() df = df.append(cell_counts, ignore_index=True) print(df) #%% cell_counts_2 = cell_counts new_dat = np.random.choice(1500, cell_counts_2.size) cell_counts_2 = cell_counts_2.replace(cell_counts_2.data, new_dat) cell_counts_2.index = cell_counts_2.index.tolist() cell_counts_2["test_type"] = 256 print(cell_counts_2) #%% df = df.append(cell_counts_2, ignore_index=True) print(df) #%% cell_counts_3 = cell_counts_2.iloc[[0, 3, 7, 8]] print(cell_counts_3) #%% df = df.append(cell_counts_3, ignore_index=True) print(df) #%% covs = dict(zip(np.arange(3), np.random.uniform(0, 1, 3))) print(covs) print(covs[0]) #%% ddf = pd.DataFrame() ddf = ddf.append(pd.Series(covs), ignore_index=True) print(ddf) #%% print(adata_ref.uns_keys()) print(adata_ref.uns["neighbors"]) #%% adata_ref.uns["cov"] = {"x1": 0, "x2": 1} print(adata_ref.uns["cov"]) #%% print(df.sum(axis=0).rename("n_cells").to_frame()) #%% data = ccd.from_scanpy_list([adata_ref, adata_ref, adata_ref], cell_type_identifier="louvain", covariate_key="cov") print(data.X) print(data.var) print(data.obs)
python
""" :type: tuple :Size: 1.295MB :Package Requirements: * **sklearn** Vec-colnames and neighber matrix used in Substitute DECS. See :py:class:`.DCESSubstitute` for detail. """ import os import pickle from OpenAttack.utils import make_zip_downloader NAME = "AttackAssist.DCES" URL = "https://cdn.data.thunlp.org/TAADToolbox/DCES.zip" DOWNLOAD = make_zip_downloader(URL) def LOAD(path): with open(os.path.join(path, 'descs.pkl'), 'rb') as f: descs = pickle.load(f) from sklearn.neighbors import NearestNeighbors neigh = NearestNeighbors(** { 'algorithm': 'auto', 'leaf_size': 30, 'metric': 'euclidean', 'metric_params': None, 'n_jobs': 1, 'n_neighbors': 5, 'p': 2, 'radius': 1.0 }) return descs, neigh
python
#coding:utf-8 """ @file: db_config @author: lyn @contact: [email protected] @python: 3.3 @editor: PyCharm @create: 2016-11-20 12:18 @description: sqlalchemy 配置数据库 """ from JsonConfig import DB_Config for path in ['.','..']: try: db = DB_Config( json_file_path= '{}/pgdb_config.json'.format(path) ).to_dict() except: continue pg_url = ( '{}://{}:{}@{}:{}/{}' ).format( db['db_type'],db['user'],db['password'], db['host'],db['port'],db['db_name'], ) print(pg_url) from sqlalchemy import * from sqlalchemy.orm import sessionmaker Session = sessionmaker() engine = create_engine( name_or_url = pg_url, echo = False ) Session.configure(bind=engine)
python
import os import datetime import dropbox from app import db from app.models import SystemLog from app.enums import LogStatus, LogType from flask import current_app def download(dbx, folder, subfolder, name): """Download a file. Return the bytes of the file, or None if it doesn't exist. """ path = '/%s/%s/%s' % (folder, subfolder.replace(os.path.sep, '/'), name) while '//' in path: path = path.replace('//', '/') try: md, res = dbx.files_download(path) except dropbox.exceptions.HttpError as err: print('*** HTTP error', err) return None data = res.content print(len(data), 'bytes; md:', md) return data def log_error_to_database(error): current_app.logger.error(error) db.session.rollback() error_message = str(error) log = SystemLog(message=error_message, status=LogStatus.OPEN, type=LogType.WEBSITE, created_at=datetime.datetime.now()) db.session.add(log) db.session.commit()
python
NumOfRows = int(input("Enter number of rows: ")) coeffcient = 1 for i in range(1, NumOfRows+1): for space in range(1, NumOfRows-i+1): print(" ",end="") for j in range(0, i): if j==0 or i==0: coeffcient = 1 else: coeffcient = coeffcient * (i - j)//j print(coeffcient, end = " ") print()
python
import abc class ORMDB(abc.ABC): @abc.abstractmethod def parse_sql(self, sql_str): pass
python
# -*- coding: utf-8 -*- """This python program converts various parts of glowscript from the most convenient format for modification into the most convenient format for deployment. * Take shaders from shaders/*.shader and combine them into lib/glow/shaders.gen.js * Extract glowscript libraries list from ``untrusted/run.js``. In the implementation, we need ``slimit`` as our dependency:: $ pip install slimit TODO * Come up with a less painful model for development than running this after every change * Combine and minify lib/*.js into ide.min.js, run.min.js, and embed.min.js """ from __future__ import division from __future__ import print_function import argparse import os import subprocess from functools import partial from collections import namedtuple from pprint import pprint from slimit import ast from slimit.parser import Parser as JSParser from slimit.visitors import nodevisitor version = "2.2dev" src_dir = os.path.dirname(__file__) def extract_glow_lib(): runjs = norm_path('untrusted/run.js') parser = JSParser() with open(runjs) as f: tree = parser.parse(f.read()) for node in nodevisitor.visit(tree): if (isinstance(node, ast.Assign) and isinstance(node.left, ast.DotAccessor) and node.left.identifier.value == 'glowscript_libraries' and isinstance(node.right, ast.Object)): break else: print('Parsing {} failed'.format(runjs)) exit(-1) return preproc_lib_path({ prop.left.value: [ eval(lib.value) for lib in prop.right.items if isinstance(lib, ast.String) ] for prop in node.right.properties }) def preproc_lib_path(libs): pjoin = partial(os.path.join, src_dir, 'untrusted') return {pkg: map(os.path.normpath, (map(pjoin, paths))) for pkg, paths in libs.items()} def build_shader(): shader_file = ["Export({shaders: {"] shaders_dir = os.path.join(src_dir, 'shaders') output_js = os.path.join(src_dir, 'lib', 'glow', 'shaders.gen.js') for fn in os.listdir(shaders_dir): if not fn.endswith('.shader'): continue name = fn.rpartition('.shader')[0] with open(os.path.join(shaders_dir, fn), 'rt') as f: shader_file.append('"{name}":{src!r},'.format( name=name, src=f.read())) shader_file.append('}});') with open(output_js, 'w') as f: f.writelines('\n'.join(shader_file)) print("Shader {!r} built successfully.".format(output_js)) def norm_path(p): ''' :param p: path related to source dir >>> norm_path('lib/glow/graph.js') 'path/to/src/dir/lib/glow/graph.js' ''' return os.path.normpath(os.path.join(src_dir, p)) def combine(inlibs): def gen(): yield ( "/*This is a combined, compressed file. " "Look at https://github.com/BruceSherwood/glowscript " "for source code and copyright information.*/" ) yield ";(function(){})();" for fn in inlibs: with open(fn, 'r') as f: yield f.read() return "\n".join(gen()) def minify(inlibs, inlibs_nomin, outlib, no_min=False): ''' Do unglify for ``inlibs`` :param inlibs: a list of paths which want to be minify :param inlibs_nomin: a list of paths which do *not* want to be minify :param no_min: if True, we build no minified libraries only. Available environment variable: :NODE_PATH: the path of nodejs exetuable ''' node_cmd = os.environ.get('NODE_PATH', 'node') uglifyjs = norm_path('build-tools/UglifyJS/bin/uglifyjs') with open(outlib, 'w') as outf: if not no_min: uglify = subprocess.Popen( [node_cmd, uglifyjs], stdin=subprocess.PIPE, stdout=outf, ) uglify.communicate(combine(inlibs)) rc = uglify.wait() if rc != 0: print("Something went wrong on {}".format(outlib)) else: print("Uglify {} successfully".format(outlib)) if inlibs_nomin: outf.write(combine(inlibs_nomin)) def build_package(libs, no_min=False): ''' :param libs: the dictionary contain all glowscript libraries:: { "package_1": [ 'lib 1' ... ], "package_2": [ ... ], ... } :param no_min: if True, we build no minified libraries only. ''' Package = namedtuple('Package', ('inlibs', 'inlibs_nomin', 'outlib', 'comment')) pkgs = ( Package(inlibs='run', inlibs_nomin=[], outlib='glow.{}.min.js'.format(version), comment='glow run-time package'), Package(inlibs='compile', inlibs_nomin=[], outlib='compiler.{}.min.js'.format(version), comment='compiler package'), Package(inlibs='RSrun', inlibs_nomin=[], outlib='RSrun.{}.min.js'.format(version), comment='RapydScript run-time package'), Package(inlibs='RScompile', inlibs_nomin=[], outlib='RScompiler.{}.min.js'.format(version), comment='GlowScript package'), ) for pkg in pkgs: minify(libs[pkg.inlibs], pkg.inlibs_nomin, norm_path('package/{}'.format(pkg.outlib)), no_min=no_min) print('Finished {}'.format(pkg.comment)) def cmd_args(): parser = argparse.ArgumentParser() parser.add_argument('-s', '--shader', action='store_true', default=False, help="Build shader file 'lib/glow/shaders.gen.js' only") parser.add_argument('--no-min', dest='no_min', action='store_true', default=False, help="Build non-minified libraries only") parser.add_argument('-l', '--libs', action='store_true', default=False, help='Show glowscript libraries and exit') return parser.parse_args() if __name__ == '__main__': glowscript_libraries = extract_glow_lib() args = cmd_args() if args.libs: pprint(glowscript_libraries) elif args.shader: build_shader(glowscript_libraries) else: # default: build all build_shader() build_package(glowscript_libraries, no_min=args.no_min)
python
# Copyright (c) 2021 Graphcore Ltd. All rights reserved. import argparse import io import numpy as np import os from PIL import Image import requests import time import yacs import torch from poptorch import inferenceModel, Options from models.detector import Detector from models.yolov4_p5 import Yolov4P5 from utils.config import get_cfg_defaults from utils.preprocessing import ResizeImage, Pad, ToTensor from utils.tools import load_and_fuse_pretrained_weights, post_processing, StatRecorder def get_cfg(): cfg = get_cfg_defaults() cfg.model.image_size = 416 cfg.inference.nms = True cfg.inference.class_conf_threshold = 0.001 cfg.inference.iou_threshold = 0.65 cfg.inference.nms_max_detections = 10 cfg.inference.pre_nms_topk_k = 1180 cfg.ipuopts.batches_per_step = 1 cfg.model.normalization = "batch" cfg.model.activation = "mish" cfg.model.half = False cfg.model.uint_io = True cfg.model.input_channels = 3 cfg.model.micro_batch_size = 1 cfg.model.mode = "test" cfg.model.ipu = True return cfg def ipu_options(opt: argparse.ArgumentParser, cfg: yacs.config.CfgNode, model: Detector): """Configurate the IPU options using cfg and opt options. Parameters: opt: opt object containing options introduced in the command line cfg: yacs object containing the config model[Detector]: a torch Detector Model Returns: ipu_opts: Options for the IPU configuration """ batches_per_step = cfg.ipuopts.batches_per_step half = cfg.model.half ipu_opts = Options() ipu_opts.deviceIterations(batches_per_step) ipu_opts.autoRoundNumIPUs(True) if half: ipu_opts.Precision.setPartialsType(torch.float16) model.half() return ipu_opts def get_image_and_label(cfg): url_sample_image = 'http://images.cocodataset.org/val2017/000000100238.jpg' img_data = requests.get(url_sample_image).content image = Image.open(io.BytesIO(img_data)).convert('RGB') height, width = image.size image_sizes = torch.Tensor([[height, width]]) label = np.array([[39, 0.319508, 0.745573, 0.020516, 0.028479], [0, 0.484391, 0.583271, 0.360031, 0.833458], [0, 0.685664, 0.494917, 0.284422, 0.986458], [0, 0.869086, 0.720719, 0.207766, 0.549563], [0, 0.168453, 0.526521, 0.333531, 0.914208], [29, 0.166422, 0.562135, 0.118313, 0.139687], [29, 0.480703, 0.565990, 0.135906, 0.120813], [26, 0.591977, 0.203583, 0.045234, 0.121958], [26, 0.349672, 0.619479, 0.150000, 0.568833], [29, 0.708734, 0.284302, 0.118188, 0.159854]]) resizer = ResizeImage(cfg.model.image_size) padder = Pad(cfg.model.image_size) to_tensor = ToTensor(int(cfg.dataset.max_bbox_per_scale), "uint") item = (image, label) item = resizer(item) image, label = padder(item) image, label = to_tensor((np.array(image), label)) return image.unsqueeze(axis=0), label.unsqueeze(axis=0), image_sizes def prepare_model(cfg, debugging_nms=False): opt = argparse.ArgumentParser() opt.weights = os.environ['PYTORCH_APPS_DETECTION_PATH'] + '/weights/yolov4-p5-sd.pt' model = Yolov4P5(cfg, debugging_nms=debugging_nms) model.eval() model = load_and_fuse_pretrained_weights(model, opt) model.optimize_for_inference() if cfg.model.ipu: ipu_opts = ipu_options(opt, cfg, model) return inferenceModel(model, ipu_opts) else: return model def post_process_and_eval(cfg, y, image_sizes, transformed_labels): stat_recorder = StatRecorder(cfg) processed_batch = post_processing(cfg, y, image_sizes, transformed_labels) pruned_preds_batch = processed_batch[0] processed_labels_batch = processed_batch[1] for idx, (pruned_preds, processed_labels) in enumerate(zip(pruned_preds_batch, processed_labels_batch)): stat_recorder.record_eval_stats(processed_labels, pruned_preds, image_sizes[idx]) return stat_recorder.compute_and_print_eval_metrics(print)
python
from datetime import datetime import bs4 from bs4 import BeautifulSoup from django.contrib.auth.models import User from bookmarks.models import Bookmark, parse_tag_string from bookmarks.services.tags import get_or_create_tags def import_netscape_html(html: str, user: User): soup = BeautifulSoup(html, 'html.parser') bookmark_tags = soup.find_all('dt') for bookmark_tag in bookmark_tags: _import_bookmark_tag(bookmark_tag, user) def _import_bookmark_tag(bookmark_tag: bs4.Tag, user: User): link_tag = bookmark_tag.a if link_tag is None: return # Either modify existing bookmark for the URL or create new one url = link_tag['href'] bookmark = _get_or_create_bookmark(url, user) bookmark.url = url bookmark.date_added = datetime.utcfromtimestamp(int(link_tag['add_date'])) bookmark.date_modified = bookmark.date_added bookmark.unread = link_tag['toread'] == '1' bookmark.title = link_tag.string bookmark.owner = user bookmark.save() # Set tags tag_string = link_tag['tags'] tag_names = parse_tag_string(tag_string) tags = get_or_create_tags(tag_names, user) bookmark.tags.set(tags) bookmark.save() def _get_or_create_bookmark(url: str, user: User): try: return Bookmark.objects.get(url=url, owner=user) except Bookmark.DoesNotExist: return Bookmark()
python
###exercicio 49 n = int(input('digite um numero: ')) for c in range (1, 11): print (' {} * {} = {}'.format(n, c, n*c)) print ('Fim!!!')
python
import cv2 import numpy as np from PyQt5.QtCore import Qt, QObject, pyqtSignal from PyQt5.QtGui import QImage, QPixmap, QDropEvent from PyQt5.QtWidgets import QWidget, QVBoxLayout, QLabel, QSizePolicy class QMapCommunicate(QObject): drop_event = pyqtSignal(QDropEvent) class PsQMapWidget(QWidget): def __init__(self, qmap, model=None): super(PsQMapWidget, self).__init__() self.qmap = qmap self.model = model self.setAcceptDrops(True) self.c = QMapCommunicate() self.canvas = QLabel() # self.canvas.setMaximumSize(400, 400) sp = self.canvas.sizePolicy() sp.setHorizontalPolicy(QSizePolicy.Expanding) sp.setVerticalPolicy(QSizePolicy.Expanding) self.canvas.setSizePolicy(sp) self.setContentsMargins(0,0,0,0) self.canvas.setMinimumSize(20, 20) vbox = QVBoxLayout() vbox.addWidget(self.canvas) self.setLayout(vbox) # self.setStyleSheet(""" # border: 1px solid red; # padding: 0px; # border-radius: 8px; # margin: 0px; # """) # title self.image_info_label = QLabel(parent=self.canvas) self.image_info_label.setText(self.qmap.map_type) #background-color: rgba(31, 27, 36, .7); self.image_info_label.setStyleSheet(""" background-color: rgba(31, 27, 36, .7); padding: 4px; border-radius: 4px; margin: 1px; font-weight: bold; """) def get_affine_cv(self, scale_center, rot, scale, translate): sin_theta = np.sin(rot) cos_theta = np.cos(rot) a_11 = scale * cos_theta a_21 = -scale * sin_theta a_12 = scale * sin_theta a_22 = scale * cos_theta a_13 = scale_center.x() * (1 - scale * cos_theta) - scale * sin_theta * scale_center.x() + translate.x() a_23 = scale_center.y() * (1 - scale * cos_theta) + scale * sin_theta * scale_center.y() + translate.y() return np.array([[a_11, a_12, a_13], [a_21, a_22, a_23]], dtype=float) def update(self): np_matrix_2d = self.qmap.get_matrix(dim=2) # typically initial resize if np_matrix_2d is None: return img_2d_cp = np_matrix_2d.astype(np.uint16) # scale over min max of all slices m_max = self.qmap.get_max_value() m_min = self.qmap.get_min_value() cv_image = (255 * ((img_2d_cp - m_min) / (m_max - m_min))).astype(np.uint8) # .copy() # scale over min max of single slice # cv_image = (255 * ((img_2d_cp - img_2d_cp.min()) / img_2d_cp.ptp())).astype(np.uint8) # .copy() cv_image = cv2.applyColorMap(cv_image, cv2.COLORMAP_HOT) # COLORMAP_HOT cv2.cvtColor(cv_image, cv2.COLOR_BGR2RGB, cv_image) height, width, rgb = cv_image.shape q_img = QImage(cv_image.data, width, height, QImage.Format.Format_RGB888) q_pix_map = QPixmap(q_img) q_pix_map = q_pix_map.scaled(self.canvas.size(), Qt.KeepAspectRatio) self.canvas.setAlignment(Qt.AlignCenter) self.canvas.setPixmap(q_pix_map) def dragEnterEvent(self, event): if event.mimeData().hasText(): event.accept() else: event.ignore() def dropEvent(self, event): self.c.drop_event.emit(event) # text = event.mimeData().text() # print(text)
python
# coding: utf-8 import torch import torch.nn.functional as F from helpers.utils import int_type, add_noise_to_imgs class NumDiffAutoGradFn(torch.autograd.Function): """ A custom backward pass for our [s, x, y] vector when using hard attention grid = torch.Size([16, 32, 32, 2]) grad_output_shape = torch.Size([16, 1, 32, 32]) z_grad = torch.Size([48, 1, 32, 32]) expected shape [16, 3] but got [48, 1, 32, 32] """ @staticmethod def forward(ctx, z, crops, window_size, delta): """ In the forward pass we receive a Tensor containing the input and return a Tensor containing the output. ctx is a context object that can be used to stash information for backward computation. You can cache arbitrary objects for use in the backward pass using the ctx.save_for_backward method. """ window_size_tensor = int_type(z.is_cuda)([window_size]) delta_tensor = int_type(z.is_cuda)([delta]) ctx.save_for_backward(z, crops, window_size_tensor, delta_tensor) # save the full extra window _, _, cw_b, cw_e, ch_b, ch_e = NumDiffAutoGradFn._get_dims(crops, window_size) return crops[:, :, cw_b:cw_e, ch_b:ch_e].clone() # return center crop @staticmethod def _get_dims(crops, window_size): W, H = crops.shape[2:] assert (W - window_size) % 2 == 0, "width - window_size is not divisible by 2" assert (H - window_size) % 2 == 0, "height - window_size is not divisible by 2" cw_b, cw_e = [int((W - window_size) / 2.) , int((W - window_size) / 2. + window_size)] ch_b, ch_e = [int((H - window_size) / 2.) , int((H - window_size) / 2. + window_size)] return W, H, cw_b, cw_e, ch_b, ch_e @staticmethod def _numerical_grads(crops, window_size, delta=1): ''' takes an enlarged crop window and returns delta-px perturbed grads eg for delta=1: full = 34 34 | delta = 1 | center = 1 33 1 33 xmh = 0 32 1 33 xph = 2 34 1 33 ymh = 1 33 0 32 yph = 1 33 2 34 smh = 2 32 2 32 sph = 0 34 0 34 eg for delta=2: full = 36 36 | delta = 1 | center = 2 34 2 34 xmh = 1 33 2 34 xph = 3 35 2 34 ymh = 2 34 1 33 yph = 2 34 3 35 smh = 3 33 3 33 sph = 1 35 1 35 full = 36 36 | delta = 2 | center = 2 34 2 34 xmh = 0 32 2 34 xph = 4 36 2 34 ymh = 2 34 0 32 yph = 2 34 4 36 smh = 4 32 4 32 sph = 0 36 0 36 ''' assert len(crops.shape) == 4, "num-grad needs 4d inputs" assert window_size > 1, "window size needs to be larger than 1" # get dims and sanity check W, H, cw_b, cw_e, ch_b, ch_e = NumDiffAutoGradFn._get_dims(crops, window_size) # print("full = ", W, H, " | delta =", delta, " | center = ", cw_b, cw_e, ch_b, ch_e) assert cw_b - delta >= 0 assert cw_e + delta < W + 1 assert ch_b - delta >= 0 assert ch_e + delta < H + 1 # [f(x+h, y) - f(x-h, y)] / delta fx_m_h = crops[:, :, cw_b-delta:cw_e-delta, ch_b:ch_e] fx_p_h = crops[:, :, cw_b+delta:cw_e+delta, ch_b:ch_e] # print('xmh = ',cw_b-delta,cw_e-delta, ch_b,ch_e) # print('xph = ', cw_b+delta,cw_e+delta, ch_b,ch_e) dfx = (fx_p_h - fx_m_h) / delta # [f(x, y+h) - f(x, y-h)] / delta fy_m_h = crops[:, :, cw_b:cw_e, ch_b-delta:ch_e-delta] fy_p_h = crops[:, :, cw_b:cw_e, ch_b+delta:ch_e+delta] # print('ymh = ', cw_b,cw_e, ch_b-delta,ch_e-delta) # print('yph = ', cw_b,cw_e, ch_b+delta,ch_e+delta) dfy = (fy_p_h - fy_m_h) / delta # approximately this: [f(x, y, s*1.01) - f(x, y, s*0.99)] / delta fs_m_h = crops[:, :, cw_b+delta:cw_e-delta, ch_b+delta:ch_e-delta] fs_p_h = crops[:, :, cw_b-delta:cw_e+delta, ch_b-delta:ch_e+delta] # print("fs_m_h = ", fs_m_h.shape, " | fs_p_h = ", fs_p_h.shape) fs_m_h = F.interpolate(fs_m_h, size=(window_size, window_size), mode='bilinear') fs_p_h = F.interpolate(fs_p_h, size=(window_size, window_size), mode='bilinear') # print('smh = ', cw_b+delta,cw_e-delta, ch_b+delta,ch_e-delta) # print('sph = ', cw_b-delta,cw_e+delta, ch_b-delta,ch_e+delta) dfs = (fs_p_h - fs_m_h) / delta # TODO: is this delta right? # expand 1'st dim and concat, returns [B, 3, C, W, H] grads = torch.cat( [dfs.unsqueeze(1), dfx.unsqueeze(1), dfy.unsqueeze(1)], 1 ) # memory cleanups del dfx; del fx_m_h; del fx_p_h del dfy; del fy_m_h; del fy_p_h del dfs; del fs_m_h; del fs_p_h return grads @staticmethod def backward(ctx, grad_output): """ In the backward pass we receive a Tensor containing the gradient of the loss with respect to the output, and we need to compute the gradient of the loss with respect to the input. """ z, crops, window_size, delta = ctx.saved_tensors window_size, delta = window_size.item(), delta.item() crops_perturbed = add_noise_to_imgs(crops) # add noise # get the mean of the gradients over all perturbations z_grad = torch.cat([NumDiffAutoGradFn._numerical_grads( crops_perturbed, window_size, k+1).unsqueeze(0) for k in range(0, delta)], 0) z_grad = torch.mean(z_grad, 0) # MC estimate over all possible perturbations #z_grad = torch.sum(z_grad, 0) # MC estimate over all possible perturbations, TODO: try mean z_grad = torch.matmul(grad_output.unsqueeze(1), z_grad) # connect the grads z_grad = torch.mean(torch.mean(torch.mean(z_grad, -1), -1), -1) # reduce over y, x, chans #z_grad = torch.sum(torch.sum(torch.sum(z_grad, -1), -1), -1) # reduce over y, x, chans TODO: try mean del crops; del crops_perturbed # mem cleanups return z_grad, None, None, None # no need for grads for crops, window_size and delta
python
import os import shutil # Create a new dummy store to run tests on from tests._stores_for_tests import _TestFixStore # recs = [ # {'fix_id': 'Fix1', 'operands': {'arg1': '1'}, 'ncml': '<NcML1>'}, # {'fix_id': 'Fix2', 'operands': {'arg2': '2'}, 'ncml': '<NcML2>'} # ] recs = [ { "fix_id": "Fix1", "title": "Apply Fix 1", "description": "Applies fix 1", "category": "test_fixes", "reference_implementation": "daops.test.test_fix1", "operands": {"arg1": "1"}, }, { "fix_id": "Fix2", "title": "Apply Fix 2", "description": "Applies fix 2", "category": "test_fixes", "reference_implementation": "daops.test.test_fix2", "operands": {"arg2": "2"}, }, ] store = None def _clear_store(): dr = _TestFixStore.config["local.base_dir"] if os.path.isdir(dr): shutil.rmtree(dr) def setup_module(): _clear_store() global store store = _TestFixStore() def test_publish_fix_1(): _id = "ds.1.1.1.1.1.1" store.publish_fix(_id, recs[0]) assert store.get(_id)["fixes"] == [recs[0]] def test_publish_fix_2(): _id = "ds.1.1.1.1.1.2" store.publish_fix(_id, recs[1]) assert store.get(_id)["fixes"] == [recs[1]] _id = "ds.1.1.1.1.1.1" store.publish_fix(_id, recs[1]) assert store.get(_id)["fixes"] == [recs[0], recs[1]] def test_withdraw_fix_1(): _id = "ds.1.1.1.1.1.1" store.withdraw_fix(_id, "Fix1") assert store.get(_id)["fixes"] == [recs[1]] store.withdraw_fix(_id, "Fix2") assert store.exists(_id) is False def teardown_module(): # pass _clear_store()
python
import os import lldb class ConcurrentLazyFormatter: def __init__(self, valobj, dict): self.valobj = lldb.value(valobj) def get_child_index(self, name): return 0 # There is only ever one child def num_children(self): if self.has_value: return 1 return 0 def get_child_at_index(self, index): if index != 0: return None # There is only ever one child if not self.has_value: return None return self.valobj.value_.storage_.value.sbvalue def update(self): self.has_value = True if ( self.valobj .value_ .storage_ .init .mutex_ .lock_ .sbvalue.GetValueAsUnsigned() ) != 0 else False return False def has_children(self): return self.has_value def ConcurrentLazySummary(valobj, _dict): computed = valobj.GetNumChildren() > 0; return f"Is Computed={'true' if computed else 'false'}" def __lldb_init_module(debugger, _dict): typeName = r"(^folly::ConcurrentLazy<.*$)" moduleName = os.path.splitext(os.path.basename(__file__))[0] debugger.HandleCommand( 'type synthetic add ' + f'-x "{typeName}" ' + f'--python-class {moduleName}.ConcurrentLazyFormatter' ) debugger.HandleCommand( 'type summary add --expand --hide-empty --no-value ' + f'-x "{typeName}" ' + f'--python-function {moduleName}.ConcurrentLazySummary' )
python
import os import re from .models import Photo def generate_photo(file_path): photo_path, width, height = image_utils.fit_and_save(file_path) thumb_path = image_utils.generate_thumbnail(photo_path) photo_path, thumb_path = (relp(rp(p), PARENT_DIR) for p in (photo_path, thumb_path)) photo = Photo(image_path=photo_path, thumbnail_path=thumb_path, width=width, height=height) photo.save() return photo def save_file(file, file_path): with open(file_path, 'wb+') as destination: for chunk in file.chunks(): destination.write(chunk)
python
# project/users/forms.py from flask_wtf import Form from wtforms import StringField, PasswordField from wtforms.validators import DataRequired, Length, EqualTo, Email class RegisterForm(Form): email = StringField('Email', validators=[DataRequired(), Email(), Length(min=6, max=40)]) password = PasswordField('Password', validators=[DataRequired(), Length(min=6, max=40)]) confirm = PasswordField('Repeat Password', validators=[DataRequired(), EqualTo('password')]) class LoginForm(Form): email = StringField('Email', validators=[DataRequired(), Email(), Length(min=6, max=40)]) password = PasswordField('Password', validators=[DataRequired()]) class EmailForm(Form): email = StringField('Email', validators=[DataRequired(), Email(), Length(min=6, max=40)]) class PasswordForm(Form): password = PasswordField('Password', validators=[DataRequired()])
python
from .libfm import ( RegressionCallback, ClassificationCallback, OrderedProbitCallback, LibFMLikeCallbackBase, )
python