content
stringlengths
27
928k
path
stringlengths
4
230
size
int64
27
928k
nl_text
stringlengths
21
396k
nl_size
int64
21
396k
nl_language
stringlengths
2
3
nl_language_score
float64
0.04
1
#!/usr/bin/python # Copyright (c) 2020, 2021 Oracle and/or its affiliates. # This software is made available to you under the terms of the GPL 3.0 license or the Apache 2.0 license. # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) # Apache License v2.0 # See LICENSE.TXT for details. # GENERATED FILE - DO NOT EDIT - MANUAL CHANGES WILL BE OVERWRITTEN from __future__ import absolute_import, division, print_function __metaclass__ = type ANSIBLE_METADATA = { "metadata_version": "1.1", "status": ["preview"], "supported_by": "community", } DOCUMENTATION = """ --- module: oci_optimizer_recommendation_actions short_description: Perform actions on a Recommendation resource in Oracle Cloud Infrastructure description: - Perform actions on a Recommendation resource in Oracle Cloud Infrastructure - For I(action=bulk_apply), applies the specified recommendations to the resources. version_added: "2.9.0" author: Oracle (@oracle) options: recommendation_id: description: - The unique OCID associated with the recommendation. type: str aliases: ["id"] required: true resource_action_ids: description: - The unique OCIDs of the resource actions that recommendations are applied to. - This field is deprecated. type: list elements: str actions: description: - The unique resource actions that recommendations are applied to. type: list elements: dict suboptions: resource_action_id: description: - The unique OCIDs of the resource actions that recommendations are applied to. type: str required: true status: description: - The current status of the recommendation. type: str choices: - "PENDING" - "DISMISSED" - "POSTPONED" - "IMPLEMENTED" time_status_end: description: - The date and time the current status will change. The format is defined by RFC3339. - "For example, \\"The current `postponed` status of the resource action will end and change to `pending` on this date and time.\\"" type: str parameters: description: - "Additional parameter key-value pairs defining the resource action. For example:" - "`{\\"timeAmount\\": 15, \\"timeUnit\\": \\"seconds\\"}`" type: dict strategy_name: description: - The name of the strategy. type: str status: description: - The current status of the recommendation. type: str choices: - "PENDING" - "DISMISSED" - "POSTPONED" - "IMPLEMENTED" required: true time_status_end: description: - The date and time the current status will change. The format is defined by RFC3339. - "For example, \\"The current `postponed` status of the resource action will end and change to `pending` on this date and time.\\"" type: str action: description: - The action to perform on the Recommendation. type: str required: true choices: - "bulk_apply" extends_documentation_fragment: [ oracle.oci.oracle, oracle.oci.oracle_wait_options ] """ EXAMPLES = """ - name: Perform action bulk_apply on recommendation oci_optimizer_recommendation_actions: # required recommendation_id: "ocid1.recommendation.oc1..xxxxxxEXAMPLExxxxxx" status: PENDING action: bulk_apply # optional resource_action_ids: [ "null" ] actions: - # required resource_action_id: "ocid1.resourceaction.oc1..xxxxxxEXAMPLExxxxxx" # optional status: PENDING time_status_end: 2013-10-20T19:20:30+01:00 parameters: null strategy_name: strategy_name_example time_status_end: 2013-10-20T19:20:30+01:00 """ RETURN = """ recommendation: description: - Details of the Recommendation resource acted upon by the current operation returned: on success type: complex contains: id: description: - The unique OCID associated with the recommendation. returned: on success type: str sample: "ocid1.resource.oc1..xxxxxxEXAMPLExxxxxx" compartment_id: description: - The OCID of the tenancy. The tenancy is the root compartment. returned: on success type: str sample: "ocid1.compartment.oc1..xxxxxxEXAMPLExxxxxx" category_id: description: - The unique OCID associated with the category. returned: on success type: str sample: "ocid1.category.oc1..xxxxxxEXAMPLExxxxxx" name: description: - The name assigned to the recommendation. returned: on success type: str sample: name_example description: description: - Text describing the recommendation. returned: on success type: str sample: description_example importance: description: - The level of importance assigned to the recommendation. returned: on success type: str sample: CRITICAL resource_counts: description: - An array of `ResourceCount` objects grouped by the status of the resource actions. returned: on success type: complex contains: status: description: - The recommendation status of the resource. returned: on success type: str sample: PENDING count: description: - The count of resources. returned: on success type: int sample: 56 lifecycle_state: description: - The recommendation's current state. returned: on success type: str sample: ACTIVE estimated_cost_saving: description: - The estimated cost savings, in dollars, for the recommendation. returned: on success type: float sample: 1.2 status: description: - The current status of the recommendation. returned: on success type: str sample: PENDING time_status_begin: description: - The date and time that the recommendation entered its current status. The format is defined by RFC3339. - "For example, \\"The status of the recommendation changed from `pending` to `current(ignored)` on this date and time.\\"" returned: on success type: str sample: "2013-10-20T19:20:30+01:00" time_status_end: description: - The date and time the current status will change. The format is defined by RFC3339. - "For example, \\"The current `postponed` status of the recommendation will end and change to `pending` on this date and time.\\"" returned: on success type: str sample: "2013-10-20T19:20:30+01:00" time_created: description: - The date and time the recommendation details were created, in the format defined by RFC3339. returned: on success type: str sample: "2020-08-25T21:10:29.600Z" time_updated: description: - The date and time the recommendation details were last updated, in the format defined by RFC3339. returned: on success type: str sample: "2020-08-25T21:10:29.600Z" supported_levels: description: - "" returned: on success type: complex contains: items: description: - The list of supported levels. returned: on success type: complex contains: name: description: - The name of the profile level. returned: on success type: str sample: name_example extended_metadata: description: - Additional metadata key/value pairs for the recommendation. - "For example:" - "`{\\"EstimatedSaving\\": \\"200\\"}`" returned: on success type: dict sample: {} sample: { "id": "ocid1.resource.oc1..xxxxxxEXAMPLExxxxxx", "compartment_id": "ocid1.compartment.oc1..xxxxxxEXAMPLExxxxxx", "category_id": "ocid1.category.oc1..xxxxxxEXAMPLExxxxxx", "name": "name_example", "description": "description_example", "importance": "CRITICAL", "resource_counts": [{ "status": "PENDING", "count": 56 }], "lifecycle_state": "ACTIVE", "estimated_cost_saving": 1.2, "status": "PENDING", "time_status_begin": "2013-10-20T19:20:30+01:00", "time_status_end": "2013-10-20T19:20:30+01:00", "time_created": "2020-08-25T21:10:29.600Z", "time_updated": "2020-08-25T21:10:29.600Z", "supported_levels": { "items": [{ "name": "name_example" }] }, "extended_metadata": {} } """ from ansible.module_utils.basic import AnsibleModule from ansible_collections.oracle.oci.plugins.module_utils import ( oci_common_utils, oci_wait_utils, ) from ansible_collections.oracle.oci.plugins.module_utils.oci_resource_utils import ( OCIActionsHelperBase, get_custom_class, ) try: from oci.optimizer import OptimizerClient from oci.optimizer.models import BulkApplyRecommendationsDetails HAS_OCI_PY_SDK = True except ImportError: HAS_OCI_PY_SDK = False class RecommendationActionsHelperGen(OCIActionsHelperBase): """ Supported actions: bulk_apply """ @staticmethod def get_module_resource_id_param(): return "recommendation_id" def get_module_resource_id(self): return self.module.params.get("recommendation_id") def get_get_fn(self): return self.client.get_recommendation def get_resource(self): return oci_common_utils.call_with_backoff( self.client.get_recommendation, recommendation_id=self.module.params.get("recommendation_id"), ) def bulk_apply(self): action_details = oci_common_utils.convert_input_data_to_model_class( self.module.params, BulkApplyRecommendationsDetails ) return oci_wait_utils.call_and_wait( call_fn=self.client.bulk_apply_recommendations, call_fn_args=(), call_fn_kwargs=dict( recommendation_id=self.module.params.get("recommendation_id"), bulk_apply_recommendations_details=action_details, ), waiter_type=oci_wait_utils.WORK_REQUEST_WAITER_KEY, operation="{0}_{1}".format( self.module.params.get("action").upper(), oci_common_utils.ACTION_OPERATION_KEY, ), waiter_client=self.get_waiter_client(), resource_helper=self, wait_for_states=oci_common_utils.get_work_request_completed_states(), ) RecommendationActionsHelperCustom = get_custom_class( "RecommendationActionsHelperCustom" ) class ResourceHelper(RecommendationActionsHelperCustom, RecommendationActionsHelperGen): pass def main(): module_args = oci_common_utils.get_common_arg_spec( supports_create=False, supports_wait=True ) module_args.update( dict( recommendation_id=dict(aliases=["id"], type="str", required=True), resource_action_ids=dict(type="list", elements="str"), actions=dict( type="list", elements="dict", options=dict( resource_action_id=dict(type="str", required=True), status=dict( type="str", choices=["PENDING", "DISMISSED", "POSTPONED", "IMPLEMENTED"], ), time_status_end=dict(type="str"), parameters=dict(type="dict"), strategy_name=dict(type="str"), ), ), status=dict( type="str", required=True, choices=["PENDING", "DISMISSED", "POSTPONED", "IMPLEMENTED"], ), time_status_end=dict(type="str"), action=dict(type="str", required=True, choices=["bulk_apply"]), ) ) module = AnsibleModule(argument_spec=module_args, supports_check_mode=True) if not HAS_OCI_PY_SDK: module.fail_json(msg="oci python sdk required for this module.") resource_helper = ResourceHelper( module=module, resource_type="recommendation", service_client_class=OptimizerClient, namespace="optimizer", ) result = resource_helper.perform_action(module.params.get("action")) module.exit_json(**result) if __name__ == "__main__": main()
plugins/modules/oci_optimizer_recommendation_actions.py
14,148
Supported actions: bulk_apply !/usr/bin/python Copyright (c) 2020, 2021 Oracle and/or its affiliates. This software is made available to you under the terms of the GPL 3.0 license or the Apache 2.0 license. GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) Apache License v2.0 See LICENSE.TXT for details. GENERATED FILE - DO NOT EDIT - MANUAL CHANGES WILL BE OVERWRITTEN
417
en
0.741496
#!/usr/bin/env python import os import sys if __name__ == "__main__": from django_secrets.startup import check check() os.environ['DJANGO_SETTINGS_MODULE'] = 'django_secrets.settings' try: from django.core.management import execute_from_command_line except ImportError: # The above import may fail for some other reason. Ensure that the # issue is really that Django is missing to avoid masking other # exceptions on Python 2. try: import django # noqa except ImportError: raise ImportError( "Couldn't import Django. Are you sure it's installed and " "available on your PYTHONPATH environment variable? Did you " "forget to activate a virtual environment?" ) raise execute_from_command_line(sys.argv)
manage.py
869
!/usr/bin/env python The above import may fail for some other reason. Ensure that the issue is really that Django is missing to avoid masking other exceptions on Python 2. noqa
176
en
0.862894
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Time : 2017/7/31 上午10:21 # @Author : Matrix # @Github : https://github.com/blackmatrix7/ # @Blog : http://www.cnblogs.com/blackmatrix/ # @File : __init__.py.py # @Software: PyCharm from .huawei import SMSCenter __author__ = 'blackmatrix' if __name__ == '__main__': pass
sms/__init__.py
329
!/usr/bin/env python -*- coding: utf-8 -*- @Time : 2017/7/31 上午10:21 @Author : Matrix @Github : https://github.com/blackmatrix7/ @Blog : http://www.cnblogs.com/blackmatrix/ @File : __init__.py.py @Software: PyCharm
214
zh
0.184227
# -*- coding: utf-8 -*- # this file is released under public domain and you can use without limitations ######################################################################### ## Customize your APP title, subtitle and menus here ######################################################################### response.logo = A('Javelin',_class="brand",_href="/") response.title = request.application.replace('_',' ').title() ## read more at http://dev.w3.org/html5/markup/meta.name.html response.meta.author = 'Your Name <you@example.com>' response.meta.description = 'a cool new app' response.meta.keywords = 'web2py, python, framework' response.meta.generator = 'Web2py Web Framework' ## your http://google.com/analytics id response.google_analytics_id = None ######################################################################### ## this is the main application menu add/remove items as required ######################################################################### response.menu = [ (T('Home'), False, URL('default', 'index'), []) ] DEVELOPMENT_MENU = True ######################################################################### ## provide shortcuts for development. remove in production ######################################################################### def _(): # shortcuts app = request.application ctr = request.controller # useful links to internal and external resources response.menu += [ (SPAN('web2py', _class='highlighted'), False, 'http://web2py.com', [ (T('My Sites'), False, URL('admin', 'default', 'site')), (T('This App'), False, URL('admin', 'default', 'design/%s' % app), [ (T('Controller'), False, URL( 'admin', 'default', 'edit/%s/controllers/%s.py' % (app, ctr))), (T('View'), False, URL( 'admin', 'default', 'edit/%s/views/%s' % (app, response.view))), (T('Layout'), False, URL( 'admin', 'default', 'edit/%s/views/layout.html' % app)), (T('Stylesheet'), False, URL( 'admin', 'default', 'edit/%s/static/css/web2py.css' % app)), (T('DB Model'), False, URL( 'admin', 'default', 'edit/%s/models/db.py' % app)), (T('Menu Model'), False, URL( 'admin', 'default', 'edit/%s/models/menu.py' % app)), (T('Database'), False, URL(app, 'appadmin', 'index')), (T('Errors'), False, URL( 'admin', 'default', 'errors/' + app)), (T('About'), False, URL( 'admin', 'default', 'about/' + app)), ]), ('web2py.com', False, 'http://www.web2py.com', [ (T('Download'), False, 'http://www.web2py.com/examples/default/download'), (T('Support'), False, 'http://www.web2py.com/examples/default/support'), (T('Demo'), False, 'http://web2py.com/demo_admin'), (T('Quick Examples'), False, 'http://web2py.com/examples/default/examples'), (T('FAQ'), False, 'http://web2py.com/AlterEgo'), (T('Videos'), False, 'http://www.web2py.com/examples/default/videos/'), (T('Free Applications'), False, 'http://web2py.com/appliances'), (T('Plugins'), False, 'http://web2py.com/plugins'), (T('Layouts'), False, 'http://web2py.com/layouts'), (T('Recipes'), False, 'http://web2pyslices.com/'), (T('Semantic'), False, 'http://web2py.com/semantic'), ]), (T('Documentation'), False, 'http://www.web2py.com/book', [ (T('Preface'), False, 'http://www.web2py.com/book/default/chapter/00'), (T('Introduction'), False, 'http://www.web2py.com/book/default/chapter/01'), (T('Python'), False, 'http://www.web2py.com/book/default/chapter/02'), (T('Overview'), False, 'http://www.web2py.com/book/default/chapter/03'), (T('The Core'), False, 'http://www.web2py.com/book/default/chapter/04'), (T('The Views'), False, 'http://www.web2py.com/book/default/chapter/05'), (T('Database'), False, 'http://www.web2py.com/book/default/chapter/06'), (T('Forms and Validators'), False, 'http://www.web2py.com/book/default/chapter/07'), (T('Email and SMS'), False, 'http://www.web2py.com/book/default/chapter/08'), (T('Access Control'), False, 'http://www.web2py.com/book/default/chapter/09'), (T('Services'), False, 'http://www.web2py.com/book/default/chapter/10'), (T('Ajax Recipes'), False, 'http://www.web2py.com/book/default/chapter/11'), (T('Components and Plugins'), False, 'http://www.web2py.com/book/default/chapter/12'), (T('Deployment Recipes'), False, 'http://www.web2py.com/book/default/chapter/13'), (T('Other Recipes'), False, 'http://www.web2py.com/book/default/chapter/14'), (T('Buy this book'), False, 'http://stores.lulu.com/web2py'), ]), (T('Community'), False, None, [ (T('Groups'), False, 'http://www.web2py.com/examples/default/usergroups'), (T('Twitter'), False, 'http://twitter.com/web2py'), (T('Live Chat'), False, 'http://webchat.freenode.net/?channels=web2py'), ]), (T('Plugins'), False, None, [ ('plugin_wiki', False, 'http://web2py.com/examples/default/download'), (T('Other Plugins'), False, 'http://web2py.com/plugins'), (T('Layout Plugins'), False, 'http://web2py.com/layouts'), ]) ] )] if DEVELOPMENT_MENU: _() if "auth" in locals(): auth.wikimenu()
applications/javelin/models/menu.py
6,153
-*- coding: utf-8 -*- this file is released under public domain and you can use without limitations Customize your APP title, subtitle and menus here read more at http://dev.w3.org/html5/markup/meta.name.html your http://google.com/analytics id this is the main application menu add/remove items as required provide shortcuts for development. remove in production shortcuts useful links to internal and external resources
421
en
0.779725
# -*- coding: utf-8 -*- # Generated by the protocol buffer compiler. DO NOT EDIT! # source: google/cloud/videointelligence_v1/proto/video_intelligence.proto """Generated protocol buffer code.""" from google.protobuf.internal import enum_type_wrapper from google.protobuf import descriptor as _descriptor from google.protobuf import message as _message from google.protobuf import reflection as _reflection from google.protobuf import symbol_database as _symbol_database # @@protoc_insertion_point(imports) _sym_db = _symbol_database.Default() from google.api import annotations_pb2 as google_dot_api_dot_annotations__pb2 from google.api import client_pb2 as google_dot_api_dot_client__pb2 from google.api import field_behavior_pb2 as google_dot_api_dot_field__behavior__pb2 from google.longrunning import ( operations_pb2 as google_dot_longrunning_dot_operations__pb2, ) from google.protobuf import duration_pb2 as google_dot_protobuf_dot_duration__pb2 from google.protobuf import timestamp_pb2 as google_dot_protobuf_dot_timestamp__pb2 from google.rpc import status_pb2 as google_dot_rpc_dot_status__pb2 DESCRIPTOR = _descriptor.FileDescriptor( name="google/cloud/videointelligence_v1/proto/video_intelligence.proto", package="google.cloud.videointelligence.v1", syntax="proto3", serialized_options=b"\n%com.google.cloud.videointelligence.v1B\035VideoIntelligenceServiceProtoP\001ZRgoogle.golang.org/genproto/googleapis/cloud/videointelligence/v1;videointelligence\252\002!Google.Cloud.VideoIntelligence.V1\312\002!Google\\Cloud\\VideoIntelligence\\V1\352\002$Google::Cloud::VideoIntelligence::V1", create_key=_descriptor._internal_create_key, serialized_pb=b'\n@google/cloud/videointelligence_v1/proto/video_intelligence.proto\x12!google.cloud.videointelligence.v1\x1a\x1cgoogle/api/annotations.proto\x1a\x17google/api/client.proto\x1a\x1fgoogle/api/field_behavior.proto\x1a#google/longrunning/operations.proto\x1a\x1egoogle/protobuf/duration.proto\x1a\x1fgoogle/protobuf/timestamp.proto\x1a\x17google/rpc/status.proto"\xfe\x01\n\x14\x41nnotateVideoRequest\x12\x11\n\tinput_uri\x18\x01 \x01(\t\x12\x15\n\rinput_content\x18\x06 \x01(\x0c\x12\x41\n\x08\x66\x65\x61tures\x18\x02 \x03(\x0e\x32*.google.cloud.videointelligence.v1.FeatureB\x03\xe0\x41\x02\x12\x46\n\rvideo_context\x18\x03 \x01(\x0b\x32/.google.cloud.videointelligence.v1.VideoContext\x12\x17\n\noutput_uri\x18\x04 \x01(\tB\x03\xe0\x41\x01\x12\x18\n\x0blocation_id\x18\x05 \x01(\tB\x03\xe0\x41\x01"\xc1\x06\n\x0cVideoContext\x12\x41\n\x08segments\x18\x01 \x03(\x0b\x32/.google.cloud.videointelligence.v1.VideoSegment\x12W\n\x16label_detection_config\x18\x02 \x01(\x0b\x32\x37.google.cloud.videointelligence.v1.LabelDetectionConfig\x12\x62\n\x1cshot_change_detection_config\x18\x03 \x01(\x0b\x32<.google.cloud.videointelligence.v1.ShotChangeDetectionConfig\x12l\n!explicit_content_detection_config\x18\x04 \x01(\x0b\x32\x41.google.cloud.videointelligence.v1.ExplicitContentDetectionConfig\x12U\n\x15\x66\x61\x63\x65_detection_config\x18\x05 \x01(\x0b\x32\x36.google.cloud.videointelligence.v1.FaceDetectionConfig\x12\x61\n\x1bspeech_transcription_config\x18\x06 \x01(\x0b\x32<.google.cloud.videointelligence.v1.SpeechTranscriptionConfig\x12U\n\x15text_detection_config\x18\x08 \x01(\x0b\x32\x36.google.cloud.videointelligence.v1.TextDetectionConfig\x12Y\n\x17person_detection_config\x18\x0b \x01(\x0b\x32\x38.google.cloud.videointelligence.v1.PersonDetectionConfig\x12W\n\x16object_tracking_config\x18\r \x01(\x0b\x32\x37.google.cloud.videointelligence.v1.ObjectTrackingConfig"\xdd\x01\n\x14LabelDetectionConfig\x12S\n\x14label_detection_mode\x18\x01 \x01(\x0e\x32\x35.google.cloud.videointelligence.v1.LabelDetectionMode\x12\x19\n\x11stationary_camera\x18\x02 \x01(\x08\x12\r\n\x05model\x18\x03 \x01(\t\x12"\n\x1a\x66rame_confidence_threshold\x18\x04 \x01(\x02\x12"\n\x1avideo_confidence_threshold\x18\x05 \x01(\x02"*\n\x19ShotChangeDetectionConfig\x12\r\n\x05model\x18\x01 \x01(\t"%\n\x14ObjectTrackingConfig\x12\r\n\x05model\x18\x01 \x01(\t"`\n\x13\x46\x61\x63\x65\x44\x65tectionConfig\x12\r\n\x05model\x18\x01 \x01(\t\x12\x1e\n\x16include_bounding_boxes\x18\x02 \x01(\x08\x12\x1a\n\x12include_attributes\x18\x05 \x01(\x08"s\n\x15PersonDetectionConfig\x12\x1e\n\x16include_bounding_boxes\x18\x01 \x01(\x08\x12\x1e\n\x16include_pose_landmarks\x18\x02 \x01(\x08\x12\x1a\n\x12include_attributes\x18\x03 \x01(\x08"/\n\x1e\x45xplicitContentDetectionConfig\x12\r\n\x05model\x18\x01 \x01(\t"<\n\x13TextDetectionConfig\x12\x16\n\x0elanguage_hints\x18\x01 \x03(\t\x12\r\n\x05model\x18\x02 \x01(\t"x\n\x0cVideoSegment\x12\x34\n\x11start_time_offset\x18\x01 \x01(\x0b\x32\x19.google.protobuf.Duration\x12\x32\n\x0f\x65nd_time_offset\x18\x02 \x01(\x0b\x32\x19.google.protobuf.Duration"d\n\x0cLabelSegment\x12@\n\x07segment\x18\x01 \x01(\x0b\x32/.google.cloud.videointelligence.v1.VideoSegment\x12\x12\n\nconfidence\x18\x02 \x01(\x02"P\n\nLabelFrame\x12.\n\x0btime_offset\x18\x01 \x01(\x0b\x32\x19.google.protobuf.Duration\x12\x12\n\nconfidence\x18\x02 \x01(\x02"G\n\x06\x45ntity\x12\x11\n\tentity_id\x18\x01 \x01(\t\x12\x13\n\x0b\x64\x65scription\x18\x02 \x01(\t\x12\x15\n\rlanguage_code\x18\x03 \x01(\t"\xa5\x02\n\x0fLabelAnnotation\x12\x39\n\x06\x65ntity\x18\x01 \x01(\x0b\x32).google.cloud.videointelligence.v1.Entity\x12\x44\n\x11\x63\x61tegory_entities\x18\x02 \x03(\x0b\x32).google.cloud.videointelligence.v1.Entity\x12\x41\n\x08segments\x18\x03 \x03(\x0b\x32/.google.cloud.videointelligence.v1.LabelSegment\x12=\n\x06\x66rames\x18\x04 \x03(\x0b\x32-.google.cloud.videointelligence.v1.LabelFrame\x12\x0f\n\x07version\x18\x05 \x01(\t"\x95\x01\n\x14\x45xplicitContentFrame\x12.\n\x0btime_offset\x18\x01 \x01(\x0b\x32\x19.google.protobuf.Duration\x12M\n\x16pornography_likelihood\x18\x02 \x01(\x0e\x32-.google.cloud.videointelligence.v1.Likelihood"u\n\x19\x45xplicitContentAnnotation\x12G\n\x06\x66rames\x18\x01 \x03(\x0b\x32\x37.google.cloud.videointelligence.v1.ExplicitContentFrame\x12\x0f\n\x07version\x18\x02 \x01(\t"Q\n\x15NormalizedBoundingBox\x12\x0c\n\x04left\x18\x01 \x01(\x02\x12\x0b\n\x03top\x18\x02 \x01(\x02\x12\r\n\x05right\x18\x03 \x01(\x02\x12\x0e\n\x06\x62ottom\x18\x04 \x01(\x02"*\n\x17\x46\x61\x63\x65\x44\x65tectionAnnotation\x12\x0f\n\x07version\x18\x05 \x01(\t"f\n\x19PersonDetectionAnnotation\x12\x38\n\x06tracks\x18\x01 \x03(\x0b\x32(.google.cloud.videointelligence.v1.Track\x12\x0f\n\x07version\x18\x02 \x01(\t"O\n\x0b\x46\x61\x63\x65Segment\x12@\n\x07segment\x18\x01 \x01(\x0b\x32/.google.cloud.videointelligence.v1.VideoSegment"\x9c\x01\n\tFaceFrame\x12[\n\x19normalized_bounding_boxes\x18\x01 \x03(\x0b\x32\x38.google.cloud.videointelligence.v1.NormalizedBoundingBox\x12.\n\x0btime_offset\x18\x02 \x01(\x0b\x32\x19.google.protobuf.Duration:\x02\x18\x01"\xa7\x01\n\x0e\x46\x61\x63\x65\x41nnotation\x12\x11\n\tthumbnail\x18\x01 \x01(\x0c\x12@\n\x08segments\x18\x02 \x03(\x0b\x32..google.cloud.videointelligence.v1.FaceSegment\x12<\n\x06\x66rames\x18\x03 \x03(\x0b\x32,.google.cloud.videointelligence.v1.FaceFrame:\x02\x18\x01"\xba\x02\n\x11TimestampedObject\x12Y\n\x17normalized_bounding_box\x18\x01 \x01(\x0b\x32\x38.google.cloud.videointelligence.v1.NormalizedBoundingBox\x12.\n\x0btime_offset\x18\x02 \x01(\x0b\x32\x19.google.protobuf.Duration\x12M\n\nattributes\x18\x03 \x03(\x0b\x32\x34.google.cloud.videointelligence.v1.DetectedAttributeB\x03\xe0\x41\x01\x12K\n\tlandmarks\x18\x04 \x03(\x0b\x32\x33.google.cloud.videointelligence.v1.DetectedLandmarkB\x03\xe0\x41\x01"\x84\x02\n\x05Track\x12@\n\x07segment\x18\x01 \x01(\x0b\x32/.google.cloud.videointelligence.v1.VideoSegment\x12Q\n\x13timestamped_objects\x18\x02 \x03(\x0b\x32\x34.google.cloud.videointelligence.v1.TimestampedObject\x12M\n\nattributes\x18\x03 \x03(\x0b\x32\x34.google.cloud.videointelligence.v1.DetectedAttributeB\x03\xe0\x41\x01\x12\x17\n\nconfidence\x18\x04 \x01(\x02\x42\x03\xe0\x41\x01"D\n\x11\x44\x65tectedAttribute\x12\x0c\n\x04name\x18\x01 \x01(\t\x12\x12\n\nconfidence\x18\x02 \x01(\x02\x12\r\n\x05value\x18\x03 \x01(\t"x\n\x10\x44\x65tectedLandmark\x12\x0c\n\x04name\x18\x01 \x01(\t\x12\x42\n\x05point\x18\x02 \x01(\x0b\x32\x33.google.cloud.videointelligence.v1.NormalizedVertex\x12\x12\n\nconfidence\x18\x03 \x01(\x02"\xe9\n\n\x16VideoAnnotationResults\x12\x11\n\tinput_uri\x18\x01 \x01(\t\x12@\n\x07segment\x18\n \x01(\x0b\x32/.google.cloud.videointelligence.v1.VideoSegment\x12U\n\x19segment_label_annotations\x18\x02 \x03(\x0b\x32\x32.google.cloud.videointelligence.v1.LabelAnnotation\x12^\n"segment_presence_label_annotations\x18\x17 \x03(\x0b\x32\x32.google.cloud.videointelligence.v1.LabelAnnotation\x12R\n\x16shot_label_annotations\x18\x03 \x03(\x0b\x32\x32.google.cloud.videointelligence.v1.LabelAnnotation\x12[\n\x1fshot_presence_label_annotations\x18\x18 \x03(\x0b\x32\x32.google.cloud.videointelligence.v1.LabelAnnotation\x12S\n\x17\x66rame_label_annotations\x18\x04 \x03(\x0b\x32\x32.google.cloud.videointelligence.v1.LabelAnnotation\x12O\n\x10\x66\x61\x63\x65_annotations\x18\x05 \x03(\x0b\x32\x31.google.cloud.videointelligence.v1.FaceAnnotationB\x02\x18\x01\x12^\n\x1a\x66\x61\x63\x65_detection_annotations\x18\r \x03(\x0b\x32:.google.cloud.videointelligence.v1.FaceDetectionAnnotation\x12I\n\x10shot_annotations\x18\x06 \x03(\x0b\x32/.google.cloud.videointelligence.v1.VideoSegment\x12Y\n\x13\x65xplicit_annotation\x18\x07 \x01(\x0b\x32<.google.cloud.videointelligence.v1.ExplicitContentAnnotation\x12U\n\x15speech_transcriptions\x18\x0b \x03(\x0b\x32\x36.google.cloud.videointelligence.v1.SpeechTranscription\x12K\n\x10text_annotations\x18\x0c \x03(\x0b\x32\x31.google.cloud.videointelligence.v1.TextAnnotation\x12W\n\x12object_annotations\x18\x0e \x03(\x0b\x32;.google.cloud.videointelligence.v1.ObjectTrackingAnnotation\x12\x62\n\x1clogo_recognition_annotations\x18\x13 \x03(\x0b\x32<.google.cloud.videointelligence.v1.LogoRecognitionAnnotation\x12\x62\n\x1cperson_detection_annotations\x18\x14 \x03(\x0b\x32<.google.cloud.videointelligence.v1.PersonDetectionAnnotation\x12!\n\x05\x65rror\x18\t \x01(\x0b\x32\x12.google.rpc.Status"n\n\x15\x41nnotateVideoResponse\x12U\n\x12\x61nnotation_results\x18\x01 \x03(\x0b\x32\x39.google.cloud.videointelligence.v1.VideoAnnotationResults"\xa6\x02\n\x17VideoAnnotationProgress\x12\x11\n\tinput_uri\x18\x01 \x01(\t\x12\x18\n\x10progress_percent\x18\x02 \x01(\x05\x12.\n\nstart_time\x18\x03 \x01(\x0b\x32\x1a.google.protobuf.Timestamp\x12/\n\x0bupdate_time\x18\x04 \x01(\x0b\x32\x1a.google.protobuf.Timestamp\x12;\n\x07\x66\x65\x61ture\x18\x05 \x01(\x0e\x32*.google.cloud.videointelligence.v1.Feature\x12@\n\x07segment\x18\x06 \x01(\x0b\x32/.google.cloud.videointelligence.v1.VideoSegment"p\n\x15\x41nnotateVideoProgress\x12W\n\x13\x61nnotation_progress\x18\x01 \x03(\x0b\x32:.google.cloud.videointelligence.v1.VideoAnnotationProgress"\x81\x03\n\x19SpeechTranscriptionConfig\x12\x1a\n\rlanguage_code\x18\x01 \x01(\tB\x03\xe0\x41\x02\x12\x1d\n\x10max_alternatives\x18\x02 \x01(\x05\x42\x03\xe0\x41\x01\x12\x1d\n\x10\x66ilter_profanity\x18\x03 \x01(\x08\x42\x03\xe0\x41\x01\x12N\n\x0fspeech_contexts\x18\x04 \x03(\x0b\x32\x30.google.cloud.videointelligence.v1.SpeechContextB\x03\xe0\x41\x01\x12)\n\x1c\x65nable_automatic_punctuation\x18\x05 \x01(\x08\x42\x03\xe0\x41\x01\x12\x19\n\x0c\x61udio_tracks\x18\x06 \x03(\x05\x42\x03\xe0\x41\x01\x12\'\n\x1a\x65nable_speaker_diarization\x18\x07 \x01(\x08\x42\x03\xe0\x41\x01\x12&\n\x19\x64iarization_speaker_count\x18\x08 \x01(\x05\x42\x03\xe0\x41\x01\x12#\n\x16\x65nable_word_confidence\x18\t \x01(\x08\x42\x03\xe0\x41\x01"%\n\rSpeechContext\x12\x14\n\x07phrases\x18\x01 \x03(\tB\x03\xe0\x41\x01"\x88\x01\n\x13SpeechTranscription\x12U\n\x0c\x61lternatives\x18\x01 \x03(\x0b\x32?.google.cloud.videointelligence.v1.SpeechRecognitionAlternative\x12\x1a\n\rlanguage_code\x18\x02 \x01(\tB\x03\xe0\x41\x03"\x8c\x01\n\x1cSpeechRecognitionAlternative\x12\x12\n\ntranscript\x18\x01 \x01(\t\x12\x17\n\nconfidence\x18\x02 \x01(\x02\x42\x03\xe0\x41\x03\x12?\n\x05words\x18\x03 \x03(\x0b\x32+.google.cloud.videointelligence.v1.WordInfoB\x03\xe0\x41\x03"\xa7\x01\n\x08WordInfo\x12-\n\nstart_time\x18\x01 \x01(\x0b\x32\x19.google.protobuf.Duration\x12+\n\x08\x65nd_time\x18\x02 \x01(\x0b\x32\x19.google.protobuf.Duration\x12\x0c\n\x04word\x18\x03 \x01(\t\x12\x17\n\nconfidence\x18\x04 \x01(\x02\x42\x03\xe0\x41\x03\x12\x18\n\x0bspeaker_tag\x18\x05 \x01(\x05\x42\x03\xe0\x41\x03"(\n\x10NormalizedVertex\x12\t\n\x01x\x18\x01 \x01(\x02\x12\t\n\x01y\x18\x02 \x01(\x02"_\n\x16NormalizedBoundingPoly\x12\x45\n\x08vertices\x18\x01 \x03(\x0b\x32\x33.google.cloud.videointelligence.v1.NormalizedVertex"\xa1\x01\n\x0bTextSegment\x12@\n\x07segment\x18\x01 \x01(\x0b\x32/.google.cloud.videointelligence.v1.VideoSegment\x12\x12\n\nconfidence\x18\x02 \x01(\x02\x12<\n\x06\x66rames\x18\x03 \x03(\x0b\x32,.google.cloud.videointelligence.v1.TextFrame"\x94\x01\n\tTextFrame\x12W\n\x14rotated_bounding_box\x18\x01 \x01(\x0b\x32\x39.google.cloud.videointelligence.v1.NormalizedBoundingPoly\x12.\n\x0btime_offset\x18\x02 \x01(\x0b\x32\x19.google.protobuf.Duration"q\n\x0eTextAnnotation\x12\x0c\n\x04text\x18\x01 \x01(\t\x12@\n\x08segments\x18\x02 \x03(\x0b\x32..google.cloud.videointelligence.v1.TextSegment\x12\x0f\n\x07version\x18\x03 \x01(\t"\xa0\x01\n\x13ObjectTrackingFrame\x12Y\n\x17normalized_bounding_box\x18\x01 \x01(\x0b\x32\x38.google.cloud.videointelligence.v1.NormalizedBoundingBox\x12.\n\x0btime_offset\x18\x02 \x01(\x0b\x32\x19.google.protobuf.Duration"\xa8\x02\n\x18ObjectTrackingAnnotation\x12\x42\n\x07segment\x18\x03 \x01(\x0b\x32/.google.cloud.videointelligence.v1.VideoSegmentH\x00\x12\x12\n\x08track_id\x18\x05 \x01(\x03H\x00\x12\x39\n\x06\x65ntity\x18\x01 \x01(\x0b\x32).google.cloud.videointelligence.v1.Entity\x12\x12\n\nconfidence\x18\x04 \x01(\x02\x12\x46\n\x06\x66rames\x18\x02 \x03(\x0b\x32\x36.google.cloud.videointelligence.v1.ObjectTrackingFrame\x12\x0f\n\x07version\x18\x06 \x01(\tB\x0c\n\ntrack_info"\xd3\x01\n\x19LogoRecognitionAnnotation\x12\x39\n\x06\x65ntity\x18\x01 \x01(\x0b\x32).google.cloud.videointelligence.v1.Entity\x12\x38\n\x06tracks\x18\x02 \x03(\x0b\x32(.google.cloud.videointelligence.v1.Track\x12\x41\n\x08segments\x18\x03 \x03(\x0b\x32/.google.cloud.videointelligence.v1.VideoSegment*\xf5\x01\n\x07\x46\x65\x61ture\x12\x17\n\x13\x46\x45\x41TURE_UNSPECIFIED\x10\x00\x12\x13\n\x0fLABEL_DETECTION\x10\x01\x12\x19\n\x15SHOT_CHANGE_DETECTION\x10\x02\x12\x1e\n\x1a\x45XPLICIT_CONTENT_DETECTION\x10\x03\x12\x12\n\x0e\x46\x41\x43\x45_DETECTION\x10\x04\x12\x18\n\x14SPEECH_TRANSCRIPTION\x10\x06\x12\x12\n\x0eTEXT_DETECTION\x10\x07\x12\x13\n\x0fOBJECT_TRACKING\x10\t\x12\x14\n\x10LOGO_RECOGNITION\x10\x0c\x12\x14\n\x10PERSON_DETECTION\x10\x0e*r\n\x12LabelDetectionMode\x12$\n LABEL_DETECTION_MODE_UNSPECIFIED\x10\x00\x12\r\n\tSHOT_MODE\x10\x01\x12\x0e\n\nFRAME_MODE\x10\x02\x12\x17\n\x13SHOT_AND_FRAME_MODE\x10\x03*t\n\nLikelihood\x12\x1a\n\x16LIKELIHOOD_UNSPECIFIED\x10\x00\x12\x11\n\rVERY_UNLIKELY\x10\x01\x12\x0c\n\x08UNLIKELY\x10\x02\x12\x0c\n\x08POSSIBLE\x10\x03\x12\n\n\x06LIKELY\x10\x04\x12\x0f\n\x0bVERY_LIKELY\x10\x05\x32\xc0\x02\n\x18VideoIntelligenceService\x12\xcd\x01\n\rAnnotateVideo\x12\x37.google.cloud.videointelligence.v1.AnnotateVideoRequest\x1a\x1d.google.longrunning.Operation"d\x82\xd3\xe4\x93\x02\x18"\x13/v1/videos:annotate:\x01*\xda\x41\x12input_uri,features\xca\x41.\n\x15\x41nnotateVideoResponse\x12\x15\x41nnotateVideoProgress\x1aT\xca\x41 videointelligence.googleapis.com\xd2\x41.https://www.googleapis.com/auth/cloud-platformB\x8b\x02\n%com.google.cloud.videointelligence.v1B\x1dVideoIntelligenceServiceProtoP\x01ZRgoogle.golang.org/genproto/googleapis/cloud/videointelligence/v1;videointelligence\xaa\x02!Google.Cloud.VideoIntelligence.V1\xca\x02!Google\\Cloud\\VideoIntelligence\\V1\xea\x02$Google::Cloud::VideoIntelligence::V1b\x06proto3', dependencies=[ google_dot_api_dot_annotations__pb2.DESCRIPTOR, google_dot_api_dot_client__pb2.DESCRIPTOR, google_dot_api_dot_field__behavior__pb2.DESCRIPTOR, google_dot_longrunning_dot_operations__pb2.DESCRIPTOR, google_dot_protobuf_dot_duration__pb2.DESCRIPTOR, google_dot_protobuf_dot_timestamp__pb2.DESCRIPTOR, google_dot_rpc_dot_status__pb2.DESCRIPTOR, ], ) _FEATURE = _descriptor.EnumDescriptor( name="Feature", full_name="google.cloud.videointelligence.v1.Feature", filename=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key, values=[ _descriptor.EnumValueDescriptor( name="FEATURE_UNSPECIFIED", index=0, number=0, serialized_options=None, type=None, create_key=_descriptor._internal_create_key, ), _descriptor.EnumValueDescriptor( name="LABEL_DETECTION", index=1, number=1, serialized_options=None, type=None, create_key=_descriptor._internal_create_key, ), _descriptor.EnumValueDescriptor( name="SHOT_CHANGE_DETECTION", index=2, number=2, serialized_options=None, type=None, create_key=_descriptor._internal_create_key, ), _descriptor.EnumValueDescriptor( name="EXPLICIT_CONTENT_DETECTION", index=3, number=3, serialized_options=None, type=None, create_key=_descriptor._internal_create_key, ), _descriptor.EnumValueDescriptor( name="FACE_DETECTION", index=4, number=4, serialized_options=None, type=None, create_key=_descriptor._internal_create_key, ), _descriptor.EnumValueDescriptor( name="SPEECH_TRANSCRIPTION", index=5, number=6, serialized_options=None, type=None, create_key=_descriptor._internal_create_key, ), _descriptor.EnumValueDescriptor( name="TEXT_DETECTION", index=6, number=7, serialized_options=None, type=None, create_key=_descriptor._internal_create_key, ), _descriptor.EnumValueDescriptor( name="OBJECT_TRACKING", index=7, number=9, serialized_options=None, type=None, create_key=_descriptor._internal_create_key, ), _descriptor.EnumValueDescriptor( name="LOGO_RECOGNITION", index=8, number=12, serialized_options=None, type=None, create_key=_descriptor._internal_create_key, ), _descriptor.EnumValueDescriptor( name="PERSON_DETECTION", index=9, number=14, serialized_options=None, type=None, create_key=_descriptor._internal_create_key, ), ], containing_type=None, serialized_options=None, serialized_start=8439, serialized_end=8684, ) _sym_db.RegisterEnumDescriptor(_FEATURE) Feature = enum_type_wrapper.EnumTypeWrapper(_FEATURE) _LABELDETECTIONMODE = _descriptor.EnumDescriptor( name="LabelDetectionMode", full_name="google.cloud.videointelligence.v1.LabelDetectionMode", filename=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key, values=[ _descriptor.EnumValueDescriptor( name="LABEL_DETECTION_MODE_UNSPECIFIED", index=0, number=0, serialized_options=None, type=None, create_key=_descriptor._internal_create_key, ), _descriptor.EnumValueDescriptor( name="SHOT_MODE", index=1, number=1, serialized_options=None, type=None, create_key=_descriptor._internal_create_key, ), _descriptor.EnumValueDescriptor( name="FRAME_MODE", index=2, number=2, serialized_options=None, type=None, create_key=_descriptor._internal_create_key, ), _descriptor.EnumValueDescriptor( name="SHOT_AND_FRAME_MODE", index=3, number=3, serialized_options=None, type=None, create_key=_descriptor._internal_create_key, ), ], containing_type=None, serialized_options=None, serialized_start=8686, serialized_end=8800, ) _sym_db.RegisterEnumDescriptor(_LABELDETECTIONMODE) LabelDetectionMode = enum_type_wrapper.EnumTypeWrapper(_LABELDETECTIONMODE) _LIKELIHOOD = _descriptor.EnumDescriptor( name="Likelihood", full_name="google.cloud.videointelligence.v1.Likelihood", filename=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key, values=[ _descriptor.EnumValueDescriptor( name="LIKELIHOOD_UNSPECIFIED", index=0, number=0, serialized_options=None, type=None, create_key=_descriptor._internal_create_key, ), _descriptor.EnumValueDescriptor( name="VERY_UNLIKELY", index=1, number=1, serialized_options=None, type=None, create_key=_descriptor._internal_create_key, ), _descriptor.EnumValueDescriptor( name="UNLIKELY", index=2, number=2, serialized_options=None, type=None, create_key=_descriptor._internal_create_key, ), _descriptor.EnumValueDescriptor( name="POSSIBLE", index=3, number=3, serialized_options=None, type=None, create_key=_descriptor._internal_create_key, ), _descriptor.EnumValueDescriptor( name="LIKELY", index=4, number=4, serialized_options=None, type=None, create_key=_descriptor._internal_create_key, ), _descriptor.EnumValueDescriptor( name="VERY_LIKELY", index=5, number=5, serialized_options=None, type=None, create_key=_descriptor._internal_create_key, ), ], containing_type=None, serialized_options=None, serialized_start=8802, serialized_end=8918, ) _sym_db.RegisterEnumDescriptor(_LIKELIHOOD) Likelihood = enum_type_wrapper.EnumTypeWrapper(_LIKELIHOOD) FEATURE_UNSPECIFIED = 0 LABEL_DETECTION = 1 SHOT_CHANGE_DETECTION = 2 EXPLICIT_CONTENT_DETECTION = 3 FACE_DETECTION = 4 SPEECH_TRANSCRIPTION = 6 TEXT_DETECTION = 7 OBJECT_TRACKING = 9 LOGO_RECOGNITION = 12 PERSON_DETECTION = 14 LABEL_DETECTION_MODE_UNSPECIFIED = 0 SHOT_MODE = 1 FRAME_MODE = 2 SHOT_AND_FRAME_MODE = 3 LIKELIHOOD_UNSPECIFIED = 0 VERY_UNLIKELY = 1 UNLIKELY = 2 POSSIBLE = 3 LIKELY = 4 VERY_LIKELY = 5 _ANNOTATEVIDEOREQUEST = _descriptor.Descriptor( name="AnnotateVideoRequest", full_name="google.cloud.videointelligence.v1.AnnotateVideoRequest", filename=None, file=DESCRIPTOR, containing_type=None, create_key=_descriptor._internal_create_key, fields=[ _descriptor.FieldDescriptor( name="input_uri", full_name="google.cloud.videointelligence.v1.AnnotateVideoRequest.input_uri", index=0, number=1, type=9, cpp_type=9, label=1, has_default_value=False, default_value=b"".decode("utf-8"), message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key, ), _descriptor.FieldDescriptor( name="input_content", full_name="google.cloud.videointelligence.v1.AnnotateVideoRequest.input_content", index=1, number=6, type=12, cpp_type=9, label=1, has_default_value=False, default_value=b"", message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key, ), _descriptor.FieldDescriptor( name="features", full_name="google.cloud.videointelligence.v1.AnnotateVideoRequest.features", index=2, number=2, type=14, cpp_type=8, label=3, has_default_value=False, default_value=[], message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=b"\340A\002", file=DESCRIPTOR, create_key=_descriptor._internal_create_key, ), _descriptor.FieldDescriptor( name="video_context", full_name="google.cloud.videointelligence.v1.AnnotateVideoRequest.video_context", index=3, number=3, type=11, cpp_type=10, label=1, has_default_value=False, default_value=None, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key, ), _descriptor.FieldDescriptor( name="output_uri", full_name="google.cloud.videointelligence.v1.AnnotateVideoRequest.output_uri", index=4, number=4, type=9, cpp_type=9, label=1, has_default_value=False, default_value=b"".decode("utf-8"), message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=b"\340A\001", file=DESCRIPTOR, create_key=_descriptor._internal_create_key, ), _descriptor.FieldDescriptor( name="location_id", full_name="google.cloud.videointelligence.v1.AnnotateVideoRequest.location_id", index=5, number=5, type=9, cpp_type=9, label=1, has_default_value=False, default_value=b"".decode("utf-8"), message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=b"\340A\001", file=DESCRIPTOR, create_key=_descriptor._internal_create_key, ), ], extensions=[], nested_types=[], enum_types=[], serialized_options=None, is_extendable=False, syntax="proto3", extension_ranges=[], oneofs=[], serialized_start=319, serialized_end=573, ) _VIDEOCONTEXT = _descriptor.Descriptor( name="VideoContext", full_name="google.cloud.videointelligence.v1.VideoContext", filename=None, file=DESCRIPTOR, containing_type=None, create_key=_descriptor._internal_create_key, fields=[ _descriptor.FieldDescriptor( name="segments", full_name="google.cloud.videointelligence.v1.VideoContext.segments", index=0, number=1, type=11, cpp_type=10, label=3, has_default_value=False, default_value=[], message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key, ), _descriptor.FieldDescriptor( name="label_detection_config", full_name="google.cloud.videointelligence.v1.VideoContext.label_detection_config", index=1, number=2, type=11, cpp_type=10, label=1, has_default_value=False, default_value=None, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key, ), _descriptor.FieldDescriptor( name="shot_change_detection_config", full_name="google.cloud.videointelligence.v1.VideoContext.shot_change_detection_config", index=2, number=3, type=11, cpp_type=10, label=1, has_default_value=False, default_value=None, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key, ), _descriptor.FieldDescriptor( name="explicit_content_detection_config", full_name="google.cloud.videointelligence.v1.VideoContext.explicit_content_detection_config", index=3, number=4, type=11, cpp_type=10, label=1, has_default_value=False, default_value=None, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key, ), _descriptor.FieldDescriptor( name="face_detection_config", full_name="google.cloud.videointelligence.v1.VideoContext.face_detection_config", index=4, number=5, type=11, cpp_type=10, label=1, has_default_value=False, default_value=None, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key, ), _descriptor.FieldDescriptor( name="speech_transcription_config", full_name="google.cloud.videointelligence.v1.VideoContext.speech_transcription_config", index=5, number=6, type=11, cpp_type=10, label=1, has_default_value=False, default_value=None, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key, ), _descriptor.FieldDescriptor( name="text_detection_config", full_name="google.cloud.videointelligence.v1.VideoContext.text_detection_config", index=6, number=8, type=11, cpp_type=10, label=1, has_default_value=False, default_value=None, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key, ), _descriptor.FieldDescriptor( name="person_detection_config", full_name="google.cloud.videointelligence.v1.VideoContext.person_detection_config", index=7, number=11, type=11, cpp_type=10, label=1, has_default_value=False, default_value=None, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key, ), _descriptor.FieldDescriptor( name="object_tracking_config", full_name="google.cloud.videointelligence.v1.VideoContext.object_tracking_config", index=8, number=13, type=11, cpp_type=10, label=1, has_default_value=False, default_value=None, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key, ), ], extensions=[], nested_types=[], enum_types=[], serialized_options=None, is_extendable=False, syntax="proto3", extension_ranges=[], oneofs=[], serialized_start=576, serialized_end=1409, ) _LABELDETECTIONCONFIG = _descriptor.Descriptor( name="LabelDetectionConfig", full_name="google.cloud.videointelligence.v1.LabelDetectionConfig", filename=None, file=DESCRIPTOR, containing_type=None, create_key=_descriptor._internal_create_key, fields=[ _descriptor.FieldDescriptor( name="label_detection_mode", full_name="google.cloud.videointelligence.v1.LabelDetectionConfig.label_detection_mode", index=0, number=1, type=14, cpp_type=8, label=1, has_default_value=False, default_value=0, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key, ), _descriptor.FieldDescriptor( name="stationary_camera", full_name="google.cloud.videointelligence.v1.LabelDetectionConfig.stationary_camera", index=1, number=2, type=8, cpp_type=7, label=1, has_default_value=False, default_value=False, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key, ), _descriptor.FieldDescriptor( name="model", full_name="google.cloud.videointelligence.v1.LabelDetectionConfig.model", index=2, number=3, type=9, cpp_type=9, label=1, has_default_value=False, default_value=b"".decode("utf-8"), message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key, ), _descriptor.FieldDescriptor( name="frame_confidence_threshold", full_name="google.cloud.videointelligence.v1.LabelDetectionConfig.frame_confidence_threshold", index=3, number=4, type=2, cpp_type=6, label=1, has_default_value=False, default_value=float(0), message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key, ), _descriptor.FieldDescriptor( name="video_confidence_threshold", full_name="google.cloud.videointelligence.v1.LabelDetectionConfig.video_confidence_threshold", index=4, number=5, type=2, cpp_type=6, label=1, has_default_value=False, default_value=float(0), message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key, ), ], extensions=[], nested_types=[], enum_types=[], serialized_options=None, is_extendable=False, syntax="proto3", extension_ranges=[], oneofs=[], serialized_start=1412, serialized_end=1633, ) _SHOTCHANGEDETECTIONCONFIG = _descriptor.Descriptor( name="ShotChangeDetectionConfig", full_name="google.cloud.videointelligence.v1.ShotChangeDetectionConfig", filename=None, file=DESCRIPTOR, containing_type=None, create_key=_descriptor._internal_create_key, fields=[ _descriptor.FieldDescriptor( name="model", full_name="google.cloud.videointelligence.v1.ShotChangeDetectionConfig.model", index=0, number=1, type=9, cpp_type=9, label=1, has_default_value=False, default_value=b"".decode("utf-8"), message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key, ), ], extensions=[], nested_types=[], enum_types=[], serialized_options=None, is_extendable=False, syntax="proto3", extension_ranges=[], oneofs=[], serialized_start=1635, serialized_end=1677, ) _OBJECTTRACKINGCONFIG = _descriptor.Descriptor( name="ObjectTrackingConfig", full_name="google.cloud.videointelligence.v1.ObjectTrackingConfig", filename=None, file=DESCRIPTOR, containing_type=None, create_key=_descriptor._internal_create_key, fields=[ _descriptor.FieldDescriptor( name="model", full_name="google.cloud.videointelligence.v1.ObjectTrackingConfig.model", index=0, number=1, type=9, cpp_type=9, label=1, has_default_value=False, default_value=b"".decode("utf-8"), message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key, ), ], extensions=[], nested_types=[], enum_types=[], serialized_options=None, is_extendable=False, syntax="proto3", extension_ranges=[], oneofs=[], serialized_start=1679, serialized_end=1716, ) _FACEDETECTIONCONFIG = _descriptor.Descriptor( name="FaceDetectionConfig", full_name="google.cloud.videointelligence.v1.FaceDetectionConfig", filename=None, file=DESCRIPTOR, containing_type=None, create_key=_descriptor._internal_create_key, fields=[ _descriptor.FieldDescriptor( name="model", full_name="google.cloud.videointelligence.v1.FaceDetectionConfig.model", index=0, number=1, type=9, cpp_type=9, label=1, has_default_value=False, default_value=b"".decode("utf-8"), message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key, ), _descriptor.FieldDescriptor( name="include_bounding_boxes", full_name="google.cloud.videointelligence.v1.FaceDetectionConfig.include_bounding_boxes", index=1, number=2, type=8, cpp_type=7, label=1, has_default_value=False, default_value=False, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key, ), _descriptor.FieldDescriptor( name="include_attributes", full_name="google.cloud.videointelligence.v1.FaceDetectionConfig.include_attributes", index=2, number=5, type=8, cpp_type=7, label=1, has_default_value=False, default_value=False, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key, ), ], extensions=[], nested_types=[], enum_types=[], serialized_options=None, is_extendable=False, syntax="proto3", extension_ranges=[], oneofs=[], serialized_start=1718, serialized_end=1814, ) _PERSONDETECTIONCONFIG = _descriptor.Descriptor( name="PersonDetectionConfig", full_name="google.cloud.videointelligence.v1.PersonDetectionConfig", filename=None, file=DESCRIPTOR, containing_type=None, create_key=_descriptor._internal_create_key, fields=[ _descriptor.FieldDescriptor( name="include_bounding_boxes", full_name="google.cloud.videointelligence.v1.PersonDetectionConfig.include_bounding_boxes", index=0, number=1, type=8, cpp_type=7, label=1, has_default_value=False, default_value=False, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key, ), _descriptor.FieldDescriptor( name="include_pose_landmarks", full_name="google.cloud.videointelligence.v1.PersonDetectionConfig.include_pose_landmarks", index=1, number=2, type=8, cpp_type=7, label=1, has_default_value=False, default_value=False, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key, ), _descriptor.FieldDescriptor( name="include_attributes", full_name="google.cloud.videointelligence.v1.PersonDetectionConfig.include_attributes", index=2, number=3, type=8, cpp_type=7, label=1, has_default_value=False, default_value=False, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key, ), ], extensions=[], nested_types=[], enum_types=[], serialized_options=None, is_extendable=False, syntax="proto3", extension_ranges=[], oneofs=[], serialized_start=1816, serialized_end=1931, ) _EXPLICITCONTENTDETECTIONCONFIG = _descriptor.Descriptor( name="ExplicitContentDetectionConfig", full_name="google.cloud.videointelligence.v1.ExplicitContentDetectionConfig", filename=None, file=DESCRIPTOR, containing_type=None, create_key=_descriptor._internal_create_key, fields=[ _descriptor.FieldDescriptor( name="model", full_name="google.cloud.videointelligence.v1.ExplicitContentDetectionConfig.model", index=0, number=1, type=9, cpp_type=9, label=1, has_default_value=False, default_value=b"".decode("utf-8"), message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key, ), ], extensions=[], nested_types=[], enum_types=[], serialized_options=None, is_extendable=False, syntax="proto3", extension_ranges=[], oneofs=[], serialized_start=1933, serialized_end=1980, ) _TEXTDETECTIONCONFIG = _descriptor.Descriptor( name="TextDetectionConfig", full_name="google.cloud.videointelligence.v1.TextDetectionConfig", filename=None, file=DESCRIPTOR, containing_type=None, create_key=_descriptor._internal_create_key, fields=[ _descriptor.FieldDescriptor( name="language_hints", full_name="google.cloud.videointelligence.v1.TextDetectionConfig.language_hints", index=0, number=1, type=9, cpp_type=9, label=3, has_default_value=False, default_value=[], message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key, ), _descriptor.FieldDescriptor( name="model", full_name="google.cloud.videointelligence.v1.TextDetectionConfig.model", index=1, number=2, type=9, cpp_type=9, label=1, has_default_value=False, default_value=b"".decode("utf-8"), message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key, ), ], extensions=[], nested_types=[], enum_types=[], serialized_options=None, is_extendable=False, syntax="proto3", extension_ranges=[], oneofs=[], serialized_start=1982, serialized_end=2042, ) _VIDEOSEGMENT = _descriptor.Descriptor( name="VideoSegment", full_name="google.cloud.videointelligence.v1.VideoSegment", filename=None, file=DESCRIPTOR, containing_type=None, create_key=_descriptor._internal_create_key, fields=[ _descriptor.FieldDescriptor( name="start_time_offset", full_name="google.cloud.videointelligence.v1.VideoSegment.start_time_offset", index=0, number=1, type=11, cpp_type=10, label=1, has_default_value=False, default_value=None, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key, ), _descriptor.FieldDescriptor( name="end_time_offset", full_name="google.cloud.videointelligence.v1.VideoSegment.end_time_offset", index=1, number=2, type=11, cpp_type=10, label=1, has_default_value=False, default_value=None, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key, ), ], extensions=[], nested_types=[], enum_types=[], serialized_options=None, is_extendable=False, syntax="proto3", extension_ranges=[], oneofs=[], serialized_start=2044, serialized_end=2164, ) _LABELSEGMENT = _descriptor.Descriptor( name="LabelSegment", full_name="google.cloud.videointelligence.v1.LabelSegment", filename=None, file=DESCRIPTOR, containing_type=None, create_key=_descriptor._internal_create_key, fields=[ _descriptor.FieldDescriptor( name="segment", full_name="google.cloud.videointelligence.v1.LabelSegment.segment", index=0, number=1, type=11, cpp_type=10, label=1, has_default_value=False, default_value=None, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key, ), _descriptor.FieldDescriptor( name="confidence", full_name="google.cloud.videointelligence.v1.LabelSegment.confidence", index=1, number=2, type=2, cpp_type=6, label=1, has_default_value=False, default_value=float(0), message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key, ), ], extensions=[], nested_types=[], enum_types=[], serialized_options=None, is_extendable=False, syntax="proto3", extension_ranges=[], oneofs=[], serialized_start=2166, serialized_end=2266, ) _LABELFRAME = _descriptor.Descriptor( name="LabelFrame", full_name="google.cloud.videointelligence.v1.LabelFrame", filename=None, file=DESCRIPTOR, containing_type=None, create_key=_descriptor._internal_create_key, fields=[ _descriptor.FieldDescriptor( name="time_offset", full_name="google.cloud.videointelligence.v1.LabelFrame.time_offset", index=0, number=1, type=11, cpp_type=10, label=1, has_default_value=False, default_value=None, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key, ), _descriptor.FieldDescriptor( name="confidence", full_name="google.cloud.videointelligence.v1.LabelFrame.confidence", index=1, number=2, type=2, cpp_type=6, label=1, has_default_value=False, default_value=float(0), message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key, ), ], extensions=[], nested_types=[], enum_types=[], serialized_options=None, is_extendable=False, syntax="proto3", extension_ranges=[], oneofs=[], serialized_start=2268, serialized_end=2348, ) _ENTITY = _descriptor.Descriptor( name="Entity", full_name="google.cloud.videointelligence.v1.Entity", filename=None, file=DESCRIPTOR, containing_type=None, create_key=_descriptor._internal_create_key, fields=[ _descriptor.FieldDescriptor( name="entity_id", full_name="google.cloud.videointelligence.v1.Entity.entity_id", index=0, number=1, type=9, cpp_type=9, label=1, has_default_value=False, default_value=b"".decode("utf-8"), message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key, ), _descriptor.FieldDescriptor( name="description", full_name="google.cloud.videointelligence.v1.Entity.description", index=1, number=2, type=9, cpp_type=9, label=1, has_default_value=False, default_value=b"".decode("utf-8"), message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key, ), _descriptor.FieldDescriptor( name="language_code", full_name="google.cloud.videointelligence.v1.Entity.language_code", index=2, number=3, type=9, cpp_type=9, label=1, has_default_value=False, default_value=b"".decode("utf-8"), message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key, ), ], extensions=[], nested_types=[], enum_types=[], serialized_options=None, is_extendable=False, syntax="proto3", extension_ranges=[], oneofs=[], serialized_start=2350, serialized_end=2421, ) _LABELANNOTATION = _descriptor.Descriptor( name="LabelAnnotation", full_name="google.cloud.videointelligence.v1.LabelAnnotation", filename=None, file=DESCRIPTOR, containing_type=None, create_key=_descriptor._internal_create_key, fields=[ _descriptor.FieldDescriptor( name="entity", full_name="google.cloud.videointelligence.v1.LabelAnnotation.entity", index=0, number=1, type=11, cpp_type=10, label=1, has_default_value=False, default_value=None, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key, ), _descriptor.FieldDescriptor( name="category_entities", full_name="google.cloud.videointelligence.v1.LabelAnnotation.category_entities", index=1, number=2, type=11, cpp_type=10, label=3, has_default_value=False, default_value=[], message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key, ), _descriptor.FieldDescriptor( name="segments", full_name="google.cloud.videointelligence.v1.LabelAnnotation.segments", index=2, number=3, type=11, cpp_type=10, label=3, has_default_value=False, default_value=[], message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key, ), _descriptor.FieldDescriptor( name="frames", full_name="google.cloud.videointelligence.v1.LabelAnnotation.frames", index=3, number=4, type=11, cpp_type=10, label=3, has_default_value=False, default_value=[], message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key, ), _descriptor.FieldDescriptor( name="version", full_name="google.cloud.videointelligence.v1.LabelAnnotation.version", index=4, number=5, type=9, cpp_type=9, label=1, has_default_value=False, default_value=b"".decode("utf-8"), message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key, ), ], extensions=[], nested_types=[], enum_types=[], serialized_options=None, is_extendable=False, syntax="proto3", extension_ranges=[], oneofs=[], serialized_start=2424, serialized_end=2717, ) _EXPLICITCONTENTFRAME = _descriptor.Descriptor( name="ExplicitContentFrame", full_name="google.cloud.videointelligence.v1.ExplicitContentFrame", filename=None, file=DESCRIPTOR, containing_type=None, create_key=_descriptor._internal_create_key, fields=[ _descriptor.FieldDescriptor( name="time_offset", full_name="google.cloud.videointelligence.v1.ExplicitContentFrame.time_offset", index=0, number=1, type=11, cpp_type=10, label=1, has_default_value=False, default_value=None, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key, ), _descriptor.FieldDescriptor( name="pornography_likelihood", full_name="google.cloud.videointelligence.v1.ExplicitContentFrame.pornography_likelihood", index=1, number=2, type=14, cpp_type=8, label=1, has_default_value=False, default_value=0, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key, ), ], extensions=[], nested_types=[], enum_types=[], serialized_options=None, is_extendable=False, syntax="proto3", extension_ranges=[], oneofs=[], serialized_start=2720, serialized_end=2869, ) _EXPLICITCONTENTANNOTATION = _descriptor.Descriptor( name="ExplicitContentAnnotation", full_name="google.cloud.videointelligence.v1.ExplicitContentAnnotation", filename=None, file=DESCRIPTOR, containing_type=None, create_key=_descriptor._internal_create_key, fields=[ _descriptor.FieldDescriptor( name="frames", full_name="google.cloud.videointelligence.v1.ExplicitContentAnnotation.frames", index=0, number=1, type=11, cpp_type=10, label=3, has_default_value=False, default_value=[], message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key, ), _descriptor.FieldDescriptor( name="version", full_name="google.cloud.videointelligence.v1.ExplicitContentAnnotation.version", index=1, number=2, type=9, cpp_type=9, label=1, has_default_value=False, default_value=b"".decode("utf-8"), message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key, ), ], extensions=[], nested_types=[], enum_types=[], serialized_options=None, is_extendable=False, syntax="proto3", extension_ranges=[], oneofs=[], serialized_start=2871, serialized_end=2988, ) _NORMALIZEDBOUNDINGBOX = _descriptor.Descriptor( name="NormalizedBoundingBox", full_name="google.cloud.videointelligence.v1.NormalizedBoundingBox", filename=None, file=DESCRIPTOR, containing_type=None, create_key=_descriptor._internal_create_key, fields=[ _descriptor.FieldDescriptor( name="left", full_name="google.cloud.videointelligence.v1.NormalizedBoundingBox.left", index=0, number=1, type=2, cpp_type=6, label=1, has_default_value=False, default_value=float(0), message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key, ), _descriptor.FieldDescriptor( name="top", full_name="google.cloud.videointelligence.v1.NormalizedBoundingBox.top", index=1, number=2, type=2, cpp_type=6, label=1, has_default_value=False, default_value=float(0), message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key, ), _descriptor.FieldDescriptor( name="right", full_name="google.cloud.videointelligence.v1.NormalizedBoundingBox.right", index=2, number=3, type=2, cpp_type=6, label=1, has_default_value=False, default_value=float(0), message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key, ), _descriptor.FieldDescriptor( name="bottom", full_name="google.cloud.videointelligence.v1.NormalizedBoundingBox.bottom", index=3, number=4, type=2, cpp_type=6, label=1, has_default_value=False, default_value=float(0), message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key, ), ], extensions=[], nested_types=[], enum_types=[], serialized_options=None, is_extendable=False, syntax="proto3", extension_ranges=[], oneofs=[], serialized_start=2990, serialized_end=3071, ) _FACEDETECTIONANNOTATION = _descriptor.Descriptor( name="FaceDetectionAnnotation", full_name="google.cloud.videointelligence.v1.FaceDetectionAnnotation", filename=None, file=DESCRIPTOR, containing_type=None, create_key=_descriptor._internal_create_key, fields=[ _descriptor.FieldDescriptor( name="version", full_name="google.cloud.videointelligence.v1.FaceDetectionAnnotation.version", index=0, number=5, type=9, cpp_type=9, label=1, has_default_value=False, default_value=b"".decode("utf-8"), message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key, ), ], extensions=[], nested_types=[], enum_types=[], serialized_options=None, is_extendable=False, syntax="proto3", extension_ranges=[], oneofs=[], serialized_start=3073, serialized_end=3115, ) _PERSONDETECTIONANNOTATION = _descriptor.Descriptor( name="PersonDetectionAnnotation", full_name="google.cloud.videointelligence.v1.PersonDetectionAnnotation", filename=None, file=DESCRIPTOR, containing_type=None, create_key=_descriptor._internal_create_key, fields=[ _descriptor.FieldDescriptor( name="tracks", full_name="google.cloud.videointelligence.v1.PersonDetectionAnnotation.tracks", index=0, number=1, type=11, cpp_type=10, label=3, has_default_value=False, default_value=[], message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key, ), _descriptor.FieldDescriptor( name="version", full_name="google.cloud.videointelligence.v1.PersonDetectionAnnotation.version", index=1, number=2, type=9, cpp_type=9, label=1, has_default_value=False, default_value=b"".decode("utf-8"), message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key, ), ], extensions=[], nested_types=[], enum_types=[], serialized_options=None, is_extendable=False, syntax="proto3", extension_ranges=[], oneofs=[], serialized_start=3117, serialized_end=3219, ) _FACESEGMENT = _descriptor.Descriptor( name="FaceSegment", full_name="google.cloud.videointelligence.v1.FaceSegment", filename=None, file=DESCRIPTOR, containing_type=None, create_key=_descriptor._internal_create_key, fields=[ _descriptor.FieldDescriptor( name="segment", full_name="google.cloud.videointelligence.v1.FaceSegment.segment", index=0, number=1, type=11, cpp_type=10, label=1, has_default_value=False, default_value=None, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key, ), ], extensions=[], nested_types=[], enum_types=[], serialized_options=None, is_extendable=False, syntax="proto3", extension_ranges=[], oneofs=[], serialized_start=3221, serialized_end=3300, ) _FACEFRAME = _descriptor.Descriptor( name="FaceFrame", full_name="google.cloud.videointelligence.v1.FaceFrame", filename=None, file=DESCRIPTOR, containing_type=None, create_key=_descriptor._internal_create_key, fields=[ _descriptor.FieldDescriptor( name="normalized_bounding_boxes", full_name="google.cloud.videointelligence.v1.FaceFrame.normalized_bounding_boxes", index=0, number=1, type=11, cpp_type=10, label=3, has_default_value=False, default_value=[], message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key, ), _descriptor.FieldDescriptor( name="time_offset", full_name="google.cloud.videointelligence.v1.FaceFrame.time_offset", index=1, number=2, type=11, cpp_type=10, label=1, has_default_value=False, default_value=None, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key, ), ], extensions=[], nested_types=[], enum_types=[], serialized_options=b"\030\001", is_extendable=False, syntax="proto3", extension_ranges=[], oneofs=[], serialized_start=3303, serialized_end=3459, ) _FACEANNOTATION = _descriptor.Descriptor( name="FaceAnnotation", full_name="google.cloud.videointelligence.v1.FaceAnnotation", filename=None, file=DESCRIPTOR, containing_type=None, create_key=_descriptor._internal_create_key, fields=[ _descriptor.FieldDescriptor( name="thumbnail", full_name="google.cloud.videointelligence.v1.FaceAnnotation.thumbnail", index=0, number=1, type=12, cpp_type=9, label=1, has_default_value=False, default_value=b"", message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key, ), _descriptor.FieldDescriptor( name="segments", full_name="google.cloud.videointelligence.v1.FaceAnnotation.segments", index=1, number=2, type=11, cpp_type=10, label=3, has_default_value=False, default_value=[], message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key, ), _descriptor.FieldDescriptor( name="frames", full_name="google.cloud.videointelligence.v1.FaceAnnotation.frames", index=2, number=3, type=11, cpp_type=10, label=3, has_default_value=False, default_value=[], message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key, ), ], extensions=[], nested_types=[], enum_types=[], serialized_options=b"\030\001", is_extendable=False, syntax="proto3", extension_ranges=[], oneofs=[], serialized_start=3462, serialized_end=3629, ) _TIMESTAMPEDOBJECT = _descriptor.Descriptor( name="TimestampedObject", full_name="google.cloud.videointelligence.v1.TimestampedObject", filename=None, file=DESCRIPTOR, containing_type=None, create_key=_descriptor._internal_create_key, fields=[ _descriptor.FieldDescriptor( name="normalized_bounding_box", full_name="google.cloud.videointelligence.v1.TimestampedObject.normalized_bounding_box", index=0, number=1, type=11, cpp_type=10, label=1, has_default_value=False, default_value=None, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key, ), _descriptor.FieldDescriptor( name="time_offset", full_name="google.cloud.videointelligence.v1.TimestampedObject.time_offset", index=1, number=2, type=11, cpp_type=10, label=1, has_default_value=False, default_value=None, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key, ), _descriptor.FieldDescriptor( name="attributes", full_name="google.cloud.videointelligence.v1.TimestampedObject.attributes", index=2, number=3, type=11, cpp_type=10, label=3, has_default_value=False, default_value=[], message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=b"\340A\001", file=DESCRIPTOR, create_key=_descriptor._internal_create_key, ), _descriptor.FieldDescriptor( name="landmarks", full_name="google.cloud.videointelligence.v1.TimestampedObject.landmarks", index=3, number=4, type=11, cpp_type=10, label=3, has_default_value=False, default_value=[], message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=b"\340A\001", file=DESCRIPTOR, create_key=_descriptor._internal_create_key, ), ], extensions=[], nested_types=[], enum_types=[], serialized_options=None, is_extendable=False, syntax="proto3", extension_ranges=[], oneofs=[], serialized_start=3632, serialized_end=3946, ) _TRACK = _descriptor.Descriptor( name="Track", full_name="google.cloud.videointelligence.v1.Track", filename=None, file=DESCRIPTOR, containing_type=None, create_key=_descriptor._internal_create_key, fields=[ _descriptor.FieldDescriptor( name="segment", full_name="google.cloud.videointelligence.v1.Track.segment", index=0, number=1, type=11, cpp_type=10, label=1, has_default_value=False, default_value=None, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key, ), _descriptor.FieldDescriptor( name="timestamped_objects", full_name="google.cloud.videointelligence.v1.Track.timestamped_objects", index=1, number=2, type=11, cpp_type=10, label=3, has_default_value=False, default_value=[], message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key, ), _descriptor.FieldDescriptor( name="attributes", full_name="google.cloud.videointelligence.v1.Track.attributes", index=2, number=3, type=11, cpp_type=10, label=3, has_default_value=False, default_value=[], message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=b"\340A\001", file=DESCRIPTOR, create_key=_descriptor._internal_create_key, ), _descriptor.FieldDescriptor( name="confidence", full_name="google.cloud.videointelligence.v1.Track.confidence", index=3, number=4, type=2, cpp_type=6, label=1, has_default_value=False, default_value=float(0), message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=b"\340A\001", file=DESCRIPTOR, create_key=_descriptor._internal_create_key, ), ], extensions=[], nested_types=[], enum_types=[], serialized_options=None, is_extendable=False, syntax="proto3", extension_ranges=[], oneofs=[], serialized_start=3949, serialized_end=4209, ) _DETECTEDATTRIBUTE = _descriptor.Descriptor( name="DetectedAttribute", full_name="google.cloud.videointelligence.v1.DetectedAttribute", filename=None, file=DESCRIPTOR, containing_type=None, create_key=_descriptor._internal_create_key, fields=[ _descriptor.FieldDescriptor( name="name", full_name="google.cloud.videointelligence.v1.DetectedAttribute.name", index=0, number=1, type=9, cpp_type=9, label=1, has_default_value=False, default_value=b"".decode("utf-8"), message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key, ), _descriptor.FieldDescriptor( name="confidence", full_name="google.cloud.videointelligence.v1.DetectedAttribute.confidence", index=1, number=2, type=2, cpp_type=6, label=1, has_default_value=False, default_value=float(0), message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key, ), _descriptor.FieldDescriptor( name="value", full_name="google.cloud.videointelligence.v1.DetectedAttribute.value", index=2, number=3, type=9, cpp_type=9, label=1, has_default_value=False, default_value=b"".decode("utf-8"), message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key, ), ], extensions=[], nested_types=[], enum_types=[], serialized_options=None, is_extendable=False, syntax="proto3", extension_ranges=[], oneofs=[], serialized_start=4211, serialized_end=4279, ) _DETECTEDLANDMARK = _descriptor.Descriptor( name="DetectedLandmark", full_name="google.cloud.videointelligence.v1.DetectedLandmark", filename=None, file=DESCRIPTOR, containing_type=None, create_key=_descriptor._internal_create_key, fields=[ _descriptor.FieldDescriptor( name="name", full_name="google.cloud.videointelligence.v1.DetectedLandmark.name", index=0, number=1, type=9, cpp_type=9, label=1, has_default_value=False, default_value=b"".decode("utf-8"), message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key, ), _descriptor.FieldDescriptor( name="point", full_name="google.cloud.videointelligence.v1.DetectedLandmark.point", index=1, number=2, type=11, cpp_type=10, label=1, has_default_value=False, default_value=None, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key, ), _descriptor.FieldDescriptor( name="confidence", full_name="google.cloud.videointelligence.v1.DetectedLandmark.confidence", index=2, number=3, type=2, cpp_type=6, label=1, has_default_value=False, default_value=float(0), message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key, ), ], extensions=[], nested_types=[], enum_types=[], serialized_options=None, is_extendable=False, syntax="proto3", extension_ranges=[], oneofs=[], serialized_start=4281, serialized_end=4401, ) _VIDEOANNOTATIONRESULTS = _descriptor.Descriptor( name="VideoAnnotationResults", full_name="google.cloud.videointelligence.v1.VideoAnnotationResults", filename=None, file=DESCRIPTOR, containing_type=None, create_key=_descriptor._internal_create_key, fields=[ _descriptor.FieldDescriptor( name="input_uri", full_name="google.cloud.videointelligence.v1.VideoAnnotationResults.input_uri", index=0, number=1, type=9, cpp_type=9, label=1, has_default_value=False, default_value=b"".decode("utf-8"), message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key, ), _descriptor.FieldDescriptor( name="segment", full_name="google.cloud.videointelligence.v1.VideoAnnotationResults.segment", index=1, number=10, type=11, cpp_type=10, label=1, has_default_value=False, default_value=None, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key, ), _descriptor.FieldDescriptor( name="segment_label_annotations", full_name="google.cloud.videointelligence.v1.VideoAnnotationResults.segment_label_annotations", index=2, number=2, type=11, cpp_type=10, label=3, has_default_value=False, default_value=[], message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key, ), _descriptor.FieldDescriptor( name="segment_presence_label_annotations", full_name="google.cloud.videointelligence.v1.VideoAnnotationResults.segment_presence_label_annotations", index=3, number=23, type=11, cpp_type=10, label=3, has_default_value=False, default_value=[], message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key, ), _descriptor.FieldDescriptor( name="shot_label_annotations", full_name="google.cloud.videointelligence.v1.VideoAnnotationResults.shot_label_annotations", index=4, number=3, type=11, cpp_type=10, label=3, has_default_value=False, default_value=[], message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key, ), _descriptor.FieldDescriptor( name="shot_presence_label_annotations", full_name="google.cloud.videointelligence.v1.VideoAnnotationResults.shot_presence_label_annotations", index=5, number=24, type=11, cpp_type=10, label=3, has_default_value=False, default_value=[], message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key, ), _descriptor.FieldDescriptor( name="frame_label_annotations", full_name="google.cloud.videointelligence.v1.VideoAnnotationResults.frame_label_annotations", index=6, number=4, type=11, cpp_type=10, label=3, has_default_value=False, default_value=[], message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key, ), _descriptor.FieldDescriptor( name="face_annotations", full_name="google.cloud.videointelligence.v1.VideoAnnotationResults.face_annotations", index=7, number=5, type=11, cpp_type=10, label=3, has_default_value=False, default_value=[], message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=b"\030\001", file=DESCRIPTOR, create_key=_descriptor._internal_create_key, ), _descriptor.FieldDescriptor( name="face_detection_annotations", full_name="google.cloud.videointelligence.v1.VideoAnnotationResults.face_detection_annotations", index=8, number=13, type=11, cpp_type=10, label=3, has_default_value=False, default_value=[], message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key, ), _descriptor.FieldDescriptor( name="shot_annotations", full_name="google.cloud.videointelligence.v1.VideoAnnotationResults.shot_annotations", index=9, number=6, type=11, cpp_type=10, label=3, has_default_value=False, default_value=[], message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key, ), _descriptor.FieldDescriptor( name="explicit_annotation", full_name="google.cloud.videointelligence.v1.VideoAnnotationResults.explicit_annotation", index=10, number=7, type=11, cpp_type=10, label=1, has_default_value=False, default_value=None, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key, ), _descriptor.FieldDescriptor( name="speech_transcriptions", full_name="google.cloud.videointelligence.v1.VideoAnnotationResults.speech_transcriptions", index=11, number=11, type=11, cpp_type=10, label=3, has_default_value=False, default_value=[], message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key, ), _descriptor.FieldDescriptor( name="text_annotations", full_name="google.cloud.videointelligence.v1.VideoAnnotationResults.text_annotations", index=12, number=12, type=11, cpp_type=10, label=3, has_default_value=False, default_value=[], message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key, ), _descriptor.FieldDescriptor( name="object_annotations", full_name="google.cloud.videointelligence.v1.VideoAnnotationResults.object_annotations", index=13, number=14, type=11, cpp_type=10, label=3, has_default_value=False, default_value=[], message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key, ), _descriptor.FieldDescriptor( name="logo_recognition_annotations", full_name="google.cloud.videointelligence.v1.VideoAnnotationResults.logo_recognition_annotations", index=14, number=19, type=11, cpp_type=10, label=3, has_default_value=False, default_value=[], message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key, ), _descriptor.FieldDescriptor( name="person_detection_annotations", full_name="google.cloud.videointelligence.v1.VideoAnnotationResults.person_detection_annotations", index=15, number=20, type=11, cpp_type=10, label=3, has_default_value=False, default_value=[], message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key, ), _descriptor.FieldDescriptor( name="error", full_name="google.cloud.videointelligence.v1.VideoAnnotationResults.error", index=16, number=9, type=11, cpp_type=10, label=1, has_default_value=False, default_value=None, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key, ), ], extensions=[], nested_types=[], enum_types=[], serialized_options=None, is_extendable=False, syntax="proto3", extension_ranges=[], oneofs=[], serialized_start=4404, serialized_end=5789, ) _ANNOTATEVIDEORESPONSE = _descriptor.Descriptor( name="AnnotateVideoResponse", full_name="google.cloud.videointelligence.v1.AnnotateVideoResponse", filename=None, file=DESCRIPTOR, containing_type=None, create_key=_descriptor._internal_create_key, fields=[ _descriptor.FieldDescriptor( name="annotation_results", full_name="google.cloud.videointelligence.v1.AnnotateVideoResponse.annotation_results", index=0, number=1, type=11, cpp_type=10, label=3, has_default_value=False, default_value=[], message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key, ), ], extensions=[], nested_types=[], enum_types=[], serialized_options=None, is_extendable=False, syntax="proto3", extension_ranges=[], oneofs=[], serialized_start=5791, serialized_end=5901, ) _VIDEOANNOTATIONPROGRESS = _descriptor.Descriptor( name="VideoAnnotationProgress", full_name="google.cloud.videointelligence.v1.VideoAnnotationProgress", filename=None, file=DESCRIPTOR, containing_type=None, create_key=_descriptor._internal_create_key, fields=[ _descriptor.FieldDescriptor( name="input_uri", full_name="google.cloud.videointelligence.v1.VideoAnnotationProgress.input_uri", index=0, number=1, type=9, cpp_type=9, label=1, has_default_value=False, default_value=b"".decode("utf-8"), message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key, ), _descriptor.FieldDescriptor( name="progress_percent", full_name="google.cloud.videointelligence.v1.VideoAnnotationProgress.progress_percent", index=1, number=2, type=5, cpp_type=1, label=1, has_default_value=False, default_value=0, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key, ), _descriptor.FieldDescriptor( name="start_time", full_name="google.cloud.videointelligence.v1.VideoAnnotationProgress.start_time", index=2, number=3, type=11, cpp_type=10, label=1, has_default_value=False, default_value=None, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key, ), _descriptor.FieldDescriptor( name="update_time", full_name="google.cloud.videointelligence.v1.VideoAnnotationProgress.update_time", index=3, number=4, type=11, cpp_type=10, label=1, has_default_value=False, default_value=None, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key, ), _descriptor.FieldDescriptor( name="feature", full_name="google.cloud.videointelligence.v1.VideoAnnotationProgress.feature", index=4, number=5, type=14, cpp_type=8, label=1, has_default_value=False, default_value=0, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key, ), _descriptor.FieldDescriptor( name="segment", full_name="google.cloud.videointelligence.v1.VideoAnnotationProgress.segment", index=5, number=6, type=11, cpp_type=10, label=1, has_default_value=False, default_value=None, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key, ), ], extensions=[], nested_types=[], enum_types=[], serialized_options=None, is_extendable=False, syntax="proto3", extension_ranges=[], oneofs=[], serialized_start=5904, serialized_end=6198, ) _ANNOTATEVIDEOPROGRESS = _descriptor.Descriptor( name="AnnotateVideoProgress", full_name="google.cloud.videointelligence.v1.AnnotateVideoProgress", filename=None, file=DESCRIPTOR, containing_type=None, create_key=_descriptor._internal_create_key, fields=[ _descriptor.FieldDescriptor( name="annotation_progress", full_name="google.cloud.videointelligence.v1.AnnotateVideoProgress.annotation_progress", index=0, number=1, type=11, cpp_type=10, label=3, has_default_value=False, default_value=[], message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key, ), ], extensions=[], nested_types=[], enum_types=[], serialized_options=None, is_extendable=False, syntax="proto3", extension_ranges=[], oneofs=[], serialized_start=6200, serialized_end=6312, ) _SPEECHTRANSCRIPTIONCONFIG = _descriptor.Descriptor( name="SpeechTranscriptionConfig", full_name="google.cloud.videointelligence.v1.SpeechTranscriptionConfig", filename=None, file=DESCRIPTOR, containing_type=None, create_key=_descriptor._internal_create_key, fields=[ _descriptor.FieldDescriptor( name="language_code", full_name="google.cloud.videointelligence.v1.SpeechTranscriptionConfig.language_code", index=0, number=1, type=9, cpp_type=9, label=1, has_default_value=False, default_value=b"".decode("utf-8"), message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=b"\340A\002", file=DESCRIPTOR, create_key=_descriptor._internal_create_key, ), _descriptor.FieldDescriptor( name="max_alternatives", full_name="google.cloud.videointelligence.v1.SpeechTranscriptionConfig.max_alternatives", index=1, number=2, type=5, cpp_type=1, label=1, has_default_value=False, default_value=0, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=b"\340A\001", file=DESCRIPTOR, create_key=_descriptor._internal_create_key, ), _descriptor.FieldDescriptor( name="filter_profanity", full_name="google.cloud.videointelligence.v1.SpeechTranscriptionConfig.filter_profanity", index=2, number=3, type=8, cpp_type=7, label=1, has_default_value=False, default_value=False, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=b"\340A\001", file=DESCRIPTOR, create_key=_descriptor._internal_create_key, ), _descriptor.FieldDescriptor( name="speech_contexts", full_name="google.cloud.videointelligence.v1.SpeechTranscriptionConfig.speech_contexts", index=3, number=4, type=11, cpp_type=10, label=3, has_default_value=False, default_value=[], message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=b"\340A\001", file=DESCRIPTOR, create_key=_descriptor._internal_create_key, ), _descriptor.FieldDescriptor( name="enable_automatic_punctuation", full_name="google.cloud.videointelligence.v1.SpeechTranscriptionConfig.enable_automatic_punctuation", index=4, number=5, type=8, cpp_type=7, label=1, has_default_value=False, default_value=False, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=b"\340A\001", file=DESCRIPTOR, create_key=_descriptor._internal_create_key, ), _descriptor.FieldDescriptor( name="audio_tracks", full_name="google.cloud.videointelligence.v1.SpeechTranscriptionConfig.audio_tracks", index=5, number=6, type=5, cpp_type=1, label=3, has_default_value=False, default_value=[], message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=b"\340A\001", file=DESCRIPTOR, create_key=_descriptor._internal_create_key, ), _descriptor.FieldDescriptor( name="enable_speaker_diarization", full_name="google.cloud.videointelligence.v1.SpeechTranscriptionConfig.enable_speaker_diarization", index=6, number=7, type=8, cpp_type=7, label=1, has_default_value=False, default_value=False, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=b"\340A\001", file=DESCRIPTOR, create_key=_descriptor._internal_create_key, ), _descriptor.FieldDescriptor( name="diarization_speaker_count", full_name="google.cloud.videointelligence.v1.SpeechTranscriptionConfig.diarization_speaker_count", index=7, number=8, type=5, cpp_type=1, label=1, has_default_value=False, default_value=0, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=b"\340A\001", file=DESCRIPTOR, create_key=_descriptor._internal_create_key, ), _descriptor.FieldDescriptor( name="enable_word_confidence", full_name="google.cloud.videointelligence.v1.SpeechTranscriptionConfig.enable_word_confidence", index=8, number=9, type=8, cpp_type=7, label=1, has_default_value=False, default_value=False, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=b"\340A\001", file=DESCRIPTOR, create_key=_descriptor._internal_create_key, ), ], extensions=[], nested_types=[], enum_types=[], serialized_options=None, is_extendable=False, syntax="proto3", extension_ranges=[], oneofs=[], serialized_start=6315, serialized_end=6700, ) _SPEECHCONTEXT = _descriptor.Descriptor( name="SpeechContext", full_name="google.cloud.videointelligence.v1.SpeechContext", filename=None, file=DESCRIPTOR, containing_type=None, create_key=_descriptor._internal_create_key, fields=[ _descriptor.FieldDescriptor( name="phrases", full_name="google.cloud.videointelligence.v1.SpeechContext.phrases", index=0, number=1, type=9, cpp_type=9, label=3, has_default_value=False, default_value=[], message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=b"\340A\001", file=DESCRIPTOR, create_key=_descriptor._internal_create_key, ), ], extensions=[], nested_types=[], enum_types=[], serialized_options=None, is_extendable=False, syntax="proto3", extension_ranges=[], oneofs=[], serialized_start=6702, serialized_end=6739, ) _SPEECHTRANSCRIPTION = _descriptor.Descriptor( name="SpeechTranscription", full_name="google.cloud.videointelligence.v1.SpeechTranscription", filename=None, file=DESCRIPTOR, containing_type=None, create_key=_descriptor._internal_create_key, fields=[ _descriptor.FieldDescriptor( name="alternatives", full_name="google.cloud.videointelligence.v1.SpeechTranscription.alternatives", index=0, number=1, type=11, cpp_type=10, label=3, has_default_value=False, default_value=[], message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key, ), _descriptor.FieldDescriptor( name="language_code", full_name="google.cloud.videointelligence.v1.SpeechTranscription.language_code", index=1, number=2, type=9, cpp_type=9, label=1, has_default_value=False, default_value=b"".decode("utf-8"), message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=b"\340A\003", file=DESCRIPTOR, create_key=_descriptor._internal_create_key, ), ], extensions=[], nested_types=[], enum_types=[], serialized_options=None, is_extendable=False, syntax="proto3", extension_ranges=[], oneofs=[], serialized_start=6742, serialized_end=6878, ) _SPEECHRECOGNITIONALTERNATIVE = _descriptor.Descriptor( name="SpeechRecognitionAlternative", full_name="google.cloud.videointelligence.v1.SpeechRecognitionAlternative", filename=None, file=DESCRIPTOR, containing_type=None, create_key=_descriptor._internal_create_key, fields=[ _descriptor.FieldDescriptor( name="transcript", full_name="google.cloud.videointelligence.v1.SpeechRecognitionAlternative.transcript", index=0, number=1, type=9, cpp_type=9, label=1, has_default_value=False, default_value=b"".decode("utf-8"), message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key, ), _descriptor.FieldDescriptor( name="confidence", full_name="google.cloud.videointelligence.v1.SpeechRecognitionAlternative.confidence", index=1, number=2, type=2, cpp_type=6, label=1, has_default_value=False, default_value=float(0), message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=b"\340A\003", file=DESCRIPTOR, create_key=_descriptor._internal_create_key, ), _descriptor.FieldDescriptor( name="words", full_name="google.cloud.videointelligence.v1.SpeechRecognitionAlternative.words", index=2, number=3, type=11, cpp_type=10, label=3, has_default_value=False, default_value=[], message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=b"\340A\003", file=DESCRIPTOR, create_key=_descriptor._internal_create_key, ), ], extensions=[], nested_types=[], enum_types=[], serialized_options=None, is_extendable=False, syntax="proto3", extension_ranges=[], oneofs=[], serialized_start=6881, serialized_end=7021, ) _WORDINFO = _descriptor.Descriptor( name="WordInfo", full_name="google.cloud.videointelligence.v1.WordInfo", filename=None, file=DESCRIPTOR, containing_type=None, create_key=_descriptor._internal_create_key, fields=[ _descriptor.FieldDescriptor( name="start_time", full_name="google.cloud.videointelligence.v1.WordInfo.start_time", index=0, number=1, type=11, cpp_type=10, label=1, has_default_value=False, default_value=None, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key, ), _descriptor.FieldDescriptor( name="end_time", full_name="google.cloud.videointelligence.v1.WordInfo.end_time", index=1, number=2, type=11, cpp_type=10, label=1, has_default_value=False, default_value=None, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key, ), _descriptor.FieldDescriptor( name="word", full_name="google.cloud.videointelligence.v1.WordInfo.word", index=2, number=3, type=9, cpp_type=9, label=1, has_default_value=False, default_value=b"".decode("utf-8"), message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key, ), _descriptor.FieldDescriptor( name="confidence", full_name="google.cloud.videointelligence.v1.WordInfo.confidence", index=3, number=4, type=2, cpp_type=6, label=1, has_default_value=False, default_value=float(0), message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=b"\340A\003", file=DESCRIPTOR, create_key=_descriptor._internal_create_key, ), _descriptor.FieldDescriptor( name="speaker_tag", full_name="google.cloud.videointelligence.v1.WordInfo.speaker_tag", index=4, number=5, type=5, cpp_type=1, label=1, has_default_value=False, default_value=0, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=b"\340A\003", file=DESCRIPTOR, create_key=_descriptor._internal_create_key, ), ], extensions=[], nested_types=[], enum_types=[], serialized_options=None, is_extendable=False, syntax="proto3", extension_ranges=[], oneofs=[], serialized_start=7024, serialized_end=7191, ) _NORMALIZEDVERTEX = _descriptor.Descriptor( name="NormalizedVertex", full_name="google.cloud.videointelligence.v1.NormalizedVertex", filename=None, file=DESCRIPTOR, containing_type=None, create_key=_descriptor._internal_create_key, fields=[ _descriptor.FieldDescriptor( name="x", full_name="google.cloud.videointelligence.v1.NormalizedVertex.x", index=0, number=1, type=2, cpp_type=6, label=1, has_default_value=False, default_value=float(0), message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key, ), _descriptor.FieldDescriptor( name="y", full_name="google.cloud.videointelligence.v1.NormalizedVertex.y", index=1, number=2, type=2, cpp_type=6, label=1, has_default_value=False, default_value=float(0), message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key, ), ], extensions=[], nested_types=[], enum_types=[], serialized_options=None, is_extendable=False, syntax="proto3", extension_ranges=[], oneofs=[], serialized_start=7193, serialized_end=7233, ) _NORMALIZEDBOUNDINGPOLY = _descriptor.Descriptor( name="NormalizedBoundingPoly", full_name="google.cloud.videointelligence.v1.NormalizedBoundingPoly", filename=None, file=DESCRIPTOR, containing_type=None, create_key=_descriptor._internal_create_key, fields=[ _descriptor.FieldDescriptor( name="vertices", full_name="google.cloud.videointelligence.v1.NormalizedBoundingPoly.vertices", index=0, number=1, type=11, cpp_type=10, label=3, has_default_value=False, default_value=[], message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key, ), ], extensions=[], nested_types=[], enum_types=[], serialized_options=None, is_extendable=False, syntax="proto3", extension_ranges=[], oneofs=[], serialized_start=7235, serialized_end=7330, ) _TEXTSEGMENT = _descriptor.Descriptor( name="TextSegment", full_name="google.cloud.videointelligence.v1.TextSegment", filename=None, file=DESCRIPTOR, containing_type=None, create_key=_descriptor._internal_create_key, fields=[ _descriptor.FieldDescriptor( name="segment", full_name="google.cloud.videointelligence.v1.TextSegment.segment", index=0, number=1, type=11, cpp_type=10, label=1, has_default_value=False, default_value=None, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key, ), _descriptor.FieldDescriptor( name="confidence", full_name="google.cloud.videointelligence.v1.TextSegment.confidence", index=1, number=2, type=2, cpp_type=6, label=1, has_default_value=False, default_value=float(0), message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key, ), _descriptor.FieldDescriptor( name="frames", full_name="google.cloud.videointelligence.v1.TextSegment.frames", index=2, number=3, type=11, cpp_type=10, label=3, has_default_value=False, default_value=[], message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key, ), ], extensions=[], nested_types=[], enum_types=[], serialized_options=None, is_extendable=False, syntax="proto3", extension_ranges=[], oneofs=[], serialized_start=7333, serialized_end=7494, ) _TEXTFRAME = _descriptor.Descriptor( name="TextFrame", full_name="google.cloud.videointelligence.v1.TextFrame", filename=None, file=DESCRIPTOR, containing_type=None, create_key=_descriptor._internal_create_key, fields=[ _descriptor.FieldDescriptor( name="rotated_bounding_box", full_name="google.cloud.videointelligence.v1.TextFrame.rotated_bounding_box", index=0, number=1, type=11, cpp_type=10, label=1, has_default_value=False, default_value=None, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key, ), _descriptor.FieldDescriptor( name="time_offset", full_name="google.cloud.videointelligence.v1.TextFrame.time_offset", index=1, number=2, type=11, cpp_type=10, label=1, has_default_value=False, default_value=None, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key, ), ], extensions=[], nested_types=[], enum_types=[], serialized_options=None, is_extendable=False, syntax="proto3", extension_ranges=[], oneofs=[], serialized_start=7497, serialized_end=7645, ) _TEXTANNOTATION = _descriptor.Descriptor( name="TextAnnotation", full_name="google.cloud.videointelligence.v1.TextAnnotation", filename=None, file=DESCRIPTOR, containing_type=None, create_key=_descriptor._internal_create_key, fields=[ _descriptor.FieldDescriptor( name="text", full_name="google.cloud.videointelligence.v1.TextAnnotation.text", index=0, number=1, type=9, cpp_type=9, label=1, has_default_value=False, default_value=b"".decode("utf-8"), message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key, ), _descriptor.FieldDescriptor( name="segments", full_name="google.cloud.videointelligence.v1.TextAnnotation.segments", index=1, number=2, type=11, cpp_type=10, label=3, has_default_value=False, default_value=[], message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key, ), _descriptor.FieldDescriptor( name="version", full_name="google.cloud.videointelligence.v1.TextAnnotation.version", index=2, number=3, type=9, cpp_type=9, label=1, has_default_value=False, default_value=b"".decode("utf-8"), message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key, ), ], extensions=[], nested_types=[], enum_types=[], serialized_options=None, is_extendable=False, syntax="proto3", extension_ranges=[], oneofs=[], serialized_start=7647, serialized_end=7760, ) _OBJECTTRACKINGFRAME = _descriptor.Descriptor( name="ObjectTrackingFrame", full_name="google.cloud.videointelligence.v1.ObjectTrackingFrame", filename=None, file=DESCRIPTOR, containing_type=None, create_key=_descriptor._internal_create_key, fields=[ _descriptor.FieldDescriptor( name="normalized_bounding_box", full_name="google.cloud.videointelligence.v1.ObjectTrackingFrame.normalized_bounding_box", index=0, number=1, type=11, cpp_type=10, label=1, has_default_value=False, default_value=None, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key, ), _descriptor.FieldDescriptor( name="time_offset", full_name="google.cloud.videointelligence.v1.ObjectTrackingFrame.time_offset", index=1, number=2, type=11, cpp_type=10, label=1, has_default_value=False, default_value=None, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key, ), ], extensions=[], nested_types=[], enum_types=[], serialized_options=None, is_extendable=False, syntax="proto3", extension_ranges=[], oneofs=[], serialized_start=7763, serialized_end=7923, ) _OBJECTTRACKINGANNOTATION = _descriptor.Descriptor( name="ObjectTrackingAnnotation", full_name="google.cloud.videointelligence.v1.ObjectTrackingAnnotation", filename=None, file=DESCRIPTOR, containing_type=None, create_key=_descriptor._internal_create_key, fields=[ _descriptor.FieldDescriptor( name="segment", full_name="google.cloud.videointelligence.v1.ObjectTrackingAnnotation.segment", index=0, number=3, type=11, cpp_type=10, label=1, has_default_value=False, default_value=None, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key, ), _descriptor.FieldDescriptor( name="track_id", full_name="google.cloud.videointelligence.v1.ObjectTrackingAnnotation.track_id", index=1, number=5, type=3, cpp_type=2, label=1, has_default_value=False, default_value=0, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key, ), _descriptor.FieldDescriptor( name="entity", full_name="google.cloud.videointelligence.v1.ObjectTrackingAnnotation.entity", index=2, number=1, type=11, cpp_type=10, label=1, has_default_value=False, default_value=None, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key, ), _descriptor.FieldDescriptor( name="confidence", full_name="google.cloud.videointelligence.v1.ObjectTrackingAnnotation.confidence", index=3, number=4, type=2, cpp_type=6, label=1, has_default_value=False, default_value=float(0), message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key, ), _descriptor.FieldDescriptor( name="frames", full_name="google.cloud.videointelligence.v1.ObjectTrackingAnnotation.frames", index=4, number=2, type=11, cpp_type=10, label=3, has_default_value=False, default_value=[], message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key, ), _descriptor.FieldDescriptor( name="version", full_name="google.cloud.videointelligence.v1.ObjectTrackingAnnotation.version", index=5, number=6, type=9, cpp_type=9, label=1, has_default_value=False, default_value=b"".decode("utf-8"), message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key, ), ], extensions=[], nested_types=[], enum_types=[], serialized_options=None, is_extendable=False, syntax="proto3", extension_ranges=[], oneofs=[ _descriptor.OneofDescriptor( name="track_info", full_name="google.cloud.videointelligence.v1.ObjectTrackingAnnotation.track_info", index=0, containing_type=None, create_key=_descriptor._internal_create_key, fields=[], ), ], serialized_start=7926, serialized_end=8222, ) _LOGORECOGNITIONANNOTATION = _descriptor.Descriptor( name="LogoRecognitionAnnotation", full_name="google.cloud.videointelligence.v1.LogoRecognitionAnnotation", filename=None, file=DESCRIPTOR, containing_type=None, create_key=_descriptor._internal_create_key, fields=[ _descriptor.FieldDescriptor( name="entity", full_name="google.cloud.videointelligence.v1.LogoRecognitionAnnotation.entity", index=0, number=1, type=11, cpp_type=10, label=1, has_default_value=False, default_value=None, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key, ), _descriptor.FieldDescriptor( name="tracks", full_name="google.cloud.videointelligence.v1.LogoRecognitionAnnotation.tracks", index=1, number=2, type=11, cpp_type=10, label=3, has_default_value=False, default_value=[], message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key, ), _descriptor.FieldDescriptor( name="segments", full_name="google.cloud.videointelligence.v1.LogoRecognitionAnnotation.segments", index=2, number=3, type=11, cpp_type=10, label=3, has_default_value=False, default_value=[], message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key, ), ], extensions=[], nested_types=[], enum_types=[], serialized_options=None, is_extendable=False, syntax="proto3", extension_ranges=[], oneofs=[], serialized_start=8225, serialized_end=8436, ) _ANNOTATEVIDEOREQUEST.fields_by_name["features"].enum_type = _FEATURE _ANNOTATEVIDEOREQUEST.fields_by_name["video_context"].message_type = _VIDEOCONTEXT _VIDEOCONTEXT.fields_by_name["segments"].message_type = _VIDEOSEGMENT _VIDEOCONTEXT.fields_by_name[ "label_detection_config" ].message_type = _LABELDETECTIONCONFIG _VIDEOCONTEXT.fields_by_name[ "shot_change_detection_config" ].message_type = _SHOTCHANGEDETECTIONCONFIG _VIDEOCONTEXT.fields_by_name[ "explicit_content_detection_config" ].message_type = _EXPLICITCONTENTDETECTIONCONFIG _VIDEOCONTEXT.fields_by_name[ "face_detection_config" ].message_type = _FACEDETECTIONCONFIG _VIDEOCONTEXT.fields_by_name[ "speech_transcription_config" ].message_type = _SPEECHTRANSCRIPTIONCONFIG _VIDEOCONTEXT.fields_by_name[ "text_detection_config" ].message_type = _TEXTDETECTIONCONFIG _VIDEOCONTEXT.fields_by_name[ "person_detection_config" ].message_type = _PERSONDETECTIONCONFIG _VIDEOCONTEXT.fields_by_name[ "object_tracking_config" ].message_type = _OBJECTTRACKINGCONFIG _LABELDETECTIONCONFIG.fields_by_name[ "label_detection_mode" ].enum_type = _LABELDETECTIONMODE _VIDEOSEGMENT.fields_by_name[ "start_time_offset" ].message_type = google_dot_protobuf_dot_duration__pb2._DURATION _VIDEOSEGMENT.fields_by_name[ "end_time_offset" ].message_type = google_dot_protobuf_dot_duration__pb2._DURATION _LABELSEGMENT.fields_by_name["segment"].message_type = _VIDEOSEGMENT _LABELFRAME.fields_by_name[ "time_offset" ].message_type = google_dot_protobuf_dot_duration__pb2._DURATION _LABELANNOTATION.fields_by_name["entity"].message_type = _ENTITY _LABELANNOTATION.fields_by_name["category_entities"].message_type = _ENTITY _LABELANNOTATION.fields_by_name["segments"].message_type = _LABELSEGMENT _LABELANNOTATION.fields_by_name["frames"].message_type = _LABELFRAME _EXPLICITCONTENTFRAME.fields_by_name[ "time_offset" ].message_type = google_dot_protobuf_dot_duration__pb2._DURATION _EXPLICITCONTENTFRAME.fields_by_name["pornography_likelihood"].enum_type = _LIKELIHOOD _EXPLICITCONTENTANNOTATION.fields_by_name["frames"].message_type = _EXPLICITCONTENTFRAME _PERSONDETECTIONANNOTATION.fields_by_name["tracks"].message_type = _TRACK _FACESEGMENT.fields_by_name["segment"].message_type = _VIDEOSEGMENT _FACEFRAME.fields_by_name[ "normalized_bounding_boxes" ].message_type = _NORMALIZEDBOUNDINGBOX _FACEFRAME.fields_by_name[ "time_offset" ].message_type = google_dot_protobuf_dot_duration__pb2._DURATION _FACEANNOTATION.fields_by_name["segments"].message_type = _FACESEGMENT _FACEANNOTATION.fields_by_name["frames"].message_type = _FACEFRAME _TIMESTAMPEDOBJECT.fields_by_name[ "normalized_bounding_box" ].message_type = _NORMALIZEDBOUNDINGBOX _TIMESTAMPEDOBJECT.fields_by_name[ "time_offset" ].message_type = google_dot_protobuf_dot_duration__pb2._DURATION _TIMESTAMPEDOBJECT.fields_by_name["attributes"].message_type = _DETECTEDATTRIBUTE _TIMESTAMPEDOBJECT.fields_by_name["landmarks"].message_type = _DETECTEDLANDMARK _TRACK.fields_by_name["segment"].message_type = _VIDEOSEGMENT _TRACK.fields_by_name["timestamped_objects"].message_type = _TIMESTAMPEDOBJECT _TRACK.fields_by_name["attributes"].message_type = _DETECTEDATTRIBUTE _DETECTEDLANDMARK.fields_by_name["point"].message_type = _NORMALIZEDVERTEX _VIDEOANNOTATIONRESULTS.fields_by_name["segment"].message_type = _VIDEOSEGMENT _VIDEOANNOTATIONRESULTS.fields_by_name[ "segment_label_annotations" ].message_type = _LABELANNOTATION _VIDEOANNOTATIONRESULTS.fields_by_name[ "segment_presence_label_annotations" ].message_type = _LABELANNOTATION _VIDEOANNOTATIONRESULTS.fields_by_name[ "shot_label_annotations" ].message_type = _LABELANNOTATION _VIDEOANNOTATIONRESULTS.fields_by_name[ "shot_presence_label_annotations" ].message_type = _LABELANNOTATION _VIDEOANNOTATIONRESULTS.fields_by_name[ "frame_label_annotations" ].message_type = _LABELANNOTATION _VIDEOANNOTATIONRESULTS.fields_by_name[ "face_annotations" ].message_type = _FACEANNOTATION _VIDEOANNOTATIONRESULTS.fields_by_name[ "face_detection_annotations" ].message_type = _FACEDETECTIONANNOTATION _VIDEOANNOTATIONRESULTS.fields_by_name["shot_annotations"].message_type = _VIDEOSEGMENT _VIDEOANNOTATIONRESULTS.fields_by_name[ "explicit_annotation" ].message_type = _EXPLICITCONTENTANNOTATION _VIDEOANNOTATIONRESULTS.fields_by_name[ "speech_transcriptions" ].message_type = _SPEECHTRANSCRIPTION _VIDEOANNOTATIONRESULTS.fields_by_name[ "text_annotations" ].message_type = _TEXTANNOTATION _VIDEOANNOTATIONRESULTS.fields_by_name[ "object_annotations" ].message_type = _OBJECTTRACKINGANNOTATION _VIDEOANNOTATIONRESULTS.fields_by_name[ "logo_recognition_annotations" ].message_type = _LOGORECOGNITIONANNOTATION _VIDEOANNOTATIONRESULTS.fields_by_name[ "person_detection_annotations" ].message_type = _PERSONDETECTIONANNOTATION _VIDEOANNOTATIONRESULTS.fields_by_name[ "error" ].message_type = google_dot_rpc_dot_status__pb2._STATUS _ANNOTATEVIDEORESPONSE.fields_by_name[ "annotation_results" ].message_type = _VIDEOANNOTATIONRESULTS _VIDEOANNOTATIONPROGRESS.fields_by_name[ "start_time" ].message_type = google_dot_protobuf_dot_timestamp__pb2._TIMESTAMP _VIDEOANNOTATIONPROGRESS.fields_by_name[ "update_time" ].message_type = google_dot_protobuf_dot_timestamp__pb2._TIMESTAMP _VIDEOANNOTATIONPROGRESS.fields_by_name["feature"].enum_type = _FEATURE _VIDEOANNOTATIONPROGRESS.fields_by_name["segment"].message_type = _VIDEOSEGMENT _ANNOTATEVIDEOPROGRESS.fields_by_name[ "annotation_progress" ].message_type = _VIDEOANNOTATIONPROGRESS _SPEECHTRANSCRIPTIONCONFIG.fields_by_name[ "speech_contexts" ].message_type = _SPEECHCONTEXT _SPEECHTRANSCRIPTION.fields_by_name[ "alternatives" ].message_type = _SPEECHRECOGNITIONALTERNATIVE _SPEECHRECOGNITIONALTERNATIVE.fields_by_name["words"].message_type = _WORDINFO _WORDINFO.fields_by_name[ "start_time" ].message_type = google_dot_protobuf_dot_duration__pb2._DURATION _WORDINFO.fields_by_name[ "end_time" ].message_type = google_dot_protobuf_dot_duration__pb2._DURATION _NORMALIZEDBOUNDINGPOLY.fields_by_name["vertices"].message_type = _NORMALIZEDVERTEX _TEXTSEGMENT.fields_by_name["segment"].message_type = _VIDEOSEGMENT _TEXTSEGMENT.fields_by_name["frames"].message_type = _TEXTFRAME _TEXTFRAME.fields_by_name["rotated_bounding_box"].message_type = _NORMALIZEDBOUNDINGPOLY _TEXTFRAME.fields_by_name[ "time_offset" ].message_type = google_dot_protobuf_dot_duration__pb2._DURATION _TEXTANNOTATION.fields_by_name["segments"].message_type = _TEXTSEGMENT _OBJECTTRACKINGFRAME.fields_by_name[ "normalized_bounding_box" ].message_type = _NORMALIZEDBOUNDINGBOX _OBJECTTRACKINGFRAME.fields_by_name[ "time_offset" ].message_type = google_dot_protobuf_dot_duration__pb2._DURATION _OBJECTTRACKINGANNOTATION.fields_by_name["segment"].message_type = _VIDEOSEGMENT _OBJECTTRACKINGANNOTATION.fields_by_name["entity"].message_type = _ENTITY _OBJECTTRACKINGANNOTATION.fields_by_name["frames"].message_type = _OBJECTTRACKINGFRAME _OBJECTTRACKINGANNOTATION.oneofs_by_name["track_info"].fields.append( _OBJECTTRACKINGANNOTATION.fields_by_name["segment"] ) _OBJECTTRACKINGANNOTATION.fields_by_name[ "segment" ].containing_oneof = _OBJECTTRACKINGANNOTATION.oneofs_by_name["track_info"] _OBJECTTRACKINGANNOTATION.oneofs_by_name["track_info"].fields.append( _OBJECTTRACKINGANNOTATION.fields_by_name["track_id"] ) _OBJECTTRACKINGANNOTATION.fields_by_name[ "track_id" ].containing_oneof = _OBJECTTRACKINGANNOTATION.oneofs_by_name["track_info"] _LOGORECOGNITIONANNOTATION.fields_by_name["entity"].message_type = _ENTITY _LOGORECOGNITIONANNOTATION.fields_by_name["tracks"].message_type = _TRACK _LOGORECOGNITIONANNOTATION.fields_by_name["segments"].message_type = _VIDEOSEGMENT DESCRIPTOR.message_types_by_name["AnnotateVideoRequest"] = _ANNOTATEVIDEOREQUEST DESCRIPTOR.message_types_by_name["VideoContext"] = _VIDEOCONTEXT DESCRIPTOR.message_types_by_name["LabelDetectionConfig"] = _LABELDETECTIONCONFIG DESCRIPTOR.message_types_by_name[ "ShotChangeDetectionConfig" ] = _SHOTCHANGEDETECTIONCONFIG DESCRIPTOR.message_types_by_name["ObjectTrackingConfig"] = _OBJECTTRACKINGCONFIG DESCRIPTOR.message_types_by_name["FaceDetectionConfig"] = _FACEDETECTIONCONFIG DESCRIPTOR.message_types_by_name["PersonDetectionConfig"] = _PERSONDETECTIONCONFIG DESCRIPTOR.message_types_by_name[ "ExplicitContentDetectionConfig" ] = _EXPLICITCONTENTDETECTIONCONFIG DESCRIPTOR.message_types_by_name["TextDetectionConfig"] = _TEXTDETECTIONCONFIG DESCRIPTOR.message_types_by_name["VideoSegment"] = _VIDEOSEGMENT DESCRIPTOR.message_types_by_name["LabelSegment"] = _LABELSEGMENT DESCRIPTOR.message_types_by_name["LabelFrame"] = _LABELFRAME DESCRIPTOR.message_types_by_name["Entity"] = _ENTITY DESCRIPTOR.message_types_by_name["LabelAnnotation"] = _LABELANNOTATION DESCRIPTOR.message_types_by_name["ExplicitContentFrame"] = _EXPLICITCONTENTFRAME DESCRIPTOR.message_types_by_name[ "ExplicitContentAnnotation" ] = _EXPLICITCONTENTANNOTATION DESCRIPTOR.message_types_by_name["NormalizedBoundingBox"] = _NORMALIZEDBOUNDINGBOX DESCRIPTOR.message_types_by_name["FaceDetectionAnnotation"] = _FACEDETECTIONANNOTATION DESCRIPTOR.message_types_by_name[ "PersonDetectionAnnotation" ] = _PERSONDETECTIONANNOTATION DESCRIPTOR.message_types_by_name["FaceSegment"] = _FACESEGMENT DESCRIPTOR.message_types_by_name["FaceFrame"] = _FACEFRAME DESCRIPTOR.message_types_by_name["FaceAnnotation"] = _FACEANNOTATION DESCRIPTOR.message_types_by_name["TimestampedObject"] = _TIMESTAMPEDOBJECT DESCRIPTOR.message_types_by_name["Track"] = _TRACK DESCRIPTOR.message_types_by_name["DetectedAttribute"] = _DETECTEDATTRIBUTE DESCRIPTOR.message_types_by_name["DetectedLandmark"] = _DETECTEDLANDMARK DESCRIPTOR.message_types_by_name["VideoAnnotationResults"] = _VIDEOANNOTATIONRESULTS DESCRIPTOR.message_types_by_name["AnnotateVideoResponse"] = _ANNOTATEVIDEORESPONSE DESCRIPTOR.message_types_by_name["VideoAnnotationProgress"] = _VIDEOANNOTATIONPROGRESS DESCRIPTOR.message_types_by_name["AnnotateVideoProgress"] = _ANNOTATEVIDEOPROGRESS DESCRIPTOR.message_types_by_name[ "SpeechTranscriptionConfig" ] = _SPEECHTRANSCRIPTIONCONFIG DESCRIPTOR.message_types_by_name["SpeechContext"] = _SPEECHCONTEXT DESCRIPTOR.message_types_by_name["SpeechTranscription"] = _SPEECHTRANSCRIPTION DESCRIPTOR.message_types_by_name[ "SpeechRecognitionAlternative" ] = _SPEECHRECOGNITIONALTERNATIVE DESCRIPTOR.message_types_by_name["WordInfo"] = _WORDINFO DESCRIPTOR.message_types_by_name["NormalizedVertex"] = _NORMALIZEDVERTEX DESCRIPTOR.message_types_by_name["NormalizedBoundingPoly"] = _NORMALIZEDBOUNDINGPOLY DESCRIPTOR.message_types_by_name["TextSegment"] = _TEXTSEGMENT DESCRIPTOR.message_types_by_name["TextFrame"] = _TEXTFRAME DESCRIPTOR.message_types_by_name["TextAnnotation"] = _TEXTANNOTATION DESCRIPTOR.message_types_by_name["ObjectTrackingFrame"] = _OBJECTTRACKINGFRAME DESCRIPTOR.message_types_by_name["ObjectTrackingAnnotation"] = _OBJECTTRACKINGANNOTATION DESCRIPTOR.message_types_by_name[ "LogoRecognitionAnnotation" ] = _LOGORECOGNITIONANNOTATION DESCRIPTOR.enum_types_by_name["Feature"] = _FEATURE DESCRIPTOR.enum_types_by_name["LabelDetectionMode"] = _LABELDETECTIONMODE DESCRIPTOR.enum_types_by_name["Likelihood"] = _LIKELIHOOD _sym_db.RegisterFileDescriptor(DESCRIPTOR) AnnotateVideoRequest = _reflection.GeneratedProtocolMessageType( "AnnotateVideoRequest", (_message.Message,), { "DESCRIPTOR": _ANNOTATEVIDEOREQUEST, "__module__": "google.cloud.videointelligence_v1.proto.video_intelligence_pb2", "__doc__": """Video annotation request. Attributes: input_uri: Input video location. Currently, only `Cloud Storage <https://cloud.google.com/storage/>`__ URIs are supported. URIs must be specified in the following format: ``gs://bucket- id/object-id`` (other URI formats return [google.rpc.Code.INVA LID_ARGUMENT][google.rpc.Code.INVALID_ARGUMENT]). For more information, see `Request URIs <https://cloud.google.com/storage/docs/request-endpoints>`__. To identify multiple videos, a video URI may include wildcards in the ``object-id``. Supported wildcards: ’*’ to match 0 or more characters; ‘?’ to match 1 character. If unset, the input video should be embedded in the request as ``input_content``. If set, ``input_content`` must be unset. input_content: The video data bytes. If unset, the input video(s) should be specified via the ``input_uri``. If set, ``input_uri`` must be unset. features: Required. Requested video annotation features. video_context: Additional video context and/or feature-specific parameters. output_uri: Optional. Location where the output (in JSON format) should be stored. Currently, only `Cloud Storage <https://cloud.google.com/storage/>`__ URIs are supported. These must be specified in the following format: ``gs://bucket-id/object-id`` (other URI formats return [google .rpc.Code.INVALID_ARGUMENT][google.rpc.Code.INVALID_ARGUMENT]) . For more information, see `Request URIs <https://cloud.google.com/storage/docs/request-endpoints>`__. location_id: Optional. Cloud region where annotation should take place. Supported cloud regions are: ``us-east1``, ``us-west1``, ``europe-west1``, ``asia-east1``. If no region is specified, the region will be determined based on video file location. """, # @@protoc_insertion_point(class_scope:google.cloud.videointelligence.v1.AnnotateVideoRequest) }, ) _sym_db.RegisterMessage(AnnotateVideoRequest) VideoContext = _reflection.GeneratedProtocolMessageType( "VideoContext", (_message.Message,), { "DESCRIPTOR": _VIDEOCONTEXT, "__module__": "google.cloud.videointelligence_v1.proto.video_intelligence_pb2", "__doc__": """Video context and/or feature-specific parameters. Attributes: segments: Video segments to annotate. The segments may overlap and are not required to be contiguous or span the whole video. If unspecified, each video is treated as a single segment. label_detection_config: Config for LABEL_DETECTION. shot_change_detection_config: Config for SHOT_CHANGE_DETECTION. explicit_content_detection_config: Config for EXPLICIT_CONTENT_DETECTION. face_detection_config: Config for FACE_DETECTION. speech_transcription_config: Config for SPEECH_TRANSCRIPTION. text_detection_config: Config for TEXT_DETECTION. person_detection_config: Config for PERSON_DETECTION. object_tracking_config: Config for OBJECT_TRACKING. """, # @@protoc_insertion_point(class_scope:google.cloud.videointelligence.v1.VideoContext) }, ) _sym_db.RegisterMessage(VideoContext) LabelDetectionConfig = _reflection.GeneratedProtocolMessageType( "LabelDetectionConfig", (_message.Message,), { "DESCRIPTOR": _LABELDETECTIONCONFIG, "__module__": "google.cloud.videointelligence_v1.proto.video_intelligence_pb2", "__doc__": """Config for LABEL_DETECTION. Attributes: label_detection_mode: What labels should be detected with LABEL_DETECTION, in addition to video-level labels or segment-level labels. If unspecified, defaults to ``SHOT_MODE``. stationary_camera: Whether the video has been shot from a stationary (i.e., non- moving) camera. When set to true, might improve detection accuracy for moving objects. Should be used with ``SHOT_AND_FRAME_MODE`` enabled. model: Model to use for label detection. Supported values: “builtin/stable” (the default if unset) and “builtin/latest”. frame_confidence_threshold: The confidence threshold we perform filtering on the labels from frame-level detection. If not set, it is set to 0.4 by default. The valid range for this threshold is [0.1, 0.9]. Any value set outside of this range will be clipped. Note: For best results, follow the default threshold. We will update the default threshold everytime when we release a new model. video_confidence_threshold: The confidence threshold we perform filtering on the labels from video-level and shot-level detections. If not set, it’s set to 0.3 by default. The valid range for this threshold is [0.1, 0.9]. Any value set outside of this range will be clipped. Note: For best results, follow the default threshold. We will update the default threshold everytime when we release a new model. """, # @@protoc_insertion_point(class_scope:google.cloud.videointelligence.v1.LabelDetectionConfig) }, ) _sym_db.RegisterMessage(LabelDetectionConfig) ShotChangeDetectionConfig = _reflection.GeneratedProtocolMessageType( "ShotChangeDetectionConfig", (_message.Message,), { "DESCRIPTOR": _SHOTCHANGEDETECTIONCONFIG, "__module__": "google.cloud.videointelligence_v1.proto.video_intelligence_pb2", "__doc__": """Config for SHOT_CHANGE_DETECTION. Attributes: model: Model to use for shot change detection. Supported values: “builtin/stable” (the default if unset) and “builtin/latest”. """, # @@protoc_insertion_point(class_scope:google.cloud.videointelligence.v1.ShotChangeDetectionConfig) }, ) _sym_db.RegisterMessage(ShotChangeDetectionConfig) ObjectTrackingConfig = _reflection.GeneratedProtocolMessageType( "ObjectTrackingConfig", (_message.Message,), { "DESCRIPTOR": _OBJECTTRACKINGCONFIG, "__module__": "google.cloud.videointelligence_v1.proto.video_intelligence_pb2", "__doc__": """Config for OBJECT_TRACKING. Attributes: model: Model to use for object tracking. Supported values: “builtin/stable” (the default if unset) and “builtin/latest”. """, # @@protoc_insertion_point(class_scope:google.cloud.videointelligence.v1.ObjectTrackingConfig) }, ) _sym_db.RegisterMessage(ObjectTrackingConfig) FaceDetectionConfig = _reflection.GeneratedProtocolMessageType( "FaceDetectionConfig", (_message.Message,), { "DESCRIPTOR": _FACEDETECTIONCONFIG, "__module__": "google.cloud.videointelligence_v1.proto.video_intelligence_pb2", "__doc__": """Config for FACE_DETECTION. Attributes: model: Model to use for face detection. Supported values: “builtin/stable” (the default if unset) and “builtin/latest”. include_bounding_boxes: Whether bounding boxes are included in the face annotation output. include_attributes: Whether to enable face attributes detection, such as glasses, dark_glasses, mouth_open etc. Ignored if ‘include_bounding_boxes’ is set to false. """, # @@protoc_insertion_point(class_scope:google.cloud.videointelligence.v1.FaceDetectionConfig) }, ) _sym_db.RegisterMessage(FaceDetectionConfig) PersonDetectionConfig = _reflection.GeneratedProtocolMessageType( "PersonDetectionConfig", (_message.Message,), { "DESCRIPTOR": _PERSONDETECTIONCONFIG, "__module__": "google.cloud.videointelligence_v1.proto.video_intelligence_pb2", "__doc__": """Config for PERSON_DETECTION. Attributes: include_bounding_boxes: Whether bounding boxes are included in the person detection annotation output. include_pose_landmarks: Whether to enable pose landmarks detection. Ignored if ‘include_bounding_boxes’ is set to false. include_attributes: Whether to enable person attributes detection, such as cloth color (black, blue, etc), type (coat, dress, etc), pattern (plain, floral, etc), hair, etc. Ignored if ‘include_bounding_boxes’ is set to false. """, # @@protoc_insertion_point(class_scope:google.cloud.videointelligence.v1.PersonDetectionConfig) }, ) _sym_db.RegisterMessage(PersonDetectionConfig) ExplicitContentDetectionConfig = _reflection.GeneratedProtocolMessageType( "ExplicitContentDetectionConfig", (_message.Message,), { "DESCRIPTOR": _EXPLICITCONTENTDETECTIONCONFIG, "__module__": "google.cloud.videointelligence_v1.proto.video_intelligence_pb2", "__doc__": """Config for EXPLICIT_CONTENT_DETECTION. Attributes: model: Model to use for explicit content detection. Supported values: “builtin/stable” (the default if unset) and “builtin/latest”. """, # @@protoc_insertion_point(class_scope:google.cloud.videointelligence.v1.ExplicitContentDetectionConfig) }, ) _sym_db.RegisterMessage(ExplicitContentDetectionConfig) TextDetectionConfig = _reflection.GeneratedProtocolMessageType( "TextDetectionConfig", (_message.Message,), { "DESCRIPTOR": _TEXTDETECTIONCONFIG, "__module__": "google.cloud.videointelligence_v1.proto.video_intelligence_pb2", "__doc__": """Config for TEXT_DETECTION. Attributes: language_hints: Language hint can be specified if the language to be detected is known a priori. It can increase the accuracy of the detection. Language hint must be language code in BCP-47 format. Automatic language detection is performed if no hint is provided. model: Model to use for text detection. Supported values: “builtin/stable” (the default if unset) and “builtin/latest”. """, # @@protoc_insertion_point(class_scope:google.cloud.videointelligence.v1.TextDetectionConfig) }, ) _sym_db.RegisterMessage(TextDetectionConfig) VideoSegment = _reflection.GeneratedProtocolMessageType( "VideoSegment", (_message.Message,), { "DESCRIPTOR": _VIDEOSEGMENT, "__module__": "google.cloud.videointelligence_v1.proto.video_intelligence_pb2", "__doc__": """Video segment. Attributes: start_time_offset: Time-offset, relative to the beginning of the video, corresponding to the start of the segment (inclusive). end_time_offset: Time-offset, relative to the beginning of the video, corresponding to the end of the segment (inclusive). """, # @@protoc_insertion_point(class_scope:google.cloud.videointelligence.v1.VideoSegment) }, ) _sym_db.RegisterMessage(VideoSegment) LabelSegment = _reflection.GeneratedProtocolMessageType( "LabelSegment", (_message.Message,), { "DESCRIPTOR": _LABELSEGMENT, "__module__": "google.cloud.videointelligence_v1.proto.video_intelligence_pb2", "__doc__": """Video segment level annotation results for label detection. Attributes: segment: Video segment where a label was detected. confidence: Confidence that the label is accurate. Range: [0, 1]. """, # @@protoc_insertion_point(class_scope:google.cloud.videointelligence.v1.LabelSegment) }, ) _sym_db.RegisterMessage(LabelSegment) LabelFrame = _reflection.GeneratedProtocolMessageType( "LabelFrame", (_message.Message,), { "DESCRIPTOR": _LABELFRAME, "__module__": "google.cloud.videointelligence_v1.proto.video_intelligence_pb2", "__doc__": """Video frame level annotation results for label detection. Attributes: time_offset: Time-offset, relative to the beginning of the video, corresponding to the video frame for this location. confidence: Confidence that the label is accurate. Range: [0, 1]. """, # @@protoc_insertion_point(class_scope:google.cloud.videointelligence.v1.LabelFrame) }, ) _sym_db.RegisterMessage(LabelFrame) Entity = _reflection.GeneratedProtocolMessageType( "Entity", (_message.Message,), { "DESCRIPTOR": _ENTITY, "__module__": "google.cloud.videointelligence_v1.proto.video_intelligence_pb2", "__doc__": """Detected entity from video analysis. Attributes: entity_id: Opaque entity ID. Some IDs may be available in `Google Knowledge Graph Search API <https://developers.google.com/knowledge-graph/>`__. description: Textual description, e.g., ``Fixed-gear bicycle``. language_code: Language code for ``description`` in BCP-47 format. """, # @@protoc_insertion_point(class_scope:google.cloud.videointelligence.v1.Entity) }, ) _sym_db.RegisterMessage(Entity) LabelAnnotation = _reflection.GeneratedProtocolMessageType( "LabelAnnotation", (_message.Message,), { "DESCRIPTOR": _LABELANNOTATION, "__module__": "google.cloud.videointelligence_v1.proto.video_intelligence_pb2", "__doc__": """Label annotation. Attributes: entity: Detected entity. category_entities: Common categories for the detected entity. For example, when the label is ``Terrier``, the category is likely ``dog``. And in some cases there might be more than one categories e.g., ``Terrier`` could also be a ``pet``. segments: All video segments where a label was detected. frames: All video frames where a label was detected. version: Feature version. """, # @@protoc_insertion_point(class_scope:google.cloud.videointelligence.v1.LabelAnnotation) }, ) _sym_db.RegisterMessage(LabelAnnotation) ExplicitContentFrame = _reflection.GeneratedProtocolMessageType( "ExplicitContentFrame", (_message.Message,), { "DESCRIPTOR": _EXPLICITCONTENTFRAME, "__module__": "google.cloud.videointelligence_v1.proto.video_intelligence_pb2", "__doc__": """Video frame level annotation results for explicit content. Attributes: time_offset: Time-offset, relative to the beginning of the video, corresponding to the video frame for this location. pornography_likelihood: Likelihood of the pornography content.. """, # @@protoc_insertion_point(class_scope:google.cloud.videointelligence.v1.ExplicitContentFrame) }, ) _sym_db.RegisterMessage(ExplicitContentFrame) ExplicitContentAnnotation = _reflection.GeneratedProtocolMessageType( "ExplicitContentAnnotation", (_message.Message,), { "DESCRIPTOR": _EXPLICITCONTENTANNOTATION, "__module__": "google.cloud.videointelligence_v1.proto.video_intelligence_pb2", "__doc__": """Explicit content annotation (based on per-frame visual signals only). If no explicit content has been detected in a frame, no annotations are present for that frame. Attributes: frames: All video frames where explicit content was detected. version: Feature version. """, # @@protoc_insertion_point(class_scope:google.cloud.videointelligence.v1.ExplicitContentAnnotation) }, ) _sym_db.RegisterMessage(ExplicitContentAnnotation) NormalizedBoundingBox = _reflection.GeneratedProtocolMessageType( "NormalizedBoundingBox", (_message.Message,), { "DESCRIPTOR": _NORMALIZEDBOUNDINGBOX, "__module__": "google.cloud.videointelligence_v1.proto.video_intelligence_pb2", "__doc__": """Normalized bounding box. The normalized vertex coordinates are relative to the original image. Range: [0, 1]. Attributes: left: Left X coordinate. top: Top Y coordinate. right: Right X coordinate. bottom: Bottom Y coordinate. """, # @@protoc_insertion_point(class_scope:google.cloud.videointelligence.v1.NormalizedBoundingBox) }, ) _sym_db.RegisterMessage(NormalizedBoundingBox) FaceDetectionAnnotation = _reflection.GeneratedProtocolMessageType( "FaceDetectionAnnotation", (_message.Message,), { "DESCRIPTOR": _FACEDETECTIONANNOTATION, "__module__": "google.cloud.videointelligence_v1.proto.video_intelligence_pb2", "__doc__": """Face detection annotation. Attributes: version: Feature version. """, # @@protoc_insertion_point(class_scope:google.cloud.videointelligence.v1.FaceDetectionAnnotation) }, ) _sym_db.RegisterMessage(FaceDetectionAnnotation) PersonDetectionAnnotation = _reflection.GeneratedProtocolMessageType( "PersonDetectionAnnotation", (_message.Message,), { "DESCRIPTOR": _PERSONDETECTIONANNOTATION, "__module__": "google.cloud.videointelligence_v1.proto.video_intelligence_pb2", "__doc__": """Person detection annotation per video. Attributes: tracks: The detected tracks of a person. version: Feature version. """, # @@protoc_insertion_point(class_scope:google.cloud.videointelligence.v1.PersonDetectionAnnotation) }, ) _sym_db.RegisterMessage(PersonDetectionAnnotation) FaceSegment = _reflection.GeneratedProtocolMessageType( "FaceSegment", (_message.Message,), { "DESCRIPTOR": _FACESEGMENT, "__module__": "google.cloud.videointelligence_v1.proto.video_intelligence_pb2", "__doc__": """Video segment level annotation results for face detection. Attributes: segment: Video segment where a face was detected. """, # @@protoc_insertion_point(class_scope:google.cloud.videointelligence.v1.FaceSegment) }, ) _sym_db.RegisterMessage(FaceSegment) FaceFrame = _reflection.GeneratedProtocolMessageType( "FaceFrame", (_message.Message,), { "DESCRIPTOR": _FACEFRAME, "__module__": "google.cloud.videointelligence_v1.proto.video_intelligence_pb2", "__doc__": """Deprecated. No effect. Attributes: normalized_bounding_boxes: Normalized Bounding boxes in a frame. There can be more than one boxes if the same face is detected in multiple locations within the current frame. time_offset: Time-offset, relative to the beginning of the video, corresponding to the video frame for this location. """, # @@protoc_insertion_point(class_scope:google.cloud.videointelligence.v1.FaceFrame) }, ) _sym_db.RegisterMessage(FaceFrame) FaceAnnotation = _reflection.GeneratedProtocolMessageType( "FaceAnnotation", (_message.Message,), { "DESCRIPTOR": _FACEANNOTATION, "__module__": "google.cloud.videointelligence_v1.proto.video_intelligence_pb2", "__doc__": """Deprecated. No effect. Attributes: thumbnail: Thumbnail of a representative face view (in JPEG format). segments: All video segments where a face was detected. frames: All video frames where a face was detected. """, # @@protoc_insertion_point(class_scope:google.cloud.videointelligence.v1.FaceAnnotation) }, ) _sym_db.RegisterMessage(FaceAnnotation) TimestampedObject = _reflection.GeneratedProtocolMessageType( "TimestampedObject", (_message.Message,), { "DESCRIPTOR": _TIMESTAMPEDOBJECT, "__module__": "google.cloud.videointelligence_v1.proto.video_intelligence_pb2", "__doc__": """For tracking related features. An object at time_offset with attributes, and located with normalized_bounding_box. Attributes: normalized_bounding_box: Normalized Bounding box in a frame, where the object is located. time_offset: Time-offset, relative to the beginning of the video, corresponding to the video frame for this object. attributes: Optional. The attributes of the object in the bounding box. landmarks: Optional. The detected landmarks. """, # @@protoc_insertion_point(class_scope:google.cloud.videointelligence.v1.TimestampedObject) }, ) _sym_db.RegisterMessage(TimestampedObject) Track = _reflection.GeneratedProtocolMessageType( "Track", (_message.Message,), { "DESCRIPTOR": _TRACK, "__module__": "google.cloud.videointelligence_v1.proto.video_intelligence_pb2", "__doc__": """A track of an object instance. Attributes: segment: Video segment of a track. timestamped_objects: The object with timestamp and attributes per frame in the track. attributes: Optional. Attributes in the track level. confidence: Optional. The confidence score of the tracked object. """, # @@protoc_insertion_point(class_scope:google.cloud.videointelligence.v1.Track) }, ) _sym_db.RegisterMessage(Track) DetectedAttribute = _reflection.GeneratedProtocolMessageType( "DetectedAttribute", (_message.Message,), { "DESCRIPTOR": _DETECTEDATTRIBUTE, "__module__": "google.cloud.videointelligence_v1.proto.video_intelligence_pb2", "__doc__": """A generic detected attribute represented by name in string format. Attributes: name: The name of the attribute, for example, glasses, dark_glasses, mouth_open. A full list of supported type names will be provided in the document. confidence: Detected attribute confidence. Range [0, 1]. value: Text value of the detection result. For example, the value for “HairColor” can be “black”, “blonde”, etc. """, # @@protoc_insertion_point(class_scope:google.cloud.videointelligence.v1.DetectedAttribute) }, ) _sym_db.RegisterMessage(DetectedAttribute) DetectedLandmark = _reflection.GeneratedProtocolMessageType( "DetectedLandmark", (_message.Message,), { "DESCRIPTOR": _DETECTEDLANDMARK, "__module__": "google.cloud.videointelligence_v1.proto.video_intelligence_pb2", "__doc__": """A generic detected landmark represented by name in string format and a 2D location. Attributes: name: The name of this landmark, for example, left_hand, right_shoulder. point: The 2D point of the detected landmark using the normalized image coordindate system. The normalized coordinates have the range from 0 to 1. confidence: The confidence score of the detected landmark. Range [0, 1]. """, # @@protoc_insertion_point(class_scope:google.cloud.videointelligence.v1.DetectedLandmark) }, ) _sym_db.RegisterMessage(DetectedLandmark) VideoAnnotationResults = _reflection.GeneratedProtocolMessageType( "VideoAnnotationResults", (_message.Message,), { "DESCRIPTOR": _VIDEOANNOTATIONRESULTS, "__module__": "google.cloud.videointelligence_v1.proto.video_intelligence_pb2", "__doc__": """Annotation results for a single video. Attributes: input_uri: Video file location in `Cloud Storage <https://cloud.google.com/storage/>`__. segment: Video segment on which the annotation is run. segment_label_annotations: Topical label annotations on video level or user-specified segment level. There is exactly one element for each unique label. segment_presence_label_annotations: Presence label annotations on video level or user-specified segment level. There is exactly one element for each unique label. Compared to the existing topical ``segment_label_annotations``, this field presents more fine- grained, segment-level labels detected in video content and is made available only when the client sets ``LabelDetectionConfig.model`` to “builtin/latest” in the request. shot_label_annotations: Topical label annotations on shot level. There is exactly one element for each unique label. shot_presence_label_annotations: Presence label annotations on shot level. There is exactly one element for each unique label. Compared to the existing topical ``shot_label_annotations``, this field presents more fine-grained, shot-level labels detected in video content and is made available only when the client sets ``LabelDetectionConfig.model`` to “builtin/latest” in the request. frame_label_annotations: Label annotations on frame level. There is exactly one element for each unique label. face_annotations: Deprecated. Please use ``face_detection_annotations`` instead. face_detection_annotations: Face detection annotations. shot_annotations: Shot annotations. Each shot is represented as a video segment. explicit_annotation: Explicit content annotation. speech_transcriptions: Speech transcription. text_annotations: OCR text detection and tracking. Annotations for list of detected text snippets. Each will have list of frame information associated with it. object_annotations: Annotations for list of objects detected and tracked in video. logo_recognition_annotations: Annotations for list of logos detected, tracked and recognized in video. person_detection_annotations: Person detection annotations. error: If set, indicates an error. Note that for a single ``AnnotateVideoRequest`` some videos may succeed and some may fail. """, # @@protoc_insertion_point(class_scope:google.cloud.videointelligence.v1.VideoAnnotationResults) }, ) _sym_db.RegisterMessage(VideoAnnotationResults) AnnotateVideoResponse = _reflection.GeneratedProtocolMessageType( "AnnotateVideoResponse", (_message.Message,), { "DESCRIPTOR": _ANNOTATEVIDEORESPONSE, "__module__": "google.cloud.videointelligence_v1.proto.video_intelligence_pb2", "__doc__": """Video annotation response. Included in the ``response`` field of the ``Operation`` returned by the ``GetOperation`` call of the ``google::longrunning::Operations`` service. Attributes: annotation_results: Annotation results for all videos specified in ``AnnotateVideoRequest``. """, # @@protoc_insertion_point(class_scope:google.cloud.videointelligence.v1.AnnotateVideoResponse) }, ) _sym_db.RegisterMessage(AnnotateVideoResponse) VideoAnnotationProgress = _reflection.GeneratedProtocolMessageType( "VideoAnnotationProgress", (_message.Message,), { "DESCRIPTOR": _VIDEOANNOTATIONPROGRESS, "__module__": "google.cloud.videointelligence_v1.proto.video_intelligence_pb2", "__doc__": """Annotation progress for a single video. Attributes: input_uri: Video file location in `Cloud Storage <https://cloud.google.com/storage/>`__. progress_percent: Approximate percentage processed thus far. Guaranteed to be 100 when fully processed. start_time: Time when the request was received. update_time: Time of the most recent update. feature: Specifies which feature is being tracked if the request contains more than one feature. segment: Specifies which segment is being tracked if the request contains more than one segment. """, # @@protoc_insertion_point(class_scope:google.cloud.videointelligence.v1.VideoAnnotationProgress) }, ) _sym_db.RegisterMessage(VideoAnnotationProgress) AnnotateVideoProgress = _reflection.GeneratedProtocolMessageType( "AnnotateVideoProgress", (_message.Message,), { "DESCRIPTOR": _ANNOTATEVIDEOPROGRESS, "__module__": "google.cloud.videointelligence_v1.proto.video_intelligence_pb2", "__doc__": """Video annotation progress. Included in the ``metadata`` field of the ``Operation`` returned by the ``GetOperation`` call of the ``google::longrunning::Operations`` service. Attributes: annotation_progress: Progress metadata for all videos specified in ``AnnotateVideoRequest``. """, # @@protoc_insertion_point(class_scope:google.cloud.videointelligence.v1.AnnotateVideoProgress) }, ) _sym_db.RegisterMessage(AnnotateVideoProgress) SpeechTranscriptionConfig = _reflection.GeneratedProtocolMessageType( "SpeechTranscriptionConfig", (_message.Message,), { "DESCRIPTOR": _SPEECHTRANSCRIPTIONCONFIG, "__module__": "google.cloud.videointelligence_v1.proto.video_intelligence_pb2", "__doc__": """Config for SPEECH_TRANSCRIPTION. Attributes: language_code: Required. *Required* The language of the supplied audio as a `BCP-47 <https://www.rfc-editor.org/rfc/bcp/bcp47.txt>`__ language tag. Example: “en-US”. See `Language Support <https://cloud.google.com/speech/docs/languages>`__ for a list of the currently supported language codes. max_alternatives: Optional. Maximum number of recognition hypotheses to be returned. Specifically, the maximum number of ``SpeechRecognitionAlternative`` messages within each ``SpeechTranscription``. The server may return fewer than ``max_alternatives``. Valid values are ``0``-``30``. A value of ``0`` or ``1`` will return a maximum of one. If omitted, will return a maximum of one. filter_profanity: Optional. If set to ``true``, the server will attempt to filter out profanities, replacing all but the initial character in each filtered word with asterisks, e.g. "f***". If set to ``false`` or omitted, profanities won’t be filtered out. speech_contexts: Optional. A means to provide context to assist the speech recognition. enable_automatic_punctuation: Optional. If ‘true’, adds punctuation to recognition result hypotheses. This feature is only available in select languages. Setting this for requests in other languages has no effect at all. The default ‘false’ value does not add punctuation to result hypotheses. NOTE: “This is currently offered as an experimental service, complimentary to all users. In the future this may be exclusively available as a premium feature.” audio_tracks: Optional. For file formats, such as MXF or MKV, supporting multiple audio tracks, specify up to two tracks. Default: track 0. enable_speaker_diarization: Optional. If ‘true’, enables speaker detection for each recognized word in the top alternative of the recognition result using a speaker_tag provided in the WordInfo. Note: When this is true, we send all the words from the beginning of the audio for the top alternative in every consecutive response. This is done in order to improve our speaker tags as our models learn to identify the speakers in the conversation over time. diarization_speaker_count: Optional. If set, specifies the estimated number of speakers in the conversation. If not set, defaults to ‘2’. Ignored unless enable_speaker_diarization is set to true. enable_word_confidence: Optional. If ``true``, the top result includes a list of words and the confidence for those words. If ``false``, no word- level confidence information is returned. The default is ``false``. """, # @@protoc_insertion_point(class_scope:google.cloud.videointelligence.v1.SpeechTranscriptionConfig) }, ) _sym_db.RegisterMessage(SpeechTranscriptionConfig) SpeechContext = _reflection.GeneratedProtocolMessageType( "SpeechContext", (_message.Message,), { "DESCRIPTOR": _SPEECHCONTEXT, "__module__": "google.cloud.videointelligence_v1.proto.video_intelligence_pb2", "__doc__": """Provides “hints” to the speech recognizer to favor specific words and phrases in the results. Attributes: phrases: Optional. A list of strings containing words and phrases “hints” so that the speech recognition is more likely to recognize them. This can be used to improve the accuracy for specific words and phrases, for example, if specific commands are typically spoken by the user. This can also be used to add additional words to the vocabulary of the recognizer. See `usage limits <https://cloud.google.com/speech/limits#content>`__. """, # @@protoc_insertion_point(class_scope:google.cloud.videointelligence.v1.SpeechContext) }, ) _sym_db.RegisterMessage(SpeechContext) SpeechTranscription = _reflection.GeneratedProtocolMessageType( "SpeechTranscription", (_message.Message,), { "DESCRIPTOR": _SPEECHTRANSCRIPTION, "__module__": "google.cloud.videointelligence_v1.proto.video_intelligence_pb2", "__doc__": """A speech recognition result corresponding to a portion of the audio. Attributes: alternatives: May contain one or more recognition hypotheses (up to the maximum specified in ``max_alternatives``). These alternatives are ordered in terms of accuracy, with the top (first) alternative being the most probable, as ranked by the recognizer. language_code: Output only. The `BCP-47 <https://www.rfc- editor.org/rfc/bcp/bcp47.txt>`__ language tag of the language in this result. This language code was detected to have the most likelihood of being spoken in the audio. """, # @@protoc_insertion_point(class_scope:google.cloud.videointelligence.v1.SpeechTranscription) }, ) _sym_db.RegisterMessage(SpeechTranscription) SpeechRecognitionAlternative = _reflection.GeneratedProtocolMessageType( "SpeechRecognitionAlternative", (_message.Message,), { "DESCRIPTOR": _SPEECHRECOGNITIONALTERNATIVE, "__module__": "google.cloud.videointelligence_v1.proto.video_intelligence_pb2", "__doc__": """Alternative hypotheses (a.k.a. n-best list). Attributes: transcript: Transcript text representing the words that the user spoke. confidence: Output only. The confidence estimate between 0.0 and 1.0. A higher number indicates an estimated greater likelihood that the recognized words are correct. This field is set only for the top alternative. This field is not guaranteed to be accurate and users should not rely on it to be always provided. The default of 0.0 is a sentinel value indicating ``confidence`` was not set. words: Output only. A list of word-specific information for each recognized word. Note: When ``enable_speaker_diarization`` is set to true, you will see all the words from the beginning of the audio. """, # @@protoc_insertion_point(class_scope:google.cloud.videointelligence.v1.SpeechRecognitionAlternative) }, ) _sym_db.RegisterMessage(SpeechRecognitionAlternative) WordInfo = _reflection.GeneratedProtocolMessageType( "WordInfo", (_message.Message,), { "DESCRIPTOR": _WORDINFO, "__module__": "google.cloud.videointelligence_v1.proto.video_intelligence_pb2", "__doc__": """Word-specific information for recognized words. Word information is only included in the response when certain request parameters are set, such as ``enable_word_time_offsets``. Attributes: start_time: Time offset relative to the beginning of the audio, and corresponding to the start of the spoken word. This field is only set if ``enable_word_time_offsets=true`` and only in the top hypothesis. This is an experimental feature and the accuracy of the time offset can vary. end_time: Time offset relative to the beginning of the audio, and corresponding to the end of the spoken word. This field is only set if ``enable_word_time_offsets=true`` and only in the top hypothesis. This is an experimental feature and the accuracy of the time offset can vary. word: The word corresponding to this set of information. confidence: Output only. The confidence estimate between 0.0 and 1.0. A higher number indicates an estimated greater likelihood that the recognized words are correct. This field is set only for the top alternative. This field is not guaranteed to be accurate and users should not rely on it to be always provided. The default of 0.0 is a sentinel value indicating ``confidence`` was not set. speaker_tag: Output only. A distinct integer value is assigned for every speaker within the audio. This field specifies which one of those speakers was detected to have spoken this word. Value ranges from 1 up to diarization_speaker_count, and is only set if speaker diarization is enabled. """, # @@protoc_insertion_point(class_scope:google.cloud.videointelligence.v1.WordInfo) }, ) _sym_db.RegisterMessage(WordInfo) NormalizedVertex = _reflection.GeneratedProtocolMessageType( "NormalizedVertex", (_message.Message,), { "DESCRIPTOR": _NORMALIZEDVERTEX, "__module__": "google.cloud.videointelligence_v1.proto.video_intelligence_pb2", "__doc__": """X coordinate. Attributes: y: Y coordinate. """, # @@protoc_insertion_point(class_scope:google.cloud.videointelligence.v1.NormalizedVertex) }, ) _sym_db.RegisterMessage(NormalizedVertex) NormalizedBoundingPoly = _reflection.GeneratedProtocolMessageType( "NormalizedBoundingPoly", (_message.Message,), { "DESCRIPTOR": _NORMALIZEDBOUNDINGPOLY, "__module__": "google.cloud.videointelligence_v1.proto.video_intelligence_pb2", "__doc__": """Normalized bounding polygon for text (that might not be aligned with axis). Contains list of the corner points in clockwise order starting from top-left corner. For example, for a rectangular bounding box: When the text is horizontal it might look like: 0—-1 \| \| 3—-2 When it’s clockwise rotated 180 degrees around the top-left corner it becomes: 2—-3 \| \| 1—-0 and the vertex order will still be (0, 1, 2, 3). Note that values can be less than 0, or greater than 1 due to trignometric calculations for location of the box. Attributes: vertices: Normalized vertices of the bounding polygon. """, # @@protoc_insertion_point(class_scope:google.cloud.videointelligence.v1.NormalizedBoundingPoly) }, ) _sym_db.RegisterMessage(NormalizedBoundingPoly) TextSegment = _reflection.GeneratedProtocolMessageType( "TextSegment", (_message.Message,), { "DESCRIPTOR": _TEXTSEGMENT, "__module__": "google.cloud.videointelligence_v1.proto.video_intelligence_pb2", "__doc__": """Video segment level annotation results for text detection. Attributes: segment: Video segment where a text snippet was detected. confidence: Confidence for the track of detected text. It is calculated as the highest over all frames where OCR detected text appears. frames: Information related to the frames where OCR detected text appears. """, # @@protoc_insertion_point(class_scope:google.cloud.videointelligence.v1.TextSegment) }, ) _sym_db.RegisterMessage(TextSegment) TextFrame = _reflection.GeneratedProtocolMessageType( "TextFrame", (_message.Message,), { "DESCRIPTOR": _TEXTFRAME, "__module__": "google.cloud.videointelligence_v1.proto.video_intelligence_pb2", "__doc__": """Video frame level annotation results for text annotation (OCR). Contains information regarding timestamp and bounding box locations for the frames containing detected OCR text snippets. Attributes: rotated_bounding_box: Bounding polygon of the detected text for this frame. time_offset: Timestamp of this frame. """, # @@protoc_insertion_point(class_scope:google.cloud.videointelligence.v1.TextFrame) }, ) _sym_db.RegisterMessage(TextFrame) TextAnnotation = _reflection.GeneratedProtocolMessageType( "TextAnnotation", (_message.Message,), { "DESCRIPTOR": _TEXTANNOTATION, "__module__": "google.cloud.videointelligence_v1.proto.video_intelligence_pb2", "__doc__": """Annotations related to one detected OCR text snippet. This will contain the corresponding text, confidence value, and frame level information for each detection. Attributes: text: The detected text. segments: All video segments where OCR detected text appears. version: Feature version. """, # @@protoc_insertion_point(class_scope:google.cloud.videointelligence.v1.TextAnnotation) }, ) _sym_db.RegisterMessage(TextAnnotation) ObjectTrackingFrame = _reflection.GeneratedProtocolMessageType( "ObjectTrackingFrame", (_message.Message,), { "DESCRIPTOR": _OBJECTTRACKINGFRAME, "__module__": "google.cloud.videointelligence_v1.proto.video_intelligence_pb2", "__doc__": """Video frame level annotations for object detection and tracking. This field stores per frame location, time offset, and confidence. Attributes: normalized_bounding_box: The normalized bounding box location of this object track for the frame. time_offset: The timestamp of the frame in microseconds. """, # @@protoc_insertion_point(class_scope:google.cloud.videointelligence.v1.ObjectTrackingFrame) }, ) _sym_db.RegisterMessage(ObjectTrackingFrame) ObjectTrackingAnnotation = _reflection.GeneratedProtocolMessageType( "ObjectTrackingAnnotation", (_message.Message,), { "DESCRIPTOR": _OBJECTTRACKINGANNOTATION, "__module__": "google.cloud.videointelligence_v1.proto.video_intelligence_pb2", "__doc__": """Annotations corresponding to one tracked object. Attributes: track_info: Different representation of tracking info in non-streaming batch and streaming modes. segment: Non-streaming batch mode ONLY. Each object track corresponds to one video segment where it appears. track_id: Streaming mode ONLY. In streaming mode, we do not know the end time of a tracked object before it is completed. Hence, there is no VideoSegment info returned. Instead, we provide a unique identifiable integer track_id so that the customers can correlate the results of the ongoing ObjectTrackAnnotation of the same track_id over time. entity: Entity to specify the object category that this track is labeled as. confidence: Object category’s labeling confidence of this track. frames: Information corresponding to all frames where this object track appears. Non-streaming batch mode: it may be one or multiple ObjectTrackingFrame messages in frames. Streaming mode: it can only be one ObjectTrackingFrame message in frames. version: Feature version. """, # @@protoc_insertion_point(class_scope:google.cloud.videointelligence.v1.ObjectTrackingAnnotation) }, ) _sym_db.RegisterMessage(ObjectTrackingAnnotation) LogoRecognitionAnnotation = _reflection.GeneratedProtocolMessageType( "LogoRecognitionAnnotation", (_message.Message,), { "DESCRIPTOR": _LOGORECOGNITIONANNOTATION, "__module__": "google.cloud.videointelligence_v1.proto.video_intelligence_pb2", "__doc__": """Annotation corresponding to one detected, tracked and recognized logo class. Attributes: entity: Entity category information to specify the logo class that all the logo tracks within this LogoRecognitionAnnotation are recognized as. tracks: All logo tracks where the recognized logo appears. Each track corresponds to one logo instance appearing in consecutive frames. segments: All video segments where the recognized logo appears. There might be multiple instances of the same logo class appearing in one VideoSegment. """, # @@protoc_insertion_point(class_scope:google.cloud.videointelligence.v1.LogoRecognitionAnnotation) }, ) _sym_db.RegisterMessage(LogoRecognitionAnnotation) DESCRIPTOR._options = None _ANNOTATEVIDEOREQUEST.fields_by_name["features"]._options = None _ANNOTATEVIDEOREQUEST.fields_by_name["output_uri"]._options = None _ANNOTATEVIDEOREQUEST.fields_by_name["location_id"]._options = None _FACEFRAME._options = None _FACEANNOTATION._options = None _TIMESTAMPEDOBJECT.fields_by_name["attributes"]._options = None _TIMESTAMPEDOBJECT.fields_by_name["landmarks"]._options = None _TRACK.fields_by_name["attributes"]._options = None _TRACK.fields_by_name["confidence"]._options = None _VIDEOANNOTATIONRESULTS.fields_by_name["face_annotations"]._options = None _SPEECHTRANSCRIPTIONCONFIG.fields_by_name["language_code"]._options = None _SPEECHTRANSCRIPTIONCONFIG.fields_by_name["max_alternatives"]._options = None _SPEECHTRANSCRIPTIONCONFIG.fields_by_name["filter_profanity"]._options = None _SPEECHTRANSCRIPTIONCONFIG.fields_by_name["speech_contexts"]._options = None _SPEECHTRANSCRIPTIONCONFIG.fields_by_name[ "enable_automatic_punctuation" ]._options = None _SPEECHTRANSCRIPTIONCONFIG.fields_by_name["audio_tracks"]._options = None _SPEECHTRANSCRIPTIONCONFIG.fields_by_name["enable_speaker_diarization"]._options = None _SPEECHTRANSCRIPTIONCONFIG.fields_by_name["diarization_speaker_count"]._options = None _SPEECHTRANSCRIPTIONCONFIG.fields_by_name["enable_word_confidence"]._options = None _SPEECHCONTEXT.fields_by_name["phrases"]._options = None _SPEECHTRANSCRIPTION.fields_by_name["language_code"]._options = None _SPEECHRECOGNITIONALTERNATIVE.fields_by_name["confidence"]._options = None _SPEECHRECOGNITIONALTERNATIVE.fields_by_name["words"]._options = None _WORDINFO.fields_by_name["confidence"]._options = None _WORDINFO.fields_by_name["speaker_tag"]._options = None _VIDEOINTELLIGENCESERVICE = _descriptor.ServiceDescriptor( name="VideoIntelligenceService", full_name="google.cloud.videointelligence.v1.VideoIntelligenceService", file=DESCRIPTOR, index=0, serialized_options=b"\312A videointelligence.googleapis.com\322A.https://www.googleapis.com/auth/cloud-platform", create_key=_descriptor._internal_create_key, serialized_start=8921, serialized_end=9241, methods=[ _descriptor.MethodDescriptor( name="AnnotateVideo", full_name="google.cloud.videointelligence.v1.VideoIntelligenceService.AnnotateVideo", index=0, containing_service=None, input_type=_ANNOTATEVIDEOREQUEST, output_type=google_dot_longrunning_dot_operations__pb2._OPERATION, serialized_options=b'\202\323\344\223\002\030"\023/v1/videos:annotate:\001*\332A\022input_uri,features\312A.\n\025AnnotateVideoResponse\022\025AnnotateVideoProgress', create_key=_descriptor._internal_create_key, ), ], ) _sym_db.RegisterServiceDescriptor(_VIDEOINTELLIGENCESERVICE) DESCRIPTOR.services_by_name["VideoIntelligenceService"] = _VIDEOINTELLIGENCESERVICE # @@protoc_insertion_point(module_scope)
google/cloud/videointelligence_v1/proto/video_intelligence_pb2.py
197,079
Generated protocol buffer code. -*- coding: utf-8 -*- Generated by the protocol buffer compiler. DO NOT EDIT! source: google/cloud/videointelligence_v1/proto/video_intelligence.proto @@protoc_insertion_point(imports) @@protoc_insertion_point(class_scope:google.cloud.videointelligence.v1.AnnotateVideoRequest) @@protoc_insertion_point(class_scope:google.cloud.videointelligence.v1.VideoContext) @@protoc_insertion_point(class_scope:google.cloud.videointelligence.v1.LabelDetectionConfig) @@protoc_insertion_point(class_scope:google.cloud.videointelligence.v1.ShotChangeDetectionConfig) @@protoc_insertion_point(class_scope:google.cloud.videointelligence.v1.ObjectTrackingConfig) @@protoc_insertion_point(class_scope:google.cloud.videointelligence.v1.FaceDetectionConfig) @@protoc_insertion_point(class_scope:google.cloud.videointelligence.v1.PersonDetectionConfig) @@protoc_insertion_point(class_scope:google.cloud.videointelligence.v1.ExplicitContentDetectionConfig) @@protoc_insertion_point(class_scope:google.cloud.videointelligence.v1.TextDetectionConfig) @@protoc_insertion_point(class_scope:google.cloud.videointelligence.v1.VideoSegment) @@protoc_insertion_point(class_scope:google.cloud.videointelligence.v1.LabelSegment) @@protoc_insertion_point(class_scope:google.cloud.videointelligence.v1.LabelFrame) @@protoc_insertion_point(class_scope:google.cloud.videointelligence.v1.Entity) @@protoc_insertion_point(class_scope:google.cloud.videointelligence.v1.LabelAnnotation) @@protoc_insertion_point(class_scope:google.cloud.videointelligence.v1.ExplicitContentFrame) @@protoc_insertion_point(class_scope:google.cloud.videointelligence.v1.ExplicitContentAnnotation) @@protoc_insertion_point(class_scope:google.cloud.videointelligence.v1.NormalizedBoundingBox) @@protoc_insertion_point(class_scope:google.cloud.videointelligence.v1.FaceDetectionAnnotation) @@protoc_insertion_point(class_scope:google.cloud.videointelligence.v1.PersonDetectionAnnotation) @@protoc_insertion_point(class_scope:google.cloud.videointelligence.v1.FaceSegment) @@protoc_insertion_point(class_scope:google.cloud.videointelligence.v1.FaceFrame) @@protoc_insertion_point(class_scope:google.cloud.videointelligence.v1.FaceAnnotation) @@protoc_insertion_point(class_scope:google.cloud.videointelligence.v1.TimestampedObject) @@protoc_insertion_point(class_scope:google.cloud.videointelligence.v1.Track) @@protoc_insertion_point(class_scope:google.cloud.videointelligence.v1.DetectedAttribute) @@protoc_insertion_point(class_scope:google.cloud.videointelligence.v1.DetectedLandmark) @@protoc_insertion_point(class_scope:google.cloud.videointelligence.v1.VideoAnnotationResults) @@protoc_insertion_point(class_scope:google.cloud.videointelligence.v1.AnnotateVideoResponse) @@protoc_insertion_point(class_scope:google.cloud.videointelligence.v1.VideoAnnotationProgress) @@protoc_insertion_point(class_scope:google.cloud.videointelligence.v1.AnnotateVideoProgress) @@protoc_insertion_point(class_scope:google.cloud.videointelligence.v1.SpeechTranscriptionConfig) @@protoc_insertion_point(class_scope:google.cloud.videointelligence.v1.SpeechContext) @@protoc_insertion_point(class_scope:google.cloud.videointelligence.v1.SpeechTranscription) @@protoc_insertion_point(class_scope:google.cloud.videointelligence.v1.SpeechRecognitionAlternative) @@protoc_insertion_point(class_scope:google.cloud.videointelligence.v1.WordInfo) @@protoc_insertion_point(class_scope:google.cloud.videointelligence.v1.NormalizedVertex) @@protoc_insertion_point(class_scope:google.cloud.videointelligence.v1.NormalizedBoundingPoly) @@protoc_insertion_point(class_scope:google.cloud.videointelligence.v1.TextSegment) @@protoc_insertion_point(class_scope:google.cloud.videointelligence.v1.TextFrame) @@protoc_insertion_point(class_scope:google.cloud.videointelligence.v1.TextAnnotation) @@protoc_insertion_point(class_scope:google.cloud.videointelligence.v1.ObjectTrackingFrame) @@protoc_insertion_point(class_scope:google.cloud.videointelligence.v1.ObjectTrackingAnnotation) @@protoc_insertion_point(class_scope:google.cloud.videointelligence.v1.LogoRecognitionAnnotation) @@protoc_insertion_point(module_scope)
4,161
en
0.305723
# Copyright 2019, A10 Networks # # 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 a10_octavia.db import repositories as repo from a10_octavia.db import api as db_apis from oslo_utils import uuidutils class VThunderDB(): def __init__(self, **kwargs): self.vthunder_repo = repo.VThunderRepository() def create_vthunder(self, project_id, device_name, username, password, ip_address, undercloud=None, axapi_version=30): if axapi_version == 2.1: axapi_version = 21 else: axapi_version = 30 amphora_id = uuidutils.generate_uuid() vthunder_id = uuidutils.generate_uuid() if undercloud == 'True' or undercloud == 'true': undercloud = True else: undercloud = False db_session = db_apis.get_session() vthunder = self.vthunder_repo.create(db_session, vthunder_id=vthunder_id, amphora_id=amphora_id, project_id=project_id, device_name=device_name, username=username, password=password, ip_address=ip_address, undercloud=undercloud, axapi_version=axapi_version) db_apis.close_session(db_session) print("vThunder entry created successfully.") def update_vthunder(self, id, project_id, device_name, username, password, ip_address, undercloud=None, axapi_version=30): if axapi_version == 2.1: axapi_version = 21 else: axapi_version = 30 if undercloud == 'True' or undercloud == 'true': undercloud = True else: undercloud = False db_session = db_apis.get_session() vthunder = self.vthunder_repo.update(db_session, id, project_id=project_id, device_name=device_name, username=username, password=password, ip_address=ip_address, undercloud=undercloud, axapi_version=axapi_version) db_apis.close_session(db_session) print("vThunder entry updated successfully.") def delete_vthunder(self, vthunderid): db_session = db_apis.get_session() vthunder = self.vthunder_repo.delete(db_session, id=vthunderid) db_apis.close_session(db_session) print("vThunder entry deleted successfully.")
a10_octavia/controller/worker/tasks/a10_vthunder_db.py
3,027
Copyright 2019, A10 Networks 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.
578
en
0.869296
from __future__ import unicode_literals from nose.tools import assert_raises import datetime import boto import boto3 import sure # noqa from boto.exception import JSONResponseError from moto import mock_ec2 from moto.backends import get_model from moto.core.utils import iso_8601_datetime_with_milliseconds @mock_ec2 def test_request_spot_instances(): conn = boto3.client('ec2', 'us-east-1') vpc = conn.create_vpc(CidrBlock="10.0.0.0/8")['Vpc'] subnet = conn.create_subnet(VpcId=vpc['VpcId'], CidrBlock='10.0.0.0/16', AvailabilityZone='us-east-1a')['Subnet'] subnet_id = subnet['SubnetId'] conn = boto.connect_ec2() conn.create_security_group('group1', 'description') conn.create_security_group('group2', 'description') start = iso_8601_datetime_with_milliseconds(datetime.datetime(2013, 1, 1)) end = iso_8601_datetime_with_milliseconds(datetime.datetime(2013, 1, 2)) with assert_raises(JSONResponseError) as ex: request = conn.request_spot_instances( price=0.5, image_id='ami-abcd1234', count=1, type='one-time', valid_from=start, valid_until=end, launch_group="the-group", availability_zone_group='my-group', key_name="test", security_groups=['group1', 'group2'], user_data=b"some test data", instance_type='m1.small', placement='us-east-1c', kernel_id="test-kernel", ramdisk_id="test-ramdisk", monitoring_enabled=True, subnet_id=subnet_id, dry_run=True ) ex.exception.reason.should.equal('DryRunOperation') ex.exception.status.should.equal(400) ex.exception.message.should.equal('An error occurred (DryRunOperation) when calling the RequestSpotInstance operation: Request would have succeeded, but DryRun flag is set') request = conn.request_spot_instances( price=0.5, image_id='ami-abcd1234', count=1, type='one-time', valid_from=start, valid_until=end, launch_group="the-group", availability_zone_group='my-group', key_name="test", security_groups=['group1', 'group2'], user_data=b"some test data", instance_type='m1.small', placement='us-east-1c', kernel_id="test-kernel", ramdisk_id="test-ramdisk", monitoring_enabled=True, subnet_id=subnet_id, ) requests = conn.get_all_spot_instance_requests() requests.should.have.length_of(1) request = requests[0] request.state.should.equal("open") request.price.should.equal(0.5) request.launch_specification.image_id.should.equal('ami-abcd1234') request.type.should.equal('one-time') request.valid_from.should.equal(start) request.valid_until.should.equal(end) request.launch_group.should.equal("the-group") request.availability_zone_group.should.equal('my-group') request.launch_specification.key_name.should.equal("test") security_group_names = [group.name for group in request.launch_specification.groups] set(security_group_names).should.equal(set(['group1', 'group2'])) request.launch_specification.instance_type.should.equal('m1.small') request.launch_specification.placement.should.equal('us-east-1c') request.launch_specification.kernel.should.equal("test-kernel") request.launch_specification.ramdisk.should.equal("test-ramdisk") request.launch_specification.subnet_id.should.equal(subnet_id) @mock_ec2 def test_request_spot_instances_default_arguments(): """ Test that moto set the correct default arguments """ conn = boto.connect_ec2() request = conn.request_spot_instances( price=0.5, image_id='ami-abcd1234', ) requests = conn.get_all_spot_instance_requests() requests.should.have.length_of(1) request = requests[0] request.state.should.equal("open") request.price.should.equal(0.5) request.launch_specification.image_id.should.equal('ami-abcd1234') request.type.should.equal('one-time') request.valid_from.should.equal(None) request.valid_until.should.equal(None) request.launch_group.should.equal(None) request.availability_zone_group.should.equal(None) request.launch_specification.key_name.should.equal(None) security_group_names = [group.name for group in request.launch_specification.groups] security_group_names.should.equal(["default"]) request.launch_specification.instance_type.should.equal('m1.small') request.launch_specification.placement.should.equal(None) request.launch_specification.kernel.should.equal(None) request.launch_specification.ramdisk.should.equal(None) request.launch_specification.subnet_id.should.equal(None) @mock_ec2 def test_cancel_spot_instance_request(): conn = boto.connect_ec2() conn.request_spot_instances( price=0.5, image_id='ami-abcd1234', ) requests = conn.get_all_spot_instance_requests() requests.should.have.length_of(1) with assert_raises(JSONResponseError) as ex: conn.cancel_spot_instance_requests([requests[0].id], dry_run=True) ex.exception.reason.should.equal('DryRunOperation') ex.exception.status.should.equal(400) ex.exception.message.should.equal('An error occurred (DryRunOperation) when calling the CancelSpotInstance operation: Request would have succeeded, but DryRun flag is set') conn.cancel_spot_instance_requests([requests[0].id]) requests = conn.get_all_spot_instance_requests() requests.should.have.length_of(0) @mock_ec2 def test_request_spot_instances_fulfilled(): """ Test that moto correctly fullfills a spot instance request """ conn = boto.ec2.connect_to_region("us-east-1") request = conn.request_spot_instances( price=0.5, image_id='ami-abcd1234', ) requests = conn.get_all_spot_instance_requests() requests.should.have.length_of(1) request = requests[0] request.state.should.equal("open") get_model('SpotInstanceRequest')[0].state = 'active' requests = conn.get_all_spot_instance_requests() requests.should.have.length_of(1) request = requests[0] request.state.should.equal("active") @mock_ec2 def test_tag_spot_instance_request(): """ Test that moto correctly tags a spot instance request """ conn = boto.connect_ec2() request = conn.request_spot_instances( price=0.5, image_id='ami-abcd1234', ) request[0].add_tag('tag1', 'value1') request[0].add_tag('tag2', 'value2') requests = conn.get_all_spot_instance_requests() requests.should.have.length_of(1) request = requests[0] tag_dict = dict(request.tags) tag_dict.should.equal({'tag1': 'value1', 'tag2': 'value2'}) @mock_ec2 def test_get_all_spot_instance_requests_filtering(): """ Test that moto correctly filters spot instance requests """ conn = boto.connect_ec2() request1 = conn.request_spot_instances( price=0.5, image_id='ami-abcd1234', ) request2 = conn.request_spot_instances( price=0.5, image_id='ami-abcd1234', ) conn.request_spot_instances( price=0.5, image_id='ami-abcd1234', ) request1[0].add_tag('tag1', 'value1') request1[0].add_tag('tag2', 'value2') request2[0].add_tag('tag1', 'value1') request2[0].add_tag('tag2', 'wrong') requests = conn.get_all_spot_instance_requests(filters={'state': 'active'}) requests.should.have.length_of(0) requests = conn.get_all_spot_instance_requests(filters={'state': 'open'}) requests.should.have.length_of(3) requests = conn.get_all_spot_instance_requests(filters={'tag:tag1': 'value1'}) requests.should.have.length_of(2) requests = conn.get_all_spot_instance_requests(filters={'tag:tag1': 'value1', 'tag:tag2': 'value2'}) requests.should.have.length_of(1) @mock_ec2 def test_request_spot_instances_setting_instance_id(): conn = boto.ec2.connect_to_region("us-east-1") request = conn.request_spot_instances( price=0.5, image_id='ami-abcd1234') req = get_model('SpotInstanceRequest')[0] req.state = 'active' req.instance_id = 'i-12345678' request = conn.get_all_spot_instance_requests()[0] assert request.state == 'active' assert request.instance_id == 'i-12345678'
tests/test_ec2/test_spot_instances.py
8,198
Test that moto correctly filters spot instance requests Test that moto set the correct default arguments Test that moto correctly fullfills a spot instance request Test that moto correctly tags a spot instance request noqa
224
en
0.497336
# coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for # license information. # # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is # regenerated. # -------------------------------------------------------------------------- from typing import Any, Optional, TYPE_CHECKING from azure.core.pipeline.transport import AsyncHttpResponse, HttpRequest from azure.mgmt.core import AsyncARMPipelineClient from azure.profiles import KnownProfiles, ProfileDefinition from azure.profiles.multiapiclient import MultiApiClientMixin from msrest import Deserializer, Serializer from ._configuration import ContainerRegistryManagementClientConfiguration if TYPE_CHECKING: # pylint: disable=unused-import,ungrouped-imports from azure.core.credentials_async import AsyncTokenCredential class _SDKClient(object): def __init__(self, *args, **kwargs): """This is a fake class to support current implemetation of MultiApiClientMixin." Will be removed in final version of multiapi azure-core based client """ pass class ContainerRegistryManagementClient(MultiApiClientMixin, _SDKClient): """ContainerRegistryManagementClient. This ready contains multiple API versions, to help you deal with all of the Azure clouds (Azure Stack, Azure Government, Azure China, etc.). By default, it uses the latest API version available on public Azure. For production, you should stick to a particular api-version and/or profile. The profile sets a mapping between an operation group and its API version. The api-version parameter sets the default API version if the operation group is not described in the profile. :param credential: Credential needed for the client to connect to Azure. :type credential: ~azure.core.credentials_async.AsyncTokenCredential :param subscription_id: The Microsoft Azure subscription ID. :type subscription_id: str :param api_version: API version to use if no profile is provided, or if missing in profile. :type api_version: str :param base_url: Service URL :type base_url: str :param profile: A profile definition, from KnownProfiles to dict. :type profile: azure.profiles.KnownProfiles :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. """ DEFAULT_API_VERSION = '2019-05-01' _PROFILE_TAG = "azure.mgmt.containerregistry.ContainerRegistryManagementClient" LATEST_PROFILE = ProfileDefinition({ _PROFILE_TAG: { None: DEFAULT_API_VERSION, 'build_steps': '2018-02-01-preview', 'build_tasks': '2018-02-01-preview', 'builds': '2018-02-01-preview', 'runs': '2019-04-01', 'tasks': '2019-04-01', }}, _PROFILE_TAG + " latest" ) def __init__( self, credential: "AsyncTokenCredential", subscription_id: str, api_version: Optional[str] = None, base_url: Optional[str] = None, profile: KnownProfiles = KnownProfiles.default, **kwargs # type: Any ) -> None: if not base_url: base_url = 'https://management.azure.com' self._config = ContainerRegistryManagementClientConfiguration(credential, subscription_id, **kwargs) self._client = AsyncARMPipelineClient(base_url=base_url, config=self._config, **kwargs) super(ContainerRegistryManagementClient, self).__init__( api_version=api_version, profile=profile ) @classmethod def _models_dict(cls, api_version): return {k: v for k, v in cls.models(api_version).__dict__.items() if isinstance(v, type)} @classmethod def models(cls, api_version=DEFAULT_API_VERSION): """Module depends on the API version: * 2017-03-01: :mod:`v2017_03_01.models<azure.mgmt.containerregistry.v2017_03_01.models>` * 2017-10-01: :mod:`v2017_10_01.models<azure.mgmt.containerregistry.v2017_10_01.models>` * 2018-02-01-preview: :mod:`v2018_02_01_preview.models<azure.mgmt.containerregistry.v2018_02_01_preview.models>` * 2018-09-01: :mod:`v2018_09_01.models<azure.mgmt.containerregistry.v2018_09_01.models>` * 2019-04-01: :mod:`v2019_04_01.models<azure.mgmt.containerregistry.v2019_04_01.models>` * 2019-05-01: :mod:`v2019_05_01.models<azure.mgmt.containerregistry.v2019_05_01.models>` * 2019-05-01-preview: :mod:`v2019_05_01_preview.models<azure.mgmt.containerregistry.v2019_05_01_preview.models>` * 2019-06-01-preview: :mod:`v2019_06_01_preview.models<azure.mgmt.containerregistry.v2019_06_01_preview.models>` * 2019-12-01-preview: :mod:`v2019_12_01_preview.models<azure.mgmt.containerregistry.v2019_12_01_preview.models>` * 2020-11-01-preview: :mod:`v2020_11_01_preview.models<azure.mgmt.containerregistry.v2020_11_01_preview.models>` * 2021-06-01-preview: :mod:`v2021_06_01_preview.models<azure.mgmt.containerregistry.v2021_06_01_preview.models>` * 2021-08-01-preview: :mod:`v2021_08_01_preview.models<azure.mgmt.containerregistry.v2021_08_01_preview.models>` """ if api_version == '2017-03-01': from ..v2017_03_01 import models return models elif api_version == '2017-10-01': from ..v2017_10_01 import models return models elif api_version == '2018-02-01-preview': from ..v2018_02_01_preview import models return models elif api_version == '2018-09-01': from ..v2018_09_01 import models return models elif api_version == '2019-04-01': from ..v2019_04_01 import models return models elif api_version == '2019-05-01': from ..v2019_05_01 import models return models elif api_version == '2019-05-01-preview': from ..v2019_05_01_preview import models return models elif api_version == '2019-06-01-preview': from ..v2019_06_01_preview import models return models elif api_version == '2019-12-01-preview': from ..v2019_12_01_preview import models return models elif api_version == '2020-11-01-preview': from ..v2020_11_01_preview import models return models elif api_version == '2021-06-01-preview': from ..v2021_06_01_preview import models return models elif api_version == '2021-08-01-preview': from ..v2021_08_01_preview import models return models raise ValueError("API version {} is not available".format(api_version)) @property def agent_pools(self): """Instance depends on the API version: * 2019-06-01-preview: :class:`AgentPoolsOperations<azure.mgmt.containerregistry.v2019_06_01_preview.aio.operations.AgentPoolsOperations>` """ api_version = self._get_api_version('agent_pools') if api_version == '2019-06-01-preview': from ..v2019_06_01_preview.aio.operations import AgentPoolsOperations as OperationClass else: raise ValueError("API version {} does not have operation group 'agent_pools'".format(api_version)) return OperationClass(self._client, self._config, Serializer(self._models_dict(api_version)), Deserializer(self._models_dict(api_version))) @property def build_steps(self): """Instance depends on the API version: * 2018-02-01-preview: :class:`BuildStepsOperations<azure.mgmt.containerregistry.v2018_02_01_preview.aio.operations.BuildStepsOperations>` """ api_version = self._get_api_version('build_steps') if api_version == '2018-02-01-preview': from ..v2018_02_01_preview.aio.operations import BuildStepsOperations as OperationClass else: raise ValueError("API version {} does not have operation group 'build_steps'".format(api_version)) return OperationClass(self._client, self._config, Serializer(self._models_dict(api_version)), Deserializer(self._models_dict(api_version))) @property def build_tasks(self): """Instance depends on the API version: * 2018-02-01-preview: :class:`BuildTasksOperations<azure.mgmt.containerregistry.v2018_02_01_preview.aio.operations.BuildTasksOperations>` """ api_version = self._get_api_version('build_tasks') if api_version == '2018-02-01-preview': from ..v2018_02_01_preview.aio.operations import BuildTasksOperations as OperationClass else: raise ValueError("API version {} does not have operation group 'build_tasks'".format(api_version)) return OperationClass(self._client, self._config, Serializer(self._models_dict(api_version)), Deserializer(self._models_dict(api_version))) @property def builds(self): """Instance depends on the API version: * 2018-02-01-preview: :class:`BuildsOperations<azure.mgmt.containerregistry.v2018_02_01_preview.aio.operations.BuildsOperations>` """ api_version = self._get_api_version('builds') if api_version == '2018-02-01-preview': from ..v2018_02_01_preview.aio.operations import BuildsOperations as OperationClass else: raise ValueError("API version {} does not have operation group 'builds'".format(api_version)) return OperationClass(self._client, self._config, Serializer(self._models_dict(api_version)), Deserializer(self._models_dict(api_version))) @property def connected_registries(self): """Instance depends on the API version: * 2020-11-01-preview: :class:`ConnectedRegistriesOperations<azure.mgmt.containerregistry.v2020_11_01_preview.aio.operations.ConnectedRegistriesOperations>` * 2021-06-01-preview: :class:`ConnectedRegistriesOperations<azure.mgmt.containerregistry.v2021_06_01_preview.aio.operations.ConnectedRegistriesOperations>` * 2021-08-01-preview: :class:`ConnectedRegistriesOperations<azure.mgmt.containerregistry.v2021_08_01_preview.aio.operations.ConnectedRegistriesOperations>` """ api_version = self._get_api_version('connected_registries') if api_version == '2020-11-01-preview': from ..v2020_11_01_preview.aio.operations import ConnectedRegistriesOperations as OperationClass elif api_version == '2021-06-01-preview': from ..v2021_06_01_preview.aio.operations import ConnectedRegistriesOperations as OperationClass elif api_version == '2021-08-01-preview': from ..v2021_08_01_preview.aio.operations import ConnectedRegistriesOperations as OperationClass else: raise ValueError("API version {} does not have operation group 'connected_registries'".format(api_version)) return OperationClass(self._client, self._config, Serializer(self._models_dict(api_version)), Deserializer(self._models_dict(api_version))) @property def export_pipelines(self): """Instance depends on the API version: * 2019-12-01-preview: :class:`ExportPipelinesOperations<azure.mgmt.containerregistry.v2019_12_01_preview.aio.operations.ExportPipelinesOperations>` * 2020-11-01-preview: :class:`ExportPipelinesOperations<azure.mgmt.containerregistry.v2020_11_01_preview.aio.operations.ExportPipelinesOperations>` * 2021-06-01-preview: :class:`ExportPipelinesOperations<azure.mgmt.containerregistry.v2021_06_01_preview.aio.operations.ExportPipelinesOperations>` * 2021-08-01-preview: :class:`ExportPipelinesOperations<azure.mgmt.containerregistry.v2021_08_01_preview.aio.operations.ExportPipelinesOperations>` """ api_version = self._get_api_version('export_pipelines') if api_version == '2019-12-01-preview': from ..v2019_12_01_preview.aio.operations import ExportPipelinesOperations as OperationClass elif api_version == '2020-11-01-preview': from ..v2020_11_01_preview.aio.operations import ExportPipelinesOperations as OperationClass elif api_version == '2021-06-01-preview': from ..v2021_06_01_preview.aio.operations import ExportPipelinesOperations as OperationClass elif api_version == '2021-08-01-preview': from ..v2021_08_01_preview.aio.operations import ExportPipelinesOperations as OperationClass else: raise ValueError("API version {} does not have operation group 'export_pipelines'".format(api_version)) return OperationClass(self._client, self._config, Serializer(self._models_dict(api_version)), Deserializer(self._models_dict(api_version))) @property def import_pipelines(self): """Instance depends on the API version: * 2019-12-01-preview: :class:`ImportPipelinesOperations<azure.mgmt.containerregistry.v2019_12_01_preview.aio.operations.ImportPipelinesOperations>` * 2020-11-01-preview: :class:`ImportPipelinesOperations<azure.mgmt.containerregistry.v2020_11_01_preview.aio.operations.ImportPipelinesOperations>` * 2021-06-01-preview: :class:`ImportPipelinesOperations<azure.mgmt.containerregistry.v2021_06_01_preview.aio.operations.ImportPipelinesOperations>` * 2021-08-01-preview: :class:`ImportPipelinesOperations<azure.mgmt.containerregistry.v2021_08_01_preview.aio.operations.ImportPipelinesOperations>` """ api_version = self._get_api_version('import_pipelines') if api_version == '2019-12-01-preview': from ..v2019_12_01_preview.aio.operations import ImportPipelinesOperations as OperationClass elif api_version == '2020-11-01-preview': from ..v2020_11_01_preview.aio.operations import ImportPipelinesOperations as OperationClass elif api_version == '2021-06-01-preview': from ..v2021_06_01_preview.aio.operations import ImportPipelinesOperations as OperationClass elif api_version == '2021-08-01-preview': from ..v2021_08_01_preview.aio.operations import ImportPipelinesOperations as OperationClass else: raise ValueError("API version {} does not have operation group 'import_pipelines'".format(api_version)) return OperationClass(self._client, self._config, Serializer(self._models_dict(api_version)), Deserializer(self._models_dict(api_version))) @property def operations(self): """Instance depends on the API version: * 2017-03-01: :class:`Operations<azure.mgmt.containerregistry.v2017_03_01.aio.operations.Operations>` * 2017-10-01: :class:`Operations<azure.mgmt.containerregistry.v2017_10_01.aio.operations.Operations>` * 2019-05-01: :class:`Operations<azure.mgmt.containerregistry.v2019_05_01.aio.operations.Operations>` * 2019-12-01-preview: :class:`Operations<azure.mgmt.containerregistry.v2019_12_01_preview.aio.operations.Operations>` * 2020-11-01-preview: :class:`Operations<azure.mgmt.containerregistry.v2020_11_01_preview.aio.operations.Operations>` * 2021-06-01-preview: :class:`Operations<azure.mgmt.containerregistry.v2021_06_01_preview.aio.operations.Operations>` * 2021-08-01-preview: :class:`Operations<azure.mgmt.containerregistry.v2021_08_01_preview.aio.operations.Operations>` """ api_version = self._get_api_version('operations') if api_version == '2017-03-01': from ..v2017_03_01.aio.operations import Operations as OperationClass elif api_version == '2017-10-01': from ..v2017_10_01.aio.operations import Operations as OperationClass elif api_version == '2019-05-01': from ..v2019_05_01.aio.operations import Operations as OperationClass elif api_version == '2019-12-01-preview': from ..v2019_12_01_preview.aio.operations import Operations as OperationClass elif api_version == '2020-11-01-preview': from ..v2020_11_01_preview.aio.operations import Operations as OperationClass elif api_version == '2021-06-01-preview': from ..v2021_06_01_preview.aio.operations import Operations as OperationClass elif api_version == '2021-08-01-preview': from ..v2021_08_01_preview.aio.operations import Operations as OperationClass else: raise ValueError("API version {} does not have operation group 'operations'".format(api_version)) return OperationClass(self._client, self._config, Serializer(self._models_dict(api_version)), Deserializer(self._models_dict(api_version))) @property def pipeline_runs(self): """Instance depends on the API version: * 2019-12-01-preview: :class:`PipelineRunsOperations<azure.mgmt.containerregistry.v2019_12_01_preview.aio.operations.PipelineRunsOperations>` * 2020-11-01-preview: :class:`PipelineRunsOperations<azure.mgmt.containerregistry.v2020_11_01_preview.aio.operations.PipelineRunsOperations>` * 2021-06-01-preview: :class:`PipelineRunsOperations<azure.mgmt.containerregistry.v2021_06_01_preview.aio.operations.PipelineRunsOperations>` * 2021-08-01-preview: :class:`PipelineRunsOperations<azure.mgmt.containerregistry.v2021_08_01_preview.aio.operations.PipelineRunsOperations>` """ api_version = self._get_api_version('pipeline_runs') if api_version == '2019-12-01-preview': from ..v2019_12_01_preview.aio.operations import PipelineRunsOperations as OperationClass elif api_version == '2020-11-01-preview': from ..v2020_11_01_preview.aio.operations import PipelineRunsOperations as OperationClass elif api_version == '2021-06-01-preview': from ..v2021_06_01_preview.aio.operations import PipelineRunsOperations as OperationClass elif api_version == '2021-08-01-preview': from ..v2021_08_01_preview.aio.operations import PipelineRunsOperations as OperationClass else: raise ValueError("API version {} does not have operation group 'pipeline_runs'".format(api_version)) return OperationClass(self._client, self._config, Serializer(self._models_dict(api_version)), Deserializer(self._models_dict(api_version))) @property def private_endpoint_connections(self): """Instance depends on the API version: * 2019-12-01-preview: :class:`PrivateEndpointConnectionsOperations<azure.mgmt.containerregistry.v2019_12_01_preview.aio.operations.PrivateEndpointConnectionsOperations>` * 2020-11-01-preview: :class:`PrivateEndpointConnectionsOperations<azure.mgmt.containerregistry.v2020_11_01_preview.aio.operations.PrivateEndpointConnectionsOperations>` * 2021-06-01-preview: :class:`PrivateEndpointConnectionsOperations<azure.mgmt.containerregistry.v2021_06_01_preview.aio.operations.PrivateEndpointConnectionsOperations>` * 2021-08-01-preview: :class:`PrivateEndpointConnectionsOperations<azure.mgmt.containerregistry.v2021_08_01_preview.aio.operations.PrivateEndpointConnectionsOperations>` """ api_version = self._get_api_version('private_endpoint_connections') if api_version == '2019-12-01-preview': from ..v2019_12_01_preview.aio.operations import PrivateEndpointConnectionsOperations as OperationClass elif api_version == '2020-11-01-preview': from ..v2020_11_01_preview.aio.operations import PrivateEndpointConnectionsOperations as OperationClass elif api_version == '2021-06-01-preview': from ..v2021_06_01_preview.aio.operations import PrivateEndpointConnectionsOperations as OperationClass elif api_version == '2021-08-01-preview': from ..v2021_08_01_preview.aio.operations import PrivateEndpointConnectionsOperations as OperationClass else: raise ValueError("API version {} does not have operation group 'private_endpoint_connections'".format(api_version)) return OperationClass(self._client, self._config, Serializer(self._models_dict(api_version)), Deserializer(self._models_dict(api_version))) @property def registries(self): """Instance depends on the API version: * 2017-03-01: :class:`RegistriesOperations<azure.mgmt.containerregistry.v2017_03_01.aio.operations.RegistriesOperations>` * 2017-10-01: :class:`RegistriesOperations<azure.mgmt.containerregistry.v2017_10_01.aio.operations.RegistriesOperations>` * 2018-02-01-preview: :class:`RegistriesOperations<azure.mgmt.containerregistry.v2018_02_01_preview.aio.operations.RegistriesOperations>` * 2018-09-01: :class:`RegistriesOperations<azure.mgmt.containerregistry.v2018_09_01.aio.operations.RegistriesOperations>` * 2019-04-01: :class:`RegistriesOperations<azure.mgmt.containerregistry.v2019_04_01.aio.operations.RegistriesOperations>` * 2019-05-01: :class:`RegistriesOperations<azure.mgmt.containerregistry.v2019_05_01.aio.operations.RegistriesOperations>` * 2019-05-01-preview: :class:`RegistriesOperations<azure.mgmt.containerregistry.v2019_05_01_preview.aio.operations.RegistriesOperations>` * 2019-06-01-preview: :class:`RegistriesOperations<azure.mgmt.containerregistry.v2019_06_01_preview.aio.operations.RegistriesOperations>` * 2019-12-01-preview: :class:`RegistriesOperations<azure.mgmt.containerregistry.v2019_12_01_preview.aio.operations.RegistriesOperations>` * 2020-11-01-preview: :class:`RegistriesOperations<azure.mgmt.containerregistry.v2020_11_01_preview.aio.operations.RegistriesOperations>` * 2021-06-01-preview: :class:`RegistriesOperations<azure.mgmt.containerregistry.v2021_06_01_preview.aio.operations.RegistriesOperations>` * 2021-08-01-preview: :class:`RegistriesOperations<azure.mgmt.containerregistry.v2021_08_01_preview.aio.operations.RegistriesOperations>` """ api_version = self._get_api_version('registries') if api_version == '2017-03-01': from ..v2017_03_01.aio.operations import RegistriesOperations as OperationClass elif api_version == '2017-10-01': from ..v2017_10_01.aio.operations import RegistriesOperations as OperationClass elif api_version == '2018-02-01-preview': from ..v2018_02_01_preview.aio.operations import RegistriesOperations as OperationClass elif api_version == '2018-09-01': from ..v2018_09_01.aio.operations import RegistriesOperations as OperationClass elif api_version == '2019-04-01': from ..v2019_04_01.aio.operations import RegistriesOperations as OperationClass elif api_version == '2019-05-01': from ..v2019_05_01.aio.operations import RegistriesOperations as OperationClass elif api_version == '2019-05-01-preview': from ..v2019_05_01_preview.aio.operations import RegistriesOperations as OperationClass elif api_version == '2019-06-01-preview': from ..v2019_06_01_preview.aio.operations import RegistriesOperations as OperationClass elif api_version == '2019-12-01-preview': from ..v2019_12_01_preview.aio.operations import RegistriesOperations as OperationClass elif api_version == '2020-11-01-preview': from ..v2020_11_01_preview.aio.operations import RegistriesOperations as OperationClass elif api_version == '2021-06-01-preview': from ..v2021_06_01_preview.aio.operations import RegistriesOperations as OperationClass elif api_version == '2021-08-01-preview': from ..v2021_08_01_preview.aio.operations import RegistriesOperations as OperationClass else: raise ValueError("API version {} does not have operation group 'registries'".format(api_version)) return OperationClass(self._client, self._config, Serializer(self._models_dict(api_version)), Deserializer(self._models_dict(api_version))) @property def replications(self): """Instance depends on the API version: * 2017-10-01: :class:`ReplicationsOperations<azure.mgmt.containerregistry.v2017_10_01.aio.operations.ReplicationsOperations>` * 2019-05-01: :class:`ReplicationsOperations<azure.mgmt.containerregistry.v2019_05_01.aio.operations.ReplicationsOperations>` * 2019-12-01-preview: :class:`ReplicationsOperations<azure.mgmt.containerregistry.v2019_12_01_preview.aio.operations.ReplicationsOperations>` * 2020-11-01-preview: :class:`ReplicationsOperations<azure.mgmt.containerregistry.v2020_11_01_preview.aio.operations.ReplicationsOperations>` * 2021-06-01-preview: :class:`ReplicationsOperations<azure.mgmt.containerregistry.v2021_06_01_preview.aio.operations.ReplicationsOperations>` * 2021-08-01-preview: :class:`ReplicationsOperations<azure.mgmt.containerregistry.v2021_08_01_preview.aio.operations.ReplicationsOperations>` """ api_version = self._get_api_version('replications') if api_version == '2017-10-01': from ..v2017_10_01.aio.operations import ReplicationsOperations as OperationClass elif api_version == '2019-05-01': from ..v2019_05_01.aio.operations import ReplicationsOperations as OperationClass elif api_version == '2019-12-01-preview': from ..v2019_12_01_preview.aio.operations import ReplicationsOperations as OperationClass elif api_version == '2020-11-01-preview': from ..v2020_11_01_preview.aio.operations import ReplicationsOperations as OperationClass elif api_version == '2021-06-01-preview': from ..v2021_06_01_preview.aio.operations import ReplicationsOperations as OperationClass elif api_version == '2021-08-01-preview': from ..v2021_08_01_preview.aio.operations import ReplicationsOperations as OperationClass else: raise ValueError("API version {} does not have operation group 'replications'".format(api_version)) return OperationClass(self._client, self._config, Serializer(self._models_dict(api_version)), Deserializer(self._models_dict(api_version))) @property def runs(self): """Instance depends on the API version: * 2018-09-01: :class:`RunsOperations<azure.mgmt.containerregistry.v2018_09_01.aio.operations.RunsOperations>` * 2019-04-01: :class:`RunsOperations<azure.mgmt.containerregistry.v2019_04_01.aio.operations.RunsOperations>` * 2019-06-01-preview: :class:`RunsOperations<azure.mgmt.containerregistry.v2019_06_01_preview.aio.operations.RunsOperations>` """ api_version = self._get_api_version('runs') if api_version == '2018-09-01': from ..v2018_09_01.aio.operations import RunsOperations as OperationClass elif api_version == '2019-04-01': from ..v2019_04_01.aio.operations import RunsOperations as OperationClass elif api_version == '2019-06-01-preview': from ..v2019_06_01_preview.aio.operations import RunsOperations as OperationClass else: raise ValueError("API version {} does not have operation group 'runs'".format(api_version)) return OperationClass(self._client, self._config, Serializer(self._models_dict(api_version)), Deserializer(self._models_dict(api_version))) @property def scope_maps(self): """Instance depends on the API version: * 2019-05-01-preview: :class:`ScopeMapsOperations<azure.mgmt.containerregistry.v2019_05_01_preview.aio.operations.ScopeMapsOperations>` * 2020-11-01-preview: :class:`ScopeMapsOperations<azure.mgmt.containerregistry.v2020_11_01_preview.aio.operations.ScopeMapsOperations>` * 2021-06-01-preview: :class:`ScopeMapsOperations<azure.mgmt.containerregistry.v2021_06_01_preview.aio.operations.ScopeMapsOperations>` * 2021-08-01-preview: :class:`ScopeMapsOperations<azure.mgmt.containerregistry.v2021_08_01_preview.aio.operations.ScopeMapsOperations>` """ api_version = self._get_api_version('scope_maps') if api_version == '2019-05-01-preview': from ..v2019_05_01_preview.aio.operations import ScopeMapsOperations as OperationClass elif api_version == '2020-11-01-preview': from ..v2020_11_01_preview.aio.operations import ScopeMapsOperations as OperationClass elif api_version == '2021-06-01-preview': from ..v2021_06_01_preview.aio.operations import ScopeMapsOperations as OperationClass elif api_version == '2021-08-01-preview': from ..v2021_08_01_preview.aio.operations import ScopeMapsOperations as OperationClass else: raise ValueError("API version {} does not have operation group 'scope_maps'".format(api_version)) return OperationClass(self._client, self._config, Serializer(self._models_dict(api_version)), Deserializer(self._models_dict(api_version))) @property def task_runs(self): """Instance depends on the API version: * 2019-06-01-preview: :class:`TaskRunsOperations<azure.mgmt.containerregistry.v2019_06_01_preview.aio.operations.TaskRunsOperations>` """ api_version = self._get_api_version('task_runs') if api_version == '2019-06-01-preview': from ..v2019_06_01_preview.aio.operations import TaskRunsOperations as OperationClass else: raise ValueError("API version {} does not have operation group 'task_runs'".format(api_version)) return OperationClass(self._client, self._config, Serializer(self._models_dict(api_version)), Deserializer(self._models_dict(api_version))) @property def tasks(self): """Instance depends on the API version: * 2018-09-01: :class:`TasksOperations<azure.mgmt.containerregistry.v2018_09_01.aio.operations.TasksOperations>` * 2019-04-01: :class:`TasksOperations<azure.mgmt.containerregistry.v2019_04_01.aio.operations.TasksOperations>` * 2019-06-01-preview: :class:`TasksOperations<azure.mgmt.containerregistry.v2019_06_01_preview.aio.operations.TasksOperations>` """ api_version = self._get_api_version('tasks') if api_version == '2018-09-01': from ..v2018_09_01.aio.operations import TasksOperations as OperationClass elif api_version == '2019-04-01': from ..v2019_04_01.aio.operations import TasksOperations as OperationClass elif api_version == '2019-06-01-preview': from ..v2019_06_01_preview.aio.operations import TasksOperations as OperationClass else: raise ValueError("API version {} does not have operation group 'tasks'".format(api_version)) return OperationClass(self._client, self._config, Serializer(self._models_dict(api_version)), Deserializer(self._models_dict(api_version))) @property def tokens(self): """Instance depends on the API version: * 2019-05-01-preview: :class:`TokensOperations<azure.mgmt.containerregistry.v2019_05_01_preview.aio.operations.TokensOperations>` * 2020-11-01-preview: :class:`TokensOperations<azure.mgmt.containerregistry.v2020_11_01_preview.aio.operations.TokensOperations>` * 2021-06-01-preview: :class:`TokensOperations<azure.mgmt.containerregistry.v2021_06_01_preview.aio.operations.TokensOperations>` * 2021-08-01-preview: :class:`TokensOperations<azure.mgmt.containerregistry.v2021_08_01_preview.aio.operations.TokensOperations>` """ api_version = self._get_api_version('tokens') if api_version == '2019-05-01-preview': from ..v2019_05_01_preview.aio.operations import TokensOperations as OperationClass elif api_version == '2020-11-01-preview': from ..v2020_11_01_preview.aio.operations import TokensOperations as OperationClass elif api_version == '2021-06-01-preview': from ..v2021_06_01_preview.aio.operations import TokensOperations as OperationClass elif api_version == '2021-08-01-preview': from ..v2021_08_01_preview.aio.operations import TokensOperations as OperationClass else: raise ValueError("API version {} does not have operation group 'tokens'".format(api_version)) return OperationClass(self._client, self._config, Serializer(self._models_dict(api_version)), Deserializer(self._models_dict(api_version))) @property def webhooks(self): """Instance depends on the API version: * 2017-10-01: :class:`WebhooksOperations<azure.mgmt.containerregistry.v2017_10_01.aio.operations.WebhooksOperations>` * 2019-05-01: :class:`WebhooksOperations<azure.mgmt.containerregistry.v2019_05_01.aio.operations.WebhooksOperations>` * 2019-12-01-preview: :class:`WebhooksOperations<azure.mgmt.containerregistry.v2019_12_01_preview.aio.operations.WebhooksOperations>` * 2020-11-01-preview: :class:`WebhooksOperations<azure.mgmt.containerregistry.v2020_11_01_preview.aio.operations.WebhooksOperations>` * 2021-06-01-preview: :class:`WebhooksOperations<azure.mgmt.containerregistry.v2021_06_01_preview.aio.operations.WebhooksOperations>` * 2021-08-01-preview: :class:`WebhooksOperations<azure.mgmt.containerregistry.v2021_08_01_preview.aio.operations.WebhooksOperations>` """ api_version = self._get_api_version('webhooks') if api_version == '2017-10-01': from ..v2017_10_01.aio.operations import WebhooksOperations as OperationClass elif api_version == '2019-05-01': from ..v2019_05_01.aio.operations import WebhooksOperations as OperationClass elif api_version == '2019-12-01-preview': from ..v2019_12_01_preview.aio.operations import WebhooksOperations as OperationClass elif api_version == '2020-11-01-preview': from ..v2020_11_01_preview.aio.operations import WebhooksOperations as OperationClass elif api_version == '2021-06-01-preview': from ..v2021_06_01_preview.aio.operations import WebhooksOperations as OperationClass elif api_version == '2021-08-01-preview': from ..v2021_08_01_preview.aio.operations import WebhooksOperations as OperationClass else: raise ValueError("API version {} does not have operation group 'webhooks'".format(api_version)) return OperationClass(self._client, self._config, Serializer(self._models_dict(api_version)), Deserializer(self._models_dict(api_version))) async def close(self): await self._client.close() async def __aenter__(self): await self._client.__aenter__() return self async def __aexit__(self, *exc_details): await self._client.__aexit__(*exc_details)
sdk/containerregistry/azure-mgmt-containerregistry/azure/mgmt/containerregistry/aio/_container_registry_management_client.py
35,215
ContainerRegistryManagementClient. This ready contains multiple API versions, to help you deal with all of the Azure clouds (Azure Stack, Azure Government, Azure China, etc.). By default, it uses the latest API version available on public Azure. For production, you should stick to a particular api-version and/or profile. The profile sets a mapping between an operation group and its API version. The api-version parameter sets the default API version if the operation group is not described in the profile. :param credential: Credential needed for the client to connect to Azure. :type credential: ~azure.core.credentials_async.AsyncTokenCredential :param subscription_id: The Microsoft Azure subscription ID. :type subscription_id: str :param api_version: API version to use if no profile is provided, or if missing in profile. :type api_version: str :param base_url: Service URL :type base_url: str :param profile: A profile definition, from KnownProfiles to dict. :type profile: azure.profiles.KnownProfiles :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. This is a fake class to support current implemetation of MultiApiClientMixin." Will be removed in final version of multiapi azure-core based client Instance depends on the API version: * 2019-06-01-preview: :class:`AgentPoolsOperations<azure.mgmt.containerregistry.v2019_06_01_preview.aio.operations.AgentPoolsOperations>` Instance depends on the API version: * 2018-02-01-preview: :class:`BuildStepsOperations<azure.mgmt.containerregistry.v2018_02_01_preview.aio.operations.BuildStepsOperations>` Instance depends on the API version: * 2018-02-01-preview: :class:`BuildTasksOperations<azure.mgmt.containerregistry.v2018_02_01_preview.aio.operations.BuildTasksOperations>` Instance depends on the API version: * 2018-02-01-preview: :class:`BuildsOperations<azure.mgmt.containerregistry.v2018_02_01_preview.aio.operations.BuildsOperations>` Instance depends on the API version: * 2020-11-01-preview: :class:`ConnectedRegistriesOperations<azure.mgmt.containerregistry.v2020_11_01_preview.aio.operations.ConnectedRegistriesOperations>` * 2021-06-01-preview: :class:`ConnectedRegistriesOperations<azure.mgmt.containerregistry.v2021_06_01_preview.aio.operations.ConnectedRegistriesOperations>` * 2021-08-01-preview: :class:`ConnectedRegistriesOperations<azure.mgmt.containerregistry.v2021_08_01_preview.aio.operations.ConnectedRegistriesOperations>` Instance depends on the API version: * 2019-12-01-preview: :class:`ExportPipelinesOperations<azure.mgmt.containerregistry.v2019_12_01_preview.aio.operations.ExportPipelinesOperations>` * 2020-11-01-preview: :class:`ExportPipelinesOperations<azure.mgmt.containerregistry.v2020_11_01_preview.aio.operations.ExportPipelinesOperations>` * 2021-06-01-preview: :class:`ExportPipelinesOperations<azure.mgmt.containerregistry.v2021_06_01_preview.aio.operations.ExportPipelinesOperations>` * 2021-08-01-preview: :class:`ExportPipelinesOperations<azure.mgmt.containerregistry.v2021_08_01_preview.aio.operations.ExportPipelinesOperations>` Instance depends on the API version: * 2019-12-01-preview: :class:`ImportPipelinesOperations<azure.mgmt.containerregistry.v2019_12_01_preview.aio.operations.ImportPipelinesOperations>` * 2020-11-01-preview: :class:`ImportPipelinesOperations<azure.mgmt.containerregistry.v2020_11_01_preview.aio.operations.ImportPipelinesOperations>` * 2021-06-01-preview: :class:`ImportPipelinesOperations<azure.mgmt.containerregistry.v2021_06_01_preview.aio.operations.ImportPipelinesOperations>` * 2021-08-01-preview: :class:`ImportPipelinesOperations<azure.mgmt.containerregistry.v2021_08_01_preview.aio.operations.ImportPipelinesOperations>` Module depends on the API version: * 2017-03-01: :mod:`v2017_03_01.models<azure.mgmt.containerregistry.v2017_03_01.models>` * 2017-10-01: :mod:`v2017_10_01.models<azure.mgmt.containerregistry.v2017_10_01.models>` * 2018-02-01-preview: :mod:`v2018_02_01_preview.models<azure.mgmt.containerregistry.v2018_02_01_preview.models>` * 2018-09-01: :mod:`v2018_09_01.models<azure.mgmt.containerregistry.v2018_09_01.models>` * 2019-04-01: :mod:`v2019_04_01.models<azure.mgmt.containerregistry.v2019_04_01.models>` * 2019-05-01: :mod:`v2019_05_01.models<azure.mgmt.containerregistry.v2019_05_01.models>` * 2019-05-01-preview: :mod:`v2019_05_01_preview.models<azure.mgmt.containerregistry.v2019_05_01_preview.models>` * 2019-06-01-preview: :mod:`v2019_06_01_preview.models<azure.mgmt.containerregistry.v2019_06_01_preview.models>` * 2019-12-01-preview: :mod:`v2019_12_01_preview.models<azure.mgmt.containerregistry.v2019_12_01_preview.models>` * 2020-11-01-preview: :mod:`v2020_11_01_preview.models<azure.mgmt.containerregistry.v2020_11_01_preview.models>` * 2021-06-01-preview: :mod:`v2021_06_01_preview.models<azure.mgmt.containerregistry.v2021_06_01_preview.models>` * 2021-08-01-preview: :mod:`v2021_08_01_preview.models<azure.mgmt.containerregistry.v2021_08_01_preview.models>` Instance depends on the API version: * 2017-03-01: :class:`Operations<azure.mgmt.containerregistry.v2017_03_01.aio.operations.Operations>` * 2017-10-01: :class:`Operations<azure.mgmt.containerregistry.v2017_10_01.aio.operations.Operations>` * 2019-05-01: :class:`Operations<azure.mgmt.containerregistry.v2019_05_01.aio.operations.Operations>` * 2019-12-01-preview: :class:`Operations<azure.mgmt.containerregistry.v2019_12_01_preview.aio.operations.Operations>` * 2020-11-01-preview: :class:`Operations<azure.mgmt.containerregistry.v2020_11_01_preview.aio.operations.Operations>` * 2021-06-01-preview: :class:`Operations<azure.mgmt.containerregistry.v2021_06_01_preview.aio.operations.Operations>` * 2021-08-01-preview: :class:`Operations<azure.mgmt.containerregistry.v2021_08_01_preview.aio.operations.Operations>` Instance depends on the API version: * 2019-12-01-preview: :class:`PipelineRunsOperations<azure.mgmt.containerregistry.v2019_12_01_preview.aio.operations.PipelineRunsOperations>` * 2020-11-01-preview: :class:`PipelineRunsOperations<azure.mgmt.containerregistry.v2020_11_01_preview.aio.operations.PipelineRunsOperations>` * 2021-06-01-preview: :class:`PipelineRunsOperations<azure.mgmt.containerregistry.v2021_06_01_preview.aio.operations.PipelineRunsOperations>` * 2021-08-01-preview: :class:`PipelineRunsOperations<azure.mgmt.containerregistry.v2021_08_01_preview.aio.operations.PipelineRunsOperations>` Instance depends on the API version: * 2019-12-01-preview: :class:`PrivateEndpointConnectionsOperations<azure.mgmt.containerregistry.v2019_12_01_preview.aio.operations.PrivateEndpointConnectionsOperations>` * 2020-11-01-preview: :class:`PrivateEndpointConnectionsOperations<azure.mgmt.containerregistry.v2020_11_01_preview.aio.operations.PrivateEndpointConnectionsOperations>` * 2021-06-01-preview: :class:`PrivateEndpointConnectionsOperations<azure.mgmt.containerregistry.v2021_06_01_preview.aio.operations.PrivateEndpointConnectionsOperations>` * 2021-08-01-preview: :class:`PrivateEndpointConnectionsOperations<azure.mgmt.containerregistry.v2021_08_01_preview.aio.operations.PrivateEndpointConnectionsOperations>` Instance depends on the API version: * 2017-03-01: :class:`RegistriesOperations<azure.mgmt.containerregistry.v2017_03_01.aio.operations.RegistriesOperations>` * 2017-10-01: :class:`RegistriesOperations<azure.mgmt.containerregistry.v2017_10_01.aio.operations.RegistriesOperations>` * 2018-02-01-preview: :class:`RegistriesOperations<azure.mgmt.containerregistry.v2018_02_01_preview.aio.operations.RegistriesOperations>` * 2018-09-01: :class:`RegistriesOperations<azure.mgmt.containerregistry.v2018_09_01.aio.operations.RegistriesOperations>` * 2019-04-01: :class:`RegistriesOperations<azure.mgmt.containerregistry.v2019_04_01.aio.operations.RegistriesOperations>` * 2019-05-01: :class:`RegistriesOperations<azure.mgmt.containerregistry.v2019_05_01.aio.operations.RegistriesOperations>` * 2019-05-01-preview: :class:`RegistriesOperations<azure.mgmt.containerregistry.v2019_05_01_preview.aio.operations.RegistriesOperations>` * 2019-06-01-preview: :class:`RegistriesOperations<azure.mgmt.containerregistry.v2019_06_01_preview.aio.operations.RegistriesOperations>` * 2019-12-01-preview: :class:`RegistriesOperations<azure.mgmt.containerregistry.v2019_12_01_preview.aio.operations.RegistriesOperations>` * 2020-11-01-preview: :class:`RegistriesOperations<azure.mgmt.containerregistry.v2020_11_01_preview.aio.operations.RegistriesOperations>` * 2021-06-01-preview: :class:`RegistriesOperations<azure.mgmt.containerregistry.v2021_06_01_preview.aio.operations.RegistriesOperations>` * 2021-08-01-preview: :class:`RegistriesOperations<azure.mgmt.containerregistry.v2021_08_01_preview.aio.operations.RegistriesOperations>` Instance depends on the API version: * 2017-10-01: :class:`ReplicationsOperations<azure.mgmt.containerregistry.v2017_10_01.aio.operations.ReplicationsOperations>` * 2019-05-01: :class:`ReplicationsOperations<azure.mgmt.containerregistry.v2019_05_01.aio.operations.ReplicationsOperations>` * 2019-12-01-preview: :class:`ReplicationsOperations<azure.mgmt.containerregistry.v2019_12_01_preview.aio.operations.ReplicationsOperations>` * 2020-11-01-preview: :class:`ReplicationsOperations<azure.mgmt.containerregistry.v2020_11_01_preview.aio.operations.ReplicationsOperations>` * 2021-06-01-preview: :class:`ReplicationsOperations<azure.mgmt.containerregistry.v2021_06_01_preview.aio.operations.ReplicationsOperations>` * 2021-08-01-preview: :class:`ReplicationsOperations<azure.mgmt.containerregistry.v2021_08_01_preview.aio.operations.ReplicationsOperations>` Instance depends on the API version: * 2018-09-01: :class:`RunsOperations<azure.mgmt.containerregistry.v2018_09_01.aio.operations.RunsOperations>` * 2019-04-01: :class:`RunsOperations<azure.mgmt.containerregistry.v2019_04_01.aio.operations.RunsOperations>` * 2019-06-01-preview: :class:`RunsOperations<azure.mgmt.containerregistry.v2019_06_01_preview.aio.operations.RunsOperations>` Instance depends on the API version: * 2019-05-01-preview: :class:`ScopeMapsOperations<azure.mgmt.containerregistry.v2019_05_01_preview.aio.operations.ScopeMapsOperations>` * 2020-11-01-preview: :class:`ScopeMapsOperations<azure.mgmt.containerregistry.v2020_11_01_preview.aio.operations.ScopeMapsOperations>` * 2021-06-01-preview: :class:`ScopeMapsOperations<azure.mgmt.containerregistry.v2021_06_01_preview.aio.operations.ScopeMapsOperations>` * 2021-08-01-preview: :class:`ScopeMapsOperations<azure.mgmt.containerregistry.v2021_08_01_preview.aio.operations.ScopeMapsOperations>` Instance depends on the API version: * 2019-06-01-preview: :class:`TaskRunsOperations<azure.mgmt.containerregistry.v2019_06_01_preview.aio.operations.TaskRunsOperations>` Instance depends on the API version: * 2018-09-01: :class:`TasksOperations<azure.mgmt.containerregistry.v2018_09_01.aio.operations.TasksOperations>` * 2019-04-01: :class:`TasksOperations<azure.mgmt.containerregistry.v2019_04_01.aio.operations.TasksOperations>` * 2019-06-01-preview: :class:`TasksOperations<azure.mgmt.containerregistry.v2019_06_01_preview.aio.operations.TasksOperations>` Instance depends on the API version: * 2019-05-01-preview: :class:`TokensOperations<azure.mgmt.containerregistry.v2019_05_01_preview.aio.operations.TokensOperations>` * 2020-11-01-preview: :class:`TokensOperations<azure.mgmt.containerregistry.v2020_11_01_preview.aio.operations.TokensOperations>` * 2021-06-01-preview: :class:`TokensOperations<azure.mgmt.containerregistry.v2021_06_01_preview.aio.operations.TokensOperations>` * 2021-08-01-preview: :class:`TokensOperations<azure.mgmt.containerregistry.v2021_08_01_preview.aio.operations.TokensOperations>` Instance depends on the API version: * 2017-10-01: :class:`WebhooksOperations<azure.mgmt.containerregistry.v2017_10_01.aio.operations.WebhooksOperations>` * 2019-05-01: :class:`WebhooksOperations<azure.mgmt.containerregistry.v2019_05_01.aio.operations.WebhooksOperations>` * 2019-12-01-preview: :class:`WebhooksOperations<azure.mgmt.containerregistry.v2019_12_01_preview.aio.operations.WebhooksOperations>` * 2020-11-01-preview: :class:`WebhooksOperations<azure.mgmt.containerregistry.v2020_11_01_preview.aio.operations.WebhooksOperations>` * 2021-06-01-preview: :class:`WebhooksOperations<azure.mgmt.containerregistry.v2021_06_01_preview.aio.operations.WebhooksOperations>` * 2021-08-01-preview: :class:`WebhooksOperations<azure.mgmt.containerregistry.v2021_08_01_preview.aio.operations.WebhooksOperations>` coding=utf-8 -------------------------------------------------------------------------- Copyright (c) Microsoft Corporation. All rights reserved. Licensed under the MIT License. See License.txt in the project root for license information. Code generated by Microsoft (R) AutoRest Code Generator. Changes may cause incorrect behavior and will be lost if the code is regenerated. -------------------------------------------------------------------------- pylint: disable=unused-import,ungrouped-imports type: Any
13,043
en
0.395959
import os import json import numpy as np import itertools import matplotlib.pyplot as plt from mpl_toolkits.mplot3d.art3d import Line3DCollection from mpl_toolkits import mplot3d def liver_dump_init(env, name = None): liver = {'x':[],'Fes':[],'Fis':[],'Ficp':[],'volume':[],'col_p_n':[],'crash':[]} liver['vtx'] = env.liver.x.copy() if name is not None: liver['name'] = name else: liver['name'] = f"_dt{env.timestep}_down_gm{env.liver.gamma}" return liver def liver_dump_step(liver,env): liver['x'].append(env.liver.x) liver['Fes'].append(env.liver.Fes) liver['Fis'].append(env.liver.Fis) liver['Ficp'].append(env.liver.Ficp) liver['volume'].append(np.round(env.liver.volumes6.sum() / env.liver.init_volume6.sum(),3)) liver['col_p_n'].append(len(env.liver.check_tet_aabb_collision(env.sg.x))) liver['crash'].append(env.liver.crash_flag) return liver def liver_dump(liver,ep = None): liver_save ={} liver_save['vtx'] = liver['vtx'].tolist() liver_save['x'] = np.array(liver['x']).tolist() liver_save['Fes'] = np.array(liver['Fes']).tolist() liver_save['Fis'] = np.array(liver['Fis']).tolist() liver_save['Ficp'] = np.array(liver['Ficp']).tolist() liver_save['volume'] = np.array(liver['volume']).tolist() liver_save['col_p_n']= np.array(liver['col_p_n']).tolist() liver_save['crash'] = np.array(liver['crash']).tolist() if ep is None: with open(os.path.join('liver_json',f"liver_record{liver['name']}.json"),'w') as f: json.dump(liver_save,f) else: with open(os.path.join('liver_json',f"liver_record_{int(ep)}.json"),'w') as f: json.dump(liver_save,f) def liver_dump_load(liver): vtx = np.array(liver['vtx']) x = np.array(liver['x']) Fes = np.array(liver['Fes']) Fis = np.array(liver['Fis']) Ficp = np.array(liver['Ficp']) volume = np.array(liver['volume']) col_p_n = np.array(liver['col_p_n']) crash = np.array(liver['crash']) return vtx, x, Fes, Fis, Ficp, volume, col_p_n, crash ''' temp: 1. collision_response_cotin 2. collision_response_self ''' def collision_response_cotin(pair,liver,past_p,current_p): # check bc_co for all surface tri_element # add dn to decide move_v_disp_dict = {} move_tri_indexs = [] flat_list = [item for sublist in list(pair.values()) for item in sublist] p_indexs = np.array(flat_list).reshape(-1) p_n = p_indexs.shape[0] ray = current_p[p_indexs]-past_p[p_indexs] ray = ray*(1/np.linalg.norm(ray,axis=-1))[:,None] # p_n x3 # compute ray and normal vector, d= ray,n=normal_vec dn = ray@liver.tri_normal_vec.T # p_n x n_tri ap = liver.x[liver.tri_elements[:,0]][None,:] - past_p[p_indexs][:,None] # p_n x n_tri x 3 #choose first point as a apn = (ap * liver.tri_normal_vec[None,:]).sum(axis=-1) # p_n x n_tri x 3 -> p_n x n_tri ts = apn * (1/dn) # p_n x n_tri int_p = ts[:,:,None]*ray[:,None]+past_p[p_indexs][:,None] # p_n x n_tri x3 <- p_n x n_tri x1 * p_n x1 x3 + p_n x1 x3 # compute barycentric coordinates of intersection points v1 = liver.x[liver.tri_elements[:,1]]-liver.x[liver.tri_elements[:,0]] # n_tri x3 v2 = liver.x[liver.tri_elements[:,2]]-liver.x[liver.tri_elements[:,0]] tri_areax2 = np.linalg.norm(np.cross(v1,v2,axis=-1),axis=-1) # n_tri bc_temp = np.zeros((p_n,liver.n_tri,3,3,3)) bc_temp[:] = np.tile(liver.x[liver.tri_elements], 3).reshape(-1, 3, 3, 3).transpose(0, 2, 1, 3) # p_n x n_tri x 3area x 3ps x 3 for itemp in range(p_n): bc_temp[itemp, :, [0, 1, 2], [0, 1, 2]] = int_p[itemp] v1 = bc_temp[:, :, :, 1] - bc_temp[:, :, :, 0] # p_n x n_tri x 3area x 3xyz v2 = bc_temp[:, :, :, 2] - bc_temp[:, :, :, 0] areax2 = np.linalg.norm(np.cross(v1, v2, axis=-1), axis=-1) # p_n x n_tri x 3area bc_co = areax2 * (1.0 / tri_areax2)[np.newaxis, :, np.newaxis] # p_n x n_tri x 3area<- p_n x n_tri x 3area * 1 x n_tri x 3area for itemp in range(p_n): # check bc_co check1 = np.argwhere(abs(bc_co[itemp].sum(axis=-1) - 1) < 1e-3).flatten() # each p should have at least 1 check2 = np.argwhere(dn[itemp] < 0).flatten() psb_tri_index = np.intersect1d(check1,check2) # all possible tri_elements satisfies the bc_co and the negative normal vector if psb_tri_index.size!=0: psb_ts = ts[itemp,psb_tri_index] # n_psb_tri_index # if np.any(psb_ts<0): # raise ValueError("liver shape error") move_tri_index = psb_tri_index[psb_ts.argmin()] # only 1 the tri_elements should move move_t = current_p[p_indexs[itemp]] - int_p[itemp,move_tri_index] move_v_index_p = liver.tri_elements[move_tri_index] for ividx in move_v_index_p: # same points may move multiple times. if ividx not in move_v_disp_dict.keys(): move_v_disp_dict[ividx] = move_t # move_t put in for new vindex else:# compare move_t for old vindex if np.linalg.norm(np.c_[move_v_disp_dict[ividx],move_t].T,axis=-1).argmax() == 1 : # older move closer than new move_v_disp_dict[ividx] = move_t move_tri_indexs.append(move_tri_index.tolist()) print(move_tri_indexs) return move_v_disp_dict def collision_response_self(pair, liver, tool): # not so good when the deform is bigger # change to old fixed to test, problem still, try cotin methods new_vtx_delta = None move_tris = {} nv_aves = {} new_vtx_deltas = {} for key, value in pair.items(): new_vtx_delta = np.zeros(liver.x.shape) i_tet, p_index = int(key), np.array(value) p_n = p_index.shape[0] # find potential collpaision surface tri_element col_tri_index = np.argwhere(liver.tri_tet[:, 0] == i_tet).flatten() if col_tri_index.size == 0: raise ValueError( "Update time step too big, vertices skip the surface tetrahedron elements") col_tri_n = col_tri_index.shape[0] col_tri_nv = liver.tri_normal_vec[col_tri_index] col_tri_p = liver.x[liver.tri_elements[col_tri_index].T[0]] # chose the first points # compute nv_ave nv_ave = tool.vtx_normal_vec[p_index].sum(axis=0) nv_ave = nv_ave / np.linalg.norm(nv_ave) nv_aves[key] = nv_ave # compute ts and intersection points dn = nv_ave.dot(col_tri_nv.T) # col_tri_n ap = col_tri_p[np.newaxis, :] - tool.x[p_index, np.newaxis] # p_n x col_tri_n x 3 dotn = np.tile(col_tri_nv, p_n).reshape(-1, p_n, 3).transpose(1, 0, 2) apn = (ap * dotn).sum(axis=-1) # p_n x col_tri_n ts = apn * (1 / dn) # p_n x col_tri_n int_col_p = ts[:, :, np.newaxis] * nv_ave[np.newaxis, np.newaxis, :] \ + tool.vertices[p_index][:, np.newaxis, :] # p_n x col_tri_n x 1 * 1 x 1 x 3 + p_n x 1 x 3 # compute barycentric coordinates of intersection points tri_vertices = liver.x[liver.tri_elements[col_tri_index]] # n_tri x 3 x 3 v1 = tri_vertices[:, 1] - tri_vertices[:, 0] v2 = tri_vertices[:, 2] - tri_vertices[:, 0] tri_areax2 = np.linalg.norm(np.cross(v1, v2, axis=-1), axis=-1) # n_tri bc_temp = np.zeros((p_n, col_tri_n, 3, 3, 3)) bc_temp[:] = np.tile(tri_vertices, 3).reshape(-1, 3, 3, 3).transpose(0, 2, 1, 3) # p_n x col_tri_n x 3 x 3 x 3 for itemp in range(p_n): bc_temp[itemp, :, [0, 1, 2], [0, 1, 2]] = int_col_p[itemp] v1 = bc_temp[:, :, :, 1] - bc_temp[:, :, :, 0] # p_n x col_tri_n x 3area x 3xyz v2 = bc_temp[:, :, :, 2] - bc_temp[:, :, :, 0] areax2 = np.linalg.norm(np.cross(v1, v2, axis=-1), axis=-1) # p_n x col_tri_n x 3area bc_co = areax2 * (1.0 / tri_areax2)[np.newaxis, :, np.newaxis] # p_n x col_tri_n x 3area * 1 x col_tri_n x 3area = p_n x col_tri_n x 3area # Move tri to point with tmax check1 = np.argwhere(abs(bc_co.sum(axis=-1) - 1) < 1e-3) check2 = np.argwhere(dn < 0) inter_tri_index = np.intersect1d(check1[:, 1], check2) # find colliable surface tri_elements index # no colliable tri_elements if inter_tri_index.size == 0: the_best_tri = dn.argmin() # chose one of most collidable tri move_tri = liver.tri_elements[col_tri_index[the_best_tri]] tri_nv = liver.tri_normal_vec[col_tri_index[the_best_tri]].flatten() tri_vtx = liver.x[move_tri].reshape(3, 3) v = nv_ave - tri_nv # find a new direction, not so sharp as nv_ave v = v / np.linalg.norm(v) dn_t = v.dot(tri_nv) # 1 ap_t = tri_vtx[0] - tool.x[p_index] t_t = ap_t.dot(tri_nv) / dn_t move_t = t_t.min() new_vtx_delta[move_tri] += - move_t * v new_vtx_deltas.setdefault(key, []).append(new_vtx_delta) move_tris.setdefault(key, []).append(move_tri.flatten()) print(' None ',end='') else: # more than 1 colliable tri_elements if len(inter_tri_index) > 1: temp_delta = np.zeros((liver.x.shape[0], len(inter_tri_index))) # n_v * n_inter itemp = 0 for inter_tri_i in inter_tri_index: part_p_index = check1[ check1[:, 1] == inter_tri_i, 0] # p index of each tri_element that satisfies bc_co condition move_t = ts[part_p_index, inter_tri_i].min() move_tri = liver.tri_elements[col_tri_index[inter_tri_i]] temp_delta[move_tri, itemp] = - move_t # collect all possible move_t for all vertices move_tris.setdefault(key, []).append(move_tri.flatten()) itemp += 1 new_vtx_delta += temp_delta.max(axis=-1)[:, np.newaxis] * nv_ave[np.newaxis,:] # move with the maximal move_t new_vtx_deltas.setdefault(key, []).append(new_vtx_delta) print(' Multi ',end='') else: # only 1 colliable tri_elements move_t = ts[:, inter_tri_index].min() move_tri = liver.tri_elements[col_tri_index[inter_tri_index]] new_vtx_delta[move_tri] += -move_t * nv_ave new_vtx_deltas.setdefault(key, []).append(new_vtx_delta) move_tris.setdefault(key, []).append(move_tri.flatten()) print(' Single ',end='') return new_vtx_delta, move_tris, nv_aves, new_vtx_deltas ''' static methods: 1. lame_param 2. tri_mid_vec 3. rotation_matrix 4. flatten_list ''' def lame_param(E, v): la = E * v / (1 + v) / (1 - 2 * v) mu = E / 2 / (1 + v) return la, mu def tri_mid_vec(vertices, tri_elements): tri_vtx = vertices[tri_elements] tri_mid = tri_vtx.mean(axis=1) tri_normal_vec = np.cross(tri_vtx[:, 1] - tri_vtx[:, 0], tri_vtx[:, 2] - tri_vtx[:, 0]) tri_normal_vec = tri_normal_vec * (1.0 / np.linalg.norm(tri_normal_vec, axis=1))[:, np.newaxis] return tri_mid, tri_normal_vec def rotation_matrix(deg,axis='x'): rad = np.deg2rad(deg) s,c = np.sin(rad),np.cos(rad) if axis=='x': return np.array([ 1, 0, 0, 0, c, -s, 0, s, c]).reshape(-1,3) elif axis=='y': return np.array([ c, 0, s, 0, 1, 0, -s, 0, c]).reshape(-1,3) elif axis=='z': return np.array([ c, -s, 0, s, c, 0, 0, 0, 1]).reshape(-1,3) else: return np.ones((3,3)) # def flatten_list(l): # # not work well # for el in l: # if isinstance(el, Iterable) and not isinstance(el, (str, bytes)): # return flatten_list(el) # else: # return el ''' matplotlibe subplot 1. create_axs 2. draw_liver 3. draw_liver_tool ''' def create_axs(subplot_n,block=False,return_fig=False): r = int(np.floor(np.sqrt(subplot_n))) c = int(subplot_n/r) fig = plt.figure(figsize=plt.figaspect(0.5)) axs = {} for i in range(subplot_n): axs[i] = fig.add_subplot(r, c, i+1, projection='3d') if return_fig: return axs,fig return axs def draw_liver(liver,ax): ax.cla() ax = liver.plt_vtx(ax=ax) ax = liver.plt_x(ax=ax) plt_equal(ax) return ax def draw_liver_F(liver,axs,f_scl = 5e0): # Fes, Ficp, Fis+ displacement axs[0].cla() axs[0] = liver.plt_x(ax=axs[0]) axs[0] = liver.plt_Fes(vec_to_scl=f_scl,ax=axs[0]) plt_equal(axs[0]) axs[1].cla() axs[1] = liver.plt_x(ax=axs[1]) axs[1] = liver.plt_Ficp(vec_to_scl=f_scl,ax=axs[1]) plt_equal(axs[1]) axs[2].cla() axs[2] = liver.plt_vtx(ax=axs[2]) axs[2] = liver.plt_x(ax=axs[2]) axs[2] = liver.plt_Fis(vec_to_scl=f_scl,ax=axs[2]) plt_equal(axs[2]) return axs def draw_liver_tool(liver,sg,axs,f_scl=5e0): axs[0].cla() axs[0] = liver.plt_x(ax=axs[0]) axs[0] = liver.plt_tri_normal_vec(vec_scl=f_scl/2,ax=axs[0]) plt_equal(axs[0]) axs[1].cla() axs[1] = sg.plt_sg_x(ax=axs[1]) axs[1] = sg._plt_vtx_normal_vec(sg.x,vec_scl=f_scl/2,ax=axs[1]) plt_equal(axs[1]) axs[2].cla() axs[2] = liver.plt_x(ax=axs[2]) axs[2] = sg.plt_sg_x(ax=axs[2]) plt_equal(axs[2]) axs_l = {axs[3],axs[4],axs[5]} axs_l = draw_liver(liver,axs_l,f_scl=f_scl) axs[3],axs[4],axs[5] = axs_l[0],axs_l[1],axs_l[2] plt.draw()#plt.show(block=False) return axs ''' aabb 1. xyzminmax 2. _plt_AABB 3. plt_aabb_p ''' def xyzminmax(aabb): # xmin, ymin, zmin, xmax, ymax, zmax = aabb[0], aabb[1], aabb[2], aabb[3], aabb[4], aabb[5] return aabb[0], aabb[1], aabb[2], aabb[3], aabb[4], aabb[5] def plt_AABB(aabb, **kwargs): c_line = '#9467bd' c_p = '#e377c2' if 'c' in kwargs.keys(): colors = kwargs['c'] if type(colors) is list: c_line = colors[0] c_p = colors[1] elif type(colors) is str: c_line = colors ax = ax3d_handle(**kwargs) # aabb: 1x6, xmin, ymin, zmin, xmax, ymax, zmax xmin, ymin, zmin, xmax, ymax, zmax = xyzminmax(aabb) xyz = np.array([xmin, ymin, zmin, xmax, ymin, zmin, xmax, ymax, zmin, xmin, ymax, zmin, xmin, ymin, zmax, xmax, ymin, zmax, xmax, ymax, zmax, xmin, ymax, zmax]).reshape(-1, 3) line_segs = np.array([1, 2, 2, 3, 3, 4, 4, 1, 1, 5, 2, 6, 3, 7, 4, 8, 5, 6, 6, 7, 7, 8, 8, 5]).reshape(-1, 2) - 1 line_vt = np.hstack((xyz[line_segs[:, 0]], xyz[line_segs[:, 1]])).copy() lc = Line3DCollection(line_vt.reshape(-1, 2, 3), colors=c_line, linestyles='--') ax.add_collection(lc) ax.scatter(xyz[:, 0], xyz[:, 1], xyz[:, 2], marker='o', c=c_p) return ax def plt_aabb_p(aabb, p, **kwargs): ax = ax3d_handle(**kwargs) ax.scatter(p[0], p[1], p[2], c='#22D8C3') plt_AABB(aabb, ax=ax) return ax ''' ax handle 1. 1) plt_equal 2) plt_show_equal 3) set_axes_equal 4) _set_axes_radius 2. ax3d_handle 3. plt_tet 4. plt_tet_ps 5. plt_normal_vecs 6. plt_tri 7. plt_tri_ps ''' def plt_equal(ax,limits = None): ax.set_box_aspect((1, 1, 1)) # IMPORTANT - this is the new, key line set_axes_equal(ax,limits=limits) # IMPORTANT - this is also required def plt_show_equal(ax,block=False,limits = None): plt_equal(ax,limits=limits) plt.show(block=block) def set_axes_equal(ax: plt.Axes,limits = None): """Set 3D plot axes to equal scale. Make axes of 3D plot have equal scale so that spheres appear as spheres and cubes as cubes. Required since `ax.axis('equal')` and `ax.set_aspect('equal')` don't work on 3D. """ if limits is None: limits = np.array([ ax.get_xlim3d(), ax.get_ylim3d(), ax.get_zlim3d(), ]) origin = np.mean(limits, axis=1) radius = 0.5 * np.max(np.abs(limits[:, 1] - limits[:, 0])) _set_axes_radius(ax, origin, radius) def _set_axes_radius(ax, origin, radius): x, y, z = origin ax.set_xlim3d([x - radius, x + radius]) ax.set_ylim3d([y - radius, y + radius]) ax.set_zlim3d([z - radius, z + radius]) def ax3d_handle(return_fig=False,**kwargs): if 'ax' in kwargs: ax = kwargs['ax'] else: fig = plt.figure(figsize=(8,6)) ax = fig.add_subplot(projection='3d') if return_fig: return ax,fig return ax def plt_tet(vs, text_opt='off', **kwargs): ax = ax3d_handle(**kwargs) ax.scatter(vs[:, 0], vs[:, 1], vs[:, 2], c='#BCB6E3') if text_opt == "on": for i in range(4): ax.text(vs[i, 0], vs[i, 1], vs[i, 2], f'{i + 1}') line_order = np.array([1, 2, 1, 3, 1, 4, 2, 3, 2, 4, 3, 4]).reshape(-1, 2) - 1 line_vt = np.hstack((vs[line_order[:, 0]], vs[line_order[:, 1]])) lc = Line3DCollection(line_vt.reshape(-1, 2, 3), colors='#8A7BFB') ax.add_collection(lc) return ax def plt_tet_ps(vs, p, text_opt='off', **kwargs): p = np.array(p) ax = ax3d_handle(**kwargs) ax = plt_tet(vs, text_opt=text_opt, ax=ax) if len(p.shape) == 1: p = p.reshape(1, -1) ax.scatter(p[:, 0], p[:, 1], p[:, 2], c='#22D8C3') return ax def plt_normal_vecs(base_ps, vecs, scl=1, **kwargs): vesc_scl = vecs * scl ax = ax3d_handle(**kwargs) ax.scatter(base_ps[:, 0], base_ps[:, 1], base_ps[:, 2], c='#1D1788') ax.quiver(base_ps[:, 0], base_ps[:, 1], base_ps[:, 2], vesc_scl[:, 0], vesc_scl[:, 1], vesc_scl[:, 2], color='#7D75FE') return ax def plt_tet_ps_vecs(vs, p, vec, scl=1, text_opt = 'off', **kwargs): ax = ax3d_handle(**kwargs) ax = plt_tet_ps(vs, p, ax=ax, text_opt = text_opt) if len(p.shape) == 1: p = p.reshape(1, -1) if len(vec.shape) == 1: vec = vec.reshape(1, -1) ax = plt_normal_vecs(p, vec, scl=scl, ax=ax) return ax def plt_tri(vs, text_opt='off', **kwargs): ax = ax3d_handle(**kwargs) ax.scatter(vs[:, 0], vs[:, 1], vs[:, 2], c='#ff00ff') if text_opt == "on": for i in range(3): ax.text(vs[i, 0], vs[i, 1], vs[i, 2], f'{i + 1}') line_order = np.array([1, 2, 1, 3, 2, 3]).reshape(-1, 2) - 1 line_vt = np.hstack((vs[line_order[:, 0]], vs[line_order[:, 1]])) lc = Line3DCollection(line_vt.reshape(-1, 2, 3), colors='#9933ff') ax.add_collection(lc) return ax def plt_tri_ps(vs, p, text_opt='off', **kwargs): ax = ax3d_handle(**kwargs) ax = plt_tri(vs, text_opt=text_opt, ax=ax) if len(p.shape) == 1: p = p.reshape(1, -1) ax.scatter(p[:, 0], p[:, 1], p[:, 2], c='#22D8C3') return ax
env_pyrep/utils.py
19,453
Set 3D plot axes to equal scale. Make axes of 3D plot have equal scale so that spheres appear as spheres and cubes as cubes. Required since `ax.axis('equal')` and `ax.set_aspect('equal')` don't work on 3D. check bc_co for all surface tri_element add dn to decide p_n x3 compute ray and normal vector, d= ray,n=normal_vec p_n x n_tri p_n x n_tri x 3 choose first point as a p_n x n_tri x 3 -> p_n x n_tri p_n x n_tri p_n x n_tri x3 <- p_n x n_tri x1 * p_n x1 x3 + p_n x1 x3 compute barycentric coordinates of intersection points n_tri x3 n_tri p_n x n_tri x 3area x 3ps x 3 p_n x n_tri x 3area x 3xyz p_n x n_tri x 3area p_n x n_tri x 3area<- p_n x n_tri x 3area * 1 x n_tri x 3area check bc_co each p should have at least 1 all possible tri_elements satisfies the bc_co and the negative normal vector n_psb_tri_index if np.any(psb_ts<0): raise ValueError("liver shape error") only 1 the tri_elements should move same points may move multiple times. move_t put in for new vindex compare move_t for old vindex older move closer than new not so good when the deform is bigger change to old fixed to test, problem still, try cotin methods find potential collpaision surface tri_element chose the first points compute nv_ave compute ts and intersection points col_tri_n p_n x col_tri_n x 3 p_n x col_tri_n p_n x col_tri_n p_n x col_tri_n x 1 * 1 x 1 x 3 + p_n x 1 x 3 compute barycentric coordinates of intersection points n_tri x 3 x 3 n_tri p_n x col_tri_n x 3 x 3 x 3 p_n x col_tri_n x 3area x 3xyz p_n x col_tri_n x 3area p_n x col_tri_n x 3area * 1 x col_tri_n x 3area = p_n x col_tri_n x 3area Move tri to point with tmax find colliable surface tri_elements index no colliable tri_elements chose one of most collidable tri find a new direction, not so sharp as nv_ave 1 more than 1 colliable tri_elements n_v * n_inter p index of each tri_element that satisfies bc_co condition collect all possible move_t for all vertices move with the maximal move_t only 1 colliable tri_elements def flatten_list(l): not work well for el in l: if isinstance(el, Iterable) and not isinstance(el, (str, bytes)): return flatten_list(el) else: return el Fes, Ficp, Fis+ displacementplt.show(block=False) xmin, ymin, zmin, xmax, ymax, zmax = aabb[0], aabb[1], aabb[2], aabb[3], aabb[4], aabb[5] aabb: 1x6, xmin, ymin, zmin, xmax, ymax, zmax IMPORTANT - this is the new, key line IMPORTANT - this is also required
2,464
en
0.535975
from django.db import models # Create your models here. class Message(models.Model): tab_name = models.TextField(max_length=50) text = models.TextField(max_length=300)
Robocol/testapp/Interfaz/models.py
176
Create your models here.
24
en
0.920486
from a10sdk.common.A10BaseClass import A10BaseClass class AuthSamlIdp(A10BaseClass): """ :param remote_file: {"optional": true, "type": "string", "description": "Profile name for remote url", "format": "url"} :param use_mgmt_port: {"default": 0, "optional": true, "type": "number", "description": "Use management port as source port", "format": "flag"} :param verify_xml_signature: {"default": 0, "optional": true, "type": "number", "description": "Verify metadata's XML signature", "format": "flag"} :param saml_idp_name: {"description": "Metadata name", "format": "string", "minLength": 1, "optional": true, "maxLength": 63, "type": "string"} :param overwrite: {"default": 0, "optional": true, "type": "number", "description": "Overwrite existing file", "format": "flag"} :param DeviceProxy: The device proxy for REST operations and session handling. Refer to `common/device_proxy.py` Class Description:: SAML metadata of identity provider. Class auth-saml-idp supports CRUD Operations and inherits from `common/A10BaseClass`. This class is the `"PARENT"` class for this module.` URL for this object:: `https://<Hostname|Ip address>//axapi/v3/import/auth-saml-idp`. """ def __init__(self, **kwargs): self.ERROR_MSG = "" self.required=[] self.b_key = "auth-saml-idp" self.a10_url="/axapi/v3/import/auth-saml-idp" self.DeviceProxy = "" self.remote_file = "" self.use_mgmt_port = "" self.verify_xml_signature = "" self.saml_idp_name = "" self.overwrite = "" for keys, value in kwargs.items(): setattr(self,keys, value)
a10sdk/core/A10_import/import_auth_saml_idp.py
1,704
:param remote_file: {"optional": true, "type": "string", "description": "Profile name for remote url", "format": "url"} :param use_mgmt_port: {"default": 0, "optional": true, "type": "number", "description": "Use management port as source port", "format": "flag"} :param verify_xml_signature: {"default": 0, "optional": true, "type": "number", "description": "Verify metadata's XML signature", "format": "flag"} :param saml_idp_name: {"description": "Metadata name", "format": "string", "minLength": 1, "optional": true, "maxLength": 63, "type": "string"} :param overwrite: {"default": 0, "optional": true, "type": "number", "description": "Overwrite existing file", "format": "flag"} :param DeviceProxy: The device proxy for REST operations and session handling. Refer to `common/device_proxy.py` Class Description:: SAML metadata of identity provider. Class auth-saml-idp supports CRUD Operations and inherits from `common/A10BaseClass`. This class is the `"PARENT"` class for this module.` URL for this object:: `https://<Hostname|Ip address>//axapi/v3/import/auth-saml-idp`.
1,127
en
0.431725
# coding: utf-8 """ Intersight REST API This is Intersight REST API OpenAPI spec version: 1.0.9-255 Generated by: https://github.com/swagger-api/swagger-codegen.git """ from pprint import pformat from six import iteritems import re class EquipmentChassis(object): """ NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually. """ """ Attributes: swagger_types (dict): The key is attribute name and the value is attribute type. attribute_map (dict): The key is attribute name and the value is json key in definition. """ swagger_types = { 'account_moid': 'str', 'ancestors': 'list[MoBaseMoRef]', 'create_time': 'datetime', 'mod_time': 'datetime', 'moid': 'str', 'object_type': 'str', 'owners': 'list[str]', 'parent': 'MoBaseMoRef', 'tags': 'list[MoTag]', 'version_context': 'MoVersionContext', 'device_mo_id': 'str', 'dn': 'str', 'rn': 'str', 'model': 'str', 'revision': 'str', 'serial': 'str', 'vendor': 'str', 'blades': 'list[ComputeBladeRef]', 'fanmodules': 'list[EquipmentFanModuleRef]', 'ioms': 'list[EquipmentIoCardRef]', 'oper_state': 'str', 'psus': 'list[EquipmentPsuRef]', 'registered_device': 'AssetDeviceRegistrationRef', 'sasexpanders': 'list[StorageSasExpanderRef]', 'siocs': 'list[EquipmentSystemIoControllerRef]', 'storage_enclosures': 'list[StorageEnclosureRef]' } attribute_map = { 'account_moid': 'AccountMoid', 'ancestors': 'Ancestors', 'create_time': 'CreateTime', 'mod_time': 'ModTime', 'moid': 'Moid', 'object_type': 'ObjectType', 'owners': 'Owners', 'parent': 'Parent', 'tags': 'Tags', 'version_context': 'VersionContext', 'device_mo_id': 'DeviceMoId', 'dn': 'Dn', 'rn': 'Rn', 'model': 'Model', 'revision': 'Revision', 'serial': 'Serial', 'vendor': 'Vendor', 'blades': 'Blades', 'fanmodules': 'Fanmodules', 'ioms': 'Ioms', 'oper_state': 'OperState', 'psus': 'Psus', 'registered_device': 'RegisteredDevice', 'sasexpanders': 'Sasexpanders', 'siocs': 'Siocs', 'storage_enclosures': 'StorageEnclosures' } def __init__(self, account_moid=None, ancestors=None, create_time=None, mod_time=None, moid=None, object_type=None, owners=None, parent=None, tags=None, version_context=None, device_mo_id=None, dn=None, rn=None, model=None, revision=None, serial=None, vendor=None, blades=None, fanmodules=None, ioms=None, oper_state=None, psus=None, registered_device=None, sasexpanders=None, siocs=None, storage_enclosures=None): """ EquipmentChassis - a model defined in Swagger """ self._account_moid = None self._ancestors = None self._create_time = None self._mod_time = None self._moid = None self._object_type = None self._owners = None self._parent = None self._tags = None self._version_context = None self._device_mo_id = None self._dn = None self._rn = None self._model = None self._revision = None self._serial = None self._vendor = None self._blades = None self._fanmodules = None self._ioms = None self._oper_state = None self._psus = None self._registered_device = None self._sasexpanders = None self._siocs = None self._storage_enclosures = None if account_moid is not None: self.account_moid = account_moid if ancestors is not None: self.ancestors = ancestors if create_time is not None: self.create_time = create_time if mod_time is not None: self.mod_time = mod_time if moid is not None: self.moid = moid if object_type is not None: self.object_type = object_type if owners is not None: self.owners = owners if parent is not None: self.parent = parent if tags is not None: self.tags = tags if version_context is not None: self.version_context = version_context if device_mo_id is not None: self.device_mo_id = device_mo_id if dn is not None: self.dn = dn if rn is not None: self.rn = rn if model is not None: self.model = model if revision is not None: self.revision = revision if serial is not None: self.serial = serial if vendor is not None: self.vendor = vendor if blades is not None: self.blades = blades if fanmodules is not None: self.fanmodules = fanmodules if ioms is not None: self.ioms = ioms if oper_state is not None: self.oper_state = oper_state if psus is not None: self.psus = psus if registered_device is not None: self.registered_device = registered_device if sasexpanders is not None: self.sasexpanders = sasexpanders if siocs is not None: self.siocs = siocs if storage_enclosures is not None: self.storage_enclosures = storage_enclosures @property def account_moid(self): """ Gets the account_moid of this EquipmentChassis. The Account ID for this managed object. :return: The account_moid of this EquipmentChassis. :rtype: str """ return self._account_moid @account_moid.setter def account_moid(self, account_moid): """ Sets the account_moid of this EquipmentChassis. The Account ID for this managed object. :param account_moid: The account_moid of this EquipmentChassis. :type: str """ self._account_moid = account_moid @property def ancestors(self): """ Gets the ancestors of this EquipmentChassis. Ancestors is an array containing the MO references of the ancestors in the object containment hierarchy. :return: The ancestors of this EquipmentChassis. :rtype: list[MoBaseMoRef] """ return self._ancestors @ancestors.setter def ancestors(self, ancestors): """ Sets the ancestors of this EquipmentChassis. Ancestors is an array containing the MO references of the ancestors in the object containment hierarchy. :param ancestors: The ancestors of this EquipmentChassis. :type: list[MoBaseMoRef] """ self._ancestors = ancestors @property def create_time(self): """ Gets the create_time of this EquipmentChassis. The time when this managed object was created. :return: The create_time of this EquipmentChassis. :rtype: datetime """ return self._create_time @create_time.setter def create_time(self, create_time): """ Sets the create_time of this EquipmentChassis. The time when this managed object was created. :param create_time: The create_time of this EquipmentChassis. :type: datetime """ self._create_time = create_time @property def mod_time(self): """ Gets the mod_time of this EquipmentChassis. The time when this managed object was last modified. :return: The mod_time of this EquipmentChassis. :rtype: datetime """ return self._mod_time @mod_time.setter def mod_time(self, mod_time): """ Sets the mod_time of this EquipmentChassis. The time when this managed object was last modified. :param mod_time: The mod_time of this EquipmentChassis. :type: datetime """ self._mod_time = mod_time @property def moid(self): """ Gets the moid of this EquipmentChassis. A unique identifier of this Managed Object instance. :return: The moid of this EquipmentChassis. :rtype: str """ return self._moid @moid.setter def moid(self, moid): """ Sets the moid of this EquipmentChassis. A unique identifier of this Managed Object instance. :param moid: The moid of this EquipmentChassis. :type: str """ self._moid = moid @property def object_type(self): """ Gets the object_type of this EquipmentChassis. The fully-qualified type of this managed object, e.g. the class name. :return: The object_type of this EquipmentChassis. :rtype: str """ return self._object_type @object_type.setter def object_type(self, object_type): """ Sets the object_type of this EquipmentChassis. The fully-qualified type of this managed object, e.g. the class name. :param object_type: The object_type of this EquipmentChassis. :type: str """ self._object_type = object_type @property def owners(self): """ Gets the owners of this EquipmentChassis. An array of owners which represent effective ownership of this object. :return: The owners of this EquipmentChassis. :rtype: list[str] """ return self._owners @owners.setter def owners(self, owners): """ Sets the owners of this EquipmentChassis. An array of owners which represent effective ownership of this object. :param owners: The owners of this EquipmentChassis. :type: list[str] """ self._owners = owners @property def parent(self): """ Gets the parent of this EquipmentChassis. The direct ancestor of this managed object in the containment hierarchy. :return: The parent of this EquipmentChassis. :rtype: MoBaseMoRef """ return self._parent @parent.setter def parent(self, parent): """ Sets the parent of this EquipmentChassis. The direct ancestor of this managed object in the containment hierarchy. :param parent: The parent of this EquipmentChassis. :type: MoBaseMoRef """ self._parent = parent @property def tags(self): """ Gets the tags of this EquipmentChassis. An array of tags, which allow to add key, value meta-data to managed objects. :return: The tags of this EquipmentChassis. :rtype: list[MoTag] """ return self._tags @tags.setter def tags(self, tags): """ Sets the tags of this EquipmentChassis. An array of tags, which allow to add key, value meta-data to managed objects. :param tags: The tags of this EquipmentChassis. :type: list[MoTag] """ self._tags = tags @property def version_context(self): """ Gets the version_context of this EquipmentChassis. The versioning info for this managed object :return: The version_context of this EquipmentChassis. :rtype: MoVersionContext """ return self._version_context @version_context.setter def version_context(self, version_context): """ Sets the version_context of this EquipmentChassis. The versioning info for this managed object :param version_context: The version_context of this EquipmentChassis. :type: MoVersionContext """ self._version_context = version_context @property def device_mo_id(self): """ Gets the device_mo_id of this EquipmentChassis. :return: The device_mo_id of this EquipmentChassis. :rtype: str """ return self._device_mo_id @device_mo_id.setter def device_mo_id(self, device_mo_id): """ Sets the device_mo_id of this EquipmentChassis. :param device_mo_id: The device_mo_id of this EquipmentChassis. :type: str """ self._device_mo_id = device_mo_id @property def dn(self): """ Gets the dn of this EquipmentChassis. :return: The dn of this EquipmentChassis. :rtype: str """ return self._dn @dn.setter def dn(self, dn): """ Sets the dn of this EquipmentChassis. :param dn: The dn of this EquipmentChassis. :type: str """ self._dn = dn @property def rn(self): """ Gets the rn of this EquipmentChassis. :return: The rn of this EquipmentChassis. :rtype: str """ return self._rn @rn.setter def rn(self, rn): """ Sets the rn of this EquipmentChassis. :param rn: The rn of this EquipmentChassis. :type: str """ self._rn = rn @property def model(self): """ Gets the model of this EquipmentChassis. :return: The model of this EquipmentChassis. :rtype: str """ return self._model @model.setter def model(self, model): """ Sets the model of this EquipmentChassis. :param model: The model of this EquipmentChassis. :type: str """ self._model = model @property def revision(self): """ Gets the revision of this EquipmentChassis. :return: The revision of this EquipmentChassis. :rtype: str """ return self._revision @revision.setter def revision(self, revision): """ Sets the revision of this EquipmentChassis. :param revision: The revision of this EquipmentChassis. :type: str """ self._revision = revision @property def serial(self): """ Gets the serial of this EquipmentChassis. :return: The serial of this EquipmentChassis. :rtype: str """ return self._serial @serial.setter def serial(self, serial): """ Sets the serial of this EquipmentChassis. :param serial: The serial of this EquipmentChassis. :type: str """ self._serial = serial @property def vendor(self): """ Gets the vendor of this EquipmentChassis. :return: The vendor of this EquipmentChassis. :rtype: str """ return self._vendor @vendor.setter def vendor(self, vendor): """ Sets the vendor of this EquipmentChassis. :param vendor: The vendor of this EquipmentChassis. :type: str """ self._vendor = vendor @property def blades(self): """ Gets the blades of this EquipmentChassis. :return: The blades of this EquipmentChassis. :rtype: list[ComputeBladeRef] """ return self._blades @blades.setter def blades(self, blades): """ Sets the blades of this EquipmentChassis. :param blades: The blades of this EquipmentChassis. :type: list[ComputeBladeRef] """ self._blades = blades @property def fanmodules(self): """ Gets the fanmodules of this EquipmentChassis. :return: The fanmodules of this EquipmentChassis. :rtype: list[EquipmentFanModuleRef] """ return self._fanmodules @fanmodules.setter def fanmodules(self, fanmodules): """ Sets the fanmodules of this EquipmentChassis. :param fanmodules: The fanmodules of this EquipmentChassis. :type: list[EquipmentFanModuleRef] """ self._fanmodules = fanmodules @property def ioms(self): """ Gets the ioms of this EquipmentChassis. :return: The ioms of this EquipmentChassis. :rtype: list[EquipmentIoCardRef] """ return self._ioms @ioms.setter def ioms(self, ioms): """ Sets the ioms of this EquipmentChassis. :param ioms: The ioms of this EquipmentChassis. :type: list[EquipmentIoCardRef] """ self._ioms = ioms @property def oper_state(self): """ Gets the oper_state of this EquipmentChassis. :return: The oper_state of this EquipmentChassis. :rtype: str """ return self._oper_state @oper_state.setter def oper_state(self, oper_state): """ Sets the oper_state of this EquipmentChassis. :param oper_state: The oper_state of this EquipmentChassis. :type: str """ self._oper_state = oper_state @property def psus(self): """ Gets the psus of this EquipmentChassis. :return: The psus of this EquipmentChassis. :rtype: list[EquipmentPsuRef] """ return self._psus @psus.setter def psus(self, psus): """ Sets the psus of this EquipmentChassis. :param psus: The psus of this EquipmentChassis. :type: list[EquipmentPsuRef] """ self._psus = psus @property def registered_device(self): """ Gets the registered_device of this EquipmentChassis. :return: The registered_device of this EquipmentChassis. :rtype: AssetDeviceRegistrationRef """ return self._registered_device @registered_device.setter def registered_device(self, registered_device): """ Sets the registered_device of this EquipmentChassis. :param registered_device: The registered_device of this EquipmentChassis. :type: AssetDeviceRegistrationRef """ self._registered_device = registered_device @property def sasexpanders(self): """ Gets the sasexpanders of this EquipmentChassis. :return: The sasexpanders of this EquipmentChassis. :rtype: list[StorageSasExpanderRef] """ return self._sasexpanders @sasexpanders.setter def sasexpanders(self, sasexpanders): """ Sets the sasexpanders of this EquipmentChassis. :param sasexpanders: The sasexpanders of this EquipmentChassis. :type: list[StorageSasExpanderRef] """ self._sasexpanders = sasexpanders @property def siocs(self): """ Gets the siocs of this EquipmentChassis. :return: The siocs of this EquipmentChassis. :rtype: list[EquipmentSystemIoControllerRef] """ return self._siocs @siocs.setter def siocs(self, siocs): """ Sets the siocs of this EquipmentChassis. :param siocs: The siocs of this EquipmentChassis. :type: list[EquipmentSystemIoControllerRef] """ self._siocs = siocs @property def storage_enclosures(self): """ Gets the storage_enclosures of this EquipmentChassis. :return: The storage_enclosures of this EquipmentChassis. :rtype: list[StorageEnclosureRef] """ return self._storage_enclosures @storage_enclosures.setter def storage_enclosures(self, storage_enclosures): """ Sets the storage_enclosures of this EquipmentChassis. :param storage_enclosures: The storage_enclosures of this EquipmentChassis. :type: list[StorageEnclosureRef] """ self._storage_enclosures = storage_enclosures def to_dict(self): """ Returns the model properties as a dict """ result = {} for attr, _ in iteritems(self.swagger_types): value = getattr(self, attr) if isinstance(value, list): result[attr] = list(map( lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value )) elif hasattr(value, "to_dict"): result[attr] = value.to_dict() elif isinstance(value, dict): result[attr] = dict(map( lambda item: (item[0], item[1].to_dict()) if hasattr(item[1], "to_dict") else item, value.items() )) else: result[attr] = value return result def to_str(self): """ Returns the string representation of the model """ return pformat(self.to_dict()) def __repr__(self): """ For `print` and `pprint` """ return self.to_str() def __eq__(self, other): """ Returns true if both objects are equal """ if not isinstance(other, EquipmentChassis): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """ Returns true if both objects are not equal """ return not self == other
intersight/models/equipment_chassis.py
21,365
NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually. Returns true if both objects are equal EquipmentChassis - a model defined in Swagger Returns true if both objects are not equal For `print` and `pprint` Gets the account_moid of this EquipmentChassis. The Account ID for this managed object. :return: The account_moid of this EquipmentChassis. :rtype: str Sets the account_moid of this EquipmentChassis. The Account ID for this managed object. :param account_moid: The account_moid of this EquipmentChassis. :type: str Gets the ancestors of this EquipmentChassis. Ancestors is an array containing the MO references of the ancestors in the object containment hierarchy. :return: The ancestors of this EquipmentChassis. :rtype: list[MoBaseMoRef] Sets the ancestors of this EquipmentChassis. Ancestors is an array containing the MO references of the ancestors in the object containment hierarchy. :param ancestors: The ancestors of this EquipmentChassis. :type: list[MoBaseMoRef] Gets the blades of this EquipmentChassis. :return: The blades of this EquipmentChassis. :rtype: list[ComputeBladeRef] Sets the blades of this EquipmentChassis. :param blades: The blades of this EquipmentChassis. :type: list[ComputeBladeRef] Gets the create_time of this EquipmentChassis. The time when this managed object was created. :return: The create_time of this EquipmentChassis. :rtype: datetime Sets the create_time of this EquipmentChassis. The time when this managed object was created. :param create_time: The create_time of this EquipmentChassis. :type: datetime Gets the device_mo_id of this EquipmentChassis. :return: The device_mo_id of this EquipmentChassis. :rtype: str Sets the device_mo_id of this EquipmentChassis. :param device_mo_id: The device_mo_id of this EquipmentChassis. :type: str Gets the dn of this EquipmentChassis. :return: The dn of this EquipmentChassis. :rtype: str Sets the dn of this EquipmentChassis. :param dn: The dn of this EquipmentChassis. :type: str Gets the fanmodules of this EquipmentChassis. :return: The fanmodules of this EquipmentChassis. :rtype: list[EquipmentFanModuleRef] Sets the fanmodules of this EquipmentChassis. :param fanmodules: The fanmodules of this EquipmentChassis. :type: list[EquipmentFanModuleRef] Gets the ioms of this EquipmentChassis. :return: The ioms of this EquipmentChassis. :rtype: list[EquipmentIoCardRef] Sets the ioms of this EquipmentChassis. :param ioms: The ioms of this EquipmentChassis. :type: list[EquipmentIoCardRef] Gets the mod_time of this EquipmentChassis. The time when this managed object was last modified. :return: The mod_time of this EquipmentChassis. :rtype: datetime Sets the mod_time of this EquipmentChassis. The time when this managed object was last modified. :param mod_time: The mod_time of this EquipmentChassis. :type: datetime Gets the model of this EquipmentChassis. :return: The model of this EquipmentChassis. :rtype: str Sets the model of this EquipmentChassis. :param model: The model of this EquipmentChassis. :type: str Gets the moid of this EquipmentChassis. A unique identifier of this Managed Object instance. :return: The moid of this EquipmentChassis. :rtype: str Sets the moid of this EquipmentChassis. A unique identifier of this Managed Object instance. :param moid: The moid of this EquipmentChassis. :type: str Gets the object_type of this EquipmentChassis. The fully-qualified type of this managed object, e.g. the class name. :return: The object_type of this EquipmentChassis. :rtype: str Sets the object_type of this EquipmentChassis. The fully-qualified type of this managed object, e.g. the class name. :param object_type: The object_type of this EquipmentChassis. :type: str Gets the oper_state of this EquipmentChassis. :return: The oper_state of this EquipmentChassis. :rtype: str Sets the oper_state of this EquipmentChassis. :param oper_state: The oper_state of this EquipmentChassis. :type: str Gets the owners of this EquipmentChassis. An array of owners which represent effective ownership of this object. :return: The owners of this EquipmentChassis. :rtype: list[str] Sets the owners of this EquipmentChassis. An array of owners which represent effective ownership of this object. :param owners: The owners of this EquipmentChassis. :type: list[str] Gets the parent of this EquipmentChassis. The direct ancestor of this managed object in the containment hierarchy. :return: The parent of this EquipmentChassis. :rtype: MoBaseMoRef Sets the parent of this EquipmentChassis. The direct ancestor of this managed object in the containment hierarchy. :param parent: The parent of this EquipmentChassis. :type: MoBaseMoRef Gets the psus of this EquipmentChassis. :return: The psus of this EquipmentChassis. :rtype: list[EquipmentPsuRef] Sets the psus of this EquipmentChassis. :param psus: The psus of this EquipmentChassis. :type: list[EquipmentPsuRef] Gets the registered_device of this EquipmentChassis. :return: The registered_device of this EquipmentChassis. :rtype: AssetDeviceRegistrationRef Sets the registered_device of this EquipmentChassis. :param registered_device: The registered_device of this EquipmentChassis. :type: AssetDeviceRegistrationRef Gets the revision of this EquipmentChassis. :return: The revision of this EquipmentChassis. :rtype: str Sets the revision of this EquipmentChassis. :param revision: The revision of this EquipmentChassis. :type: str Gets the rn of this EquipmentChassis. :return: The rn of this EquipmentChassis. :rtype: str Sets the rn of this EquipmentChassis. :param rn: The rn of this EquipmentChassis. :type: str Gets the sasexpanders of this EquipmentChassis. :return: The sasexpanders of this EquipmentChassis. :rtype: list[StorageSasExpanderRef] Sets the sasexpanders of this EquipmentChassis. :param sasexpanders: The sasexpanders of this EquipmentChassis. :type: list[StorageSasExpanderRef] Gets the serial of this EquipmentChassis. :return: The serial of this EquipmentChassis. :rtype: str Sets the serial of this EquipmentChassis. :param serial: The serial of this EquipmentChassis. :type: str Gets the siocs of this EquipmentChassis. :return: The siocs of this EquipmentChassis. :rtype: list[EquipmentSystemIoControllerRef] Sets the siocs of this EquipmentChassis. :param siocs: The siocs of this EquipmentChassis. :type: list[EquipmentSystemIoControllerRef] Gets the storage_enclosures of this EquipmentChassis. :return: The storage_enclosures of this EquipmentChassis. :rtype: list[StorageEnclosureRef] Sets the storage_enclosures of this EquipmentChassis. :param storage_enclosures: The storage_enclosures of this EquipmentChassis. :type: list[StorageEnclosureRef] Gets the tags of this EquipmentChassis. An array of tags, which allow to add key, value meta-data to managed objects. :return: The tags of this EquipmentChassis. :rtype: list[MoTag] Sets the tags of this EquipmentChassis. An array of tags, which allow to add key, value meta-data to managed objects. :param tags: The tags of this EquipmentChassis. :type: list[MoTag] Returns the model properties as a dict Returns the string representation of the model Gets the vendor of this EquipmentChassis. :return: The vendor of this EquipmentChassis. :rtype: str Sets the vendor of this EquipmentChassis. :param vendor: The vendor of this EquipmentChassis. :type: str Gets the version_context of this EquipmentChassis. The versioning info for this managed object :return: The version_context of this EquipmentChassis. :rtype: MoVersionContext Sets the version_context of this EquipmentChassis. The versioning info for this managed object :param version_context: The version_context of this EquipmentChassis. :type: MoVersionContext Intersight REST API This is Intersight REST API OpenAPI spec version: 1.0.9-255 Generated by: https://github.com/swagger-api/swagger-codegen.git coding: utf-8
7,968
en
0.724457
# -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'button_editor.ui' # # Created by: PyQt5 UI code generator 5.7 # # WARNING! All changes made in this file will be lost! from PyQt5 import QtCore, QtGui, QtWidgets class Ui_Dialog(object): def setupUi(self, Dialog): Dialog.setObjectName("Dialog") Dialog.resize(493, 380) self.verticalLayout = QtWidgets.QVBoxLayout(Dialog) self.verticalLayout.setObjectName("verticalLayout") self.scrollArea = QtWidgets.QScrollArea(Dialog) self.scrollArea.setWidgetResizable(True) self.scrollArea.setObjectName("scrollArea") self.scrollAreaWidgetContents = QtWidgets.QWidget() self.scrollAreaWidgetContents.setGeometry(QtCore.QRect(0, 0, 473, 327)) self.scrollAreaWidgetContents.setObjectName("scrollAreaWidgetContents") self.scrollArea.setWidget(self.scrollAreaWidgetContents) self.verticalLayout.addWidget(self.scrollArea) self.buttonBox = QtWidgets.QDialogButtonBox(Dialog) self.buttonBox.setOrientation(QtCore.Qt.Horizontal) self.buttonBox.setStandardButtons(QtWidgets.QDialogButtonBox.Cancel|QtWidgets.QDialogButtonBox.Ok) self.buttonBox.setObjectName("buttonBox") self.verticalLayout.addWidget(self.buttonBox) self.retranslateUi(Dialog) self.buttonBox.accepted.connect(Dialog.accept) self.buttonBox.rejected.connect(Dialog.reject) QtCore.QMetaObject.connectSlotsByName(Dialog) def retranslateUi(self, Dialog): _translate = QtCore.QCoreApplication.translate Dialog.setWindowTitle(_translate("Dialog", "Power Button Editor"))
storm_control/hal4000/illumination/button_editor_ui.py
1,687
-*- coding: utf-8 -*- Form implementation generated from reading ui file 'button_editor.ui' Created by: PyQt5 UI code generator 5.7 WARNING! All changes made in this file will be lost!
184
en
0.853711
#!/usr/bin/env python # Copyright (c) 2005 Gavin E. Crooks <gec@threeplusone.com> # # This software is distributed under the MIT Open Source License. # <http://www.opensource.org/licenses/mit-license.html> # # 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 unittest from corebio import * from corebio._py3k import StringIO from corebio.seq import * from corebio.seq_io import * from test_corebio import * class test_table_io(unittest.TestCase): def test_read(self): f = StringIO(table_io.example) seqs = table_io.read(f) self.assertEqual(len(seqs), 10) self.assertEqual(seqs[2].name, "EC0003") self.assertEqual(len(seqs[1]), 50) def test_read_fail(self): f = StringIO(plain_io.example) # Wrong alphabet self.assertRaises(ValueError, table_io.read, f) def test_write_seq(self): f = StringIO(table_io.example) seqs = table_io.read(f) fout = StringIO() table_io.write(fout, seqs) fout.seek(0) seqs2 = table_io.read(fout) self.assertEqual(seqs, seqs2) if __name__ == '__main__': unittest.main()
test_corebio/test_table_io.py
2,178
!/usr/bin/env python Copyright (c) 2005 Gavin E. Crooks <gec@threeplusone.com> This software is distributed under the MIT Open Source License. <http://www.opensource.org/licenses/mit-license.html> 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. Wrong alphabet
1,255
en
0.840866
#!/usr/bin/env python # Copyright 2015 Rackspace, Inc # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. from lib import script class DecomPort(script.TeethScript): use_ironic = True use_neutron = True def __init__(self): super(DecomPort, self).__init__( 'Utility for temporarily putting a node on the decom network.') self.add_ironic_node_arguments() self.add_argument('command', help='Run command', choices=['add', 'remove']) def run(self): uuid = self.get_argument('node_uuid') node = self.ironic_client.get_node(uuid) command = self.get_argument('command') if command == 'add': self.neutron_client.add_decom_port(node) elif command == 'remove': self.neutron_client.remove_decom_port(node) if __name__ == "__main__": DecomPort().run()
onmetal_scripts/decom_port.py
1,467
!/usr/bin/env python Copyright 2015 Rackspace, Inc All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.
621
en
0.854865
""" File: weather_master.py Name: Claire Lin ----------------------- This program should implement a console program that asks weather data from user to compute the average, highest, lowest, cold days among the inputs. Output format should match what is shown in the sample run in the Assignment 2 Handout. """ EXIT = -100 def main(): """ To find the highest and lowest temperature, cold days and the average. """ print('stanCode \"Weather Master 4.0\"!') # my friend told me the maximum and minimum variable can set like this. maximum = -100000000 minimum = 100000000 total = 0 count = 0 cold_day = 0 while True: temperature = int(input('Next Temperature: (or '+str(EXIT) + ' to quit)? ')) # To jump out from the program when no temperature were entered. if temperature == EXIT and count == 0: print('No temperatures were entered.') break # To exclude the temperature not exist. if temperature > 90 or temperature < -100: print('>>> The temperature \"'+str(temperature)+'\" not exist, so we exclude and stop it.') break if temperature == EXIT: break else: count += 1 # count the total days. if temperature < 16: cold_day += 1 # count the cold days which temperature below 16. total += temperature # To plus all temperature. if temperature > maximum: maximum = temperature if temperature < minimum: minimum = temperature else: pass if count != 0: avg = total / count print("") print('Highest temperature = ' + str(maximum)) print('Lowest temperature = ' + str(minimum)) print('Average = '+str(avg)) print(str(cold_day) + ' cold day(s)') # For checking # print(total) # print(count) """ My note: This is the first try, when I debug I found the calculation logic is wrong. The first variable I type will disappear when it enter into the while loop. And the count of total days would include the EXIT constant. """ # if temperature == EXIT: # print('No temperatures were entered.') # # else: # while True: # # if temperature < 16: # # cold_day += 1 # # temperature = int(input('Next Temperature: (or '+str(EXIT) + ' to quit)? ')) # # # count the total days. # count += 1 # # if temperature == EXIT: # break # # total += temperature # if temperature > maximum: # maximum = temperature # elif temperature < minimum: # minimum = temperature # else: # pass # # avg = total / count # print('Highest temperature = ' + str(maximum)) # print('Lowest temperature = ' + str(minimum)) # print('Average = '+str(avg)) # print(str(cold_day) + ' cold day(s)') ###### DO NOT EDIT CODE BELOW THIS LINE ###### if __name__ == "__main__": main()
stanCode_Projects/weather_master/weather_master.py
3,222
To find the highest and lowest temperature, cold days and the average. File: weather_master.py Name: Claire Lin ----------------------- This program should implement a console program that asks weather data from user to compute the average, highest, lowest, cold days among the inputs. Output format should match what is shown in the sample run in the Assignment 2 Handout. my friend told me the maximum and minimum variable can set like this. To jump out from the program when no temperature were entered. To exclude the temperature not exist. count the total days. count the cold days which temperature below 16. To plus all temperature. For checking print(total) print(count) if temperature == EXIT: print('No temperatures were entered.') else: while True: if temperature < 16: cold_day += 1 temperature = int(input('Next Temperature: (or '+str(EXIT) + ' to quit)? ')) count the total days. count += 1 if temperature == EXIT: break total += temperature if temperature > maximum: maximum = temperature elif temperature < minimum: minimum = temperature else: pass avg = total / count print('Highest temperature = ' + str(maximum)) print('Lowest temperature = ' + str(minimum)) print('Average = '+str(avg)) print(str(cold_day) + ' cold day(s)') DO NOT EDIT CODE BELOW THIS LINE
1,442
en
0.7887
"""Module of sample legends for some commonly used geospatial datasets. """ import os import pkg_resources # Land Cover datasets in Earth Engine https://developers.google.com/earth-engine/datasets/tags/landcover builtin_legends = { # National Land Cover Database 2016 (NLCD2016) Legend https://www.mrlc.gov/data/legends/national-land-cover-database-2016-nlcd2016-legend 'NLCD': { '11 Open Water': '466b9f', '12 Perennial Ice/Snow': 'd1def8', '21 Developed, Open Space': 'dec5c5', '22 Developed, Low Intensity': 'd99282', '23 Developed, Medium Intensity': 'eb0000', '24 Developed High Intensity': 'ab0000', '31 Barren Land (Rock/Sand/Clay)': 'b3ac9f', '41 Deciduous Forest': '68ab5f', '42 Evergreen Forest': '1c5f2c', '43 Mixed Forest': 'b5c58f', '51 Dwarf Scrub': 'af963c', '52 Shrub/Scrub': 'ccb879', '71 Grassland/Herbaceous': 'dfdfc2', '72 Sedge/Herbaceous': 'd1d182', '73 Lichens': 'a3cc51', '74 Moss': '82ba9e', '81 Pasture/Hay': 'dcd939', '82 Cultivated Crops': 'ab6c28', '90 Woody Wetlands': 'b8d9eb', '95 Emergent Herbaceous Wetlands': '6c9fb8' }, # National Wetlands Inventory Legend: https://www.fws.gov/wetlands/data/Mapper-Wetlands-Legend.html 'NWI': { 'Freshwater- Forested and Shrub wetland': (0, 136, 55), 'Freshwater Emergent wetland': (127, 195, 28), 'Freshwater pond': (104, 140, 192), 'Estuarine and Marine wetland': (102, 194, 165), 'Riverine': (1, 144, 191), 'Lakes': (19, 0, 124), 'Estuarine and Marine Deepwater': (0, 124, 136), 'Other Freshwater wetland': (178, 134, 86) }, # MCD12Q1.051 Land Cover Type Yearly Global 500m https://developers.google.com/earth-engine/datasets/catalog/MODIS_051_MCD12Q1 'MODIS/051/MCD12Q1': { '0 Water': '1c0dff', '1 Evergreen needleleaf forest': '05450a', '2 Evergreen broadleaf forest': '086a10', '3 Deciduous needleleaf forest': '54a708', '4 Deciduous broadleaf forest': '78d203', '5 Mixed forest': '009900', '6 Closed shrublands': 'c6b044', '7 Open shrublands': 'dcd159', '8 Woody savannas': 'dade48', '9 Savannas': 'fbff13', '10 Grasslands': 'b6ff05', '11 Permanent wetlands': '27ff87', '12 Croplands': 'c24f44', '13 Urban and built-up': 'a5a5a5', '14 Cropland/natural vegetation mosaic': 'ff6d4c', '15 Snow and ice': '69fff8', '16 Barren or sparsely vegetated': 'f9ffa4', '254 Unclassified': 'ffffff' }, # GlobCover: Global Land Cover Map https://developers.google.com/earth-engine/datasets/catalog/ESA_GLOBCOVER_L4_200901_200912_V2_3 'GLOBCOVER': { '11 Post-flooding or irrigated croplands': 'aaefef', '14 Rainfed croplands': 'ffff63', '20 Mosaic cropland (50-70%) / vegetation (grassland, shrubland, forest) (20-50%)': 'dcef63', '30 Mosaic vegetation (grassland, shrubland, forest) (50-70%) / cropland (20-50%)': 'cdcd64', '40 Closed to open (>15%) broadleaved evergreen and/or semi-deciduous forest (>5m)': '006300', '50 Closed (>40%) broadleaved deciduous forest (>5m)': '009f00', '60 Open (15-40%) broadleaved deciduous forest (>5m)': 'aac700', '70 Closed (>40%) needleleaved evergreen forest (>5m)': '003b00', '90 Open (15-40%) needleleaved deciduous or evergreen forest (>5m)': '286300', '100 Closed to open (>15%) mixed broadleaved and needleleaved forest (>5m)': '788300', '110 Mosaic forest-shrubland (50-70%) / grassland (20-50%)': '8d9f00', '120 Mosaic grassland (50-70%) / forest-shrubland (20-50%)': 'bd9500', '130 Closed to open (>15%) shrubland (<5m)': '956300', '140 Closed to open (>15%) grassland': 'ffb431', '150 Sparse (>15%) vegetation (woody vegetation, shrubs, grassland)': 'ffebae', '160 Closed (>40%) broadleaved forest regularly flooded - Fresh water': '00785a', '170 Closed (>40%) broadleaved semi-deciduous and/or evergreen forest regularly flooded - saline water': '009578', '180 Closed to open (>15%) vegetation (grassland, shrubland, woody vegetation) on regularly flooded or waterlogged soil - fresh, brackish or saline water': '00dc83', '190 Artificial surfaces and associated areas (urban areas >50%) GLOBCOVER 2009': 'c31300', '200 Bare areas': 'fff5d6', '210 Water bodies': '0046c7', '220 Permanent snow and ice': 'ffffff', '230 Unclassified': '743411' }, # Global PALSAR-2/PALSAR Forest/Non-Forest Map https://developers.google.com/earth-engine/datasets/catalog/JAXA_ALOS_PALSAR_YEARLY_FNF 'JAXA/PALSAR': { '1 Forest': '006400', '2 Non-Forest': 'FEFF99', '3 Water': '0000FF' }, # MCD12Q1.006 MODIS Land Cover Type Yearly Global 500m https://developers.google.com/earth-engine/datasets/catalog/MODIS_006_MCD12Q1 'MODIS/006/MCD12Q1': { '1 Evergreen Needleleaf Forests: dominated by evergreen conifer trees (canopy >2m). Tree cover >60%.': '05450a', '2 Evergreen Broadleaf Forests: dominated by evergreen broadleaf and palmate trees (canopy >2m). Tree cover >60%.': '086a10', '3 Deciduous Needleleaf Forests: dominated by deciduous needleleaf (larch) trees (canopy >2m). Tree cover >60%.': '54a708', '4 Deciduous Broadleaf Forests: dominated by deciduous broadleaf trees (canopy >2m). Tree cover >60%.': '78d203', '5 Mixed Forests: dominated by neither deciduous nor evergreen (40-60% of each) tree type (canopy >2m). Tree cover >60%.': '009900', '6 Closed Shrublands: dominated by woody perennials (1-2m height) >60% cover.': 'c6b044', '7 Open Shrublands: dominated by woody perennials (1-2m height) 10-60% cover.': 'dcd159', '8 Woody Savannas: tree cover 30-60% (canopy >2m).': 'dade48', '9 Savannas: tree cover 10-30% (canopy >2m).': 'fbff13', '10 Grasslands: dominated by herbaceous annuals (<2m).': 'b6ff05', '11 Permanent Wetlands: permanently inundated lands with 30-60% water cover and >10% vegetated cover.': '27ff87', '12 Croplands: at least 60% of area is cultivated cropland.': 'c24f44', '13 Urban and Built-up Lands: at least 30% impervious surface area including building materials, asphalt and vehicles.': 'a5a5a5', '14 Cropland/Natural Vegetation Mosaics: mosaics of small-scale cultivation 40-60% with natural tree, shrub, or herbaceous vegetation.': 'ff6d4c', '15 Permanent Snow and Ice: at least 60% of area is covered by snow and ice for at least 10 months of the year.': '69fff8', '16 Barren: at least 60% of area is non-vegetated barren (sand, rock, soil) areas with less than 10% vegetation.': 'f9ffa4', '17 Water Bodies: at least 60% of area is covered by permanent water bodies.': '1c0dff' }, # Oxford MAP: Malaria Atlas Project Fractional International Geosphere-Biosphere Programme Landcover https://developers.google.com/earth-engine/datasets/catalog/Oxford_MAP_IGBP_Fractional_Landcover_5km_Annual 'Oxford': { '0 Water': '032f7e', '1 Evergreen_Needleleaf_Fores': '02740b', '2 Evergreen_Broadleaf_Forest': '02740b', '3 Deciduous_Needleleaf_Forest': '8cf502', '4 Deciduous_Broadleaf_Forest': '8cf502', '5 Mixed_Forest': 'a4da01', '6 Closed_Shrublands': 'ffbd05', '7 Open_Shrublands': 'ffbd05', '8 Woody_Savannas': '7a5a02', '9 Savannas': 'f0ff0f', '10 Grasslands': '869b36', '11 Permanent_Wetlands': '6091b4', '12 Croplands': 'ff4e4e', '13 Urban_and_Built-up': '999999', '14 Cropland_Natural_Vegetation_Mosaic': 'ff4e4e', '15 Snow_and_Ice': 'ffffff', '16 Barren_Or_Sparsely_Vegetated': 'feffc0', '17 Unclassified': '020202' }, # Canada AAFC Annual Crop Inventory https://developers.google.com/earth-engine/datasets/catalog/AAFC_ACI 'AAFC/ACI': { '10 Cloud': '000000', '20 Water': '3333ff', '30 Exposed Land and Barren': '996666', '34 Urban and Developed': 'cc6699', '35 Greenhouses': 'e1e1e1', '50 Shrubland': 'ffff00', '80 Wetland': '993399', '110 Grassland': 'cccc00', '120 Agriculture (undifferentiated)': 'cc6600', '122 Pasture and Forages': 'ffcc33', '130 Too Wet to be Seeded': '7899f6', '131 Fallow': 'ff9900', '132 Cereals': '660000', '133 Barley': 'dae31d', '134 Other Grains': 'd6cc00', '135 Millet': 'd2db25', '136 Oats': 'd1d52b', '137 Rye': 'cace32', '138 Spelt': 'c3c63a', '139 Triticale': 'b9bc44', '140 Wheat': 'a7b34d', '141 Switchgrass': 'b9c64e', '142 Sorghum': '999900', '145 Winter Wheat': '92a55b', '146 Spring Wheat': '809769', '147 Corn': 'ffff99', '148 Tobacco': '98887c', '149 Ginseng': '799b93', '150 Oilseeds': '5ea263', '151 Borage': '52ae77', '152 Camelina': '41bf7a', '153 Canola and Rapeseed': 'd6ff70', '154 Flaxseed': '8c8cff', '155 Mustard': 'd6cc00', '156 Safflower': 'ff7f00', '157 Sunflower': '315491', '158 Soybeans': 'cc9933', '160 Pulses': '896e43', '162 Peas': '8f6c3d', '167 Beans': '82654a', '174 Lentils': 'b85900', '175 Vegetables': 'b74b15', '176 Tomatoes': 'ff8a8a', '177 Potatoes': 'ffcccc', '178 Sugarbeets': '6f55ca', '179 Other Vegetables': 'ffccff', '180 Fruits': 'dc5424', '181 Berries': 'd05a30', '182 Blueberry': 'd20000', '183 Cranberry': 'cc0000', '185 Other Berry': 'dc3200', '188 Orchards': 'ff6666', '189 Other Fruits': 'c5453b', '190 Vineyards': '7442bd', '191 Hops': 'ffcccc', '192 Sod': 'b5fb05', '193 Herbs': 'ccff05', '194 Nursery': '07f98c', '195 Buckwheat': '00ffcc', '196 Canaryseed': 'cc33cc', '197 Hemp': '8e7672', '198 Vetch': 'b1954f', '199 Other Crops': '749a66', '200 Forest (undifferentiated)': '009900', '210 Coniferous': '006600', '220 Broadleaf': '00cc00', '230 Mixedwood': 'cc9900' }, # Copernicus CORINE Land Cover https://developers.google.com/earth-engine/datasets/catalog/COPERNICUS_CORINE_V20_100m 'COPERNICUS/CORINE/V20/100m': { '111 Artificial surfaces > Urban fabric > Continuous urban fabric': 'E6004D', '112 Artificial surfaces > Urban fabric > Discontinuous urban fabric': 'FF0000', '121 Artificial surfaces > Industrial, commercial, and transport units > Industrial or commercial units': 'CC4DF2', '122 Artificial surfaces > Industrial, commercial, and transport units > Road and rail networks and associated land': 'CC0000', '123 Artificial surfaces > Industrial, commercial, and transport units > Port areas': 'E6CCCC', '124 Artificial surfaces > Industrial, commercial, and transport units > Airports': 'E6CCE6', '131 Artificial surfaces > Mine, dump, and construction sites > Mineral extraction sites': 'A600CC', '132 Artificial surfaces > Mine, dump, and construction sites > Dump sites': 'A64DCC', '133 Artificial surfaces > Mine, dump, and construction sites > Construction sites': 'FF4DFF', '141 Artificial surfaces > Artificial, non-agricultural vegetated areas > Green urban areas': 'FFA6FF', '142 Artificial surfaces > Artificial, non-agricultural vegetated areas > Sport and leisure facilities': 'FFE6FF', '211 Agricultural areas > Arable land > Non-irrigated arable land': 'FFFFA8', '212 Agricultural areas > Arable land > Permanently irrigated land': 'FFFF00', '213 Agricultural areas > Arable land > Rice fields': 'E6E600', '221 Agricultural areas > Permanent crops > Vineyards': 'E68000', '222 Agricultural areas > Permanent crops > Fruit trees and berry plantations': 'F2A64D', '223 Agricultural areas > Permanent crops > Olive groves': 'E6A600', '231 Agricultural areas > Pastures > Pastures': 'E6E64D', '241 Agricultural areas > Heterogeneous agricultural areas > Annual crops associated with permanent crops': 'FFE6A6', '242 Agricultural areas > Heterogeneous agricultural areas > Complex cultivation patterns': 'FFE64D', '243 Agricultural areas > Heterogeneous agricultural areas > Land principally occupied by agriculture, with significant areas of natural vegetation': 'E6CC4D', '244 Agricultural areas > Heterogeneous agricultural areas > Agro-forestry areas': 'F2CCA6', '311 Forest and semi natural areas > Forests > Broad-leaved forest': '80FF00', '312 Forest and semi natural areas > Forests > Coniferous forest': '00A600', '313 Forest and semi natural areas > Forests > Mixed forest': '4DFF00', '321 Forest and semi natural areas > Scrub and/or herbaceous vegetation associations > Natural grasslands': 'CCF24D', '322 Forest and semi natural areas > Scrub and/or herbaceous vegetation associations > Moors and heathland': 'A6FF80', '323 Forest and semi natural areas > Scrub and/or herbaceous vegetation associations > Sclerophyllous vegetation': 'A6E64D', '324 Forest and semi natural areas > Scrub and/or herbaceous vegetation associations > Transitional woodland-shrub': 'A6F200', '331 Forest and semi natural areas > Open spaces with little or no vegetation > Beaches, dunes, sands': 'E6E6E6', '332 Forest and semi natural areas > Open spaces with little or no vegetation > Bare rocks': 'CCCCCC', '333 Forest and semi natural areas > Open spaces with little or no vegetation > Sparsely vegetated areas': 'CCFFCC', '334 Forest and semi natural areas > Open spaces with little or no vegetation > Burnt areas': '000000', '335 Forest and semi natural areas > Open spaces with little or no vegetation > Glaciers and perpetual snow': 'A6E6CC', '411 Wetlands > Inland wetlands > Inland marshes': 'A6A6FF', '412 Wetlands > Inland wetlands > Peat bogs': '4D4DFF', '421 Wetlands > Maritime wetlands > Salt marshes': 'CCCCFF', '422 Wetlands > Maritime wetlands > Salines': 'E6E6FF', '423 Wetlands > Maritime wetlands > Intertidal flats': 'A6A6E6', '511 Water bodies > Inland waters > Water courses': '00CCF2', '512 Water bodies > Inland waters > Water bodies': '80F2E6', '521 Water bodies > Marine waters > Coastal lagoons': '00FFA6', '522 Water bodies > Marine waters > Estuaries': 'A6FFE6', '523 Water bodies > Marine waters > Sea and ocean': 'E6F2FF' }, # Copernicus Global Land Cover Layers: CGLS-LC100 collection 2 https://developers.google.com/earth-engine/datasets/catalog/COPERNICUS_Landcover_100m_Proba-V_Global 'COPERNICUS/Landcover/100m/Proba-V/Global': { '0 Unknown': '282828', '20 Shrubs. Woody perennial plants with persistent and woody stems and without any defined main stem being less than 5 m tall. The shrub foliage can be either evergreen or deciduous.': 'FFBB22', '30 Herbaceous vegetation. Plants without persistent stem or shoots above ground and lacking definite firm structure. Tree and shrub cover is less than 10 %.': 'FFFF4C', '40 Cultivated and managed vegetation / agriculture. Lands covered with temporary crops followed by harvest and a bare soil period (e.g., single and multiple cropping systems). Note that perennial woody crops will be classified as the appropriate forest or shrub land cover type.': 'F096FF', '50 Urban / built up. Land covered by buildings and other man-made structures.': 'FA0000', '60 Bare / sparse vegetation. Lands with exposed soil, sand, or rocks and never has more than 10 % vegetated cover during any time of the year.': 'B4B4B4', '70 Snow and ice. Lands under snow or ice cover throughout the year.': 'F0F0F0', '80 Permanent water bodies. Lakes, reservoirs, and rivers. Can be either fresh or salt-water bodies.': '0032C8', '90 Herbaceous wetland. Lands with a permanent mixture of water and herbaceous or woody vegetation. The vegetation can be present in either salt, brackish, or fresh water.': '0096A0', '100 Moss and lichen.': 'FAE6A0', '111 Closed forest, evergreen needle leaf. Tree canopy >70 %, almost all needle leaf trees remain green all year. Canopy is never without green foliage.': '58481F', '112 Closed forest, evergreen broad leaf. Tree canopy >70 %, almost all broadleaf trees remain green year round. Canopy is never without green foliage.': '009900', '113 Closed forest, deciduous needle leaf. Tree canopy >70 %, consists of seasonal needle leaf tree communities with an annual cycle of leaf-on and leaf-off periods.': '70663E', '114 Closed forest, deciduous broad leaf. Tree canopy >70 %, consists of seasonal broadleaf tree communities with an annual cycle of leaf-on and leaf-off periods.': '00CC00', '115 Closed forest, mixed.': '4E751F', '116 Closed forest, not matching any of the other definitions.': '007800', '121 Open forest, evergreen needle leaf. Top layer- trees 15-70 % and second layer- mixed of shrubs and grassland, almost all needle leaf trees remain green all year. Canopy is never without green foliage.': '666000', '122 Open forest, evergreen broad leaf. Top layer- trees 15-70 % and second layer- mixed of shrubs and grassland, almost all broadleaf trees remain green year round. Canopy is never without green foliage.': '8DB400', '123 Open forest, deciduous needle leaf. Top layer- trees 15-70 % and second layer- mixed of shrubs and grassland, consists of seasonal needle leaf tree communities with an annual cycle of leaf-on and leaf-off periods.': '8D7400', '124 Open forest, deciduous broad leaf. Top layer- trees 15-70 % and second layer- mixed of shrubs and grassland, consists of seasonal broadleaf tree communities with an annual cycle of leaf-on and leaf-off periods.': 'A0DC00', '125 Open forest, mixed.': '929900', '126 Open forest, not matching any of the other definitions.': '648C00', '200 Oceans, seas. Can be either fresh or salt-water bodies.': '000080' }, # USDA NASS Cropland Data Layers https://developers.google.com/earth-engine/datasets/catalog/USDA_NASS_CDL 'USDA/NASS/CDL': { '1 Corn': 'ffd300', '2 Cotton': 'ff2626', '3 Rice': '00a8e2', '4 Sorghum': 'ff9e0a', '5 Soybeans': '267000', '6 Sunflower': 'ffff00', '10 Peanuts': '70a500', '11 Tobacco': '00af49', '12 Sweet Corn': 'dda50a', '13 Pop or Orn Corn': 'dda50a', '14 Mint': '7cd3ff', '21 Barley': 'e2007c', '22 Durum Wheat': '896054', '23 Spring Wheat': 'd8b56b', '24 Winter Wheat': 'a57000', '25 Other Small Grains': 'd69ebc', '26 Dbl Crop WinWht/Soybeans': '707000', '27 Rye': 'aa007c', '28 Oats': 'a05989', '29 Millet': '700049', '30 Speltz': 'd69ebc', '31 Canola': 'd1ff00', '32 Flaxseed': '7c99ff', '33 Safflower': 'd6d600', '34 Rape Seed': 'd1ff00', '35 Mustard': '00af49', '36 Alfalfa': 'ffa5e2', '37 Other Hay/Non Alfalfa': 'a5f28c', '38 Camelina': '00af49', '39 Buckwheat': 'd69ebc', '41 Sugarbeets': 'a800e2', '42 Dry Beans': 'a50000', '43 Potatoes': '702600', '44 Other Crops': '00af49', '45 Sugarcane': 'af7cff', '46 Sweet Potatoes': '702600', '47 Misc Vegs & Fruits': 'ff6666', '48 Watermelons': 'ff6666', '49 Onions': 'ffcc66', '50 Cucumbers': 'ff6666', '51 Chick Peas': '00af49', '52 Lentils': '00ddaf', '53 Peas': '54ff00', '54 Tomatoes': 'f2a377', '55 Caneberries': 'ff6666', '56 Hops': '00af49', '57 Herbs': '7cd3ff', '58 Clover/Wildflowers': 'e8bfff', '59 Sod/Grass Seed': 'afffdd', '60 Switchgrass': '00af49', '61 Fallow/Idle Cropland': 'bfbf77', '63 Forest': '93cc93', '64 Shrubland': 'c6d69e', '65 Barren': 'ccbfa3', '66 Cherries': 'ff00ff', '67 Peaches': 'ff8eaa', '68 Apples': 'ba004f', '69 Grapes': '704489', '70 Christmas Trees': '007777', '71 Other Tree Crops': 'af9970', '72 Citrus': 'ffff7c', '74 Pecans': 'b5705b', '75 Almonds': '00a582', '76 Walnuts': 'e8d6af', '77 Pears': 'af9970', '81 Clouds/No Data': 'f2f2f2', '82 Developed': '999999', '83 Water': '4970a3', '87 Wetlands': '7cafaf', '88 Nonag/Undefined': 'e8ffbf', '92 Aquaculture': '00ffff', '111 Open Water': '4970a3', '112 Perennial Ice/Snow': 'd3e2f9', '121 Developed/Open Space': '999999', '122 Developed/Low Intensity': '999999', '123 Developed/Med Intensity': '999999', '124 Developed/High Intensity': '999999', '131 Barren': 'ccbfa3', '141 Deciduous Forest': '93cc93', '142 Evergreen Forest': '93cc93', '143 Mixed Forest': '93cc93', '152 Shrubland': 'c6d69e', '176 Grassland/Pasture': 'e8ffbf', '190 Woody Wetlands': '7cafaf', '195 Herbaceous Wetlands': '7cafaf', '204 Pistachios': '00ff8c', '205 Triticale': 'd69ebc', '206 Carrots': 'ff6666', '207 Asparagus': 'ff6666', '208 Garlic': 'ff6666', '209 Cantaloupes': 'ff6666', '210 Prunes': 'ff8eaa', '211 Olives': '334933', '212 Oranges': 'e27026', '213 Honeydew Melons': 'ff6666', '214 Broccoli': 'ff6666', '216 Peppers': 'ff6666', '217 Pomegranates': 'af9970', '218 Nectarines': 'ff8eaa', '219 Greens': 'ff6666', '220 Plums': 'ff8eaa', '221 Strawberries': 'ff6666', '222 Squash': 'ff6666', '223 Apricots': 'ff8eaa', '224 Vetch': '00af49', '225 Dbl Crop WinWht/Corn': 'ffd300', '226 Dbl Crop Oats/Corn': 'ffd300', '227 Lettuce': 'ff6666', '229 Pumpkins': 'ff6666', '230 Dbl Crop Lettuce/Durum Wht': '896054', '231 Dbl Crop Lettuce/Cantaloupe': 'ff6666', '232 Dbl Crop Lettuce/Cotton': 'ff2626', '233 Dbl Crop Lettuce/Barley': 'e2007c', '234 Dbl Crop Durum Wht/Sorghum': 'ff9e0a', '235 Dbl Crop Barley/Sorghum': 'ff9e0a', '236 Dbl Crop WinWht/Sorghum': 'a57000', '237 Dbl Crop Barley/Corn': 'ffd300', '238 Dbl Crop WinWht/Cotton': 'a57000', '239 Dbl Crop Soybeans/Cotton': '267000', '240 Dbl Crop Soybeans/Oats': '267000', '241 Dbl Crop Corn/Soybeans': 'ffd300', '242 Blueberries': '000099', '243 Cabbage': 'ff6666', '244 Cauliflower': 'ff6666', '245 Celery': 'ff6666', '246 Radishes': 'ff6666', '247 Turnips': 'ff6666', '248 Eggplants': 'ff6666', '249 Gourds': 'ff6666', '250 Cranberries': 'ff6666', '254 Dbl Crop Barley/Soybeans': '267000' } } def ee_table_to_legend(in_table, out_file): """Converts an Earth Engine color table to a dictionary Args: in_table (str): The input file path (*.txt) to the Earth Engine color table. out_file (str): The output file path (*.txt) to the legend dictionary. """ pkg_dir = os.path.dirname( pkg_resources.resource_filename("geemap", "geemap.py")) ee_legend_table = os.path.join(pkg_dir, 'data/template/ee_legend_table.txt') if not os.path.exists(in_table): print('The class table does not exist.') out_file = os.path.abspath(out_file) if not os.path.exists(os.path.dirname(out_file)): os.makedirs(os.path.dirname(out_file)) legend_dict = {} with open(in_table) as f: lines = f.readlines() for index, line in enumerate(lines): if index > 0: items = line.split("\t") items = [item.strip() for item in items] color = items[1] key = items[0] + " " + items[2] legend_dict[key] = color out_lines = [] out_lines.append('{\n') for key in legend_dict.keys(): line = "\t'{}': '{}',\n".format(key,legend_dict[key]) out_lines.append(line) out_lines[-1] = out_lines[-1].rstrip()[:-1] + '\n' out_lines.append('}\n') with open(out_file, 'w') as f: f.writelines(out_lines)
geemap/legends.py
24,929
Converts an Earth Engine color table to a dictionary Args: in_table (str): The input file path (*.txt) to the Earth Engine color table. out_file (str): The output file path (*.txt) to the legend dictionary. Module of sample legends for some commonly used geospatial datasets. Land Cover datasets in Earth Engine https://developers.google.com/earth-engine/datasets/tags/landcover National Land Cover Database 2016 (NLCD2016) Legend https://www.mrlc.gov/data/legends/national-land-cover-database-2016-nlcd2016-legend National Wetlands Inventory Legend: https://www.fws.gov/wetlands/data/Mapper-Wetlands-Legend.html MCD12Q1.051 Land Cover Type Yearly Global 500m https://developers.google.com/earth-engine/datasets/catalog/MODIS_051_MCD12Q1 GlobCover: Global Land Cover Map https://developers.google.com/earth-engine/datasets/catalog/ESA_GLOBCOVER_L4_200901_200912_V2_3 Global PALSAR-2/PALSAR Forest/Non-Forest Map https://developers.google.com/earth-engine/datasets/catalog/JAXA_ALOS_PALSAR_YEARLY_FNF MCD12Q1.006 MODIS Land Cover Type Yearly Global 500m https://developers.google.com/earth-engine/datasets/catalog/MODIS_006_MCD12Q1 Oxford MAP: Malaria Atlas Project Fractional International Geosphere-Biosphere Programme Landcover https://developers.google.com/earth-engine/datasets/catalog/Oxford_MAP_IGBP_Fractional_Landcover_5km_Annual Canada AAFC Annual Crop Inventory https://developers.google.com/earth-engine/datasets/catalog/AAFC_ACI Copernicus CORINE Land Cover https://developers.google.com/earth-engine/datasets/catalog/COPERNICUS_CORINE_V20_100m Copernicus Global Land Cover Layers: CGLS-LC100 collection 2 https://developers.google.com/earth-engine/datasets/catalog/COPERNICUS_Landcover_100m_Proba-V_Global USDA NASS Cropland Data Layers https://developers.google.com/earth-engine/datasets/catalog/USDA_NASS_CDL
1,835
en
0.63013
""" naivefit.py A NaiveFit follows the approach described in Crundall et al. (2019). NaiveFit begins with an initial guess provided by user of an N component fit. If no guess is provided, all provided stars are assumed to be members of one component. NaiveFit will perform an Expectation Maximisation on this N component fit until converged. Then NaiveFit will test increasing the compoennt count to N+1. This is done by for each component out of the N existing, substituting it for 2 similar components with slight age offsets, and running an EM fit. The result is N separate "N+1 component" fits. The best one will be compared to the "N component" fit using the Bayesian Information Criterion (BIC). If the BIC has improved, this "N+1 component fit" will be taken as the best fit so far. This process iterates until adding a component fails to yield a better fit. """ import numpy as np import os import sys import logging from distutils.dir_util import mkpath import random import uuid #~ from emcee.utils import MPIPool from multiprocessing import Pool from multiprocessing import cpu_count sys.path.insert(0, os.path.abspath('..')) from . import expectmax from . import readparam from . import tabletool from . import component from . import traceorbit # python3 throws FileNotFoundError that is essentially the same as IOError try: FileNotFoundError except NameError: FileNotFoundError = IOError def dummy_trace_orbit_func(loc, times=None): """ Purely for testing purposes Dummy trace orbit func to skip irrelevant computation A little constraint on age (since otherwise its a free floating parameter) """ if times is not None: if np.all(times > 1.): return loc + 1000. return loc def log_message(msg, symbol='.', surround=False): """Little formatting helper""" res = '{}{:^40}{}'.format(5 * symbol, msg, 5 * symbol) if surround: res = '\n{}\n{}\n{}'.format(50 * symbol, res, 50 * symbol) logging.info(res) class NaiveFit(object): """ Many arguments can be taken straight from the fit_pars dictionary, so no point explicitly looking for them. Description of parameters can be found in README.md along with their default values and whether they are required. """ # Internal filestems that Chronostar uses to store results throughout a fit # Should not be changed, otherwise Chronostar may struggle to retreive progress # from previous fits. final_comps_file = 'final_comps.npy' final_med_and_spans_file = 'final_med_and_spans.npy' final_memb_probs_file = 'final_membership.npy' # For detailed description of parameters, see the main README.md file # in parent directory. DEFAULT_FIT_PARS = { 'results_dir':'', # Output from dataprep, XYZUVW data, plus background overlaps # Can be a filename to a astropy table, or an actual table 'data_table':None, # Whether to look for dX, .. c_XY or X_error, .. corr_X_Y in # the column names 'historical_colnames':False, # Column name for stellar IDs. This is used at the end when generating # final fits table with IDs and membership probabilities. # This is optional. 'stellar_id_colname': None, # File name that points to a stored list of components, typically from # a previous fit. Some example filenames could be: # - 'some/prev/fit/final_comps.npy # - 'some/prev/fit/2/A/final_comps.npy # Alternatively, if you already have the list of components, just # provide them to `init_comps`. Don't do both. # 'init_comps_file':None, # TODO: Is this redundant with 'init_comps' 'init_comps':None, # One of these two are required if initialising a run with ncomps != 1 # One can also initialise a Chronostar run with memberships. # Array is [nstars, ncomps] float array # Each row should sum to 1. # Same as in 'final_membership.npy' # TODO: implement this in a way that info can be passed in from text file # e.g. a path to a file name # for now, can only be used from within a script, i.e. given a numpy # array object 'init_memb_probs':None, # Provide a string name that corresponds to a ComponentClass # An actual Component Class will be inserted into the paramter # dictionary to be passed into expectmax 'component':'sphere', 'max_comp_count':20, 'max_em_iterations':200, 'nthreads':1, # TODO: NOT IMPLEMENTED 'use_background':True, 'overwrite_prev_run':False, 'burnin':500, 'sampling_steps':1000, 'store_burnin_chains':False, 'ignore_stable_comps':True, # If loading parameters from text file, can provide strings: # - 'epicyclic' for epicyclic # - 'dummy_trace_orbit_func' for a trace orbit funciton that doens't do antyhing (for testing) # Alternativley, if building up parameter dictionary in a script, can # provide actual function. 'trace_orbit_func':traceorbit.trace_cartesian_orbit, # MZ # Specify what optimisation method in the maximisation step of # the EM algorithm to use. Default: emcee. Also available: # In principle any method from scipy.optimise.minimise, but # here we recommend Nelder-Mead (because the initialisation # with any additional arguments, e.g. Jacobian etc. is not # implemented in Chronostar). # 'emcee' | 'Nelder-Mead' 'optimisation_method': 'emcee', # Optimise components in parallel in expectmax.maximise. 'nprocess_ncomp': False, # Overwrite final results in a fits file 'overwrite_fits': False, # How to split group: in age or in space? 'split_group': 'age', 'par_log_file':'fit_pars.log', } def __init__(self, fit_pars): """ Parameters ---------- fit_pars : str -or- dictionary If a string, `fit_pars` should be a path to a parameter file which can be parsed by readparam.readParam, to construct a dictionary. Alternatively, an actual dictionary can be passed in. See README.md for a description of parameters. """ # Parse parameter file if required if type(fit_pars) is str: fit_pars = readparam.readParam(fit_pars, default_pars=self.DEFAULT_FIT_PARS) # Make a new dictionary, with priority given to contents of fit_pars self.fit_pars = dict(self.DEFAULT_FIT_PARS) self.fit_pars.update(fit_pars) assert type(self.fit_pars) is dict # MZ: Make sure 'par_log_file' is written into the results folder self.fit_pars['par_log_file'] = os.path.join(self.fit_pars['results_dir'], self.fit_pars['par_log_file']) # Data prep should already have been completed, so we simply build # the dictionary of arrays from the astropy table self.data_dict = tabletool.build_data_dict_from_table(self.fit_pars['data_table'], historical=self.fit_pars['historical_colnames']) # The NaiveFit approach is to assume starting with 1 component self.ncomps = 1 # Import suitable component class if self.fit_pars['component'] == 'sphere': self.Component = component.SphereComponent self.fit_pars['Component'] = component.SphereComponent elif self.fit_pars['component'] == 'ellip': self.Component = component.EllipComponent self.fit_pars['Component'] = component.EllipComponent else: raise UserWarning('Unknown (or missing) component parametrisation') # Check results directory is valid # If path exists, make a new results_directory with a random int if os.path.exists(self.fit_pars['results_dir']) and \ not self.fit_pars['overwrite_prev_run']: rdir = '{}_{}'.format(self.fit_pars['results_dir'].rstrip('/'), random.randint(0, 1000)) else: rdir = self.fit_pars['results_dir'] self.rdir = rdir.rstrip('/') + '/' mkpath(self.rdir) assert os.access(self.rdir, os.W_OK) # Log fit parameters, readparam.log_used_pars(self.fit_pars, default_pars=self.DEFAULT_FIT_PARS) # Now that results directory is set up, can set up log file logging.basicConfig(filename=self.rdir + 'log.log', level=logging.INFO) # Make some logs about how many iterations (+ other stuff) code can run for log_message(msg='Component count cap set to {}'.format( self.fit_pars['max_comp_count']), symbol='+', surround=True) log_message(msg='Iteration count cap set to {}'.format( self.fit_pars['max_em_iterations']), symbol='+', surround=True) print('printed') # Check nthreads does not exceed hardware if self.fit_pars['nthreads'] > cpu_count() - 1: raise UserWarning('Provided nthreads exceeds cpu count on this machine. ' 'Rememeber to leave one cpu free for master thread!') # MZ: If nthreads>1: create an MPIPool if self.fit_pars['nthreads']>1: #self.pool = MPIPool() log_message('pool = Pool(nthreads) = pool(%d)'%self.fit_pars['nthreads']) self.fit_pars['pool']=Pool(self.fit_pars['nthreads']) else: self.pool = None # ------------------------------------------------------------ # ----- SETTING UP RUN CUSTOMISATIONS ---------------------- # ------------------------------------------------------------ # Set up trace_orbit_func if self.fit_pars['trace_orbit_func'] == 'dummy_trace_orbit_func': self.fit_pars['trace_orbit_func'] = dummy_trace_orbit_func elif self.fit_pars['trace_orbit_func'] == 'epicyclic': log_message('trace_orbit: epicyclic') self.fit_pars['trace_orbit_func'] = traceorbit.trace_epicyclic_orbit else: self.fit_pars['trace_orbit_func'] = traceorbit.trace_cartesian_orbit if type(self.fit_pars['init_comps']) is str: self.fit_pars['init_comps'] = self.Component.load_raw_components( self.fit_pars['init_comps']) self.ncomps = len(self.fit_pars['init_comps']) print('Managed to load in init_comps from file') else: self.fit_pars['init_comps'] = None print("'Init comps' is initialised as none") # TODO: If initialising with membership probabilities, adjust self.ncomps def build_comps_from_chains(self, run_dir): """ Build compoennt objects from stored emcee chains and cooresponding lnprobs. Parameters ---------- run_dir: str Directory of an EM fit, which in the context of NaiveFit will be e.g. 'myfit/1', or 'myfit/2/A' Returns ------- comps: [Component] A list of components that correspond to the best fit from the run in question. """ logging.info('Component class has been modified, reconstructing ' 'from chain') comps = self.ncomps * [None] for i in range(self.ncomps): final_cdir = run_dir + 'final/comp{}/'.format(i) chain = np.load(final_cdir + 'final_chain.npy') lnprob = np.load(final_cdir + 'final_lnprob.npy') npars = len(self.Component.PARAMETER_FORMAT) best_ix = np.argmax(lnprob) best_pars = chain.reshape(-1, npars)[best_ix] comps[i] = self.Component(emcee_pars=best_pars) self.Component.store_raw_components( str(run_dir + 'final/' + self.final_comps_file), comps) return comps def log_score_comparison(self, prev, new): """ Purely a logging helper function. Log BIC comparisons. Parameters ---------- prev: dict A dictinoary of scores from the previous run with the following entries - bic: the Bayesian Information Criterion - lnlike : the log likelihood - lnpost : the log posterior new: dict A dictinoary of scores from the new run, with identical entries as `prev` Result ------ None """ if new['bic'] < prev['bic']: logging.info("Extra component has improved BIC...") logging.info( "New BIC: {} < Old BIC: {}".format(new['bic'], prev['bic'])) else: logging.info("Extra component has worsened BIC...") logging.info( "New BIC: {} > Old BIC: {}".format(new['bic'], prev['bic'])) logging.info("lnlike: {} | {}".format(new['lnlike'], prev['lnlike'])) logging.info("lnpost: {} | {}".format(new['lnpost'], prev['lnpost'])) def build_init_comps(self, prev_comps, split_comp_ix, prev_med_and_spans, memb_probs): """ Given a list of converged components from a N component fit, generate a list of N+1 components with which to initialise an EM run. This is done by taking the target component, `prev_comps[comp_ix]`, replacing it in the list of comps, by splitting it into two components with a lower and higher age, Parameters ---------- prev_comps : [N] list of Component objects List of components from the N component fit split_comp_ix : int The index of component which is to be split into two prev_med_and_spans : [ncomps,npars,3] np.array The median and spans of Return ------ init_comps: [N+1] list of Component objects Side effects ------------ Updates self.fit_pars['init_comps'] with a [N+1] list of Component objects """ target_comp = prev_comps[split_comp_ix] assert isinstance(target_comp, self.Component) # Decompose and replace the ith component with two new components # by using the 16th and 84th percentile ages from previous run if self.fit_pars['split_group']=='age': if self.fit_pars['optimisation_method']=='emcee': split_comps = target_comp.split_group_age( lo_age=prev_med_and_spans[split_comp_ix, -1, 1], hi_age=prev_med_and_spans[split_comp_ix, -1, 2]) elif self.fit_pars['optimisation_method']=='Nelder-Mead': age = target_comp.get_age() split_comps = target_comp.split_group_age( # TODO: Maybe even smaller change lo_age=0.8*age, hi_age=1.2*age) elif self.fit_pars['split_group']=='spatial': split_comps = target_comp.split_group_spatial(self.data_dict, memb_probs[:,split_comp_ix]) init_comps = list(prev_comps) init_comps.pop(split_comp_ix) init_comps.insert(split_comp_ix, split_comps[1]) init_comps.insert(split_comp_ix, split_comps[0]) return init_comps def run_em_unless_loadable(self, run_dir): """ Run and EM fit, but only if not loadable from a previous run """ try: # This fails when gradient descent is used and med_and_spans are not meaningful. try: med_and_spans = np.load(os.path.join(run_dir, 'final/', self.final_med_and_spans_file)) except ValueError: logging.info('med_and_spans not read. Presumably you are using gradient descent optimisation procedure?') med_and_spans = [None] memb_probs = np.load(os.path.join( run_dir, 'final/', self.final_memb_probs_file)) comps = self.Component.load_raw_components( str(os.path.join(run_dir, 'final/', self.final_comps_file))) logging.info('Loaded from previous run') # Handle case where Component class has been modified and can't # load the raw components except AttributeError: # TODO: check that the final chains looked for are guaranteed to be saved comps = self.build_comps_from_chains(run_dir) # Handle the case where files are missing, which means we must # perform the fit. #~ except (IOError, FileNotFoundError) as e: except IOError: comps, med_and_spans, memb_probs = \ expectmax.fit_many_comps(data=self.data_dict, ncomps=self.ncomps, rdir=run_dir, **self.fit_pars) # Since init_comps and init_memb_probs are only meant for one time uses # we clear them to avoid any future usage self.fit_pars['init_comps'] = None self.fit_pars['init_memb_probs'] = None return {'comps':comps, 'med_and_spans':med_and_spans, 'memb_probs':memb_probs} def iter_end_log(self, best_split_ix, prev_result, new_result): logging.info("Selected {} as best decomposition".format( chr(ord('A') + best_split_ix))) logging.info( "Turned\n{}".format(prev_result['comps'][best_split_ix].get_pars())) logging.info('with {} members'.format( prev_result['memb_probs'].sum(axis=0)[best_split_ix])) logging.info("into\n{}\n&\n{}".format( new_result['comps'][best_split_ix].get_pars(), new_result['comps'][best_split_ix + 1].get_pars(), )) logging.info('with {} and {} members'.format( new_result['memb_probs'].sum(axis=0)[best_split_ix], new_result['memb_probs'].sum(axis=0)[best_split_ix + 1], )) logging.info("for an overall membership breakdown\n{}".format( new_result['memb_probs'].sum(axis=0) )) def log_final_log(self, prev_result, prev_score): logging.info('Final best fits:') [logging.info(c.get_pars()) for c in prev_result['comps']] logging.info('Final age med and span:') if self.fit_pars['optimisation_method']=='emcee': [logging.info(row[-1]) for row in prev_result['med_and_spans']] logging.info('Membership distribution: {}'.format( prev_result['memb_probs'].sum(axis=0))) logging.info('Final membership:') logging.info('\n{}'.format(np.round(prev_result['memb_probs'] * 100))) logging.info('Final lnlikelihood: {}'.format(prev_score['lnlike'])) logging.info('Final lnposterior: {}'.format(prev_score['lnpost'])) logging.info('Final BIC: {}'.format(prev_score['bic'])) logging.info('#########################') logging.info('### END #################') logging.info('#########################') def calc_score(self, comps, memb_probs): """ Calculate global score of fit for comparison with future fits with different component counts Parameters ---------- :param comps: :param memb_probs: :return: TODO: Establish relevance of bg_ln_ols """ lnlike = expectmax.get_overall_lnlikelihood(self.data_dict, comps, old_memb_probs=memb_probs, # bg_ln_ols=bg_ln_ols, ) lnpost = expectmax.get_overall_lnlikelihood(self.data_dict, comps, # bg_ln_ols=bg_ln_ols, old_memb_probs=memb_probs, inc_posterior=True) bic = expectmax.calc_bic(self.data_dict, self.ncomps, lnlike, memb_probs=memb_probs, Component=self.Component) return {'bic':bic, 'lnlike':lnlike, 'lnpost':lnpost} def run_fit(self): """ Perform a fit (as described in Paper I) to a set of prepared data. Results are outputted as two dictionaries results = {'comps':best_fit, (list of components) 'med_and_spans':median and spans of model parameters, 'memb_probs': membership probability array (the standard one)} scores = {'bic': the bic, 'lnlike': log likelihood of that run, 'lnpost': log posterior of that run} """ log_message('Beginning Chronostar run', symbol='_', surround=True) # ------------------------------------------------------------ # ----- EXECUTE RUN ---------------------------------------- # ------------------------------------------------------------ if self.fit_pars['store_burnin_chains']: log_message(msg='Storing burnin chains', symbol='-') # ------------------------------------------------------------ # ----- STAGE 1: ESTABLISHING INITIAL FIT ----------- # ------------------------------------------------------------ # Handle special case of very first run # Either by fitting one component (default) or by using `init_comps` # to initialise the EM fit. # Check if not provided with init comps or membs if (self.fit_pars['init_comps'] is None) and (self.fit_pars['init_memb_probs'] is None): # NaiveFit doesn't know how to blindly intiialise runs with ncomps > 1 assert self.ncomps == 1, 'If no initialisation set, can only accept ncomp==1' # If no init conditions provided, assume all stars are members and begine # fit with 1 component. init_memb_probs = np.zeros((len(self.data_dict['means']), self.ncomps + self.fit_pars[ 'use_background'])) init_memb_probs[:, 0] = 1. # Otherwise, we must have been given an init_comps, or an init_memb_probs # to start things with else: log_message(msg='Initialising with init_comps or init_memb_probs with' '%i components'%self.ncomps, symbol='*', surround=True) pass log_message(msg='FITTING {} COMPONENT'.format(self.ncomps), symbol='*', surround=True) run_dir = self.rdir + '{}/'.format(self.ncomps) prev_result = self.run_em_unless_loadable(run_dir) prev_score = self.calc_score(prev_result['comps'], prev_result['memb_probs']) self.ncomps += 1 # ------------------------------------------------------------ # ----- STAGE 2: EXPLORE EXTRA COMPONENT BY DECOMPOSITION -- # ------------------------------------------------------------ # Calculate global score of fit for comparison with future fits with different # component counts # Begin iterative loop, each time trialing the incorporation of a new component while self.ncomps <= self.fit_pars['max_comp_count']: log_message(msg='FITTING {} COMPONENT'.format(self.ncomps), symbol='*', surround=True) all_results = [] all_scores = [] # Iteratively try subdividing each previous component # target_comp is the component we will split into two. # This will make a total of ncomps (the target comp split into 2, # plus the remaining components from prev_result['comps'] for i, target_comp in enumerate(prev_result['comps']): div_label = chr(ord('A') + i) run_dir = self.rdir + '{}/{}/'.format(self.ncomps, div_label) log_message(msg='Subdividing stage {}'.format(div_label), symbol='+', surround=True) mkpath(run_dir) self.fit_pars['init_comps'] = self.build_init_comps( prev_result['comps'], split_comp_ix=i, prev_med_and_spans=prev_result['med_and_spans'], memb_probs = prev_result['memb_probs']) result = self.run_em_unless_loadable(run_dir) all_results.append(result) score = self.calc_score(result['comps'], result['memb_probs']) all_scores.append(score) logging.info( 'Decomposition {} finished with \nBIC: {}\nlnlike: {}\n' 'lnpost: {}'.format( div_label, all_scores[-1]['bic'], all_scores[-1]['lnlike'], all_scores[-1]['lnpost'], )) # identify the best performing decomposition all_bics = [score['bic'] for score in all_scores] best_split_ix = np.nanargmin(all_bics) new_result = all_results[best_split_ix] new_score = all_scores[best_split_ix] self.iter_end_log(best_split_ix, prev_result=prev_result, new_result=new_result) # Check if the fit has improved self.log_score_comparison(new=new_score, prev=prev_score) if new_score['bic'] < prev_score['bic']: prev_score = new_score prev_result = new_result self.ncomps += 1 log_message(msg="Commencing {} component fit on {}{}".format( self.ncomps, self.ncomps - 1, chr(ord('A') + best_split_ix)), symbol='+' ) else: # WRITING THE FINAL RESULTS INTO FILES logging.info("... saving previous fit as best fit to data") self.Component.store_raw_components(self.rdir + self.final_comps_file, prev_result['comps']) np.save(self.rdir + self.final_med_and_spans_file, prev_result['med_and_spans']) np.save(self.rdir + self.final_memb_probs_file, prev_result['memb_probs']) np.save(self.rdir + 'final_likelihood_post_and_bic', prev_score) # Save components in fits file tabcomps = self.Component.convert_components_array_into_astropy_table(prev_result['comps']) if self.fit_pars['overwrite_fits']: tabcomps.write(os.path.join(self.rdir, 'final_comps_%d.fits'%len(prev_result['comps'])), overwrite=self.fit_pars['overwrite_fits']) else: filename_comps_fits_random = os.path.join(self.rdir, 'final_comps_%d_%s.fits'%(len(prev_result['comps']), str(uuid.uuid4().hex))) tabcomps.write(filename_comps_fits_random, overwrite=self.fit_pars['overwrite_fits']) # Save membership fits file try: if self.fit_pars['overwrite_fits']: tabletool.construct_an_astropy_table_with_gaia_ids_and_membership_probabilities(self.fit_pars['data_table'], prev_result['memb_probs'], prev_result['comps'], os.path.join(self.rdir, 'final_memberships_%d.fits'%len(prev_result['comps'])), get_background_overlaps=True, stellar_id_colname = self.fit_pars['stellar_id_colname'], overwrite_fits = self.fit_pars['overwrite_fits']) else: filename_memb_probs_fits_random = os.path.join(self.rdir, 'final_memberships_%d_%s.fits'%(len(prev_result['comps']), str(uuid.uuid4().hex))) tabletool.construct_an_astropy_table_with_gaia_ids_and_membership_probabilities(self.fit_pars['data_table'], prev_result['memb_probs'], prev_result['comps'], filename_memb_probs_fits_random, get_background_overlaps=True, stellar_id_colname = self.fit_pars['stellar_id_colname'], overwrite_fits = self.fit_pars['overwrite_fits']) except: logging.info("[WARNING] Couldn't print membership.fits file. Check column id.") self.log_final_log(prev_result, prev_score) break logging.info("Best fit:\n{}".format( [group.get_pars() for group in prev_result['comps']])) if self.ncomps >= self.fit_pars['max_comp_count']: log_message(msg='REACHED MAX COMP LIMIT', symbol='+', surround=True) return prev_result, prev_score
chronostar/naivefit-bak.py
29,289
Many arguments can be taken straight from the fit_pars dictionary, so no point explicitly looking for them. Description of parameters can be found in README.md along with their default values and whether they are required. Parameters ---------- fit_pars : str -or- dictionary If a string, `fit_pars` should be a path to a parameter file which can be parsed by readparam.readParam, to construct a dictionary. Alternatively, an actual dictionary can be passed in. See README.md for a description of parameters. Build compoennt objects from stored emcee chains and cooresponding lnprobs. Parameters ---------- run_dir: str Directory of an EM fit, which in the context of NaiveFit will be e.g. 'myfit/1', or 'myfit/2/A' Returns ------- comps: [Component] A list of components that correspond to the best fit from the run in question. Given a list of converged components from a N component fit, generate a list of N+1 components with which to initialise an EM run. This is done by taking the target component, `prev_comps[comp_ix]`, replacing it in the list of comps, by splitting it into two components with a lower and higher age, Parameters ---------- prev_comps : [N] list of Component objects List of components from the N component fit split_comp_ix : int The index of component which is to be split into two prev_med_and_spans : [ncomps,npars,3] np.array The median and spans of Return ------ init_comps: [N+1] list of Component objects Side effects ------------ Updates self.fit_pars['init_comps'] with a [N+1] list of Component objects Calculate global score of fit for comparison with future fits with different component counts Parameters ---------- :param comps: :param memb_probs: :return: TODO: Establish relevance of bg_ln_ols Purely for testing purposes Dummy trace orbit func to skip irrelevant computation A little constraint on age (since otherwise its a free floating parameter) Little formatting helper Purely a logging helper function. Log BIC comparisons. Parameters ---------- prev: dict A dictinoary of scores from the previous run with the following entries - bic: the Bayesian Information Criterion - lnlike : the log likelihood - lnpost : the log posterior new: dict A dictinoary of scores from the new run, with identical entries as `prev` Result ------ None Run and EM fit, but only if not loadable from a previous run Perform a fit (as described in Paper I) to a set of prepared data. Results are outputted as two dictionaries results = {'comps':best_fit, (list of components) 'med_and_spans':median and spans of model parameters, 'memb_probs': membership probability array (the standard one)} scores = {'bic': the bic, 'lnlike': log likelihood of that run, 'lnpost': log posterior of that run} naivefit.py A NaiveFit follows the approach described in Crundall et al. (2019). NaiveFit begins with an initial guess provided by user of an N component fit. If no guess is provided, all provided stars are assumed to be members of one component. NaiveFit will perform an Expectation Maximisation on this N component fit until converged. Then NaiveFit will test increasing the compoennt count to N+1. This is done by for each component out of the N existing, substituting it for 2 similar components with slight age offsets, and running an EM fit. The result is N separate "N+1 component" fits. The best one will be compared to the "N component" fit using the Bayesian Information Criterion (BIC). If the BIC has improved, this "N+1 component fit" will be taken as the best fit so far. This process iterates until adding a component fails to yield a better fit. ~ from emcee.utils import MPIPool python3 throws FileNotFoundError that is essentially the same as IOError Internal filestems that Chronostar uses to store results throughout a fit Should not be changed, otherwise Chronostar may struggle to retreive progress from previous fits. For detailed description of parameters, see the main README.md file in parent directory. Output from dataprep, XYZUVW data, plus background overlaps Can be a filename to a astropy table, or an actual table Whether to look for dX, .. c_XY or X_error, .. corr_X_Y in the column names Column name for stellar IDs. This is used at the end when generating final fits table with IDs and membership probabilities. This is optional. File name that points to a stored list of components, typically from a previous fit. Some example filenames could be: - 'some/prev/fit/final_comps.npy - 'some/prev/fit/2/A/final_comps.npy Alternatively, if you already have the list of components, just provide them to `init_comps`. Don't do both. 'init_comps_file':None, TODO: Is this redundant with 'init_comps' One of these two are required if initialising a run with ncomps != 1 One can also initialise a Chronostar run with memberships. Array is [nstars, ncomps] float array Each row should sum to 1. Same as in 'final_membership.npy' TODO: implement this in a way that info can be passed in from text file e.g. a path to a file name for now, can only be used from within a script, i.e. given a numpy array object Provide a string name that corresponds to a ComponentClass An actual Component Class will be inserted into the paramter dictionary to be passed into expectmax TODO: NOT IMPLEMENTED If loading parameters from text file, can provide strings: - 'epicyclic' for epicyclic - 'dummy_trace_orbit_func' for a trace orbit funciton that doens't do antyhing (for testing) Alternativley, if building up parameter dictionary in a script, can provide actual function. MZ Specify what optimisation method in the maximisation step of the EM algorithm to use. Default: emcee. Also available: In principle any method from scipy.optimise.minimise, but here we recommend Nelder-Mead (because the initialisation with any additional arguments, e.g. Jacobian etc. is not implemented in Chronostar). 'emcee' | 'Nelder-Mead' Optimise components in parallel in expectmax.maximise. Overwrite final results in a fits file How to split group: in age or in space? Parse parameter file if required Make a new dictionary, with priority given to contents of fit_pars MZ: Make sure 'par_log_file' is written into the results folder Data prep should already have been completed, so we simply build the dictionary of arrays from the astropy table The NaiveFit approach is to assume starting with 1 component Import suitable component class Check results directory is valid If path exists, make a new results_directory with a random int Log fit parameters, Now that results directory is set up, can set up log file Make some logs about how many iterations (+ other stuff) code can run for Check nthreads does not exceed hardware MZ: If nthreads>1: create an MPIPoolself.pool = MPIPool() ------------------------------------------------------------ ----- SETTING UP RUN CUSTOMISATIONS ---------------------- ------------------------------------------------------------ Set up trace_orbit_func TODO: If initialising with membership probabilities, adjust self.ncomps Decompose and replace the ith component with two new components by using the 16th and 84th percentile ages from previous run TODO: Maybe even smaller change This fails when gradient descent is used and med_and_spans are not meaningful. Handle case where Component class has been modified and can't load the raw components TODO: check that the final chains looked for are guaranteed to be saved Handle the case where files are missing, which means we must perform the fit.~ except (IOError, FileNotFoundError) as e: Since init_comps and init_memb_probs are only meant for one time uses we clear them to avoid any future usage bg_ln_ols=bg_ln_ols, bg_ln_ols=bg_ln_ols, ------------------------------------------------------------ ----- EXECUTE RUN ---------------------------------------- ------------------------------------------------------------ ------------------------------------------------------------ ----- STAGE 1: ESTABLISHING INITIAL FIT ----------- ------------------------------------------------------------ Handle special case of very first run Either by fitting one component (default) or by using `init_comps` to initialise the EM fit. Check if not provided with init comps or membs NaiveFit doesn't know how to blindly intiialise runs with ncomps > 1 If no init conditions provided, assume all stars are members and begine fit with 1 component. Otherwise, we must have been given an init_comps, or an init_memb_probs to start things with ------------------------------------------------------------ ----- STAGE 2: EXPLORE EXTRA COMPONENT BY DECOMPOSITION -- ------------------------------------------------------------ Calculate global score of fit for comparison with future fits with different component counts Begin iterative loop, each time trialing the incorporation of a new component Iteratively try subdividing each previous component target_comp is the component we will split into two. This will make a total of ncomps (the target comp split into 2, plus the remaining components from prev_result['comps'] identify the best performing decomposition Check if the fit has improved WRITING THE FINAL RESULTS INTO FILES Save components in fits file Save membership fits file
9,355
en
0.776102
"""The token kinds currently recognized.""" from shivyc.tokens import TokenKind keyword_kinds = [] symbol_kinds = [] # Until function definition is ready, we define `main` as a hardcoded keyword main = TokenKind("main", keyword_kinds) bool_kw = TokenKind("_Bool", keyword_kinds) char_kw = TokenKind("char", keyword_kinds) short_kw = TokenKind("short", keyword_kinds) int_kw = TokenKind("int", keyword_kinds) long_kw = TokenKind("long", keyword_kinds) signed_kw = TokenKind("signed", keyword_kinds) unsigned_kw = TokenKind("unsigned", keyword_kinds) void_kw = TokenKind("void", keyword_kinds) return_kw = TokenKind("return", keyword_kinds) if_kw = TokenKind("if", keyword_kinds) else_kw = TokenKind("else", keyword_kinds) while_kw = TokenKind("while", keyword_kinds) for_kw = TokenKind("for", keyword_kinds) break_kw = TokenKind("break", keyword_kinds) continue_kw = TokenKind("continue", keyword_kinds) auto_kw = TokenKind("auto", keyword_kinds) static_kw = TokenKind("static", keyword_kinds) extern_kw = TokenKind("extern", keyword_kinds) struct_kw = TokenKind("struct", keyword_kinds) const_kw = TokenKind("const", keyword_kinds) plus = TokenKind("+", symbol_kinds) minus = TokenKind("-", symbol_kinds) star = TokenKind("*", symbol_kinds) slash = TokenKind("/", symbol_kinds) mod = TokenKind("%", symbol_kinds) incr = TokenKind("++", symbol_kinds) decr = TokenKind("--", symbol_kinds) equals = TokenKind("=", symbol_kinds) plusequals = TokenKind("+=", symbol_kinds) minusequals = TokenKind("-=", symbol_kinds) starequals = TokenKind("*=", symbol_kinds) divequals = TokenKind("/=", symbol_kinds) modequals = TokenKind("%=", symbol_kinds) twoequals = TokenKind("==", symbol_kinds) notequal = TokenKind("!=", symbol_kinds) bool_and = TokenKind("&&", symbol_kinds) bool_or = TokenKind("||", symbol_kinds) bool_not = TokenKind("!", symbol_kinds) lt = TokenKind("<", symbol_kinds) gt = TokenKind(">", symbol_kinds) ltoe = TokenKind("<=", symbol_kinds) gtoe = TokenKind(">=", symbol_kinds) amp = TokenKind("&", symbol_kinds) pound = TokenKind("#", symbol_kinds) dquote = TokenKind('"', symbol_kinds) squote = TokenKind("'", symbol_kinds) open_paren = TokenKind("(", symbol_kinds) close_paren = TokenKind(")", symbol_kinds) open_brack = TokenKind("{", symbol_kinds) close_brack = TokenKind("}", symbol_kinds) open_sq_brack = TokenKind("[", symbol_kinds) close_sq_brack = TokenKind("]", symbol_kinds) comma = TokenKind(",", symbol_kinds) semicolon = TokenKind(";", symbol_kinds) dot = TokenKind(".", symbol_kinds) arrow = TokenKind("->", symbol_kinds) identifier = TokenKind() number = TokenKind() string = TokenKind() char_string = TokenKind() include_file = TokenKind()
shivyc/token_kinds.py
2,676
The token kinds currently recognized. Until function definition is ready, we define `main` as a hardcoded keyword
115
en
0.90259
# coding: utf-8 def get_dict_output_dir_to_parameters_ini_dump_filename(): import os dir_ = '.' output_dir_list = sorted([output_dir for output_dir in os.listdir(dir_) if output_dir.startswith('output')]) ret = {} for output_dir in output_dir_list: with open(os.path.join(output_dir, 'parameters_ini_filename')) as f: parameters_ini_filename = list(f)[0].rstrip() ret[output_dir] = parameters_ini_filename + '.dump' return ret dict_output_dir_to_parameters_ini_dump = get_dict_output_dir_to_parameters_ini_dump_filename() import finess.util import finess.params.util import finess.dim2 import generate_iniparams # q(:, :, i - 1): # * i = 1: mass # * i = 2: momentum-1 # * i = 3: momentum-2 # * i = 4: momentum-3 # * i = 5: energy # * i = 6: B1 # * i = 7: B2 # * i = 8: B3 import finess.viz.dim2 def L1_error_list(output_dir_list): global debug_B1_abs_error global debug_B2_abs_error global debug_B_perp, debug_B3, debug_u_perp, debug_u3 global debug_B_perp_rel_error, debug_B_perp_abs_error, debug_B_perp_exact global debug_u_perp_rel_error, debug_u_perp_abs_error, debug_u_perp_exact global debug_B3_rel_error, debug_B3_abs_error, debug_B3_exact global debug_u3_rel_error, debug_u3_abs_error, debug_u3_exact global debug_B3_rel_error_100, debug_u3_rel_error_100 global debug_tfinal global debug_B_plane_perp global debug_B_plane_perp_abs_error import finess.viz.dim2 error_list = [] for output_dir in output_dir_list: parameters_ini_dump_filename = dict_output_dir_to_parameters_ini_dump[output_dir] import os.path params = finess.params.util.read_params(os.path.join(output_dir, parameters_ini_dump_filename), generate_iniparams.parameter_list) xlow = params['grid', 'xlow'] xhigh = params['grid', 'xhigh'] ylow = params['grid', 'ylow'] yhigh = params['grid', 'yhigh'] mx = params['grid', 'mx'] my = params['grid', 'my'] dx = (xhigh - xlow) / float(mx) dy = (yhigh - ylow) / float(my) nout = params['finess', 'nout'] tfinal, q, aux = finess.dim2.read_qa(params, nout) debug_tfinal = tfinal print "tfinal: ", tfinal from numpy import sin, cos, sum, abs, pi, max angle = params['initial', 'angle'] X, Y = finess.viz.dim2.meshgrid(params) u3_exact = 0.1 * cos(2*pi * (X*cos(angle) + Y*sin(angle) + tfinal)) B3_exact = u3_exact u_perp_exact = 0.1 * sin(2*pi * (X * cos(angle) + Y * sin(angle) + tfinal) ) B_perp_exact = u_perp_exact rho_exact = 1.0 u1_exact = -u_perp_exact * sin(angle) u2_exact = u_perp_exact * cos(angle) B1_exact = 1.0 * cos(angle) - B_perp_exact * sin(angle) B2_exact = 1.0 * sin(angle) + B_perp_exact * cos(angle) rho = q[:, :, 1 - 1] u1 = q[:, :, 2 - 1] / q[:, :, 1 - 1] u2 = q[:, :, 3 - 1] / q[:, :, 1 - 1] u3 = q[:, :, 4 - 1] / q[:, :, 1 - 1] B1 = q[:, :, 6 - 1] B2 = q[:, :, 7 - 1] B3 = q[:, :, 8 - 1] u_perp = -u1 * sin(angle) + u2 * cos(angle) B_perp = -B1 * sin(angle) + B2 * cos(angle) L1_error_u_perp = sum(abs(u_perp - u_perp_exact)) L1_u_perp_exact = sum(abs(u_perp_exact)) # print "u_perp error: ", L1_error_u_perp / L1_u_perp_exact L1_error_u1 = sum(abs(u1 - u1_exact)) L1_u1_exact = sum(abs(u1_exact)) L1_error_u2 = sum(abs(u2 - u2_exact)) L1_u2_exact = sum(abs(u2_exact)) L1_error_u3 = sum(abs(u3 - u3_exact)) L1_u3_exact = sum(abs(u3_exact)) # print "u3 error: ", L1_error_u3 / L1_u3_exact L1_error_B_perp = sum(abs(B_perp - B_perp_exact)) L1_B_perp_exact = sum(abs(B_perp_exact)) # print "B_perp error: ", L1_error_B_perp / L1_B_perp_exact debug_B1_abs_error = abs(B1 - B1_exact) debug_B2_abs_error = abs(B2 - B2_exact) debug_B_perp_exact = B_perp_exact debug_B_perp_abs_error = abs(B_perp - B_perp_exact) debug_B_perp_rel_error = debug_B_perp_abs_error / abs(B_perp_exact) debug_u_perp_exact = u_perp_exact debug_u_perp_abs_error = abs(u_perp - u_perp_exact) debug_u_perp_rel_error = debug_u_perp_abs_error / abs(u_perp_exact) debug_B3_exact = B3_exact debug_B3_abs_error = abs(B3 - B3_exact) debug_B3_rel_error = debug_B3_abs_error / abs(B3_exact) debug_B3_rel_error_100 = debug_B3_rel_error * 100 debug_u3_exact = u3_exact debug_u3_abs_error = abs(u3 - u3_exact) debug_u3_rel_error = debug_u3_abs_error / abs(u3_exact) debug_u3_rel_error_100 = 100 * debug_u3_rel_error debug_B3 = B3 debug_B_perp = B_perp debug_B_plane_perp = ((B3 / 0.1)**2 + (B_perp / 0.1)**2) * 0.1 debug_B_plane_perp_abs_error = abs(debug_B_plane_perp - 0.1) L1_error_B3 = sum(abs(B3 - B3_exact)) L1_B3_exact = sum(abs(B3_exact)) # print "B3 error: ", L1_error_B3 / L1_B3_exact # delta = 0.25 * (L1_error_u_perp / L1_u_perp_exact + L1_error_u3 / L1_u3_exact + L1_error_B_perp / L1_B_perp_exact + L1_error_B3 / L1_B3_exact) # delta = 0.5 * (L1_error_B_perp / L1_B_perp_exact + L1_error_B3 / L1_B3_exact) # delta = 0.5 * (L1_error_u_perp / L1_u_perp_exact + L1_error_u3 / L1_u3_exact) #delta = max(abs(u3 - u3_exact)) #delta = max(abs(u1 - u1_exact)) #delta = max(abs(u2 - u2_exact)) #delta = max(abs(u3 - u3_exact)) #delta = max(abs(B1 - B1_exact)) #delta = max(abs(B2 - B2_exact)) #delta = max(abs(B3 - B3_exact)) delta = max(abs(rho - rho_exact)) #delta = L1_error_u1 / L1_u1_exact error_list.append(delta) return error_list def log2_adjacent_ratio(error_list): order_list = [] from numpy import log2 for i in range(len(error_list) - 1): order_list.append(log2(error_list[i] / error_list[i+1])) return order_list def L1_A_error_list(output_dir_list): from numpy import max global debug_A_abs_error import finess.viz.dim2 error_list = [] for output_dir in output_dir_list: parameters_ini_dump_filename = dict_output_dir_to_parameters_ini_dump[output_dir] import os.path params = finess.params.util.read_params(os.path.join(output_dir, parameters_ini_dump_filename), generate_iniparams.parameter_list) xlow = params['grid', 'xlow'] xhigh = params['grid', 'xhigh'] ylow = params['grid', 'ylow'] yhigh = params['grid', 'yhigh'] mx = params['grid', 'mx'] my = params['grid', 'my'] dx = (xhigh - xlow) / float(mx) dy = (yhigh - ylow) / float(my) nout = params['finess', 'nout'] tfinal, q, aux = finess.dim2.read_qa(params, nout) A = aux[:, :, 1 - 1] from numpy import allclose, sin, cos, sum, abs, pi angle = params['initial', 'angle'] X, Y = finess.viz.dim2.meshgrid(params) A_exact = -X * sin(angle) + Y * cos(angle) + 0.1 / (2 * pi) * cos(2*pi * (X*cos(angle) + Y*sin(angle) + tfinal)) debug_A_abs_error = abs(A - A_exact) L1_A_exact = sum(abs(A_exact)) L1_A_error = sum(abs(A - A_exact)) #delta = L1_A_error / L1_A_exact delta = max(abs(A - A_exact)) error_list.append(delta) return error_list #output_dir_list = ['output_1deg_%(i)02d' % {'i': i} for i in range(6)] #error_list = L1_error_list(output_dir_list) #order_list = log2_adjacent_ratio(error_list) #print order_list # # #output_dir_list = ['output_30deg_%(i)02d' % {'i': i} for i in range(6)] #error_list = L1_error_list(output_dir_list) #order_list = log2_adjacent_ratio(error_list) #print order_list # # ## In[140]: output_dir_list = ['output_30deg_%(i)02d' % {'i': i} for i in [0, 1, 2, 3, 4]] error_list = L1_error_list(output_dir_list) order_list = log2_adjacent_ratio(error_list) print 'rho' print order_list print error_list A_error_list = L1_A_error_list(output_dir_list) A_order_list = log2_adjacent_ratio(A_error_list) print 'A:' print A_order_list print A_error_list
apps/2d/mhd/rotated_alfven/convergence/convergence_study.py
8,465
coding: utf-8 q(:, :, i - 1): * i = 1: mass * i = 2: momentum-1 * i = 3: momentum-2 * i = 4: momentum-3 * i = 5: energy * i = 6: B1 * i = 7: B2 * i = 8: B3 print "u_perp error: ", L1_error_u_perp / L1_u_perp_exact print "u3 error: ", L1_error_u3 / L1_u3_exact print "B_perp error: ", L1_error_B_perp / L1_B_perp_exact print "B3 error: ", L1_error_B3 / L1_B3_exact delta = 0.25 * (L1_error_u_perp / L1_u_perp_exact + L1_error_u3 / L1_u3_exact + L1_error_B_perp / L1_B_perp_exact + L1_error_B3 / L1_B3_exact) delta = 0.5 * (L1_error_B_perp / L1_B_perp_exact + L1_error_B3 / L1_B3_exact) delta = 0.5 * (L1_error_u_perp / L1_u_perp_exact + L1_error_u3 / L1_u3_exact)delta = max(abs(u3 - u3_exact))delta = max(abs(u1 - u1_exact))delta = max(abs(u2 - u2_exact))delta = max(abs(u3 - u3_exact))delta = max(abs(B1 - B1_exact))delta = max(abs(B2 - B2_exact))delta = max(abs(B3 - B3_exact))delta = L1_error_u1 / L1_u1_exactdelta = L1_A_error / L1_A_exactoutput_dir_list = ['output_1deg_%(i)02d' % {'i': i} for i in range(6)]error_list = L1_error_list(output_dir_list)order_list = log2_adjacent_ratio(error_list)print order_listoutput_dir_list = ['output_30deg_%(i)02d' % {'i': i} for i in range(6)]error_list = L1_error_list(output_dir_list)order_list = log2_adjacent_ratio(error_list)print order_list In[140]:
1,384
en
0.239498
from __future__ import print_function import click from openelex.base.cache import StateCache from .utils import default_state_options, print_files @click.command(name="cache.files", help="List files in state cache diretory") @default_state_options def files(state, datefilter=''): """List files in state cache diretory State is required. Optionally provide a date filter to limit results. NOTE: Cache must be populated in order to load data. """ cache = StateCache(state) files = cache.list_dir(datefilter) if files: print_files(files) else: msg = "No files found" if datefilter: msg += " using date filter: %s" % datefilter print(msg) @click.command(name='cache.clear', help="Delete files in state cache diretory") @default_state_options def clear(state, datefilter=''): """Delete files in state cache diretory State is required. Optionally provide a date filter to limit results. """ cache = StateCache(state) cache.clear(datefilter) def cache_discrepancy(self): pass
openelex/tasks/cache.py
1,091
Delete files in state cache diretory State is required. Optionally provide a date filter to limit results. List files in state cache diretory State is required. Optionally provide a date filter to limit results. NOTE: Cache must be populated in order to load data.
268
en
0.870812
import os import sys # os.system('bash ./set_env.sh') PARALLEL = 1 # assuming a quad-core machine ATTRIBUTE = "organic_figure" os.environ['FONDUERHOME'] = '/home/xiuyuan/private/839/fonduer_new/839_fonduer/' os.environ['FONDUERDBNAME'] = ATTRIBUTE os.environ['SNORKELDB'] = 'postgres://postgres:112233@localhost:5432/' + os.environ['FONDUERDBNAME'] from fonduer import SnorkelSession session = SnorkelSession() from fonduer import candidate_subclass Org_Fig = candidate_subclass('Org_Fig', ['product','figure']) from fonduer import HTMLPreprocessor, OmniParser docs_path = os.environ['FONDUERHOME'] + 'tutorials/organic_synthesis_figures/data/html/' pdf_path = os.environ['FONDUERHOME'] + 'tutorials/organic_synthesis_figures/data/pdf/' max_docs = float(10) doc_preprocessor = HTMLPreprocessor(docs_path, max_docs=max_docs) corpus_parser = OmniParser(structural=True, lingual=True, visual=True, pdf_path=pdf_path, # flatten=['sup', 'sub', 'small'], # ignore=['italic', 'bold'], blacklist=['style', 'script', 'meta', 'noscript']) corpus_parser.apply(doc_preprocessor, parallelism=PARALLEL) from fonduer import Document # divide train/dev/test docs = session.query(Document).order_by(Document.name).all() ld = len(docs) train_docs = set() dev_docs = set() test_docs = set() splits = (1.0, 0.9) data = [(doc.name, doc) for doc in docs] data.sort(key=lambda x: x[0]) for i, (doc_name, doc) in enumerate(data): if i < splits[0] * ld: train_docs.add(doc) elif i < splits[1] * ld: dev_docs.add(doc) else: test_docs.add(doc) from pprint import pprint pprint([x.name for x in train_docs]) from fonduer.snorkel.matchers import RegexMatchSpan, RegexMatchSplitEach,\ DictionaryMatch, LambdaFunctionMatcher, Intersect, Union prefix_rgx = '(\(?((mono|bi|di|tri|tetra|hex|hept|oct|iso|a?cycl|poly).+)?(meth|carb|benz|fluoro|chloro|bromo|iodo|hydro(xy)?|amino|alk).+)' suffix_rgx = '(.+(ane|yl|adiene|atriene|yne|anol|anediol|anetriol|anone|acid|amine|xide|dine|(or?mone)|thiol)\)?)' dash_rgx = '((\w+\-|\(?)([a-z|\d]\'?\-)\w*)' comma_dash_rgx = '((\w+\-|\(?)([a-z|\d]\'?,[a-z|\d]\'?\-)\w*)' inorganic_rgx = '(([A-Z][a-z]?\d*\+?){2,})' org_rgx = '|'.join([prefix_rgx, suffix_rgx, dash_rgx, comma_dash_rgx, inorganic_rgx]) rgx_matcher = RegexMatchSplitEach(rgx = org_rgx, longest_match_only=False, ignore_case=False) blacklist = ['CAS', 'PDF', 'RSC', 'SAR', 'TEM'] prod_blacklist_lambda_matcher = LambdaFunctionMatcher(func=lambda x: x.text not in blacklist, ignore_case=False) blacklist_rgx = ['methods?.?'] prod_blacklist_rgx_lambda_matcher = LambdaFunctionMatcher( func=lambda x: all([re.match(r, x.text) is None for r in blacklist_rgx]), ignore_case=False) prod_matcher = Intersect(rgx_matcher, prod_blacklist_lambda_matcher) from fonduer import CandidateExtractor from fonduer.lf_helpers import * import re def candidate_filter(c): (organic, figure) = c if same_file(organic, figure): if mentionsFig(organic, figure) or mentionsOrg(figure, organic): return True from tutorials.organic_synthesis_figures.organic_spaces import OmniNgramsProd prod_ngrams = OmniNgramsProd(parts_by_doc=None, n_max=3) from fonduer.matchers import LambdaFunctionFigureMatcher import time def white_black_list_matcher(fig): # print("enter filter 1") # enter_time = time.time() white_list = ['synthesis', 'plausible'] black_list = ['spectra', 'x-ray', 'copyright', 'structur', 'application'] fig_desc = fig.figure.description.lower() in_white = in_black = False if any(fig_desc.find(v) >= 0 for v in white_list): in_white = True if any(fig_desc.find(v) >= 0 for v in black_list): in_black = True if in_black and (not in_white): # print('Filtered by f1!') return False # # print("{} has passed filter 1 in {} seconds!".format(fig.figure.name, time.time()-enter_time)) # elif in_black: # desc_wordlist = fig.figure.description.lower().split(' ') # if any(re.search(org_rgx, w) for w in desc_wordlist): return True # if not fig.figure.text == '': # orc_wordlist = fig.figure.text.lower().split('\n') # orc_wordlist = [w for w in orc_wordlist if not w == ''] # if any(re.search(org_rgx, w) for w in orc_wordlist): return True # # print('Filtered by f2! Removed!') # print(fig.figure.name + " " + fig.figure.description) # return False return True def contain_organic_matcher(fig): # print("{} has failed filter 1 in {} seconds!".format(fig.figure.name, time.time() - enter_time)) # filter 2 desc_wordlist = fig.figure.description.lower().split(' ') if any(re.search(org_rgx, w) for w in desc_wordlist): return True if not fig.figure.text == '': orc_wordlist = fig.figure.text.lower().split('\n') orc_wordlist = [w for w in orc_wordlist if not w == ''] if any(re.search(org_rgx, w) for w in orc_wordlist): return True # print('Filtered by f2! Removed!') # print(fig.figure.name + " " + fig.figure.description) return False fig_matcher1 = LambdaFunctionFigureMatcher(func=white_black_list_matcher) fig_matcher2 = LambdaFunctionFigureMatcher(func=contain_organic_matcher) fig_matcher = Union(fig_matcher1, fig_matcher2) # fig_matcher = LambdaFunctionFigureMatcher(func=white_black_list_matcher) from fonduer.candidates import OmniDetailedFigures figs = OmniDetailedFigures() # extract candidate candidate_extractor = CandidateExtractor(Org_Fig, [prod_ngrams, figs], [prod_matcher, fig_matcher], candidate_filter=candidate_filter) candidate_extractor.apply(train_docs, split=0, parallelism=PARALLEL) train_cands = session.query(Org_Fig).filter(Org_Fig.split == 0).all() print("Number of candidates:", len(train_cands)) # extract feature from fonduer import BatchFeatureAnnotator from fonduer.features.features import get_organic_image_feats featurizer = BatchFeatureAnnotator(Org_Fig, f=get_organic_image_feats) F_train = featurizer.apply(split=0, replace_key_set=True, parallelism=PARALLEL) F_train = featurizer.load_matrix(split=0) # load gold label from tutorials.organic_synthesis_figures.organic_utils import load_organic_labels gold_file = os.environ['FONDUERHOME'] + 'tutorials/organic_synthesis_figures/data/organic_gold.csv' load_organic_labels(session, Org_Fig, gold_file, ATTRIBUTE ,annotator_name='gold') # labeling function from fonduer.lf_helpers import * from fuzzywuzzy import fuzz import re def LF_fig_name_match(c): args = c.get_contexts() if len(args) != 2: raise NotImplementedError("Only handles binary candidates currently") product, img = args if img.name == '': return -1 else: return 0 def LF_text_desc_match(c): args = c.get_contexts() if len(args) != 2: raise NotImplementedError("Only handles binary candidates currently") product, img = args if fuzz.partial_ratio(product.text, img.description) >= 70: return 1 elif fuzz.partial_ratio(product.text, img.description) <= 40: return -1 else: return 0 def LF_ocr_text_match(c): args = c.get_contexts() if len(args) != 2: raise NotImplementedError("Only handles binary candidates currently") product, img = args ocr_wordlist = img.text.lower().split('\n') ocr_wordlist = [w for w in ocr_wordlist if not w == ''] for w in ocr_wordlist: if fuzz.partial_ratio(product.text, w) >= 90: return 1 return 0 def LF_text_lenth_match(c): args = c.get_contexts() if len(args) != 2: raise NotImplementedError("Only handles binary candidates currently") product, img = args return -1 if len(product.text) < 5 else 0 def LF_match_keywords(c): args = c.get_contexts() if len(args) != 2: raise NotImplementedError("Only handles binary candidates currently") organic, figure, = args keywords = ['synthesis', 'reaction', 'produce', 'yield', 'formation', 'approach'] return 1 if both_contain_keywords(organic, figure, keywords) else 0 def LF_match_page(c): args = c.get_contexts() if len(args) != 2: raise NotImplementedError("Only handles binary candidates currently") organic, figure, = args return 1 if is_same_org_fig_page(organic, figure) else 0 def LF_page_not_match(c): args = c.get_contexts() if len(args) != 2: raise NotImplementedError("Only handles binary candidates currently") organic, figure, = args if abs(max(organic.sentence.page) - figure.page) > 1 or abs(min(organic.sentence.page) - figure.page) > 1: return -1 else: return 0 def LF_pos_near(c): args = c.get_contexts() if len(args) != 2: raise NotImplementedError("Only handles binary candidates currently") organic, figure, = args return 1 if org_pos_near_fig(organic, figure) else 0 def LF_organic_compound(c): args = c.get_contexts() organic = args[0] result = re.search(org_rgx, organic.text) return 1 if result else 0 org_fig_lfs = [ LF_fig_name_match, LF_text_desc_match, LF_ocr_text_match, LF_text_lenth_match, LF_match_keywords, LF_match_page, LF_page_not_match, LF_pos_near, LF_organic_compound ] from fonduer import BatchLabelAnnotator labeler = BatchLabelAnnotator(Org_Fig, lfs = org_fig_lfs) L_train = labeler.apply(split=0, clear=True, parallelism=PARALLEL) print(L_train.shape) L_train.get_candidate(session, 0) from fonduer import GenerativeModel gen_model = GenerativeModel() gen_model.train(L_train, epochs=500, decay=0.9, step_size=0.001/L_train.shape[0], reg_param=0) train_marginals = gen_model.marginals(L_train) print(gen_model.weights.lf_accuracy) from fonduer import SparseLogisticRegression from fonduer import BatchFeatureAnnotator from fonduer.features.features import get_organic_image_feats ### load feature # featurizer = BatchFeatureAnnotator(Org_Fig, f=get_organic_image_feats) # F_train = featurizer.load_matrix(split=0) disc_model = SparseLogisticRegression() disc_model.train(F_train, train_marginals, n_epochs=200, lr=0.001) #Current we only predict on the training set test_candidates = [F_train.get_candidate(session, i) for i in range(F_train.shape[0])] test_score = disc_model.predictions(F_train) true_pred = [test_candidates[_] for _ in np.nditer(np.where(test_score > 0))]
tutorials/organic_synthesis_figures/parse_organic_figures_xiuyuan.py
10,592
os.system('bash ./set_env.sh') assuming a quad-core machine flatten=['sup', 'sub', 'small'], ignore=['italic', 'bold'], divide train/dev/test print("enter filter 1") enter_time = time.time() print('Filtered by f1!') print("{} has passed filter 1 in {} seconds!".format(fig.figure.name, time.time()-enter_time)) elif in_black: desc_wordlist = fig.figure.description.lower().split(' ') if any(re.search(org_rgx, w) for w in desc_wordlist): return True if not fig.figure.text == '': orc_wordlist = fig.figure.text.lower().split('\n') orc_wordlist = [w for w in orc_wordlist if not w == ''] if any(re.search(org_rgx, w) for w in orc_wordlist): return True print('Filtered by f2! Removed!') print(fig.figure.name + " " + fig.figure.description) return False print("{} has failed filter 1 in {} seconds!".format(fig.figure.name, time.time() - enter_time)) filter 2 print('Filtered by f2! Removed!') print(fig.figure.name + " " + fig.figure.description) fig_matcher = LambdaFunctionFigureMatcher(func=white_black_list_matcher) extract candidate extract feature load gold label labeling function load feature featurizer = BatchFeatureAnnotator(Org_Fig, f=get_organic_image_feats) F_train = featurizer.load_matrix(split=0)Current we only predict on the training set
1,357
en
0.520572
"""Support for local control of entities by emulating a Philips Hue bridge.""" import logging from aiohttp import web import voluptuous as vol from homeassistant import util from homeassistant.const import EVENT_HOMEASSISTANT_START, EVENT_HOMEASSISTANT_STOP from homeassistant.exceptions import HomeAssistantError from homeassistant.helpers.deprecation import get_deprecated import homeassistant.helpers.config_validation as cv from homeassistant.util.json import load_json, save_json from homeassistant.components.http import real_ip from .hue_api import ( HueUsernameView, HueAllLightsStateView, HueOneLightStateView, HueOneLightChangeView, HueGroupView, HueAllGroupsStateView, ) from .upnp import DescriptionXmlView, UPNPResponderThread DOMAIN = "emulated_hue" _LOGGER = logging.getLogger(__name__) NUMBERS_FILE = "emulated_hue_ids.json" CONF_ADVERTISE_IP = "advertise_ip" CONF_ADVERTISE_PORT = "advertise_port" CONF_ENTITIES = "entities" CONF_ENTITY_HIDDEN = "hidden" CONF_ENTITY_NAME = "name" CONF_EXPOSE_BY_DEFAULT = "expose_by_default" CONF_EXPOSED_DOMAINS = "exposed_domains" CONF_HOST_IP = "host_ip" CONF_LISTEN_PORT = "listen_port" CONF_OFF_MAPS_TO_ON_DOMAINS = "off_maps_to_on_domains" CONF_TYPE = "type" CONF_UPNP_BIND_MULTICAST = "upnp_bind_multicast" TYPE_ALEXA = "alexa" TYPE_GOOGLE = "google_home" DEFAULT_LISTEN_PORT = 8300 DEFAULT_UPNP_BIND_MULTICAST = True DEFAULT_OFF_MAPS_TO_ON_DOMAINS = ["script", "scene"] DEFAULT_EXPOSE_BY_DEFAULT = True DEFAULT_EXPOSED_DOMAINS = [ "switch", "light", "group", "input_boolean", "media_player", "fan", ] DEFAULT_TYPE = TYPE_GOOGLE CONFIG_ENTITY_SCHEMA = vol.Schema( { vol.Optional(CONF_ENTITY_NAME): cv.string, vol.Optional(CONF_ENTITY_HIDDEN): cv.boolean, } ) CONFIG_SCHEMA = vol.Schema( { DOMAIN: vol.Schema( { vol.Optional(CONF_HOST_IP): cv.string, vol.Optional(CONF_LISTEN_PORT, default=DEFAULT_LISTEN_PORT): cv.port, vol.Optional(CONF_ADVERTISE_IP): cv.string, vol.Optional(CONF_ADVERTISE_PORT): cv.port, vol.Optional(CONF_UPNP_BIND_MULTICAST): cv.boolean, vol.Optional(CONF_OFF_MAPS_TO_ON_DOMAINS): cv.ensure_list, vol.Optional(CONF_EXPOSE_BY_DEFAULT): cv.boolean, vol.Optional(CONF_EXPOSED_DOMAINS): cv.ensure_list, vol.Optional(CONF_TYPE, default=DEFAULT_TYPE): vol.Any( TYPE_ALEXA, TYPE_GOOGLE ), vol.Optional(CONF_ENTITIES): vol.Schema( {cv.entity_id: CONFIG_ENTITY_SCHEMA} ), } ) }, extra=vol.ALLOW_EXTRA, ) ATTR_EMULATED_HUE = "emulated_hue" ATTR_EMULATED_HUE_NAME = "emulated_hue_name" ATTR_EMULATED_HUE_HIDDEN = "emulated_hue_hidden" async def async_setup(hass, yaml_config): """Activate the emulated_hue component.""" config = Config(hass, yaml_config.get(DOMAIN, {})) app = web.Application() app["hass"] = hass real_ip.setup_real_ip(app, False, []) # We misunderstood the startup signal. You're not allowed to change # anything during startup. Temp workaround. # pylint: disable=protected-access app._on_startup.freeze() await app.startup() runner = None site = None DescriptionXmlView(config).register(app, app.router) HueUsernameView().register(app, app.router) HueAllLightsStateView(config).register(app, app.router) HueOneLightStateView(config).register(app, app.router) HueOneLightChangeView(config).register(app, app.router) HueAllGroupsStateView(config).register(app, app.router) HueGroupView(config).register(app, app.router) upnp_listener = UPNPResponderThread( config.host_ip_addr, config.listen_port, config.upnp_bind_multicast, config.advertise_ip, config.advertise_port, ) async def stop_emulated_hue_bridge(event): """Stop the emulated hue bridge.""" upnp_listener.stop() if site: await site.stop() if runner: await runner.cleanup() async def start_emulated_hue_bridge(event): """Start the emulated hue bridge.""" upnp_listener.start() nonlocal site nonlocal runner runner = web.AppRunner(app) await runner.setup() site = web.TCPSite(runner, config.host_ip_addr, config.listen_port) try: await site.start() except OSError as error: _LOGGER.error( "Failed to create HTTP server at port %d: %s", config.listen_port, error ) else: hass.bus.async_listen_once( EVENT_HOMEASSISTANT_STOP, stop_emulated_hue_bridge ) hass.bus.async_listen_once(EVENT_HOMEASSISTANT_START, start_emulated_hue_bridge) return True class Config: """Hold configuration variables for the emulated hue bridge.""" def __init__(self, hass, conf): """Initialize the instance.""" self.hass = hass self.type = conf.get(CONF_TYPE) self.numbers = None self.cached_states = {} if self.type == TYPE_ALEXA: _LOGGER.warning( "Emulated Hue running in legacy mode because type has been " "specified. More info at https://goo.gl/M6tgz8" ) # Get the IP address that will be passed to the Echo during discovery self.host_ip_addr = conf.get(CONF_HOST_IP) if self.host_ip_addr is None: self.host_ip_addr = util.get_local_ip() _LOGGER.info( "Listen IP address not specified, auto-detected address is %s", self.host_ip_addr, ) # Get the port that the Hue bridge will listen on self.listen_port = conf.get(CONF_LISTEN_PORT) if not isinstance(self.listen_port, int): self.listen_port = DEFAULT_LISTEN_PORT _LOGGER.info( "Listen port not specified, defaulting to %s", self.listen_port ) # Get whether or not UPNP binds to multicast address (239.255.255.250) # or to the unicast address (host_ip_addr) self.upnp_bind_multicast = conf.get( CONF_UPNP_BIND_MULTICAST, DEFAULT_UPNP_BIND_MULTICAST ) # Get domains that cause both "on" and "off" commands to map to "on" # This is primarily useful for things like scenes or scripts, which # don't really have a concept of being off self.off_maps_to_on_domains = conf.get(CONF_OFF_MAPS_TO_ON_DOMAINS) if not isinstance(self.off_maps_to_on_domains, list): self.off_maps_to_on_domains = DEFAULT_OFF_MAPS_TO_ON_DOMAINS # Get whether or not entities should be exposed by default, or if only # explicitly marked ones will be exposed self.expose_by_default = conf.get( CONF_EXPOSE_BY_DEFAULT, DEFAULT_EXPOSE_BY_DEFAULT ) # Get domains that are exposed by default when expose_by_default is # True self.exposed_domains = conf.get(CONF_EXPOSED_DOMAINS, DEFAULT_EXPOSED_DOMAINS) # Calculated effective advertised IP and port for network isolation self.advertise_ip = conf.get(CONF_ADVERTISE_IP) or self.host_ip_addr self.advertise_port = conf.get(CONF_ADVERTISE_PORT) or self.listen_port self.entities = conf.get(CONF_ENTITIES, {}) def entity_id_to_number(self, entity_id): """Get a unique number for the entity id.""" if self.type == TYPE_ALEXA: return entity_id if self.numbers is None: self.numbers = _load_json(self.hass.config.path(NUMBERS_FILE)) # Google Home for number, ent_id in self.numbers.items(): if entity_id == ent_id: return number number = "1" if self.numbers: number = str(max(int(k) for k in self.numbers) + 1) self.numbers[number] = entity_id save_json(self.hass.config.path(NUMBERS_FILE), self.numbers) return number def number_to_entity_id(self, number): """Convert unique number to entity id.""" if self.type == TYPE_ALEXA: return number if self.numbers is None: self.numbers = _load_json(self.hass.config.path(NUMBERS_FILE)) # Google Home assert isinstance(number, str) return self.numbers.get(number) def get_entity_name(self, entity): """Get the name of an entity.""" if ( entity.entity_id in self.entities and CONF_ENTITY_NAME in self.entities[entity.entity_id] ): return self.entities[entity.entity_id][CONF_ENTITY_NAME] return entity.attributes.get(ATTR_EMULATED_HUE_NAME, entity.name) def is_entity_exposed(self, entity): """Determine if an entity should be exposed on the emulated bridge. Async friendly. """ if entity.attributes.get("view") is not None: # Ignore entities that are views return False domain = entity.domain.lower() explicit_expose = entity.attributes.get(ATTR_EMULATED_HUE, None) explicit_hidden = entity.attributes.get(ATTR_EMULATED_HUE_HIDDEN, None) if ( entity.entity_id in self.entities and CONF_ENTITY_HIDDEN in self.entities[entity.entity_id] ): explicit_hidden = self.entities[entity.entity_id][CONF_ENTITY_HIDDEN] if explicit_expose is True or explicit_hidden is False: expose = True elif explicit_expose is False or explicit_hidden is True: expose = False else: expose = None get_deprecated( entity.attributes, ATTR_EMULATED_HUE_HIDDEN, ATTR_EMULATED_HUE, None ) domain_exposed_by_default = ( self.expose_by_default and domain in self.exposed_domains ) # Expose an entity if the entity's domain is exposed by default and # the configuration doesn't explicitly exclude it from being # exposed, or if the entity is explicitly exposed is_default_exposed = domain_exposed_by_default and expose is not False return is_default_exposed or expose def _load_json(filename): """Wrapper, because we actually want to handle invalid json.""" try: return load_json(filename) except HomeAssistantError: pass return {}
homeassistant/components/emulated_hue/__init__.py
10,598
Hold configuration variables for the emulated hue bridge. Initialize the instance. Wrapper, because we actually want to handle invalid json. Get a unique number for the entity id. Get the name of an entity. Determine if an entity should be exposed on the emulated bridge. Async friendly. Convert unique number to entity id. Support for local control of entities by emulating a Philips Hue bridge. We misunderstood the startup signal. You're not allowed to change anything during startup. Temp workaround. pylint: disable=protected-access Get the IP address that will be passed to the Echo during discovery Get the port that the Hue bridge will listen on Get whether or not UPNP binds to multicast address (239.255.255.250) or to the unicast address (host_ip_addr) Get domains that cause both "on" and "off" commands to map to "on" This is primarily useful for things like scenes or scripts, which don't really have a concept of being off Get whether or not entities should be exposed by default, or if only explicitly marked ones will be exposed Get domains that are exposed by default when expose_by_default is True Calculated effective advertised IP and port for network isolation Google Home Google Home Ignore entities that are views Expose an entity if the entity's domain is exposed by default and the configuration doesn't explicitly exclude it from being exposed, or if the entity is explicitly exposed
1,413
en
0.890011
# coding: utf-8 """ ESMInterfaceTypeData.py The Clear BSD License Copyright (c) – 2016, NetApp, Inc. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted (subject to the limitations in the disclaimer below) provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of NetApp, Inc. nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. NO EXPRESS OR IMPLIED LICENSES TO ANY PARTY'S PATENT RIGHTS ARE GRANTED BY THIS LICENSE. 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. """ from pprint import pformat from six import iteritems class ESMInterfaceTypeData(object): """ NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually. """ def __init__(self): """ ESMInterfaceTypeData - a model defined in Swagger :param dict swaggerTypes: The key is attribute name and the value is attribute type. :param dict attributeMap: The key is attribute name and the value is json key in definition. """ self.swagger_types = { 'io_interface_type': 'str', # (required parameter) 'port_list': 'PortList' } self.attribute_map = { 'io_interface_type': 'ioInterfaceType', # (required parameter) 'port_list': 'portList' } self._io_interface_type = None self._port_list = None @property def io_interface_type(self): """ Gets the io_interface_type of this ESMInterfaceTypeData. This enumeration defines the different I/O interface types that may be reported as part of the configuration information associated with a controller. :return: The io_interface_type of this ESMInterfaceTypeData. :rtype: str :required/optional: required """ return self._io_interface_type @io_interface_type.setter def io_interface_type(self, io_interface_type): """ Sets the io_interface_type of this ESMInterfaceTypeData. This enumeration defines the different I/O interface types that may be reported as part of the configuration information associated with a controller. :param io_interface_type: The io_interface_type of this ESMInterfaceTypeData. :type: str """ allowed_values = ["notImplemented", "scsi", "fc", "sata", "sas", "iscsi", "ib", "fcoe", "nvmeof", "__UNDEFINED"] if io_interface_type not in allowed_values: raise ValueError( "Invalid value for `io_interface_type`, must be one of {0}" .format(allowed_values) ) self._io_interface_type = io_interface_type @property def port_list(self): """ Gets the port_list of this ESMInterfaceTypeData. A list of detailed information for each port. :return: The port_list of this ESMInterfaceTypeData. :rtype: PortList :required/optional: optional """ return self._port_list @port_list.setter def port_list(self, port_list): """ Sets the port_list of this ESMInterfaceTypeData. A list of detailed information for each port. :param port_list: The port_list of this ESMInterfaceTypeData. :type: PortList """ self._port_list = port_list def to_dict(self): """ Returns the model properties as a dict """ result = {} for attr, _ in iteritems(self.swagger_types): value = getattr(self, attr) if isinstance(value, list): result[attr] = list(map( lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value )) elif hasattr(value, "to_dict"): result[attr] = value.to_dict() elif isinstance(value, dict): result[attr] = dict(map( lambda item: (item[0], item[1].to_dict()) if hasattr(item[1], "to_dict") else item, value.items() )) else: result[attr] = value return result def to_str(self): """ Returns the string representation of the model """ return pformat(self.to_dict()) def __repr__(self): """ For `print` and `pprint` """ if self is None: return None return self.to_str() def __eq__(self, other): """ Returns true if both objects are equal """ if self is None or other is None: return None return self.__dict__ == other.__dict__ def __ne__(self, other): """ Returns true if both objects are not equal """ return not self == other
netapp/santricity/models/symbol/esm_interface_type_data.py
6,086
NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually. Returns true if both objects are equal ESMInterfaceTypeData - a model defined in Swagger :param dict swaggerTypes: The key is attribute name and the value is attribute type. :param dict attributeMap: The key is attribute name and the value is json key in definition. Returns true if both objects are not equal For `print` and `pprint` Gets the io_interface_type of this ESMInterfaceTypeData. This enumeration defines the different I/O interface types that may be reported as part of the configuration information associated with a controller. :return: The io_interface_type of this ESMInterfaceTypeData. :rtype: str :required/optional: required Sets the io_interface_type of this ESMInterfaceTypeData. This enumeration defines the different I/O interface types that may be reported as part of the configuration information associated with a controller. :param io_interface_type: The io_interface_type of this ESMInterfaceTypeData. :type: str Gets the port_list of this ESMInterfaceTypeData. A list of detailed information for each port. :return: The port_list of this ESMInterfaceTypeData. :rtype: PortList :required/optional: optional Sets the port_list of this ESMInterfaceTypeData. A list of detailed information for each port. :param port_list: The port_list of this ESMInterfaceTypeData. :type: PortList Returns the model properties as a dict Returns the string representation of the model ESMInterfaceTypeData.py The Clear BSD License Copyright (c) – 2016, NetApp, Inc. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted (subject to the limitations in the disclaimer below) provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of NetApp, Inc. nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. NO EXPRESS OR IMPLIED LICENSES TO ANY PARTY'S PATENT RIGHTS ARE GRANTED BY THIS LICENSE. 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. coding: utf-8 (required parameter) (required parameter)
3,285
en
0.781725
#!/usr/bin/python3 # # Copyright (C) 2011 Google Inc. # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: # # 1. Redistributions of source code must retain the above copyright notice, # this list of conditions and the following disclaimer. # # 2. 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 HOLDER OR # CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, # EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, # PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR # PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF # LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING # NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS # SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. """Script for testing lock performance""" import os import sys import time import optparse import threading import resource from ganeti import locking def ParseOptions(): """Parses the command line options. In case of command line errors, it will show the usage and exit the program. @return: the options in a tuple """ parser = optparse.OptionParser() parser.add_option("-t", dest="thread_count", default=1, type="int", help="Number of threads", metavar="NUM") parser.add_option("-d", dest="duration", default=5, type="float", help="Duration", metavar="SECS") (opts, args) = parser.parse_args() if opts.thread_count < 1: parser.error("Number of threads must be at least 1") return (opts, args) class State(object): def __init__(self, thread_count): """Initializes this class. """ self.verify = [0 for _ in range(thread_count)] self.counts = [0 for _ in range(thread_count)] self.total_count = 0 def _Counter(lock, state, me): """Thread function for acquiring locks. """ counts = state.counts verify = state.verify while True: lock.acquire() try: verify[me] = 1 counts[me] += 1 state.total_count += 1 if state.total_count % 1000 == 0: sys.stdout.write(" %8d\r" % state.total_count) sys.stdout.flush() if sum(verify) != 1: print("Inconsistent state!") os._exit(1) # pylint: disable=W0212 verify[me] = 0 finally: lock.release() def main(): (opts, _) = ParseOptions() lock = locking.SharedLock("TestLock") state = State(opts.thread_count) lock.acquire(shared=0) try: for i in range(opts.thread_count): t = threading.Thread(target=_Counter, args=(lock, state, i)) t.setDaemon(True) t.start() start = time.clock() finally: lock.release() while True: if (time.clock() - start) > opts.duration: break time.sleep(0.1) # Make sure we get a consistent view lock.acquire(shared=0) lock_cputime = time.clock() - start res = resource.getrusage(resource.RUSAGE_SELF) print("Total number of acquisitions: %s" % state.total_count) print("Per-thread acquisitions:") for (i, count) in enumerate(state.counts): print(" Thread %s: %d (%0.1f%%)" % (i, count, (100.0 * count / state.total_count))) print("Benchmark CPU time: %0.3fs" % lock_cputime) print("Average time per lock acquisition: %0.5fms" % (1000.0 * lock_cputime / state.total_count)) print("Process:") print(" User time: %0.3fs" % res.ru_utime) print(" System time: %0.3fs" % res.ru_stime) print(" Total time: %0.3fs" % (res.ru_utime + res.ru_stime)) # Exit directly without attempting to clean up threads os._exit(0) # pylint: disable=W0212 if __name__ == "__main__": main()
test/py/lockperf.py
4,213
Parses the command line options. In case of command line errors, it will show the usage and exit the program. @return: the options in a tuple Thread function for acquiring locks. Initializes this class. Script for testing lock performance !/usr/bin/python3 Copyright (C) 2011 Google Inc. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. 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 HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. pylint: disable=W0212 Make sure we get a consistent view Exit directly without attempting to clean up threads pylint: disable=W0212
1,686
en
0.864929
# 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 ecl.compute import compute_service from ecl.compute.v2 import metadata from ecl import resource2 class Image(resource2.Resource, metadata.MetadataMixin): resource_key = 'image' resources_key = 'images' base_path = '/images' service = compute_service.ComputeService() # capabilities allow_get = True allow_delete = True allow_list = True _query_mapping = resource2.QueryParameters("server", "name", "status", "type", min_disk="minDisk", min_ram="minRam", changes_since="changes-since") # Properties #: Links pertaining to this image. This is a list of dictionaries, #: each including keys ``href`` and ``rel``, and optionally ``type``. links = resource2.Body('links') #: The name of this image. name = resource2.Body('name') #: Timestamp when the image was created. created_at = resource2.Body('created') #: Metadata pertaining to this image. *Type: dict* metadata = resource2.Body('metadata', type=dict) #: The mimimum disk size. *Type: int* min_disk = resource2.Body('minDisk', type=int) #: The minimum RAM size. *Type: int* min_ram = resource2.Body('minRam', type=int) #: If this image is still building, its progress is represented here. #: Once an image is created, progres will be 100. *Type: int* progress = resource2.Body('progress', type=int) #: The status of this image. status = resource2.Body('status') #: Timestamp when the image was updated. updated_at = resource2.Body('updated') #: Size of the image in bytes. *Type: int* size = resource2.Body('OS-EXT-IMG-SIZE:size', type=int) class ImageDetail(Image): base_path = '/images/detail' allow_get = False allow_delete = False allow_list = True
ecl/compute/v2/image.py
2,496
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. capabilities Properties: Links pertaining to this image. This is a list of dictionaries,: each including keys ``href`` and ``rel``, and optionally ``type``.: The name of this image.: Timestamp when the image was created.: Metadata pertaining to this image. *Type: dict*: The mimimum disk size. *Type: int*: The minimum RAM size. *Type: int*: If this image is still building, its progress is represented here.: Once an image is created, progres will be 100. *Type: int*: The status of this image.: Timestamp when the image was updated.: Size of the image in bytes. *Type: int*
1,098
en
0.873695
# -*- coding: utf-8 -*- """ Adjustment from the 2D version from Machine Learning & Simulation code and video: https://www.youtube.com/watch?v=ZUXmO4hu-20&list=LL&index=1&ab_channel=MachineLearning%26Simulation https://github.com/Ceyron/machine-learning-and-simulation/blob/main/english/simulation_scripts/lattice_boltzmann_method_python_jax.py by Bart Davids. Originally made in Google Colab: https://colab.research.google.com/drive/1F3EH9_2N3lkEpgQXOScR3lcQ6oqCARPk?usp=sharing Additional notes and figures for clarification can be found there. """ # Import dependancies import jax import jax.numpy as jnp import matplotlib.pyplot as plt import cmasher as cmr from tqdm import tqdm if __name__ == '__main__': # Enable 64bit JAX jax.config.update("jax_enable_x64", True) # Radius of the cylinder radius = 5.5 # Dimensions of domain ny = 50 nz = 60 nx = 300 KINEMATIC_VISCOSITY = 0.0025 HORIZONTAL_INFLOW_VELOCITY = 0.04 reynolds_number = (HORIZONTAL_INFLOW_VELOCITY * radius) / KINEMATIC_VISCOSITY RELAXATION_OMEGA = (1.0 / (3.0 * KINEMATIC_VISCOSITY + 0.5)) PLOT_EVERY_N_STEPS = 100 SKIP_FIRS_N_ITERATIONS = 5000 N_ITERATIONS = 20000 print('Reynolds number:', reynolds_number) # Define a mesh for the obstacle mask x = jnp.arange(nx) y = jnp.arange(ny) z = jnp.arange(nz) X, Y, Z = jnp.meshgrid(x, y, z, indexing="ij") cylinder = jnp.sqrt((X - nx//5)**2 + (Y - ny//2)**2) obstacle_mask = cylinder < radius # Show topview of the cylinder: plt.imshow(obstacle_mask[:, :, nz//2].T) plt.show() # Front view: plt.imshow(obstacle_mask[nx//5, :, :].T) plt.show() # Side View: plt.imshow(obstacle_mask[:, ny//2, :].T) plt.show() def get_density(discrete_velocities): density = jnp.sum(discrete_velocities, axis=-1) return density def get_macroscopic_velocities(discrete_velocities, density): return jnp.einsum("NMLQ,dQ->NMLd", discrete_velocities, LATTICE_VELOCITIES) / density[..., jnp.newaxis] def get_equilibrium_discrete_velocities(macroscopic_velocities, density): projected_discrete_velocities = jnp.einsum("dQ,NMLd->NMLQ", LATTICE_VELOCITIES, macroscopic_velocities) macroscopic_velocity_magnitude = jnp.linalg.norm(macroscopic_velocities, axis=-1, ord=2) equilibrium_discrete_velocities = (density[..., jnp.newaxis] * LATTICE_WEIGHTS[jnp.newaxis, jnp.newaxis, jnp.newaxis, :] * (1 + 3 * projected_discrete_velocities + 9/2 * projected_discrete_velocities**2 - 3/2 * macroscopic_velocity_magnitude[..., jnp.newaxis]**2)) return equilibrium_discrete_velocities N_DISCRETE_VELOCITIES = 19 # 3D lattice velocities and numbering used as in: # https://www.researchgate.net/publication/290158292_An_introduction_to_Lattice-Boltzmann_methods LATTICE_INDICES = jnp.array([ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9,10,11,12,13,14,15,16,17,18]) LATICE_VELOCITIES_X = jnp.array([ 0, 1, 0,-1, 0, 0, 0, 1,-1,-1, 1, 1,-1,-1, 1, 0, 0, 0, 0]) LATICE_VELOCITIES_Y = jnp.array([ 0, 0, 1, 0,-1, 0, 0, 1, 1,-1,-1, 0, 0, 0, 0, 1,-1,-1, 1]) LATICE_VELOCITIES_Z = jnp.array([ 0, 0, 0, 0, 0, 1,-1, 0, 0, 0, 0, 1, 1,-1,-1, 1, 1,-1,-1]) OPPOSITE_LATTICE_INDICES = jnp.array([ 0, 3, 4, 1, 2, 6, 5, 9,10, 7, 8,13,14,11,12,17,18,15,16]) LATTICE_VELOCITIES = jnp.array([LATICE_VELOCITIES_X, LATICE_VELOCITIES_Y, LATICE_VELOCITIES_Z]) LATTICE_WEIGHTS = jnp.array([# rest particle 1/3, # face-connected neighbors 1/18, 1/18, 1/18, 1/18, 1/18, 1/18, # edge-connected neighbors 1/36, 1/36, 1/36, 1/36, 1/36, 1/36, 1/36, 1/36, 1/36, 1/36, 1/36, 1/36]) # Velocity directions/planes RIGHT_VELOCITIES = jnp.array([1, 7, 10, 11, 14]) # LATICE_VELOCITIES_X = 1 LEFT_VELOCITIES = jnp.array([3, 8, 9, 12, 13]) # LATICE_VELOCITIES_X =-1 YZ_VELOCITIES = jnp.array([0, 2, 4, 5, 6, 15, 16, 17, 18]) # LATICE_VELOCITIES_X = 0 VELOCITY_PROFILE = jnp.zeros((nx, ny, nz, 3)) VELOCITY_PROFILE = VELOCITY_PROFILE.at[:, :, :, 0].set(HORIZONTAL_INFLOW_VELOCITY) discrete_velocities_prev = get_equilibrium_discrete_velocities(VELOCITY_PROFILE, jnp.ones((nx, ny, nz))) @jax.jit def update(discrete_velocities_prev): # (1) Prescribe the outflow BC on the right boundary. Flow can go out, but not back in. discrete_velocities_prev = discrete_velocities_prev.at[-1, :, :, LEFT_VELOCITIES].set(discrete_velocities_prev[-2, :, :, LEFT_VELOCITIES]) # (2) Determine macroscopic velocities density_prev = get_density(discrete_velocities_prev) macroscopic_velocities_prev = get_macroscopic_velocities( discrete_velocities_prev, density_prev) # (3) Prescribe Inflow Dirichlet BC using Zou/He scheme in 3D: # https://arxiv.org/pdf/0811.4593.pdf # https://terpconnect.umd.edu/~aydilek/papers/LB.pdf macroscopic_velocities_prev = macroscopic_velocities_prev.at[0, 1:-1, 1:-1, :].set(VELOCITY_PROFILE[0, 1:-1, 1:-1, :]) lateral_densities = get_density(jnp.transpose(discrete_velocities_prev[0, :, :, YZ_VELOCITIES], axes = (1, 2, 0))) left_densities = get_density(jnp.transpose(discrete_velocities_prev[0, :, :, LEFT_VELOCITIES], axes = (1, 2, 0))) density_prev = density_prev.at[0, :, :].set((lateral_densities + 2 * left_densities) / (1 - macroscopic_velocities_prev[0, :, :, 0])) # (4) Compute discrete Equilibria velocities equilibrium_discrete_velocities = get_equilibrium_discrete_velocities( macroscopic_velocities_prev, density_prev) # (3) Belongs to the Zou/He scheme discrete_velocities_prev =\ discrete_velocities_prev.at[0, :, :, RIGHT_VELOCITIES].set( equilibrium_discrete_velocities[0, :, :, RIGHT_VELOCITIES]) # (5) Collide according to BGK discrete_velocities_post_collision = (discrete_velocities_prev - RELAXATION_OMEGA * (discrete_velocities_prev - equilibrium_discrete_velocities)) # (6) Bounce-Back Boundary Conditions to enfore the no-slip for i in range(N_DISCRETE_VELOCITIES): discrete_velocities_post_collision = discrete_velocities_post_collision.at[obstacle_mask, LATTICE_INDICES[i]].set( discrete_velocities_prev[obstacle_mask, OPPOSITE_LATTICE_INDICES[i]]) # (7) Stream alongside lattice velocities discrete_velocities_streamed = discrete_velocities_post_collision for i in range(N_DISCRETE_VELOCITIES): discrete_velocities_streamed = discrete_velocities_streamed.at[:, :, :, i].set( jnp.roll( jnp.roll( jnp.roll( discrete_velocities_post_collision[:, :, :, i], LATTICE_VELOCITIES[0, i], axis = 0), LATTICE_VELOCITIES[1, i], axis = 1), LATTICE_VELOCITIES[2, i], axis = 2)) return discrete_velocities_streamed def run(discrete_velocities_prev): for i in tqdm(range(N_ITERATIONS)): discrete_velocities_next = update(discrete_velocities_prev) discrete_velocities_prev = discrete_velocities_next if i % PLOT_EVERY_N_STEPS == 0 and i > SKIP_FIRS_N_ITERATIONS - PLOT_EVERY_N_STEPS: density = get_density(discrete_velocities_next) macroscopic_velocities = get_macroscopic_velocities( discrete_velocities_next, density) print('\n', jnp.max(macroscopic_velocities)) velocity_magnitude = jnp.linalg.norm( macroscopic_velocities, axis=-1, ord=2) fig = plt.figure(figsize = (15, 3)) cont = plt.contourf(X[:, :, nz//2], Y[:, :, nz//2], jnp.flip(velocity_magnitude[:, :, nz//2], axis = 1), alpha=0.8, cmap=cmr.iceburn) plt.axis('scaled') plt.axis('off') plt.show() return run(discrete_velocities_prev)
english/simulation_scripts/D3Q19_lattice_boltzmann_method_python_jax.py
8,953
Adjustment from the 2D version from Machine Learning & Simulation code and video: https://www.youtube.com/watch?v=ZUXmO4hu-20&list=LL&index=1&ab_channel=MachineLearning%26Simulation https://github.com/Ceyron/machine-learning-and-simulation/blob/main/english/simulation_scripts/lattice_boltzmann_method_python_jax.py by Bart Davids. Originally made in Google Colab: https://colab.research.google.com/drive/1F3EH9_2N3lkEpgQXOScR3lcQ6oqCARPk?usp=sharing Additional notes and figures for clarification can be found there. -*- coding: utf-8 -*- Import dependancies Enable 64bit JAX Radius of the cylinder Dimensions of domain Define a mesh for the obstacle mask Show topview of the cylinder: Front view: Side View: 3D lattice velocities and numbering used as in: https://www.researchgate.net/publication/290158292_An_introduction_to_Lattice-Boltzmann_methods rest particle face-connected neighbors edge-connected neighbors Velocity directions/planes LATICE_VELOCITIES_X = 1 LATICE_VELOCITIES_X =-1 LATICE_VELOCITIES_X = 0 (1) Prescribe the outflow BC on the right boundary. Flow can go out, but not back in. (2) Determine macroscopic velocities (3) Prescribe Inflow Dirichlet BC using Zou/He scheme in 3D: https://arxiv.org/pdf/0811.4593.pdf https://terpconnect.umd.edu/~aydilek/papers/LB.pdf (4) Compute discrete Equilibria velocities (3) Belongs to the Zou/He scheme (5) Collide according to BGK (6) Bounce-Back Boundary Conditions to enfore the no-slip (7) Stream alongside lattice velocities
1,505
en
0.716374
__author__ = 'ialbert' from django.views.generic import DetailView, ListView, TemplateView, RedirectView, View from haystack.views import SearchView from haystack.forms import SearchForm from haystack.query import SearchQuerySet, AutoQuery from haystack.utils import Highlighter from django.conf import settings from biostar.server.views import BaseListMixin from ajax import ajax_error, ajax_success, ajax_error_wrapper, json_response from django.conf.urls import patterns from django.contrib.sitemaps import FlatPageSitemap, GenericSitemap from biostar.apps.posts.models import Post, Tag from biostar.apps.planet.models import BlogPost import logging logger = logging.getLogger(__name__) info_dict = { 'queryset': Post.objects.all(), } sitemaps = { 'flatpages': FlatPageSitemap, 'posts': GenericSitemap(info_dict, priority=0.6), } class SiteSearch(SearchView): extra_context = lambda x: dict(topic="search", page_title="Search") def slow_highlight(query, text): "Invoked only if the search backend does not support highlighting" highlight = Highlighter(query) value = highlight.highlight(text) return value def join_highlights(row): "Joins the highlighted text" if type(row.highlighted) is dict: return '' if not row.highlighted: return return '<br>'.join(x for x in row.highlighted) class Search(BaseListMixin): template_name = "search/search.html" paginate_by = settings.PAGINATE_BY context_object_name = "results" page_title = "Search" def get_queryset(self): self.q = self.request.GET.get('q', '') if not self.q: return [] content = AutoQuery(self.q) query = SearchQuerySet().filter(content=content).highlight()[:50] for row in query: if row is None: continue context = join_highlights(row) context = context or slow_highlight(query=self.q, text=row.content) row.context = context return query def get_context_data(self, **kwargs): context = super(Search, self).get_context_data(**kwargs) context['q'] = self.q return context def suggest_tags(request): "Returns suggested tags" tags = Tag.objects.all().order_by('-count')#[:10] data = settings.POST_TAG_LIST + [t.name for t in tags] data = filter(None, data) return json_response(data) #@ajax_error_wrapper def search_title(request): "Handles title searches" q = request.GET.get('q', '') content = AutoQuery(q) results = SearchQuerySet().filter(content=content).highlight()[:50] items = [] for row in results: try: ob = row.object # Why can this happen? if not ob: continue context = join_highlights(row) context = context or slow_highlight(query=q, text=row.content) text = "%s" % row.title items.append( dict(id=ob.get_absolute_url(), text=text, context=context, author=row.author, url=ob.get_absolute_url()), ) except Exception, exc: logger.error(content) logger.error(exc) pass payload = dict(items=items) return json_response(payload)
biostar/server/search.py
3,312
[:10]@ajax_error_wrapper Why can this happen?
45
en
0.299277
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. import re import sys import unittest from shutil import copyfile, copytree from tempfile import TemporaryDirectory import jmespath import pytest from parameterized import parameterized from tests.helm_template_generator import render_chart class PodTemplateFileTest(unittest.TestCase): @classmethod @pytest.fixture(autouse=True, scope="class") def isolate_chart(cls): with TemporaryDirectory() as tmp_dir: cls.temp_chart_dir = tmp_dir + "/chart" copytree(sys.path[0], cls.temp_chart_dir) copyfile( cls.temp_chart_dir + "/files/pod-template-file.kubernetes-helm-yaml", cls.temp_chart_dir + "/templates/pod-template-file.yaml", ) yield def test_should_work(self): docs = render_chart( values={}, show_only=["templates/pod-template-file.yaml"], chart_dir=self.temp_chart_dir, ) assert re.search("Pod", docs[0]["kind"]) assert jmespath.search("spec.containers[0].image", docs[0]) is not None assert "base" == jmespath.search("spec.containers[0].name", docs[0]) def test_should_add_an_init_container_if_git_sync_is_true(self): docs = render_chart( values={ "images": { "gitSync": { "repository": "test-registry/test-repo", "tag": "test-tag", "pullPolicy": "Always", } }, "dags": { "gitSync": { "enabled": True, "containerName": "git-sync-test", "wait": 66, "maxFailures": 70, "subPath": "path1/path2", "dest": "test-dest", "root": "/git-root", "rev": "HEAD", "depth": 1, "repo": "https://github.com/apache/airflow.git", "branch": "test-branch", "sshKeySecret": None, "credentialsSecret": None, "knownHosts": None, } }, }, show_only=["templates/pod-template-file.yaml"], chart_dir=self.temp_chart_dir, ) assert re.search("Pod", docs[0]["kind"]) assert { "name": "git-sync-test", "securityContext": {"runAsUser": 65533}, "image": "test-registry/test-repo:test-tag", "imagePullPolicy": "Always", "env": [ {"name": "GIT_SYNC_REV", "value": "HEAD"}, {"name": "GIT_SYNC_BRANCH", "value": "test-branch"}, {"name": "GIT_SYNC_REPO", "value": "https://github.com/apache/airflow.git"}, {"name": "GIT_SYNC_DEPTH", "value": "1"}, {"name": "GIT_SYNC_ROOT", "value": "/git-root"}, {"name": "GIT_SYNC_DEST", "value": "test-dest"}, {"name": "GIT_SYNC_ADD_USER", "value": "true"}, {"name": "GIT_SYNC_WAIT", "value": "66"}, {"name": "GIT_SYNC_MAX_SYNC_FAILURES", "value": "70"}, {"name": "GIT_SYNC_ONE_TIME", "value": "true"}, ], "volumeMounts": [{"mountPath": "/git-root", "name": "dags"}], } == jmespath.search("spec.initContainers[0]", docs[0]) def test_should_not_add_init_container_if_dag_persistence_is_true(self): docs = render_chart( values={ "dags": { "persistence": {"enabled": True}, "gitSync": {"enabled": True}, } }, show_only=["templates/pod-template-file.yaml"], chart_dir=self.temp_chart_dir, ) assert jmespath.search("spec.initContainers", docs[0]) is None @parameterized.expand( [ ({"gitSync": {"enabled": True}},), ({"persistence": {"enabled": True}},), ( { "gitSync": {"enabled": True}, "persistence": {"enabled": True}, }, ), ] ) def test_dags_mount(self, dag_values): docs = render_chart( values={"dags": dag_values}, show_only=["templates/pod-template-file.yaml"], chart_dir=self.temp_chart_dir, ) assert {"mountPath": "/opt/airflow/dags", "name": "dags", "readOnly": True} in jmespath.search( "spec.containers[0].volumeMounts", docs[0] ) def test_dags_mount_with_gitsync_and_persistence(self): docs = render_chart( values={ "dags": { "gitSync": {"enabled": True}, "persistence": {"enabled": True}, } }, show_only=["templates/pod-template-file.yaml"], chart_dir=self.temp_chart_dir, ) assert {"mountPath": "/opt/airflow/dags", "name": "dags", "readOnly": True} in jmespath.search( "spec.containers[0].volumeMounts", docs[0] ) def test_validate_if_ssh_params_are_added(self): docs = render_chart( values={ "dags": { "gitSync": { "enabled": True, "containerName": "git-sync-test", "sshKeySecret": "ssh-secret", "knownHosts": None, "branch": "test-branch", } } }, show_only=["templates/pod-template-file.yaml"], chart_dir=self.temp_chart_dir, ) assert {"name": "GIT_SSH_KEY_FILE", "value": "/etc/git-secret/ssh"} in jmespath.search( "spec.initContainers[0].env", docs[0] ) assert {"name": "GIT_SYNC_SSH", "value": "true"} in jmespath.search( "spec.initContainers[0].env", docs[0] ) assert {"name": "GIT_KNOWN_HOSTS", "value": "false"} in jmespath.search( "spec.initContainers[0].env", docs[0] ) assert { "name": "git-sync-ssh-key", "secret": {"secretName": "ssh-secret", "defaultMode": 288}, } in jmespath.search("spec.volumes", docs[0]) def test_validate_if_ssh_known_hosts_are_added(self): docs = render_chart( values={ "dags": { "gitSync": { "enabled": True, "containerName": "git-sync-test", "sshKeySecret": "ssh-secret", "knownHosts": "github.com ssh-rsa AAAABdummy", "branch": "test-branch", } } }, show_only=["templates/pod-template-file.yaml"], chart_dir=self.temp_chart_dir, ) assert {"name": "GIT_KNOWN_HOSTS", "value": "true"} in jmespath.search( "spec.initContainers[0].env", docs[0] ) assert { "name": "git-sync-known-hosts", "configMap": {"defaultMode": 288, "name": "RELEASE-NAME-airflow-config"}, } in jmespath.search("spec.volumes", docs[0]) assert { "name": "git-sync-known-hosts", "mountPath": "/etc/git-secret/known_hosts", "subPath": "known_hosts", } in jmespath.search("spec.containers[0].volumeMounts", docs[0]) def test_should_set_username_and_pass_env_variables(self): docs = render_chart( values={ "dags": { "gitSync": { "enabled": True, "credentialsSecret": "user-pass-secret", "sshKeySecret": None, } } }, show_only=["templates/pod-template-file.yaml"], chart_dir=self.temp_chart_dir, ) assert { "name": "GIT_SYNC_USERNAME", "valueFrom": {"secretKeyRef": {"name": "user-pass-secret", "key": "GIT_SYNC_USERNAME"}}, } in jmespath.search("spec.initContainers[0].env", docs[0]) assert { "name": "GIT_SYNC_PASSWORD", "valueFrom": {"secretKeyRef": {"name": "user-pass-secret", "key": "GIT_SYNC_PASSWORD"}}, } in jmespath.search("spec.initContainers[0].env", docs[0]) def test_should_set_the_dags_volume_claim_correctly_when_using_an_existing_claim(self): docs = render_chart( values={"dags": {"persistence": {"enabled": True, "existingClaim": "test-claim"}}}, show_only=["templates/pod-template-file.yaml"], chart_dir=self.temp_chart_dir, ) assert {"name": "dags", "persistentVolumeClaim": {"claimName": "test-claim"}} in jmespath.search( "spec.volumes", docs[0] ) def test_should_use_empty_dir_for_gitsync_without_persistence(self): docs = render_chart( values={"dags": {"gitSync": {"enabled": True}}}, show_only=["templates/pod-template-file.yaml"], chart_dir=self.temp_chart_dir, ) assert {"name": "dags", "emptyDir": {}} in jmespath.search("spec.volumes", docs[0]) @parameterized.expand( [ ({"enabled": False}, {"emptyDir": {}}), ({"enabled": True}, {"persistentVolumeClaim": {"claimName": "RELEASE-NAME-logs"}}), ( {"enabled": True, "existingClaim": "test-claim"}, {"persistentVolumeClaim": {"claimName": "test-claim"}}, ), ] ) def test_logs_persistence_changes_volume(self, log_persistence_values, expected): docs = render_chart( values={"logs": {"persistence": log_persistence_values}}, show_only=["templates/pod-template-file.yaml"], chart_dir=self.temp_chart_dir, ) assert {"name": "logs", **expected} in jmespath.search("spec.volumes", docs[0]) def test_should_set_a_custom_image_in_pod_template(self): docs = render_chart( values={"images": {"pod_template": {"repository": "dummy_image", "tag": "latest"}}}, show_only=["templates/pod-template-file.yaml"], chart_dir=self.temp_chart_dir, ) assert re.search("Pod", docs[0]["kind"]) assert "dummy_image:latest" == jmespath.search("spec.containers[0].image", docs[0]) assert "base" == jmespath.search("spec.containers[0].name", docs[0]) def test_mount_airflow_cfg(self): docs = render_chart( values={}, show_only=["templates/pod-template-file.yaml"], chart_dir=self.temp_chart_dir, ) assert re.search("Pod", docs[0]["kind"]) assert {'configMap': {'name': 'RELEASE-NAME-airflow-config'}, 'name': 'config'} == jmespath.search( "spec.volumes[1]", docs[0] ) assert { 'name': 'config', 'mountPath': '/opt/airflow/airflow.cfg', 'subPath': 'airflow.cfg', 'readOnly': True, } == jmespath.search("spec.containers[0].volumeMounts[1]", docs[0]) def test_should_create_valid_affinity_and_node_selector(self): docs = render_chart( values={ "affinity": { "nodeAffinity": { "requiredDuringSchedulingIgnoredDuringExecution": { "nodeSelectorTerms": [ { "matchExpressions": [ {"key": "foo", "operator": "In", "values": ["true"]}, ] } ] } } }, "tolerations": [ {"key": "dynamic-pods", "operator": "Equal", "value": "true", "effect": "NoSchedule"} ], "nodeSelector": {"diskType": "ssd"}, }, show_only=["templates/pod-template-file.yaml"], chart_dir=self.temp_chart_dir, ) assert re.search("Pod", docs[0]["kind"]) assert "foo" == jmespath.search( "spec.affinity.nodeAffinity." "requiredDuringSchedulingIgnoredDuringExecution." "nodeSelectorTerms[0]." "matchExpressions[0]." "key", docs[0], ) assert "ssd" == jmespath.search( "spec.nodeSelector.diskType", docs[0], ) assert "dynamic-pods" == jmespath.search( "spec.tolerations[0].key", docs[0], ) def test_should_add_fsgroup_to_the_pod_template(self): docs = render_chart( values={"gid": 5000}, show_only=["templates/pod-template-file.yaml"], chart_dir=self.temp_chart_dir, ) self.assertEqual(5000, jmespath.search("spec.securityContext.fsGroup", docs[0])) def test_should_create_valid_volume_mount_and_volume(self): docs = render_chart( values={ "workers": { "extraVolumes": [{"name": "test-volume", "emptyDir": {}}], "extraVolumeMounts": [{"name": "test-volume", "mountPath": "/opt/test"}], } }, show_only=["templates/pod-template-file.yaml"], chart_dir=self.temp_chart_dir, ) assert "test-volume" == jmespath.search( "spec.volumes[2].name", docs[0], ) assert "test-volume" == jmespath.search( "spec.containers[0].volumeMounts[2].name", docs[0], ) def test_should_add_env_for_gitsync(self): docs = render_chart( values={ "dags": { "gitSync": { "enabled": True, "env": [{"name": "FOO", "value": "bar"}], } }, }, show_only=["templates/pod-template-file.yaml"], chart_dir=self.temp_chart_dir, ) assert {"name": "FOO", "value": "bar"} in jmespath.search("spec.initContainers[0].env", docs[0]) def test_no_airflow_local_settings_by_default(self): docs = render_chart(show_only=["templates/pod-template-file.yaml"], chart_dir=self.temp_chart_dir) volume_mounts = jmespath.search("spec.containers[0].volumeMounts", docs[0]) assert "airflow_local_settings.py" not in str(volume_mounts) def test_airflow_local_settings(self): docs = render_chart( values={"airflowLocalSettings": "# Well hello!"}, show_only=["templates/pod-template-file.yaml"], chart_dir=self.temp_chart_dir, ) assert { "name": "config", "mountPath": "/opt/airflow/config/airflow_local_settings.py", "subPath": "airflow_local_settings.py", "readOnly": True, } in jmespath.search("spec.containers[0].volumeMounts", docs[0]) def test_airflow_pod_annotations(self): docs = render_chart( values={"airflowPodAnnotations": {"my_annotation": "annotated!"}}, show_only=["templates/pod-template-file.yaml"], chart_dir=self.temp_chart_dir, ) annotations = jmespath.search("metadata.annotations", docs[0]) assert "my_annotation" in annotations assert "annotated!" in annotations["my_annotation"]
chart/tests/test_pod_template_file.py
16,578
Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to you under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.
752
en
0.883564
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. """ Auto-tuning a Convolutional Network for Mobile GPU ================================================== **Author**: `Lianmin Zheng <https://github.com/merrymercy>`_, `Eddie Yan <https://github.com/eqy>`_ Auto-tuning for a specific device is critical for getting the best performance. This is a tutorial about how to tune a whole convolutional network. The operator implementation for Mobile GPU in TVM is written in template form. The template has many tunable knobs (tile factor, vectorization, unrolling, etc). We will tune all convolution, depthwise convolution and dense operators in the neural network. After tuning, we produce a log file which stores the best knob values for all required operators. When the TVM compiler compiles these operators, it will query this log file to get the best knob values. We also released pre-tuned parameters for some arm devices. You can go to `Mobile GPU Benchmark <https://github.com/apache/tvm/wiki/Benchmark#mobile-gpu>`_ to see the results. Note that this tutorial will not run on Windows or recent versions of macOS. To get it to run, you will need to wrap the body of this tutorial in a :code:`if __name__ == "__main__":` block. """ ###################################################################### # Install dependencies # -------------------- # To use the autotvm package in tvm, we need to install some extra dependencies. # (change "3" to "2" if you use python2): # # .. code-block:: bash # # pip3 install --user psutil xgboost tornado cloudpickle # # To make TVM run faster during tuning, it is recommended to use cython # as FFI of tvm. In the root directory of tvm, execute # (change "3" to "2" if you use python2): # # .. code-block:: bash # # pip3 install --user cython # sudo make cython3 # # Now return to python code. Import packages. import os import numpy as np import tvm from tvm import relay, autotvm import tvm.relay.testing from tvm.autotvm.tuner import XGBTuner, GATuner, RandomTuner, GridSearchTuner from tvm.contrib.utils import tempdir import tvm.contrib.graph_executor as runtime ################################################################# # Define network # -------------- # First we need to define the network in relay frontend API. # We can load some pre-defined network from :code:`relay.testing`. # We can also load models from MXNet, ONNX and TensorFlow. def get_network(name, batch_size): """Get the symbol definition and random weight of a network""" input_shape = (batch_size, 3, 224, 224) output_shape = (batch_size, 1000) if "resnet" in name: n_layer = int(name.split("-")[1]) mod, params = relay.testing.resnet.get_workload( num_layers=n_layer, batch_size=batch_size, dtype=dtype ) elif "vgg" in name: n_layer = int(name.split("-")[1]) mod, params = relay.testing.vgg.get_workload( num_layers=n_layer, batch_size=batch_size, dtype=dtype ) elif name == "mobilenet": mod, params = relay.testing.mobilenet.get_workload(batch_size=batch_size, dtype=dtype) elif name == "squeezenet_v1.1": mod, params = relay.testing.squeezenet.get_workload( batch_size=batch_size, version="1.1", dtype=dtype ) elif name == "inception_v3": input_shape = (batch_size, 3, 299, 299) mod, params = relay.testing.inception_v3.get_workload(batch_size=batch_size, dtype=dtype) elif name == "mxnet": # an example for mxnet model from mxnet.gluon.model_zoo.vision import get_model block = get_model("resnet18_v1", pretrained=True) mod, params = relay.frontend.from_mxnet(block, shape={"data": input_shape}, dtype=dtype) net = mod["main"] net = relay.Function( net.params, relay.nn.softmax(net.body), None, net.type_params, net.attrs ) mod = tvm.IRModule.from_expr(net) else: raise ValueError("Unsupported network: " + name) return mod, params, input_shape, output_shape ################################################################# # .. _tutorials-autotvm-start-rpc-tracker: ################################################################# # Start RPC Tracker # ----------------- # TVM uses RPC session to communicate with ARM boards. # During tuning, the tuner will send the generated code to the board and # measure the speed of code on the board. # # To scale up the tuning, TVM uses RPC Tracker to manage distributed devices. # The RPC Tracker is a centralized controller node. We can register all devices to # the tracker. For example, if we have 10 phones, we can register all of them # to the tracker, and run 10 measurements in parallel, accelerating the tuning process. # # To start an RPC tracker, run this command on the host machine. The tracker is # required during the whole tuning process, so we need to open a new terminal for # this command: # # .. code-block:: bash # # python -m tvm.exec.rpc_tracker --host=0.0.0.0 --port=9190 # # The expected output is # # .. code-block:: bash # # INFO:RPCTracker:bind to 0.0.0.0:9190 ################################################################# # Register Devices to RPC Tracker # ----------------------------------- # Now we can register our devices to the tracker. The first step is to # build the TVM runtime for the ARM devices. # # * For Linux: # Follow this section :ref:`build-tvm-runtime-on-device` to build # the TVM runtime on the device. Then register the device to tracker by # # .. code-block:: bash # # python -m tvm.exec.rpc_server --tracker=[HOST_IP]:9190 --key=rk3399 # # (replace :code:`[HOST_IP]` with the IP address of your host machine) # # * For Android: # Follow this `readme page <https://github.com/apache/tvm/tree/main/apps/android_rpc>`_ to # install TVM RPC APK on the android device. Make sure you can pass the android RPC test. # Then you have already registered your device. During tuning, you have to go to developer option # and enable "Keep screen awake during changing" and charge your phone to make it stable. # # After registering devices, we can confirm it by querying rpc_tracker # # .. code-block:: bash # # python -m tvm.exec.query_rpc_tracker --host=0.0.0.0 --port=9190 # # For example, if we have 2 Huawei mate10 pro, 11 Raspberry Pi 3B and 2 rk3399, # the output can be # # .. code-block:: bash # # Queue Status # ---------------------------------- # key total free pending # ---------------------------------- # mate10pro 2 2 0 # rk3399 2 2 0 # rpi3b 11 11 0 # ---------------------------------- # # You can register multiple devices to the tracker to accelerate the measurement in tuning. ########################################### # Set Tuning Options # ------------------ # Before tuning, we should apply some configurations. Here I use an RK3399 board # as example. In your setting, you should modify the target and device_key accordingly. # set :code:`use_android` to True if you use android phone. #### DEVICE CONFIG #### # Replace "aarch64-linux-gnu" with the correct target of your board. # This target host is used for cross compilation. You can query it by :code:`gcc -v` on your device. target = tvm.target.Target("opencl -device=mali", host="llvm -mtriple=aarch64-linux-gnu") # Also replace this with the device key in your tracker device_key = "rk3399" # Set this to True if you use android phone use_android = False #### TUNING OPTION #### network = "resnet-18" log_file = "%s.%s.log" % (device_key, network) dtype = "float32" tuning_option = { "log_filename": log_file, "tuner": "xgb", "n_trial": 1000, "early_stopping": 450, "measure_option": autotvm.measure_option( builder=autotvm.LocalBuilder(build_func="ndk" if use_android else "default"), runner=autotvm.RPCRunner( device_key, host="127.0.0.1", port=9190, number=10, timeout=5, ), ), } #################################################################### # # .. note:: How to set tuning options # # In general, the default values provided here work well. # If you have enough time budget, you can set :code:`n_trial`, :code:`early_stopping` larger, # which makes the tuning run longer. # If your device runs very slow or your conv2d operators have many GFLOPs, considering to # set timeout larger. # ################################################################### # Begin Tuning # ------------ # Now we can extract tuning tasks from the network and begin tuning. # Here, we provide a simple utility function to tune a list of tasks. # This function is just an initial implementation which tunes them in sequential order. # We will introduce a more sophisticated tuning scheduler in the future. # You can skip the implementation of this function for this tutorial. def tune_tasks( tasks, measure_option, tuner="xgb", n_trial=1000, early_stopping=None, log_filename="tuning.log", use_transfer_learning=True, ): # create tmp log file tmp_log_file = log_filename + ".tmp" if os.path.exists(tmp_log_file): os.remove(tmp_log_file) for i, tsk in enumerate(reversed(tasks)): prefix = "[Task %2d/%2d] " % (i + 1, len(tasks)) # create tuner if tuner == "xgb" or tuner == "xgb-rank": tuner_obj = XGBTuner(tsk, loss_type="rank") elif tuner == "ga": tuner_obj = GATuner(tsk, pop_size=50) elif tuner == "random": tuner_obj = RandomTuner(tsk) elif tuner == "gridsearch": tuner_obj = GridSearchTuner(tsk) else: raise ValueError("Invalid tuner: " + tuner) if use_transfer_learning: if os.path.isfile(tmp_log_file): tuner_obj.load_history(autotvm.record.load_from_file(tmp_log_file)) # do tuning tsk_trial = min(n_trial, len(tsk.config_space)) tuner_obj.tune( n_trial=tsk_trial, early_stopping=early_stopping, measure_option=measure_option, callbacks=[ autotvm.callback.progress_bar(tsk_trial, prefix=prefix), autotvm.callback.log_to_file(tmp_log_file), ], ) # pick best records to a cache file autotvm.record.pick_best(tmp_log_file, log_filename) os.remove(tmp_log_file) ######################################################################## # Finally, we launch tuning jobs and evaluate the end-to-end performance. def tune_and_evaluate(tuning_opt): # extract workloads from relay program print("Extract tasks...") mod, params, input_shape, _ = get_network(network, batch_size=1) tasks = autotvm.task.extract_from_program( mod["main"], target=target, params=params, ops=(relay.op.get("nn.conv2d"),), ) # run tuning tasks print("Tuning...") tune_tasks(tasks, **tuning_opt) # compile kernels with history best records with autotvm.apply_history_best(log_file): print("Compile...") with tvm.transform.PassContext(opt_level=3): lib = relay.build_module.build(mod, target=target, params=params) # export library tmp = tempdir() if use_android: from tvm.contrib import ndk filename = "net.so" lib.export_library(tmp.relpath(filename), ndk.create_shared) else: filename = "net.tar" lib.export_library(tmp.relpath(filename)) # upload module to device print("Upload...") remote = autotvm.measure.request_remote(device_key, "127.0.0.1", 9190, timeout=10000) remote.upload(tmp.relpath(filename)) rlib = remote.load_module(filename) # upload parameters to device dev = remote.device(str(target), 0) module = runtime.GraphModule(rlib["default"](dev)) data_tvm = tvm.nd.array((np.random.uniform(size=input_shape)).astype(dtype)) module.set_input("data", data_tvm) # evaluate print("Evaluate inference time cost...") ftimer = module.module.time_evaluator("run", dev, number=1, repeat=30) prof_res = np.array(ftimer().results) * 1000 # convert to millisecond print( "Mean inference time (std dev): %.2f ms (%.2f ms)" % (np.mean(prof_res), np.std(prof_res)) ) # We do not run the tuning in our webpage server since it takes too long. # Uncomment the following line to run it by yourself. # tune_and_evaluate(tuning_option) ###################################################################### # Sample Output # ------------- # The tuning needs to compile many programs and extract feature from them. # So a high performance CPU is recommended. # One sample output is listed below. It takes about 3 hours on a 32T AMD Ryzen Threadripper. # # .. code-block:: bash # # Extract tasks... # Tuning... # [Task 1/17] Current/Best: 25.30/ 39.12 GFLOPS | Progress: (992/1000) | 751.22 s Done. # [Task 2/17] Current/Best: 40.70/ 45.50 GFLOPS | Progress: (736/1000) | 545.46 s Done. # [Task 3/17] Current/Best: 38.83/ 42.35 GFLOPS | Progress: (992/1000) | 1549.85 s Done. # [Task 4/17] Current/Best: 23.31/ 31.02 GFLOPS | Progress: (640/1000) | 1059.31 s Done. # [Task 5/17] Current/Best: 0.06/ 2.34 GFLOPS | Progress: (544/1000) | 305.45 s Done. # [Task 6/17] Current/Best: 10.97/ 17.20 GFLOPS | Progress: (992/1000) | 1050.00 s Done. # [Task 7/17] Current/Best: 8.98/ 10.94 GFLOPS | Progress: (928/1000) | 421.36 s Done. # [Task 8/17] Current/Best: 4.48/ 14.86 GFLOPS | Progress: (704/1000) | 582.60 s Done. # [Task 9/17] Current/Best: 10.30/ 25.99 GFLOPS | Progress: (864/1000) | 899.85 s Done. # [Task 10/17] Current/Best: 11.73/ 12.52 GFLOPS | Progress: (608/1000) | 304.85 s Done. # [Task 11/17] Current/Best: 15.26/ 18.68 GFLOPS | Progress: (800/1000) | 747.52 s Done. # [Task 12/17] Current/Best: 17.48/ 26.71 GFLOPS | Progress: (1000/1000) | 1166.40 s Done. # [Task 13/17] Current/Best: 0.96/ 11.43 GFLOPS | Progress: (960/1000) | 611.65 s Done. # [Task 14/17] Current/Best: 17.88/ 20.22 GFLOPS | Progress: (672/1000) | 670.29 s Done. # [Task 15/17] Current/Best: 11.62/ 13.98 GFLOPS | Progress: (736/1000) | 449.25 s Done. # [Task 16/17] Current/Best: 19.90/ 23.83 GFLOPS | Progress: (608/1000) | 708.64 s Done. # [Task 17/17] Current/Best: 17.98/ 22.75 GFLOPS | Progress: (736/1000) | 1122.60 s Done. # Compile... # Upload... # Evaluate inference time cost... # Mean inference time (std dev): 128.05 ms (7.74 ms) # ###################################################################### # # .. note:: **Experiencing Difficulties?** # # The auto tuning module is error-prone. If you always see " 0.00/ 0.00 GFLOPS", # then there must be something wrong. # # First, make sure you set the correct configuration of your device. # Then, you can print debug information by adding these lines in the beginning # of the script. It will print every measurement result, where you can find useful # error messages. # # .. code-block:: python # # import logging # logging.getLogger('autotvm').setLevel(logging.DEBUG) # # Finally, always feel free to ask our community for help on https://discuss.tvm.apache.org
tutorials/autotvm/tune_relay_mobile_gpu.py
16,292
Get the symbol definition and random weight of a network Auto-tuning a Convolutional Network for Mobile GPU ================================================== **Author**: `Lianmin Zheng <https://github.com/merrymercy>`_, `Eddie Yan <https://github.com/eqy>`_ Auto-tuning for a specific device is critical for getting the best performance. This is a tutorial about how to tune a whole convolutional network. The operator implementation for Mobile GPU in TVM is written in template form. The template has many tunable knobs (tile factor, vectorization, unrolling, etc). We will tune all convolution, depthwise convolution and dense operators in the neural network. After tuning, we produce a log file which stores the best knob values for all required operators. When the TVM compiler compiles these operators, it will query this log file to get the best knob values. We also released pre-tuned parameters for some arm devices. You can go to `Mobile GPU Benchmark <https://github.com/apache/tvm/wiki/Benchmark#mobile-gpu>`_ to see the results. Note that this tutorial will not run on Windows or recent versions of macOS. To get it to run, you will need to wrap the body of this tutorial in a :code:`if __name__ == "__main__":` block. Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to you under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. Install dependencies -------------------- To use the autotvm package in tvm, we need to install some extra dependencies. (change "3" to "2" if you use python2): .. code-block:: bash pip3 install --user psutil xgboost tornado cloudpickle To make TVM run faster during tuning, it is recommended to use cython as FFI of tvm. In the root directory of tvm, execute (change "3" to "2" if you use python2): .. code-block:: bash pip3 install --user cython sudo make cython3 Now return to python code. Import packages. Define network -------------- First we need to define the network in relay frontend API. We can load some pre-defined network from :code:`relay.testing`. We can also load models from MXNet, ONNX and TensorFlow. an example for mxnet model .. _tutorials-autotvm-start-rpc-tracker: Start RPC Tracker ----------------- TVM uses RPC session to communicate with ARM boards. During tuning, the tuner will send the generated code to the board and measure the speed of code on the board. To scale up the tuning, TVM uses RPC Tracker to manage distributed devices. The RPC Tracker is a centralized controller node. We can register all devices to the tracker. For example, if we have 10 phones, we can register all of them to the tracker, and run 10 measurements in parallel, accelerating the tuning process. To start an RPC tracker, run this command on the host machine. The tracker is required during the whole tuning process, so we need to open a new terminal for this command: .. code-block:: bash python -m tvm.exec.rpc_tracker --host=0.0.0.0 --port=9190 The expected output is .. code-block:: bash INFO:RPCTracker:bind to 0.0.0.0:9190 Register Devices to RPC Tracker ----------------------------------- Now we can register our devices to the tracker. The first step is to build the TVM runtime for the ARM devices. * For Linux: Follow this section :ref:`build-tvm-runtime-on-device` to build the TVM runtime on the device. Then register the device to tracker by .. code-block:: bash python -m tvm.exec.rpc_server --tracker=[HOST_IP]:9190 --key=rk3399 (replace :code:`[HOST_IP]` with the IP address of your host machine) * For Android: Follow this `readme page <https://github.com/apache/tvm/tree/main/apps/android_rpc>`_ to install TVM RPC APK on the android device. Make sure you can pass the android RPC test. Then you have already registered your device. During tuning, you have to go to developer option and enable "Keep screen awake during changing" and charge your phone to make it stable. After registering devices, we can confirm it by querying rpc_tracker .. code-block:: bash python -m tvm.exec.query_rpc_tracker --host=0.0.0.0 --port=9190 For example, if we have 2 Huawei mate10 pro, 11 Raspberry Pi 3B and 2 rk3399, the output can be .. code-block:: bash Queue Status ---------------------------------- key total free pending ---------------------------------- mate10pro 2 2 0 rk3399 2 2 0 rpi3b 11 11 0 ---------------------------------- You can register multiple devices to the tracker to accelerate the measurement in tuning. Set Tuning Options ------------------ Before tuning, we should apply some configurations. Here I use an RK3399 board as example. In your setting, you should modify the target and device_key accordingly. set :code:`use_android` to True if you use android phone. DEVICE CONFIG Replace "aarch64-linux-gnu" with the correct target of your board. This target host is used for cross compilation. You can query it by :code:`gcc -v` on your device. Also replace this with the device key in your tracker Set this to True if you use android phone TUNING OPTION .. note:: How to set tuning options In general, the default values provided here work well. If you have enough time budget, you can set :code:`n_trial`, :code:`early_stopping` larger, which makes the tuning run longer. If your device runs very slow or your conv2d operators have many GFLOPs, considering to set timeout larger. Begin Tuning ------------ Now we can extract tuning tasks from the network and begin tuning. Here, we provide a simple utility function to tune a list of tasks. This function is just an initial implementation which tunes them in sequential order. We will introduce a more sophisticated tuning scheduler in the future. You can skip the implementation of this function for this tutorial. create tmp log file create tuner do tuning pick best records to a cache file Finally, we launch tuning jobs and evaluate the end-to-end performance. extract workloads from relay program run tuning tasks compile kernels with history best records export library upload module to device upload parameters to device evaluate convert to millisecond We do not run the tuning in our webpage server since it takes too long. Uncomment the following line to run it by yourself. tune_and_evaluate(tuning_option) Sample Output ------------- The tuning needs to compile many programs and extract feature from them. So a high performance CPU is recommended. One sample output is listed below. It takes about 3 hours on a 32T AMD Ryzen Threadripper. .. code-block:: bash Extract tasks... Tuning... [Task 1/17] Current/Best: 25.30/ 39.12 GFLOPS | Progress: (992/1000) | 751.22 s Done. [Task 2/17] Current/Best: 40.70/ 45.50 GFLOPS | Progress: (736/1000) | 545.46 s Done. [Task 3/17] Current/Best: 38.83/ 42.35 GFLOPS | Progress: (992/1000) | 1549.85 s Done. [Task 4/17] Current/Best: 23.31/ 31.02 GFLOPS | Progress: (640/1000) | 1059.31 s Done. [Task 5/17] Current/Best: 0.06/ 2.34 GFLOPS | Progress: (544/1000) | 305.45 s Done. [Task 6/17] Current/Best: 10.97/ 17.20 GFLOPS | Progress: (992/1000) | 1050.00 s Done. [Task 7/17] Current/Best: 8.98/ 10.94 GFLOPS | Progress: (928/1000) | 421.36 s Done. [Task 8/17] Current/Best: 4.48/ 14.86 GFLOPS | Progress: (704/1000) | 582.60 s Done. [Task 9/17] Current/Best: 10.30/ 25.99 GFLOPS | Progress: (864/1000) | 899.85 s Done. [Task 10/17] Current/Best: 11.73/ 12.52 GFLOPS | Progress: (608/1000) | 304.85 s Done. [Task 11/17] Current/Best: 15.26/ 18.68 GFLOPS | Progress: (800/1000) | 747.52 s Done. [Task 12/17] Current/Best: 17.48/ 26.71 GFLOPS | Progress: (1000/1000) | 1166.40 s Done. [Task 13/17] Current/Best: 0.96/ 11.43 GFLOPS | Progress: (960/1000) | 611.65 s Done. [Task 14/17] Current/Best: 17.88/ 20.22 GFLOPS | Progress: (672/1000) | 670.29 s Done. [Task 15/17] Current/Best: 11.62/ 13.98 GFLOPS | Progress: (736/1000) | 449.25 s Done. [Task 16/17] Current/Best: 19.90/ 23.83 GFLOPS | Progress: (608/1000) | 708.64 s Done. [Task 17/17] Current/Best: 17.98/ 22.75 GFLOPS | Progress: (736/1000) | 1122.60 s Done. Compile... Upload... Evaluate inference time cost... Mean inference time (std dev): 128.05 ms (7.74 ms) .. note:: **Experiencing Difficulties?** The auto tuning module is error-prone. If you always see " 0.00/ 0.00 GFLOPS", then there must be something wrong. First, make sure you set the correct configuration of your device. Then, you can print debug information by adding these lines in the beginning of the script. It will print every measurement result, where you can find useful error messages. .. code-block:: python import logging logging.getLogger('autotvm').setLevel(logging.DEBUG) Finally, always feel free to ask our community for help on https://discuss.tvm.apache.org
9,533
en
0.800315
from __future__ import absolute_import import abc class Database(object): __metaclass__ = abc.ABCMeta FIELD_FILE_SHA1 = 'file_sha1' FIELD_SONG_ID = 'song_id' FIELD_SONGNAME = 'song_name' FIELD_OFFSET = 'offset' FIELD_HASH = 'hash' # Name of your Database subclass, this is used in configuration # to refer to your class type = None def __init__(self): super(Database, self).__init__() def before_fork(self): """ Called before the database instance is given to the new process """ pass def after_fork(self): """ Called after the database instance has been given to the new process This will be called in the new process. """ pass def setup(self): """ Called on creation or shortly afterwards. """ pass @abc.abstractmethod def empty(self): """ Called when the database should be cleared of all data. """ pass @abc.abstractmethod def delete_unfingerprinted_songs(self): """ Called to remove any song entries that do not have any fingerprints associated with them. """ pass @abc.abstractmethod def get_num_songs(self): """ Returns the amount of songs in the database. """ pass @abc.abstractmethod def get_num_fingerprints(self): """ Returns the number of fingerprints in the database. """ pass @abc.abstractmethod def set_song_fingerprinted(self, sid): """ Sets a specific song as having all fingerprints in the database. sid: Song identifier """ pass @abc.abstractmethod def get_songs(self): """ Returns all fully fingerprinted songs in the database. """ pass @abc.abstractmethod def get_song_by_id(self, sid): """ Return a song by its identifier sid: Song identifier """ pass @abc.abstractmethod def insert(self, hash, sid, offset): """ Inserts a single fingerprint into the database. hash: Part of a sha1 hash, in hexadecimal format sid: Song identifier this fingerprint is off offset: The offset this hash is from """ pass @abc.abstractmethod def insert_song(self, song_name): """ Inserts a song name into the database, returns the new identifier of the song. song_name: The name of the song. """ pass @abc.abstractmethod def query(self, hash): """ Returns all matching fingerprint entries associated with the given hash as parameter. hash: Part of a sha1 hash, in hexadecimal format """ pass @abc.abstractmethod def get_iterable_kv_pairs(self): """ Returns all fingerprints in the database. """ pass @abc.abstractmethod def insert_hashes(self, sid, hashes): """ Insert a multitude of fingerprints. sid: Song identifier the fingerprints belong to hashes: A sequence of tuples in the format (hash, offset) - hash: Part of a sha1 hash, in hexadecimal format - offset: Offset this hash was created from/at. """ pass @abc.abstractmethod def return_matches(self, hashes): """ Searches the database for pairs of (hash, offset) values. hashes: A sequence of tuples in the format (hash, offset) - hash: Part of a sha1 hash, in hexadecimal format - offset: Offset this hash was created from/at. Returns a sequence of (sid, offset_difference) tuples. sid: Song identifier offset_difference: (offset - database_offset) """ pass def get_database(database_type=None): # Default to using the mysql database database_type = database_type or "mysql" # Lower all the input. database_type = database_type.lower() for db_cls in Database.__subclasses__(): if db_cls.type == database_type: return db_cls raise TypeError("Unsupported database type supplied.") # Import our default database handler # MySQL # import dejavu.database_sql # SQLite import dejavu.database_sqlite
dejavu/database.py
4,403
Called after the database instance has been given to the new process This will be called in the new process. Called before the database instance is given to the new process Called to remove any song entries that do not have any fingerprints associated with them. Called when the database should be cleared of all data. Returns all fingerprints in the database. Returns the number of fingerprints in the database. Returns the amount of songs in the database. Return a song by its identifier sid: Song identifier Returns all fully fingerprinted songs in the database. Inserts a single fingerprint into the database. hash: Part of a sha1 hash, in hexadecimal format sid: Song identifier this fingerprint is off offset: The offset this hash is from Insert a multitude of fingerprints. sid: Song identifier the fingerprints belong to hashes: A sequence of tuples in the format (hash, offset) - hash: Part of a sha1 hash, in hexadecimal format - offset: Offset this hash was created from/at. Inserts a song name into the database, returns the new identifier of the song. song_name: The name of the song. Returns all matching fingerprint entries associated with the given hash as parameter. hash: Part of a sha1 hash, in hexadecimal format Searches the database for pairs of (hash, offset) values. hashes: A sequence of tuples in the format (hash, offset) - hash: Part of a sha1 hash, in hexadecimal format - offset: Offset this hash was created from/at. Returns a sequence of (sid, offset_difference) tuples. sid: Song identifier offset_difference: (offset - database_offset) Sets a specific song as having all fingerprints in the database. sid: Song identifier Called on creation or shortly afterwards. Name of your Database subclass, this is used in configuration to refer to your class Default to using the mysql database Lower all the input. Import our default database handler MySQL import dejavu.database_sql SQLite
1,953
en
0.836437
import pytest from unittest.mock import patch from collections import Counter from bigchaindb.core import Bigchain from bigchaindb.exceptions import CriticalDuplicateVote from bigchaindb.voting import Voting, INVALID, VALID, UNDECIDED ################################################################################ # Tests for checking vote eligibility def test_partition_eligible_votes(): class TestVoting(Voting): @classmethod def verify_vote_signature(cls, vote): if vote['node_pubkey'] == 'invalid sig': return False if vote['node_pubkey'] == 'value error': raise ValueError() return True voters = ['valid', 'invalid sig', 'value error', 'not in set'] votes = [{'node_pubkey': k} for k in voters] el, inel = TestVoting.partition_eligible_votes(votes, voters[:-1]) assert el == [votes[0]] assert inel == votes[1:] ################################################################################ # Test vote counting def test_count_votes(): class TestVoting(Voting): @classmethod def verify_vote_schema(cls, vote): return vote['node_pubkey'] != 'malformed' voters = (['says invalid', 'malformed'] + ['kosher' + str(i) for i in range(10)]) votes = [Bigchain(v).vote('block', 'a', True) for v in voters] votes[0]['vote']['is_block_valid'] = False # Incorrect previous block subtracts from n_valid and adds to n_invalid votes[-1]['vote']['previous_block'] = 'z' by_voter = dict(enumerate(votes)) assert TestVoting.count_votes(by_voter) == { 'counts': { 'n_valid': 9, # 9 kosher votes 'n_invalid': 3, # 1 invalid, 1 malformed, 1 rogue prev block }, 'malformed': [votes[1]], 'previous_block': 'a', 'other_previous_block': {'z': 1}, } def test_must_agree_prev_block(): class TestVoting(Voting): @classmethod def verify_vote_schema(cls, vote): return True voters = 'abcd' votes = [Bigchain(v).vote('block', 'a', True) for v in voters] votes[0]['vote']['previous_block'] = 'b' votes[1]['vote']['previous_block'] = 'c' by_voter = dict(enumerate(votes)) assert TestVoting.count_votes(by_voter) == { 'counts': { 'n_valid': 2, 'n_invalid': 2, }, 'previous_block': 'a', 'other_previous_block': {'b': 1, 'c': 1}, 'malformed': [], } ################################################################################ # Tests for vote decision making DECISION_TESTS = [ {'n_voters': 1, 'n_valid': 1, 'n_invalid': 1}, {'n_voters': 2, 'n_valid': 2, 'n_invalid': 1}, {'n_voters': 3, 'n_valid': 2, 'n_invalid': 2}, {'n_voters': 4, 'n_valid': 3, 'n_invalid': 2}, {'n_voters': 5, 'n_valid': 3, 'n_invalid': 3}, {'n_voters': 6, 'n_valid': 4, 'n_invalid': 3}, {'n_voters': 7, 'n_valid': 4, 'n_invalid': 4}, {'n_voters': 8, 'n_valid': 5, 'n_invalid': 4} ] @pytest.mark.parametrize('kwargs', DECISION_TESTS) def test_decide_votes_valid(kwargs): kwargs = kwargs.copy() kwargs['n_invalid'] = 0 assert Voting.decide_votes(**kwargs) == VALID kwargs['n_valid'] -= 1 assert Voting.decide_votes(**kwargs) == UNDECIDED @pytest.mark.parametrize('kwargs', DECISION_TESTS) def test_decide_votes_invalid(kwargs): kwargs = kwargs.copy() kwargs['n_valid'] = 0 assert Voting.decide_votes(**kwargs) == INVALID kwargs['n_invalid'] -= 1 assert Voting.decide_votes(**kwargs) == UNDECIDED ################################################################################ # Actions - test state transitions @pytest.mark.parametrize('n_voters', range(8)) def test_vote_actions(n_voters): """* Legal transitions are UNDECIDED -> [VALID|INVALID] only * Block is never left UNDECIDED after voting * Accomodates rogues on previous block / invalid schema """ class TestVoting(Voting): @classmethod def verify_vote_schema(cls, vote): return type(vote['vote']['is_block_valid']) == bool @classmethod def verify_vote_signature(cls, vote): return True keyring = 'abcdefghijklmnopqrstuvwxyz'[:n_voters] block = {'id': 'block', 'block': {'voters': keyring}} state = UNDECIDED todo = [(state, [], [])] def branch(p, r): todo.append((state, votes, votes + [{ 'node_pubkey': keyring[len(votes)], 'vote': {'previous_block': p, 'is_block_valid': r} }])) while todo: prev_state, prev_votes, votes = todo.pop(0) results = Counter(v['vote']['is_block_valid'] for v in votes) prev_blocks = Counter(v['vote']['previous_block'] for v in votes) majority = n_voters // 2 + 1 honest = (len(votes) == majority and len(prev_blocks) == 1 and not results['lol'] and len(results) == 1) closed = len(votes) == n_voters # Test legal transition if votes: state = TestVoting.block_election(block, votes, keyring)['status'] assert prev_state in [state, UNDECIDED] # Test that decision has been reached if honest or closed: assert state != UNDECIDED or n_voters == 0 if closed: continue # Can accomodate more votes, add them to the todo list. # This vote is the good case branch('A', True) # This vote disagrees on previous block branch('B', True) # This vote says the block is invalid branch('A', False) # This vote is invalid branch('A', 'lol') ################################################################################ # Tests for vote signature def test_verify_vote_signature_passes(b): vote = b.vote('block', 'a', True) assert Voting.verify_vote_signature(vote) vote['signature'] = '' assert not Voting.verify_vote_signature(vote) ################################################################################ # Tests for vote schema def test_verify_vote_schema(b): vote = b.vote('b' * 64, 'a' * 64, True) assert Voting.verify_vote_schema(vote) vote = b.vote('b' * 64, 'a', True) assert not Voting.verify_vote_schema(vote) vote = b.vote('b', 'a' * 64, True) assert not Voting.verify_vote_schema(vote) ################################################################################ # block_election tests def test_block_election(b): class TestVoting(Voting): @classmethod def verify_vote_signature(cls, vote): return True @classmethod def verify_vote_schema(cls, vote): return True keyring = 'abc' block = {'id': 'xyz', 'block': {'voters': 'ab'}} votes = [{ 'node_pubkey': c, 'vote': {'is_block_valid': True, 'previous_block': 'a'} } for c in 'abc'] assert TestVoting.block_election(block, votes, keyring) == { 'status': VALID, 'block_id': 'xyz', 'counts': {'n_valid': 2, 'n_invalid': 0}, 'ineligible': [votes[-1]], 'malformed': [], 'previous_block': 'a', 'other_previous_block': {}, } @patch('bigchaindb.voting.Voting.verify_vote_signature', return_value=True) def test_duplicate_vote_throws_critical_error(b): keyring = 'abc' block = {'id': 'xyz', 'block': {'voters': 'ab'}} votes = [{ 'node_pubkey': c, 'vote': {'is_block_valid': True, 'previous_block': 'a'} } for c in 'aabc'] with pytest.raises(CriticalDuplicateVote): Voting.block_election(block, votes, keyring)
tests/test_voting.py
7,709
* Legal transitions are UNDECIDED -> [VALID|INVALID] only * Block is never left UNDECIDED after voting * Accomodates rogues on previous block / invalid schema Tests for checking vote eligibility Test vote counting Incorrect previous block subtracts from n_valid and adds to n_invalid 9 kosher votes 1 invalid, 1 malformed, 1 rogue prev block Tests for vote decision making Actions - test state transitions Test legal transition Test that decision has been reached Can accomodate more votes, add them to the todo list. This vote is the good case This vote disagrees on previous block This vote says the block is invalid This vote is invalid Tests for vote signature Tests for vote schema block_election tests
709
en
0.888163
#!/usr/bin/env python # ref: Kaiming He, Xiangyu Zhang, Shaoqing Ren, Jian Sun"Deep Residual Learning for Image Recognition" # https://arxiv.org/pdf/1512.03385v1.pdf # ResNetConfig={ "16":[ "16", "small", 1, 1, 1, 1], "18":[ "18", "small", 2, 2, 2, 2], "34":[ "34", "small", 3, 4, 6, 3], "50":[ "50", "large", 3, 4, 6, 3], "101":["101", "large", 3, 4, 23, 3], "152":["152", "large", 3, 8, 36, 3] } def genDataLayer(train_val, number): layer_str = '''name: "Resnet{number}" layer {{ name: "data" type: "Data" top: "data" top: "label" data_param {{ source: "examples/imagenet/ilsvrc12_train_lmdb" backend: LMDB batch_size: 32 }} transform_param {{ crop_size: 224 mean_file: "data/ilsvrc12/imagenet_mean.binaryproto" mirror: true }} include: {{ phase: TRAIN }} }} layer {{ name: "data" type: "Data" top: "data" top: "label" data_param {{ source: "examples/imagenet/ilsvrc12_val_lmdb" backend: LMDB batch_size: 32 }} transform_param {{ mean_file: "data/ilsvrc12/imagenet_mean.binaryproto" crop_size: 224 mirror: false }} include: {{ phase: TEST }} }}'''.format(number=number) train_val += layer_str return train_val, "data" def genConvLayer(train_val, name, bottom, kernel_size, num_output, stride, pad, bias_term=False,filler="msra"): layer_str = ''' layer {{ name: "{name}" type: "Convolution" bottom: "{bottom}" top: "{top}" convolution_param {{ num_output: {num_output} kernel_size: {kernel_size} stride: {stride} pad: {pad} weight_filler {{ type: "{weight_filler_type}" std: 0.010 }}'''.format(name=name, top=name, bottom=bottom, kernel_size=kernel_size, num_output=num_output, pad=pad, stride=stride, weight_filler_type=filler) if bias_term: layer_str = layer_str + \ ''' bias_filler { type: "constant" value: 0 } } }''' else : layer_str = layer_str + \ ''' bias_term: false } }''' train_val += layer_str return train_val, name def genBNLayer(train_val, name, bottom, top=None): top = name if top is None else top layer_str = ''' layer {{ name: "{name}" type: "BatchNorm" bottom: "{bottom}" top: "{top}" batch_norm_param {{ moving_average_fraction: 0.9 eps: 0.0001 scale_bias: true }} }}'''.format(name=name, top=top, bottom=bottom) train_val += layer_str return train_val, top # def genScaleLayer(train_val, name, bottom): # layer_str = ''' # layer {{ # name: "{name}" # type: "Scale" # top: "{top}" # bottom: "{bottom}" # scale_param {{ # bias_term: true # TODO # }} # }}'''.format(name=name, top=bottom, bottom=bottom) # train_val += layer_str # return train_val, bottom def genActivationLayer(train_val, name, bottom, type="ReLU"): layer_str = ''' layer {{ name: "{name}" type: "{type}" bottom: "{bottom}" top: "{top}" }}'''.format(name=name, top=bottom, bottom=bottom, type=type) train_val += layer_str return train_val, bottom def genConvBnLayer(train_val, name, bottom, kernel_size, num_output, stride, pad, filler="msra"): train_val, last_top = genConvLayer(train_val=train_val, name=name, bottom=bottom, kernel_size=kernel_size, num_output=num_output, stride=stride, pad=pad, bias_term=False,filler=filler) train_val, last_top = genBNLayer(train_val=train_val, name="{name}_bn".format(name=name), bottom=last_top) return train_val, last_top def genConvBnReluLayer(train_val, name, bottom, kernel_size, num_output, stride, pad, filler="msra", activation_type="ReLU"): train_val, last_top = genConvBnLayer(train_val=train_val, name=name, bottom=bottom, kernel_size=kernel_size, num_output=num_output, stride=stride, pad=pad, filler=filler) train_val, last_top = genActivationLayer(train_val=train_val, name="{name}_relu".format(name=name), bottom=last_top, type=activation_type) return train_val, last_top def genBnReluLayer(train_val, name, bottom, activation_type="ReLU"): train_val, last_top = genBNLayer(train_val=train_val, name="{name}bn".format(name=name), bottom=bottom, top="{name}bn".format(name=name)) train_val, last_top = genActivationLayer(train_val=train_val, name="{name}relu".format(name=name), bottom=last_top, type=activation_type) return train_val, last_top def genPoolLayer(train_val, name, bottom, kernel_size, stride, pool_type): layer_str = ''' layer {{ name: "{name}" type: "Pooling" bottom: "{bottom}" top: "{top}" pooling_param {{ pool: {pool_type} kernel_size: {kernel_size} stride: {stride} }} }}'''.format(name=name, top=name, bottom=bottom, pool_type=pool_type, kernel_size=kernel_size, stride=stride) train_val += layer_str return train_val, name def genFCLayer(train_val, name, bottom, num_output, filler="gaussian"): layer_str = ''' layer {{ name: "{name}" type: "InnerProduct" bottom: "{bottom}" top: "{top}" inner_product_param {{ num_output: {num_output} weight_filler {{ type: "{weight_filler_type}" std: 0.01 }} bias_filler {{ type: "constant" value: 0 }} }} }}'''.format(name=name, top=name, bottom=bottom, num_output=num_output, weight_filler_type=filler) train_val += layer_str return train_val, name def genEltwiseLayer(train_val, name, bottom_1, bottom_2, operation="SUM"): layer_str = ''' layer {{ name: "{name}" type: "Eltwise" bottom: "{bottom_1}" bottom: "{bottom_2}" top: "{top}" eltwise_param {{ operation: {operation} }} }}'''.format(name=name, top=name, bottom_1=bottom_1, bottom_2=bottom_2, operation=operation) train_val += layer_str return train_val, name def genSoftmaxLossLayer(train_val, name, bottom_1, bottom_2="label"): layer_str = ''' layer {{ name: "{name}" type: "SoftmaxWithLoss" bottom: "{bottom_1}" bottom: "{bottom_2}" top: "{top}" }}'''.format(name=name, top=name, bottom_1=bottom_1, bottom_2=bottom_2) train_val += layer_str return train_val, name def genAccuracyLayer(train_val, name, bottom_1, bottom_2="label", k=1): layer_str=''' layer {{ type: "Accuracy" name: "{name}" bottom: "{bottom_1}" bottom: "{bottom_2}" top: "{top}" accuracy_param {{ top_k: {k} }} include {{ phase: TEST }} }}'''.format(name=name, top=name, bottom_1=bottom_1, bottom_2=bottom_2, k=k) train_val += layer_str return train_val, name def addComment(train_val, comment): train_val += "\n#\n# {comment}\n#".format(comment=comment) return train_val def digit_to_char(digit): return chr(ord('A') + digit) def str_base(number, base): if number < 0: return '-' + str_base(-number, base) (d, m) = divmod(number, base) if d > 0: return str_base(d, base) + digit_to_char(m) return (digit_to_char(m).lower()) def genRes2(train_val, last_top, small, i, fix_dim): # prefix="res2.{i}_".format(i=str_base(i-1, 26)) prefix = "res2.{i}.".format(i=str(i)) branch_str="" res_last_top=last_top branch_last_top=last_top if small: branch_str, branch_last_top = genConvBnReluLayer(train_val=branch_str, name='{}conv1'.format(prefix), bottom=branch_last_top, kernel_size=3, num_output=64, stride=1, pad=1) branch_str, branch_last_top = genConvBnLayer(train_val=branch_str, name='{}conv2'.format(prefix), bottom=branch_last_top, kernel_size=3, num_output=64, stride=1, pad=1) else: branch_str, branch_last_top = genConvBnReluLayer(train_val=branch_str, name='{}conv1'.format(prefix), bottom=branch_last_top, kernel_size=1, num_output=64, stride=1, pad=0) branch_str, branch_last_top = genConvBnReluLayer(train_val=branch_str, name='{}conv2'.format(prefix), bottom=branch_last_top, kernel_size=3, num_output=64, stride=1, pad=1) branch_str, branch_last_top = genConvBnLayer(train_val=branch_str, name='{}conv3'.format(prefix), bottom=branch_last_top, kernel_size=1, num_output=256, stride=1, pad=0) if small==False: branch_str, res_last_top = genConvBnLayer(train_val=branch_str, name='{}skipConv'.format(prefix), bottom=res_last_top, kernel_size=1, num_output=64 if small else 256, stride=1, pad=0) branch_str, last_top = genEltwiseLayer(train_val=branch_str, name='{}eltwise'.format(prefix), bottom_1=branch_last_top, bottom_2=res_last_top, operation="SUM") branch_str, last_top = genActivationLayer(train_val=branch_str, name="{}relu".format(prefix), bottom=last_top) train_val += branch_str return train_val, last_top def genRes3(train_val, last_top, small, i, fix_dim): # prefix="res3{i}_".format(i=str_base(i-1, 26)) prefix="res3.{i}.".format(i=str(i)) branch_str="" res_last_top=last_top branch_last_top=last_top if small: branch_str, branch_last_top = genConvBnReluLayer(train_val=branch_str, name='{}conv1'.format(prefix), bottom=branch_last_top, kernel_size=3, num_output=128, stride=2 if i==1 else 1, pad=1) branch_str, branch_last_top = genConvBnLayer(train_val=branch_str, name='{}conv2'.format(prefix), bottom=branch_last_top, kernel_size=3, num_output=128, stride=1, pad=1) else: branch_str, branch_last_top = genConvBnReluLayer(train_val=branch_str, name='{}conv1'.format(prefix), bottom=branch_last_top, kernel_size=1, num_output=128, stride=2 if i==1 else 1, pad=0) branch_str, branch_last_top = genConvBnReluLayer(train_val=branch_str, name='{}conv2'.format(prefix), bottom=branch_last_top, kernel_size=3, num_output=128, stride=1, pad=1) branch_str, branch_last_top = genConvBnLayer(train_val=branch_str, name='{}conv3'.format(prefix), bottom=branch_last_top, kernel_size=1, num_output=512, stride=1, pad=0) if fix_dim: branch_str, res_last_top = genConvBnLayer(train_val=branch_str, name='{}skipConv'.format(prefix), bottom=res_last_top, kernel_size=1, num_output=128 if small else 512, stride=2, pad=0) branch_str, last_top = genEltwiseLayer(train_val=branch_str, name='{}eltwise'.format(prefix), bottom_1=branch_last_top, bottom_2=res_last_top, operation="SUM") branch_str, last_top = genActivationLayer(train_val=branch_str, name="{}relu".format(prefix), bottom=last_top) train_val += branch_str return train_val, last_top def genRes4(train_val, last_top, small, i, fix_dim): # prefix="res4{i}_".format(i=str_base(i-1, 26)) prefix="res4.{i}.".format(i=str(i)) branch_str="" res_last_top=last_top branch_last_top=last_top if small: branch_str, branch_last_top = genConvBnReluLayer(train_val=branch_str, name='{}conv1'.format(prefix), bottom=branch_last_top, kernel_size=3, num_output=256, stride=2 if i==1 else 1, pad=1) branch_str, branch_last_top = genConvBnLayer(train_val=branch_str, name='{}conv2'.format(prefix), bottom=branch_last_top, kernel_size=3, num_output=256, stride=1, pad=1) else: branch_str, branch_last_top = genConvBnReluLayer(train_val=branch_str, name='{}conv1'.format(prefix), bottom=branch_last_top, kernel_size=1, num_output=256, stride=2 if i==1 else 1, pad=0) branch_str, branch_last_top = genConvBnReluLayer(train_val=branch_str, name='{}conv2'.format(prefix), bottom=branch_last_top, kernel_size=3, num_output=256, stride=1, pad=1) branch_str, branch_last_top = genConvBnLayer(train_val=branch_str, name='{}conv3'.format(prefix), bottom=branch_last_top, kernel_size=1, num_output=1024, stride=1, pad=0) if fix_dim: branch_str, res_last_top = genConvBnLayer(train_val=branch_str, name='{}skipConv'.format(prefix), bottom=res_last_top, kernel_size=1, num_output=256 if small else 1024, stride=2, pad=0) branch_str, last_top = genEltwiseLayer(train_val=branch_str, name='{}eltwise'.format(prefix), bottom_1=branch_last_top, bottom_2=res_last_top, operation="SUM") branch_str, last_top = genActivationLayer(train_val=branch_str, name="{}relu".format(prefix), bottom=last_top) train_val += branch_str return train_val, last_top def genRes5(train_val, last_top, small, i, fix_dim): # prefix="res5{i}_".format(i=str_base(i-1, 26)) prefix="res5.{i}.".format(i=str(i)) branch_str="" res_last_top=last_top branch_last_top=last_top if small: branch_str, branch_last_top = genConvBnReluLayer(train_val=branch_str, name='{}conv1'.format(prefix), bottom=branch_last_top, kernel_size=3, num_output=512, stride=2 if i==1 else 1, pad=1) branch_str, branch_last_top = genConvBnLayer(train_val=branch_str, name='{}conv2'.format(prefix), bottom=branch_last_top, kernel_size=3, num_output=512, stride=1, pad=1) else: branch_str, branch_last_top = genConvBnReluLayer(train_val=branch_str, name='{}conv1'.format(prefix), bottom=branch_last_top, kernel_size=1, num_output=512, stride=2 if i==1 else 1, pad=0) branch_str, branch_last_top = genConvBnReluLayer(train_val=branch_str, name='{}conv2'.format(prefix), bottom=branch_last_top, kernel_size=3, num_output=512, stride=1, pad=1) branch_str, branch_last_top = genConvBnLayer(train_val=branch_str, name='{}conv3'.format(prefix), bottom=branch_last_top, kernel_size=1, num_output=2048, stride=1, pad=0) if fix_dim: branch_str, res_last_top = genConvBnLayer(train_val=branch_str, name='{}skipConv'.format(prefix), bottom=res_last_top, kernel_size=1, num_output=512 if small else 2048, stride=2, pad=0) branch_str, last_top = genEltwiseLayer(train_val=branch_str, name='{}eltwise'.format(prefix), bottom_1=branch_last_top, bottom_2=res_last_top, operation="SUM") branch_str, last_top = genActivationLayer(train_val=branch_str, name="{}relu".format(prefix), bottom=last_top) train_val += branch_str return train_val, last_top def genTrainVal(network): train_val = "" train_val, last_top = genDataLayer(train_val=train_val, number=network[0]) train_val = addComment(train_val=train_val, comment="Res1") train_val, last_top = genConvBnReluLayer(train_val=train_val, name="conv1", bottom="data", kernel_size=7, num_output=64, stride=2, pad=3) train_val, last_top = genPoolLayer(train_val=train_val, name="pool1", bottom=last_top, kernel_size=3, stride=2, pool_type="MAX") train_val = addComment(train_val=train_val, comment="ResBlock2") for i in xrange(1, network[2]+1): train_val, last_top = genRes2(train_val=train_val, last_top=last_top, small=network[1] is "small", i=i, fix_dim=False) train_val = addComment(train_val=train_val, comment="ResBlock3") for i in xrange(1, network[3]+1): train_val, last_top = genRes3(train_val=train_val, last_top=last_top, small=network[1] is "small", i=i, fix_dim=i==1) train_val = addComment(train_val=train_val, comment="ResBlock4") for i in xrange(1, network[4]+1): train_val, last_top = genRes4(train_val=train_val, last_top=last_top, small=network[1] is "small", i=i, fix_dim=i==1) train_val = addComment(train_val=train_val, comment="ResBlock5") for i in xrange(1, network[5]+1): train_val, last_top = genRes5(train_val=train_val, last_top=last_top, small=network[1] is "small", i=i, fix_dim=i==1) train_val, last_top = genPoolLayer(train_val=train_val, name="pool2", bottom=last_top, kernel_size=7, stride=1, pool_type="AVE") train_val, last_top = genFCLayer (train_val=train_val, name="fc", bottom=last_top, num_output=1000, filler='msra') fc_top = last_top train_val, last_top = genSoftmaxLossLayer(train_val=train_val, name="loss", bottom_1=fc_top) train_val, last_top = genAccuracyLayer(train_val=train_val, name="accuracy/top-1", bottom_1=fc_top, k=1) train_val, last_top = genAccuracyLayer(train_val=train_val, name="accuracy/top-5", bottom_1=fc_top, k=5) return train_val def main(): for net in ResNetConfig.keys(): network_str = genTrainVal(ResNetConfig[net]) # with open("./models/train_val_{}.prototxt".format(net), 'w') as fp: # fp.write(network_str) fp = open("./models/train_val_{}.prototxt".format(net), 'w') fp.write(network_str) if __name__ == '__main__': main()
models/resnet18/ResNet_Generator.py
16,416
!/usr/bin/env python ref: Kaiming He, Xiangyu Zhang, Shaoqing Ren, Jian Sun"Deep Residual Learning for Image Recognition" https://arxiv.org/pdf/1512.03385v1.pdf def genScaleLayer(train_val, name, bottom): layer_str = ''' layer {{ name: "{name}" type: "Scale" top: "{top}" bottom: "{bottom}" scale_param {{ bias_term: true TODO }} }}'''.format(name=name, top=bottom, bottom=bottom) train_val += layer_str return train_val, bottom prefix="res2.{i}_".format(i=str_base(i-1, 26)) prefix="res3{i}_".format(i=str_base(i-1, 26)) prefix="res4{i}_".format(i=str_base(i-1, 26)) prefix="res5{i}_".format(i=str_base(i-1, 26)) with open("./models/train_val_{}.prototxt".format(net), 'w') as fp: fp.write(network_str)
765
en
0.351827
import gym import rlkit.torch.pytorch_util as ptu from rlkit.data_management.obs_dict_replay_buffer import ObsDictRelabelingBuffer from rlkit.exploration_strategies.base import \ PolicyWrappedWithExplorationStrategy from rlkit.exploration_strategies.gaussian_and_epislon import \ GaussianAndEpislonStrategy from rlkit.launchers.launcher_util import setup_logger from rlkit.samplers.data_collector import GoalConditionedPathCollector from rlkit.torch.her.her import HERTrainer from rlkit.torch.networks import ConcatMlp, TanhMlpPolicy # from rlkit.torch.td3.td3 import TD3 from rlkit.demos.td3_bc import TD3BCTrainer from rlkit.torch.torch_rl_algorithm import TorchBatchRLAlgorithm # from multiworld.envs.mujoco.sawyer_xyz.sawyer_push_multiobj_subset import SawyerMultiobjectEnv # from multiworld.envs.mujoco.sawyer_xyz.sawyer_reach import SawyerReachXYZEnv from multiworld.core.image_env import ImageEnv from multiworld.envs.real_world.sawyer.sawyer_reaching import SawyerReachXYZEnv # from sawyer_control.envs.sawyer_reaching import SawyerReachXYZEnv from rlkit.launchers.arglauncher import run_variants import rlkit.misc.hyperparameter as hyp # from rlkit.launchers.experiments.ashvin.rfeatures.rfeatures_trainer import TimePredictionTrainer from rlkit.launchers.experiments.ashvin.rfeatures.rfeatures_rl import encoder_wrapped_td3bc_experiment if __name__ == "__main__": variant = dict( env_class=SawyerReachXYZEnv, env_kwargs=dict( action_mode="position", max_speed = 0.05, camera="sawyer_head" ), # algo_kwargs=dict( # num_epochs=3000, # max_path_length=20, # batch_size=128, # num_eval_steps_per_epoch=1000, # num_expl_steps_per_train_loop=1000, # num_trains_per_train_loop=1000, # min_num_steps_before_training=1000, # ), algo_kwargs=dict( num_epochs=500, max_path_length=100, batch_size=128, num_eval_steps_per_epoch=500, num_expl_steps_per_train_loop=500, num_trains_per_train_loop=500, min_num_steps_before_training=0, ), model_kwargs=dict( decoder_distribution='gaussian_identity_variance', input_channels=3, imsize=224, architecture=dict( hidden_sizes=[200, 200], ), delta_features=True, pretrained_features=False, ), trainer_kwargs=dict( discount=0.99, demo_path="/home/lerrel/ros_ws/src/railrl-private/demo_v4_processed.npy", add_demo_latents=False, # already done bc_num_pretrain_steps=1000, rl_weight=0.0, bc_weight=1.0, weight_decay=0.001, ), replay_buffer_kwargs=dict( max_size=100000, fraction_goals_rollout_goals=1.0, fraction_goals_env_goals=0.0, ), qf_kwargs=dict( hidden_sizes=[400, 300], ), policy_kwargs=dict( hidden_sizes=[32, 32], ), save_video=True, dump_video_kwargs=dict( save_period=1, # imsize=(3, 500, 300), ), desired_trajectory="demo_v4.npy", snapshot_mode="all", ) search_space = { 'seedid': range(1), } sweeper = hyp.DeterministicHyperparameterSweeper( search_space, default_parameters=variant, ) variants = [] for variant in sweeper.iterate_hyperparameters(): variants.append(variant) run_variants(encoder_wrapped_td3bc_experiment, variants, run_id=1)
experiments/ashvin/rfeatures/sawyer/door/bc3.py
3,715
from rlkit.torch.td3.td3 import TD3 from multiworld.envs.mujoco.sawyer_xyz.sawyer_push_multiobj_subset import SawyerMultiobjectEnv from multiworld.envs.mujoco.sawyer_xyz.sawyer_reach import SawyerReachXYZEnv from sawyer_control.envs.sawyer_reaching import SawyerReachXYZEnv from rlkit.launchers.experiments.ashvin.rfeatures.rfeatures_trainer import TimePredictionTrainer algo_kwargs=dict( num_epochs=3000, max_path_length=20, batch_size=128, num_eval_steps_per_epoch=1000, num_expl_steps_per_train_loop=1000, num_trains_per_train_loop=1000, min_num_steps_before_training=1000, ), already done imsize=(3, 500, 300),
642
en
0.498585
import os import platform import re import sys from contextlib import suppress from pathlib import Path from loguru import logger from sc2 import wsl BASEDIR = { "Windows": "C:/Program Files (x86)/StarCraft II", "WSL1": "/mnt/c/Program Files (x86)/StarCraft II", "WSL2": "/mnt/c/Program Files (x86)/StarCraft II", "Darwin": "/Applications/StarCraft II", "Linux": "~/StarCraftII", "WineLinux": "~/.wine/drive_c/Program Files (x86)/StarCraft II", } USERPATH = { "Windows": "Documents\\StarCraft II\\ExecuteInfo.txt", "WSL1": "Documents/StarCraft II/ExecuteInfo.txt", "WSL2": "Documents/StarCraft II/ExecuteInfo.txt", "Darwin": "Library/Application Support/Blizzard/StarCraft II/ExecuteInfo.txt", "Linux": None, "WineLinux": None, } BINPATH = { "Windows": "SC2_x64.exe", "WSL1": "SC2_x64.exe", "WSL2": "SC2_x64.exe", "Darwin": "SC2.app/Contents/MacOS/SC2", "Linux": "SC2_x64", "WineLinux": "SC2_x64.exe", } CWD = { "Windows": "Support64", "WSL1": "Support64", "WSL2": "Support64", "Darwin": None, "Linux": None, "WineLinux": "Support64", } def platform_detect(): pf = os.environ.get("SC2PF", platform.system()) if pf == "Linux": return wsl.detect() or pf return pf PF = platform_detect() def get_home(): """Get home directory of user, using Windows home directory for WSL.""" if PF in {"WSL1", "WSL2"}: return wsl.get_wsl_home() or Path.home().expanduser() return Path.home().expanduser() def get_user_sc2_install(): """Attempts to find a user's SC2 install if their OS has ExecuteInfo.txt""" if USERPATH[PF]: einfo = str(get_home() / Path(USERPATH[PF])) if os.path.isfile(einfo): with open(einfo) as f: content = f.read() if content: base = re.search(r" = (.*)Versions", content).group(1) if PF in {"WSL1", "WSL2"}: base = str(wsl.win_path_to_wsl_path(base)) if os.path.exists(base): return base return None def get_env(): # TODO: Linux env conf from: https://github.com/deepmind/pysc2/blob/master/pysc2/run_configs/platforms.py return None def get_runner_args(cwd): if "WINE" in os.environ: runner_file = Path(os.environ.get("WINE")) runner_file = runner_file if runner_file.is_file() else runner_file / "wine" """ TODO Is converting linux path really necessary? That would convert '/home/burny/Games/battlenet/drive_c/Program Files (x86)/StarCraft II/Support64' to 'Z:\\home\\burny\\Games\\battlenet\\drive_c\\Program Files (x86)\\StarCraft II\\Support64' """ return [runner_file, "start", "/d", cwd, "/unix"] return [] def latest_executeble(versions_dir, base_build=None): latest = None if base_build is not None: with suppress(ValueError): latest = ( int(base_build[4:]), max(p for p in versions_dir.iterdir() if p.is_dir() and p.name.startswith(str(base_build))), ) if base_build is None or latest is None: latest = max((int(p.name[4:]), p) for p in versions_dir.iterdir() if p.is_dir() and p.name.startswith("Base")) version, path = latest if version < 55958: logger.critical("Your SC2 binary is too old. Upgrade to 3.16.1 or newer.") sys.exit(1) return path / BINPATH[PF] class _MetaPaths(type): """"Lazily loads paths to allow importing the library even if SC2 isn't installed.""" # pylint: disable=C0203 def __setup(self): if PF not in BASEDIR: logger.critical(f"Unsupported platform '{PF}'") sys.exit(1) try: base = os.environ.get("SC2PATH") or get_user_sc2_install() or BASEDIR[PF] self.BASE = Path(base).expanduser() self.EXECUTABLE = latest_executeble(self.BASE / "Versions") self.CWD = self.BASE / CWD[PF] if CWD[PF] else None self.REPLAYS = self.BASE / "Replays" if (self.BASE / "maps").exists(): self.MAPS = self.BASE / "maps" else: self.MAPS = self.BASE / "Maps" except FileNotFoundError as e: logger.critical(f"SC2 installation not found: File '{e.filename}' does not exist.") sys.exit(1) # pylint: disable=C0203 def __getattr__(self, attr): # pylint: disable=E1120 self.__setup() return getattr(self, attr) class Paths(metaclass=_MetaPaths): """Paths for SC2 folders, lazily loaded using the above metaclass."""
sc2/paths.py
4,699
Paths for SC2 folders, lazily loaded using the above metaclass. "Lazily loads paths to allow importing the library even if SC2 isn't installed. Get home directory of user, using Windows home directory for WSL. Attempts to find a user's SC2 install if their OS has ExecuteInfo.txt TODO: Linux env conf from: https://github.com/deepmind/pysc2/blob/master/pysc2/run_configs/platforms.py pylint: disable=C0203 pylint: disable=C0203 pylint: disable=E1120
451
en
0.799239
# http://www.pythonchallenge.com/pc/def/peak.html import requests, pickle input_url = "http://www.pythonchallenge.com/pc/def/banner.p" obj = requests.get(input_url) text = obj.text banner = pickle.loads(text) final = [] for index, value in enumerate(banner): for j in value: final.append("".join(j[0] * j[1])) final.append('\n') print "".join(final)
5.py
372
http://www.pythonchallenge.com/pc/def/peak.html
47
en
0.414613
import argparse import os import os.path as osp import shutil import tempfile import json import pdb import numpy as np import pickle import pandas as pd import mmcv import torch import torch.distributed as dist from mmcv.parallel import MMDataParallel, MMDistributedDataParallel from mmcv.runner import get_dist_info, load_checkpoint from mmdet.apis import init_dist from mmdet.core import lvis_eval, results2json, wrap_fp16_model from mmdet.datasets import build_dataloader, build_dataset from mmdet.models import build_detector from mmdet.core import build_assigner from utils import filter_logits_by_gt TEMP_DATASET_SIZE = 5000 def single_gpu_test(model, data_loader, show=False, cfg=None, index=0, img_meta=None): model.eval() results = [] logits_list = [] dataset = data_loader.dataset prog_bar = mmcv.ProgressBar(len(dataset)) class_instances = pickle.load(open('train_instances_list.p', 'rb')) normalized_classes = np.zeros(1231) for i, c in enumerate(class_instances): if c: normalized_classes[i] = 1/np.sqrt(c) for i, data in enumerate(data_loader): # if i < TEMP_DATASET_SIZE*index: # continue if i >= TEMP_DATASET_SIZE*(index+1): # temporary condition for testing break with torch.no_grad(): bbox_results, det_bboxes, det_labels, scores = model(return_loss=False, rescale=not show, **data, img_id=i, norm_cls=normalized_classes) det_bboxes = det_bboxes.detach().cpu() det_labels = det_labels.detach().cpu() scores = scores.detach().cpu() # save original logits: # filename = data['img_meta'][0].data[0][0]['filename'].split('/')[-1] # get the file name, e.g: '000000397133.jpg' # with open(f'test_logits/logits_per_img/{filename}.p', 'wb') as outfile: # pickle.dump(scores, outfile) results.append(bbox_results) logits_list.append((det_bboxes, det_labels, scores)) if show: model.module.show_result(data, bbox_results) batch_size = data['img'][0].size(0) for _ in range(batch_size): prog_bar.update() return results, logits_list # return also class. logits and labels def multi_gpu_test(model, data_loader, tmpdir=None): model.eval() results = [] dataset = data_loader.dataset rank, world_size = get_dist_info() if rank == 0: prog_bar = mmcv.ProgressBar(len(dataset)) for i, data in enumerate(data_loader): with torch.no_grad(): result = model(return_loss=False, rescale=True, **data) results.append(result) if rank == 0: batch_size = data['img'][0].size(0) for _ in range(batch_size * world_size): prog_bar.update() # collect results from all ranks results = collect_results(results, len(dataset), tmpdir) return results def collect_results(result_part, size, tmpdir=None): rank, world_size = get_dist_info() # create a tmp dir if it is not specified if tmpdir is None: MAX_LEN = 512 # 32 is whitespace dir_tensor = torch.full((MAX_LEN, ), 32, dtype=torch.uint8, device='cuda') if rank == 0: tmpdir = tempfile.mkdtemp() tmpdir = torch.tensor( bytearray(tmpdir.encode()), dtype=torch.uint8, device='cuda') dir_tensor[:len(tmpdir)] = tmpdir dist.broadcast(dir_tensor, 0) tmpdir = dir_tensor.cpu().numpy().tobytes().decode().rstrip() else: mmcv.mkdir_or_exist(tmpdir) # dump the part result to the dir mmcv.dump(result_part, osp.join(tmpdir, 'part_{}.pkl'.format(rank))) dist.barrier() # collect all parts if rank != 0: return None else: # load results of all parts from tmp dir part_list = [] for i in range(world_size): part_file = osp.join(tmpdir, 'part_{}.pkl'.format(i)) part_list.append(mmcv.load(part_file)) # sort the results ordered_results = [] for res in zip(*part_list): ordered_results.extend(list(res)) # the dataloader may pad some samples ordered_results = ordered_results[:size] # remove tmp dir shutil.rmtree(tmpdir) return ordered_results def parse_args(): parser = argparse.ArgumentParser(description='MMDet test detector') parser.add_argument('config', help='test config file path') parser.add_argument('checkpoint', help='checkpoint file') parser.add_argument('--out', help='output result file') parser.add_argument( '--json_out', help='output result file name without extension', type=str) parser.add_argument( '--eval', type=str, nargs='+', choices=['proposal', 'proposal_fast', 'bbox', 'segm', 'keypoints'], help='eval types') parser.add_argument('--show', action='store_true', help='show results') parser.add_argument('--tmpdir', help='tmp dir for writing some results') parser.add_argument( '--launcher', choices=['none', 'pytorch', 'slurm', 'mpi'], default='none', help='job launcher') parser.add_argument('--local_rank', type=int, default=0) parser.add_argument('--tau', type=float, default=0.0) parser.add_argument('--data_index', type=int, default=0) args = parser.parse_args() if 'LOCAL_RANK' not in os.environ: os.environ['LOCAL_RANK'] = str(args.local_rank) return args def reweight_cls(model, tauuu): if tauuu == 0: return model model_dict = model.state_dict() def pnorm(weights, tau): normB = torch.norm(weights, 2, 1) ws = weights.clone() for i in range(0, weights.shape[0]): ws[i] = ws[i] / torch.pow(normB[i], tau) return ws reweight_set = ['bbox_head.fc_cls.weight'] tau = tauuu for k in reweight_set: weight = model_dict[k] # ([1231, 1024]) weight = pnorm(weight, tau) model_dict[k].copy_(weight) print('Reweight param {:<30} with tau={}'.format(k, tau)) return model def logits_process(logits): """ Get the logits as a tuple of softmax logits ,bounding boxes and labels. Output: to matrices: logits_mat in size (dataset, 300, 1231) - top 300 logits for each image. bboxes_mat in size (dataset, 300, 4) - top 300 bboxes for each image. labels_mat in size (dataset, 300, 1) - corresponding labels. 300 for each image. """ # all_bboxes_logits = [] # for image in logits: # image_bboxes_logits = [] # for i, bbox in enumerate(image[0]): # bboxes_logits_dict = dict() # image[0] = tensor including 300 bboxes # index = int(bbox[5].item()) # bbox[6] specifies the relevant line in the logits matrix # logits_vector = image[1][index] # bboxes_logits_dict['bbox'] = bbox[:4] # bboxes_logits_dict['score'] = bbox[4] # bboxes_logits_dict['logits'] = logits_vector # image_bboxes_logits.append(bboxes_logits_dict) # all_bboxes_logits.append(image_bboxes_logits) # for idx in range(len(dataset)): # img_id = dataset.img_ids[idx] logits_mat = np.zeros((TEMP_DATASET_SIZE, 300, 1231)) bboxes_mat = np.zeros((TEMP_DATASET_SIZE, 300, 4)) labels_mat = np.zeros((TEMP_DATASET_SIZE, 300)) proposal_num = np.zeros((TEMP_DATASET_SIZE, 300, 1)) for i, image in enumerate(logits): for j, bbox in enumerate(image[0]): # image[0] = tensor including 300 bboxes # bboxes_logits_dict = dict() index = int(bbox[5].item()) # bbox[5] specifies the relevant line in the logits matrix logits_vector = image[2][index] # image[2] includes the scores # bbox_arr = np.array(bbox[:4]) bboxes_mat[i][j][:] = bbox[:4] logits_mat[i][j] = np.array(logits_vector) # added this to compute proposal numbers proposal_num[i][j] = bbox[-1] labels_mat[i] = image[1] # image[1] includes the labels return bboxes_mat, labels_mat, logits_mat, proposal_num def main(): args = parse_args() os.environ["CUDA_VISIBLE_DEVICES"] = str(args.data_index % 2) assert args.out or args.show or args.json_out, \ ('Please specify at least one operation (save or show the results) ' 'with the argument "--out" or "--show" or "--json_out"') if args.out is not None and not args.out.endswith(('.pkl', '.pickle')): raise ValueError('The output file must be a pkl file.') if args.json_out is not None and args.json_out.endswith('.json'): args.json_out = args.json_out[:-5] cfg = mmcv.Config.fromfile(args.config) # set cudnn_benchmark if cfg.get('cudnn_benchmark', False): torch.backends.cudnn.benchmark = True cfg.model.pretrained = None cfg.data.test.test_mode = True # init distributed env first, since logger depends on the dist info. if args.launcher == 'none': distributed = False else: distributed = True init_dist(args.launcher, **cfg.dist_params) # build the dataloader # TODO: support multiple images per gpu (only minor changes are needed) dataset = build_dataset(cfg.data.test) # original - test | changed to test_with_train_data data_loader = build_dataloader( dataset, imgs_per_gpu=1, workers_per_gpu=0, # cfg.data.workers_per_gpu dist=distributed, shuffle=False) # save gt boxes and labels for learning nms # for i, data in enumerate(data_loader): # img_id = dataset.img_infos[i]['id'] # gt = dataset.get_ann_info(i) # gt_boxes = gt['bboxes'] # gt_labels = gt['labels'] # filename = f'test_logits/learning_nms_data/{i}/gt_boxes.p' # file name for new directory # os.makedirs(os.path.dirname(filename), exist_ok=True) # with open(f'test_logits/learning_nms_data/{i}/gt_boxes.p', 'wb') as outfile: # possible to include img_id # pickle.dump(gt_boxes, outfile) # with open(f'test_logits/learning_nms_data/{i}/gt_labels.p', 'wb') as outfile: # pickle.dump(gt_boxes, outfile) # # # filename = dataset.img_infos[i]['filename'] # # with open(f'test_gt/{filename}.p', 'wb') as outfile: # # pickle.dump(gt_labels, outfile) # save gt instances per class # instances_list = np.zeros(1231) # for i, data in enumerate(data_loader): # original script in test_lvis_tnorm.py # gt = dataset.get_ann_info(i) # print(i) # for label in gt['labels']: # instances_list[label] += 1 # with open('train_instances_list.p', 'wb') as outfile: # pickle.dump(instances_list, outfile) # build the model and load checkpoint model = build_detector(cfg.model, train_cfg=None, test_cfg=cfg.test_cfg) fp16_cfg = cfg.get('fp16', None) if fp16_cfg is not None: wrap_fp16_model(model) checkpoint = load_checkpoint(model, args.checkpoint, map_location='cpu') # old versions did not save class info in checkpoints, this walkaround is # for backward compatibility if 'CLASSES' in checkpoint['meta']: model.CLASSES = checkpoint['meta']['CLASSES'] else: model.CLASSES = dataset.CLASSES model = reweight_cls(model, args.tau) if not distributed: model = MMDataParallel(model, device_ids=[0]) outputs, logits = single_gpu_test(model, data_loader, args.show, cfg, args.data_index) else: model = MMDistributedDataParallel(model.cuda()) outputs = multi_gpu_test(model, data_loader, args.tmpdir) # save outputs as csv: # pd.DataFrame(outputs).to_csv("original_outputs_full.csv") # preprocess logits and save them on json file # otp = np.asarray(outputs) # temp # df = pd.DataFrame(otp) # df.to_csv('otp.csv', index=False) bboxes_mat, labels_mat, logits_mat, proposal_num = logits_process(logits) # save labels, boxes and logits # with open('test_logits/dragon_test_bboxes_mat.p', 'wb') as outfile: # pickle.dump(bboxes_mat, outfile) # with open('test_logits/dragon_labels_mat.p', 'wb') as outfile: # pickle.dump(labels_mat, outfile) # with open('logits_mat1.p', 'wb') as outfile: # pickle.dump(logits_mat[:1000], outfile) # with open('logits_mat2.p', 'wb') as outfile: # pickle.dump(logits_mat[1000:2000], outfile) # with open('logits_mat3.p', 'wb') as outfile: # pickle.dump(logits_mat[2000:3000], outfile) # with open('logits_mat4.p', 'wb') as outfile: # pickle.dump(logits_mat[3000:4000], outfile) # with open('logits_mat5.p', 'wb') as outfile: # pickle.dump(logits_mat[4000:], outfile) # filter detections by iou with gt (for dragon training) gt_list = [] results_per_image = [] for i, data in enumerate(data_loader): # original script in test_lvis_tnorm.py # if i < TEMP_DATASET_SIZE*args.data_index: # continue if i >= TEMP_DATASET_SIZE: # temporary condition for testing break print(i) img_id = dataset.img_infos[i]['id'] gt = dataset.get_ann_info(i) gt_dict = dict() gt_dict['id'] = img_id gt_dict['bboxes'] = gt['bboxes'] gt_dict['labels'] = gt['labels'] gt_list.append(gt_dict) # filter logits according to equivalent ground truth. # after filtering, for each image we get a list in length of classes and detections belongs to this class. results = filter_logits_by_gt(bboxes_mat[i], logits_mat[i], gt_list[i], proposal_num[i], i) results_per_image.append(results) with open(f'dragon_bboxes_logits_map24.p', 'wb') as outfile: pickle.dump(results_per_image, outfile) print('saved') # evaluation: rank, _ = get_dist_info() if args.out and rank == 0: print('\nwriting results to {}'.format(args.out)) mmcv.dump(outputs, args.out) eval_types = args.eval if eval_types: print('Starting evaluate {}'.format(' and '.join(eval_types))) if eval_types == ['proposal_fast']: result_file = args.out lvis_eval(result_file, eval_types, dataset.lvis) else: if not isinstance(outputs[0], dict): result_files = results2json(dataset, outputs, args.out, args.data_index) lvis_eval(result_files, eval_types, dataset.lvis, max_dets=300) else: for name in outputs[0]: print('\nEvaluating {}'.format(name)) outputs_ = [out[name] for out in outputs] result_file = args.out + '.{}'.format(name) result_files = results2json(dataset, outputs_, result_file) lvis_eval(result_files, eval_types, dataset.lvis) # Save predictions in the COCO json format if args.json_out and rank == 0: if not isinstance(outputs[0], dict): results2json(dataset, outputs, args.json_out) else: for name in outputs[0]: outputs_ = [out[name] for out in outputs] result_file = args.json_out + '.{}'.format(name) results2json(dataset, outputs_, result_file) if __name__ == '__main__': main()
tools/test_lvis.py
15,707
Get the logits as a tuple of softmax logits ,bounding boxes and labels. Output: to matrices: logits_mat in size (dataset, 300, 1231) - top 300 logits for each image. bboxes_mat in size (dataset, 300, 4) - top 300 bboxes for each image. labels_mat in size (dataset, 300, 1) - corresponding labels. 300 for each image. if i < TEMP_DATASET_SIZE*index: continue temporary condition for testing save original logits: filename = data['img_meta'][0].data[0][0]['filename'].split('/')[-1] get the file name, e.g: '000000397133.jpg' with open(f'test_logits/logits_per_img/{filename}.p', 'wb') as outfile: pickle.dump(scores, outfile) return also class. logits and labels collect results from all ranks create a tmp dir if it is not specified 32 is whitespace dump the part result to the dir collect all parts load results of all parts from tmp dir sort the results the dataloader may pad some samples remove tmp dir ([1231, 1024]) all_bboxes_logits = [] for image in logits: image_bboxes_logits = [] for i, bbox in enumerate(image[0]): bboxes_logits_dict = dict() image[0] = tensor including 300 bboxes index = int(bbox[5].item()) bbox[6] specifies the relevant line in the logits matrix logits_vector = image[1][index] bboxes_logits_dict['bbox'] = bbox[:4] bboxes_logits_dict['score'] = bbox[4] bboxes_logits_dict['logits'] = logits_vector image_bboxes_logits.append(bboxes_logits_dict) all_bboxes_logits.append(image_bboxes_logits) for idx in range(len(dataset)): img_id = dataset.img_ids[idx] image[0] = tensor including 300 bboxes bboxes_logits_dict = dict() bbox[5] specifies the relevant line in the logits matrix image[2] includes the scores bbox_arr = np.array(bbox[:4]) added this to compute proposal numbers image[1] includes the labels set cudnn_benchmark init distributed env first, since logger depends on the dist info. build the dataloader TODO: support multiple images per gpu (only minor changes are needed) original - test | changed to test_with_train_data cfg.data.workers_per_gpu save gt boxes and labels for learning nms for i, data in enumerate(data_loader): img_id = dataset.img_infos[i]['id'] gt = dataset.get_ann_info(i) gt_boxes = gt['bboxes'] gt_labels = gt['labels'] filename = f'test_logits/learning_nms_data/{i}/gt_boxes.p' file name for new directory os.makedirs(os.path.dirname(filename), exist_ok=True) with open(f'test_logits/learning_nms_data/{i}/gt_boxes.p', 'wb') as outfile: possible to include img_id pickle.dump(gt_boxes, outfile) with open(f'test_logits/learning_nms_data/{i}/gt_labels.p', 'wb') as outfile: pickle.dump(gt_boxes, outfile) filename = dataset.img_infos[i]['filename'] with open(f'test_gt/{filename}.p', 'wb') as outfile: pickle.dump(gt_labels, outfile) save gt instances per class instances_list = np.zeros(1231) for i, data in enumerate(data_loader): original script in test_lvis_tnorm.py gt = dataset.get_ann_info(i) print(i) for label in gt['labels']: instances_list[label] += 1 with open('train_instances_list.p', 'wb') as outfile: pickle.dump(instances_list, outfile) build the model and load checkpoint old versions did not save class info in checkpoints, this walkaround is for backward compatibility save outputs as csv: pd.DataFrame(outputs).to_csv("original_outputs_full.csv") preprocess logits and save them on json file otp = np.asarray(outputs) temp df = pd.DataFrame(otp) df.to_csv('otp.csv', index=False) save labels, boxes and logits with open('test_logits/dragon_test_bboxes_mat.p', 'wb') as outfile: pickle.dump(bboxes_mat, outfile) with open('test_logits/dragon_labels_mat.p', 'wb') as outfile: pickle.dump(labels_mat, outfile) with open('logits_mat1.p', 'wb') as outfile: pickle.dump(logits_mat[:1000], outfile) with open('logits_mat2.p', 'wb') as outfile: pickle.dump(logits_mat[1000:2000], outfile) with open('logits_mat3.p', 'wb') as outfile: pickle.dump(logits_mat[2000:3000], outfile) with open('logits_mat4.p', 'wb') as outfile: pickle.dump(logits_mat[3000:4000], outfile) with open('logits_mat5.p', 'wb') as outfile: pickle.dump(logits_mat[4000:], outfile) filter detections by iou with gt (for dragon training) original script in test_lvis_tnorm.py if i < TEMP_DATASET_SIZE*args.data_index: continue temporary condition for testing filter logits according to equivalent ground truth. after filtering, for each image we get a list in length of classes and detections belongs to this class. evaluation: Save predictions in the COCO json format
4,643
en
0.57095
from __future__ import absolute_import from __future__ import print_function from typing import Any, Iterable from optparse import make_option import logging import sys from django.core.management.base import BaseCommand, CommandParser from zerver.lib import utils from zerver.models import UserMessage, get_user_profile_by_email from django.db import models class Command(BaseCommand): help = """Sets user message flags. Used internally by actions.py. Marks all Expects a comma-delimited list of user message ids via stdin, and an EOF to terminate.""" def add_arguments(self, parser): # type: (CommandParser) -> None parser.add_argument('-r', '--for-real', dest='for_real', action='store_true', default=False, help="Actually change message flags. Default is a dry run.") parser.add_argument('-f', '--flag', dest='flag', type=str, help="The flag to add of remove") parser.add_argument('-o', '--op', dest='op', type=str, help="The operation to do: 'add' or 'remove'") parser.add_argument('-u', '--until', dest='all_until', type=str, help="Mark all messages <= specific usermessage id") parser.add_argument('-m', '--email', dest='email', type=str, help="Email to set messages for") def handle(self, *args, **options): # type: (*Any, **Any) -> None if not options["flag"] or not options["op"] or not options["email"]: print("Please specify an operation, a flag and an email") exit(1) op = options['op'] flag = getattr(UserMessage.flags, options['flag']) all_until = options['all_until'] email = options['email'] user_profile = get_user_profile_by_email(email) if all_until: filt = models.Q(id__lte=all_until) else: filt = models.Q(message__id__in=[mid.strip() for mid in sys.stdin.read().split(',')]) mids = [m.id for m in UserMessage.objects.filter(filt, user_profile=user_profile).order_by('-id')] if options["for_real"]: sys.stdin.close() sys.stdout.close() sys.stderr.close() def do_update(batch): # type: (Iterable[int]) -> None msgs = UserMessage.objects.filter(id__in=batch) if op == 'add': msgs.update(flags=models.F('flags').bitor(flag)) elif op == 'remove': msgs.update(flags=models.F('flags').bitand(~flag)) if not options["for_real"]: logging.info("Updating %s by %s %s" % (mids, op, flag)) logging.info("Dry run completed. Run with --for-real to change message flags.") exit(1) utils.run_in_batches(mids, 400, do_update, sleep_time=3) exit(0)
zerver/management/commands/set_message_flags.py
3,224
type: (CommandParser) -> None type: (*Any, **Any) -> None type: (Iterable[int]) -> None
87
en
0.410488
# coding: utf-8 import errno import os import random import re from contextlib import contextmanager import h5py import numpy as np import time import yaml from datetime import datetime def write_yaml_file(yaml_dict, file_yaml): path_yaml = os.path.dirname(file_yaml) if not os.path.isdir(path_yaml): os.makedirs(path_yaml) with open(file_yaml, 'w') as stream: yaml.dump(yaml_dict, stream, default_flow_style=False) def make_sure_path_exists(path): try: os.makedirs(path) except OSError as exception: if exception.errno != errno.EEXIST: raise def find_file(path, reg): """ path: 要遍历的目录 reg: 符合条件的文件 """ FileLst = [] try: lst = os.walk(path) for root, dirs, files in lst: for name in files: try: m = re.match(reg, name) except Exception as e: continue if m: FileLst.append(os.path.join(root, name)) except Exception as e: print(str(e)) return sorted(FileLst) def path_replace_ymd(path, ymd): """ path:替换路径中的日期 ,path中%YYYY%MM%DD%JJJ 等关键字会被ymd日期实例 ymd: yyyymmdd (20180101) """ # 转成datetime类型 ymd = datetime.strptime(ymd, '%Y%m%d') yy = ymd.strftime('%Y') mm = ymd.strftime('%m') dd = ymd.strftime('%d') jj = ymd.strftime('%j') path = path.replace('%YYYY', yy) path = path.replace('%MM', mm) path = path.replace('%DD', dd) path = path.replace('%JJJ', jj) return path def is_none(*args): """ 判断传入的变量中是否有 None :param args: :return: """ has_none = False for arg in args: if arg is None: has_none = True return has_none def copy_attrs_h5py(pre_object, out_object): """ 复制 file、dataset 或者 group 的属性 :param pre_object: 被复制属性的 dataset 或者 group :param out_object: 复制属性的 dataset 或者 group :return: """ for akey in list(pre_object.attrs.keys()): out_object.attrs[akey] = pre_object.attrs[akey] def read_dataset_hdf5(file_path, set_name): """ 读取 hdf5 文件,返回一个 numpy 多维数组 :param file_path: (unicode)文件路径 :param set_name: (str or list)表的名字 :return: 如果传入的表名字是一个字符串,返回 numpy.ndarray 如果传入的表名字是一个列表,返回一个字典,key 是表名字, value 是 numpy.ndarry """ if isinstance(set_name, str): if os.path.isfile(file_path): file_h5py = h5py.File(file_path, 'r') data = file_h5py.get(set_name)[:] dataset = np.array(data) file_h5py.close() return dataset else: raise ValueError('value error: file_path') elif isinstance(set_name, list): datasets = {} if os.path.isfile(file_path): file_h5py = h5py.File(file_path, 'r') for name in set_name: data = file_h5py.get(name)[:] dataset = np.array(data) datasets[name] = dataset file_h5py.close() return datasets else: raise ValueError('value error: file_path') else: raise ValueError('value error: set_name') def attrs2dict(attrs): """ 将一个 HDF5 attr 类转为 Dict 类 :return: """ d = {} for k, v in list(attrs.items()): d[k] = v return d @contextmanager def progress_lock(max_wait_time=5): try: sleep_time = 0 lock = "progress.lock" while True: if os.path.isfile(lock): if sleep_time > max_wait_time: try: os.remove(lock) break except: continue else: random_number = random.random() * 0.1 sleep_time += random_number time.sleep(random_number) else: break with open(lock, "w"): pass yield finally: try: os.remove(lock) except: pass def write_txt(in_file, head, bodys, keylens=8): """ description: wangpeng add 20180615 (写入或更新txt) :in_file 写入文件位置 :head 文件头信息 :bodys 文件体 :keylens 更新文件使用的第一列关键字长度 """ allLines = [] DICT_D = {} FilePath = os.path.dirname(in_file) if not os.path.exists(FilePath): os.makedirs(FilePath) if os.path.isfile(in_file) and os.path.getsize(in_file) != 0: fp = open(in_file, 'r') fp.readline() Lines = fp.readlines() fp.close() # 使用字典特性,保证时间唯一,读取数据 for Line in Lines: DICT_D[Line[:keylens]] = Line[keylens:] # 添加或更改数据 for Line in bodys: DICT_D[Line[:keylens]] = Line[keylens:] # 按照时间排序 newLines = sorted( iter(DICT_D.items()), key=lambda d: d[0], reverse=False) for i in range(len(newLines)): allLines.append(str(newLines[i][0]) + str(newLines[i][1])) fp = open(in_file, 'w') fp.write(head) fp.writelines(allLines) fp.close() else: fp = open(in_file, 'w') fp.write(head) fp.writelines(bodys) fp.close() def str_format(string, values): """ 格式化字符串 :param string:(str) "DCC: %sat_sensor_Projection_%ymd(分辨率 %resolution 度)" :param values:(dict) {"sat_sensor": sat_sensor, "resolution": str(resolution), "ymd": ymd} :return: DCC: FY3D+MERSI_Projection_201712(分辨率 1 度) """ if not isinstance(string, str): return for k, v in values.items(): string = string.replace("%" + str(k), str(v)) return string def get_files_by_ymd(dir_path, time_start, time_end, ext=None, pattern_ymd=None): """ :param dir_path: 文件夹 :param time_start: 开始时间 :param time_end: 结束时间 :param ext: 后缀名, '.hdf5' :param pattern_ymd: 匹配时间的模式, 可以是 r".*(\d{8})_(\d{4})_" :return: list """ files_found = [] if pattern_ymd is not None: pattern = pattern_ymd else: pattern = r".*(\d{8})" for root, dirs, files in os.walk(dir_path): for file_name in files: if ext is not None: if '.' not in ext: ext = '.' + ext if os.path.splitext(file_name)[1].lower() != ext.lower(): continue re_result = re.match(pattern, file_name) if re_result is not None: time_file = ''.join(re_result.groups()) else: continue if int(time_start) <= int(time_file) <= int(time_end): files_found.append(os.path.join(root, file_name)) files_found.sort() return files_found class ReadOrbitCrossFile(object): """ test """ @staticmethod def read_cross_file(in_file, file_type): """ :param in_file: :param file_type: :return: """ data = { 'ymdhms1': None, 'ymdhms2': None, 'lon1': None, 'lat1': None, 'lon2': None, 'lat2': None, 'fix_name': None # 只有固定点才有 } if not os.path.isfile(in_file): print('***WARNING***File is not exist: {}'.format(in_file)) return data # with open(in_file, 'r') as fp: # lines_10 = fp.readlines()[0: 10] # # count = 0 # for line in lines_10: # print count, line.split() # count += 1 if file_type == 'leo_area': data_raw = np.loadtxt(in_file, skiprows=10, dtype={ 'names': ('d1', 'd2', 'd3', 'd4', 'd5', 'd6', 'd7'), 'formats': ('S8', 'S8', 'S8', 'f4', 'f4', 'f4', 'f4')}) if data_raw.size != 0: ymd = data_raw['d1'] hms1 = data_raw['d2'] hms2 = data_raw['d3'] ymdhms1 = list(map(ymdhms2date, ymd, hms1)) ymdhms2 = list(map(ymdhms2date, ymd, hms2)) data['ymdhms1'] = ymdhms1 data['ymdhms2'] = ymdhms2 data['lat1'] = data_raw['d4'] data['lon1'] = data_raw['d5'] data['lat2'] = data_raw['d6'] data['lon2'] = data_raw['d7'] elif file_type == 'leo_leo': data_raw = np.loadtxt(in_file, skiprows=10, dtype={ 'names': ('d1', 'd2', 'd3', 'd4', 'd5', 'd6', 'd7', 'd8', 'd9'), 'formats': ('S8', 'S8', 'f4', 'f4', 'S8', 'f4', 'f4', 'f4', 'f4')}) if data_raw.size != 0: ymd = data_raw['d1'] hms1 = data_raw['d2'] hms2 = data_raw['d5'] ymdhms1 = list(map(ymdhms2date, ymd, hms1)) ymdhms2 = list(map(ymdhms2date, ymd, hms2)) data['ymdhms1'] = ymdhms1 data['ymdhms2'] = ymdhms2 data['lat1'] = data_raw['d3'] data['lon1'] = data_raw['d4'] data['lat2'] = data_raw['d6'] data['lon2'] = data_raw['d7'] elif file_type == 'leo_fix': # 数据 data_raw = np.loadtxt(in_file, skiprows=10, dtype={ 'names': ('d1', 'd2', 'd3', 'd4', 'd5', 'd6', 'd7', 'd8',), 'formats': ('S8', 'S8', 'S8', 'f4', 'f4', 'f4', 'f4', 'f4')}) if data_raw.size != 0: ymd = data_raw['d1'] hms1 = data_raw['d2'] hms2 = data_raw['d2'] ymdhms1 = list(map(ymdhms2date, ymd, hms1)) ymdhms2 = list(map(ymdhms2date, ymd, hms2)) data['ymdhms1'] = ymdhms1 data['ymdhms2'] = ymdhms2 data['lat1'] = data_raw['d6'] data['lon1'] = data_raw['d7'] data['lat2'] = data_raw['d4'] data['lon2'] = data_raw['d5'] data['fix_name'] = data_raw['d3'] elif file_type == 'geo_leo': # 信息 data_raw = np.loadtxt(in_file, skiprows=10, dtype={ 'names': ('d1', 'd2', 'd3', 'd4', 'd5', 'd6', 'd7'), 'formats': ('S8', 'S8', 'S8', 'f4', 'f4', 'f4', 'f4')}) if data_raw.size != 0: ymd = data_raw['d1'] hms1 = data_raw['d2'] hms2 = data_raw['d3'] ymdhms1 = list(map(ymdhms2date, ymd, hms1)) ymdhms2 = list(map(ymdhms2date, ymd, hms2)) data['ymdhms1'] = ymdhms1 data['ymdhms2'] = ymdhms2 data['lat1'] = data_raw['d4'] data['lon1'] = data_raw['d5'] data['lat2'] = data_raw['d6'] data['lon2'] = data_raw['d7'] else: raise KeyError('Cant handle this file type: {}'.format(file_type)) return data def ymdhms2date(ymd, hms): """ ymd = 20180101 hms = 04:04:04 """ ymdhms = ymd + hms return datetime.strptime(ymdhms, '%Y%m%d%H:%M:%S') def CombineTimeList(TimeList): # 将时间段list中有重叠的时间段进行融合为新的时间段 newTimeList = [] # 默认排序,升序 TimeList.sort() # 标记有时间融合的时间 stime = TimeList[0][0] etime = TimeList[0][1] for i in range(1, len(TimeList), 1): if TimeList[i][1] <= etime: continue elif TimeList[i][0] <= etime <= TimeList[i][1]: etime = TimeList[i][1] elif TimeList[i][0] > etime: newTimeList.append([stime, etime]) stime = TimeList[i][0] etime = TimeList[i][1] newTimeList.append([stime, etime]) return newTimeList def get_files_by_date(dir_path, time_start=None, time_end=None, ext=None, pattern=None): """ :param dir_path: 文件夹 :param time_start: 开始时间 :param time_end: 结束时间 :param ext: 后缀名, '.hdf5' :param pattern: 匹配时间的模式 :return: list """ files_found = [] for root, dirs, files in os.walk(dir_path): for file_name in files: if ext is not None: if '.' not in ext: ext = '.' + ext if os.path.splitext(file_name)[1].lower() != ext.lower(): continue if pattern is not None: re_result = re.match(pattern, file_name) if re_result is None: continue if time_start is not None: time_file = ''.join(re_result.groups()) if not int(time_start) <= int(time_file) <= int(time_end): continue files_found.append(os.path.join(root, file_name)) files_found.sort() return files_found if __name__ == '__main__': pass path_out_map = str_format('/abc/%YYYY%MM%DD', { 'YYYY': '20180101', 'MM': '01', 'DD': '01', }) print(path_out_map) # path1 = "E:/projects/ocrs/cfg/global.cfg" # path2 = "E:/projects/ocrs/cfg/FY3B+MERSI.yaml" # c = Config(path1) # c = Config(path2) # print c.error # l = c.__dict__.keys() # l = sorted(l) # for k in l: # print k, ":", c.__dict__[k] # print k # ################# test ReadOrbitCrossFile ################ # LEO_AREA # leo_area_name = r'C:\Users\wangpeng\Desktop\tmp\cross\AQUA_australia_LEO_AREA_20171221.txt' # read_data = ReadOrbitCrossFile.read_cross_file(leo_area_name, 'leo_area') # LEO_LEO # leo_leo_name = r'C:\Users\wangpeng\Desktop\tmp\cross\FENGYUN-3D_NPP_LEO_LEO_20180901.txt' # read_data = ReadOrbitCrossFile.read_cross_file(leo_leo_name, 'leo_leo') # LEO_FIX # leo_fix_name = r'C:\Users\wangpeng\Desktop\tmp\cross\AQUA_FIX_LEO_FIX_20181101.txt' # read_data = ReadOrbitCrossFile.read_cross_file(leo_fix_name, 'leo_fix') # GEO_LEO # geo_leo_name = r'C:\Users\wangpeng\Desktop\tmp\cross\FENGYUN-2F_METOP-A_GEO_LEO20181101.txt' # read_data = ReadOrbitCrossFile.read_cross_file(geo_leo_name, 'geo_leo') # keys = read_data.keys() # keys.sort() # for data_name in keys: # print data_name, type(read_data[data_name]), read_data[data_name]
lib/pb_io.py
14,837
test 将一个 HDF5 attr 类转为 Dict 类 :return: 复制 file、dataset 或者 group 的属性 :param pre_object: 被复制属性的 dataset 或者 group :param out_object: 复制属性的 dataset 或者 group :return: path: 要遍历的目录 reg: 符合条件的文件 :param dir_path: 文件夹 :param time_start: 开始时间 :param time_end: 结束时间 :param ext: 后缀名, '.hdf5' :param pattern: 匹配时间的模式 :return: list :param dir_path: 文件夹 :param time_start: 开始时间 :param time_end: 结束时间 :param ext: 后缀名, '.hdf5' :param pattern_ymd: 匹配时间的模式, 可以是 r".*(\d{8})_(\d{4})_" :return: list 判断传入的变量中是否有 None :param args: :return: path:替换路径中的日期 ,path中%YYYY%MM%DD%JJJ 等关键字会被ymd日期实例 ymd: yyyymmdd (20180101) :param in_file: :param file_type: :return: 读取 hdf5 文件,返回一个 numpy 多维数组 :param file_path: (unicode)文件路径 :param set_name: (str or list)表的名字 :return: 如果传入的表名字是一个字符串,返回 numpy.ndarray 如果传入的表名字是一个列表,返回一个字典,key 是表名字, value 是 numpy.ndarry 格式化字符串 :param string:(str) "DCC: %sat_sensor_Projection_%ymd(分辨率 %resolution 度)" :param values:(dict) {"sat_sensor": sat_sensor, "resolution": str(resolution), "ymd": ymd} :return: DCC: FY3D+MERSI_Projection_201712(分辨率 1 度) description: wangpeng add 20180615 (写入或更新txt) :in_file 写入文件位置 :head 文件头信息 :bodys 文件体 :keylens 更新文件使用的第一列关键字长度 ymd = 20180101 hms = 04:04:04 coding: utf-8 转成datetime类型 使用字典特性,保证时间唯一,读取数据 添加或更改数据 按照时间排序 只有固定点才有 with open(in_file, 'r') as fp: lines_10 = fp.readlines()[0: 10] count = 0 for line in lines_10: print count, line.split() count += 1 数据 信息 将时间段list中有重叠的时间段进行融合为新的时间段 默认排序,升序 标记有时间融合的时间 path1 = "E:/projects/ocrs/cfg/global.cfg" path2 = "E:/projects/ocrs/cfg/FY3B+MERSI.yaml" c = Config(path1) c = Config(path2) print c.error l = c.__dict__.keys() l = sorted(l) for k in l: print k, ":", c.__dict__[k] print k test ReadOrbitCrossFile LEO_AREA leo_area_name = r'C:\Users\wangpeng\Desktop\tmp\cross\AQUA_australia_LEO_AREA_20171221.txt' read_data = ReadOrbitCrossFile.read_cross_file(leo_area_name, 'leo_area') LEO_LEO leo_leo_name = r'C:\Users\wangpeng\Desktop\tmp\cross\FENGYUN-3D_NPP_LEO_LEO_20180901.txt' read_data = ReadOrbitCrossFile.read_cross_file(leo_leo_name, 'leo_leo') LEO_FIX leo_fix_name = r'C:\Users\wangpeng\Desktop\tmp\cross\AQUA_FIX_LEO_FIX_20181101.txt' read_data = ReadOrbitCrossFile.read_cross_file(leo_fix_name, 'leo_fix') GEO_LEO geo_leo_name = r'C:\Users\wangpeng\Desktop\tmp\cross\FENGYUN-2F_METOP-A_GEO_LEO20181101.txt' read_data = ReadOrbitCrossFile.read_cross_file(geo_leo_name, 'geo_leo') keys = read_data.keys() keys.sort() for data_name in keys: print data_name, type(read_data[data_name]), read_data[data_name]
2,654
zh
0.342058
#!/usr/bin/env python3 # purpose: Mimics a simple telnet daemon login prompts and records output # starts a tcp listener on port and address with variables defined below # author: Raresteak # date: 6 October 2021 # version: 3 import datetime import socket HOST = '127.0.0.1' PORT = 2323 FILE = "stn-results.json" fh = open(FILE, "a") with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s: s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) s.bind((HOST, PORT)) s.listen() while True: conn, addr = s.accept() with conn: timeNow = datetime.datetime.now() conn.send(b'Warning: Telnet is not a secure protocol, and it is recommended to use Stelnet.\n\nLogin authentication\n\n\nUsername: ') username = "" while True: data = conn.recv(1024) if not data: break else: try: username = data.decode("utf-8").rstrip() except UnicodeDecodeError: username = "cancelledInput" conn.send(b'Password: ') password = "" while True: data = conn.recv(1024) if not data: break else: try: password = data.decode("utf-8").rstrip() except UnicodeDecodeError: password = "cancelledInput" conn.sendall(b'\b \b') break break output = str("{ \"time\": \"" + timeNow.strftime('%Y-%m-%dT%H:%M:%S') + "\", \"src.ip\": \"" + addr[0] + "\", \"username\": \"" + username + "\", \"password\": \"" + password + "\" }") print(output) fh.write(output + "\n")
simple-telnet-deception.py
2,061
!/usr/bin/env python3 purpose: Mimics a simple telnet daemon login prompts and records output starts a tcp listener on port and address with variables defined below author: Raresteak date: 6 October 2021 version: 3
214
en
0.617931
import unittest import filecmp import datetime from utils import in_tst_dir, in_tst_output_dir import xlwt as xlwt ezxf = xlwt.easyxf def write_xls(file_name, sheet_name, headings, data, heading_xf, data_xfs): book = xlwt.Workbook() sheet = book.add_sheet(sheet_name) rowx = 0 for colx, value in enumerate(headings): sheet.write(rowx, colx, value, heading_xf) sheet.set_panes_frozen(True) # frozen headings instead of split panes sheet.set_horz_split_pos(rowx+1) # in general, freeze after last heading row sheet.set_remove_splits(True) # if user does unfreeze, don't leave a split there for row in data: rowx += 1 for colx, value in enumerate(row): sheet.write(rowx, colx, value, data_xfs[colx]) book.save(file_name) EXAMPLE_XLS = 'xlwt_easyxf_simple_demo.xls' class TestUnicode0(unittest.TestCase): def create_example_xls(self, filename): mkd = datetime.date hdngs = ['Date', 'Stock Code', 'Quantity', 'Unit Price', 'Value', 'Message'] kinds = 'date text int price money text'.split() data = [ [mkd(2007, 7, 1), 'ABC', 1000, 1.234567, 1234.57, ''], [mkd(2007, 12, 31), 'XYZ', -100, 4.654321, -465.43, 'Goods returned'], ] + [ [mkd(2008, 6, 30), 'PQRCD', 100, 2.345678, 234.57, ''], ] * 100 heading_xf = ezxf('font: bold on; align: wrap on, vert centre, horiz center') kind_to_xf_map = { 'date': ezxf(num_format_str='yyyy-mm-dd'), 'int': ezxf(num_format_str='#,##0'), 'money': ezxf('font: italic on; pattern: pattern solid, fore-colour grey25', num_format_str='$#,##0.00'), 'price': ezxf(num_format_str='#0.000000'), 'text': ezxf(), } data_xfs = [kind_to_xf_map[k] for k in kinds] write_xls(filename, 'Demo', hdngs, data, heading_xf, data_xfs) def test_example_xls(self): self.create_example_xls(in_tst_output_dir(EXAMPLE_XLS)) self.assertTrue(filecmp.cmp(in_tst_dir(EXAMPLE_XLS), in_tst_output_dir(EXAMPLE_XLS), shallow=False))
desktop/core/ext-py/xlwt-1.3.0/tests/test_easyxf.py
2,253
frozen headings instead of split panes in general, freeze after last heading row if user does unfreeze, don't leave a split there
129
en
0.862805
#!c:\users\jerem\dev\ipp-core\venv\scripts\python.exe # See http://cens.ioc.ee/projects/f2py2e/ from __future__ import division, print_function import os import sys for mode in ["g3-numpy", "2e-numeric", "2e-numarray", "2e-numpy"]: try: i = sys.argv.index("--" + mode) del sys.argv[i] break except ValueError: pass os.environ["NO_SCIPY_IMPORT"] = "f2py" if mode == "g3-numpy": sys.stderr.write("G3 f2py support is not implemented, yet.\\n") sys.exit(1) elif mode == "2e-numeric": from f2py2e import main elif mode == "2e-numarray": sys.argv.append("-DNUMARRAY") from f2py2e import main elif mode == "2e-numpy": from numpy.f2py import main else: sys.stderr.write("Unknown mode: " + repr(mode) + "\\n") sys.exit(1) main()
venv/Scripts/f2py.py
793
!c:\users\jerem\dev\ipp-core\venv\scripts\python.exe See http://cens.ioc.ee/projects/f2py2e/
92
en
0.394205
import sys sys.path.append('..') from utilities import jamfconfig from utilities import apirequests from computergroups import computergroups import xml.etree.ElementTree as etree jss_api_base_url = jamfconfig.getJSS_API_URL() #print("JSS API Base URL: {}".format(jss_api_base_url)) def cleanupOutput(inputString): #print str(inputString) return inputString.replace(u"\u2018", "'").replace(u"\u2019", "'").replace(u"\u201c", "\"").replace(u"\u201d", "\"") def getAllPolicies(username, password): ''' List all policies in JSS to screen ''' #print(username) print "We're Refactored! Getting All JAMF Policies..." reqStr = jss_api_base_url + '/policies' r = apirequests.sendAPIRequest(reqStr, username, password, 'GET') if r == -1: return baseXml = r.read() responseXml = etree.fromstring(baseXml) for policy in responseXml.findall('policy'): policyName = policy.find('name').text policyID = policy.find('id').text print 'Policy ID: ' + policyID + ', ' + 'Policy Name: ' + policyName + '\n' def getPolicybyId(policyid, username, password): ''' Method to search for Policy ID by ID number and return General Policy Information, Scoping Information, and Package Configuration information - send results to Stdout ''' print 'Running refactored getpolicybyid ...' reqStr = jss_api_base_url + '/policies/id/' + policyid r = apirequests.sendAPIRequest(reqStr, username, password, 'GET') if r != -1: baseXml = r.read() responseXml = etree.fromstring(baseXml) general = responseXml.find('general') ## General Policy Information name = general.find('name').text policy_id = general.find('id').text enabled = general.find('enabled').text trigger = general.find('trigger').text frequency = general.find('frequency').text print '\nGENERAL POLICY INFORMATION: ' print 'Policy Name: ' + str(name) print 'Policy ID #: ' + str(policy_id) print 'Policy is Enabled: ' + str(enabled) print 'Policy Trigger: ' + str(trigger) print 'Policy Frequency: ' + str(frequency) ## Policy Scope Information scope = responseXml.find('scope') allcomputers = scope.find('all_computers').text groups = scope.find('computer_groups') comp_groups = [] computers = scope.find('computers') members = [] ## Add Header Row for output for info categories # headerRow = "Computer Name, JSS ID" # members += [ headerRow ] for computer in computers.findall('computer'): # compID = computer.find('id').text name = computer.find('name').text computerInfo = str(name) computerInfo = cleanupOutput(computerInfo) #print computerInfo.encode('ascii', 'ignore') members += [ computerInfo ] for g in groups.findall('computer_group'): group_name = g.find('name').text groupInfo = str(group_name) comp_groups += [ groupInfo ] print '\nPOLICY SCOPE INFORMATION:' print 'Scoped to All Computers: ' + str(allcomputers) print '\nCOMPUTER GROUPS IN SCOPE: ' print '\n'.join (sorted(comp_groups)) if members: print '\nADDITIONAL COMPUTERS IN SCOPE: ' print '\n'.join (sorted(members)) print '\nTotal Computers in Scope: ' + str(len(members)) ## Package Configuration Information pkgconfig = responseXml.find('package_configuration') packages = pkgconfig.find('packages') pkgheaderRow = "Package Name" pkglist = [] for pkg in packages.findall('package'): pkg_name = pkg.find('name').text pkg_action = pkg.find('action').text pkgInfo = str(pkg_name) + ', ' + str(pkg_action) pkgInfo = cleanupOutput(pkgInfo) pkglist += [ pkgInfo ] print '\nPACKAGE CONFIGURATION: ' print '\n'.join (sorted(pkglist)) else: print 'Failed to find policy with ID ' + policyid def listAllPolicies(username, password): ''' List all policies in JSS - for function use ''' reqStr = jss_api_base_url + '/policies' r = apirequests.sendAPIRequest(reqStr, username, password, 'GET') if r == -1: return baseXml = r.read() responseXml = etree.fromstring(baseXml) PoliciesList = [] for policy in responseXml.findall('policy'): policyName = policy.find('name').text policyID = policy.find('id').text PoliciesList.append({'name': policyName, 'id': policyID}) return PoliciesList def listAllPolicyIds(username, password): ''' List all policy IDs in JSS - for function use - returns a list of Policy ID #s ''' reqStr = jss_api_base_url + '/policies' r = apirequests.sendAPIRequest(reqStr, username, password, 'GET') if r == -1: return baseXml = r.read() responseXml = etree.fromstring(baseXml) PolicyIDList = [] for policy in responseXml.findall('policy'): policyID = policy.find('id').text PolicyIDList.append(policyID) return PolicyIDList def listPolicyStatusbyId(policyid, username, password): ''' Function to search for Policy ID by ID number and return status results for use in functions ''' reqStr = jss_api_base_url + '/policies/id/' + policyid + '/subset/General' r = apirequests.sendAPIRequest(reqStr, username, password, 'GET') if r != -1: baseXml = r.read() responseXml = etree.fromstring(baseXml) general = responseXml.find('general') status = general.find('enabled').text return status def listPolicyNamebyId(policyid, username, password): ''' Function to search for Policy ID by ID number and return name for use in functions ''' reqStr = jss_api_base_url + '/policies/id/' + policyid + '/subset/General' r = apirequests.sendAPIRequest(reqStr, username, password, 'GET') if r != -1: baseXml = r.read() responseXml = etree.fromstring(baseXml) general = responseXml.find('general') name = general.find('name').text return name def listPolicyScopebyId(policyid, username, password): ''' Function to search for Policy ID by ID number and return scope details as a dict for use in functions ''' reqStr = jss_api_base_url + '/policies/id/' + policyid + '/subset/Scope' r = apirequests.sendAPIRequest(reqStr, username, password, 'GET') scopeData = [] if r != -1: baseXml = r.read() responseXml = etree.fromstring(baseXml) scope = responseXml.find('scope') allcomputers = scope.find('all_computers').text groups = scope.find('computer_groups') comp_groups = [] comp_groupIDs = [] computers = scope.find('computers') members = [] scope_details = {} for comp in computers.findall('computer'): if comp.find('name').text: name = comp.find('name').text members.append(name) for g in groups.findall('computer_group'): if g.find('name').text: group_name = g.find('name').text groupID = computergroups.getComputerGroupId(group_name, username, password) comp_groups.append(group_name) comp_groupIDs.append(groupID) scope_details = { "Policy ID: ": policyid, "All computers?: ": allcomputers, "Computer groups: ": comp_groups, "Computer group IDs: ": comp_groupIDs, "Specific computers: ": members } return scope_details def listPolicyPackagesbyId(policyid, username, password): ''' Function to search for Policy ID by ID number and return package details as a list for use in functions ''' reqStr = jss_api_base_url + '/policies/id/' + policyid + '/subset/Packages' r = apirequests.sendAPIRequest(reqStr, username, password, 'GET') pkglist = [] if r != -1: baseXml = r.read() responseXml = etree.fromstring(baseXml) pkgconfig = responseXml.find('package_configuration') packages = pkgconfig.find('packages') if packages.findall('package'): for pkg in packages.findall('package'): pkg_name = pkg.find('name').text pkglist.append(pkg_name) return pkglist def listPolicybyId(policyid, username, password): ''' Method to search for Policy ID by ID number and return General Policy Information, Scoping Information, and Package Configuration information - for use in functions ''' reqStr = jss_api_base_url + '/policies/id/' + policyid r = apirequests.sendAPIRequest(reqStr, username, password, 'GET') if r != -1: baseXml = r.read() responseXml = etree.fromstring(baseXml) policyDict = {} ## General Policy Information general = responseXml.find('general') polname = general.find('name').text policy_id = general.find('id').text enabled = general.find('enabled').text trigger = general.find('trigger').text frequency = general.find('frequency').text ## Policy Scope Information scope = responseXml.find('scope') allcomputers = scope.find('all_computers').text groups = scope.find('computer_groups') comp_groups = [] computers = scope.find('computers') members = [] for computer in computers.findall('computer'): name = computer.find('name').text computerInfo = name.encode("utf-8") # computerInfo = cleanupOutput(computerInfo) # members.append(name) members += [ computerInfo ] for g in groups.findall('computer_group'): group_name = g.find('name').text groupInfo = str(group_name) comp_groups += [ groupInfo ] ## Package Configuration Information pkgconfig = responseXml.find('package_configuration') packages = pkgconfig.find('packages') pkglist = [] for pkg in packages.findall('package'): pkg_name = pkg.find('name').text pkg_action = pkg.find('action').text pkglist.append({"Package Name": pkg_name, "Package Action": pkg_action}) ## Add policy details to policyDict and return policyDict = { "Policy Name": polname, "Policy ID": policy_id, "Policy Enabled": enabled, "Policy Trigger": trigger, "Policy Frequency": frequency, "All Computers in Scope": allcomputers, "Scoped Computers": members, "Scoped Computer Groups": comp_groups, "Package Configuration": pkglist } return policyDict else: print 'Failed to find policy with ID ' + policyid
policies/policies_core.py
9,694
print("JSS API Base URL: {}".format(jss_api_base_url))print str(inputString)print(username) General Policy Information Policy Scope Information Add Header Row for output for info categories headerRow = "Computer Name, JSS ID" members += [ headerRow ] compID = computer.find('id').textprint computerInfo.encode('ascii', 'ignore') Package Configuration Information General Policy Information Policy Scope Information computerInfo = cleanupOutput(computerInfo) members.append(name) Package Configuration Information Add policy details to policyDict and return
556
en
0.407345
from __future__ import annotations from typing import List, Tuple, Optional from network_simulator.BloodType import BloodType from network_simulator.compatibility_markers import OrganType path_structure = Optional[List[Optional[int]]] shortest_path_structure = Tuple[path_structure, float] class Organ: """ A class representing a given organ which is available for transplant. Each organ has a name, a unique ID, lifetime (a maximum out of body duration), type matching, and a location. """ organ_count = 0 def __init__(self, organ_type: OrganType, blood_type: BloodType, location: int, organ_list: 'OrganList' = None) -> None: # type: ignore Organ.organ_count = Organ.organ_count + 1 self.organ_id: int = Organ.organ_count self.organ_type: OrganType = organ_type self.blood_type: BloodType = blood_type self.viability: float = Organ.get_viability(self.organ_type) self.origin_location: int = location self.current_location: int = location self.path: path_structure = [location] if organ_list: organ_list.add_organ(self) def move_organ(self, new_location: int, cost: float, shortest_path: shortest_path_structure) -> None: """ This function allows an organ's attributes to be altered to represent it's transportation across the network. This is intended to be used with Dijkstra.shortest_path (this will be the source of the cost parameter) :param int new_location: node id representing the destination location :param cost: weight/cost associated with then most efficient path :param list shortest_path: transit path taken when moving organ """ if self.viability < cost: print('ERROR: organ no longer viable!') return path, weight = shortest_path self.path = path self.current_location = new_location self.viability -= cost @staticmethod def get_viability(organ_type: OrganType) -> float: """ Gets viability rating for each organ individually Viability is represented by hours an organ can be out of body * 10 :param int organ_type: constant corresponding to an organ type :return: int viability rating (used in __init__()) """ viability = { OrganType.Heart.value: 60, OrganType.Kidney.value: 300, OrganType.Liver.value: 120, OrganType.Lungs.value: 60, OrganType.Pancreas.value: 120, OrganType.Intestines.value: 80} return viability[organ_type.value] def __str__(self) -> str: """ Builds an easily readable string representing an organ :return: str """ return f'Organ:\n' \ f'\tOrgan ID: {"{:05d}".format(self.organ_id)}\n' \ f'\tOrgan type: {OrganType(self.organ_type).name}\n' \ f'\tBlood type: {self.blood_type}\n' \ f'\tViability: {self.viability}\n' \ f'\tOrigin location: {self.origin_location}\n' \ f'\tCurrent location: {self.current_location}\n' \ f'\tTransit path: {self.path}\n'
network_simulator/Organ.py
3,283
A class representing a given organ which is available for transplant. Each organ has a name, a unique ID, lifetime (a maximum out of body duration), type matching, and a location. Builds an easily readable string representing an organ :return: str Gets viability rating for each organ individually Viability is represented by hours an organ can be out of body * 10 :param int organ_type: constant corresponding to an organ type :return: int viability rating (used in __init__()) This function allows an organ's attributes to be altered to represent it's transportation across the network. This is intended to be used with Dijkstra.shortest_path (this will be the source of the cost parameter) :param int new_location: node id representing the destination location :param cost: weight/cost associated with then most efficient path :param list shortest_path: transit path taken when moving organ type: ignore
913
en
0.858828
""" Example how setup service """ from typing import Optional, Any from orchestrator_service import Message from orchestrator_service.service import CommandHandlerPostStrategy from orchestrator_service.service import CommandHandlerStrategy from orchestrator_service.service import ServiceBlock, ServiceBuilder, Service class FirstCommand(CommandHandlerStrategy): """ Example first command """ target_command = 'first_command' def process(self, msg: Message) -> Message: print('process 1') # set to global scope self.set_to_swap_scope('val', 1) return msg class SecondCommand(CommandHandlerStrategy): """ Example second command """ target_command = 'second_command' def process(self, msg: Message) -> Message: print('process 2') # get value from scope print(self.get_from_swap_scope('val')) return msg class ThirdCommand(CommandHandlerStrategy): """ Example third command """ target_command = 'third_command' def process(self, msg: Message) -> Message: # example call another command in current command = self.get_service_command(SecondCommand.target_command, # type: CommandHandlerStrategy is_process=True) msg = command.process(msg) return msg class PPFirstCommand(CommandHandlerPostStrategy): """ Example first post process handler """ def post_process(self, msg: Message, additional_data: Optional[Any] = None) -> None: print('post_process 1') class PPSecondCommand(CommandHandlerPostStrategy): """ Example second post process handler """ def post_process(self, msg: Message, additional_data: Optional[Any] = None) -> None: print('post_process 2') # example builder example_service_builder = ServiceBuilder( ServiceBlock(process=FirstCommand(), post_process=PPFirstCommand()), ServiceBlock(process=SecondCommand()), ServiceBlock(process=ThirdCommand), default_post_process=PPSecondCommand()) class MyService(Service): """ Custom service second use case """ _default_command = 'first_command' service_commands = example_service_builder if __name__ == '__main__': service = Service(example_service_builder, default_command='first_command') my_service = MyService() msg_1 = Message(body={'val': 1}, header={'command': 'first_command'}) msg_2 = Message(body={'val': 1}, header={'command': 'second_command'}) msg_3 = Message(body={'val': 1}, header={'command': 'third_command'}) msg_4 = Message(body={'val': 1}, header={}) # running correct with there is both a handler # and a post handler and a command is specified service.handle(msg_1) # >>> process 1 # >>> post_process 1 # running command with default PP handlers service.handle(msg_2) # >>> process 2 # >>> post_process 2 service.handle(msg_3) # >>> process 3 # >>> post_process 2 # running default command service.handle(msg_4) # >>> process 1 # >>> post_process 1 # Run overridden service my_service.handle(msg_1) # >>> process 1 # >>> post_process 1 my_service.handle(msg_2) # >>> process 2 # >>> post_process 2 my_service.handle(msg_3) # >>> process 3 # >>> post_process 2 my_service.handle(msg_4) # >>> process 1 # >>> post_process 1
examples/example_service.py
3,623
Example first command Custom service second use case Example first post process handler Example second post process handler Example second command Example third command Example how setup service set to global scope get value from scope example call another command in current type: CommandHandlerStrategy example builder running correct with there is both a handler and a post handler and a command is specified >>> process 1 >>> post_process 1 running command with default PP handlers >>> process 2 >>> post_process 2 >>> process 3 >>> post_process 2 running default command >>> process 1 >>> post_process 1 Run overridden service >>> process 1 >>> post_process 1 >>> process 2 >>> post_process 2 >>> process 3 >>> post_process 2 >>> process 1 >>> post_process 1
765
en
0.766457
""" Expose top-level symbols that are safe for import * """ from __future__ import print_function, division, absolute_import import re from . import testing, decorators from ._version import get_versions from . import special, types, config # Re-export typeof from .special import * from .pycc.decorators import export, exportmany # Version __version__ = get_versions()['version'] # Re-export all type names from .types import * # Re export decorators jit = decorators.jit autojit = decorators.autojit njit = decorators.njit # Re export vectorize decorators from .npyufunc import vectorize, guvectorize # Re export from_dtype from .numpy_support import from_dtype # Re-export test entrypoint test = testing.test # Try initialize cuda from . import cuda __all__ = """ jit autojit njit vectorize guvectorize export exportmany cuda from_dtype """.split() + types.__all__ + special.__all__ def _sentry_llvm_version(): """ Make sure we meet min llvmpy version """ import warnings import llvm min_version = (0, 12, 6) # Only look at the the major, minor and bugfix version numbers. # Ignore other stuffs regex = re.compile(r'(\d+)\.(\d+).(\d+)') m = regex.match(llvm.__version__) if m: ver = tuple(map(int, m.groups())) if ver < min_version: msg = ("Numba requires at least version %d.%d.%d of llvmpy.\n" "Installed version is %s.\n" "Please update llvmpy." % (min_version + (llvm.__version__,))) raise ImportError(msg) else: # Not matching? warnings.warn("llvmpy version format not recognized!") _sentry_llvm_version()
numba/__init__.py
1,689
Make sure we meet min llvmpy version Expose top-level symbols that are safe for import * Re-export typeof Version Re-export all type names Re export decorators Re export vectorize decorators Re export from_dtype Re-export test entrypoint Try initialize cuda Only look at the the major, minor and bugfix version numbers. Ignore other stuffs Not matching?
355
en
0.832402
from string import ascii_lowercase import numpy as np import pandas as pd import plotly.graph_objects as go from plotly.subplots import make_subplots from plotly.colors import hex_to_rgb from src.timeit import timeit @timeit def plotOverTime(FSCPData: pd.DataFrame, FSCPDataSteel: pd.DataFrame, config: dict): # select which lines to plot based on function argument FSCPsCols, plotFSCP, plotLines = __selectPlotFSCPs(FSCPData, config['showFSCPs'], config['refFuelTop'], config['n_samples']) FSCPsCols, plotFSCPSteel, plotLinesSteel = __selectPlotFSCPs(FSCPDataSteel, config['showFSCPs'], config['refFuelBottom'], config['n_samples']) # produce figure fig = __produceFigure(FSCPsCols, plotFSCP, plotFSCPSteel, plotLines, plotLinesSteel, config) # styling figure __styling(fig, config) return {'fig3': fig} def __selectPlotFSCPs(FSCPData: pd.DataFrame, showFSCPs: dict, refFuel: str, n_samples: int): FSCPsCols = [None] * len(showFSCPs) listOfFSCPs = pd.DataFrame(columns=(FSCPData.keys().tolist() + ['plotIndex'])) for index, args in enumerate(showFSCPs): cols, fuel_x, fuel_y = args if fuel_x == 'ref': fuel_x = refFuel addFSCP = FSCPData.query(f"fuel_x=='{fuel_x}' & fuel_y=='{fuel_y}' & year_x==year_y").reset_index(drop=True) if fuel_x == refFuel: addFSCP.loc[:, 'fuel_x'] = 'ref' addFSCP.insert(1, 'plotIndex', len(addFSCP) * [index]) FSCPsCols[index] = cols listOfFSCPs = pd.concat([listOfFSCPs, addFSCP], ignore_index=True) # year_x == year_y, so we only need one of them from now on listOfFSCPs['year'] = listOfFSCPs['year_x'] # return FSCPs for scatter plots plotFSCP = listOfFSCPs[['plotIndex', 'fuel_x', 'fuel_y', 'year', 'fscp', 'fscp_uu', 'fscp_ul']] # return costs and GHGIs for line plots plotLines = listOfFSCPs[['plotIndex', 'fuel_x', 'fuel_y', 'year', 'cost_x', 'cost_y', 'ghgi_x', 'ghgi_y']] # interpolation of plotLines t = np.linspace(plotLines['year'].min(), plotLines['year'].max(), n_samples) dtypes = {'year': float, 'cost_x': float, 'cost_y': float, 'ghgi_x': float, 'ghgi_y': float} allEntries = [] for index in plotLines['plotIndex'].unique(): samples = plotLines.query(f"plotIndex=={index}").reset_index(drop=True).astype(dtypes) fuel_x = samples.fuel_x.iloc[0] fuel_y = samples.fuel_y.iloc[0] new = dict( plotIndex=n_samples * [int(index)], fuel_x=n_samples * [fuel_x], fuel_y=n_samples * [fuel_y], year=t, ) tmp = pd.DataFrame(new, columns=plotLines.keys()) tmp.index = np.arange(len(samples), len(tmp) + len(samples)) tmp = tmp.merge(samples, how='outer').sort_values(by=['year']).astype(dtypes) allEntries.append(tmp.interpolate()) plotLinesInterpolated = pd.concat(allEntries, ignore_index=True) plotLinesInterpolated['fscp'] = (plotLinesInterpolated['cost_x'] - plotLinesInterpolated['cost_y']) / ( plotLinesInterpolated['ghgi_y'] - plotLinesInterpolated['ghgi_x']) return FSCPsCols, plotFSCP, plotLinesInterpolated def __produceFigure(FSCPsCols: list, plotFSCP: pd.DataFrame, plotFSCPSteel: pd.DataFrame, plotLines: pd.DataFrame, plotLinesSteel: pd.DataFrame, config: dict): # plot fig = make_subplots( rows=2, cols=2, subplot_titles=ascii_lowercase, shared_yaxes=True, horizontal_spacing=0.025, vertical_spacing=0.1, ) # add FSCP traces for heating traces = __addFSCPTraces(plotFSCP, plotLines, len(FSCPsCols), config['refFuelTop'], config) for id, trace in traces: for j, col in enumerate(FSCPsCols[id]): if j: trace.showlegend = False fig.add_trace(trace, row=1, col=col) # add FSCP traces for steel traces = __addFSCPTraces(plotFSCPSteel, plotLinesSteel, len(FSCPsCols), config['refFuelBottom'], config) for id, trace in traces: for j, col in enumerate(FSCPsCols[id]): trace.showlegend = False fig.add_trace(trace, row=2, col=col) # compute and plot carbon price tracjetory cpTrajData = __computeCPTraj(config['co2price_traj']['years'], config['co2price_traj']['values'], config['n_samples']) traces = __addCPTraces(cpTrajData, config) for trace in traces: for i, j in [(0, 0), (0, 1), (1, 0), (1, 1)]: if i or j: trace.showlegend = False fig.add_trace(trace, row=i + 1, col=j + 1) # zero y line for i, j in [(0, 0), (0, 1), (1, 0), (1, 1)]: fig.add_hline(0.0, line_width=config['global']['lw_thin'], line_color='black', row=i + 1, col=j + 1) # add text annotations explaining figure content annotationStyling = dict(xanchor='center', yanchor='middle', showarrow=False, bordercolor='black', borderwidth=2, borderpad=3, bgcolor='white') for i in range(2): axisNumb = str(i+1) if i else '' blueTech = config['annotationLabels']['blueTechs'][i] fig.add_annotation( x=0.50, xref=f"x{axisNumb} domain", y=1.15, yref=f"y{axisNumb} domain", text=f"Blue H<sub>2</sub> from {blueTech}", **annotationStyling ) for i in range(2): axisNumb = str(i+2) if i else '' application = config['annotationLabels']['applications'][i] fig.add_annotation( x=-0.17, xref=f"x{axisNumb} domain", y=0.5, yref=f"y{axisNumb} domain", text=f"{application}", textangle=-90, **annotationStyling ) # add circles on intersects __addAnnotations(fig, cpTrajData, plotLines, plotLinesSteel, config) # add arrows in 2025 __addAnnotationArrows(fig, config) # add legend for annotations __addAnnotationsLegend(fig, config) # update axes titles and ranges fig.update_layout( xaxis=dict( title=config['labels']['time'], range=[config['plotting']['t_min'], config['plotting']['t_max']] ), xaxis2=dict( title=config['labels']['time'], range=[config['plotting']['t_min'], config['plotting']['t_max']] ), xaxis3=dict( title=config['labels']['time'], range=[config['plotting']['t_min'], config['plotting']['t_max']] ), xaxis4=dict( title=config['labels']['time'], range=[config['plotting']['t_min'], config['plotting']['t_max']] ), yaxis=dict( title=config['labels']['fscp'], range=[config['plotting']['fscp_min'], config['plotting']['fscp_max']] ), yaxis3=dict( title=config['labels']['fscp_steel'], range=[config['plotting']['fscp_min'], config['plotting']['fscp_max']] ), margin_l=180.0, margin_b=520.0, ) return fig def __addAnnotations(fig: go.Figure, cpTrajData: pd.DataFrame, plotLines: pd.DataFrame, plotLinesSteel: pd.DataFrame, config: dict): traceArgs = [ dict(row=1, col=1, lines=plotLines, anno=config['annotationFuels']['left']), dict(row=1, col=2, lines=plotLines, anno=config['annotationFuels']['right']), dict(row=2, col=1, lines=plotLinesSteel, anno=config['annotationFuels']['left']), dict(row=2, col=2, lines=plotLinesSteel, anno=config['annotationFuels']['right']), ] for args in traceArgs: points = __calcPoints(cpTrajData, args['lines'], args['anno']) data = pd.DataFrame(points).T fig.add_trace(go.Scatter( x=data.year, y=data.fscp, text=data.index, mode='markers+text', marker=dict(symbol='circle-open', size=config['global']['highlight_marker'], line={'width': config['global']['lw_thin']}, color='Black'), textposition='bottom center', showlegend=False, # hovertemplate = f"{name}<br>Carbon price: %{{x:.2f}}&plusmn;%{{error_x.array:.2f}}<extra></extra>", ), row=args['row'], col=args['col']) def __calcPoints(cpTrajData: pd.DataFrame, plotLines: pd.DataFrame, fuels: list) -> dict: points = {} fuelRef, fuelGreen, fuelBlue = fuels dropCols = ['plotIndex', 'fuel_x', 'fuel_y', 'cost_x', 'cost_y', 'ghgi_x', 'ghgi_y'] greenLine = plotLines.query(f"fuel_x=='{fuelRef}' & fuel_y=='{fuelGreen}'").drop(columns=dropCols).reset_index(drop=True) blueLine = plotLines.query(f"fuel_x=='{fuelRef}' & fuel_y=='{fuelBlue}'").drop(columns=dropCols).reset_index(drop=True) redLine = plotLines.query(f"fuel_x=='{fuelBlue}' & fuel_y=='{fuelGreen}'").drop(columns=dropCols).reset_index(drop=True) purpleLine = cpTrajData.drop(columns=['name', 'CP_u', 'CP_l']) for i, line in enumerate([blueLine, greenLine, redLine]): diffLines = pd.merge(line, purpleLine, on=['year']) diffLines['delta'] = (diffLines['fscp'] - diffLines['CP']).abs() points[i+2] = diffLines.nsmallest(1, 'delta').drop(columns=['CP', 'delta']).iloc[0] diffLines = pd.merge(blueLine, greenLine, on=['year'], suffixes=('', '_right')) diffLines['delta'] = (diffLines['fscp'] - diffLines['fscp_right']).abs() points[5] = diffLines.nsmallest(1, 'delta').drop(columns=['fscp_right', 'delta']).iloc[0] points[6] = redLine.abs().nsmallest(1, 'fscp').iloc[0] return points def __addAnnotationArrows(fig: go.Figure, config: dict): __addArrow(fig, 2025.0, 150.0, 600.0, 1, 1, config) __addArrow(fig, 2025.5, 150.0, 800.0, 1, 1, config) fig.add_annotation(text='1', x=2024.5, y=200.0, row=1, col=1, showarrow=False) __addArrow(fig, 2025.0, 150.0, 300.0, 1, 2, config) __addArrow(fig, 2025.5, 150.0, 800.0, 1, 2, config) fig.add_annotation(text='1', x=2024.5, y=200.0, row=1, col=2, showarrow=False) __addArrow(fig, 2024.5, 90.0, 200.0, 2, 1, config) fig.add_annotation(text='1', x=2024.0, y=150.0, row=2, col=1, showarrow=False) __addArrow(fig, 2024.5, 90.0, 200.0, 2, 2, config) fig.add_annotation(text='1', x=2024.0, y=150.0, row=2, col=2, showarrow=False) def __addArrow(fig: go.Figure, x: float, y1: float, y2: float, row: int, col: int, config: dict): xaxes = [['x', 'x2'], ['x3', 'x4']] yaxes = [['y', 'y2'], ['y3', 'y4']] for ay, y in [(y1, y2), (y2, y1)]: fig.add_annotation( axref=xaxes[row-1][col-1], xref=xaxes[row-1][col-1], ayref=yaxes[row-1][col-1], yref=yaxes[row-1][col-1], ax=x, x=x, ay=ay, y=y, arrowcolor='black', arrowwidth=config['global']['lw_thin'], #arrowsize=config['global']['highlight_marker_sm'], arrowhead=2, showarrow=True, row=row, col=col, ) def __addAnnotationsLegend(fig: go.Figure, config: dict): y0 = -0.40 fig.add_shape( type='rect', x0=0.0, y0=y0, x1=0.80, y1=y0-0.2, xref='paper', yref='paper', line_width=2, fillcolor='white', ) fig.add_annotation( text=f"<b>{config['annotationTexts']['heading1']}:</b><br><br><br><b>{config['annotationTexts']['heading2']}:</b>", align='left', xanchor='left', x=0.0, yanchor='top', y=y0, xref='paper', yref='paper', showarrow=False, ) for i in range(6): fig.add_annotation( text=f"{i+1}: "+config['annotationTexts'][f"point{i+1}"], align='left', xanchor='left', x=0.0 + i%3 * 0.22, yanchor='top', y=y0-(0.03 if i<3 else 0.13), xref='paper', yref='paper', showarrow=False, ) def __addFSCPTraces(plotData: pd.DataFrame, plotLines: pd.DataFrame, n_lines: int, refFuel: str, config: dict, sensitivityNG: bool = False): traces = [] for index in range(n_lines): thisDataScatter = plotData.query(f"plotIndex=={index}").reset_index(drop=True) thisDataLine = plotLines.query(f"plotIndex=={index}").reset_index(drop=True) # styling of individual lines truncated = (thisDataScatter.loc[0, 'fuel_x'] == 'blue LEB' and thisDataScatter.loc[0, 'fuel_y'] == 'green RE') or \ thisDataScatter.loc[0, 'fuel_x'] == 'blue LEB lowscco2' dashed = thisDataScatter.loc[0, 'fuel_y'] in ['green pure RE', 'blue LEB lowscco2'] longdashed = thisDataScatter.loc[0, 'fuel_x'] == 'blue LEB lowscco2' shift = 0 if thisDataScatter.loc[0, 'fuel_y'] == 'green RE': if thisDataScatter.loc[0, 'fuel_x'] == 'ref': shift = -1 else: shift = +1 elif thisDataScatter.loc[0, 'fuel_y'] == 'green pure RE': shift = +2 thisDataScatter = thisDataScatter.query(f"year<=2035") thisDataLine = thisDataLine.query(f"year<=2035") # line properties fuel_x = thisDataScatter.iloc[thisDataScatter.first_valid_index()]['fuel_x'] fuel_y = thisDataScatter.iloc[0]['fuel_y'] name = f"Fossil→{config['names'][fuel_y]}" if fuel_x == 'ref' else f"{config['names'][fuel_x]}→{config['names'][fuel_y]}" col = config['fscp_colours'][f"{fuel_x} to {fuel_y}"] if f"{fuel_x} to {fuel_y}" in config['fscp_colours'] else \ config['colours'][fuel_y] # do not plot awkward red line in sensitivity analysis row 2 if sensitivityNG and fuel_x == 'blue LEB': continue # scatter plot traces.append((index, go.Scatter( x=thisDataScatter['year'], y=thisDataScatter['fscp'], name=name, legendgroup=0 if fuel_x == 'ref' else 1, showlegend=False, mode='markers', line=dict(color=col, width=config['global']['lw_default'], dash='dot' if dashed else 'solid'), marker=dict(symbol='x-thin', size=config['global']['highlight_marker_sm'], line={'width': config['global']['lw_thin'], 'color': col}, ), hovertemplate=f"<b>{name}</b><br>Year: %{{x:d}}<br>FSCP: %{{y:.2f}}&plusmn;%{{error_y.array:.2f}}<extra></extra>", ))) # remove unphysical negative FSCPs if truncated and not sensitivityNG: thisDataLine = thisDataLine.query(f"(year>=2030 & fscp>0.0) | year>=2040") # line plot traces.append((index, go.Scatter( x=thisDataLine['year'], y=thisDataLine['fscp'], legendgroup=0 if fuel_x == 'ref' else 1, legendgrouptitle=dict(text=f"<b>{config['legendlabels'][0]}:</b>" if fuel_x=='ref' else f"<b>{config['legendlabels'][0]}:</b>"), name=name, mode='lines', line=dict(color=col, width=config['global']['lw_default'], dash='dot' if dashed else 'dash' if longdashed else 'solid'), ))) # error bars thisDataScatter = thisDataScatter.query(f"year==[2030,2040,2050]") thisDataScatter = thisDataScatter.query(f"fscp<={config['plotting']['fscp_max']} and (fscp>0.0 | year > 2040)") traces.append((index, go.Scatter( x=thisDataScatter['year'] + shift * 0.1, y=thisDataScatter['fscp'], error_y=dict(type='data', array=thisDataScatter['fscp_uu'], arrayminus=thisDataScatter['fscp_ul'], thickness=config['global']['lw_thin']), name=name, legendgroup=0 if fuel_x == 'ref' else 1, showlegend=False, mode='markers', marker=dict(symbol='x-thin', size=0.00001,), line_color=('rgba({}, {}, {}, {})'.format(*hex_to_rgb(col), .4)), hovertemplate=f"<b>{name}</b><br>Year: %{{x:d}}<br>FSCP: %{{y:.2f}}&plusmn;%{{error_y.array:.2f}}<extra></extra>", ))) return traces # compute carbon price trajectories def __computeCPTraj(years: list, values: dict, n_samples: int): v_mean = [] v_upper = [] v_lower = [] for i, year in enumerate(years): vals = [v[i] for v in values.values()] mean = sum(vals)/len(vals) v_mean.append(mean) v_upper.append(max(vals)-mean) v_lower.append(mean-min(vals)) # create data frame with time and cp values cpData = pd.DataFrame({ 'year': years, 'CP': v_mean, 'CP_u': v_upper, 'CP_l': v_lower, }) # interpolate in between samples = pd.DataFrame({'year': np.linspace(years[0], years[-1], n_samples)}) dtypes = {'year': float, 'CP': float, 'CP_u': float, 'CP_l': float} cpData = cpData.merge(samples, how='outer').sort_values(by=['year']).astype(dtypes).interpolate() # add name to dataframe cpData['name'] = 'cp' return cpData # plot traces def __addCPTraces(cpTrajData: pd.DataFrame, config: dict): traces = [] name = config['carbon_price_config']['name'] colour = config['carbon_price_config']['colour'] # add main graphs (FSCP and CP) traces.append(go.Scatter( name=name, legendgroup=1, mode='lines', x=cpTrajData['year'], y=cpTrajData['CP'], line_color=colour, line_width=config['global']['lw_thin'], showlegend=True, hovertemplate=f"<b>{name}</b><br>Time: %{{x:.2f}}<br>Carbon price: %{{y:.2f}}<extra></extra>" )) data_x = cpTrajData['year'] data_yu = cpTrajData['CP'] + cpTrajData['CP_u'] data_yl = cpTrajData['CP'] - cpTrajData['CP_l'] errorBand = go.Scatter( name='Uncertainty Range', legendgroup=1, x=pd.concat([data_x, data_x[::-1]], ignore_index=True), y=pd.concat([data_yl, data_yu[::-1]], ignore_index=True), mode='lines', marker=dict(color=colour), fillcolor=("rgba({}, {}, {}, 0.1)".format(*hex_to_rgb(colour))), fill='toself', line=dict(width=config['global']['lw_ultrathin']), showlegend=False, hoverinfo='skip' ) traces.append(errorBand) return traces def __styling(fig: go.Figure, config: dict): # update legend styling fig.update_layout( legend=dict( orientation='h', xanchor='left', x=0.0, yanchor='top', y=-0.1, bgcolor='rgba(255,255,255,1.0)', bordercolor='black', borderwidth=2, ), ) # update axis styling for axis in ['xaxis', 'xaxis2', 'xaxis3', 'xaxis4', 'yaxis', 'yaxis2', 'yaxis3', 'yaxis4']: update = {axis: dict( showline=True, linewidth=2, linecolor='black', showgrid=False, zeroline=False, mirror=True, ticks='outside', )} fig.update_layout(**update) # update figure background colour and font colour and type fig.update_layout( paper_bgcolor='rgba(255, 255, 255, 1.0)', plot_bgcolor='rgba(255, 255, 255, 0.0)', font_color='black', font_family='Helvetica', ) # move title annotations for i, annotation in enumerate(fig['layout']['annotations'][:len(config['subplot_title_positions'])]): x_pos, y_pos = config['subplot_title_positions'][i] annotation['xanchor'] = 'left' annotation['yanchor'] = 'top' annotation['xref'] = 'paper' annotation['yref'] = 'paper' annotation['x'] = x_pos annotation['y'] = y_pos annotation['text'] = "<b>{0}</b>".format(annotation['text'])
src/plotting/plots/plotOverTime.py
19,861
select which lines to plot based on function argument produce figure styling figure year_x == year_y, so we only need one of them from now on return FSCPs for scatter plots return costs and GHGIs for line plots interpolation of plotLines plot add FSCP traces for heating add FSCP traces for steel compute and plot carbon price tracjetory zero y line add text annotations explaining figure content add circles on intersects add arrows in 2025 add legend for annotations update axes titles and ranges hovertemplate = f"{name}<br>Carbon price: %{{x:.2f}}&plusmn;%{{error_x.array:.2f}}<extra></extra>",arrowsize=config['global']['highlight_marker_sm'], styling of individual lines line properties do not plot awkward red line in sensitivity analysis row 2 scatter plot remove unphysical negative FSCPs line plot error bars compute carbon price trajectories create data frame with time and cp values interpolate in between add name to dataframe plot traces add main graphs (FSCP and CP) update legend styling update axis styling update figure background colour and font colour and type move title annotations
1,103
en
0.619502
suite = { "mxversion": "5.156.0", "name": "truffleruby", "imports": { "suites": [ { # Import only the tools suite which depends on truffle, to avoid duplicating import versions. # We want tools to be reliably available with TruffleRuby, even with "mx build", so this is a static import. "name": "tools", "subdir": True, # version must always be equal to the version of the "sulong" import below "version": "aacc6652e247841b2bfa9bdba308021049c2e215", "urls": [ {"url": "https://github.com/oracle/graal.git", "kind": "git"}, {"url": "https://curio.ssw.jku.at/nexus/content/repositories/snapshots", "kind": "binary"}, ] }, { "name": "sulong", "subdir": True, # version must always be equal to the version of the "tools" import above "version": "aacc6652e247841b2bfa9bdba308021049c2e215", "urls": [ {"url": "https://github.com/oracle/graal.git", "kind": "git"}, {"url": "https://curio.ssw.jku.at/nexus/content/repositories/snapshots", "kind": "binary"}, ] }, ], }, "licenses": { "EPL-1.0": { "name": "Eclipse Public License 1.0", "url": "https://opensource.org/licenses/EPL-1.0", }, "BSD-simplified": { "name": "Simplified BSD License (2-clause BSD license)", "url": "http://opensource.org/licenses/BSD-2-Clause" }, "MIT": { "name": "MIT License", "url": "http://opensource.org/licenses/MIT" }, }, "repositories": { "truffleruby-binary-snapshots": { "url": "https://curio.ssw.jku.at/nexus/content/repositories/snapshots", "licenses": [ "EPL-1.0", # JRuby (we're choosing EPL out of EPL,GPL,LGPL) "BSD-simplified", # MRI "BSD-new", # Rubinius, FFI "MIT", # JCodings, minitest, did_you_mean, rake ] }, }, "libraries": { # ------------- Libraries ------------- "JONI": { "maven": { "groupId": "org.jruby.joni", "artifactId": "joni", "version": "2.1.25" }, "sha1": "5dbb09787a9b8780737b71fbf942235ef59051b9", "sourceSha1": "505a09064f6e2209616f38724f6d97d8d889aa92", "license": [ "MIT", # Joni ], }, "JCODINGS": { "maven": { "groupId": "org.jruby.jcodings", "artifactId": "jcodings", "version": "1.0.40" }, "sha1": "2838952e91baa37ac73ed817451268a193ba440a", "sourceSha1": "0ed89e096c83d540acac00d6ee3ea935b4c905ff", "license": [ "MIT", # JCodings ], }, }, "externalProjects": { "truffleruby-root": { "type": "ruby", "path": '.', "source": [ "lib/json", "lib/mri", "lib/truffle", ], "load_path": ["src/main/ruby/core"], "test": ["spec", "test"], "excluded": [ "bench", "dumps", "logo", "mxbuild", "truffleruby-gem-test-pack", "lib/ruby", "test/truffle/ecosystem/blog", "test/truffle/ecosystem/hello-world", "test/truffle/ecosystem/rails-app", ] }, }, "projects": { # ------------- Projects ------------- "org.truffleruby.annotations": { "dir": "src/annotations", "sourceDirs": ["java"], "javaCompliance": "1.8", "workingSets": "TruffleRuby", "checkPackagePrefix": "false", "license": [ "EPL-1.0", # JRuby (we're choosing EPL out of EPL,GPL,LGPL) ], }, "org.truffleruby.shared": { "dir": "src/shared", "sourceDirs": ["java"], "dependencies": [ "truffleruby:TRUFFLERUBY-ANNOTATIONS", "sdk:GRAAL_SDK", ], "annotationProcessors": [ "TRUFFLERUBY-PROCESSOR", ], "javaCompliance": "1.8", "workingSets": "TruffleRuby", "checkPackagePrefix": "false", "license": [ "EPL-1.0", # JRuby (we're choosing EPL out of EPL,GPL,LGPL) ], }, "org.truffleruby.processor": { "dir": "src/processor", "sourceDirs": ["java"], "dependencies": [ "truffleruby:TRUFFLERUBY-ANNOTATIONS", ], "javaCompliance": "1.8", "workingSets": "TruffleRuby", "checkPackagePrefix": "false", "license": [ "EPL-1.0", # JRuby (we're choosing EPL out of EPL,GPL,LGPL) ], }, "org.truffleruby.services": { "dir": "src/services", "sourceDirs": ["java"], "dependencies": [ "sdk:GRAAL_SDK", ], "javaCompliance": "1.8", "workingSets": "TruffleRuby", "checkPackagePrefix": "false", "license": [ "EPL-1.0", # JRuby (we're choosing EPL out of EPL,GPL,LGPL) ], }, "org.truffleruby": { "dir": "src/main", "sourceDirs": ["java"], "dependencies": [ "truffleruby:TRUFFLERUBY-ANNOTATIONS", "truffleruby:TRUFFLERUBY-SHARED", "truffle:TRUFFLE_API", "truffle:JLINE", "JONI", "JCODINGS", ], "annotationProcessors": [ "truffle:TRUFFLE_DSL_PROCESSOR", "TRUFFLERUBY-PROCESSOR", ], "javaCompliance": "1.8", "checkstyle" : "org.truffleruby", "workingSets": "TruffleRuby", "findbugsIgnoresGenerated" : True, "checkPackagePrefix": "false", "license": [ "EPL-1.0", # JRuby (we're choosing EPL out of EPL,GPL,LGPL) "BSD-new", # Rubinius "BSD-simplified", # MRI "MIT", # Joni, JCodings ], "externalProjects": { "ruby-core" : { "type": "ruby", "path": "ruby", "source": ["core", "post-boot"], "load_path": ["core"] } } }, "org.truffleruby.launcher": { "dir": "src/launcher", "sourceDirs": ["java"], "dependencies": [ "truffleruby:TRUFFLERUBY-ANNOTATIONS", "truffleruby:TRUFFLERUBY-SHARED", "sdk:GRAAL_SDK", "sdk:LAUNCHER_COMMON", ], "javaCompliance": "1.8", "workingSets": "TruffleRuby", "checkPackagePrefix": "false", "license": [ "EPL-1.0", # JRuby (we're choosing EPL out of EPL,GPL,LGPL) ], }, "org.truffleruby.core": { "class": "ArchiveProject", "outputDir": "src/main/ruby", "prefix": "truffleruby", "license": [ "EPL-1.0", # JRuby (we're choosing EPL out of EPL,GPL,LGPL) "BSD-new", # Rubinius ], }, "org.truffleruby.test": { "dir": "src/test", "sourceDirs": ["java"], "dependencies": [ "org.truffleruby", "org.truffleruby.services", "truffle:TRUFFLE_TCK", "mx:JUNIT", ], "javaCompliance": "1.8", "checkPackagePrefix": "false", "license": [ "EPL-1.0", # JRuby (we're choosing EPL out of EPL,GPL,LGPL) ], }, "org.truffleruby.test-ruby": { "class": "ArchiveProject", "outputDir": "src/test/ruby", "prefix": "src/test/ruby", "license": [ "EPL-1.0", # JRuby (we're choosing EPL out of EPL,GPL,LGPL) ], }, "org.truffleruby.cext": { "native": True, "dir": "src/main/c", "buildDependencies": [ "TRUFFLERUBY", # We need truffleruby.jar to run extconf.rb "org.truffleruby.bin", # bin/truffleruby "org.truffleruby.sulong-libs", # polyglot.h ], "output": ".", "results": [], # Empty results as they overlap with org.truffleruby.lib "license": [ "EPL-1.0", # JRuby (we're choosing EPL out of EPL,GPL,LGPL) "BSD-simplified", # MRI ], }, # Copy the files from SULONG_LIBS to lib/cext/sulong-libs. # Used by native images, which need a relative path from the Ruby home # to these libraries to pass to Sulong so it can find them outside GraalVM. "org.truffleruby.sulong-libs": { "class": "TruffleRubySulongLibsProject", "outputDir": "lib/cext/sulong-libs", "prefix": "lib/cext/sulong-libs", "buildDependencies": [ "sulong:SULONG_LIBS", ], }, "org.truffleruby.lib": { "class": "ArchiveProject", "dependencies": [ "org.truffleruby.cext", "org.truffleruby.sulong-libs", ], "outputDir": "lib", "prefix": "lib", "license": [ "EPL-1.0", "MIT", # minitest, did_you_mean, rake "BSD-simplified", # MRI "BSD-new", # Rubinius, FFI and RubySL ], }, "org.truffleruby.bin": { "class": "TruffleRubyLauncherProject", "buildDependencies": [ "TRUFFLERUBY", "TRUFFLERUBY-LAUNCHER", "sulong:SULONG", "tools:CHROMEINSPECTOR", "tools:TRUFFLE_PROFILER", ], "outputDir": "bin", "prefix": "bin", "license": [ "EPL-1.0", # JRuby (we're choosing EPL out of EPL,GPL,LGPL) ], }, "org.truffleruby.doc": { "class": "TruffleRubyDocsProject", "outputDir": "", "prefix": "", }, "org.truffleruby.specs": { "class": "ArchiveProject", "prefix": "spec", "outputDir": "spec", "license": [ "EPL-1.0", # JRuby (we're choosing EPL out of EPL,GPL,LGPL) "MIT", # Ruby Specs ], }, }, "distributions": { # ------------- Distributions ------------- "TRUFFLERUBY-ANNOTATIONS": { "dependencies": [ "org.truffleruby.annotations" ], "description": "TruffleRuby Annotations", "license": ["EPL-1.0"] }, # Required to share code between the launcher and the rest, # since the rest cannot depend on the launcher and the shared code cannot be there. # This code is loaded twice in different classloaders, therefore any created instances should not be passed around. "TRUFFLERUBY-SHARED": { "dependencies": [ "org.truffleruby.shared" ], "distDependencies": [ "truffleruby:TRUFFLERUBY-ANNOTATIONS", "sdk:GRAAL_SDK", ], "description": "TruffleRuby Shared constants and predicates", "license": ["EPL-1.0"] }, "TRUFFLERUBY-PROCESSOR": { "dependencies": [ "org.truffleruby.processor" ], "distDependencies": [ "truffleruby:TRUFFLERUBY-ANNOTATIONS", ], "description": "TruffleRuby Annotation Processor", "license": [ "EPL-1.0", # JRuby (we're choosing EPL out of EPL,GPL,LGPL) ], }, "TRUFFLERUBY-SERVICES": { "dependencies": [ "org.truffleruby.services" ], "distDependencies": [ "sdk:GRAAL_SDK", ], "description": "TruffleRuby services", "license": ["EPL-1.0"] }, "TRUFFLERUBY": { "mainClass": "org.truffleruby.launcher.RubyLauncher", "dependencies": [ "org.truffleruby", "org.truffleruby.core", ], "distDependencies": [ "truffle:TRUFFLE_API", "truffle:TRUFFLE_NFI", "truffleruby:TRUFFLERUBY-ANNOTATIONS", "truffleruby:TRUFFLERUBY-SHARED", ], "description": "TruffleRuby", "license": [ "EPL-1.0", # JRuby (we're choosing EPL out of EPL,GPL,LGPL) "BSD-new", # Rubinius "BSD-simplified", # MRI "MIT", # Joni, JCodings ], }, "TRUFFLERUBY-LAUNCHER": { "dependencies": [ "org.truffleruby.launcher" ], "distDependencies": [ "truffleruby:TRUFFLERUBY-ANNOTATIONS", "truffleruby:TRUFFLERUBY-SHARED", "truffleruby:TRUFFLERUBY-SERVICES", # For the file type detection service "sdk:GRAAL_SDK", "sdk:LAUNCHER_COMMON", ], "description": "TruffleRuby Launcher", "license": [ "EPL-1.0", # JRuby (we're choosing EPL out of EPL,GPL,LGPL) ], }, # Set of extra files to extract to run Ruby "TRUFFLERUBY-ZIP": { "native": True, # Not Java "relpath": True, "platformDependent": True, # org.truffleruby.cext, org.truffleruby.bin "dependencies": [ "org.truffleruby.bin", "org.truffleruby.lib", "org.truffleruby.doc", ], "description": "TruffleRuby libraries, documentation, bin directory", "license": [ "EPL-1.0", # JRuby (we're choosing EPL out of EPL,GPL,LGPL) "MIT", # minitest, did_you_mean, rake "BSD-simplified", # MRI "BSD-new", # Rubinius, FFI ], }, "TRUFFLERUBY_GRAALVM_SUPPORT" : { "native": True, "platformDependent": True, "description" : "TruffleRuby support distribution for the GraalVM", "dependencies" : [ "org.truffleruby.cext", ], "layout" : { "./" : [ "file:lib", # contains some results from org.truffleruby.cext "file:CHANGELOG.md", "file:README.md", "file:mx.truffleruby/native-image.properties", ], "LICENSE_TRUFFLERUBY.md" : "file:LICENCE.md", "3rd_party_licenses_truffleruby.txt" : "file:3rd_party_licenses.txt", "bin/" : [ "file:bin/gem", "file:bin/irb", "file:bin/rake", "file:bin/rdoc", "file:bin/ri", "file:bin/testrb", ], "doc/" : [ "file:doc/legal", "file:doc/user", ], "src/main/c/openssl/": [ "file:src/main/c/openssl/deprecation.rb", "file:src/main/c/openssl/extconf.rb", "file:src/main/c/openssl/*.c", { "source_type": "file", "path": "src/main/c/openssl/*.h", "exclude": ["src/main/c/openssl/extconf.h"] }, ], }, "license": [ "EPL-1.0", # JRuby (we're choosing EPL out of EPL,GPL,LGPL) "MIT", # minitest, did_you_mean, rake "BSD-simplified", # MRI "BSD-new", # Rubinius, FFI ], }, "TRUFFLERUBY-TEST": { "dependencies": [ "org.truffleruby.test", "org.truffleruby.test-ruby", ], "exclude": [ "mx:HAMCREST", "mx:JUNIT" ], "distDependencies": [ "TRUFFLERUBY", "truffle:TRUFFLE_TCK" ], "license": [ "EPL-1.0", # JRuby (we're choosing EPL out of EPL,GPL,LGPL) ], }, "TRUFFLERUBY-SPECS": { "native": True, # Not Java "relpath": True, "dependencies": [ "org.truffleruby.specs", ], "description": "TruffleRuby spec files from ruby/spec", "license": [ "EPL-1.0", # JRuby (we're choosing EPL out of EPL,GPL,LGPL) "MIT", # Ruby Specs ], }, }, }
mx.truffleruby/suite.py
18,164
Import only the tools suite which depends on truffle, to avoid duplicating import versions. We want tools to be reliably available with TruffleRuby, even with "mx build", so this is a static import. version must always be equal to the version of the "sulong" import below version must always be equal to the version of the "tools" import above JRuby (we're choosing EPL out of EPL,GPL,LGPL) MRI Rubinius, FFI JCodings, minitest, did_you_mean, rake ------------- Libraries ------------- Joni JCodings ------------- Projects ------------- JRuby (we're choosing EPL out of EPL,GPL,LGPL) JRuby (we're choosing EPL out of EPL,GPL,LGPL) JRuby (we're choosing EPL out of EPL,GPL,LGPL) JRuby (we're choosing EPL out of EPL,GPL,LGPL) JRuby (we're choosing EPL out of EPL,GPL,LGPL) Rubinius MRI Joni, JCodings JRuby (we're choosing EPL out of EPL,GPL,LGPL) JRuby (we're choosing EPL out of EPL,GPL,LGPL) Rubinius JRuby (we're choosing EPL out of EPL,GPL,LGPL) JRuby (we're choosing EPL out of EPL,GPL,LGPL) We need truffleruby.jar to run extconf.rb bin/truffleruby polyglot.h Empty results as they overlap with org.truffleruby.lib JRuby (we're choosing EPL out of EPL,GPL,LGPL) MRI Copy the files from SULONG_LIBS to lib/cext/sulong-libs. Used by native images, which need a relative path from the Ruby home to these libraries to pass to Sulong so it can find them outside GraalVM. minitest, did_you_mean, rake MRI Rubinius, FFI and RubySL JRuby (we're choosing EPL out of EPL,GPL,LGPL) JRuby (we're choosing EPL out of EPL,GPL,LGPL) Ruby Specs ------------- Distributions ------------- Required to share code between the launcher and the rest, since the rest cannot depend on the launcher and the shared code cannot be there. This code is loaded twice in different classloaders, therefore any created instances should not be passed around. JRuby (we're choosing EPL out of EPL,GPL,LGPL) JRuby (we're choosing EPL out of EPL,GPL,LGPL) Rubinius MRI Joni, JCodings For the file type detection service JRuby (we're choosing EPL out of EPL,GPL,LGPL) Set of extra files to extract to run Ruby Not Java org.truffleruby.cext, org.truffleruby.bin JRuby (we're choosing EPL out of EPL,GPL,LGPL) minitest, did_you_mean, rake MRI Rubinius, FFI contains some results from org.truffleruby.cext JRuby (we're choosing EPL out of EPL,GPL,LGPL) minitest, did_you_mean, rake MRI Rubinius, FFI JRuby (we're choosing EPL out of EPL,GPL,LGPL) Not Java JRuby (we're choosing EPL out of EPL,GPL,LGPL) Ruby Specs
2,478
en
0.783031
import torch import time from math import pi import numpy as np from ..utils.tensorboard import Tensorboard from ..utils.output import progress from .convergence import Convergence from ..model.deepmod import DeepMoD from typing import Optional def train(model: DeepMoD, data: torch.Tensor, target: torch.Tensor, optimizer, sparsity_scheduler, log_dir: Optional[str] = None, max_iterations: int = 10000, write_iterations: int = 25, **convergence_kwargs) -> None: """[summary] Args: model (DeepMoD): [description] data (torch.Tensor): [description] target (torch.Tensor): [description] optimizer ([type]): [description] sparsity_scheduler ([type]): [description] log_dir (Optional[str], optional): [description]. Defaults to None. max_iterations (int, optional): [description]. Defaults to 10000. """ start_time = time.time() board = Tensorboard(log_dir) # initializing tb board # Training convergence = Convergence(**convergence_kwargs) print('| Iteration | Progress | Time remaining | Loss | MSE | Reg | L1 norm |') for iteration in np.arange(0, max_iterations + 1): # ================== Training Model ============================ prediction, time_derivs, thetas = model(data) MSE = torch.mean((prediction - target)**2, dim=0) # loss per output Reg = torch.stack([torch.mean((dt - theta @ coeff_vector)**2) for dt, theta, coeff_vector in zip(time_derivs, thetas, model.constraint_coeffs(scaled=False, sparse=True))]) loss = torch.sum(MSE + Reg) # 1e-5 for numerical stability # Optimizer step optimizer.zero_grad() loss.backward() optimizer.step() # ====================== Logging ======================= # We calculate the normalization factor and the l1_norm l1_norm = torch.sum(torch.abs(torch.cat(model.constraint_coeffs(sparse=True, scaled=True), dim=1)), dim=0) # Write progress to command line and tensorboard if iteration % write_iterations == 0: _ = model.sparse_estimator(thetas, time_derivs) # calculating l1 adjusted coeffs but not setting mask progress(iteration, start_time, max_iterations, loss.item(), torch.sum(MSE).item(), torch.sum(Reg).item(), torch.sum(l1_norm).item()) if model.estimator_coeffs() is None: estimator_coeff_vectors = [torch.zeros_like(coeff) for coeff in model.constraint_coeffs(sparse=True, scaled=False)] # It doesnt exist before we start sparsity, so we use zeros else: estimator_coeff_vectors = model.estimator_coeffs() board.write(iteration, loss, MSE, Reg, l1_norm, model.constraint_coeffs(sparse=True, scaled=True), model.constraint_coeffs(sparse=True, scaled=False), estimator_coeff_vectors) # ================== Validation and sparsity ============= # Updating sparsity and or convergence sparsity_scheduler(iteration, torch.sum(l1_norm)) if sparsity_scheduler.apply_sparsity is True: with torch.no_grad(): model.constraint.sparsity_masks = model.sparse_estimator(thetas, time_derivs) sparsity_scheduler.reset() print(model.sparsity_masks) # Checking convergence convergence(iteration, torch.sum(l1_norm)) if convergence.converged is True: print('Algorithm converged. Stopping training.') break board.close() def train_auto_split(model: DeepMoD, data: torch.Tensor, target: torch.Tensor, optimizer, sparsity_scheduler, split: float = 0.8, log_dir: Optional[str] = None, max_iterations: int = 10000, write_iterations: int = 25, **convergence_kwargs) -> None: """[summary] Args: model (DeepMoD): [description] data (torch.Tensor): [description] target (torch.Tensor): [description] optimizer ([type]): [description] sparsity_scheduler ([type]): [description] log_dir (Optional[str], optional): [description]. Defaults to None. max_iterations (int, optional): [description]. Defaults to 10000. """ start_time = time.time() board = Tensorboard(log_dir) # initializing tb board # Splitting data, assumes data is already randomized n_train = int(split * data.shape[0]) n_test = data.shape[0] - n_train data_train, data_test = torch.split(data, [n_train, n_test], dim=0) target_train, target_test = torch.split(target, [n_train, n_test], dim=0) # Training convergence = Convergence(**convergence_kwargs) print('| Iteration | Progress | Time remaining | Loss | MSE | Reg | L1 norm |') for iteration in np.arange(0, max_iterations + 1): # ================== Training Model ============================ prediction, time_derivs, thetas = model(data_train) MSE = torch.mean((prediction - target_train)**2, dim=0) # loss per output Reg = torch.stack([torch.mean((dt - theta @ coeff_vector)**2) for dt, theta, coeff_vector in zip(time_derivs, thetas, model.constraint_coeffs(scaled=False, sparse=True))]) loss = torch.sum(MSE + Reg) # Optimizer step optimizer.zero_grad() loss.backward() optimizer.step() # ====================== Logging ======================= # We calculate the normalization factor and the l1_norm l1_norm = torch.sum(torch.abs(torch.cat(model.constraint_coeffs(sparse=True, scaled=True), dim=1)), dim=0) # Validation loss with torch.no_grad(): prediction_test = model.func_approx(data_test)[0] MSE_test = torch.mean((prediction_test - target_test)**2, dim=0) # loss per output # Write progress to command line and tensorboard if iteration % write_iterations == 0: _ = model.sparse_estimator(thetas, time_derivs) # calculating l1 adjusted coeffs but not setting mask estimator_coeff_vectors = model.estimator_coeffs() progress(iteration, start_time, max_iterations, loss.item(), torch.sum(MSE).item(), torch.sum(Reg).item(), torch.sum(l1_norm).item()) board.write(iteration, loss, MSE, Reg, l1_norm, model.constraint_coeffs(sparse=True, scaled=True), model.constraint_coeffs(sparse=True, scaled=False), estimator_coeff_vectors, MSE_test=MSE_test) # ================== Validation and sparsity ============= # Updating sparsity and or convergence sparsity_scheduler(iteration, torch.sum(MSE_test), model, optimizer) #sparsity_scheduler(torch.sum(MSE_test), model, optimizer) if sparsity_scheduler.apply_sparsity is True: with torch.no_grad(): model.constraint.sparsity_masks = model.sparse_estimator(thetas, time_derivs) sparsity_scheduler.reset() print(model.sparsity_masks) # Checking convergence convergence(iteration, torch.sum(l1_norm)) if convergence.converged is True: print('Algorithm converged. Stopping training.') break board.close() def train_auto_split_scaled(model: DeepMoD, data: torch.Tensor, target: torch.Tensor, optimizer, sparsity_scheduler, split: float = 0.8, log_dir: Optional[str] = None, max_iterations: int = 10000, write_iterations: int = 25, **convergence_kwargs) -> None: """[summary] Args: model (DeepMoD): [description] data (torch.Tensor): [description] target (torch.Tensor): [description] optimizer ([type]): [description] sparsity_scheduler ([type]): [description] log_dir (Optional[str], optional): [description]. Defaults to None. max_iterations (int, optional): [description]. Defaults to 10000. """ start_time = time.time() board = Tensorboard(log_dir) # initializing tb board # Splitting data, assumes data is already randomized n_train = int(split * data.shape[0]) n_test = data.shape[0] - n_train data_train, data_test = torch.split(data, [n_train, n_test], dim=0) target_train, target_test = torch.split(target, [n_train, n_test], dim=0) # Training convergence = Convergence(**convergence_kwargs) print('| Iteration | Progress | Time remaining | Loss | MSE | Reg | L1 norm |') for iteration in np.arange(0, max_iterations + 1): # ================== Training Model ============================ prediction, time_derivs, thetas = model(data_train) MSE = torch.mean((prediction - target_train)**2, dim=0) # loss per output theta_norms = [torch.norm(theta, dim=0) for theta in thetas] time_deriv_norms = [torch.norm(dt, dim=0) for dt in time_derivs] normed_thetas = [theta / norm for theta, norm in zip(thetas, theta_norms)] normed_time_derivs = [dt / norm for dt, norm in zip(time_derivs, time_deriv_norms)] Reg = torch.stack([torch.mean((dt - theta @ coeff_vector)**2) for dt, theta, coeff_vector in zip(normed_time_derivs, normed_thetas, model.constraint_coeffs(scaled=True, sparse=True))]) loss = torch.sum(MSE + Reg) # 1e-5 for numerical stability # Optimizer step optimizer.zero_grad() loss.backward() optimizer.step() # ====================== Logging ======================= # We calculate the normalization factor and the l1_norm l1_norm = torch.sum(torch.abs(torch.cat(model.constraint_coeffs(sparse=True, scaled=True), dim=1)), dim=0) # Validation loss prediction_test, coordinates = model.func_approx(data_test) time_derivs_test, thetas_test = model.library((prediction_test, coordinates)) MSE_test = torch.mean((prediction_test - target_test)**2, dim=0) # loss per output Reg_test = torch.stack([torch.mean((dt - theta @ coeff_vector)**2) for dt, theta, coeff_vector in zip(time_derivs_test, thetas_test, model.constraint_coeffs(scaled=False, sparse=True))]) loss_test = torch.sum(MSE_test + Reg_test) # Write progress to command line and tensorboard if iteration % write_iterations == 0: _ = model.sparse_estimator(thetas, time_derivs) # calculating l1 adjusted coeffs but not setting mask estimator_coeff_vectors = model.estimator_coeffs() progress(iteration, start_time, max_iterations, loss.item(), torch.sum(MSE).item(), torch.sum(Reg).item(), torch.sum(l1_norm).item()) board.write(iteration, loss, MSE, Reg, l1_norm, model.constraint_coeffs(sparse=True, scaled=True), model.constraint_coeffs(sparse=True, scaled=False), estimator_coeff_vectors, MSE_test=MSE_test, Reg_test=Reg_test, loss_test=loss_test) # ================== Validation and sparsity ============= # Updating sparsity and or convergence sparsity_scheduler(loss_test, model, optimizer) #sparsity_scheduler(torch.sum(MSE_test), model, optimizer) if sparsity_scheduler.apply_sparsity is True: with torch.no_grad(): checkpoint = torch.load(sparsity_scheduler.path) model.load_state_dict(checkpoint['model_state_dict']) optimizer.load_state_dict(checkpoint['optimizer_state_dict']) model.constraint.sparsity_masks = model.sparse_estimator(thetas, time_derivs) sparsity_scheduler.reset() print(model.sparsity_masks) # Checking convergence convergence(iteration, torch.sum(l1_norm)) if convergence.converged is True: print('Algorithm converged. Stopping training.') break board.close() def train_auto_split_MSE(model: DeepMoD, data: torch.Tensor, target: torch.Tensor, optimizer, sparsity_scheduler, split: float = 0.8, log_dir: Optional[str] = None, max_iterations: int = 10000, write_iterations: int = 25, **convergence_kwargs) -> None: """[summary] Args: model (DeepMoD): [description] data (torch.Tensor): [description] target (torch.Tensor): [description] optimizer ([type]): [description] sparsity_scheduler ([type]): [description] log_dir (Optional[str], optional): [description]. Defaults to None. max_iterations (int, optional): [description]. Defaults to 10000. """ start_time = time.time() board = Tensorboard(log_dir) # initializing tb board # Training convergence = Convergence(**convergence_kwargs) print('| Iteration | Progress | Time remaining | Loss | MSE | Reg | L1 norm |') for iteration in np.arange(0, max_iterations + 1): # ================== Training Model ============================ prediction, time_derivs, thetas = model(data) MSE = torch.mean((prediction - target)**2, dim=0) # loss per output #Reg = torch.stack([torch.mean((dt - theta @ coeff_vector)**2) # for dt, theta, coeff_vector in zip(time_derivs, thetas, model.constraint_coeffs(scaled=False, sparse=True))]) loss = torch.sum(MSE) # 1e-5 for numerical stability # Optimizer step optimizer.zero_grad() loss.backward() optimizer.step() # ====================== Logging ======================= with torch.no_grad(): # We calculate the normalization factor and the l1_norm l1_norm = torch.sum(torch.abs(torch.cat(model.constraint.coeff_vectors, dim=1)), dim=0) # Validation loss prediction_test = model.func_approx(data)[0] MSE_test = torch.mean((prediction_test - target)**2, dim=0) # loss per output # Write progress to command line and tensorboard if iteration % write_iterations == 0: _ = model.sparse_estimator(thetas, time_derivs) # calculating l1 adjusted coeffs but not setting mask estimator_coeff_vectors = model.estimator_coeffs() progress(iteration, start_time, max_iterations, loss.item(), torch.sum(MSE).item(), torch.sum(MSE).item(), torch.sum(l1_norm).item()) board.write(iteration, loss, MSE, MSE, l1_norm, model.constraint.coeff_vectors, model.constraint.coeff_vectors, estimator_coeff_vectors, MSE_test=MSE_test) # ================== Validation and sparsity ============= # Updating sparsity and or convergence sparsity_scheduler(iteration, torch.sum(MSE_test), model, optimizer) if sparsity_scheduler.apply_sparsity is True: with torch.no_grad(): model.constraint.sparsity_masks = model.sparse_estimator(thetas, time_derivs) sparsity_scheduler.reset() print(model.sparsity_masks) # Checking convergence convergence(iteration, torch.sum(l1_norm)) if convergence.converged is True: print('Algorithm converged. Stopping training.') break board.close() def train_split_full(model: DeepMoD, data: torch.Tensor, target: torch.Tensor, optimizer, sparsity_scheduler, test = 'mse', split: float = 0.8, log_dir: Optional[str] = None, max_iterations: int = 10000, write_iterations: int = 25, **convergence_kwargs) -> None: """[summary] Args: model (DeepMoD): [description] data (torch.Tensor): [description] target (torch.Tensor): [description] optimizer ([type]): [description] sparsity_scheduler ([type]): [description] log_dir (Optional[str], optional): [description]. Defaults to None. max_iterations (int, optional): [description]. Defaults to 10000. """ start_time = time.time() board = Tensorboard(log_dir) # initializing tb board # Splitting data, assumes data is already randomized n_train = int(split * data.shape[0]) n_test = data.shape[0] - n_train data_train, data_test = torch.split(data, [n_train, n_test], dim=0) target_train, target_test = torch.split(target, [n_train, n_test], dim=0) # Training convergence = Convergence(**convergence_kwargs) print('| Iteration | Progress | Time remaining | Loss | MSE | Reg | L1 norm |') for iteration in np.arange(0, max_iterations + 1): # ================== Training Model ============================ prediction, time_derivs, thetas = model(data_train) MSE = torch.mean((prediction - target_train)**2, dim=0) # loss per output Reg = torch.stack([torch.mean((dt - theta @ coeff_vector)**2) for dt, theta, coeff_vector in zip(time_derivs, thetas, model.constraint_coeffs(scaled=False, sparse=True))]) loss = torch.sum(MSE + Reg) # Optimizer step optimizer.zero_grad() loss.backward() optimizer.step() if iteration % write_iterations == 0: # ================== Validation costs ================ prediction_test, coordinates = model.func_approx(data_test) time_derivs_test, thetas_test = model.library((prediction_test, coordinates)) with torch.no_grad(): MSE_test = torch.mean((prediction_test - target_test)**2, dim=0) # loss per output Reg_test = torch.stack([torch.mean((dt - theta @ coeff_vector)**2) for dt, theta, coeff_vector in zip(time_derivs_test, thetas_test, model.constraint_coeffs(scaled=False, sparse=True))]) loss_test = torch.sum(MSE_test + Reg_test) # ====================== Logging ======================= _ = model.sparse_estimator(thetas, time_derivs) # calculating l1 adjusted coeffs but not setting mask estimator_coeff_vectors = model.estimator_coeffs() l1_norm = torch.sum(torch.abs(torch.cat(model.constraint_coeffs(sparse=True, scaled=True), dim=1)), dim=0) progress(iteration, start_time, max_iterations, loss.item(), torch.sum(MSE).item(), torch.sum(Reg).item(), torch.sum(l1_norm).item()) board.write(iteration, loss, MSE, Reg, l1_norm, model.constraint_coeffs(sparse=True, scaled=True), model.constraint_coeffs(sparse=True, scaled=False), estimator_coeff_vectors, MSE_test=MSE_test, Reg_test=Reg_test, loss_test=loss_test) # ================== Sparsity update ============= # Updating sparsity and or convergence #sparsity_scheduler(iteration, l1_norm) if iteration % write_iterations == 0: if test == 'mse': sparsity_scheduler(iteration, torch.sum(MSE_test), model, optimizer) else: sparsity_scheduler(iteration, loss_test, model, optimizer) if sparsity_scheduler.apply_sparsity is True: with torch.no_grad(): model.constraint.sparsity_masks = model.sparse_estimator(thetas, time_derivs) sparsity_scheduler.reset() # ================= Checking convergence convergence(iteration, torch.sum(l1_norm)) if convergence.converged is True: print('Algorithm converged. Stopping training.') break board.close()
src/multitaskpinn/training/.ipynb_checkpoints/training-checkpoint.py
20,082
[summary] Args: model (DeepMoD): [description] data (torch.Tensor): [description] target (torch.Tensor): [description] optimizer ([type]): [description] sparsity_scheduler ([type]): [description] log_dir (Optional[str], optional): [description]. Defaults to None. max_iterations (int, optional): [description]. Defaults to 10000. [summary] Args: model (DeepMoD): [description] data (torch.Tensor): [description] target (torch.Tensor): [description] optimizer ([type]): [description] sparsity_scheduler ([type]): [description] log_dir (Optional[str], optional): [description]. Defaults to None. max_iterations (int, optional): [description]. Defaults to 10000. [summary] Args: model (DeepMoD): [description] data (torch.Tensor): [description] target (torch.Tensor): [description] optimizer ([type]): [description] sparsity_scheduler ([type]): [description] log_dir (Optional[str], optional): [description]. Defaults to None. max_iterations (int, optional): [description]. Defaults to 10000. [summary] Args: model (DeepMoD): [description] data (torch.Tensor): [description] target (torch.Tensor): [description] optimizer ([type]): [description] sparsity_scheduler ([type]): [description] log_dir (Optional[str], optional): [description]. Defaults to None. max_iterations (int, optional): [description]. Defaults to 10000. [summary] Args: model (DeepMoD): [description] data (torch.Tensor): [description] target (torch.Tensor): [description] optimizer ([type]): [description] sparsity_scheduler ([type]): [description] log_dir (Optional[str], optional): [description]. Defaults to None. max_iterations (int, optional): [description]. Defaults to 10000. initializing tb board Training ================== Training Model ============================ loss per output 1e-5 for numerical stability Optimizer step ====================== Logging ======================= We calculate the normalization factor and the l1_norm Write progress to command line and tensorboard calculating l1 adjusted coeffs but not setting mask It doesnt exist before we start sparsity, so we use zeros ================== Validation and sparsity ============= Updating sparsity and or convergence Checking convergence initializing tb board Splitting data, assumes data is already randomized Training ================== Training Model ============================ loss per output Optimizer step ====================== Logging ======================= We calculate the normalization factor and the l1_norm Validation loss loss per output Write progress to command line and tensorboard calculating l1 adjusted coeffs but not setting mask ================== Validation and sparsity ============= Updating sparsity and or convergencesparsity_scheduler(torch.sum(MSE_test), model, optimizer) Checking convergence initializing tb board Splitting data, assumes data is already randomized Training ================== Training Model ============================ loss per output 1e-5 for numerical stability Optimizer step ====================== Logging ======================= We calculate the normalization factor and the l1_norm Validation loss loss per output Write progress to command line and tensorboard calculating l1 adjusted coeffs but not setting mask ================== Validation and sparsity ============= Updating sparsity and or convergencesparsity_scheduler(torch.sum(MSE_test), model, optimizer) Checking convergence initializing tb board Training ================== Training Model ============================ loss per outputReg = torch.stack([torch.mean((dt - theta @ coeff_vector)**2) for dt, theta, coeff_vector in zip(time_derivs, thetas, model.constraint_coeffs(scaled=False, sparse=True))]) 1e-5 for numerical stability Optimizer step ====================== Logging ======================= We calculate the normalization factor and the l1_norm Validation loss loss per output Write progress to command line and tensorboard calculating l1 adjusted coeffs but not setting mask ================== Validation and sparsity ============= Updating sparsity and or convergence Checking convergence initializing tb board Splitting data, assumes data is already randomized Training ================== Training Model ============================ loss per output Optimizer step ================== Validation costs ================ loss per output ====================== Logging ======================= calculating l1 adjusted coeffs but not setting mask ================== Sparsity update ============= Updating sparsity and or convergencesparsity_scheduler(iteration, l1_norm) ================= Checking convergence
4,749
en
0.619211
#!/usr/bin/env python import paho.mqtt.client as mqtt import random from logger import error, info from message import Message from pubsub import publish MQTT_ERR_SUCCESS = 0 # MQTT client wrapper for use with Mainflux. class MQTT: # Initialize the class with topics that will be used # during publish and possibly subscribe. def __init__(self, topics, client_id='mqtt-client', clean_session=True, qos=0, queue=None): info('mqtt', 'init') self.connected = False self.qos = qos self.queue = queue self.subscribe = queue != None # Handle topics string or slice. if isinstance(topics, basestring): topics = topics.split(',') self.topics = topics # Add randomness to client_id. client_id = client_id+'-'+str(random.randint(1000, 9999)) self.client = mqtt.Client(client_id=client_id, clean_session=clean_session) self.client.on_connect = self.on_connect self.client.on_disconnect = self.on_disconnect self.client.on_message = self.on_message self.client.on_publish = self.on_publish self.client.on_subscribe = self.on_subscribe # Connect to the MQTT adapter endpoint and start the internal # paho-mqtt loop. def connect(self, host, port, username, password): info('mqtt', 'connect') self.client.username_pw_set(username, password) self.client.connect(host, port=port, keepalive=60) self.client.loop_start() # Disconnect the client. def disconnect(self): self.connected = False self.client.loop_stop() self.client.disconnect() dur_count = 0.0 dur_total = 0.0 def dur_avg(self): return self.dur_total / self.dur_count # The callback for when the client receives a CONNACK response from the server. def on_connect(self, client, userdata, flags, rc): info('mqtt', 'on_connect '+str(rc)) if rc == MQTT_ERR_SUCCESS: self.connected = True # Subscribing in on_connect() means that if we lose the connection and # reconnect then subscriptions will be renewed. if self.subscribe: subs = [] for topic in self.topics: info('mqtt', 'subscribe: channels/'+topic+'/messages, qos: '+str(self.qos)) subs.append(('channels/'+topic+'/messages', self.qos)) info('mqtt', 'subscriptions: '+str(subs)) self.client.subscribe(subs) # When the client disconnects make sure to stop the loop. def on_disconnect(self, client, userdata, rc): info('mqtt', 'on_disconnect') if rc != MQTT_ERR_SUCCESS: info('mqtt', 'on_disconnect unexpected: '+str(rc)) #self.disconnect() #self.client.reconnect() # The callback for when a PUBLISH message is received from the server. def on_message(self, client, userdata, msg): info('mqtt', 'on_message:'+msg.topic+': '+str(msg.payload)) try: if self.queue: m = Message(msg.topic, msg.payload) if m.is_valid(): if m.for_device() and not m.get_name() in ['CONNECTED', 'REGISTERED', 'TX']: self.queue.put(m) publish(m, channel='inbound') else: publish(m, channel='inbound') except Exception as ex: error('mqtt', 'on_message: '+str(ex)) # When a message has been published. def on_publish(self, client, userdata, mid): info('mqtt', 'on_publish: '+str(mid)) # When a subscription is complete. def on_subscribe(client, userdata, mid, granted_qos): info('mqtt', 'on_subscribe mid: '+mid) # Publish a message to the topic provided on init. def publish(self, msg=None): if msg: info('mqtt', 'publish: '+str(msg)) mid = self.client.publish(msg.topic, payload=msg.payload_str(), qos=self.qos) self.dur_count += 1 self.dur_total += msg.get_duration() info('mqtt', 'published '+str(self.dur_count)+' for an avg. duration of '+str(self.dur_avg())+' secs. with '+str(self.dur_total)+' secs. in total')
gateway/kit/mqtt.py
4,256
!/usr/bin/env python MQTT client wrapper for use with Mainflux. Initialize the class with topics that will be used during publish and possibly subscribe. Handle topics string or slice. Add randomness to client_id. Connect to the MQTT adapter endpoint and start the internal paho-mqtt loop. Disconnect the client. The callback for when the client receives a CONNACK response from the server. Subscribing in on_connect() means that if we lose the connection and reconnect then subscriptions will be renewed. When the client disconnects make sure to stop the loop.self.disconnect()self.client.reconnect() The callback for when a PUBLISH message is received from the server. When a message has been published. When a subscription is complete. Publish a message to the topic provided on init.
787
en
0.850782
from .results import Result class K4AException(Exception): pass class K4ATimeoutException(K4AException): pass def _verify_error(res: int): """ Validate k4a_module result """ res = Result(res) if res == Result.Failed: raise K4AException() elif res == Result.Timeout: raise K4ATimeoutException()
deepclaw/driver/sensors/camera/pyk4a_cfg/errors.py
348
Validate k4a_module result
26
en
0.076032
#!/usr/bin/env python # Copyright (c) 2014, OpenCog Foundation # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # * Redistributions of source code must retain the above copyright notice, this # list of conditions and the following disclaimer. # # * Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation # and/or other materials provided with the distribution. # # * Neither the name of the OpenCog Foundation nor the names of its # contributors may be used to endorse or promote products derived from # this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE # FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL # DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR # SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, # OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. __author__ = "James Diprose" import bpy import mathutils from mathutils import Matrix, Vector from math import acos, degrees from xml.dom.minidom import parseString from xml.etree.ElementTree import Element, SubElement, Comment, tostring class LinkRef(object): def __init__(self, name, link_type): self.name = name self.link_type = link_type def to_xml(self, xml_parent): link_ref = SubElement(xml_parent, self.link_type) link_ref.set('link', self.name) return link class Origin(object): def __init__(self, x, y, z, roll, pitch, yaw): self.x = x self.y = y self.z = z self.roll = roll self.pitch = pitch self.yaw = yaw def to_xml(self, xml_parent): origin = SubElement(xml_parent, 'origin') origin.set('xyz', "{0} {1} {2}".format(self.x, self.y, self.z)) origin.set('rpy', "{0} {1} {2}".format(self.roll, self.pitch, self.yaw)) return origin class Axis(object): def __init__(self, x, y, z): self.x = x self.y = y self.z = z def to_xml(self, xml_parent): axis = SubElement(xml_parent, 'axis') axis.set('xyz', "{0} {1} {2}".format(self.x, self.y, self.z)) return axis class Limit(object): def __init__(self, velocity, effort, lower, upper): self.velocity = velocity self.effort = effort self.lower = lower self.upper = upper def to_xml(self, xml_parent): limit = SubElement(xml_parent, 'limit') limit.set('velocity', str(self.velocity)) limit.set('effort', str(self.effort)) limit.set('lower', str(self.lower)) limit.set('upper', str(self.upper)) return limit class Joint(object): def __init__(self, name, type, parent_link, child_link, origin, axis, limit): self.name = name self.type = type self.parent_link = parent_link self.child_link = child_link self.origin = origin self.axis = axis self.limit = limit @staticmethod def to_link_name(name): return name.replace('_joint', '_link') def to_xml(self, xml_parent): joint = SubElement(xml_parent, 'joint') joint.set('name', self.name) joint.set('type', self.type) self.parent_link.to_xml(joint) self.child_link.to_xml(joint) self.origin.to_xml(joint) self.axis.to_xml(joint) self.limit.to_xml(joint) return joint def get_root_bone(bones): for bone in bones: if bone.parent is None: return bone def get_bone(name, bones): for bone in bones: if bone.name == name: return bone def is_joint(bone): return bone.name.endswith('joint') def to_ros_coord(x, y, z): return (z, -x, y) def add_prefix(name): if name.startswith('l_'): return name.replace('l_', '${prefix}_') elif name.startswith('r_'): return name.replace('r_', '${prefix}_') return name class Link(object): def __init__(self, name): self.name = name def to_xml(self, xml_parent): link = SubElement(xml_parent, 'name') link.set('name', self.name) return link # joints, links #if is_root: # global visited_joints # global links # links = [] # visited_joints = {} #joints = [] # visited_joints[parent_bone.name] = True def has_been_visited(name, joints): visited = False for joint in joints: if name == joint.name: visited = True break return visited def generate_links_and_joints(parent_pose_bone, links=[], joints=[]): try: if len(visited_joints) == 0: global visited_joints visited_joints = {} except NameError: global visited_joints visited_joints = {} print(len(visited_joints)) visited_joints[parent_pose_bone.name] = True if is_joint(parent_pose_bone): parent_edit_bone = parent_pose_bone.bone for child_pose_bone in parent_pose_bone.children: child_edit_bone = child_pose_bone.bone if is_joint(child_pose_bone) and child_pose_bone.name not in visited_joints: # Parent & child parent_link = LinkRef(Joint.to_link_name(parent_pose_bone.name), 'parent') child_link = LinkRef(Joint.to_link_name(child_pose_bone.name), 'child') # Origin dX = round(parent_pose_bone.head[0] - child_pose_bone.head[0], 4) dY = round(parent_pose_bone.head[1] - child_pose_bone.head[1], 4) dZ = round(parent_pose_bone.head[2] - child_pose_bone.head[2], 4) point = to_ros_coord(dX, dY, dZ) #rot = parent_edit_bone.localOrientation.to_euler() #parent_pose_bone.worldOrientation #matrix_final = parent_edit_bone.id_data.matrix_world * parent_edit_bone.matrix #angles = get_bone_rotation(parent_edit_bone) mat = child_pose_bone.id_data.matrix_world #print(str((parent_pose_bone.matrix).to_euler())) print("angle of " + child_pose_bone.name + ": " + str((mat * child_pose_bone.matrix).to_euler()) ) origin = Origin(point[0], point[1], point[2], 0, 0, 0) axis = Axis(1, 0, 0) limit = Limit(0, 0, 0, 0) # Joint joint = Joint(child_pose_bone.name, 'revolute', parent_link, child_link, origin, axis, limit) joints.append(joint) link = Link(Joint.to_link_name(child_pose_bone.name)) links.append(link) (joints, links) = generate_links_and_joints(child_pose_bone, links, joints) print("{0} to {1}: ({2}, {3}, {4}, {5})".format(child_pose_bone.name, child_edit_bone.name, point[0], point[1], point[2], parent_pose_bone.vector)) return (joints, links) def pretty_print(xml_element): ugly_str = tostring(xml_element, 'utf-8') mini_dom_str = parseString(ugly_str) return mini_dom_str.toprettyxml(indent="\t") rig = bpy.data.objects['Armature'] root_pose_bone = get_root_bone(rig.pose.bones) print("root_bone: " + str(root_pose_bone)) print("is joint: " + str(is_joint(root_pose_bone))) robot = Element('robot') robot.set('xmlns:xacro', 'http://ros.org/wiki/xacro') macro = SubElement(robot, 'xacro:macro') macro.set('name', 'blender_generated_urdf') (joints, links) = generate_links_and_joints(root_pose_bone) print(len(joints)) bone = get_bone('big_bone', rig.pose.bones ) print("BONE: " + str((bone.id_data.matrix_world * bone.matrix).to_euler())) for link in links: link.to_xml(macro) for joint in joints: joint.to_xml(macro)
src/ros_blender_plugin/urdf_exporter.py
8,421
!/usr/bin/env python Copyright (c) 2014, OpenCog Foundation All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the OpenCog Foundation nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. joints, linksif is_root: global visited_joints global links links = [] visited_joints = {}joints = [] visited_joints[parent_bone.name] = True Parent & child Originrot = parent_edit_bone.localOrientation.to_euler()parent_pose_bone.worldOrientationmatrix_final = parent_edit_bone.id_data.matrix_world * parent_edit_bone.matrixangles = get_bone_rotation(parent_edit_bone)print(str((parent_pose_bone.matrix).to_euler())) Joint
1,951
en
0.819433
# -*- coding: utf-8 -*- """Cisco Identity Services Engine SXPConnections API wrapper. Copyright (c) 2021 Cisco and/or its affiliates. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. """ from __future__ import ( absolute_import, division, print_function, unicode_literals, ) from builtins import * from past.builtins import basestring from ...restsession import RestSession from ...utils import ( check_type, dict_from_items_with_values, apply_path_params, dict_of_str, get_next_page, ) class SxpConnections(object): """Identity Services Engine SXPConnections API (version: 3.0.0). Wraps the Identity Services Engine SXPConnections API and exposes the API as native Python methods that return native Python objects. """ def __init__(self, session, object_factory, request_validator): """Initialize a new SxpConnections object with the provided RestSession. Args: session(RestSession): The RESTful session object to be used for API calls to the Identity Services Engine service. Raises: TypeError: If the parameter types are incorrect. """ check_type(session, RestSession) super(SxpConnections, self).__init__() self._session = session self._object_factory = object_factory self._request_validator = request_validator def get_sxp_connections_by_id(self, id, headers=None, **query_parameters): """This API allows the client to get a SXP connection by ID. Args: id(basestring): id path parameter. headers(dict): Dictionary of HTTP Headers to send with the Request . **query_parameters: Additional query parameters (provides support for parameters that may be added in the future). Returns: RestResponse: REST response with following properties: - headers(MyDict): response headers. - response(MyDict): response body as a MyDict object. Access the object's properties by using the dot notation or the bracket notation. - content(bytes): representation of the request's response - text(str): representation of the request's response Raises: TypeError: If the parameter types are incorrect. MalformedRequest: If the request body created is invalid. ApiError: If the Identity Services Engine cloud returns an error. """ check_type(headers, dict) if headers is not None: if 'Content-Type' in headers: check_type(headers.get('Content-Type'), basestring, may_be_none=False) if 'Accept' in headers: check_type(headers.get('Accept'), basestring, may_be_none=False) if 'ERS-Media-Type' in headers: check_type(headers.get('ERS-Media-Type'), basestring) if 'X-CSRF-TOKEN' in headers: check_type(headers.get('X-CSRF-TOKEN'), basestring) with_custom_headers = False _headers = self._session.headers or {} if headers: _headers.update(dict_of_str(headers)) with_custom_headers = True check_type(id, basestring, may_be_none=False) _params = { } _params.update(query_parameters) _params = dict_from_items_with_values(_params) path_params = { 'id': id, } e_url = ('/ers/config/sxpconnections/{id}') endpoint_full_url = apply_path_params(e_url, path_params) if with_custom_headers: _api_response = self._session.get(endpoint_full_url, params=_params, headers=_headers) else: _api_response = self._session.get(endpoint_full_url, params=_params) return self._object_factory('bpm_a5b160a5675039b7ddf3dc960c7968_v3_0_0', _api_response) def get_by_id(self, id, headers=None, **query_parameters): """Alias for `get_sxp_connections_by_id <#ciscoisesdk. api.v3_0_0.sxp_connections. SxpConnections.get_sxp_connections_by_id>`_ """ return self.get_sxp_connections_by_id( id=id, headers=headers, **query_parameters ) def update_sxp_connections_by_id(self, id, description=None, enabled=None, ip_address=None, sxp_mode=None, sxp_node=None, sxp_peer=None, sxp_version=None, sxp_vpn=None, headers=None, payload=None, active_validation=True, **query_parameters): """This API allows the client to update a SXP connection. Args: description(string): description, property of the request body. enabled(boolean): enabled, property of the request body. id(string): id, property of the request body. ip_address(string): ipAddress, property of the request body. sxp_mode(string): sxpMode, property of the request body. sxp_node(string): sxpNode, property of the request body. sxp_peer(string): sxpPeer, property of the request body. sxp_version(string): sxpVersion, property of the request body. sxp_vpn(string): sxpVpn, property of the request body. id(basestring): id path parameter. headers(dict): Dictionary of HTTP Headers to send with the Request . payload(dict): A JSON serializable Python object to send in the body of the Request. active_validation(bool): Enable/Disable payload validation. Defaults to True. **query_parameters: Additional query parameters (provides support for parameters that may be added in the future). Returns: RestResponse: REST response with following properties: - headers(MyDict): response headers. - response(MyDict): response body as a MyDict object. Access the object's properties by using the dot notation or the bracket notation. - content(bytes): representation of the request's response - text(str): representation of the request's response Raises: TypeError: If the parameter types are incorrect. MalformedRequest: If the request body created is invalid. ApiError: If the Identity Services Engine cloud returns an error. """ check_type(headers, dict) if headers is not None: if 'Content-Type' in headers: check_type(headers.get('Content-Type'), basestring, may_be_none=False) if 'Accept' in headers: check_type(headers.get('Accept'), basestring, may_be_none=False) if 'ERS-Media-Type' in headers: check_type(headers.get('ERS-Media-Type'), basestring) if 'X-CSRF-TOKEN' in headers: check_type(headers.get('X-CSRF-TOKEN'), basestring) with_custom_headers = False _headers = self._session.headers or {} if headers: _headers.update(dict_of_str(headers)) with_custom_headers = True is_xml_payload = 'application/xml' in _headers.get('Content-Type', []) if active_validation and is_xml_payload: check_type(payload, basestring) if active_validation and not is_xml_payload: check_type(payload, dict) check_type(id, basestring, may_be_none=False) _params = { } _params.update(query_parameters) _params = dict_from_items_with_values(_params) path_params = { 'id': id, } if is_xml_payload: _payload = payload else: _tmp_payload = { 'id': id, 'description': description, 'sxpPeer': sxp_peer, 'sxpVpn': sxp_vpn, 'sxpNode': sxp_node, 'ipAddress': ip_address, 'sxpMode': sxp_mode, 'sxpVersion': sxp_version, 'enabled': enabled, } _payload = { 'ERSSxpConnection': dict_from_items_with_values(_tmp_payload) } _payload.update(payload or {}) _payload = dict_from_items_with_values(_payload) if active_validation and not is_xml_payload: self._request_validator('jsd_cab8440e21553c3a807d23d05e5e1aa_v3_0_0')\ .validate(_payload) e_url = ('/ers/config/sxpconnections/{id}') endpoint_full_url = apply_path_params(e_url, path_params) request_params = {'data': _payload} if is_xml_payload else {'json': _payload} if with_custom_headers: _api_response = self._session.put(endpoint_full_url, params=_params, headers=_headers, **request_params) else: _api_response = self._session.put(endpoint_full_url, params=_params, **request_params) return self._object_factory('bpm_cab8440e21553c3a807d23d05e5e1aa_v3_0_0', _api_response) def update_by_id(self, id, description=None, enabled=None, ip_address=None, sxp_mode=None, sxp_node=None, sxp_peer=None, sxp_version=None, sxp_vpn=None, headers=None, payload=None, active_validation=True, **query_parameters): """Alias for `update_sxp_connections_by_id <#ciscoisesdk. api.v3_0_0.sxp_connections. SxpConnections.update_sxp_connections_by_id>`_ """ return self.update_sxp_connections_by_id( id=id, description=description, enabled=enabled, ip_address=ip_address, sxp_mode=sxp_mode, sxp_node=sxp_node, sxp_peer=sxp_peer, sxp_version=sxp_version, sxp_vpn=sxp_vpn, payload=payload, active_validation=active_validation, headers=headers, **query_parameters ) def delete_sxp_connections_by_id(self, id, headers=None, **query_parameters): """This API deletes a SXP connection. Args: id(basestring): id path parameter. headers(dict): Dictionary of HTTP Headers to send with the Request . **query_parameters: Additional query parameters (provides support for parameters that may be added in the future). Returns: RestResponse: REST response with following properties: - headers(MyDict): response headers. - response(MyDict): response body as a MyDict object. Access the object's properties by using the dot notation or the bracket notation. - content(bytes): representation of the request's response - text(str): representation of the request's response Raises: TypeError: If the parameter types are incorrect. MalformedRequest: If the request body created is invalid. ApiError: If the Identity Services Engine cloud returns an error. """ check_type(headers, dict) if headers is not None: if 'Content-Type' in headers: check_type(headers.get('Content-Type'), basestring, may_be_none=False) if 'Accept' in headers: check_type(headers.get('Accept'), basestring, may_be_none=False) if 'ERS-Media-Type' in headers: check_type(headers.get('ERS-Media-Type'), basestring) if 'X-CSRF-TOKEN' in headers: check_type(headers.get('X-CSRF-TOKEN'), basestring) with_custom_headers = False _headers = self._session.headers or {} if headers: _headers.update(dict_of_str(headers)) with_custom_headers = True check_type(id, basestring, may_be_none=False) _params = { } _params.update(query_parameters) _params = dict_from_items_with_values(_params) path_params = { 'id': id, } e_url = ('/ers/config/sxpconnections/{id}') endpoint_full_url = apply_path_params(e_url, path_params) if with_custom_headers: _api_response = self._session.delete(endpoint_full_url, params=_params, headers=_headers) else: _api_response = self._session.delete(endpoint_full_url, params=_params) return self._object_factory('bpm_fb665776b98ba815b52515a6_v3_0_0', _api_response) def delete_by_id(self, id, headers=None, **query_parameters): """Alias for `delete_sxp_connections_by_id <#ciscoisesdk. api.v3_0_0.sxp_connections. SxpConnections.delete_sxp_connections_by_id>`_ """ return self.delete_sxp_connections_by_id( id=id, headers=headers, **query_parameters ) def get_sxp_connections(self, filter=None, filter_type=None, page=None, size=None, sortasc=None, sortdsc=None, headers=None, **query_parameters): """This API allows the client to get all the SXP connections. Filter: [name, description] To search resources by using toDate column,follow the format: DD-MON-YY (Example:13-SEP-18) Day or Year:GET /ers/config/guestuser/?filter=toDate.CONTAINS.13 Month:GET /ers/config/guestuser/?filter=toDate.CONTAINS.SEP Date:GET /ers/config/guestuser/?filter=toDate.CONTAINS.13-SEP-18 Sorting: [name, description]. Args: page(int): page query parameter. Page number. size(int): size query parameter. Number of objects returned per page. sortasc(basestring): sortasc query parameter. sort asc. sortdsc(basestring): sortdsc query parameter. sort desc. filter(basestring, list, set, tuple): filter query parameter. **Simple filtering** should be available through the filter query string parameter. The structure of a filter is a triplet of field operator and value separated with dots. More than one filter can be sent. The logical operator common to ALL filter criteria will be by default AND, and can be changed by using the "filterType=or" query string parameter. Each resource Data model description should specify if an attribute is a filtered field. (Operator: Description), (EQ: Equals), (NEQ: Not Equals), (GT: Greater Than), (LT: Less Then), (STARTSW: Starts With), (NSTARTSW: Not Starts With), (ENDSW: Ends With), (NENDSW: Not Ends With), (CONTAINS: Contains), (NCONTAINS: Not Contains), . filter_type(basestring): filterType query parameter. The logical operator common to ALL filter criteria will be by default AND, and can be changed by using the parameter. headers(dict): Dictionary of HTTP Headers to send with the Request . **query_parameters: Additional query parameters (provides support for parameters that may be added in the future). Returns: RestResponse: REST response with following properties: - headers(MyDict): response headers. - response(MyDict): response body as a MyDict object. Access the object's properties by using the dot notation or the bracket notation. - content(bytes): representation of the request's response - text(str): representation of the request's response Raises: TypeError: If the parameter types are incorrect. MalformedRequest: If the request body created is invalid. ApiError: If the Identity Services Engine cloud returns an error. """ check_type(headers, dict) if headers is not None: if 'Content-Type' in headers: check_type(headers.get('Content-Type'), basestring, may_be_none=False) if 'Accept' in headers: check_type(headers.get('Accept'), basestring, may_be_none=False) if 'ERS-Media-Type' in headers: check_type(headers.get('ERS-Media-Type'), basestring) if 'X-CSRF-TOKEN' in headers: check_type(headers.get('X-CSRF-TOKEN'), basestring) with_custom_headers = False _headers = self._session.headers or {} if headers: _headers.update(dict_of_str(headers)) with_custom_headers = True check_type(page, (int, basestring, list)) check_type(size, (int, basestring, list)) check_type(sortasc, basestring) check_type(sortdsc, basestring) check_type(filter, (basestring, list, set, tuple)) check_type(filter_type, basestring) _params = { 'page': page, 'size': size, 'sortasc': sortasc, 'sortdsc': sortdsc, 'filter': filter, 'filterType': filter_type, } _params.update(query_parameters) _params = dict_from_items_with_values(_params) path_params = { } e_url = ('/ers/config/sxpconnections') endpoint_full_url = apply_path_params(e_url, path_params) if with_custom_headers: _api_response = self._session.get(endpoint_full_url, params=_params, headers=_headers) else: _api_response = self._session.get(endpoint_full_url, params=_params) return self._object_factory('bpm_c56dfcff6285f9b882c884873d5d6c1_v3_0_0', _api_response) def get_all(self, filter=None, filter_type=None, page=None, size=None, sortasc=None, sortdsc=None, headers=None, **query_parameters): """Alias for `get_sxp_connections <#ciscoisesdk. api.v3_0_0.sxp_connections. SxpConnections.get_sxp_connections>`_ """ return self.get_sxp_connections( filter=filter, filter_type=filter_type, page=page, size=size, sortasc=sortasc, sortdsc=sortdsc, headers=headers, **query_parameters ) def get_sxp_connections_generator(self, filter=None, filter_type=None, page=None, size=None, sortasc=None, sortdsc=None, headers=None, **query_parameters): """This API allows the client to get all the SXP connections. Filter: [name, description] To search resources by using toDate column,follow the format: DD-MON-YY (Example:13-SEP-18) Day or Year:GET /ers/config/guestuser/?filter=toDate.CONTAINS.13 Month:GET /ers/config/guestuser/?filter=toDate.CONTAINS.SEP Date:GET /ers/config/guestuser/?filter=toDate.CONTAINS.13-SEP-18 Sorting: [name, description]. Args: page(int): page query parameter. Page number. size(int): size query parameter. Number of objects returned per page. sortasc(basestring): sortasc query parameter. sort asc. sortdsc(basestring): sortdsc query parameter. sort desc. filter(basestring, list, set, tuple): filter query parameter. **Simple filtering** should be available through the filter query string parameter. The structure of a filter is a triplet of field operator and value separated with dots. More than one filter can be sent. The logical operator common to ALL filter criteria will be by default AND, and can be changed by using the "filterType=or" query string parameter. Each resource Data model description should specify if an attribute is a filtered field. (Operator: Description), (EQ: Equals), (NEQ: Not Equals), (GT: Greater Than), (LT: Less Then), (STARTSW: Starts With), (NSTARTSW: Not Starts With), (ENDSW: Ends With), (NENDSW: Not Ends With), (CONTAINS: Contains), (NCONTAINS: Not Contains), . filter_type(basestring): filterType query parameter. The logical operator common to ALL filter criteria will be by default AND, and can be changed by using the parameter. headers(dict): Dictionary of HTTP Headers to send with the Request . **query_parameters: Additional query parameters (provides support for parameters that may be added in the future). Returns: Generator: A generator object containing the following object. + RestResponse: REST response with following properties: - headers(MyDict): response headers. - response(MyDict): response body as a MyDict object. Access the object's properties by using the dot notation or the bracket notation. - content(bytes): representation of the request's response - text(str): representation of the request's response Raises: TypeError: If the parameter types are incorrect. MalformedRequest: If the request body created is invalid. ApiError: If the Identity Services Engine cloud returns an error. """ yield from get_next_page( self.get_sxp_connections, dict( filter=filter, filter_type=filter_type, page=page, size=size, sortasc=sortasc, sortdsc=sortdsc, headers=headers, **query_parameters ), access_next_list=["SearchResult", "nextPage", "href"], access_resource_list=["SearchResult", "resources"]) def get_all_generator(self, filter=None, filter_type=None, page=None, size=None, sortasc=None, sortdsc=None, headers=None, **query_parameters): """Alias for `get_sxp_connections_generator <#ciscoisesdk. api.v3_0_0.sxp_connections. SxpConnections.get_sxp_connections_generator>`_ """ yield from get_next_page( self.get_sxp_connections, dict( filter=filter, filter_type=filter_type, page=page, size=size, sortasc=sortasc, sortdsc=sortdsc, headers=headers, **query_parameters ), access_next_list=["SearchResult", "nextPage", "href"], access_resource_list=["SearchResult", "resources"]) def create_sxp_connections(self, description=None, enabled=None, ip_address=None, sxp_mode=None, sxp_node=None, sxp_peer=None, sxp_version=None, sxp_vpn=None, headers=None, payload=None, active_validation=True, **query_parameters): """This API creates a SXP connection. Args: description(string): description, property of the request body. enabled(boolean): enabled, property of the request body. ip_address(string): ipAddress, property of the request body. sxp_mode(string): sxpMode, property of the request body. sxp_node(string): sxpNode, property of the request body. sxp_peer(string): sxpPeer, property of the request body. sxp_version(string): sxpVersion, property of the request body. sxp_vpn(string): sxpVpn, property of the request body. headers(dict): Dictionary of HTTP Headers to send with the Request . payload(dict): A JSON serializable Python object to send in the body of the Request. active_validation(bool): Enable/Disable payload validation. Defaults to True. **query_parameters: Additional query parameters (provides support for parameters that may be added in the future). Returns: RestResponse: REST response with following properties: - headers(MyDict): response headers. - response(MyDict): response body as a MyDict object. Access the object's properties by using the dot notation or the bracket notation. - content(bytes): representation of the request's response - text(str): representation of the request's response Raises: TypeError: If the parameter types are incorrect. MalformedRequest: If the request body created is invalid. ApiError: If the Identity Services Engine cloud returns an error. """ check_type(headers, dict) if headers is not None: if 'Content-Type' in headers: check_type(headers.get('Content-Type'), basestring, may_be_none=False) if 'Accept' in headers: check_type(headers.get('Accept'), basestring, may_be_none=False) if 'ERS-Media-Type' in headers: check_type(headers.get('ERS-Media-Type'), basestring) if 'X-CSRF-TOKEN' in headers: check_type(headers.get('X-CSRF-TOKEN'), basestring) with_custom_headers = False _headers = self._session.headers or {} if headers: _headers.update(dict_of_str(headers)) with_custom_headers = True is_xml_payload = 'application/xml' in _headers.get('Content-Type', []) if active_validation and is_xml_payload: check_type(payload, basestring) if active_validation and not is_xml_payload: check_type(payload, dict) _params = { } _params.update(query_parameters) _params = dict_from_items_with_values(_params) path_params = { } if is_xml_payload: _payload = payload else: _tmp_payload = { 'description': description, 'sxpPeer': sxp_peer, 'sxpVpn': sxp_vpn, 'sxpNode': sxp_node, 'ipAddress': ip_address, 'sxpMode': sxp_mode, 'sxpVersion': sxp_version, 'enabled': enabled, } _payload = { 'ERSSxpConnection': dict_from_items_with_values(_tmp_payload) } _payload.update(payload or {}) _payload = dict_from_items_with_values(_payload) if active_validation and not is_xml_payload: self._request_validator('jsd_c371214c759f791c0a522b9eaf5b5_v3_0_0')\ .validate(_payload) e_url = ('/ers/config/sxpconnections') endpoint_full_url = apply_path_params(e_url, path_params) request_params = {'data': _payload} if is_xml_payload else {'json': _payload} if with_custom_headers: _api_response = self._session.post(endpoint_full_url, params=_params, headers=_headers, **request_params) else: _api_response = self._session.post(endpoint_full_url, params=_params, **request_params) return self._object_factory('bpm_c371214c759f791c0a522b9eaf5b5_v3_0_0', _api_response) def create(self, description=None, enabled=None, ip_address=None, sxp_mode=None, sxp_node=None, sxp_peer=None, sxp_version=None, sxp_vpn=None, headers=None, payload=None, active_validation=True, **query_parameters): """Alias for `create_sxp_connections <#ciscoisesdk. api.v3_0_0.sxp_connections. SxpConnections.create_sxp_connections>`_ """ return self.create_sxp_connections( description=description, enabled=enabled, ip_address=ip_address, sxp_mode=sxp_mode, sxp_node=sxp_node, sxp_peer=sxp_peer, sxp_version=sxp_version, sxp_vpn=sxp_vpn, payload=payload, active_validation=active_validation, headers=headers, **query_parameters ) def get_version(self, headers=None, **query_parameters): """This API helps to retrieve the version information related to the SXP connections. Args: headers(dict): Dictionary of HTTP Headers to send with the Request . **query_parameters: Additional query parameters (provides support for parameters that may be added in the future). Returns: RestResponse: REST response with following properties: - headers(MyDict): response headers. - response(MyDict): response body as a MyDict object. Access the object's properties by using the dot notation or the bracket notation. - content(bytes): representation of the request's response - text(str): representation of the request's response Raises: TypeError: If the parameter types are incorrect. MalformedRequest: If the request body created is invalid. ApiError: If the Identity Services Engine cloud returns an error. """ check_type(headers, dict) if headers is not None: if 'Content-Type' in headers: check_type(headers.get('Content-Type'), basestring, may_be_none=False) if 'Accept' in headers: check_type(headers.get('Accept'), basestring, may_be_none=False) with_custom_headers = False _headers = self._session.headers or {} if headers: _headers.update(dict_of_str(headers)) with_custom_headers = True _params = { } _params.update(query_parameters) _params = dict_from_items_with_values(_params) path_params = { } e_url = ('/ers/config/sxpconnections/versioninfo') endpoint_full_url = apply_path_params(e_url, path_params) if with_custom_headers: _api_response = self._session.get(endpoint_full_url, params=_params, headers=_headers) else: _api_response = self._session.get(endpoint_full_url, params=_params) return self._object_factory('bpm_c1ceea62877152f6a4cf7ce709f4d0f8_v3_0_0', _api_response) def bulk_request_for_sxp_connections(self, operation_type=None, resource_media_type=None, headers=None, payload=None, active_validation=True, **query_parameters): """This API allows the client to submit the bulk request. Args: operation_type(string): operationType, property of the request body. resource_media_type(string): resourceMediaType, property of the request body. headers(dict): Dictionary of HTTP Headers to send with the Request . payload(dict): A JSON serializable Python object to send in the body of the Request. active_validation(bool): Enable/Disable payload validation. Defaults to True. **query_parameters: Additional query parameters (provides support for parameters that may be added in the future). Returns: RestResponse: REST response with following properties: - headers(MyDict): response headers. - response(MyDict): response body as a MyDict object. Access the object's properties by using the dot notation or the bracket notation. - content(bytes): representation of the request's response - text(str): representation of the request's response Raises: TypeError: If the parameter types are incorrect. MalformedRequest: If the request body created is invalid. ApiError: If the Identity Services Engine cloud returns an error. """ check_type(headers, dict) if headers is not None: if 'Content-Type' in headers: check_type(headers.get('Content-Type'), basestring, may_be_none=False) if 'Accept' in headers: check_type(headers.get('Accept'), basestring, may_be_none=False) with_custom_headers = False _headers = self._session.headers or {} if headers: _headers.update(dict_of_str(headers)) with_custom_headers = True is_xml_payload = 'application/xml' in _headers.get('Content-Type', []) if active_validation and is_xml_payload: check_type(payload, basestring) if active_validation and not is_xml_payload: check_type(payload, dict) _params = { } _params.update(query_parameters) _params = dict_from_items_with_values(_params) path_params = { } if is_xml_payload: _payload = payload else: _tmp_payload = { 'operationType': operation_type, 'resourceMediaType': resource_media_type, } _payload = { 'ConnectionBulkRequest': dict_from_items_with_values(_tmp_payload) } _payload.update(payload or {}) _payload = dict_from_items_with_values(_payload) if active_validation and not is_xml_payload: self._request_validator('jsd_e390313557e95aa9b8c2453d6f1de1e8_v3_0_0')\ .validate(_payload) e_url = ('/ers/config/sxpconnections/bulk/submit') endpoint_full_url = apply_path_params(e_url, path_params) request_params = {'data': _payload} if is_xml_payload else {'json': _payload} if with_custom_headers: _api_response = self._session.put(endpoint_full_url, params=_params, headers=_headers, **request_params) else: _api_response = self._session.put(endpoint_full_url, params=_params, **request_params) return self._object_factory('bpm_e390313557e95aa9b8c2453d6f1de1e8_v3_0_0', _api_response) def bulk_request(self, operation_type=None, resource_media_type=None, headers=None, payload=None, active_validation=True, **query_parameters): """Alias for `bulk_request_for_sxp_connections <#ciscoisesdk. api.v3_0_0.sxp_connections. SxpConnections.bulk_request_for_sxp_connections>`_ """ return self.bulk_request_for_sxp_connections( operation_type=operation_type, resource_media_type=resource_media_type, payload=payload, active_validation=active_validation, headers=headers, **query_parameters ) def monitor_bulk_status_sxp_connections(self, bulkid, headers=None, **query_parameters): """This API allows the client to monitor the bulk request. Args: bulkid(basestring): bulkid path parameter. headers(dict): Dictionary of HTTP Headers to send with the Request . **query_parameters: Additional query parameters (provides support for parameters that may be added in the future). Returns: RestResponse: REST response with following properties: - headers(MyDict): response headers. - response(MyDict): response body as a MyDict object. Access the object's properties by using the dot notation or the bracket notation. - content(bytes): representation of the request's response - text(str): representation of the request's response Raises: TypeError: If the parameter types are incorrect. MalformedRequest: If the request body created is invalid. ApiError: If the Identity Services Engine cloud returns an error. """ check_type(headers, dict) if headers is not None: if 'Content-Type' in headers: check_type(headers.get('Content-Type'), basestring, may_be_none=False) if 'Accept' in headers: check_type(headers.get('Accept'), basestring, may_be_none=False) with_custom_headers = False _headers = self._session.headers or {} if headers: _headers.update(dict_of_str(headers)) with_custom_headers = True check_type(bulkid, basestring, may_be_none=False) _params = { } _params.update(query_parameters) _params = dict_from_items_with_values(_params) path_params = { 'bulkid': bulkid, } e_url = ('/ers/config/sxpconnections/bulk/{bulkid}') endpoint_full_url = apply_path_params(e_url, path_params) if with_custom_headers: _api_response = self._session.get(endpoint_full_url, params=_params, headers=_headers) else: _api_response = self._session.get(endpoint_full_url, params=_params) return self._object_factory('bpm_c2fb20ca5eb79facdda896457507_v3_0_0', _api_response) def monitor_bulk_status(self, bulkid, headers=None, **query_parameters): """Alias for `monitor_bulk_status_sxp_connections <#ciscoisesdk. api.v3_0_0.sxp_connections. SxpConnections.monitor_bulk_status_sxp_connections>`_ """ return self.monitor_bulk_status_sxp_connections( bulkid=bulkid, headers=headers, **query_parameters )
ciscoisesdk/api/v3_0_0/sxp_connections.py
44,100
Identity Services Engine SXPConnections API (version: 3.0.0). Wraps the Identity Services Engine SXPConnections API and exposes the API as native Python methods that return native Python objects. Initialize a new SxpConnections object with the provided RestSession. Args: session(RestSession): The RESTful session object to be used for API calls to the Identity Services Engine service. Raises: TypeError: If the parameter types are incorrect. Alias for `bulk_request_for_sxp_connections <#ciscoisesdk. api.v3_0_0.sxp_connections. SxpConnections.bulk_request_for_sxp_connections>`_ This API allows the client to submit the bulk request. Args: operation_type(string): operationType, property of the request body. resource_media_type(string): resourceMediaType, property of the request body. headers(dict): Dictionary of HTTP Headers to send with the Request . payload(dict): A JSON serializable Python object to send in the body of the Request. active_validation(bool): Enable/Disable payload validation. Defaults to True. **query_parameters: Additional query parameters (provides support for parameters that may be added in the future). Returns: RestResponse: REST response with following properties: - headers(MyDict): response headers. - response(MyDict): response body as a MyDict object. Access the object's properties by using the dot notation or the bracket notation. - content(bytes): representation of the request's response - text(str): representation of the request's response Raises: TypeError: If the parameter types are incorrect. MalformedRequest: If the request body created is invalid. ApiError: If the Identity Services Engine cloud returns an error. Alias for `create_sxp_connections <#ciscoisesdk. api.v3_0_0.sxp_connections. SxpConnections.create_sxp_connections>`_ This API creates a SXP connection. Args: description(string): description, property of the request body. enabled(boolean): enabled, property of the request body. ip_address(string): ipAddress, property of the request body. sxp_mode(string): sxpMode, property of the request body. sxp_node(string): sxpNode, property of the request body. sxp_peer(string): sxpPeer, property of the request body. sxp_version(string): sxpVersion, property of the request body. sxp_vpn(string): sxpVpn, property of the request body. headers(dict): Dictionary of HTTP Headers to send with the Request . payload(dict): A JSON serializable Python object to send in the body of the Request. active_validation(bool): Enable/Disable payload validation. Defaults to True. **query_parameters: Additional query parameters (provides support for parameters that may be added in the future). Returns: RestResponse: REST response with following properties: - headers(MyDict): response headers. - response(MyDict): response body as a MyDict object. Access the object's properties by using the dot notation or the bracket notation. - content(bytes): representation of the request's response - text(str): representation of the request's response Raises: TypeError: If the parameter types are incorrect. MalformedRequest: If the request body created is invalid. ApiError: If the Identity Services Engine cloud returns an error. Alias for `delete_sxp_connections_by_id <#ciscoisesdk. api.v3_0_0.sxp_connections. SxpConnections.delete_sxp_connections_by_id>`_ This API deletes a SXP connection. Args: id(basestring): id path parameter. headers(dict): Dictionary of HTTP Headers to send with the Request . **query_parameters: Additional query parameters (provides support for parameters that may be added in the future). Returns: RestResponse: REST response with following properties: - headers(MyDict): response headers. - response(MyDict): response body as a MyDict object. Access the object's properties by using the dot notation or the bracket notation. - content(bytes): representation of the request's response - text(str): representation of the request's response Raises: TypeError: If the parameter types are incorrect. MalformedRequest: If the request body created is invalid. ApiError: If the Identity Services Engine cloud returns an error. Alias for `get_sxp_connections <#ciscoisesdk. api.v3_0_0.sxp_connections. SxpConnections.get_sxp_connections>`_ Alias for `get_sxp_connections_generator <#ciscoisesdk. api.v3_0_0.sxp_connections. SxpConnections.get_sxp_connections_generator>`_ Alias for `get_sxp_connections_by_id <#ciscoisesdk. api.v3_0_0.sxp_connections. SxpConnections.get_sxp_connections_by_id>`_ This API allows the client to get all the SXP connections. Filter: [name, description] To search resources by using toDate column,follow the format: DD-MON-YY (Example:13-SEP-18) Day or Year:GET /ers/config/guestuser/?filter=toDate.CONTAINS.13 Month:GET /ers/config/guestuser/?filter=toDate.CONTAINS.SEP Date:GET /ers/config/guestuser/?filter=toDate.CONTAINS.13-SEP-18 Sorting: [name, description]. Args: page(int): page query parameter. Page number. size(int): size query parameter. Number of objects returned per page. sortasc(basestring): sortasc query parameter. sort asc. sortdsc(basestring): sortdsc query parameter. sort desc. filter(basestring, list, set, tuple): filter query parameter. **Simple filtering** should be available through the filter query string parameter. The structure of a filter is a triplet of field operator and value separated with dots. More than one filter can be sent. The logical operator common to ALL filter criteria will be by default AND, and can be changed by using the "filterType=or" query string parameter. Each resource Data model description should specify if an attribute is a filtered field. (Operator: Description), (EQ: Equals), (NEQ: Not Equals), (GT: Greater Than), (LT: Less Then), (STARTSW: Starts With), (NSTARTSW: Not Starts With), (ENDSW: Ends With), (NENDSW: Not Ends With), (CONTAINS: Contains), (NCONTAINS: Not Contains), . filter_type(basestring): filterType query parameter. The logical operator common to ALL filter criteria will be by default AND, and can be changed by using the parameter. headers(dict): Dictionary of HTTP Headers to send with the Request . **query_parameters: Additional query parameters (provides support for parameters that may be added in the future). Returns: RestResponse: REST response with following properties: - headers(MyDict): response headers. - response(MyDict): response body as a MyDict object. Access the object's properties by using the dot notation or the bracket notation. - content(bytes): representation of the request's response - text(str): representation of the request's response Raises: TypeError: If the parameter types are incorrect. MalformedRequest: If the request body created is invalid. ApiError: If the Identity Services Engine cloud returns an error. This API allows the client to get a SXP connection by ID. Args: id(basestring): id path parameter. headers(dict): Dictionary of HTTP Headers to send with the Request . **query_parameters: Additional query parameters (provides support for parameters that may be added in the future). Returns: RestResponse: REST response with following properties: - headers(MyDict): response headers. - response(MyDict): response body as a MyDict object. Access the object's properties by using the dot notation or the bracket notation. - content(bytes): representation of the request's response - text(str): representation of the request's response Raises: TypeError: If the parameter types are incorrect. MalformedRequest: If the request body created is invalid. ApiError: If the Identity Services Engine cloud returns an error. This API allows the client to get all the SXP connections. Filter: [name, description] To search resources by using toDate column,follow the format: DD-MON-YY (Example:13-SEP-18) Day or Year:GET /ers/config/guestuser/?filter=toDate.CONTAINS.13 Month:GET /ers/config/guestuser/?filter=toDate.CONTAINS.SEP Date:GET /ers/config/guestuser/?filter=toDate.CONTAINS.13-SEP-18 Sorting: [name, description]. Args: page(int): page query parameter. Page number. size(int): size query parameter. Number of objects returned per page. sortasc(basestring): sortasc query parameter. sort asc. sortdsc(basestring): sortdsc query parameter. sort desc. filter(basestring, list, set, tuple): filter query parameter. **Simple filtering** should be available through the filter query string parameter. The structure of a filter is a triplet of field operator and value separated with dots. More than one filter can be sent. The logical operator common to ALL filter criteria will be by default AND, and can be changed by using the "filterType=or" query string parameter. Each resource Data model description should specify if an attribute is a filtered field. (Operator: Description), (EQ: Equals), (NEQ: Not Equals), (GT: Greater Than), (LT: Less Then), (STARTSW: Starts With), (NSTARTSW: Not Starts With), (ENDSW: Ends With), (NENDSW: Not Ends With), (CONTAINS: Contains), (NCONTAINS: Not Contains), . filter_type(basestring): filterType query parameter. The logical operator common to ALL filter criteria will be by default AND, and can be changed by using the parameter. headers(dict): Dictionary of HTTP Headers to send with the Request . **query_parameters: Additional query parameters (provides support for parameters that may be added in the future). Returns: Generator: A generator object containing the following object. + RestResponse: REST response with following properties: - headers(MyDict): response headers. - response(MyDict): response body as a MyDict object. Access the object's properties by using the dot notation or the bracket notation. - content(bytes): representation of the request's response - text(str): representation of the request's response Raises: TypeError: If the parameter types are incorrect. MalformedRequest: If the request body created is invalid. ApiError: If the Identity Services Engine cloud returns an error. This API helps to retrieve the version information related to the SXP connections. Args: headers(dict): Dictionary of HTTP Headers to send with the Request . **query_parameters: Additional query parameters (provides support for parameters that may be added in the future). Returns: RestResponse: REST response with following properties: - headers(MyDict): response headers. - response(MyDict): response body as a MyDict object. Access the object's properties by using the dot notation or the bracket notation. - content(bytes): representation of the request's response - text(str): representation of the request's response Raises: TypeError: If the parameter types are incorrect. MalformedRequest: If the request body created is invalid. ApiError: If the Identity Services Engine cloud returns an error. Alias for `monitor_bulk_status_sxp_connections <#ciscoisesdk. api.v3_0_0.sxp_connections. SxpConnections.monitor_bulk_status_sxp_connections>`_ This API allows the client to monitor the bulk request. Args: bulkid(basestring): bulkid path parameter. headers(dict): Dictionary of HTTP Headers to send with the Request . **query_parameters: Additional query parameters (provides support for parameters that may be added in the future). Returns: RestResponse: REST response with following properties: - headers(MyDict): response headers. - response(MyDict): response body as a MyDict object. Access the object's properties by using the dot notation or the bracket notation. - content(bytes): representation of the request's response - text(str): representation of the request's response Raises: TypeError: If the parameter types are incorrect. MalformedRequest: If the request body created is invalid. ApiError: If the Identity Services Engine cloud returns an error. Alias for `update_sxp_connections_by_id <#ciscoisesdk. api.v3_0_0.sxp_connections. SxpConnections.update_sxp_connections_by_id>`_ This API allows the client to update a SXP connection. Args: description(string): description, property of the request body. enabled(boolean): enabled, property of the request body. id(string): id, property of the request body. ip_address(string): ipAddress, property of the request body. sxp_mode(string): sxpMode, property of the request body. sxp_node(string): sxpNode, property of the request body. sxp_peer(string): sxpPeer, property of the request body. sxp_version(string): sxpVersion, property of the request body. sxp_vpn(string): sxpVpn, property of the request body. id(basestring): id path parameter. headers(dict): Dictionary of HTTP Headers to send with the Request . payload(dict): A JSON serializable Python object to send in the body of the Request. active_validation(bool): Enable/Disable payload validation. Defaults to True. **query_parameters: Additional query parameters (provides support for parameters that may be added in the future). Returns: RestResponse: REST response with following properties: - headers(MyDict): response headers. - response(MyDict): response body as a MyDict object. Access the object's properties by using the dot notation or the bracket notation. - content(bytes): representation of the request's response - text(str): representation of the request's response Raises: TypeError: If the parameter types are incorrect. MalformedRequest: If the request body created is invalid. ApiError: If the Identity Services Engine cloud returns an error. Cisco Identity Services Engine SXPConnections API wrapper. Copyright (c) 2021 Cisco and/or its affiliates. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -*- coding: utf-8 -*-
16,052
en
0.70265
# Copyright 2015, Google, 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. # """Tests for export_table_to_gcs.""" import json import os import unittest from bigquery.samples.streaming import run from tests import CloudBaseTest class TestStreaming(CloudBaseTest): def test_stream_row_to_bigquery(self): with open( os.path.join(self.resource_path, 'streamrows.json'), 'r') as rows_file: rows = json.load(rows_file) for result in run(self.constants['projectId'], self.constants['datasetId'], self.constants['newTableId'], rows, 5): self.assertIsNotNone(json.loads(result)) if __name__ == '__main__': unittest.main()
bigquery/tests/test_streaming.py
1,305
Tests for export_table_to_gcs. Copyright 2015, Google, 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.
582
en
0.847621
import RPi.GPIO as gpio import time class Tank: def __init__(self, name): self.name = name def init(self): gpio.setmode(gpio.BCM) gpio.setup(17, gpio.OUT) gpio.setup(22, gpio.OUT) gpio.setup(23, gpio.OUT) gpio.setup(24, gpio.OUT) def forward(self): self.init() gpio.output(17, True) #M1 FWD gpio.output(22, False) #M1 REV gpio.output(23, True) #M2 FWD gpio.output(24, False) #M2 REV #time.sleep(sec) #gpio.cleanup() def reverse(self, sec): self.init() gpio.output(17, False) gpio.output(22, True) gpio.output(23, False) gpio.output(24, True) time.sleep(sec) gpio.cleanup() def left(self, sec): self.init() gpio.output(17, False) gpio.output(22, True) gpio.output(23, False) gpio.output(24, False) time.sleep(sec) gpio.cleanup() def right(self, sec): self.init() gpio.output(17, False) gpio.output(22, False) gpio.output(23, False) gpio.output(24, True) time.sleep(sec) gpio.cleanup() def stop(self): self.init() gpio.output(17, False) gpio.output(22, False) gpio.output(23, False) gpio.output(24, False) gpio.cleanup() def init_test(self): self.forward(.05) time.sleep(.1) self.reverse(.05) time.sleep(.1) self.left(.05) time.sleep(.1) self.right(.05) print(f"Initialization Test Passed! {self.name} is ready to roll!")
tank_standalone.py
1,669
M1 FWDM1 REVM2 FWDM2 REVtime.sleep(sec)gpio.cleanup()
53
en
0.138989
import unittest from ebird.api.validation import is_subnational1 class IsSubnational1Tests(unittest.TestCase): """Tests for the is_subnational1 validation function.""" def test_is_subnational1(self): self.assertTrue(is_subnational1("US-NV")) def test_invalid_code_is_not_subnational1(self): self.assertFalse(is_subnational1("U")) self.assertFalse(is_subnational1("US-")) def test_country_is_not_subnational1(self): self.assertFalse(is_subnational1("US")) def test_subnational2_is_not_subnational1(self): self.assertFalse(is_subnational1("US-NV-VMT")) def test_location_is_not_subnational1(self): self.assertFalse(is_subnational1("L123456"))
tests/validation/test_is_subnational1.py
721
Tests for the is_subnational1 validation function.
50
en
0.475348
# Copyright (c) 2021 - present / Neuralmagic, Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import os import pytest import torch from torch.nn import Conv2d, Linear from sparseml.pytorch.optim import QuantizationModifier from tests.sparseml.pytorch.helpers import LinearNet, create_optim_sgd from tests.sparseml.pytorch.optim.test_modifier import ScheduledModifierTest from tests.sparseml.pytorch.helpers import ( # noqa isort:skip test_epoch, test_loss, test_steps_per_epoch, ) try: from torch import quantization as torch_quantization except Exception: torch_quantization = None QUANTIZATION_MODIFIERS = [ lambda: QuantizationModifier( start_epoch=0.0, disable_quantization_observer_epoch=2, freeze_bn_stats_epoch=3.0, ), lambda: QuantizationModifier(start_epoch=2.0, submodules=["seq"]), lambda: QuantizationModifier(start_epoch=2.0, submodules=["seq"]), ] def _is_valid_submodule(module_name, submodule_names): return module_name in submodule_names or any( module_name.startswith(name) for name in submodule_names ) def _is_quantiable_module(module): if isinstance(module, torch.quantization.FakeQuantize): return False return ( len(list(module.children())) > 0 or isinstance(module, Conv2d) or isinstance(module, Linear) ) def _test_qat_applied(modifier, model): # test quantization mods are applied if not modifier.submodules or modifier.submodules == [""]: assert hasattr(model, "qconfig") and model.qconfig is not None submodules = [""] for module in model.modules(): if _is_quantiable_module(module): assert hasattr(module, "qconfig") and module.qconfig == model.qconfig else: assert not hasattr(model, "qconfig") or model.qconfig is None submodules = modifier.submodules # check qconfig propagation for name, module in model.named_modules(): if _is_valid_submodule(name, submodules) and _is_quantiable_module(module): assert hasattr(module, "qconfig") and module.qconfig is not None @pytest.mark.skipif( os.getenv("NM_ML_SKIP_PYTORCH_TESTS", False), reason="Skipping pytorch tests", ) @pytest.mark.skipif( os.getenv("NM_ML_SKIP_PYTORCH_QUANT_TESTS", False), reason="Skipping pytorch torch quantization tests", ) @pytest.mark.skipif( torch_quantization is None, reason="torch quantization not available", ) @pytest.mark.parametrize("modifier_lambda", QUANTIZATION_MODIFIERS, scope="function") @pytest.mark.parametrize("model_lambda", [LinearNet], scope="function") @pytest.mark.parametrize("optim_lambda", [create_optim_sgd], scope="function") class TestQuantizationModifierImpl(ScheduledModifierTest): def test_lifecycle( self, modifier_lambda, model_lambda, optim_lambda, test_steps_per_epoch, # noqa: F811 ): modifier = modifier_lambda() model = model_lambda() optimizer = optim_lambda(model) self.initialize_helper(modifier, model) for epoch in range(int(modifier.start_epoch)): assert not modifier.update_ready(epoch, test_steps_per_epoch) update_epochs = [modifier.start_epoch] if modifier.disable_quantization_observer_epoch is not None: update_epochs.append(modifier.disable_quantization_observer_epoch) if modifier.freeze_bn_stats_epoch is not None: update_epochs.append(modifier.freeze_bn_stats_epoch) for epoch in update_epochs: assert modifier.update_ready(epoch, test_steps_per_epoch) # test update ready is still true after start epoch # even if quantization has not been applied yet assert modifier.update_ready(modifier.start_epoch + 0.1, test_steps_per_epoch) # test QAT setup if modifier.start_epoch > 0: for module in model.modules(): assert not hasattr(module, "qconfig") or module.qconfig is None else: # QAT should be applied _test_qat_applied(modifier, model) modifier.scheduled_update( model, optimizer, modifier.start_epoch, test_steps_per_epoch ) # test update ready is False after start epoch is applied, before diable epochs if ( len(update_epochs) == 1 or min(update_epochs[1:]) <= modifier.start_epoch + 1 ): # test epochs in 0.1 intervals for epoch_interval in range(10): epoch_interval *= 0.1 epoch = modifier.start_epoch + 0.1 * epoch_interval assert not modifier.update_ready(epoch, test_steps_per_epoch) _test_qat_applied(modifier, model) @pytest.mark.skipif( os.getenv("NM_ML_SKIP_PYTORCH_TESTS", False), reason="Skipping pytorch tests", ) @pytest.mark.skipif( os.getenv("NM_ML_SKIP_PYTORCH_QUANT_TESTS", False), reason="Skipping pytorch torch quantization tests", ) @pytest.mark.skipif( torch_quantization is None, reason="torch quantization not available", ) def test_quantization_modifier_yaml(): start_epoch = 0.0 submodules = ["block.0", "block.2"] model_fuse_fn_name = "fuse_module" disable_quantization_observer_epoch = 2.0 freeze_bn_stats_epoch = 3.0 yaml_str = """ !QuantizationModifier start_epoch: {start_epoch} submodules: {submodules} model_fuse_fn_name: {model_fuse_fn_name} disable_quantization_observer_epoch: {disable_quantization_observer_epoch} freeze_bn_stats_epoch: {freeze_bn_stats_epoch} """.format( start_epoch=start_epoch, submodules=submodules, model_fuse_fn_name=model_fuse_fn_name, disable_quantization_observer_epoch=disable_quantization_observer_epoch, freeze_bn_stats_epoch=freeze_bn_stats_epoch, ) yaml_modifier = QuantizationModifier.load_obj( yaml_str ) # type: QuantizationModifier serialized_modifier = QuantizationModifier.load_obj( str(yaml_modifier) ) # type: QuantizationModifier obj_modifier = QuantizationModifier( start_epoch=start_epoch, submodules=submodules, model_fuse_fn_name=model_fuse_fn_name, disable_quantization_observer_epoch=disable_quantization_observer_epoch, freeze_bn_stats_epoch=freeze_bn_stats_epoch, ) assert isinstance(yaml_modifier, QuantizationModifier) assert ( yaml_modifier.start_epoch == serialized_modifier.start_epoch == obj_modifier.start_epoch ) assert ( sorted(yaml_modifier.submodules) == sorted(serialized_modifier.submodules) == sorted(obj_modifier.submodules) ) assert ( yaml_modifier.model_fuse_fn_name == serialized_modifier.model_fuse_fn_name == obj_modifier.model_fuse_fn_name ) assert ( yaml_modifier.disable_quantization_observer_epoch == serialized_modifier.disable_quantization_observer_epoch == obj_modifier.disable_quantization_observer_epoch ) assert ( yaml_modifier.freeze_bn_stats_epoch == serialized_modifier.freeze_bn_stats_epoch == obj_modifier.freeze_bn_stats_epoch )
tests/sparseml/pytorch/optim/test_modifier_quantization.py
7,851
Copyright (c) 2021 - present / Neuralmagic, Inc. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. noqa isort:skip test quantization mods are applied check qconfig propagation noqa: F811 test update ready is still true after start epoch even if quantization has not been applied yet test QAT setup QAT should be applied test update ready is False after start epoch is applied, before diable epochs test epochs in 0.1 intervals type: QuantizationModifier type: QuantizationModifier
972
en
0.834052
# ============================================================================= # periscope-ps (blipp) # # Copyright (c) 2013-2016, Trustees of Indiana University, # All rights reserved. # # This software may be modified and distributed under the terms of the BSD # license. See the COPYING file for details. # # This software was created at the Indiana University Center for Research in # Extreme Scale Technologies (CREST). # ============================================================================= import time from unis_client import UNISInstance import settings import pprint from utils import merge_dicts from requests.exceptions import ConnectionError logger = settings.get_logger('conf') class ServiceConfigure(object): ''' ServiceConfigure is meant to be a generic class for any service which registers itself to, and gets configuration from UNIS. It was originally developed for BLiPP, but BLiPP specific features should be in the BlippConfigure class which extends ServiceConfigure. ''' def __init__(self, initial_config={}, node_id=None, urn=None): if not node_id: node_id = settings.UNIS_ID self.node_id = node_id self.urn = urn self.config = initial_config self.unis = UNISInstance(self.config) self.node_setup = False self.service_setup = False self.exponential_backoff = int(self.config["properties"]["configurations"]["unis_poll_interval"]) def initialize(self): try: r = self._setup_node(self.node_id) if not self.node_setup: return self._setup_service() except ConnectionError: return def refresh(self): try: r = self.unis.get("/services/" + self.config["id"]) if not r: logger.warn('refresh', msg="refresh failed") logger.warn('refresh', msg="re-enable service") self._setup_service() else: self.config = r if time.time() * 1e+6 + int(self.config['properties']['configurations']['unis_poll_interval']) * 1e+6 >\ self.config['ts'] + self.config['ttl'] * 1e+6: self._setup_service() self.exponential_backoff = int(self.config['properties']['configurations']['unis_poll_interval']) return self.exponential_backoff except ConnectionError: self.exponential_backoff = self.exponential_backoff * 2 return self.exponential_backoff def _setup_node(self, node_id): config = self.config props = self.config["properties"]["configurations"] logger.debug('_setup_node', config=pprint.pformat(config)) hostname = settings.HOSTNAME urn = settings.HOST_URN if not self.urn else self.urn if node_id: r = self.unis.get("/nodes/" + str(node_id)) if not r: logger.warn('_setup_node', msg="node id %s not found" % node_id) r = self.unis.post("/nodes", data={ "$schema": settings.SCHEMAS["nodes"], "name": hostname, "urn": urn, "id": node_id}) if not node_id: r = self.unis.get("/nodes?urn=" + urn) if r and len(r): r = r[0] logger.info('_setup_node', msg="Found node with our URN and id %s" % r["id"]) else: r = self.unis.post("/nodes", data={ "$schema": settings.SCHEMAS["nodes"], "name": hostname, "urn": urn}) if r: self.node_id = r["id"] if r: if isinstance(r, list): r = r[0] config["runningOn"] = { "href": r["selfRef"], "rel": "full"} self.node_setup = True else: config["runningOn"] = {"href": ""} logger.warn('_setup_node', msg="Unable to set up BLiPP node in UNIS at %s" % props["unis_url"]) def _setup_service(self): config = self.config props = self.config["properties"]["configurations"] logger.debug('_setup_service', config=pprint.pformat(config)) r = None if config.get("id", None): r = self.unis.get("/services/" + config["id"]) if not r: logger.warn('_setup_service', msg="service id not specified or not found "\ "unis instance ...querying for service") rlist = self.unis.get("/services?name=" + config.get("name", None) +\ "&runningOn.href=" + config["runningOn"]["href"] + "&limit=2") # loop over the returned services and find one that # doesn't return 410 see # https://uisapp2.iu.edu/jira-prd/browse/GEMINI-98 if rlist: for i in range(len(rlist)): r = self.unis.get('/services/' + rlist[i]["id"]) if r: logger.info('_setup_service', msg="%s service found with id %s" % (config["name"], r["id"])) break else: logger.warn('_setup_service', msg="no service found by id or querying "\ "...creating new service at %s" % props["unis_url"]) if isinstance(r, dict) and r: merge_dicts(config, r) # always update UNIS with the merged config r = None if config.get("id", None): r = self.unis.put("/services/" + config["id"], data=config) if not r: r = self.unis.post("/services", data=config) if r and isinstance(r, dict): merge_dicts(config, r) if r: self.service_setup = True else: logger.warn('_setup_service', msg="unable to set up service in UNIS") def get(self, key, default=None): try: return self.config[key] except KeyError: return default def __getitem__(self, key): ''' This allows an object which is an instance of this class to behave like a dictionary when queried with [] syntax ''' return self.config[key]
blipp/conf.py
6,602
ServiceConfigure is meant to be a generic class for any service which registers itself to, and gets configuration from UNIS. It was originally developed for BLiPP, but BLiPP specific features should be in the BlippConfigure class which extends ServiceConfigure. This allows an object which is an instance of this class to behave like a dictionary when queried with [] syntax ============================================================================= periscope-ps (blipp) Copyright (c) 2013-2016, Trustees of Indiana University, All rights reserved. This software may be modified and distributed under the terms of the BSD license. See the COPYING file for details. This software was created at the Indiana University Center for Research in Extreme Scale Technologies (CREST). ============================================================================= loop over the returned services and find one that doesn't return 410 see https://uisapp2.iu.edu/jira-prd/browse/GEMINI-98 always update UNIS with the merged config
1,030
en
0.863869
# --- # jupyter: # jupytext: # formats: ipynb,py # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.10.3 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- import pandas as pd from pyrfume.odorants import from_cids df1 = pd.read_csv('experiment1_comparisons.csv', header=0,index_col=0,names=['A','B','Similarity']) df1_cids = pd.read_csv('experiment1_cids.csv', index_col=0) df1_cids = df1_cids.applymap(lambda x:x.replace('[','').replace(']','').strip().replace(' ',',')) df1_cids df1.loc[:, ['A','B']] = df1.loc[:, ['A','B']].applymap(lambda x:df1_cids.loc[x]['Mixture Cids']) df1.head() df2 = pd.read_csv('experiment2_comparisons.csv', header=0,index_col=0,names=['A','B','Similarity']) df2_cids = pd.read_csv('experiment2_cids.csv', index_col=0) df2_cids = df2_cids.applymap(lambda x:x.replace('[','').replace(']','').strip().replace(' ',',')) df2_cids df2.loc[:, ['A','B']] = df2.loc[:, ['A','B']].applymap(lambda x:df2_cids.loc[x]['Mixture Cids']) df2.head() df3 = pd.read_csv('experiment3_comparisons.csv', header=0,index_col=0,names=['A','B','Similarity']) df3.head() df = pd.concat([df1, df2, df3]) df.to_csv('behavior-main.csv') cids1 = df1_cids['Mixture Cids'].apply(str.split, args=(',')).sum() cids2 = df2_cids['Mixture Cids'].apply(str.split, args=(',')).sum() cids3 = list(df3[['A', 'B']].values.ravel()) cids = cids1 + cids2 + cids3 cids = list(set(map(int, cids))) molecules_info = from_cids(cids) pd.DataFrame(molecules_info).set_index('CID').to_csv('molecules-info.csv')
snitz_2013/main.py
1,668
--- jupyter: jupytext: formats: ipynb,py text_representation: extension: .py format_name: light format_version: '1.5' jupytext_version: 1.10.3 kernelspec: display_name: Python 3 language: python name: python3 ---
260
en
0.461704
#!/usr/bin/env python # -*- coding: UTF-8 -*- """ Deals with K-mers and K-mer distribution from reads or genome """ from __future__ import print_function import os.path as op import sys import logging import math import numpy as np from collections import defaultdict from jcvi.graphics.base import ( plt, asciiplot, set_human_axis, savefig, markup, panel_labels, normalize_axes, set_ticklabels_arial, write_messages, ) from jcvi.formats.fasta import Fasta from jcvi.formats.base import BaseFile, must_open, get_number from jcvi.utils.cbook import thousands, percentage from jcvi.assembly.automaton import iter_project from jcvi.apps.grid import MakeManager from jcvi.apps.base import OptionParser, ActionDispatcher, sh, need_update, Popen, PIPE KMERYL, KSOAP, KALLPATHS = range(3) class KmerSpectrum(BaseFile): def __init__(self, histfile): self.load_data(histfile) def load_data(self, histfile): self.data = [] self.totalKmers = 0 self.hist = {} kformat = self.guess_format(histfile) kformats = ("Meryl", "Soap", "AllPaths") logging.debug("Guessed format: {0}".format(kformats[kformat])) fp = open(histfile) for rowno, row in enumerate(fp): if row[0] == "#": continue if kformat == KSOAP: K = rowno + 1 counts = int(row.strip()) else: # meryl histogram K, counts = row.split()[:2] K, counts = int(K), int(counts) Kcounts = K * counts self.totalKmers += Kcounts self.hist[K] = Kcounts self.data.append((K, counts)) def guess_format(self, histfile): # Guess the format of the Kmer histogram fp = open(histfile) for row in fp: if row.startswith("# 1:"): return KALLPATHS if len(row.split()) == 1: return KSOAP return KMERYL def get_xy(self, vmin=1, vmax=100): self.counts = sorted((a, b) for a, b in self.hist.items() if vmin <= a <= vmax) return zip(*self.counts) def analyze(self, ploidy=2, K=23, covmax=1000000): """ Analyze Kmer spectrum, calculations derived from allpathslg/src/kmers/KmerSpectra.cc """ from math import sqrt data = self.data kf_ceil = max(K for (K, c) in data) if kf_ceil > covmax: exceeds = sum(1 for (K, c) in data if K > covmax) logging.debug( "A total of {0} distinct K-mers appear > " "{1} times. Ignored ...".format(exceeds, covmax) ) kf_ceil = covmax nkf = kf_ceil + 1 a = [0] * nkf for kf, c in data: if kf > kf_ceil: continue a[kf] = c ndk = a # number of distinct kmers nk = [k * c for k, c in enumerate(a)] # number of kmers cndk = [0] * nkf # cumulative number of distinct kmers cnk = [0] * nkf # cumulative number of kmers for kf in range(1, nkf): cndk[kf] = cndk[kf - 1] + 0.5 * (ndk[kf - 1] + ndk[kf]) cnk[kf] = cnk[kf - 1] + 0.5 * (nk[kf - 1] + nk[kf]) # Separate kmer spectrum in 5 regions based on the kf # 1 ... kf_min1 : bad kmers with low frequency # kf_min1 ... kf_min2 : good kmers CN = 1/2 (SNPs) # kf_min2 ... kf_min3 : good kmers CN = 1 # kf_min3 ... kf_hi : good kmers CN > 1 (repetitive) # kf_hi ... inf : bad kmers with high frequency # min1: find first minimum _kf_min1 = 10 while _kf_min1 - 1 >= 2 and nk[_kf_min1 - 1] < nk[_kf_min1]: _kf_min1 -= 1 while _kf_min1 <= kf_ceil and nk[_kf_min1 + 1] < nk[_kf_min1]: _kf_min1 += 1 # max2: find absolute maximum mx2 above first minimum min1 _kf_max2 = _kf_min1 for kf in range(_kf_min1 + 1, int(0.8 * kf_ceil)): if nk[kf] > nk[_kf_max2]: _kf_max2 = kf # max2: resetting max2 for cases of very high polymorphism if ploidy == 2: ndk_half = ndk[_kf_max2 / 2] ndk_double = ndk[_kf_max2 * 2] if ndk_double > ndk_half: _kf_max2 *= 2 # max1: SNPs local maximum max1 as half global maximum max2 _kf_max1 = _kf_max2 / 2 # min2: SNPs local minimum min2 between max1 and max2 _kf_min2 = ( _kf_max1 * (2 * ndk[_kf_max1] + ndk[_kf_max2]) / (ndk[_kf_max1] + ndk[_kf_max2]) ) # min1: refine between min1 and max2/2 for kf in range(_kf_min1 + 1, _kf_max1): if nk[kf] < nk[_kf_min1]: _kf_min1 = kf # min3: not a minimum, really. upper edge of main peak _kf_min3 = _kf_max2 * 3 / 2 print("kfs:", _kf_min1, _kf_max1, _kf_min2, _kf_max2, _kf_min3, file=sys.stderr) self.min1 = _kf_min1 self.max1 = _kf_max1 self.min2 = _kf_min2 self.max2 = _kf_max2 self.min3 = _kf_min3 # Define maximum kf above which we neglect data _kf_hi = ( _kf_max2 * sqrt(4 * ndk[2 * _kf_max2] * _kf_max2) if 2 * _kf_max2 < len(ndk) else _kf_max2 * sqrt(4 * ndk[len(ndk) - 1] * _kf_max2) ) _kf_hi = int(_kf_hi) if _kf_hi > kf_ceil: _kf_hi = kf_ceil _nk_total = cnk[len(cnk) - 1] _nk_bad_low_kf = cnk[_kf_min1] _nk_good_uniq = cnk[_kf_min3] - cnk[_kf_min2] _nk_bad_high_kf = _nk_total - cnk[_kf_hi] _ndk_good_snp = cndk[_kf_min2] - cndk[_kf_min1] _ndk_good_uniq = cndk[_kf_min3] - cndk[_kf_min2] # kmer coverage C_k _kf_ave_uniq = _nk_good_uniq * 1.0 / _ndk_good_uniq _genome_size = (_nk_total - _nk_bad_low_kf - _nk_bad_high_kf) / _kf_ave_uniq _genome_size_unique = _ndk_good_uniq + _ndk_good_snp / 2 _genome_size_repetitive = _genome_size - _genome_size_unique _coverage = _nk_total / _genome_size if _genome_size else 0 # SNP rate estimation, assumes uniform distribution of SNPs over the # genome and accounts for the reduction in SNP kmer counts when # polymorphism is very high if ploidy == 2: _d_SNP = ( 1.0 / (1.0 - (1.0 - 0.5 * _ndk_good_snp / _genome_size) ** (1.0 / K)) if _ndk_good_snp > 0 else 1000000 ) G = int(_genome_size) G1 = int(_genome_size_unique) GR = int(_genome_size_repetitive) coverage = int(_coverage) m = "Kmer (K={0}) Spectrum Analysis\n".format(K) m += "Genome size estimate = {0}\n".format(thousands(G)) m += "Genome size estimate CN = 1 = {0} ({1})\n".format( thousands(G1), percentage(G1, G) ) m += "Genome size estimate CN > 1 = {0} ({1})\n".format( thousands(GR), percentage(GR, G) ) m += "Coverage estimate: {0} x\n".format(coverage) self.repetitive = "Repeats: {0} percent".format(GR * 100 / G) if ploidy == 2: d_SNP = int(_d_SNP) self.snprate = "SNP rate ~= 1/{0}".format(d_SNP) else: self.snprate = "SNP rate not computed (Ploidy = {0})".format(ploidy) m += self.snprate + "\n" self.genomesize = int(round(self.totalKmers * 1.0 / self.max2)) print(m, file=sys.stderr) class KMCComplex(object): def __init__(self, indices): self.indices = indices def write(self, outfile, filename="stdout", action="union"): assert action in ("union", "intersect") op = " + sum " if action == "union" else " * " fw = must_open(filename, "w") print("INPUT:", file=fw) ss = [] pad = len(str(len(self.indices))) for i, e in enumerate(self.indices): s = "s{0:0{1}d}".format(i + 1, pad) ss.append(s) print("{} = {}".format(s, e.rsplit(".", 1)[0]), file=fw) print("OUTPUT:", file=fw) print("{} = {}".format(outfile, op.join(ss)), file=fw) fw.close() def main(): actions = ( # K-mer counting ("jellyfish", "count kmers using `jellyfish`"), ("meryl", "count kmers using `meryl`"), ("kmc", "count kmers using `kmc`"), ("kmcop", "intersect or union kmc indices"), ("entropy", "calculate entropy for kmers from kmc dump"), ("bed", "map kmers on FASTA"), # K-mer histogram ("histogram", "plot the histogram based on meryl K-mer distribution"), ("multihistogram", "plot histogram across a set of K-mer sizes"), # These forms a pipeline to count K-mers for given FASTA seq ("dump", "convert FASTA sequences to list of K-mers"), ("bin", "serialize counts to bitarrays"), ("bincount", "count K-mers in the bin"), ("count", "run dump - jellyfish - bin - bincount in serial"), ("logodds", "compute log likelihood between two db"), ("model", "model kmer distribution given error rate"), ) p = ActionDispatcher(actions) p.dispatch(globals()) def entropy_score(kmer): """ Schmieder and Edwards. Quality control and preprocessing of metagenomic datasets. (2011) Bioinformatics https://academic.oup.com/bioinformatics/article/27/6/863/236283/Quality-control-and-preprocessing-of-metagenomic """ l = len(kmer) - 2 k = l if l < 64 else 64 counts = defaultdict(int) for i in range(l): trinuc = kmer[i : i + 3] counts[trinuc] += 1 logk = math.log(k) res = 0 for k, v in counts.items(): f = v * 1.0 / l res += f * math.log(f) / logk return res * -100 def entropy(args): """ %prog entropy kmc_dump.out kmc_dump.out contains two columns: AAAAAAAAAAAGAAGAAAGAAA 34 """ p = OptionParser(entropy.__doc__) p.add_option( "--threshold", default=0, type="int", help="Complexity needs to be above" ) opts, args = p.parse_args(args) if len(args) != 1: sys.exit(not p.print_help()) (kmc_out,) = args fp = open(kmc_out) for row in fp: kmer, count = row.split() score = entropy_score(kmer) if score >= opts.threshold: print(" ".join((kmer, count, "{:.2f}".format(score)))) def bed(args): """ %prog bed fastafile kmer.dump.txt Map kmers on FASTA. """ from jcvi.formats.fasta import rc, parse_fasta p = OptionParser(bed.__doc__) opts, args = p.parse_args(args) if len(args) != 2: sys.exit(not p.print_help()) fastafile, dumpfile = args fp = open(dumpfile) KMERS = set() for row in fp: kmer = row.split()[0] kmer_rc = rc(kmer) KMERS.add(kmer) KMERS.add(kmer_rc) K = len(kmer) logging.debug("Imported {} {}-mers".format(len(KMERS), K)) for name, seq in parse_fasta(fastafile): name = name.split()[0] for i in range(len(seq) - K): if i % 5000000 == 0: print("{}:{}".format(name, i), file=sys.stderr) kmer = seq[i : i + K] if kmer in KMERS: print("\t".join(str(x) for x in (name, i, i + K, kmer))) def kmcop(args): """ %prog kmcop *.kmc_suf Intersect or union kmc indices. """ p = OptionParser(kmcop.__doc__) p.add_option( "--action", choices=("union", "intersect"), default="union", help="Action" ) p.add_option("-o", default="results", help="Output name") opts, args = p.parse_args(args) if len(args) < 2: sys.exit(not p.print_help()) indices = args ku = KMCComplex(indices) ku.write(opts.o, action=opts.action) def kmc(args): """ %prog kmc folder Run kmc3 on Illumina reads. """ p = OptionParser(kmc.__doc__) p.add_option("-k", default=21, type="int", help="Kmer size") p.add_option( "--ci", default=2, type="int", help="Exclude kmers with less than ci counts" ) p.add_option("--cs", default=2, type="int", help="Maximal value of a counter") p.add_option( "--cx", default=None, type="int", help="Exclude kmers with more than cx counts" ) p.add_option( "--single", default=False, action="store_true", help="Input is single-end data, only one FASTQ/FASTA", ) p.add_option( "--fasta", default=False, action="store_true", help="Input is FASTA instead of FASTQ", ) p.set_cpus() opts, args = p.parse_args(args) if len(args) != 1: sys.exit(not p.print_help()) (folder,) = args K = opts.k n = 1 if opts.single else 2 pattern = ( "*.fa,*.fa.gz,*.fasta,*.fasta.gz" if opts.fasta else "*.fq,*.fq.gz,*.fastq,*.fastq.gz" ) mm = MakeManager() for p, pf in iter_project(folder, pattern=pattern, n=n, commonprefix=False): pf = pf.split("_")[0] + ".ms{}".format(K) infiles = pf + ".infiles" fw = open(infiles, "w") print("\n".join(p), file=fw) fw.close() cmd = "kmc -k{} -m64 -t{}".format(K, opts.cpus) cmd += " -ci{} -cs{}".format(opts.ci, opts.cs) if opts.cx: cmd += " -cx{}".format(opts.cx) if opts.fasta: cmd += " -fm" cmd += " @{} {} .".format(infiles, pf) outfile = pf + ".kmc_suf" mm.add(p, outfile, cmd) mm.write() def meryl(args): """ %prog meryl folder Run meryl on Illumina reads. """ p = OptionParser(meryl.__doc__) p.add_option("-k", default=19, type="int", help="Kmer size") p.set_cpus() opts, args = p.parse_args(args) if len(args) != 1: sys.exit(not p.print_help()) (folder,) = args K = opts.k cpus = opts.cpus mm = MakeManager() for p, pf in iter_project(folder): cmds = [] mss = [] for i, ip in enumerate(p): ms = "{}{}.ms{}".format(pf, i + 1, K) mss.append(ms) cmd = "meryl -B -C -m {} -threads {}".format(K, cpus) cmd += " -s {} -o {}".format(ip, ms) cmds.append(cmd) ams, bms = mss pms = "{}.ms{}".format(pf, K) cmd = "meryl -M add -s {} -s {} -o {}".format(ams, bms, pms) cmds.append(cmd) cmd = "rm -f {}.mcdat {}.mcidx {}.mcdat {}.mcidx".format(ams, ams, bms, bms) cmds.append(cmd) mm.add(p, pms + ".mcdat", cmds) mm.write() def model(args): """ %prog model erate Model kmer distribution given error rate. See derivation in FIONA paper: <http://bioinformatics.oxfordjournals.org/content/30/17/i356.full> """ from scipy.stats import binom, poisson p = OptionParser(model.__doc__) p.add_option("-k", default=23, type="int", help="Kmer size") p.add_option("--cov", default=50, type="int", help="Expected coverage") opts, args = p.parse_args(args) if len(args) != 1: sys.exit(not p.print_help()) (erate,) = args erate = float(erate) cov = opts.cov k = opts.k xy = [] # Range include c although it is unclear what it means to have c=0 for c in range(0, cov * 2 + 1): Prob_Yk = 0 for i in range(k + 1): # Probability of having exactly i errors pi_i = binom.pmf(i, k, erate) # Expected coverage of kmer with exactly i errors mu_i = cov * (erate / 3) ** i * (1 - erate) ** (k - i) # Probability of seeing coverage of c Prob_Yk_i = poisson.pmf(c, mu_i) # Sum i over 0, 1, ... up to k errors Prob_Yk += pi_i * Prob_Yk_i xy.append((c, Prob_Yk)) x, y = zip(*xy) asciiplot(x, y, title="Model") def logodds(args): """ %prog logodds cnt1 cnt2 Compute log likelihood between two db. """ from math import log from jcvi.formats.base import DictFile p = OptionParser(logodds.__doc__) opts, args = p.parse_args(args) if len(args) != 2: sys.exit(not p.print_help()) cnt1, cnt2 = args d = DictFile(cnt2) fp = open(cnt1) for row in fp: scf, c1 = row.split() c2 = d[scf] c1, c2 = float(c1), float(c2) c1 += 1 c2 += 1 score = int(100 * (log(c1) - log(c2))) print("{0}\t{1}".format(scf, score)) def get_K(jfdb): """ Infer K from jellyfish db. """ j = jfdb.rsplit("_", 1)[0].rsplit("-", 1)[-1] assert j[0] == "K" return int(j[1:]) def count(args): """ %prog count fastafile jf.db Run dump - jellyfish - bin - bincount in serial. """ from bitarray import bitarray p = OptionParser(count.__doc__) opts, args = p.parse_args(args) if len(args) != 2: sys.exit(not p.print_help()) fastafile, jfdb = args K = get_K(jfdb) cmd = "jellyfish query {0} -C | cut -d' ' -f 2".format(jfdb) t = must_open("tmp", "w") proc = Popen(cmd, stdin=PIPE, stdout=t) t.flush() f = Fasta(fastafile, lazy=True) for name, rec in f.iteritems_ordered(): kmers = list(make_kmers(rec.seq, K)) print("\n".join(kmers), file=proc.stdin) proc.stdin.close() logging.debug(cmd) proc.wait() a = bitarray() binfile = ".".join((fastafile, jfdb, "bin")) fw = open(binfile, "w") t.seek(0) for row in t: c = row.strip() a.append(int(c)) a.tofile(fw) logging.debug("Serialize {0} bits to `{1}`.".format(len(a), binfile)) fw.close() sh("rm {0}".format(t.name)) logging.debug( "Shared K-mers (K={0}) between `{1}` and `{2}` written to `{3}`.".format( K, fastafile, jfdb, binfile ) ) cntfile = ".".join((fastafile, jfdb, "cnt")) bincount([fastafile, binfile, "-o", cntfile, "-K {0}".format(K)]) logging.debug("Shared K-mer counts written to `{0}`.".format(cntfile)) def bincount(args): """ %prog bincount fastafile binfile Count K-mers in the bin. """ from bitarray import bitarray from jcvi.formats.sizes import Sizes p = OptionParser(bincount.__doc__) p.add_option("-K", default=23, type="int", help="K-mer size") p.set_outfile() opts, args = p.parse_args(args) if len(args) != 2: sys.exit(not p.print_help()) fastafile, binfile = args K = opts.K fp = open(binfile) a = bitarray() a.fromfile(fp) f = Sizes(fastafile) tsize = 0 fw = must_open(opts.outfile, "w") for name, seqlen in f.iter_sizes(): ksize = seqlen - K + 1 b = a[tsize : tsize + ksize] bcount = b.count() print("\t".join(str(x) for x in (name, bcount)), file=fw) tsize += ksize def bin(args): """ %prog bin filename filename.bin Serialize counts to bitarrays. """ from bitarray import bitarray p = OptionParser(bin.__doc__) opts, args = p.parse_args(args) if len(args) != 2: sys.exit(not p.print_help()) inp, outp = args fp = must_open(inp) fw = must_open(outp, "w") a = bitarray() for row in fp: c = row.split()[-1] a.append(int(c)) a.tofile(fw) fw.close() def make_kmers(seq, K): seq = str(seq).upper().replace("N", "A") seqlen = len(seq) for i in range(seqlen - K + 1): yield seq[i : i + K] def dump(args): """ %prog dump fastafile Convert FASTA sequences to list of K-mers. """ p = OptionParser(dump.__doc__) p.add_option("-K", default=23, type="int", help="K-mer size") p.set_outfile() opts, args = p.parse_args(args) if len(args) != 1: sys.exit(not p.print_help()) (fastafile,) = args K = opts.K fw = must_open(opts.outfile, "w") f = Fasta(fastafile, lazy=True) for name, rec in f.iteritems_ordered(): kmers = list(make_kmers(rec.seq, K)) print("\n".join(kmers), file=fw) fw.close() def jellyfish(args): """ %prog jellyfish [*.fastq|*.fasta] Run jellyfish to dump histogram to be used in kmer.histogram(). """ from jcvi.apps.base import getfilesize from jcvi.utils.cbook import human_size p = OptionParser(jellyfish.__doc__) p.add_option("-K", default=23, type="int", help="K-mer size") p.add_option( "--coverage", default=40, type="int", help="Expected sequence coverage", ) p.add_option("--prefix", default="jf", help="Database prefix") p.add_option( "--nohist", default=False, action="store_true", help="Do not print histogram", ) p.set_home("jellyfish") p.set_cpus() opts, args = p.parse_args(args) if len(args) < 1: sys.exit(not p.print_help()) fastqfiles = args K = opts.K coverage = opts.coverage totalfilesize = sum(getfilesize(x) for x in fastqfiles) fq = fastqfiles[0] pf = opts.prefix gzip = fq.endswith(".gz") hashsize = totalfilesize / coverage logging.debug( "Total file size: {0}, hashsize (-s): {1}".format( human_size(totalfilesize, a_kilobyte_is_1024_bytes=True), hashsize ) ) jfpf = "{0}-K{1}".format(pf, K) jfdb = jfpf fastqfiles = " ".join(fastqfiles) jfcmd = op.join(opts.jellyfish_home, "jellyfish") cmd = jfcmd cmd += " count -t {0} -C -o {1}".format(opts.cpus, jfpf) cmd += " -s {0} -m {1}".format(hashsize, K) if gzip: cmd = "gzip -dc {0} | ".format(fastqfiles) + cmd + " /dev/fd/0" else: cmd += " " + fastqfiles if need_update(fastqfiles, jfdb): sh(cmd) if opts.nohist: return jfhisto = jfpf + ".histogram" cmd = jfcmd + " histo -t 64 {0} -o {1}".format(jfdb, jfhisto) if need_update(jfdb, jfhisto): sh(cmd) def merylhistogram(merylfile): """ Run meryl to dump histogram to be used in kmer.histogram(). The merylfile are the files ending in .mcidx or .mcdat. """ pf, sf = op.splitext(merylfile) outfile = pf + ".histogram" if need_update(merylfile, outfile): cmd = "meryl -Dh -s {0}".format(pf) sh(cmd, outfile=outfile) return outfile def multihistogram(args): """ %prog multihistogram *.histogram species Plot the histogram based on a set of K-mer hisotograms. The method is based on Star et al.'s method (Atlantic Cod genome paper). """ p = OptionParser(multihistogram.__doc__) p.add_option("--kmin", default=15, type="int", help="Minimum K-mer size, inclusive") p.add_option("--kmax", default=30, type="int", help="Maximum K-mer size, inclusive") p.add_option("--vmin", default=2, type="int", help="Minimum value, inclusive") p.add_option("--vmax", default=100, type="int", help="Maximum value, inclusive") opts, args, iopts = p.set_image_options(args, figsize="10x5", dpi=300) if len(args) < 1: sys.exit(not p.print_help()) histfiles = args[:-1] species = args[-1] fig = plt.figure(1, (iopts.w, iopts.h)) root = fig.add_axes([0, 0, 1, 1]) A = fig.add_axes([0.08, 0.12, 0.38, 0.76]) B = fig.add_axes([0.58, 0.12, 0.38, 0.76]) lines = [] legends = [] genomesizes = [] for histfile in histfiles: ks = KmerSpectrum(histfile) x, y = ks.get_xy(opts.vmin, opts.vmax) K = get_number(op.basename(histfile).split(".")[0].split("-")[-1]) if not opts.kmin <= K <= opts.kmax: continue (line,) = A.plot(x, y, "-", lw=1) lines.append(line) legends.append("K = {0}".format(K)) ks.analyze(K=K) genomesizes.append((K, ks.genomesize / 1e6)) leg = A.legend(lines, legends, shadow=True, fancybox=True) leg.get_frame().set_alpha(0.5) title = "{0} genome K-mer histogram".format(species) A.set_title(markup(title)) xlabel, ylabel = "Coverage (X)", "Counts" A.set_xlabel(xlabel) A.set_ylabel(ylabel) set_human_axis(A) title = "{0} genome size estimate".format(species) B.set_title(markup(title)) x, y = zip(*genomesizes) B.plot(x, y, "ko", mfc="w") t = np.linspace(opts.kmin - 0.5, opts.kmax + 0.5, 100) p = np.poly1d(np.polyfit(x, y, 2)) B.plot(t, p(t), "r:") xlabel, ylabel = "K-mer size", "Estimated genome size (Mb)" B.set_xlabel(xlabel) B.set_ylabel(ylabel) set_ticklabels_arial(B) labels = ((0.04, 0.96, "A"), (0.54, 0.96, "B")) panel_labels(root, labels) normalize_axes(root) imagename = species + ".multiK.pdf" savefig(imagename, dpi=iopts.dpi, iopts=iopts) def histogram(args): """ %prog histogram meryl.histogram species K Plot the histogram based on meryl K-mer distribution, species and N are only used to annotate the graphic. """ p = OptionParser(histogram.__doc__) p.add_option( "--vmin", dest="vmin", default=1, type="int", help="minimum value, inclusive", ) p.add_option( "--vmax", dest="vmax", default=100, type="int", help="maximum value, inclusive", ) p.add_option( "--pdf", default=False, action="store_true", help="Print PDF instead of ASCII plot", ) p.add_option( "--coverage", default=0, type="int", help="Kmer coverage [default: auto]" ) p.add_option( "--nopeaks", default=False, action="store_true", help="Do not annotate K-mer peaks", ) opts, args = p.parse_args(args) if len(args) != 3: sys.exit(not p.print_help()) histfile, species, N = args ascii = not opts.pdf peaks = not opts.nopeaks N = int(N) if histfile.rsplit(".", 1)[-1] in ("mcdat", "mcidx"): logging.debug("CA kmer index found") histfile = merylhistogram(histfile) ks = KmerSpectrum(histfile) ks.analyze(K=N) Total_Kmers = int(ks.totalKmers) coverage = opts.coverage Kmer_coverage = ks.max2 if not coverage else coverage Genome_size = int(round(Total_Kmers * 1.0 / Kmer_coverage)) Total_Kmers_msg = "Total {0}-mers: {1}".format(N, thousands(Total_Kmers)) Kmer_coverage_msg = "{0}-mer coverage: {1}".format(N, Kmer_coverage) Genome_size_msg = "Estimated genome size: {0:.1f}Mb".format(Genome_size / 1e6) Repetitive_msg = ks.repetitive SNPrate_msg = ks.snprate for msg in (Total_Kmers_msg, Kmer_coverage_msg, Genome_size_msg): print(msg, file=sys.stderr) x, y = ks.get_xy(opts.vmin, opts.vmax) title = "{0} {1}-mer histogram".format(species, N) if ascii: asciiplot(x, y, title=title) return Genome_size plt.figure(1, (6, 6)) plt.plot(x, y, "g-", lw=2, alpha=0.5) ax = plt.gca() if peaks: t = (ks.min1, ks.max1, ks.min2, ks.max2, ks.min3) tcounts = [(x, y) for x, y in ks.counts if x in t] if tcounts: x, y = zip(*tcounts) tcounts = dict(tcounts) plt.plot(x, y, "ko", lw=2, mec="k", mfc="w") ax.text(ks.max1, tcounts[ks.max1], "SNP peak", va="top") ax.text(ks.max2, tcounts[ks.max2], "Main peak") messages = [ Total_Kmers_msg, Kmer_coverage_msg, Genome_size_msg, Repetitive_msg, SNPrate_msg, ] write_messages(ax, messages) ymin, ymax = ax.get_ylim() ymax = ymax * 7 / 6 ax.set_title(markup(title)) ax.set_ylim((ymin, ymax)) xlabel, ylabel = "Coverage (X)", "Counts" ax.set_xlabel(xlabel) ax.set_ylabel(ylabel) set_human_axis(ax) imagename = histfile.split(".")[0] + ".pdf" savefig(imagename, dpi=100) return Genome_size if __name__ == "__main__": main()
jcvi/assembly/kmer.py
27,844
Analyze Kmer spectrum, calculations derived from allpathslg/src/kmers/KmerSpectra.cc %prog bed fastafile kmer.dump.txt Map kmers on FASTA. %prog bin filename filename.bin Serialize counts to bitarrays. %prog bincount fastafile binfile Count K-mers in the bin. %prog count fastafile jf.db Run dump - jellyfish - bin - bincount in serial. %prog dump fastafile Convert FASTA sequences to list of K-mers. %prog entropy kmc_dump.out kmc_dump.out contains two columns: AAAAAAAAAAAGAAGAAAGAAA 34 Schmieder and Edwards. Quality control and preprocessing of metagenomic datasets. (2011) Bioinformatics https://academic.oup.com/bioinformatics/article/27/6/863/236283/Quality-control-and-preprocessing-of-metagenomic Infer K from jellyfish db. %prog histogram meryl.histogram species K Plot the histogram based on meryl K-mer distribution, species and N are only used to annotate the graphic. %prog jellyfish [*.fastq|*.fasta] Run jellyfish to dump histogram to be used in kmer.histogram(). %prog kmc folder Run kmc3 on Illumina reads. %prog kmcop *.kmc_suf Intersect or union kmc indices. %prog logodds cnt1 cnt2 Compute log likelihood between two db. %prog meryl folder Run meryl on Illumina reads. Run meryl to dump histogram to be used in kmer.histogram(). The merylfile are the files ending in .mcidx or .mcdat. %prog model erate Model kmer distribution given error rate. See derivation in FIONA paper: <http://bioinformatics.oxfordjournals.org/content/30/17/i356.full> %prog multihistogram *.histogram species Plot the histogram based on a set of K-mer hisotograms. The method is based on Star et al.'s method (Atlantic Cod genome paper). Deals with K-mers and K-mer distribution from reads or genome !/usr/bin/env python -*- coding: UTF-8 -*- meryl histogram Guess the format of the Kmer histogram number of distinct kmers number of kmers cumulative number of distinct kmers cumulative number of kmers Separate kmer spectrum in 5 regions based on the kf 1 ... kf_min1 : bad kmers with low frequency kf_min1 ... kf_min2 : good kmers CN = 1/2 (SNPs) kf_min2 ... kf_min3 : good kmers CN = 1 kf_min3 ... kf_hi : good kmers CN > 1 (repetitive) kf_hi ... inf : bad kmers with high frequency min1: find first minimum max2: find absolute maximum mx2 above first minimum min1 max2: resetting max2 for cases of very high polymorphism max1: SNPs local maximum max1 as half global maximum max2 min2: SNPs local minimum min2 between max1 and max2 min1: refine between min1 and max2/2 min3: not a minimum, really. upper edge of main peak Define maximum kf above which we neglect data kmer coverage C_k SNP rate estimation, assumes uniform distribution of SNPs over the genome and accounts for the reduction in SNP kmer counts when polymorphism is very high K-mer counting K-mer histogram These forms a pipeline to count K-mers for given FASTA seq Range include c although it is unclear what it means to have c=0 Probability of having exactly i errors Expected coverage of kmer with exactly i errors Probability of seeing coverage of c Sum i over 0, 1, ... up to k errors
3,102
en
0.744633
import serial import time import datetime import logging from recordtype import recordtype from enum import IntEnum, unique from datetime import timedelta import _thread import readchar import os import sys import threading from collections import deque import shutil import binascii START_CHAR = '02' #START_BUF = '2a2a2a' # this is not really a buffer BAUD_RATE = 1000000 #921600 #1000000 SERIAL_PORT = "/dev/ttyS0" #"/dev/ttyACM0" #"/dev/ttyS0" if len(sys.argv)>1: SERIAL_PORT=sys.argv[1] if len(sys.argv)>2: BAUD_RATE=int(sys.argv[2]) logfolderpath = os.path.dirname(os.path.realpath(__file__))+'/log/' if not os.path.exists(logfolderpath): try: os.mkdir(logfolderpath) net.addPrint("Log directory not found.") net.addPrint("%s Created " % logfolderpath) except Exception as e: net.addPrint("Can't get the access to the log folder %s." % logfolderpath) net.addPrint("Exception: %s" % str(e)) endchar = 0x0a SER_END_CHAR = endchar.to_bytes(1, byteorder='big', signed=False) SINGLE_NODE_REPORT_SIZE = 9 #must be the same as in common/inc/contraints.h MAX_REPORTS_PER_PACKET = 22 #must be the same as in common/inc/contraints.h MAX_PACKET_PAYLOAD = SINGLE_NODE_REPORT_SIZE*MAX_REPORTS_PER_PACKET MAX_BEACONS = 100 MAX_ONGOING_SEQUENCES = 10 MAX_TRICKLE_C_VALUE = 256 ser = serial.Serial() ser.port = SERIAL_PORT ser.baudrate = BAUD_RATE ser.timeout = 100 MessageSequence = recordtype("MessageSequence", "timestamp,nodeid,lastPktnum,sequenceSize,datacounter," "datalist,latestTime") messageSequenceList = [] ContactData = recordtype("ContactData", "nodeid lastRSSI maxRSSI pktCounter") firstMessageInSeq = False NodeDropInfo = recordtype("NodeDropInfo", "nodeid, lastpkt") nodeDropInfoList = [] ActiveNodes = [] deliverCounter = 0 dropCounter = 0 headerDropCounter = 0 defragmentationCounter = 0 # Timeout variables previousTimeTimeout = 0 currentTime = 0 timeoutInterval = 300 timeoutTime = 60 previousTimePing = 0 pingInterval = 115 btPreviousTime = 0 btToggleInterval = 1800 btToggleBool = True NODE_TIMEOUT_S = 60*10 NETWORK_PERIODIC_CHECK_INTERVAL = 2 CLEAR_CONSOLE = True # Loggers printVerbosity = 10 LOG_LEVEL = logging.DEBUG formatter = logging.Formatter('%(asctime)s %(levelname)s %(message)s', datefmt='%Y/%m/%d %H:%M:%S') timestr = time.strftime("%Y%m%d-%H%M%S") nameConsoleLog = "consoleLogger" filenameConsoleLog = timestr + "-console.log" fullpathConsoleLog = logfolderpath+filenameConsoleLog consolloghandler = logging.FileHandler(fullpathConsoleLog) consolloghandler.setFormatter(formatter) consoleLogger = logging.getLogger(nameConsoleLog) consoleLogger.setLevel(LOG_LEVEL) consoleLogger.addHandler(consolloghandler) nameUARTLog = "UARTLogger" filenameUARTLog = timestr + "-UART.log" fullpathUARTLog = logfolderpath+filenameUARTLog handler = logging.FileHandler(fullpathUARTLog) handler.setFormatter(formatter) UARTLogger = logging.getLogger(nameUARTLog) UARTLogger.setLevel(LOG_LEVEL) UARTLogger.addHandler(handler) nameContactLog = "contactLogger" filenameContactLog = timestr + "-contact.log" fullpathContactLog = logfolderpath+filenameContactLog contactlog_handler = logging.FileHandler(fullpathContactLog) contact_formatter = logging.Formatter('%(message)s') contactlog_handler.setFormatter(contact_formatter) contactLogger = logging.getLogger(nameContactLog) contactLogger.setLevel(LOG_LEVEL) contactLogger.addHandler(contactlog_handler) nameErrorLog = "errorLogger" filenameErrorLog = timestr + "-errorLogger.log" fullpathErrorLog = logfolderpath+filenameErrorLog errorlog_handler = logging.FileHandler(fullpathErrorLog) errorlog_formatter= logging.Formatter('%(message)s') errorlog_handler.setFormatter(errorlog_formatter) errorLogger = logging.getLogger(nameErrorLog) errorLogger.setLevel(LOG_LEVEL) errorLogger.addHandler(errorlog_handler) class Network(object): def __init__(self): self.__nodes = [] threading.Timer(NETWORK_PERIODIC_CHECK_INTERVAL,self.__periodicNetworkCheck).start() self.__consoleBuffer = deque() self.console_queue_lock = threading.Lock() self.__lastNetworkPrint=float(time.time()) self.__netMaxTrickle=0 self.__netMinTrickle=MAX_TRICKLE_C_VALUE self.__expTrickle=0 self.__uartErrors=0 self.__trickleQueue = deque() self.showHelp=False def getNode(self, label): for n in self.__nodes: if n.name == label: return n return None def addNode(self,n): self.__nodes.append(n) if len(self.__nodes) == 1: self.__expTrickle=n.lastTrickleCount def removeNode(self,label): n = self.getNode(label) if n != None: self.__nodes.remove(n) def removeNode(self,n): self.__nodes.remove(n) def __trickleCheck(self): for n in self.__nodes: #with n.lock: #self.addPrint("Node "+ n.name + "lastTrickleCount: " + str(n.lastTrickleCount)) if n==self.__nodes[0]: self.__netMaxTrickle = n.lastTrickleCount self.__netMinTrickle = n.lastTrickleCount if n.lastTrickleCount > self.__netMaxTrickle or ( n.lastTrickleCount == 0 and self.__netMaxTrickle>=(MAX_TRICKLE_C_VALUE-1) ): self.__netMaxTrickle = n.lastTrickleCount if n.lastTrickleCount < self.__netMinTrickle or ( n.lastTrickleCount >= (MAX_TRICKLE_C_VALUE-1) and self.__netMinTrickle==0 ): self.__netMinTrickle = n.lastTrickleCount #todo: it seems that this does't work. The __netMinTrickle goes up before all the nodes have sent their new values, sometimes it is __netMaxTrickle that doesn't update as soon the first new value arrives.. if self.__netMinTrickle == self.__netMaxTrickle and self.__netMaxTrickle == self.__expTrickle: return True else: return False def sendNewTrickle(self, message,forced=False): if forced: self.__trickleQueue.clear() send_serial_msg(message) net.addPrint("[APPLICATION] Trickle message: 0x {0} force send".format((message).hex())) else: if self.__trickleCheck(): self.__expTrickle = (self.__netMaxTrickle + 1)%MAX_TRICKLE_C_VALUE send_serial_msg(message) net.addPrint("[APPLICATION] Trickle message: 0x {0} sent".format((message).hex())) else: self.__trickleQueue.append(message) self.addPrint("[APPLICATION] Trickle message: 0x {0} queued".format((message).hex())) def __periodicNetworkCheck(self): threading.Timer(NETWORK_PERIODIC_CHECK_INTERVAL,self.__periodicNetworkCheck).start() nodes_removed = False; for n in self.__nodes: if n.getLastMessageElapsedTime() > NODE_TIMEOUT_S and n.online: if printVerbosity > 2: self.addPrint("[APPLICATION] Node "+ n.name +" timed out. Elasped time: %.2f" %n.getLastMessageElapsedTime() +" Removing it from the network.") #self.removeNode(n) n.online=False nodes_removed = True #self.__trickleCheck() if nodes_removed: self.__trickleCheck() self.printNetworkStatus() def printNetworkStatus(self): if(float(time.time()) - self.__lastNetworkPrint < 0.2): #this is to avoid too fast call to this function return __lastNetworkPrint = float(time.time()) netSize = len(self.__nodes) if CLEAR_CONSOLE: cls() print("|------------------------------------------------------------------------------|") print("|--------------------------| Network size %3s errors: %4s |------------------|" %(str(netSize), self.__uartErrors)) print("|------------| Trickle: min %3d; max %3d; exp %3d; queue size %2d |-------------|" %(self.__netMinTrickle, self.__netMaxTrickle, self.__expTrickle, len(self.__trickleQueue))) print("|------------------------------------------------------------------------------|") print("| NodeID | Battery | Last | Trick | #BT |") print("| | Volt SoC Capacty Cons Temp | seen[s] | Count | Rep |") #print("| | | | | |") for n in self.__nodes: n.printNodeInfo() #print("| | | | | |") print("|------------------------------------------------------------------------------|") if self.showHelp: print("| AVAILABLE COMMANDS:") print("| key command\n|") print("| 1 request ping\n" "| 2 enable bluetooth\n" "| 3 disable bluetooth\n" "| 4 bt_def\n" "| 5 bt_with_params\n" "| 6 enable battery info\n" "| 7 disable battery info\n" "| 8 reset nordic\n" "| 9 set time between sends\n" "| >9 set keep alive interval in seconds") else: print("| h+enter : Show available commands |") print("|------------------------------------------------------------------------------|") print("|------------------| CONSOLE |------------------|") print("|------------------------------------------------------------------------------|") terminalSize = shutil.get_terminal_size(([80,20])) if net.showHelp: availableLines = terminalSize[1] - (24 + len(self.__nodes)) else: availableLines = terminalSize[1] - (12 + len(self.__nodes)) while( (len(self.__consoleBuffer) > availableLines) and self.__consoleBuffer): with self.console_queue_lock: self.__consoleBuffer.popleft() with self.console_queue_lock: for l in self.__consoleBuffer: print(l) def processKeepAliveMessage(self, label, trickleCount, batteryVoltage, capacity): n = self.getNode(label) if n != None: n.updateTrickleCount(trickleCount) n.updateBatteryVoltage(batteryVoltage) n.updateBatteryCapacity(capacity) n.online=True else: n=Node(label, trickleCount) n.updateBatteryVoltage(batteryVoltage) n.updateBatteryCapacity(capacity) self.addNode(n) if len(self.__trickleQueue) != 0: if self.__trickleCheck(): self.__expTrickle = (self.__netMaxTrickle + 1)%MAX_TRICKLE_C_VALUE message=self.__trickleQueue.popleft() send_serial_msg(message) self.addPrint("[APPLICATION] Trickle message: 0x {0} automatically sent".format((message).hex())) else: self.__trickleCheck() self.printNetworkStatus() def processBatteryDataMessage(self, label, voltage, capacity, soc=None, consumption=None, temperature=None): n = self.getNode(label) if n != None: n.updateBatteryVoltage(voltage) n.updateBatteryCapacity(capacity) n.updateBatterySOC(soc) n.updateBatteryConsumption(consumption) n.updateBatteryTemperature(temperature) #else: # n=Node(label, 0) # self.addNode(n) # n.updateBatteryVoltage(batteryVoltage) def processBTReportMessage(self, label): n = self.getNode(label) if n != None: n.BTReportHandler() #else: # n=Node(label, 0) # self.addNode(n) # n.BTReportHandler() def processUARTError(self): self.__uartErrors=self.__uartErrors+1 def addPrint(self, text): consoleLogger.info(text) terminalSize = shutil.get_terminal_size(([80,20])) if(len(text) > terminalSize[0]): if(len(text) > 2*terminalSize[0]): #clip the text if it is longer than 2 lines... text=text[:2*terminalSize[0]] with self.console_queue_lock: self.__consoleBuffer.append(text[:terminalSize[0]]) self.__consoleBuffer.append(text[terminalSize[0]:]) else: with self.console_queue_lock: self.__consoleBuffer.append(text) self.printNetworkStatus() #for l in self.__consoleBuffer: # print(l) def resetCounters(self): for n in self.__nodes: n.amountOfBTReports=0 self.__trickleCheck() def resetTrickle(self): self.__trickleCheck() self.__expTrickle = self.__netMaxTrickle class Node(object): # The class "constructor" - It's actually an initializer def __init__(self, label): self.lock = threading.Lock() self.name = label self.lastTrickleCount = 0 self.lastMessageTime = float(time.time()) self.online=True def __init__(self, label, trickleCount): self.lock = threading.Lock() self.name = label self.lastTrickleCount = trickleCount self.lastMessageTime = float(time.time()) self.batteryVoltage = None self.batteryCapacity = None self.batterySoc = None self.batteryConsumption = None self.batteryTemperature = None self.amountOfBTReports = 0 self.online=True def updateTrickleCount(self,trickleCount): with self.lock: self.lastTrickleCount = trickleCount self.lastMessageTime = float(time.time()) def updateBatteryVoltage(self, batteryVoltage): with self.lock: self.batteryVoltage = batteryVoltage self.lastMessageTime = float(time.time()) def updateBatteryCapacity(self, capacity): with self.lock: self.batteryCapacity = capacity self.lastMessageTime = float(time.time()) def updateBatterySOC(self, soc): with self.lock: self.batterySoc = soc self.lastMessageTime = float(time.time()) def updateBatteryConsumption(self, consumption): with self.lock: self.batteryConsumption = consumption self.lastMessageTime = float(time.time()) def updateBatteryTemperature(self, temperature): with self.lock: self.batteryTemperature = temperature self.lastMessageTime = float(time.time()) def BTReportHandler(self): with self.lock: self.amountOfBTReports = self.amountOfBTReports + 1 self.lastMessageTime = float(time.time()) def getLastMessageElapsedTime(self): now = float(time.time()) return now-self.lastMessageTime def printNodeInfo(self): if self.online: if self.batteryConsumption != None: print("| %3s | %3.2fV %3.0f%% %4.0fmAh %6.1fmA %5.1f° | %3.0f | %3d |%5d |" % (str(self.name), self.batteryVoltage, self.batterySoc, self.batteryCapacity, self.batteryConsumption, self.batteryTemperature, self.getLastMessageElapsedTime(), self.lastTrickleCount, self.amountOfBTReports)) else: print("| %3s | %3.2fV | %3.0f | %3d |%5d |" % (str(self.name), self.batteryVoltage, self.getLastMessageElapsedTime(), self.lastTrickleCount, self.amountOfBTReports)) else: if self.batteryConsumption != None: print("| %3s * | %3.2fV %3.0f%% %4.0fmAh %6.1fmA %5.1f° | %3.0f | %3d |%5d |" % (str(self.name), self.batteryVoltage, self.batterySoc, self.batteryCapacity, self.batteryConsumption, self.batteryTemperature, self.getLastMessageElapsedTime(), self.lastTrickleCount, self.amountOfBTReports)) else: print("| %3s * | %3.2fV | %3.0f | %3d |%5d |" % (str(self.name), self.batteryVoltage, self.getLastMessageElapsedTime(), self.lastTrickleCount, self.amountOfBTReports)) @unique class PacketType(IntEnum): network_new_sequence = 0x0100 network_active_sequence = 0x0101 network_last_sequence = 0x0102 network_bat_data = 0x0200 network_set_time_between_send = 0x0601 network_request_ping = 0xF000 network_respond_ping = 0xF001 network_keep_alive = 0xF010 nordic_turn_bt_off = 0xF020 nordic_turn_bt_on = 0xF021 nordic_turn_bt_on_w_params = 0xF022 nordic_turn_bt_on_low = 0xF023 #deprecated nordic_turn_bt_on_def = 0xF024 nordic_turn_bt_on_high = 0xF025 #deprecated ti_set_batt_info_int = 0xF026 nordic_reset = 0xF027 nordic_ble_tof_enable = 0xF030 ti_set_keep_alive = 0xF801 def cls(): os.system('cls' if os.name=='nt' else 'clear') def handle_user_input(): ble_tof_enabled=False while 1: try: input_str = input() if len(input_str)>=2 and input_str[0] == 'f': forced=True user_input = int(input_str[1:]) else: if input_str=='h': if net.showHelp: net.showHelp=False else: net.showHelp=True net.printNetworkStatus() continue elif input_str=='r': net.resetCounters() net.printNetworkStatus() continue elif input_str=='t': net.resetTrickle() net.printNetworkStatus() continue else: forced=False user_input = int(input_str) if user_input == 1: payload = 233 net.addPrint("[USER_INPUT] Ping request") net.sendNewTrickle(build_outgoing_serial_message(PacketType.network_request_ping, payload.to_bytes(1, byteorder="big", signed=False)),forced) elif user_input == 2: net.addPrint("[USER_INPUT] Turn bluetooth on") net.sendNewTrickle(build_outgoing_serial_message(PacketType.nordic_turn_bt_on, None),forced) elif user_input == 3: net.addPrint("[USER_INPUT] Turn bluetooth off") net.sendNewTrickle(build_outgoing_serial_message(PacketType.nordic_turn_bt_off, None),forced) #elif user_input == 4: # net.addPrint("Turning bt on low") # appLogger.debug("[SENDING] Enable Bluetooth LOW") # net.sendNewTrickle(build_outgoing_serial_message(PacketType.nordic_turn_bt_on_low, None),forced) #elif user_input == 4: # net.addPrint("[USER_INPUT] Turn bluetooth on with default settings stored on the nodes") # net.sendNewTrickle(build_outgoing_serial_message(PacketType.nordic_turn_bt_on_def, None),forced) #elif user_input == 6: # net.addPrint("Turning bt on high") # appLogger.debug("[SENDING] Enable Bluetooth HIGH") # net.sendNewTrickle(build_outgoing_serial_message(PacketType.nordic_turn_bt_on_high, None),forced) elif user_input == 4: if ble_tof_enabled: net.addPrint("[USER_INPUT] disabling ble tof") ble_tof_enabled=False else: net.addPrint("[USER_INPUT] enabling ble tof") ble_tof_enabled=True net.sendNewTrickle(build_outgoing_serial_message(PacketType.nordic_ble_tof_enable, ble_tof_enabled.to_bytes(1, byteorder="big", signed=False)),forced) elif user_input == 5: SCAN_INTERVAL_MS = 1500 SCAN_WINDOW_MS = 1500 SCAN_TIMEOUT_S = 0 REPORT_TIMEOUT_S = 15 active_scan = 1 scan_interval = int(SCAN_INTERVAL_MS*1000/625) scan_window = int(SCAN_WINDOW_MS*1000/625) timeout = int(SCAN_TIMEOUT_S) report_timeout_ms = int(REPORT_TIMEOUT_S*1000) bactive_scan = active_scan.to_bytes(1, byteorder="big", signed=False) bscan_interval = scan_interval.to_bytes(2, byteorder="big", signed=False) bscan_window = scan_window.to_bytes(2, byteorder="big", signed=False) btimeout = timeout.to_bytes(2, byteorder="big", signed=False) breport_timeout_ms = report_timeout_ms.to_bytes(4, byteorder="big", signed=False) payload = bactive_scan + bscan_interval + bscan_window + btimeout + breport_timeout_ms net.addPrint("[USER_INPUT] Turn bluetooth on with parameters: scan_int="+str(SCAN_INTERVAL_MS)+"ms, scan_win="+str(SCAN_WINDOW_MS)+"ms, timeout="+str(SCAN_TIMEOUT_S)+"s, report_int="+str(REPORT_TIMEOUT_S)+"s") net.sendNewTrickle(build_outgoing_serial_message(PacketType.nordic_turn_bt_on_w_params, payload),forced) elif user_input == 6: bat_info_interval_s = 90 net.addPrint("[USER_INPUT] Enable battery info with interval: "+str(bat_info_interval_s)) net.sendNewTrickle(build_outgoing_serial_message(PacketType.ti_set_batt_info_int, bat_info_interval_s.to_bytes(1, byteorder="big", signed=False)),forced) elif user_input == 7: bat_info_interval_s = 0 net.addPrint("[USER_INPUT] Disable battery info") net.sendNewTrickle(build_outgoing_serial_message(PacketType.ti_set_batt_info_int, bat_info_interval_s.to_bytes(1, byteorder="big", signed=False)),forced) elif user_input == 8: net.addPrint("[USER_INPUT] Reset nordic") net.sendNewTrickle(build_outgoing_serial_message(PacketType.nordic_reset, None),forced) elif user_input == 9: time_between_send_ms = 0 time_between_send = time_between_send_ms.to_bytes(2, byteorder="big", signed=False) net.addPrint("[USER_INPUT] Set time between sends to "+ str(time_between_send_ms) + "ms") net.sendNewTrickle(build_outgoing_serial_message(PacketType.network_set_time_between_send, time_between_send),forced) elif user_input > 9: interval = user_input net.addPrint("[USER_INPUT] Set keep alive interval to "+ str(interval) + "s") net.sendNewTrickle(build_outgoing_serial_message(PacketType.ti_set_keep_alive, interval.to_bytes(1, byteorder="big", signed=False)),forced) except ValueError: net.addPrint("[USER_INPUT] Read failed. Read data: "+ input_str) def build_outgoing_serial_message(pkttype, ser_payload): payload_size = 0 if ser_payload is not None: payload_size = len(ser_payload) packet = payload_size.to_bytes(length=1, byteorder='big', signed=False) + pkttype.to_bytes(length=2, byteorder='big', signed=False) if ser_payload is not None: packet=packet+ser_payload ascii_packet=''.join('%02X'%i for i in packet) return ascii_packet.encode('utf-8') def send_serial_msg(message): line = message + SER_END_CHAR ser.write(line) UARTLogger.info('[GATEWAY] ' + str(line)) def decode_payload(payload, seqid, size, packettype, pktnum): #TODO: packettype can be removed #raw_data = "Node {0} ".format(messageSequenceList[seqid].nodeid) + "0x {:04X} ".format(packettype) + "0x {:02X}".format(pktnum) + " 0x " cur=0 try: for x in range(round(size / SINGLE_NODE_REPORT_SIZE)): nid = int(payload[cur:cur+12], 16) #int(ser.read(6).hex(), 16) cur=cur+12 lastrssi = int(payload[cur:cur+2], 16) #int(ser.read(1).hex(), 16) cur=cur+2 maxrssi = int(payload[cur:cur+2], 16) #int(ser.read(1).hex(), 16) cur=cur+2 pktcounter = int(payload[cur:cur+2], 16) #int(ser.read(1).hex(), 16) cur=cur+2 #net.addPrint("id = {:012X}".format(nid, 8)) contact = ContactData(nid, lastrssi, maxrssi, pktcounter) messageSequenceList[seqid].datalist.append(contact) messageSequenceList[seqid].datacounter += SINGLE_NODE_REPORT_SIZE #raw_data += "{:012X}".format(nid, 8) + '{:02X}'.format(lastrssi) + '{:02X}'.format(maxrssi) + '{:02X}'.format(pktcounter) except ValueError: net.addPrint("[Node {0}] Requested to decode more bytes than available. Requested: {1}" .format(messageSequenceList[seqid].nodeid, size)) #appLogger.warning("[Node {0}] Requested to decode more bytes than available. Requested: {1}" # .format(messageSequenceList[seqid].nodeid, size)) finally: #dataLogger.info(raw_data) return def log_contact_data(seqid): seq = messageSequenceList[seqid] timestamp = seq.timestamp source = seq.nodeid logstring = "{0} Node {1} ".format(timestamp, source) for x in range(len(seq.datalist)): logstring += "{:012X}".format(seq.datalist[x].nodeid) + '{:02X}'.format(seq.datalist[x].lastRSSI) + '{:02X}'.format(seq.datalist[x].maxRSSI) + '{:02X}'.format(seq.datalist[x].pktCounter) contactLogger.info(logstring) def get_sequence_index(nodeid): for x in range(len(messageSequenceList)): if messageSequenceList[x].nodeid == nodeid: return x return -1 def check_for_packetdrop(nodeid, pktnum): if pktnum == 0: return for x in range(len(nodeDropInfoList)): if nodeDropInfoList[x].nodeid == nodeid: global dropCounter dropCounter += pktnum - nodeDropInfoList[x].lastpkt - 1 #appLogger.debug("[Node {0}] Dropped {1} packet(s). Latest packet: {2}, new packet: {3}" # .format(nodeid, pktnum - nodeDropInfoList[x].lastpkt - 1, nodeDropInfoList[x].lastpkt, # pktnum)) return nodeDropInfoList.append(NodeDropInfo(nodeid, pktnum)) def to_byte(hex_text): return binascii.unhexlify(hex_text) _thread.start_new_thread(handle_user_input, ()) net = Network() net.addPrint("[APPLICATION] Starting...") net.addPrint("[APPLICATION] Logs are in: %s" %logfolderpath) if ser.is_open: net.addPrint("[UART] Serial Port already open! "+ ser.port + " open before initialization... closing first") ser.close() time.sleep(1) startCharErr=False #startBuffErr=False otherkindofErr=False try: while 1: if ser.is_open: try: bytesWaiting = ser.in_waiting except Exception as e: net.addPrint("[UART] Serial Port input exception:"+ str(e)) #appLogger.error("Serial Port input exception: {0}".format(e)) bytesWaiting = 0 ser.close() time.sleep(1) continue try: if bytesWaiting > 0: rawline = ser.readline() #can block if no timeout is provided when the port is open UARTLogger.info('[SINK] ' + str(rawline)) start = rawline[0:1].hex() if start == START_CHAR: if startCharErr or otherkindofErr: net.processUARTError() startCharErr=False otherkindofErr=False line = to_byte(rawline[1:-1]) cursor=0 deliverCounter += 1 # TODO change the way pktnum's are being tracked nodeid = int.from_bytes(line[cursor:cursor+1], "little", signed=False) #int.from_bytes(ser.read(1), "little", signed=False) cursor+=1 pkttype = int(line[cursor:cursor+2].hex(),16) #int(ser.read(2).hex(), 16) cursor+=2 pktnum = int.from_bytes(line[cursor:cursor+1], "little", signed=False) #int.from_bytes(ser.read(1), "little", signed=False) cursor+=1 if printVerbosity > 0: net.addPrint("[NODEID " + str(nodeid) + "] pkttype " + hex(pkttype) + ", pktnum " + str(pktnum)) #appLogger.info("[New message] nodeid {0}, pkttype {1} pktnum {2}".format(nodeid, hex(pkttype), pktnum)) check_for_packetdrop(nodeid, pktnum) #TODO: add here the check for duplicates. Any duplicate should be discarded HERE!!! if PacketType.network_new_sequence == pkttype: datalen = int(line[cursor:cursor+2].hex(), 16) #int(ser.read(2).hex(), 16) cursor+=2 payload = line[cursor:].hex() cursor = len(line) if datalen % SINGLE_NODE_REPORT_SIZE != 0: if printVerbosity > 1: net.addPrint(" [PACKET DECODE] Invalid datalength: "+ str(datalen)) #appLogger.warning("[Node {0}] invalid sequencelength: {1}".format(nodeid, datalen)) seqid = get_sequence_index(nodeid) #at this point, since we just received 'network_new_sequence', there should not be any sequence associated with this nodeid if seqid != -1: if messageSequenceList[seqid].lastPktnum == pktnum: #in this case we just received the 'network_new_sequence' packet twice, shall I discard duplicates before this? if printVerbosity > 1: net.addPrint(" [PACKET DECODE] Duplicate packet from node "+ str(nodeid)+ " with pktnum "+ str(pktnum)) #appLogger.info("[Node {0}] duplicate packet, pktnum: {1}".format(nodeid, pktnum)) # remove duplicate packet data from uart buffer #remainingDataSize = messageSequenceList[seqid].sequenceSize - messageSequenceList[seqid].datacounter #if remainingDataSize >= MAX_PACKET_PAYLOAD: # payload=line[10:10+MAX_PACKET_PAYLOAD].hex() #else: # payload=line[10:10+remainingDataSize].hex() #dataLogger.info("Node {0} 0x {1} 0x {2} 0x {3}".format(nodeid, '{:04x}'.format(pkttype), '{:02x}'.format(pktnum), # '{:x}'.format(int(payload, 16)))) continue else: #in this case the 'network_new_sequence' arrived before 'network_last_sequence'. if printVerbosity > 1: net.addPrint(" [PACKET DECODE] Previous sequence has not been completed yet") # TODO what to do now? For now, assume last packet was dropped # TODO send received data instead of deleting it all #appLogger.info("[Node {0}] Received new sequence packet " # "while old sequence has not been completed".format(nodeid)) log_contact_data(seqid) del messageSequenceList[seqid] messageSequenceList.append(MessageSequence(datetime.datetime.fromtimestamp(time.time()).strftime('%Y-%m-%d %H:%M:%S'), nodeid, pktnum, 0, 0, [], time.time())) seqid = len(messageSequenceList) - 1 messageSequenceList[seqid].sequenceSize += datalen if messageSequenceList[seqid].sequenceSize > MAX_PACKET_PAYLOAD: #this is the normal behaviour decode_payload(payload, seqid, MAX_PACKET_PAYLOAD, PacketType.network_new_sequence, pktnum) else: #this is when the sequence is made by only one packet. decode_payload(payload, seqid, datalen, PacketType.network_new_sequence, pktnum) # TODO Only 1 packet in this sequence, so upload this packet already if printVerbosity > 1: net.addPrint(" [PACKET DECODE] Bluetooth sequence decoded. Contact elements: "+ str(len(messageSequenceList[seqid].datalist))) #appLogger.debug("[Node {0}] Single packet sequence complete".format(nodeid)) log_contact_data(seqid) net.processBTReportMessage(str(nodeid)) del messageSequenceList[seqid] elif PacketType.network_active_sequence == pkttype: seqid = get_sequence_index(nodeid) payload = line[cursor:].hex() cursor = len(line) if seqid == -1: #this is when we received 'network_active_sequence' before receiving a valid 'network_new_sequence' if printVerbosity > 1: net.addPrint(" [PACKET DECODE] First part of sequence dropped, creating incomplete sequence at index "+ str(len(messageSequenceList)) +" from pktnum "+ str(pktnum)) messageSequenceList.append( MessageSequence(datetime.datetime.fromtimestamp(time.time()). strftime('%Y-%m-%d %H:%M:%S'), nodeid, pktnum, -1, 0, [], time.time())) seqid = len(messageSequenceList) - 1 headerDropCounter += 1 elif messageSequenceList[seqid].lastPktnum == pktnum: #in this case we just received the same 'network_active_sequence' packet twice, if printVerbosity > 1: net.addPrint(" [PACKET DECODE] Duplicate packet from node "+ str(nodeid) +" with pktnum "+ str(pktnum)) # remove duplicate packet data from uart buffer #remainingDataSize = messageSequenceList[seqid].sequenceSize - messageSequenceList[seqid].datacounter #if remainingDataSize >= MAX_PACKET_PAYLOAD: #ser.read(MAX_PACKET_PAYLOAD) #TODO:if it is a duplicate no need to store it, but it MUST be a duplicate #else: #ser.read(remainingDataSize) continue messageSequenceList[seqid].lastPktnum = pktnum messageSequenceList[seqid].latestTime = time.time() decode_payload(payload,seqid, MAX_PACKET_PAYLOAD, PacketType.network_active_sequence, pktnum) elif PacketType.network_last_sequence == pkttype: # TODO upload data before deleting element from list #if printVerbosity > 1: # net.addPrint("[INFO] Full message received") seqid = get_sequence_index(nodeid) payload = line[cursor:].hex() cursor = len(line) if seqid == -1: #this is when we receive 'network_last_sequence' before receiving a valid 'network_new_sequence' messageSequenceList.append(MessageSequence(datetime.datetime.fromtimestamp(time.time()).strftime('%Y-%m-%d %H:%M:%S'), nodeid, pktnum, 0, 0, [], time.time())) seqid = len(messageSequenceList) - 1 decode_payload(payload,seqid, MAX_PACKET_PAYLOAD, PacketType.network_last_sequence, pktnum) if printVerbosity > 1: net.addPrint(" [PACKET DECODE] Bluetooth sequence decoded but header files were never received. datacounter: "+ str(messageSequenceList[seqid].datacounter) +" ContactData elements: "+ str(len(messageSequenceList[seqid].datalist))) # net.addPrint("[INFO] Nodeid: "+ str(messageSequenceList[seqid].nodeid) +" datacounter: "+ # str(messageSequenceList[seqid].datacounter)+ " ContactData elements: "+ # str(len(messageSequenceList[seqid].datalist))) headerDropCounter += 1 #appLogger.info("[Node {0}] Message defragmented but header files were never received" # " - datacounter: {1} ContactData elements: {2}" # .format(nodeid, messageSequenceList[seqid].datacounter, # len(messageSequenceList[seqid].datalist))) log_contact_data(seqid) del messageSequenceList[seqid] elif messageSequenceList[seqid].sequenceSize == -1: #what is this??? decode_payload(payload,seqid, MAX_PACKET_PAYLOAD, PacketType.network_last_sequence, pktnum) if printVerbosity > 1: net.addPrint(" [PACKET DECODE] Bluetooth sequence decoded but header files were never received. datacounter: "+ str(messageSequenceList[seqid].datacounter) +" ContactData elements: "+ str(len(messageSequenceList[seqid].datalist))) # # net.addPrint("[WARNING] Message defragmented but header files were never received") # net.addPrint("[INFO] Nodeid: "+ str(messageSequenceList[seqid].nodeid) +" datacounter: "+ str(messageSequenceList[seqid].datacounter)+ " ContactData elements: "+ str(len(messageSequenceList[seqid].datalist))) #appLogger.info("[Node {0}] Message defragmented but header files were never received" # " - datacounter: {1} ContactData elements: " # .format(nodeid, messageSequenceList[seqid].datacounter, # len(messageSequenceList[seqid].datalist))) log_contact_data(seqid) del messageSequenceList[seqid] else: remainingDataSize = messageSequenceList[seqid].sequenceSize - messageSequenceList[seqid].datacounter if remainingDataSize > MAX_PACKET_PAYLOAD: #when is this supposed to happen??? decode_payload(payload,seqid, MAX_PACKET_PAYLOAD, PacketType.network_last_sequence, pktnum) else: decode_payload(payload,seqid, remainingDataSize, PacketType.network_last_sequence, pktnum) if messageSequenceList[seqid].sequenceSize != messageSequenceList[seqid].datacounter: if printVerbosity > 1: #net.addPrint("ERROR: Messagesequence ended, but datacounter is not equal to sequencesize") net.addPrint(" [PACKET DECODE] ERROR: Messagesequence ended, but datacounter is not equal to sequencesize") if printVerbosity > 1: net.addPrint(" [PACKET DECODE] Bluetooth sequence decoded. "+" sequencesize: "+ str(messageSequenceList[seqid].sequenceSize)+ " ContactData elements: "+ str(len(messageSequenceList[seqid].datalist))) #appLogger.warning("[Node {0}] Messagesequence ended, but datacounter is not equal to sequencesize - datacounter: {1}" #WHY IS THIS WARNING HERE????? # " ContactData elements: {2}".format(nodeid, messageSequenceList[seqid].datacounter, # len(messageSequenceList[seqid].datalist))) log_contact_data(seqid) net.processBTReportMessage(str(messageSequenceList[seqid].nodeid)) del messageSequenceList[seqid] elif PacketType.network_bat_data == pkttype: batCapacity = float(int.from_bytes(line[cursor:cursor+2], byteorder="big", signed=False)) #int.from_bytes(ser.read(2), byteorder="big", signed=False) cursor+=2 batSoC = float(int.from_bytes(line[cursor:cursor+2], byteorder="big", signed=False)) / 10 #int.from_bytes(ser.read(2), byteorder="big", signed=False) / 10 cursor+=2 bytesELT = line[cursor:cursor+2] #ser.read(2) cursor+=2 batELT = str(timedelta(minutes=int.from_bytes(bytesELT, byteorder="big", signed=False)))[:-3] # Convert minutes to hours and minutes batAvgConsumption = float(int.from_bytes(line[cursor:cursor+2], byteorder="big", signed=True)) / 10 #int.from_bytes(ser.read(2), byteorder="big", signed=True) / 10 cursor+=2 batAvgVoltage = float(int.from_bytes(line[cursor:cursor+2], byteorder="big", signed=False))/1000 #int.from_bytes(ser.read(2), byteorder="big", signed=False) cursor+=2 batAvgTemp = float(int.from_bytes(line[cursor:cursor+2], byteorder="big", signed=True)) / 100 #int.from_bytes(ser.read(2), byteorder="big", signed=True) / 100 cursor+=2 #processBatteryDataMessage(self, label, voltage, capacity, soc=None, consumption=None, temperature=None) net.processBatteryDataMessage(str(nodeid), batAvgVoltage, batCapacity, batSoC, batAvgConsumption, batAvgTemp) if printVerbosity > 1: net.addPrint(" [PACKET DECODE] Battery data, Cap: %.0f mAh SoC: %.1f ETA: %s (hh:mm) Consumption: %.1f mA Voltage: %.3f Temperature %.2f"% (batCapacity, batSoC, batELT, batAvgConsumption, batAvgVoltage, batAvgTemp)) #appLogger.info("[Node {0}] Received bat data, Capacity: {1} mAh | State Of Charge: {2}% | Estimated Lifetime: {3} (hh:mm) | " # "Average Consumption: {4} mA | Average Battery Voltage: {5} mV | Temperature: {6} *C" # .format(nodeid, batCapacity, batSoC, batELT, batAvgConsumption, # batAvgVoltage, batAvgTemp)) #dataLogger.info("Node {0} 0x {1} 0x {2} 0x {3}{4}{5}{6}{7}{8}".format(nodeid, '{:04x}'.format(pkttype), '{:02x}'.format(pktnum), '{:02x}'.format(batCapacity), '{:02x}'.format(int(batSoC * 10)), # '{:02x}'.format(int.from_bytes(bytesELT, byteorder="big", signed=False)), '{:02x}'.format(int(batAvgConsumption * 10)), # '{:02x}'.format(int(batAvgVoltage)), '{:02x}'.format(100 * int(batAvgTemp)))) elif PacketType.network_respond_ping == pkttype: payload = int(line[cursor:cursor+2].hex(), 16) #int(ser.read(1).hex(), 16) cursor+=2 #dataLogger.info("Node {0} 0x {1} 0x {2} 0x {3}".format(nodeid, '{:04x}'.format(pkttype), '{:02x}'.format(pktnum), '{:x}'.format(payload))) if payload == 233: net.addPrint(" [PACKET DECODE] Node id "+ str(nodeid) +" pinged succesfully!") #appLogger.debug("[Node {0}] pinged succesfully!".format(nodeid)) if nodeid not in ActiveNodes: ActiveNodes.append(nodeid) else: net.addPrint(" [PACKET DECODE] Node id "+ str(nodeid)+" wrong ping payload: %d" % payload ) #appLogger.info("[Node {0}] pinged wrong payload: ".format(nodeid, payload)) elif PacketType.network_keep_alive == pkttype: cap = float(int.from_bytes(line[cursor:cursor+2], byteorder="big", signed=False)) #int.from_bytes(ser.read(2), byteorder="big", signed=False) cursor+=2 batAvgVoltage = float(int.from_bytes(line[cursor:cursor+2], byteorder="big", signed=False))/1000 #int.from_bytes(ser.read(2), byteorder="big", signed=False) cursor+=2 trickle_count = int.from_bytes(line[cursor:cursor+1], byteorder="big", signed=False) #int.from_bytes(ser.read(1), byteorder="big", signed=False) cursor+=1 net.processKeepAliveMessage(str(nodeid), trickle_count, batAvgVoltage, cap) if printVerbosity > 1: net.addPrint(" [PACKET DECODE] Keep alive packet. Cap: "+ str(cap) +" Voltage: "+ str(batAvgVoltage*1000) +" Trickle count: "+ str(trickle_count)) #appLogger.info("[Node {0}] Received keep alive message with capacity: {1} and voltage: {2} trickle_count {3}".format(nodeid, cap, batAvgVoltage,trickle_count)) #dataLogger.info("Node {0} 0x {1} 0x {2} 0x {3}{4} {5}".format(nodeid, '{:02x}'.format(pkttype), '{:x}'.format(pktnum), '{:02x}'.format(cap), '{:02x}'.format(batAvgVoltage),trickle_count)) else: net.addPrint(" [PACKET DECODE] Unknown packet (unrecognized packet type): "+str(rawline)) cursor = len(line) #appLogger.warning("[Node {0}] Received unknown packettype: {1}".format(nodeid, hex(pkttype))) #dataLogger.info("Node {0} 0x {1} 0x {2}".format(nodeid, '{:02x}'.format(pkttype), '{:x}'.format(pktnum))) else: #start == START_CHAR startCharErr=True net.addPrint("[UART] Unknown START_CHAR: "+ start + ". The line was: "+str(rawline)) errorLogger.info("%s" %(str(rawline))) except Exception as e: otherkindofErr=True net.addPrint("[ERROR] Unknown error during line decoding. Exception: %s. Line was: %s" %( str(e), str(rawline))) errorLogger.info("%s" %(str(rawline))) currentTime = time.time() if currentTime - previousTimeTimeout > timeoutInterval: previousTimeTimeout = time.time() deletedCounter = 0 for x in range(len(messageSequenceList)): if currentTime - messageSequenceList[x - deletedCounter].latestTime > timeoutTime: deleted_nodeid=messageSequenceList[x - deletedCounter].nodeid del messageSequenceList[x - deletedCounter] deletedCounter += 1 if printVerbosity > 1: xd = x + deletedCounter net.addPrint("[APPLICATION] Deleted seqid %d of node %d because of timeout" %(xd, deleted_nodeid)) if currentTime - btPreviousTime > btToggleInterval: ptype = 0 if btToggleBool: # net.addPrint("Turning bt off") # appLogger.debug("[SENDING] Disable Bluetooth") ptype = PacketType.nordic_turn_bt_off # btToggleBool = False else: # net.addPrint("Turning bt on") # appLogger.debug("[SENDING] Enable Bluetooth") ptype = PacketType.nordic_turn_bt_on btToggleBool = True # send_serial_msg(ptype, None) btPreviousTime = currentTime else: # !ser.is_open (serial port is not open) net.addPrint('[UART] Serial Port closed! Trying to open port: %s'% ser.port) try: ser.open() except Exception as e: net.addPrint("[UART] Serial Port open exception:"+ str(e)) #appLogger.debug("Serial Port exception: %s", e) time.sleep(5) continue net.addPrint("[UART] Serial Port open!") #appLogger.debug("Serial Port open") except UnicodeDecodeError as e: pass except KeyboardInterrupt: print("[APPLICATION] -----Packet delivery stats summary-----") print("[APPLICATION] Total packets delivered: ", deliverCounter) print("[APPLICATION] Total packets dropped: ", dropCounter) print("[APPLICATION] Total header packets dropped: ", headerDropCounter) print("[APPLICATION] Packet delivery rate: ", 100 * (deliverCounter / (deliverCounter + dropCounter))) print("[APPLICATION] Messages defragmented: ", defragmentationCounter) print("[APPLICATION] Logs are in: "+logfolderpath) #appLogger.info("-----Packet delivery stats summary-----") #appLogger.info("Total packets delivered: {0}".format(deliverCounter)) #appLogger.info("Total packets dropped: {0}".format(dropCounter)) #appLogger.info("Total header packets dropped: {0}".format(headerDropCounter)) #appLogger.info("Packet delivery rate: {0}".format(100 * (deliverCounter / (deliverCounter + dropCounter)))) #appLogger.info("Messages defragmented: {0}".format(defragmentationCounter)) raise finally: print("done")
gateway/dev/sink_integration/main.py
52,507
START_BUF = '2a2a2a' this is not really a buffer921600 1000000"/dev/ttyACM0" "/dev/ttyS0"must be the same as in common/inc/contraints.hmust be the same as in common/inc/contraints.h Timeout variables Loggerswith n.lock:self.addPrint("Node "+ n.name + "lastTrickleCount: " + str(n.lastTrickleCount))todo: it seems that this does't work. The __netMinTrickle goes up before all the nodes have sent their new values, sometimes it is __netMaxTrickle that doesn't update as soon the first new value arrives..self.removeNode(n)self.__trickleCheck()this is to avoid too fast call to this functionprint("| | | | | |")print("| | | | | |")else: n=Node(label, 0) self.addNode(n) n.updateBatteryVoltage(batteryVoltage)else: n=Node(label, 0) self.addNode(n) n.BTReportHandler()clip the text if it is longer than 2 lines...for l in self.__consoleBuffer: print(l) The class "constructor" - It's actually an initializerdeprecateddeprecatedelif user_input == 4: net.addPrint("Turning bt on low") appLogger.debug("[SENDING] Enable Bluetooth LOW") net.sendNewTrickle(build_outgoing_serial_message(PacketType.nordic_turn_bt_on_low, None),forced)elif user_input == 4: net.addPrint("[USER_INPUT] Turn bluetooth on with default settings stored on the nodes") net.sendNewTrickle(build_outgoing_serial_message(PacketType.nordic_turn_bt_on_def, None),forced)elif user_input == 6: net.addPrint("Turning bt on high") appLogger.debug("[SENDING] Enable Bluetooth HIGH") net.sendNewTrickle(build_outgoing_serial_message(PacketType.nordic_turn_bt_on_high, None),forced)TODO: packettype can be removedraw_data = "Node {0} ".format(messageSequenceList[seqid].nodeid) + "0x {:04X} ".format(packettype) + "0x {:02X}".format(pktnum) + " 0x "int(ser.read(6).hex(), 16)int(ser.read(1).hex(), 16)int(ser.read(1).hex(), 16)int(ser.read(1).hex(), 16)net.addPrint("id = {:012X}".format(nid, 8))raw_data += "{:012X}".format(nid, 8) + '{:02X}'.format(lastrssi) + '{:02X}'.format(maxrssi) + '{:02X}'.format(pktcounter)appLogger.warning("[Node {0}] Requested to decode more bytes than available. Requested: {1}" .format(messageSequenceList[seqid].nodeid, size))dataLogger.info(raw_data)appLogger.debug("[Node {0}] Dropped {1} packet(s). Latest packet: {2}, new packet: {3}" .format(nodeid, pktnum - nodeDropInfoList[x].lastpkt - 1, nodeDropInfoList[x].lastpkt, pktnum))startBuffErr=FalseappLogger.error("Serial Port input exception: {0}".format(e))can block if no timeout is provided when the port is open TODO change the way pktnum's are being trackedint.from_bytes(ser.read(1), "little", signed=False)int(ser.read(2).hex(), 16)int.from_bytes(ser.read(1), "little", signed=False)appLogger.info("[New message] nodeid {0}, pkttype {1} pktnum {2}".format(nodeid, hex(pkttype), pktnum))TODO: add here the check for duplicates. Any duplicate should be discarded HERE!!!int(ser.read(2).hex(), 16)appLogger.warning("[Node {0}] invalid sequencelength: {1}".format(nodeid, datalen))at this point, since we just received 'network_new_sequence', there should not be any sequence associated with this nodeidin this case we just received the 'network_new_sequence' packet twice, shall I discard duplicates before this?appLogger.info("[Node {0}] duplicate packet, pktnum: {1}".format(nodeid, pktnum)) remove duplicate packet data from uart bufferremainingDataSize = messageSequenceList[seqid].sequenceSize - messageSequenceList[seqid].datacounterif remainingDataSize >= MAX_PACKET_PAYLOAD: payload=line[10:10+MAX_PACKET_PAYLOAD].hex()else: payload=line[10:10+remainingDataSize].hex()dataLogger.info("Node {0} 0x {1} 0x {2} 0x {3}".format(nodeid, '{:04x}'.format(pkttype), '{:02x}'.format(pktnum), '{:x}'.format(int(payload, 16))))in this case the 'network_new_sequence' arrived before 'network_last_sequence'. TODO what to do now? For now, assume last packet was dropped TODO send received data instead of deleting it allappLogger.info("[Node {0}] Received new sequence packet " "while old sequence has not been completed".format(nodeid))this is the normal behaviourthis is when the sequence is made by only one packet. TODO Only 1 packet in this sequence, so upload this packet alreadyappLogger.debug("[Node {0}] Single packet sequence complete".format(nodeid))this is when we received 'network_active_sequence' before receiving a valid 'network_new_sequence'in this case we just received the same 'network_active_sequence' packet twice, remove duplicate packet data from uart bufferremainingDataSize = messageSequenceList[seqid].sequenceSize - messageSequenceList[seqid].datacounterif remainingDataSize >= MAX_PACKET_PAYLOAD:ser.read(MAX_PACKET_PAYLOAD) TODO:if it is a duplicate no need to store it, but it MUST be a duplicateelse:ser.read(remainingDataSize) TODO upload data before deleting element from listif printVerbosity > 1: net.addPrint("[INFO] Full message received")this is when we receive 'network_last_sequence' before receiving a valid 'network_new_sequence' net.addPrint("[INFO] Nodeid: "+ str(messageSequenceList[seqid].nodeid) +" datacounter: "+ str(messageSequenceList[seqid].datacounter)+ " ContactData elements: "+ str(len(messageSequenceList[seqid].datalist)))appLogger.info("[Node {0}] Message defragmented but header files were never received" " - datacounter: {1} ContactData elements: {2}" .format(nodeid, messageSequenceList[seqid].datacounter, len(messageSequenceList[seqid].datalist)))what is this??? net.addPrint("[WARNING] Message defragmented but header files were never received") net.addPrint("[INFO] Nodeid: "+ str(messageSequenceList[seqid].nodeid) +" datacounter: "+ str(messageSequenceList[seqid].datacounter)+ " ContactData elements: "+ str(len(messageSequenceList[seqid].datalist)))appLogger.info("[Node {0}] Message defragmented but header files were never received" " - datacounter: {1} ContactData elements: " .format(nodeid, messageSequenceList[seqid].datacounter, len(messageSequenceList[seqid].datalist)))when is this supposed to happen???net.addPrint("ERROR: Messagesequence ended, but datacounter is not equal to sequencesize")appLogger.warning("[Node {0}] Messagesequence ended, but datacounter is not equal to sequencesize - datacounter: {1}" WHY IS THIS WARNING HERE????? " ContactData elements: {2}".format(nodeid, messageSequenceList[seqid].datacounter, len(messageSequenceList[seqid].datalist)))int.from_bytes(ser.read(2), byteorder="big", signed=False)int.from_bytes(ser.read(2), byteorder="big", signed=False) / 10ser.read(2) Convert minutes to hours and minutesint.from_bytes(ser.read(2), byteorder="big", signed=True) / 10int.from_bytes(ser.read(2), byteorder="big", signed=False)int.from_bytes(ser.read(2), byteorder="big", signed=True) / 100processBatteryDataMessage(self, label, voltage, capacity, soc=None, consumption=None, temperature=None)appLogger.info("[Node {0}] Received bat data, Capacity: {1} mAh | State Of Charge: {2}% | Estimated Lifetime: {3} (hh:mm) | " "Average Consumption: {4} mA | Average Battery Voltage: {5} mV | Temperature: {6} *C" .format(nodeid, batCapacity, batSoC, batELT, batAvgConsumption, batAvgVoltage, batAvgTemp))dataLogger.info("Node {0} 0x {1} 0x {2} 0x {3}{4}{5}{6}{7}{8}".format(nodeid, '{:04x}'.format(pkttype), '{:02x}'.format(pktnum), '{:02x}'.format(batCapacity), '{:02x}'.format(int(batSoC * 10)), '{:02x}'.format(int.from_bytes(bytesELT, byteorder="big", signed=False)), '{:02x}'.format(int(batAvgConsumption * 10)), '{:02x}'.format(int(batAvgVoltage)), '{:02x}'.format(100 * int(batAvgTemp))))int(ser.read(1).hex(), 16)dataLogger.info("Node {0} 0x {1} 0x {2} 0x {3}".format(nodeid, '{:04x}'.format(pkttype), '{:02x}'.format(pktnum), '{:x}'.format(payload)))appLogger.debug("[Node {0}] pinged succesfully!".format(nodeid))appLogger.info("[Node {0}] pinged wrong payload: ".format(nodeid, payload))int.from_bytes(ser.read(2), byteorder="big", signed=False)int.from_bytes(ser.read(2), byteorder="big", signed=False)int.from_bytes(ser.read(1), byteorder="big", signed=False)appLogger.info("[Node {0}] Received keep alive message with capacity: {1} and voltage: {2} trickle_count {3}".format(nodeid, cap, batAvgVoltage,trickle_count))dataLogger.info("Node {0} 0x {1} 0x {2} 0x {3}{4} {5}".format(nodeid, '{:02x}'.format(pkttype), '{:x}'.format(pktnum), '{:02x}'.format(cap), '{:02x}'.format(batAvgVoltage),trickle_count))appLogger.warning("[Node {0}] Received unknown packettype: {1}".format(nodeid, hex(pkttype)))dataLogger.info("Node {0} 0x {1} 0x {2}".format(nodeid, '{:02x}'.format(pkttype), '{:x}'.format(pktnum)))start == START_CHAR net.addPrint("Turning bt off") appLogger.debug("[SENDING] Disable Bluetooth") btToggleBool = False net.addPrint("Turning bt on") appLogger.debug("[SENDING] Enable Bluetooth") send_serial_msg(ptype, None) !ser.is_open (serial port is not open)appLogger.debug("Serial Port exception: %s", e)appLogger.debug("Serial Port open")appLogger.info("-----Packet delivery stats summary-----")appLogger.info("Total packets delivered: {0}".format(deliverCounter))appLogger.info("Total packets dropped: {0}".format(dropCounter))appLogger.info("Total header packets dropped: {0}".format(headerDropCounter))appLogger.info("Packet delivery rate: {0}".format(100 * (deliverCounter / (deliverCounter + dropCounter))))appLogger.info("Messages defragmented: {0}".format(defragmentationCounter))
9,930
en
0.454368
# MIT License # # Copyright (C) IBM Corporation 2018 # # Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated # documentation files (the "Software"), to deal in the Software without restriction, including without limitation the # rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit # persons to whom the Software is furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in all copies or substantial portions of the # Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE # WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, # TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE # SOFTWARE. from __future__ import absolute_import, division, print_function, unicode_literals import logging import numpy as np import six from art import NUMPY_DTYPE from art.attacks.attack import Attack from art.utils import compute_success, get_labels_np_array logger = logging.getLogger(__name__) class ElasticNet(Attack): """ The elastic net attack of Pin-Yu Chen et al. (2018). Paper link: https://arxiv.org/abs/1709.04114. """ attack_params = Attack.attack_params + ['confidence', 'targeted', 'learning_rate', 'max_iter', 'beta', 'binary_search_steps', 'initial_const', 'batch_size', 'decision_rule'] def __init__(self, classifier, confidence=0.0, targeted=True, learning_rate=1e-2, binary_search_steps=9, max_iter=10000, beta=1e-3, initial_const=1e-3, batch_size=128, decision_rule='EN'): """ Create an ElasticNet attack instance. :param classifier: A trained model. :type classifier: :class:`.Classifier` :param confidence: Confidence of adversarial examples: a higher value produces examples that are farther away, from the original input, but classified with higher confidence as the target class. :type confidence: `float` :param targeted: Should the attack target one specific class. :type targeted: `bool` :param learning_rate: The initial learning rate for the attack algorithm. Smaller values produce better results but are slower to converge. :type learning_rate: `float` :param binary_search_steps: Number of times to adjust constant with binary search (positive value). :type binary_search_steps: `int` :param max_iter: The maximum number of iterations. :type max_iter: `int` :param beta: Hyperparameter trading off L2 minimization for L1 minimization. :type beta: `float` :param initial_const: The initial trade-off constant `c` to use to tune the relative importance of distance and confidence. If `binary_search_steps` is large, the initial constant is not important, as discussed in Carlini and Wagner (2016). :type initial_const: `float` :param batch_size: Internal size of batches on which adversarial samples are generated. :type batch_size: `int` :param decision_rule: Decision rule. 'EN' means Elastic Net rule, 'L1' means L1 rule, 'L2' means L2 rule. :type decision_rule: `string` """ super(ElasticNet, self).__init__(classifier) kwargs = {'confidence': confidence, 'targeted': targeted, 'learning_rate': learning_rate, 'binary_search_steps': binary_search_steps, 'max_iter': max_iter, 'beta': beta, 'initial_const': initial_const, 'batch_size': batch_size, 'decision_rule': decision_rule } assert self.set_params(**kwargs) def _loss(self, x, x_adv): """ Compute the loss function values. :param x: An array with the original input. :type x: `np.ndarray` :param x_adv: An array with the adversarial input. :type x_adv: `np.ndarray` :return: A tuple holding the current logits, l1 distance, l2 distance and elastic net loss. :rtype: `(np.ndarray, float, float, float)` """ l1dist = np.sum(np.abs(x - x_adv).reshape(x.shape[0], -1), axis=1) l2dist = np.sum(np.square(x - x_adv).reshape(x.shape[0], -1), axis=1) endist = self.beta * l1dist + l2dist z = self.classifier.predict(np.array(x_adv, dtype=NUMPY_DTYPE), logits=True) return np.argmax(z, axis=1), l1dist, l2dist, endist def _gradient_of_loss(self, target, x, x_adv, c): """ Compute the gradient of the loss function. :param target: An array with the target class (one-hot encoded). :type target: `np.ndarray` :param x: An array with the original input. :type x: `np.ndarray` :param x_adv: An array with the adversarial input. :type x_adv: `np.ndarray` :param c: Weight of the loss term aiming for classification as target. :type c: `float` :return: An array with the gradient of the loss function. :type target: `np.ndarray` """ # Compute the current logits z = self.classifier.predict(np.array(x_adv, dtype=NUMPY_DTYPE), logits=True) if self.targeted: i_sub = np.argmax(target, axis=1) i_add = np.argmax(z * (1 - target) + (np.min(z, axis=1) - 1)[:, np.newaxis] * target, axis=1) else: i_add = np.argmax(target, axis=1) i_sub = np.argmax(z * (1 - target) + (np.min(z, axis=1) - 1)[:, np.newaxis] * target, axis=1) loss_gradient = self.classifier.class_gradient(x_adv, label=i_add, logits=True) loss_gradient -= self.classifier.class_gradient(x_adv, label=i_sub, logits=True) loss_gradient = loss_gradient.reshape(x.shape) c_mult = c for _ in range(len(x.shape)-1): c_mult = c_mult[:, np.newaxis] loss_gradient *= c_mult loss_gradient += 2 * (x_adv - x) return loss_gradient def _decay_learning_rate(self, global_step, end_learning_rate, decay_steps): """ Applies a square-root decay to the learning rate. :param global_step: Global step to use for the decay computation. :type global_step: `int` :param end_learning_rate: The minimal end learning rate. :type end_learning_rate: `float` :param decay_steps: Number of decayed steps. :type decay_steps: `int` :return: The decayed learning rate :rtype: `float` """ decayed_learning_rate = (self.learning_rate - end_learning_rate) * (1 - global_step / decay_steps)**2 + \ end_learning_rate return decayed_learning_rate def generate(self, x, **kwargs): """ Generate adversarial samples and return them in an array. :param x: An array with the original inputs to be attacked. :type x: `np.ndarray` :param y: If `self.targeted` is true, then `y` represents the target labels. Otherwise, the targets are the original class labels. :type y: `np.ndarray` :return: An array holding the adversarial examples. :rtype: `np.ndarray` """ x_adv = x.astype(NUMPY_DTYPE) (clip_min, clip_max) = self.classifier.clip_values # Parse and save attack-specific parameters params_cpy = dict(kwargs) y = params_cpy.pop(str('y'), None) self.set_params(**params_cpy) # Assert that, if attack is targeted, y is provided: if self.targeted and y is None: raise ValueError('Target labels `y` need to be provided for a targeted attack.') # No labels provided, use model prediction as correct class if y is None: y = get_labels_np_array(self.classifier.predict(x, logits=False)) # Compute adversarial examples with implicit batching nb_batches = int(np.ceil(x_adv.shape[0] / float(self.batch_size))) for batch_id in range(nb_batches): logger.debug('Processing batch %i out of %i', batch_id, nb_batches) batch_index_1, batch_index_2 = batch_id * self.batch_size, (batch_id + 1) * self.batch_size x_batch = x_adv[batch_index_1:batch_index_2] y_batch = y[batch_index_1:batch_index_2] x_adv[batch_index_1:batch_index_2] = self._generate_batch(x_batch, y_batch) # Apply clip x_adv = np.clip(x_adv, clip_min, clip_max) # Compute success rate of the EAD attack logger.info('Success rate of EAD attack: %.2f%%', 100 * compute_success(self.classifier, x, y, x_adv, self.targeted)) return x_adv def _generate_batch(self, x_batch, y_batch): """ Run the attack on a batch of images and labels. :param x_batch: A batch of original examples. :type x_batch: `np.ndarray` :param y_batch: A batch of targets (0-1 hot). :type y_batch: `np.ndarray` :return: A batch of adversarial examples. :rtype: `np.ndarray` """ # Initialize binary search: c = self.initial_const * np.ones(x_batch.shape[0]) c_lower_bound = np.zeros(x_batch.shape[0]) c_upper_bound = 10e10 * np.ones(x_batch.shape[0]) # Initialize best distortions and best attacks globally o_best_dist = np.inf * np.ones(x_batch.shape[0]) o_best_attack = x_batch.copy() # Start with a binary search for bss in range(self.binary_search_steps): logger.debug('Binary search step %i out of %i (c_mean==%f)', bss, self.binary_search_steps, np.mean(c)) # Run with 1 specific binary search step best_dist, best_label, best_attack = self._generate_bss(x_batch, y_batch, c) # Update best results so far o_best_attack[best_dist < o_best_dist] = best_attack[best_dist < o_best_dist] o_best_dist[best_dist < o_best_dist] = best_dist[best_dist < o_best_dist] # Adjust the constant as needed c, c_lower_bound, c_upper_bound = self._update_const(y_batch, best_label, c, c_lower_bound, c_upper_bound) return o_best_attack def _update_const(self, y_batch, best_label, c, c_lower_bound, c_upper_bound): """ Update constants. :param y_batch: A batch of targets (0-1 hot). :type y_batch: `np.ndarray` :param best_label: A batch of best labels. :type best_label: `np.ndarray` :param c: A batch of constants. :type c: `np.ndarray` :param c_lower_bound: A batch of lower bound constants. :type c_lower_bound: `np.ndarray` :param c_upper_bound: A batch of upper bound constants. :type c_upper_bound: `np.ndarray` :return: A tuple of three batches of updated constants and lower/upper bounds. :rtype: `tuple` """ def compare(o1, o2): if self.targeted: return o1 == o2 else: return o1 != o2 for i in range(len(c)): if compare(best_label[i], np.argmax(y_batch[i])) and best_label[i] != -np.inf: # Successful attack c_upper_bound[i] = min(c_upper_bound[i], c[i]) if c_upper_bound[i] < 1e9: c[i] = (c_lower_bound[i] + c_upper_bound[i]) / 2.0 else: # Failure attack c_lower_bound[i] = max(c_lower_bound[i], c[i]) if c_upper_bound[i] < 1e9: c[i] = (c_lower_bound[i] + c_upper_bound[i]) / 2.0 else: c[i] *= 10 return c, c_lower_bound, c_upper_bound def _generate_bss(self, x_batch, y_batch, c): """ Generate adversarial examples for a batch of inputs with a specific batch of constants. :param x_batch: A batch of original examples. :type x_batch: `np.ndarray` :param y_batch: A batch of targets (0-1 hot). :type y_batch: `np.ndarray` :param c: A batch of constants. :type c: `np.ndarray` :return: A tuple of best elastic distances, best labels, best attacks :rtype: `tuple` """ def compare(o1, o2): if self.targeted: return o1 == o2 else: return o1 != o2 # Initialize best distortions and best changed labels and best attacks best_dist = np.inf * np.ones(x_batch.shape[0]) best_label = [-np.inf] * x_batch.shape[0] best_attack = x_batch.copy() # Implement the algorithm 1 in the EAD paper x_adv = x_batch.copy() y_adv = x_batch.copy() for it in range(self.max_iter): logger.debug('Iteration step %i out of %i', it, self.max_iter) # Update learning rate lr = self._decay_learning_rate(global_step=it, end_learning_rate=0, decay_steps=self.max_iter) # Compute adversarial examples grad = self._gradient_of_loss(target=y_batch, x=x_batch, x_adv=y_adv, c=c) x_adv_next = self._shrinkage_threshold(y_adv - lr * grad, x_batch, self.beta) y_adv = x_adv_next + (1.0 * it / (it + 3)) * (x_adv_next - x_adv) x_adv = x_adv_next # Adjust the best result (z, l1dist, l2dist, endist) = self._loss(x=x_batch, x_adv=x_adv) if self.decision_rule == 'EN': zip_set = zip(endist, z) elif self.decision_rule == 'L1': zip_set = zip(l1dist, z) elif self.decision_rule == 'L2': zip_set = zip(l2dist, z) else: raise ValueError("The decision rule only supports `EN`, `L1`, `L2`.") for j, (d, s) in enumerate(zip_set): if d < best_dist[j] and compare(s, np.argmax(y_batch[j])): best_dist[j] = d best_attack[j] = x_adv[j] best_label[j] = s return best_dist, best_label, best_attack @staticmethod def _shrinkage_threshold(z, x, beta): """ Implement the element-wise projected shrinkage-threshold function. :param z: a batch of examples. :type z: `np.ndarray` :param x: a batch of original examples. :type x: `np.ndarray` :param beta: the shrink parameter. :type beta: `float` :return: a shrinked version of z. :rtype: `np.ndarray` """ cond1 = (z - x) > beta cond2 = np.abs(z - x) <= beta cond3 = (z - x) < -beta upper = np.minimum(z - beta, 1.0) lower = np.maximum(z + beta, 0.0) result = cond1 * upper + cond2 * x + cond3 * lower return result def set_params(self, **kwargs): """ Take in a dictionary of parameters and applies attack-specific checks before saving them as attributes. :param confidence: Confidence of adversarial examples: a higher value produces examples that are farther away, from the original input, but classified with higher confidence as the target class. :type confidence: `float` :param targeted: Should the attack target one specific class. :type targeted: `bool` :param learning_rate: The initial learning rate for the attack algorithm. Smaller values produce better results but are slower to converge. :type learning_rate: `float` :param binary_search_steps: Number of times to adjust constant with binary search (positive value). :type binary_search_steps: `int` :param max_iter: The maximum number of iterations. :type max_iter: `int` :param beta: Hyperparameter trading off L2 minimization for L1 minimization. :type beta: `float` :param initial_const: The initial trade-off constant `c` to use to tune the relative importance of distance and confidence. If `binary_search_steps` is large, the initial constant is not important, as discussed in Carlini and Wagner (2016). :type initial_const: `float` :param batch_size: Internal size of batches on which adversarial samples are generated. :type batch_size: `int` :param decision_rule: Decision rule. 'EN' means Elastic Net rule, 'L1' means L1 rule, 'L2' means L2 rule. :type decision_rule: `string` """ # Save attack-specific parameters super(ElasticNet, self).set_params(**kwargs) if type(self.binary_search_steps) is not int or self.binary_search_steps < 0: raise ValueError("The number of binary search steps must be a non-negative integer.") if type(self.max_iter) is not int or self.max_iter < 0: raise ValueError("The number of iterations must be a non-negative integer.") if type(self.batch_size) is not int or self.batch_size < 1: raise ValueError("The batch size must be an integer greater than zero.") if not isinstance(self.decision_rule, six.string_types) or self.decision_rule not in ['EN', 'L1', 'L2']: raise ValueError("The decision rule only supports `EN`, `L1`, `L2`.") return True
art/attacks/elastic_net.py
17,754
The elastic net attack of Pin-Yu Chen et al. (2018). Paper link: https://arxiv.org/abs/1709.04114. Create an ElasticNet attack instance. :param classifier: A trained model. :type classifier: :class:`.Classifier` :param confidence: Confidence of adversarial examples: a higher value produces examples that are farther away, from the original input, but classified with higher confidence as the target class. :type confidence: `float` :param targeted: Should the attack target one specific class. :type targeted: `bool` :param learning_rate: The initial learning rate for the attack algorithm. Smaller values produce better results but are slower to converge. :type learning_rate: `float` :param binary_search_steps: Number of times to adjust constant with binary search (positive value). :type binary_search_steps: `int` :param max_iter: The maximum number of iterations. :type max_iter: `int` :param beta: Hyperparameter trading off L2 minimization for L1 minimization. :type beta: `float` :param initial_const: The initial trade-off constant `c` to use to tune the relative importance of distance and confidence. If `binary_search_steps` is large, the initial constant is not important, as discussed in Carlini and Wagner (2016). :type initial_const: `float` :param batch_size: Internal size of batches on which adversarial samples are generated. :type batch_size: `int` :param decision_rule: Decision rule. 'EN' means Elastic Net rule, 'L1' means L1 rule, 'L2' means L2 rule. :type decision_rule: `string` Applies a square-root decay to the learning rate. :param global_step: Global step to use for the decay computation. :type global_step: `int` :param end_learning_rate: The minimal end learning rate. :type end_learning_rate: `float` :param decay_steps: Number of decayed steps. :type decay_steps: `int` :return: The decayed learning rate :rtype: `float` Run the attack on a batch of images and labels. :param x_batch: A batch of original examples. :type x_batch: `np.ndarray` :param y_batch: A batch of targets (0-1 hot). :type y_batch: `np.ndarray` :return: A batch of adversarial examples. :rtype: `np.ndarray` Generate adversarial examples for a batch of inputs with a specific batch of constants. :param x_batch: A batch of original examples. :type x_batch: `np.ndarray` :param y_batch: A batch of targets (0-1 hot). :type y_batch: `np.ndarray` :param c: A batch of constants. :type c: `np.ndarray` :return: A tuple of best elastic distances, best labels, best attacks :rtype: `tuple` Compute the gradient of the loss function. :param target: An array with the target class (one-hot encoded). :type target: `np.ndarray` :param x: An array with the original input. :type x: `np.ndarray` :param x_adv: An array with the adversarial input. :type x_adv: `np.ndarray` :param c: Weight of the loss term aiming for classification as target. :type c: `float` :return: An array with the gradient of the loss function. :type target: `np.ndarray` Compute the loss function values. :param x: An array with the original input. :type x: `np.ndarray` :param x_adv: An array with the adversarial input. :type x_adv: `np.ndarray` :return: A tuple holding the current logits, l1 distance, l2 distance and elastic net loss. :rtype: `(np.ndarray, float, float, float)` Implement the element-wise projected shrinkage-threshold function. :param z: a batch of examples. :type z: `np.ndarray` :param x: a batch of original examples. :type x: `np.ndarray` :param beta: the shrink parameter. :type beta: `float` :return: a shrinked version of z. :rtype: `np.ndarray` Update constants. :param y_batch: A batch of targets (0-1 hot). :type y_batch: `np.ndarray` :param best_label: A batch of best labels. :type best_label: `np.ndarray` :param c: A batch of constants. :type c: `np.ndarray` :param c_lower_bound: A batch of lower bound constants. :type c_lower_bound: `np.ndarray` :param c_upper_bound: A batch of upper bound constants. :type c_upper_bound: `np.ndarray` :return: A tuple of three batches of updated constants and lower/upper bounds. :rtype: `tuple` Generate adversarial samples and return them in an array. :param x: An array with the original inputs to be attacked. :type x: `np.ndarray` :param y: If `self.targeted` is true, then `y` represents the target labels. Otherwise, the targets are the original class labels. :type y: `np.ndarray` :return: An array holding the adversarial examples. :rtype: `np.ndarray` Take in a dictionary of parameters and applies attack-specific checks before saving them as attributes. :param confidence: Confidence of adversarial examples: a higher value produces examples that are farther away, from the original input, but classified with higher confidence as the target class. :type confidence: `float` :param targeted: Should the attack target one specific class. :type targeted: `bool` :param learning_rate: The initial learning rate for the attack algorithm. Smaller values produce better results but are slower to converge. :type learning_rate: `float` :param binary_search_steps: Number of times to adjust constant with binary search (positive value). :type binary_search_steps: `int` :param max_iter: The maximum number of iterations. :type max_iter: `int` :param beta: Hyperparameter trading off L2 minimization for L1 minimization. :type beta: `float` :param initial_const: The initial trade-off constant `c` to use to tune the relative importance of distance and confidence. If `binary_search_steps` is large, the initial constant is not important, as discussed in Carlini and Wagner (2016). :type initial_const: `float` :param batch_size: Internal size of batches on which adversarial samples are generated. :type batch_size: `int` :param decision_rule: Decision rule. 'EN' means Elastic Net rule, 'L1' means L1 rule, 'L2' means L2 rule. :type decision_rule: `string` MIT License Copyright (C) IBM Corporation 2018 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. Compute the current logits Parse and save attack-specific parameters Assert that, if attack is targeted, y is provided: No labels provided, use model prediction as correct class Compute adversarial examples with implicit batching Apply clip Compute success rate of the EAD attack Initialize binary search: Initialize best distortions and best attacks globally Start with a binary search Run with 1 specific binary search step Update best results so far Adjust the constant as needed Successful attack Failure attack Initialize best distortions and best changed labels and best attacks Implement the algorithm 1 in the EAD paper Update learning rate Compute adversarial examples Adjust the best result Save attack-specific parameters
7,690
en
0.748118
# coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- from typing import TYPE_CHECKING import warnings from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error from azure.core.paging import ItemPaged from azure.core.pipeline import PipelineResponse from azure.core.pipeline.transport import HttpRequest, HttpResponse from azure.core.polling import LROPoller, NoPolling, PollingMethod from azure.mgmt.core.exceptions import ARMErrorFormat from azure.mgmt.core.polling.arm_polling import ARMPolling from .. import models as _models if TYPE_CHECKING: # pylint: disable=unused-import,ungrouped-imports from typing import Any, Callable, Dict, Generic, Iterable, Optional, TypeVar, Union T = TypeVar('T') ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] class ServiceEndpointPolicyDefinitionsOperations(object): """ServiceEndpointPolicyDefinitionsOperations operations. You should not instantiate this class directly. Instead, you should create a Client instance that instantiates it for you and attaches it as an attribute. :ivar models: Alias to model classes used in this operation group. :type models: ~azure.mgmt.network.v2019_02_01.models :param client: Client for service requests. :param config: Configuration of service client. :param serializer: An object model serializer. :param deserializer: An object model deserializer. """ models = _models def __init__(self, client, config, serializer, deserializer): self._client = client self._serialize = serializer self._deserialize = deserializer self._config = config def _delete_initial( self, resource_group_name, # type: str service_endpoint_policy_name, # type: str service_endpoint_policy_definition_name, # type: str **kwargs # type: Any ): # type: (...) -> None cls = kwargs.pop('cls', None) # type: ClsType[None] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } error_map.update(kwargs.pop('error_map', {})) api_version = "2019-02-01" # Construct URL url = self._delete_initial.metadata['url'] # type: ignore path_format_arguments = { 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'), 'serviceEndpointPolicyName': self._serialize.url("service_endpoint_policy_name", service_endpoint_policy_name, 'str'), 'serviceEndpointPolicyDefinitionName': self._serialize.url("service_endpoint_policy_definition_name", service_endpoint_policy_definition_name, 'str'), 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), } url = self._client.format_url(url, **path_format_arguments) # Construct parameters query_parameters = {} # type: Dict[str, Any] query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') # Construct headers header_parameters = {} # type: Dict[str, Any] request = self._client.delete(url, query_parameters, header_parameters) pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200, 202, 204]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) if cls: return cls(pipeline_response, None, {}) _delete_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/serviceEndpointPolicies/{serviceEndpointPolicyName}/serviceEndpointPolicyDefinitions/{serviceEndpointPolicyDefinitionName}'} # type: ignore def begin_delete( self, resource_group_name, # type: str service_endpoint_policy_name, # type: str service_endpoint_policy_definition_name, # type: str **kwargs # type: Any ): # type: (...) -> LROPoller[None] """Deletes the specified ServiceEndpoint policy definitions. :param resource_group_name: The name of the resource group. :type resource_group_name: str :param service_endpoint_policy_name: The name of the Service Endpoint Policy. :type service_endpoint_policy_name: str :param service_endpoint_policy_definition_name: The name of the service endpoint policy definition. :type service_endpoint_policy_definition_name: str :keyword callable cls: A custom type or function that will be passed the direct response :keyword str continuation_token: A continuation token to restart a poller from a saved state. :keyword polling: Pass in True if you'd like the ARMPolling polling method, False for no polling, or your own initialized polling object for a personal polling strategy. :paramtype polling: bool or ~azure.core.polling.PollingMethod :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. :return: An instance of LROPoller that returns either None or the result of cls(response) :rtype: ~azure.core.polling.LROPoller[None] :raises ~azure.core.exceptions.HttpResponseError: """ polling = kwargs.pop('polling', True) # type: Union[bool, PollingMethod] cls = kwargs.pop('cls', None) # type: ClsType[None] lro_delay = kwargs.pop( 'polling_interval', self._config.polling_interval ) cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] if cont_token is None: raw_result = self._delete_initial( resource_group_name=resource_group_name, service_endpoint_policy_name=service_endpoint_policy_name, service_endpoint_policy_definition_name=service_endpoint_policy_definition_name, cls=lambda x,y,z: x, **kwargs ) kwargs.pop('error_map', None) kwargs.pop('content_type', None) def get_long_running_output(pipeline_response): if cls: return cls(pipeline_response, None, {}) path_format_arguments = { 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'), 'serviceEndpointPolicyName': self._serialize.url("service_endpoint_policy_name", service_endpoint_policy_name, 'str'), 'serviceEndpointPolicyDefinitionName': self._serialize.url("service_endpoint_policy_definition_name", service_endpoint_policy_definition_name, 'str'), 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), } if polling is True: polling_method = ARMPolling(lro_delay, lro_options={'final-state-via': 'location'}, path_format_arguments=path_format_arguments, **kwargs) elif polling is False: polling_method = NoPolling() else: polling_method = polling if cont_token: return LROPoller.from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, deserialization_callback=get_long_running_output ) else: return LROPoller(self._client, raw_result, get_long_running_output, polling_method) begin_delete.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/serviceEndpointPolicies/{serviceEndpointPolicyName}/serviceEndpointPolicyDefinitions/{serviceEndpointPolicyDefinitionName}'} # type: ignore def get( self, resource_group_name, # type: str service_endpoint_policy_name, # type: str service_endpoint_policy_definition_name, # type: str **kwargs # type: Any ): # type: (...) -> "_models.ServiceEndpointPolicyDefinition" """Get the specified service endpoint policy definitions from service endpoint policy. :param resource_group_name: The name of the resource group. :type resource_group_name: str :param service_endpoint_policy_name: The name of the service endpoint policy name. :type service_endpoint_policy_name: str :param service_endpoint_policy_definition_name: The name of the service endpoint policy definition name. :type service_endpoint_policy_definition_name: str :keyword callable cls: A custom type or function that will be passed the direct response :return: ServiceEndpointPolicyDefinition, or the result of cls(response) :rtype: ~azure.mgmt.network.v2019_02_01.models.ServiceEndpointPolicyDefinition :raises: ~azure.core.exceptions.HttpResponseError """ cls = kwargs.pop('cls', None) # type: ClsType["_models.ServiceEndpointPolicyDefinition"] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } error_map.update(kwargs.pop('error_map', {})) api_version = "2019-02-01" accept = "application/json" # Construct URL url = self.get.metadata['url'] # type: ignore path_format_arguments = { 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'), 'serviceEndpointPolicyName': self._serialize.url("service_endpoint_policy_name", service_endpoint_policy_name, 'str'), 'serviceEndpointPolicyDefinitionName': self._serialize.url("service_endpoint_policy_definition_name", service_endpoint_policy_definition_name, 'str'), 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), } url = self._client.format_url(url, **path_format_arguments) # Construct parameters query_parameters = {} # type: Dict[str, Any] query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') # Construct headers header_parameters = {} # type: Dict[str, Any] header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') request = self._client.get(url, query_parameters, header_parameters) pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) deserialized = self._deserialize('ServiceEndpointPolicyDefinition', pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized get.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/serviceEndpointPolicies/{serviceEndpointPolicyName}/serviceEndpointPolicyDefinitions/{serviceEndpointPolicyDefinitionName}'} # type: ignore def _create_or_update_initial( self, resource_group_name, # type: str service_endpoint_policy_name, # type: str service_endpoint_policy_definition_name, # type: str service_endpoint_policy_definitions, # type: "_models.ServiceEndpointPolicyDefinition" **kwargs # type: Any ): # type: (...) -> "_models.ServiceEndpointPolicyDefinition" cls = kwargs.pop('cls', None) # type: ClsType["_models.ServiceEndpointPolicyDefinition"] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } error_map.update(kwargs.pop('error_map', {})) api_version = "2019-02-01" content_type = kwargs.pop("content_type", "application/json") accept = "application/json" # Construct URL url = self._create_or_update_initial.metadata['url'] # type: ignore path_format_arguments = { 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'), 'serviceEndpointPolicyName': self._serialize.url("service_endpoint_policy_name", service_endpoint_policy_name, 'str'), 'serviceEndpointPolicyDefinitionName': self._serialize.url("service_endpoint_policy_definition_name", service_endpoint_policy_definition_name, 'str'), 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), } url = self._client.format_url(url, **path_format_arguments) # Construct parameters query_parameters = {} # type: Dict[str, Any] query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') # Construct headers header_parameters = {} # type: Dict[str, Any] header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str') header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') body_content_kwargs = {} # type: Dict[str, Any] body_content = self._serialize.body(service_endpoint_policy_definitions, 'ServiceEndpointPolicyDefinition') body_content_kwargs['content'] = body_content request = self._client.put(url, query_parameters, header_parameters, **body_content_kwargs) pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200, 201]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) if response.status_code == 200: deserialized = self._deserialize('ServiceEndpointPolicyDefinition', pipeline_response) if response.status_code == 201: deserialized = self._deserialize('ServiceEndpointPolicyDefinition', pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized _create_or_update_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/serviceEndpointPolicies/{serviceEndpointPolicyName}/serviceEndpointPolicyDefinitions/{serviceEndpointPolicyDefinitionName}'} # type: ignore def begin_create_or_update( self, resource_group_name, # type: str service_endpoint_policy_name, # type: str service_endpoint_policy_definition_name, # type: str service_endpoint_policy_definitions, # type: "_models.ServiceEndpointPolicyDefinition" **kwargs # type: Any ): # type: (...) -> LROPoller["_models.ServiceEndpointPolicyDefinition"] """Creates or updates a service endpoint policy definition in the specified service endpoint policy. :param resource_group_name: The name of the resource group. :type resource_group_name: str :param service_endpoint_policy_name: The name of the service endpoint policy. :type service_endpoint_policy_name: str :param service_endpoint_policy_definition_name: The name of the service endpoint policy definition name. :type service_endpoint_policy_definition_name: str :param service_endpoint_policy_definitions: Parameters supplied to the create or update service endpoint policy operation. :type service_endpoint_policy_definitions: ~azure.mgmt.network.v2019_02_01.models.ServiceEndpointPolicyDefinition :keyword callable cls: A custom type or function that will be passed the direct response :keyword str continuation_token: A continuation token to restart a poller from a saved state. :keyword polling: Pass in True if you'd like the ARMPolling polling method, False for no polling, or your own initialized polling object for a personal polling strategy. :paramtype polling: bool or ~azure.core.polling.PollingMethod :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. :return: An instance of LROPoller that returns either ServiceEndpointPolicyDefinition or the result of cls(response) :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.network.v2019_02_01.models.ServiceEndpointPolicyDefinition] :raises ~azure.core.exceptions.HttpResponseError: """ polling = kwargs.pop('polling', True) # type: Union[bool, PollingMethod] cls = kwargs.pop('cls', None) # type: ClsType["_models.ServiceEndpointPolicyDefinition"] lro_delay = kwargs.pop( 'polling_interval', self._config.polling_interval ) cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] if cont_token is None: raw_result = self._create_or_update_initial( resource_group_name=resource_group_name, service_endpoint_policy_name=service_endpoint_policy_name, service_endpoint_policy_definition_name=service_endpoint_policy_definition_name, service_endpoint_policy_definitions=service_endpoint_policy_definitions, cls=lambda x,y,z: x, **kwargs ) kwargs.pop('error_map', None) kwargs.pop('content_type', None) def get_long_running_output(pipeline_response): deserialized = self._deserialize('ServiceEndpointPolicyDefinition', pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized path_format_arguments = { 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'), 'serviceEndpointPolicyName': self._serialize.url("service_endpoint_policy_name", service_endpoint_policy_name, 'str'), 'serviceEndpointPolicyDefinitionName': self._serialize.url("service_endpoint_policy_definition_name", service_endpoint_policy_definition_name, 'str'), 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), } if polling is True: polling_method = ARMPolling(lro_delay, lro_options={'final-state-via': 'azure-async-operation'}, path_format_arguments=path_format_arguments, **kwargs) elif polling is False: polling_method = NoPolling() else: polling_method = polling if cont_token: return LROPoller.from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, deserialization_callback=get_long_running_output ) else: return LROPoller(self._client, raw_result, get_long_running_output, polling_method) begin_create_or_update.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/serviceEndpointPolicies/{serviceEndpointPolicyName}/serviceEndpointPolicyDefinitions/{serviceEndpointPolicyDefinitionName}'} # type: ignore def list_by_resource_group( self, resource_group_name, # type: str service_endpoint_policy_name, # type: str **kwargs # type: Any ): # type: (...) -> Iterable["_models.ServiceEndpointPolicyDefinitionListResult"] """Gets all service endpoint policy definitions in a service end point policy. :param resource_group_name: The name of the resource group. :type resource_group_name: str :param service_endpoint_policy_name: The name of the service endpoint policy name. :type service_endpoint_policy_name: str :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either ServiceEndpointPolicyDefinitionListResult or the result of cls(response) :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.network.v2019_02_01.models.ServiceEndpointPolicyDefinitionListResult] :raises: ~azure.core.exceptions.HttpResponseError """ cls = kwargs.pop('cls', None) # type: ClsType["_models.ServiceEndpointPolicyDefinitionListResult"] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } error_map.update(kwargs.pop('error_map', {})) api_version = "2019-02-01" accept = "application/json" def prepare_request(next_link=None): # Construct headers header_parameters = {} # type: Dict[str, Any] header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') if not next_link: # Construct URL url = self.list_by_resource_group.metadata['url'] # type: ignore path_format_arguments = { 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'), 'serviceEndpointPolicyName': self._serialize.url("service_endpoint_policy_name", service_endpoint_policy_name, 'str'), 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), } url = self._client.format_url(url, **path_format_arguments) # Construct parameters query_parameters = {} # type: Dict[str, Any] query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') request = self._client.get(url, query_parameters, header_parameters) else: url = next_link query_parameters = {} # type: Dict[str, Any] request = self._client.get(url, query_parameters, header_parameters) return request def extract_data(pipeline_response): deserialized = self._deserialize('ServiceEndpointPolicyDefinitionListResult', pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) return deserialized.next_link or None, iter(list_of_elem) def get_next(next_link=None): request = prepare_request(next_link) pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) return pipeline_response return ItemPaged( get_next, extract_data ) list_by_resource_group.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/serviceEndpointPolicies/{serviceEndpointPolicyName}/serviceEndpointPolicyDefinitions'} # type: ignore
sdk/network/azure-mgmt-network/azure/mgmt/network/v2019_02_01/operations/_service_endpoint_policy_definitions_operations.py
24,183
ServiceEndpointPolicyDefinitionsOperations operations. You should not instantiate this class directly. Instead, you should create a Client instance that instantiates it for you and attaches it as an attribute. :ivar models: Alias to model classes used in this operation group. :type models: ~azure.mgmt.network.v2019_02_01.models :param client: Client for service requests. :param config: Configuration of service client. :param serializer: An object model serializer. :param deserializer: An object model deserializer. Creates or updates a service endpoint policy definition in the specified service endpoint policy. :param resource_group_name: The name of the resource group. :type resource_group_name: str :param service_endpoint_policy_name: The name of the service endpoint policy. :type service_endpoint_policy_name: str :param service_endpoint_policy_definition_name: The name of the service endpoint policy definition name. :type service_endpoint_policy_definition_name: str :param service_endpoint_policy_definitions: Parameters supplied to the create or update service endpoint policy operation. :type service_endpoint_policy_definitions: ~azure.mgmt.network.v2019_02_01.models.ServiceEndpointPolicyDefinition :keyword callable cls: A custom type or function that will be passed the direct response :keyword str continuation_token: A continuation token to restart a poller from a saved state. :keyword polling: Pass in True if you'd like the ARMPolling polling method, False for no polling, or your own initialized polling object for a personal polling strategy. :paramtype polling: bool or ~azure.core.polling.PollingMethod :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. :return: An instance of LROPoller that returns either ServiceEndpointPolicyDefinition or the result of cls(response) :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.network.v2019_02_01.models.ServiceEndpointPolicyDefinition] :raises ~azure.core.exceptions.HttpResponseError: Deletes the specified ServiceEndpoint policy definitions. :param resource_group_name: The name of the resource group. :type resource_group_name: str :param service_endpoint_policy_name: The name of the Service Endpoint Policy. :type service_endpoint_policy_name: str :param service_endpoint_policy_definition_name: The name of the service endpoint policy definition. :type service_endpoint_policy_definition_name: str :keyword callable cls: A custom type or function that will be passed the direct response :keyword str continuation_token: A continuation token to restart a poller from a saved state. :keyword polling: Pass in True if you'd like the ARMPolling polling method, False for no polling, or your own initialized polling object for a personal polling strategy. :paramtype polling: bool or ~azure.core.polling.PollingMethod :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. :return: An instance of LROPoller that returns either None or the result of cls(response) :rtype: ~azure.core.polling.LROPoller[None] :raises ~azure.core.exceptions.HttpResponseError: Get the specified service endpoint policy definitions from service endpoint policy. :param resource_group_name: The name of the resource group. :type resource_group_name: str :param service_endpoint_policy_name: The name of the service endpoint policy name. :type service_endpoint_policy_name: str :param service_endpoint_policy_definition_name: The name of the service endpoint policy definition name. :type service_endpoint_policy_definition_name: str :keyword callable cls: A custom type or function that will be passed the direct response :return: ServiceEndpointPolicyDefinition, or the result of cls(response) :rtype: ~azure.mgmt.network.v2019_02_01.models.ServiceEndpointPolicyDefinition :raises: ~azure.core.exceptions.HttpResponseError Gets all service endpoint policy definitions in a service end point policy. :param resource_group_name: The name of the resource group. :type resource_group_name: str :param service_endpoint_policy_name: The name of the service endpoint policy name. :type service_endpoint_policy_name: str :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either ServiceEndpointPolicyDefinitionListResult or the result of cls(response) :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.network.v2019_02_01.models.ServiceEndpointPolicyDefinitionListResult] :raises: ~azure.core.exceptions.HttpResponseError coding=utf-8 -------------------------------------------------------------------------- Copyright (c) Microsoft Corporation. All rights reserved. Licensed under the MIT License. See License.txt in the project root for license information. Code generated by Microsoft (R) AutoRest Code Generator. Changes may cause incorrect behavior and will be lost if the code is regenerated. -------------------------------------------------------------------------- pylint: disable=unused-import,ungrouped-imports type: str type: str type: str type: Any type: (...) -> None type: ClsType[None] Construct URL type: ignore Construct parameters type: Dict[str, Any] Construct headers type: Dict[str, Any] type: ignore type: str type: str type: str type: Any type: (...) -> LROPoller[None] type: Union[bool, PollingMethod] type: ClsType[None] type: Optional[str] type: ignore type: str type: str type: str type: Any type: (...) -> "_models.ServiceEndpointPolicyDefinition" type: ClsType["_models.ServiceEndpointPolicyDefinition"] Construct URL type: ignore Construct parameters type: Dict[str, Any] Construct headers type: Dict[str, Any] type: ignore type: str type: str type: str type: "_models.ServiceEndpointPolicyDefinition" type: Any type: (...) -> "_models.ServiceEndpointPolicyDefinition" type: ClsType["_models.ServiceEndpointPolicyDefinition"] Construct URL type: ignore Construct parameters type: Dict[str, Any] Construct headers type: Dict[str, Any] type: Dict[str, Any] type: ignore type: str type: str type: str type: "_models.ServiceEndpointPolicyDefinition" type: Any type: (...) -> LROPoller["_models.ServiceEndpointPolicyDefinition"] type: Union[bool, PollingMethod] type: ClsType["_models.ServiceEndpointPolicyDefinition"] type: Optional[str] type: ignore type: str type: str type: Any type: (...) -> Iterable["_models.ServiceEndpointPolicyDefinitionListResult"] type: ClsType["_models.ServiceEndpointPolicyDefinitionListResult"] Construct headers type: Dict[str, Any] Construct URL type: ignore Construct parameters type: Dict[str, Any] type: Dict[str, Any] type: ignore
6,678
en
0.50671
from typing import List, Optional from .result import Result, Ok, Err res1 = Ok('hello') # type: Result[str, int] if isinstance(res1, Ok): ok = res1 # type: Ok[str] okValue = res1.ok() # type: str mapped_to_float = res1.map_or(1.0, lambda s: len(s) * 1.5) # type: float else: err = res1 # type: Err[int] errValue = err.err() # type: int mapped_to_list = res1.map_err(lambda e: [e]).err() # type: Optional[List[int]] # Test constructor functions res1 = Ok() res2 = Ok(42) res3 = Err(1)
result/typetests.py
520
type: Result[str, int] type: Ok[str] type: str type: float type: Err[int] type: int type: Optional[List[int]] Test constructor functions
136
en
0.195438
"""PyTorch optimizer builders.""" import argparse import torch from espnet.optimizer.factory import OptimizerFactoryInterface from espnet.optimizer.parser import adadelta from espnet.optimizer.parser import adam from espnet.optimizer.parser import sgd class AdamFactory(OptimizerFactoryInterface): """Adam factory.""" @staticmethod def add_arguments(parser: argparse.ArgumentParser) -> argparse.ArgumentParser: """Register args.""" return adam(parser) @staticmethod def from_args(target, args: argparse.Namespace): """Initialize optimizer from argparse Namespace. Args: target: for pytorch `model.parameters()`, for chainer `model` args (argparse.Namespace): parsed command-line args """ return torch.optim.Adam( target, lr=args.lr, weight_decay=args.weight_decay, betas=(args.beta1, args.beta2), ) class SGDFactory(OptimizerFactoryInterface): """SGD factory.""" @staticmethod def add_arguments(parser: argparse.ArgumentParser) -> argparse.ArgumentParser: """Register args.""" return sgd(parser) @staticmethod def from_args(target, args: argparse.Namespace): """Initialize optimizer from argparse Namespace. Args: target: for pytorch `model.parameters()`, for chainer `model` args (argparse.Namespace): parsed command-line args """ return torch.optim.SGD( target, lr=args.lr, weight_decay=args.weight_decay, ) class AdadeltaFactory(OptimizerFactoryInterface): """Adadelta factory.""" @staticmethod def add_arguments(parser: argparse.ArgumentParser) -> argparse.ArgumentParser: """Register args.""" return adadelta(parser) @staticmethod def from_args(target, args: argparse.Namespace): """Initialize optimizer from argparse Namespace. Args: target: for pytorch `model.parameters()`, for chainer `model` args (argparse.Namespace): parsed command-line args """ return torch.optim.Adadelta( target, rho=args.rho, eps=args.eps, weight_decay=args.weight_decay, ) OPTIMIZER_FACTORY_DICT = { "adam": AdamFactory, "sgd": SGDFactory, "adadelta": AdadeltaFactory, }
espnet/optimizer/pytorch.py
2,469
Adadelta factory. Adam factory. SGD factory. Register args. Register args. Register args. Initialize optimizer from argparse Namespace. Args: target: for pytorch `model.parameters()`, for chainer `model` args (argparse.Namespace): parsed command-line args Initialize optimizer from argparse Namespace. Args: target: for pytorch `model.parameters()`, for chainer `model` args (argparse.Namespace): parsed command-line args Initialize optimizer from argparse Namespace. Args: target: for pytorch `model.parameters()`, for chainer `model` args (argparse.Namespace): parsed command-line args PyTorch optimizer builders.
666
en
0.22775
#-*- coding: utf-8 -*- from __future__ import unicode_literals from django.contrib import admin from salmonella.admin import SalmonellaMixin from edw.models.postal_zone import PostZoneModel # =========================================================================================== # PostalZoneAdmin # =========================================================================================== class PostalZoneAdmin(SalmonellaMixin, admin.ModelAdmin): model = PostZoneModel list_display = ['name', 'active'] fields = ['term', 'postal_codes', 'active'] search_fields = ('term__name', 'postal_codes') salmonella_fields = ('term',) admin.site.register(PostZoneModel, PostalZoneAdmin)
backend/edw/admin/postal_zone.py
712
-*- coding: utf-8 -*- =========================================================================================== PostalZoneAdmin ===========================================================================================
221
en
0.372749
"""The Admin module for the Bower Cache registry.""" import logging from django import forms from django.core.exceptions import ValidationError from django.conf import settings from django.conf.urls import patterns, url from django.contrib import admin, messages from django.contrib.admin.views.main import ChangeList from django.shortcuts import redirect, get_object_or_404 from django.views.decorators.http import require_POST from . import bowerlib from .models import ClonedRepo, Package from .query import ClonedRepoQuerySet LOG = logging.getLogger(__name__) class ClonedRepoChangeList(ChangeList): def get_query_set(self, request): return self.root_queryset def get_results(self, request): all_repo_count = len(self.root_queryset) self.result_count = all_repo_count self.full_result_count = all_repo_count self.result_list = list(self.root_queryset) self.can_show_all = True self.multi_page = False self.paginator = self.model_admin.get_paginator(request, self.result_list, self.list_per_page) class ClonedRepoAdmin(admin.ModelAdmin): actions = None def get_urls(self): urls = super(ClonedRepoAdmin, self).get_urls() more_urls = patterns('', url(r'^(.+)/pull/$', self.admin_site.admin_view(self.git_pull_view), name='pull'), url(r'^update-all$', self.admin_site.admin_view(require_POST(self.update_all_view)), name='update-all'), ) return more_urls + urls def queryset(self, request): return ClonedRepoQuerySet(model=ClonedRepo) def get_changelist(self, request, **kwargs): return ClonedRepoChangeList def get_form(self, request, obj=None, **kwargs): if obj is not None: return super(ClonedRepoAdmin, self).get_form(request, obj, **kwargs) else: # Here we override the form for creation. return NewRepoForm def save_form(self, request, form, change): """Here we pluck out the data to create a new cloned repo. Form is an instance of NewRepoForm. """ name = form.cleaned_data['name'] origin_url = form.cleaned_data['origin_url'] res = ClonedRepo(name=name, origin=origin_url) LOG.info("New repo form produced %s" % str(res)) form.save(commit=False) return res def get_readonly_fields(self, request, obj=None): """Hide the origin field from editing, but not creation.""" return ('origin',) if obj else () def add_view(self, request, **kwargs): """A custom add_view, to catch exceptions from 'save_model'. Just to be clear, this is very filthy. """ try: return super(ClonedRepoAdmin, self).add_view(request, **kwargs) except ValidationError: # Rerender the form, having messaged the user. return redirect(request.path) def save_model(self, request, obj, form, change): try: obj.save() except Exception as exc: self.message_user(request, "Save failed: %s" % str(exc), level=messages.ERROR) raise ValidationError(str(exc)) # A success message will be flashed by default def git_pull_view(self, request, repo_name): """Perform a git pull and redirect back to the repo.""" LOG.info("Pull requested for %s." % repo_name) repo = get_object_or_404(self.model, name=repo_name) repo.pull() self.message_user(request, "Repo %s successfully updated." % repo_name, level=messages.SUCCESS) return redirect('admin:registry_clonedrepo_change', repo_name) def update_all_view(self, request): """Update all repositories and redirect back to the repo list.""" LOG.info("Total update requested.") total_count = errors = 0 for repo in self.model.objects.all(): total_count += 1 try: repo.pull() except: LOG.exception('While updating %s.' % repo) errors += 1 msg = "{0} repos successfully updated, {1} failed.".format(total_count, errors) self.message_user(request, msg, level=messages.SUCCESS) return redirect('admin:registry_clonedrepo_changelist') class NewRepoForm(forms.ModelForm): """A special form for creating cloned repositories.""" origin_url = forms.CharField(required=False) choices = [('upstream', 'from upstream Bower'), ('origin_url', 'from git repo:')] origin_widget = forms.RadioSelect origin_source = forms.ChoiceField(choices=choices, widget=origin_widget, initial=choices[0][0]) def clean(self): """Validate the new repo form. Might perform a request to upstream Bower.""" cleaned_data = super(NewRepoForm, self).clean() origin_url = cleaned_data['origin_url'] origin_source = cleaned_data['origin_source'] if origin_source == 'origin_url' and not origin_url: msg = 'Please provide an origin URL.' self._errors['origin_url'] = self.error_class([msg]) del cleaned_data['origin_url'] del cleaned_data['origin_source'] elif origin_source == 'upstream': upstream = settings.UPSTREAM_BOWER_REGISTRY name = cleaned_data['name'] try: upstream_pkg = bowerlib.get_package(upstream, name) except IOError as exc: msg = str(exc) self._errors['origin_source'] = self.error_class([msg]) else: if not upstream_pkg: msg = 'Upstream registry has no knowledge of %s.' % name self._errors['name'] = self.error_class([msg]) del cleaned_data['name'] else: upstream_origin_url = upstream_pkg['url'] cleaned_data['origin_url'] = upstream_origin_url return cleaned_data class Meta: model = ClonedRepo exclude = ['origin'] admin.site.register(Package) admin.site.register(ClonedRepo, ClonedRepoAdmin)
registry/admin.py
6,519
A special form for creating cloned repositories. A custom add_view, to catch exceptions from 'save_model'. Just to be clear, this is very filthy. Validate the new repo form. Might perform a request to upstream Bower. Hide the origin field from editing, but not creation. Perform a git pull and redirect back to the repo. Here we pluck out the data to create a new cloned repo. Form is an instance of NewRepoForm. Update all repositories and redirect back to the repo list. The Admin module for the Bower Cache registry. Here we override the form for creation. Rerender the form, having messaged the user. A success message will be flashed by default
654
en
0.844478
import re from typing import Pattern from unittest import mock import pytest from faker import Faker, providers from faker.providers.address.cs_CZ import Provider as CsCzAddressProvider from faker.providers.address.da_DK import Provider as DaDkAddressProvider from faker.providers.address.de_AT import Provider as DeAtAddressProvider from faker.providers.address.de_CH import Provider as DeChAddressProvider from faker.providers.address.de_DE import Provider as DeDeAddressProvider from faker.providers.address.el_GR import Provider as ElGrAddressProvider from faker.providers.address.en_AU import Provider as EnAuAddressProvider from faker.providers.address.en_CA import Provider as EnCaAddressProvider from faker.providers.address.en_GB import Provider as EnGbAddressProvider from faker.providers.address.en_IE import Provider as EnIeAddressProvider from faker.providers.address.en_IN import Provider as EnInAddressProvider from faker.providers.address.en_PH import Provider as EnPhAddressProvider from faker.providers.address.en_US import Provider as EnUsAddressProvider from faker.providers.address.es_ES import Provider as EsEsAddressProvider from faker.providers.address.es_MX import Provider as EsMxAddressProvider from faker.providers.address.fa_IR import Provider as FaIrAddressProvider from faker.providers.address.fi_FI import Provider as FiFiAddressProvider from faker.providers.address.fr_FR import Provider as FrFrAddressProvider from faker.providers.address.he_IL import Provider as HeIlAddressProvider from faker.providers.address.hi_IN import Provider as HiInAddressProvider from faker.providers.address.hr_HR import Provider as HrHrAddressProvider from faker.providers.address.hy_AM import Provider as HyAmAddressProvider from faker.providers.address.ja_JP import Provider as JaJpAddressProvider from faker.providers.address.ne_NP import Provider as NeNpAddressProvider from faker.providers.address.no_NO import Provider as NoNoAddressProvider from faker.providers.address.pt_BR import Provider as PtBrAddressProvider from faker.providers.address.pt_PT import Provider as PtPtAddressProvider from faker.providers.address.ro_RO import Provider as RoRoAddressProvider from faker.providers.address.ru_RU import Provider as RuRuAddressProvider from faker.providers.address.sk_SK import Provider as SkSkAddressProvider from faker.providers.address.ta_IN import Provider as TaInAddressProvider from faker.providers.address.th_TH import Provider as ThThAddressProvider from faker.providers.address.zh_CN import Provider as ZhCnAddressProvider from faker.providers.address.zh_TW import Provider as ZhTwAddressProvider class TestBaseProvider: """Test address provider methods""" def test_alpha_2_country_codes(self, faker, num_samples): for _ in range(num_samples): country_code = faker.country_code(representation="alpha-2") assert len(country_code) == 2 assert country_code.isalpha() def test_alpha_2_country_codes_as_default(self, faker, num_samples): for _ in range(num_samples): country_code = faker.country_code() assert len(country_code) == 2 assert country_code.isalpha() def test_alpha_3_country_codes(self, faker, num_samples): for _ in range(num_samples): country_code = faker.country_code(representation="alpha-3") assert len(country_code) == 3 assert country_code.isalpha() def test_bad_country_code_representation(self, faker, num_samples): for _ in range(num_samples): with pytest.raises(ValueError): faker.country_code(representation="hello") def _collect_fakers_for_locales(self): cached_locales = [] language_locale_codes = providers.BaseProvider.language_locale_codes for code, countries in language_locale_codes.items(): for country in countries: name = f"{code}_{country}" try: faker = Faker(name) cached_locales.append(faker) except AttributeError as e: print(f"Cannot generate faker for {name}: {e}. Skipped") return cached_locales def _fakers_for_locales(self): if not hasattr(self.__class__, "cached_locales"): self.__class__.cached_locales = self._collect_fakers_for_locales() return self.cached_locales def test_administrative_unit_all_locales(self): for faker in self._fakers_for_locales(): if faker.current_country_code() not in ["IL", "GE", "TW", "UA", "NZ"]: try: assert isinstance(faker.administrative_unit(), str) except Exception as e: raise e.__class__(faker.current_country_code(), *e.args) def test_country_code_all_locales(self): for faker in self._fakers_for_locales(): assert isinstance(faker.current_country(), str) def test_current_country_errors(self): dt = providers.date_time countries_duplicated = [*dt.Provider.countries, *dt.Provider.countries] with mock.patch.object(dt.Provider, "countries", countries_duplicated), pytest.raises(ValueError) as e: Faker("en_US").current_country() assert "Ambiguous" in str(e) country_code = "faker.providers.address.Provider.current_country_code" with pytest.raises(ValueError), mock.patch(country_code, lambda self: "en_ZZ"): Faker("en_US").current_country() class TestCsCz: """Test cs_CZ address provider methods""" def test_street_suffix_short(self, faker, num_samples): for _ in range(num_samples): street_suffix_short = faker.street_suffix_short() assert isinstance(street_suffix_short, str) assert street_suffix_short in CsCzAddressProvider.street_suffixes_short def test_street_suffix_long(self, faker, num_samples): for _ in range(num_samples): street_suffix_long = faker.street_suffix_long() assert isinstance(street_suffix_long, str) assert street_suffix_long in CsCzAddressProvider.street_suffixes_long def test_city_name(self, faker, num_samples): for _ in range(num_samples): city = faker.city_name() assert isinstance(city, str) assert city in CsCzAddressProvider.cities def test_street_name(self, faker, num_samples): for _ in range(num_samples): street_name = faker.street_name() assert isinstance(street_name, str) assert street_name in CsCzAddressProvider.streets def test_state(self, faker, num_samples): for _ in range(num_samples): state = faker.state() assert isinstance(state, str) assert state in CsCzAddressProvider.states def test_postcode(self, faker, num_samples): for _ in range(num_samples): postcode = faker.postcode() assert isinstance(postcode, str) assert re.fullmatch(r"\d{3} \d{2}", postcode) def test_city_with_postcode(self, faker, num_samples): for _ in range(num_samples): city_with_postcode = faker.city_with_postcode() assert isinstance(city_with_postcode, str) match = re.fullmatch(r"\d{3} \d{2} (?P<city>.*)", city_with_postcode) assert match.group("city") in CsCzAddressProvider.cities class TestDaDk: """Test dk_DK address provider methods""" def test_street_prefix(self, faker, num_samples): for _ in range(num_samples): street_prefix = faker.street_prefix() assert isinstance(street_prefix, str) assert street_prefix in DaDkAddressProvider.street_prefixes def test_city_name(self, faker, num_samples): for _ in range(num_samples): city = faker.city_name() assert isinstance(city, str) assert city in DaDkAddressProvider.cities def test_state(self, faker, num_samples): for _ in range(num_samples): state = faker.state() assert isinstance(state, str) assert state in DaDkAddressProvider.states def test_postcode(self, faker, num_samples): for _ in range(num_samples): postcode = faker.postcode() assert isinstance(postcode, str) assert re.fullmatch(r"\d{4}", postcode) class TestDeAt: """Test de_AT address provider methods""" def test_city(self, faker, num_samples): for _ in range(num_samples): city = faker.city() assert isinstance(city, str) assert city in DeAtAddressProvider.cities def test_state(self, faker, num_samples): for _ in range(num_samples): state = faker.state() assert isinstance(state, str) assert state in DeAtAddressProvider.states def test_street_suffix_short(self, faker, num_samples): for _ in range(num_samples): street_suffix_short = faker.street_suffix_short() assert isinstance(street_suffix_short, str) assert street_suffix_short in DeAtAddressProvider.street_suffixes_short def test_street_suffix_long(self, faker, num_samples): for _ in range(num_samples): street_suffix_long = faker.street_suffix_long() assert isinstance(street_suffix_long, str) assert street_suffix_long in DeAtAddressProvider.street_suffixes_long def test_country(self, faker, num_samples): for _ in range(num_samples): country = faker.country() assert isinstance(country, str) assert country in DeAtAddressProvider.countries def test_postcode(self, faker, num_samples): for _ in range(num_samples): postcode = faker.postcode() assert isinstance(postcode, str) assert re.fullmatch(r"\d{4}", postcode) def test_city_with_postcode(self, faker, num_samples): for _ in range(num_samples): city_with_postcode = faker.city_with_postcode() assert isinstance(city_with_postcode, str) match = re.fullmatch(r"\d{4} (?P<city>.*)", city_with_postcode) assert match.groupdict()["city"] in DeAtAddressProvider.cities class TestDeDe: """Test de_DE address provider methods""" def test_city(self, faker, num_samples): for _ in range(num_samples): city = faker.city() assert isinstance(city, str) assert city in DeDeAddressProvider.cities def test_state(self, faker, num_samples): for _ in range(num_samples): state = faker.state() assert isinstance(state, str) assert state in DeDeAddressProvider.states def test_street_suffix_short(self, faker, num_samples): for _ in range(num_samples): street_suffix_short = faker.street_suffix_short() assert isinstance(street_suffix_short, str) assert street_suffix_short in DeDeAddressProvider.street_suffixes_short def test_street_suffix_long(self, faker, num_samples): for _ in range(num_samples): street_suffix_long = faker.street_suffix_long() assert isinstance(street_suffix_long, str) assert street_suffix_long in DeDeAddressProvider.street_suffixes_long def test_country(self, faker, num_samples): for _ in range(num_samples): country = faker.country() assert isinstance(country, str) assert country in DeDeAddressProvider.countries def test_postcode(self, faker, num_samples): for _ in range(num_samples): postcode = faker.postcode() assert isinstance(postcode, str) assert re.fullmatch(r"\d{5}", postcode) def test_city_with_postcode(self, faker, num_samples): for _ in range(num_samples): city_with_postcode = faker.city_with_postcode() assert isinstance(city_with_postcode, str) match = re.fullmatch(r"\d{5} (?P<city>.*)", city_with_postcode) assert match.groupdict()["city"] in DeDeAddressProvider.cities class TestElGr: """Test el_GR address provider methods""" def test_line_address(self, faker, num_samples): for _ in range(num_samples): address = faker.line_address() assert isinstance(address, str) def test_street_prefix_short(self, faker, num_samples): for _ in range(num_samples): street_prefix_short = faker.street_prefix_short() assert isinstance(street_prefix_short, str) assert street_prefix_short in ElGrAddressProvider.street_prefixes_short def test_street_prefix_long(self, faker, num_samples): for _ in range(num_samples): street_prefix_long = faker.street_prefix_long() assert isinstance(street_prefix_long, str) assert street_prefix_long in ElGrAddressProvider.street_prefixes_long def test_street(self, faker, num_samples): for _ in range(num_samples): street = faker.street() assert isinstance(street, str) assert street in ElGrAddressProvider.localities def test_city(self, faker, num_samples): for _ in range(num_samples): city = faker.city() assert isinstance(city, str) assert city in ElGrAddressProvider.cities def test_region(self, faker, num_samples): for _ in range(num_samples): region = faker.region() assert isinstance(region, str) assert region in ElGrAddressProvider.regions class TestEnAu: """Test en_AU address provider methods""" def test_postcode(self, faker, num_samples): for _ in range(num_samples): postcode = faker.postcode() assert isinstance(postcode, str) assert re.fullmatch(r"\d{4}", postcode) def test_state(self, faker, num_samples): for _ in range(num_samples): state = faker.state() assert isinstance(state, str) assert state in EnAuAddressProvider.states def test_city_prefix(self, faker, num_samples): for _ in range(num_samples): city_prefix = faker.city_prefix() assert isinstance(city_prefix, str) assert city_prefix in EnAuAddressProvider.city_prefixes def test_state_abbr(self, faker, num_samples): for _ in range(num_samples): state_abbr = faker.state_abbr() assert isinstance(state_abbr, str) assert state_abbr in EnAuAddressProvider.states_abbr assert state_abbr.isupper() class TestEnNz: """Test en_NZ address provider methods""" def test_state(self, faker, num_samples): for _ in range(num_samples): # No states in New Zealand with pytest.raises(AttributeError): faker.state() def test_postcode(self, faker, num_samples): for _ in range(num_samples): postcode = faker.postcode() assert isinstance(postcode, str) assert re.fullmatch(r"\d{4}", postcode) class TestEnCa: """Test en_CA address provider methods""" valid_postcode_letter_re = r"[{}]".format("".join(EnCaAddressProvider.postal_code_letters)) valid_postcode_re = r"{0}[0-9]{0} ?[0-9]{0}[0-9]".format(valid_postcode_letter_re) def test_postcode(self, faker, num_samples): for _ in range(num_samples): postcode = faker.postcode() assert isinstance(postcode, str) assert re.fullmatch(self.valid_postcode_re, postcode) def test_postcode_in_province(self, faker, num_samples): for _ in range(num_samples): for province_abbr in EnCaAddressProvider.provinces_abbr: code = faker.postcode_in_province(province_abbr) assert code[0] in EnCaAddressProvider.provinces_postcode_prefixes[province_abbr] with pytest.raises(Exception): faker.postcode_in_province("XX") def test_postalcode(self, faker, num_samples): for _ in range(num_samples): postalcode = faker.postalcode() assert isinstance(postalcode, str) assert re.fullmatch(self.valid_postcode_re, postalcode) def test_postal_code_letter(self, faker, num_samples): for _ in range(num_samples): postal_code_letter = faker.postal_code_letter() assert isinstance(postal_code_letter, str) assert re.fullmatch(self.valid_postcode_letter_re, postal_code_letter) def test_province(self, faker, num_samples): for _ in range(num_samples): province = faker.province() assert isinstance(province, str) assert province in EnCaAddressProvider.provinces def test_province_abbr(self, faker, num_samples): for _ in range(num_samples): province_abbr = faker.province_abbr() assert isinstance(province_abbr, str) assert province_abbr in EnCaAddressProvider.provinces_abbr def test_city_prefix(self, faker, num_samples): for _ in range(num_samples): city_prefix = faker.city_prefix() assert isinstance(city_prefix, str) assert city_prefix in EnCaAddressProvider.city_prefixes def test_secondary_address(self, faker, num_samples): for _ in range(num_samples): secondary_address = faker.secondary_address() assert isinstance(secondary_address, str) assert re.fullmatch(r"(?:Apt\.|Suite) \d{3}", secondary_address) class TestEnGb: """Test en_GB address provider methods""" def test_postcode(self, faker, num_samples): ukpcp = pytest.importorskip("ukpostcodeparser.parser") for _ in range(num_samples): assert isinstance(ukpcp.parse_uk_postcode(faker.postcode()), tuple) def test_county(self, faker, num_samples): for _ in range(num_samples): county = faker.county() assert isinstance(county, str) assert county in EnGbAddressProvider.counties class TestEnIe: """Test en_IE address provider methods""" def test_postcode(self, faker, num_samples): """https://stackoverflow.com/questions/33391412/validation-for-irish-eircode""" for _ in range(num_samples): postcode = faker.postcode() assert isinstance(postcode, str) assert re.fullmatch(r"(?:^[AC-FHKNPRTV-Y][0-9]{2}|D6W)[ -]?[0-9AC-FHKNPRTV-Y]{4}$", postcode) def test_county(self, faker, num_samples): for _ in range(num_samples): county = faker.county() assert isinstance(county, str) assert county in EnIeAddressProvider.counties class TestEnUS: """Test en_US address provider methods""" def test_city_prefix(self, faker, num_samples): for _ in range(num_samples): city_prefix = faker.city_prefix() assert isinstance(city_prefix, str) assert city_prefix in EnUsAddressProvider.city_prefixes def test_state(self, faker, num_samples): for _ in range(num_samples): state = faker.state() assert isinstance(state, str) assert state in EnUsAddressProvider.states def test_state_abbr(self, faker, num_samples): for _ in range(num_samples): state_abbr = faker.state_abbr() assert isinstance(state_abbr, str) states_and_territories = EnUsAddressProvider.states_and_territories_abbr assert state_abbr in states_and_territories def test_state_abbr_no_territories(self, faker, num_samples): for _ in range(num_samples): state_abbr = faker.state_abbr(include_territories=False) assert isinstance(state_abbr, str) assert state_abbr in EnUsAddressProvider.states_abbr def test_postcode(self, faker, num_samples): for _ in range(num_samples): code = faker.postcode() assert isinstance(code, str) and len(code) == 5 assert 501 <= int(code) <= 99950 def test_postcode_in_state(self, faker, num_samples): for _ in range(num_samples): for state_abbr in EnUsAddressProvider.states_abbr: code = faker.postcode_in_state(state_abbr) assert re.fullmatch(r"\d{5}", code) assert int(code) >= EnUsAddressProvider.states_postcode[state_abbr][0] assert int(code) <= EnUsAddressProvider.states_postcode[state_abbr][1] with pytest.raises(Exception): faker.postcode_in_state("XX") def test_zipcode(self, faker, num_samples): for _ in range(num_samples): zipcode = faker.zipcode() assert isinstance(zipcode, str) and len(zipcode) == 5 assert 501 <= int(zipcode) <= 99950 def test_zipcode_in_state(self, faker, num_samples): for _ in range(num_samples): for state_abbr in EnUsAddressProvider.states_abbr: code = faker.zipcode_in_state(state_abbr) assert re.fullmatch(r"\d{5}", code) assert int(code) >= EnUsAddressProvider.states_postcode[state_abbr][0] assert int(code) <= EnUsAddressProvider.states_postcode[state_abbr][1] with pytest.raises(Exception): faker.zipcode_in_state("XX") def test_zipcode_plus4(self, faker, num_samples): for _ in range(num_samples): zipcode_plus4 = faker.zipcode_plus4() assert isinstance(zipcode_plus4, str) zipcode, plus4 = zipcode_plus4.split("-") assert 501 <= int(zipcode) <= 99950 assert 1 <= int(plus4) <= 9999 def test_military_ship(self, faker, num_samples): for _ in range(num_samples): military_ship = faker.military_ship() assert isinstance(military_ship, str) assert military_ship in EnUsAddressProvider.military_ship_prefix def test_military_state(self, faker, num_samples): for _ in range(num_samples): military_state = faker.military_state() assert isinstance(military_state, str) assert military_state in EnUsAddressProvider.military_state_abbr def test_military_apo(self, faker, num_samples): for _ in range(num_samples): military_apo = faker.military_apo() assert isinstance(military_apo, str) assert re.fullmatch(r"PSC \d{4}, Box \d{4}", military_apo) def test_military_dpo(self, faker, num_samples): for _ in range(num_samples): military_dpo = faker.military_dpo() assert isinstance(military_dpo, str) assert re.fullmatch(r"Unit \d{4} Box \d{4}", military_dpo) def test_postalcode(self, faker, num_samples): for _ in range(num_samples): postalcode = faker.postalcode() assert isinstance(postalcode, str) and len(postalcode) == 5 assert 501 <= int(postalcode) <= 99950 def test_postalcode_in_state(self, faker, num_samples): for _ in range(num_samples): for state_abbr in EnUsAddressProvider.states_abbr: code = faker.postalcode_in_state(state_abbr) assert re.fullmatch(r"\d{5}", code) assert int(code) >= EnUsAddressProvider.states_postcode[state_abbr][0] assert int(code) <= EnUsAddressProvider.states_postcode[state_abbr][1] with pytest.raises(Exception): faker.postalcode_in_state("XX") class TestEsEs: """Test es_ES address provider methods""" def test_state_name(self, faker, num_samples): for _ in range(num_samples): state_name = faker.state_name() assert isinstance(state_name, str) assert state_name in EsEsAddressProvider.states def test_street_prefix(self, faker, num_samples): for _ in range(num_samples): street_prefix = faker.street_prefix() assert isinstance(street_prefix, str) assert street_prefix in EsEsAddressProvider.street_prefixes def test_secondary_address(self, faker, num_samples): for _ in range(num_samples): secondary_address = faker.secondary_address() assert isinstance(secondary_address, str) assert re.fullmatch(r"Apt\. \d{2}|Piso \d|Puerta \d", secondary_address) def test_regions(self, faker, num_samples): for _ in range(num_samples): region = faker.region() assert isinstance(region, str) assert region in EsEsAddressProvider.regions def test_autonomous_community(self, faker, num_samples): for _ in range(num_samples): # Spanish regions, also known as "autonomous communities" autonomous_community = faker.autonomous_community() assert isinstance(autonomous_community, str) assert autonomous_community in EsEsAddressProvider.regions class TestEsMx: """Test es_MX address provider methods""" def test_city_prefix(self, faker, num_samples): for _ in range(num_samples): city_prefix = faker.city_prefix() assert isinstance(city_prefix, str) assert city_prefix in EsMxAddressProvider.city_prefixes def test_city_suffix(self, faker, num_samples): for _ in range(num_samples): city_suffix = faker.city_suffix() assert isinstance(city_suffix, str) assert city_suffix in EsMxAddressProvider.city_suffixes def test_city_adjective(self, faker, num_samples): for _ in range(num_samples): city_adjective = faker.city_adjective() assert isinstance(city_adjective, str) assert city_adjective in EsMxAddressProvider.city_adjectives def test_street_prefix(self, faker, num_samples): for _ in range(num_samples): street_prefix = faker.street_prefix() assert isinstance(street_prefix, str) assert street_prefix in EsMxAddressProvider.street_prefixes def test_secondary_address(self, faker, num_samples): for _ in range(num_samples): secondary_address = faker.secondary_address() assert isinstance(secondary_address, str) assert re.fullmatch( r"\d{3} \d{3}|\d{3} Interior \d{3}|\d{3} Edif\. \d{3} , Depto\. \d{3}", secondary_address, ) def test_state(self, faker, num_samples): states = [state_name for state_abbr, state_name in EsMxAddressProvider.states] for _ in range(num_samples): state = faker.state() assert isinstance(state, str) assert state in states def test_state_abbr(self, faker, num_samples): state_abbrs = [state_abbr for state_abbr, state_name in EsMxAddressProvider.states] for _ in range(num_samples): state_abbr = faker.state_abbr() assert isinstance(state_abbr, str) assert state_abbr in state_abbrs class TestFaIr: """Test fa_IR address provider methods""" def test_city_prefix(self, faker, num_samples): for _ in range(num_samples): city_prefix = faker.city_prefix() assert isinstance(city_prefix, str) assert city_prefix in FaIrAddressProvider.city_prefixes def test_secondary_address(self, faker, num_samples): for _ in range(num_samples): secondary_address = faker.secondary_address() assert isinstance(secondary_address, str) assert re.fullmatch(r"(?:سوئیت|واحد) \d{3}", secondary_address) def test_state(self, faker, num_samples): for _ in range(num_samples): state = faker.state() assert isinstance(state, str) assert state in FaIrAddressProvider.states class TestFrFr: """Test fr_FR address provider methods""" def test_street_prefix(self, faker, num_samples): for _ in range(num_samples): street_prefix = faker.street_prefix() assert isinstance(street_prefix, str) assert street_prefix in FrFrAddressProvider.street_prefixes def test_city_prefix(self, faker, num_samples): for _ in range(num_samples): city_prefix = faker.city_prefix() assert isinstance(city_prefix, str) assert city_prefix in FrFrAddressProvider.city_prefixes def test_region(self, faker, num_samples): for _ in range(num_samples): region = faker.region() assert isinstance(region, str) assert region in FrFrAddressProvider.regions def test_department(self, faker, num_samples): for _ in range(num_samples): department = faker.department() assert isinstance(department, tuple) assert department in FrFrAddressProvider.departments def test_department_name(self, faker, num_samples): department_names = [dept_name for dept_num, dept_name in FrFrAddressProvider.departments] for _ in range(num_samples): department_name = faker.department_name() assert isinstance(department_name, str) assert department_name in department_names def test_department_number(self, faker, num_samples): department_numbers = [dept_num for dept_num, dept_name in FrFrAddressProvider.departments] for _ in range(num_samples): department_number = faker.department_number() assert isinstance(department_number, str) assert department_number in department_numbers class TestHeIl: """Test he_IL address provider methods""" def test_city_name(self, faker, num_samples): for _ in range(num_samples): city_name = faker.city_name() assert isinstance(city_name, str) assert city_name in HeIlAddressProvider.city_names def test_street_title(self, faker, num_samples): for _ in range(num_samples): street_title = faker.street_title() assert isinstance(street_title, str) assert street_title in HeIlAddressProvider.street_titles class TestHiIn: """Test hi_IN address provider methods""" def test_city_name(self, faker, num_samples): for _ in range(num_samples): city_name = faker.city_name() assert isinstance(city_name, str) assert city_name in HiInAddressProvider.cities def test_state(self, faker, num_samples): for _ in range(num_samples): state = faker.state() assert isinstance(state, str) assert state in HiInAddressProvider.states class TestTaIn: """Test ta_IN address provider methods""" def test_city_name(self, faker, num_samples): for _ in range(num_samples): city_name = faker.city_name() assert isinstance(city_name, str) assert city_name in TaInAddressProvider.cities def test_state(self, faker, num_samples): for _ in range(num_samples): state = faker.state() assert isinstance(state, str) assert state in TaInAddressProvider.states class TestFiFi: """Test fi_FI address provider methods""" def test_city(self, faker, num_samples): for _ in range(num_samples): city = faker.city() assert isinstance(city, str) assert city in FiFiAddressProvider.cities def test_street_suffix(self, faker, num_samples): for _ in range(num_samples): suffix = faker.street_suffix() assert isinstance(suffix, str) assert suffix in FiFiAddressProvider.street_suffixes def test_state(self, faker, num_samples): for _ in range(num_samples): state = faker.state() assert isinstance(state, str) assert state in FiFiAddressProvider.states class TestHrHr: """Test hr_HR address provider methods""" def test_city_name(self, faker, num_samples): for _ in range(num_samples): city_name = faker.city_name() assert isinstance(city_name, str) assert city_name in HrHrAddressProvider.cities def test_street_name(self, faker, num_samples): for _ in range(num_samples): street_name = faker.street_name() assert isinstance(street_name, str) assert street_name in HrHrAddressProvider.streets def test_state(self, faker, num_samples): for _ in range(num_samples): state = faker.state() assert isinstance(state, str) assert state in HrHrAddressProvider.states class TestHuHu: """Test hu_HU address provider methods""" def test_postcode(self, faker, num_samples): # Hungarian postcodes begin with 'H-' followed by 4 digits. # The first digit may not begin with a zero. for _ in range(num_samples): pcd = faker.postcode() assert re.fullmatch(r"H-[1-9]\d{3}", pcd) def test_street_address(self, faker, num_samples): """ Tests street address. A street address must consist of a street name, a place type and a number, and end in a period point. """ for _ in range(num_samples): address = faker.street_address() assert address[-1] == "." # Check for correct capitalisation of place type assert address.split(" ")[-2][0].islower() # Check for street number format assert re.fullmatch(r"\d{1,4}\.", address.split(" ")[-1]) def test_street_address_with_county(self, faker, num_samples): """Tests street address with country. A street address must be: - in three rows, - starting with a valid street address, - contain a valid post code, - contain the place name validly capitalized. """ for _ in range(num_samples): address = faker.street_address_with_county() # Number of rows assert len(address.split("\n")) == 3 first, second, last = address.split("\n") # Test street address assert first[0].isupper() assert first.split(" ")[-2][0].islower() assert re.fullmatch(r"\d{1,4}\.", first.split(" ")[-1]) # Test county line assert second.split(" ")[-1][0].islower() assert second.split(" ")[0][0].isupper() # Test postcode assert re.fullmatch(r"H-[1-9]\d{3}", last.split(" ")[0]) # Test place name capitalization assert last.split(" ")[-1][0].isupper() def test_address(self, faker, num_samples): for _ in range(num_samples): address = faker.address() assert isinstance(address, str) address_with_county = faker.street_address_with_county() assert isinstance(address_with_county, str) class TestHyAm: """Test hy_AM address provider methods""" def test_address(self, faker, num_samples): for _ in range(num_samples): address = faker.address() assert isinstance(address, str) def test_building_number(self, faker, num_samples): for _ in range(num_samples): building_number = faker.building_number() assert isinstance(building_number, str) assert 0 <= int(building_number) <= 999 def test_city(self, faker, num_samples): for _ in range(num_samples): city = faker.city() assert isinstance(city, str) assert city in HyAmAddressProvider.cities def test_city_prefix(self, faker, num_samples): for _ in range(num_samples): city_prefix = faker.city_prefix() assert isinstance(city_prefix, str) assert city_prefix in HyAmAddressProvider.city_prefixes def test_country(self, faker, num_samples): for _ in range(num_samples): country = faker.country() assert isinstance(country, str) assert country in HyAmAddressProvider.countries def test_postcode(self, faker, num_samples): for _ in range(num_samples): postcode = faker.postcode() assert isinstance(postcode, str) assert 200 <= int(postcode) <= 4299 def test_postcode_in_state(self, faker, num_samples): for _ in range(num_samples): for state_abbr in HyAmAddressProvider.states_abbr: code = faker.postcode_in_state(state_abbr) assert re.fullmatch(r"\d{4}", code) assert int(code) >= HyAmAddressProvider.states_postcode[state_abbr][0] assert int(code) <= HyAmAddressProvider.states_postcode[state_abbr][1] with pytest.raises(Exception): faker.postcode_in_state("XX") def test_secondary_address(self, faker, num_samples): for _ in range(num_samples): secondary_address = faker.secondary_address() assert isinstance(secondary_address, str) assert re.fullmatch(r"բն\. \d{1,2}", secondary_address) def test_state(self, faker, num_samples): for _ in range(num_samples): state = faker.state() assert isinstance(state, str) assert state in HyAmAddressProvider.states def test_state_abbr(self, faker, num_samples): for _ in range(num_samples): state_abbr = faker.state_abbr() assert isinstance(state_abbr, str) assert state_abbr in HyAmAddressProvider.states_abbr assert state_abbr.isupper() def test_street(self, faker, num_samples): for _ in range(num_samples): street = faker.street() assert isinstance(street, str) assert street in HyAmAddressProvider.streets def test_street_address(self, faker, num_samples): for _ in range(num_samples): street_address = faker.street_address() assert isinstance(street_address, str) def test_street_name(self, faker, num_samples): for _ in range(num_samples): street_name = faker.street_name() assert isinstance(street_name, str) def test_street_prefix(self, faker, num_samples): for _ in range(num_samples): street_prefix = faker.street_prefix() assert isinstance(street_prefix, str) assert street_prefix in HyAmAddressProvider.street_prefixes def test_street_suffix(self, faker, num_samples): for _ in range(num_samples): suffix = faker.street_suffix() assert isinstance(suffix, str) assert suffix in HyAmAddressProvider.street_suffixes def test_village(self, faker, num_samples): for _ in range(num_samples): village = faker.village() assert isinstance(village, str) assert village in HyAmAddressProvider.villages def test_village_prefix(self, faker, num_samples): for _ in range(num_samples): village_prefix = faker.village_prefix() assert isinstance(village_prefix, str) assert village_prefix in HyAmAddressProvider.village_prefixes class TestJaJp: """Test ja_JP address provider methods""" def test_chome(self, faker, num_samples): for _ in range(num_samples): chome = faker.chome() assert isinstance(chome, str) match = re.fullmatch(r"(?P<chome_number>\d{1,2})丁目", chome) assert match assert 1 <= int(match.group("chome_number")) <= 42 def test_ban(self, faker, num_samples): for _ in range(num_samples): ban = faker.ban() assert isinstance(ban, str) match = re.fullmatch(r"(?P<ban_number>\d{1,2})番", ban) assert match assert 1 <= int(match.group("ban_number")) <= 27 def test_gou(self, faker, num_samples): for _ in range(num_samples): gou = faker.gou() assert isinstance(gou, str) match = re.fullmatch(r"(?P<gou_number>\d{1,2})号", gou) assert match assert 1 <= int(match.group("gou_number")) <= 20 def test_town(self, faker, num_samples): for _ in range(num_samples): town = faker.town() assert isinstance(town, str) assert town in JaJpAddressProvider.towns def test_prefecture(self, faker, num_samples): for _ in range(num_samples): prefecture = faker.prefecture() assert isinstance(prefecture, str) assert prefecture in JaJpAddressProvider.prefectures def test_city(self, faker, num_samples): for _ in range(num_samples): city = faker.city() assert isinstance(city, str) assert city in JaJpAddressProvider.cities def test_country(self, faker, num_samples): for _ in range(num_samples): country = faker.country() assert isinstance(country, str) assert country in JaJpAddressProvider.countries def test_building_name(self, faker, num_samples): for _ in range(num_samples): building_name = faker.building_name() assert isinstance(building_name, str) assert building_name in JaJpAddressProvider.building_names def test_address(self, faker, num_samples): for _ in range(num_samples): address = faker.address() assert isinstance(address, str) def test_postcode(self, faker, num_samples): for _ in range(num_samples): postcode = faker.postcode() assert isinstance(postcode, str) assert re.fullmatch(r"\d{3}-\d{4}", postcode) def test_zipcode(self, faker, num_samples): for _ in range(num_samples): zipcode = faker.zipcode() assert isinstance(zipcode, str) assert re.fullmatch(r"\d{3}-\d{4}", zipcode) class TestKoKr: """Test ko_KR address provider methods""" def test_old_postal_code(self, faker, num_samples): for _ in range(num_samples): old_postal_code = faker.old_postal_code() assert isinstance(old_postal_code, str) assert re.fullmatch(r"\d{3}-\d{3}", old_postal_code) def test_postal_code(self, faker, num_samples): for _ in range(num_samples): postal_code = faker.postal_code() assert isinstance(postal_code, str) assert re.fullmatch(r"\d{5}", postal_code) def test_postcode(self, faker, num_samples): for _ in range(num_samples): postcode = faker.postcode() assert isinstance(postcode, str) assert re.fullmatch(r"\d{5}", postcode) class TestNeNp: """Test ne_NP address provider methods""" def test_province(self, faker, num_samples): for _ in range(num_samples): province = faker.province() assert isinstance(province, str) assert province in NeNpAddressProvider.provinces def test_district(self, faker, num_samples): for _ in range(num_samples): district = faker.district() assert isinstance(district, str) assert district in NeNpAddressProvider.districts def test_city(self, faker, num_samples): for _ in range(num_samples): city = faker.city() assert isinstance(city, str) assert city in NeNpAddressProvider.cities def test_country(self, faker, num_samples): for _ in range(num_samples): country = faker.country() assert isinstance(country, str) assert country in NeNpAddressProvider.countries class TestNoNo: """Test no_NO address provider methods""" def test_postcode(self, faker): for _ in range(100): assert re.fullmatch(r"^[0-9]{4}$", faker.postcode()) def test_city_suffix(self, faker, num_samples): for _ in range(num_samples): city_suffix = faker.city_suffix() assert isinstance(city_suffix, str) assert city_suffix in NoNoAddressProvider.city_suffixes def test_street_suffix(self, faker, num_samples): for _ in range(num_samples): street_suffix = faker.street_suffix() assert isinstance(street_suffix, str) assert street_suffix in NoNoAddressProvider.street_suffixes def test_address(self, faker, num_samples): for _ in range(num_samples): address = faker.address() assert isinstance(address, str) class TestZhTw: """Test zh_TW address provider methods""" def test_postcode(self, faker, num_samples): for _ in range(num_samples): postcode = faker.postcode() assert isinstance(postcode, str) assert re.fullmatch(r"[1-9]\d{2}(?:\d{2})?", postcode) def test_city_name(self, faker, num_samples): for _ in range(num_samples): city_name = faker.city_name() assert isinstance(city_name, str) assert city_name in ZhTwAddressProvider.cities def test_city_suffix(self, faker, num_samples): for _ in range(num_samples): city_suffix = faker.city_suffix() assert isinstance(city_suffix, str) assert city_suffix in ZhTwAddressProvider.city_suffixes def test_city(self, faker, num_samples): city_pattern: Pattern = re.compile(r"(?P<city_name>.*?)[市縣]?") for _ in range(num_samples): city = faker.city() assert isinstance(city, str) match = city_pattern.fullmatch(city) assert match assert match.group("city_name") in ZhTwAddressProvider.cities def test_country(self, faker, num_samples): for _ in range(num_samples): country = faker.country() assert isinstance(country, str) assert country in ZhTwAddressProvider.countries def test_street_name(self, faker, num_samples): for _ in range(num_samples): street_name = faker.street_name() assert isinstance(street_name, str) assert street_name in ZhTwAddressProvider.street_names def test_address(self, faker, num_samples): for _ in range(num_samples): address = faker.address() assert isinstance(address, str) class TestZhCn: """Test zh_CN address provider methods""" def test_postcode(self, faker, num_samples): for _ in range(num_samples): postcode = faker.postcode() assert isinstance(postcode, str) assert re.fullmatch(r"[1-9]\d{5}", postcode) def test_city_name(self, faker, num_samples): for _ in range(num_samples): city_name = faker.city_name() assert isinstance(city_name, str) assert city_name in ZhCnAddressProvider.cities def test_city_suffix(self, faker, num_samples): for _ in range(num_samples): city_suffix = faker.city_suffix() assert isinstance(city_suffix, str) assert city_suffix in ZhCnAddressProvider.city_suffixes def test_city(self, faker, num_samples): city_pattern: Pattern = re.compile(r".*?[市县]") for _ in range(num_samples): city = faker.city() assert isinstance(city, str) assert city_pattern.fullmatch(city) def test_province(self, faker, num_samples): for _ in range(num_samples): province = faker.province() assert isinstance(province, str) assert province in ZhCnAddressProvider.provinces def test_district(self, faker, num_samples): for _ in range(num_samples): district = faker.district() assert isinstance(district, str) assert district in ZhCnAddressProvider.districts def test_country(self, faker, num_samples): for _ in range(num_samples): country = faker.country() assert isinstance(country, str) assert country in ZhCnAddressProvider.countries def test_street_name(self, faker, num_samples): for _ in range(num_samples): street_name = faker.street_name() assert isinstance(street_name, str) def test_address(self, faker, num_samples): for _ in range(num_samples): address = faker.address() assert isinstance(address, str) class TestPtBr: """Test pt_BR address provider methods""" def test_country(self, faker, num_samples): for _ in range(num_samples): country = faker.country() assert isinstance(country, str) assert country in PtBrAddressProvider.countries def test_bairro(self, faker, num_samples): for _ in range(num_samples): bairro = faker.bairro() assert isinstance(bairro, str) assert bairro in PtBrAddressProvider.bairros def test_neighborhood(self, faker, num_samples): for _ in range(num_samples): neighborhood = faker.neighborhood() assert isinstance(neighborhood, str) assert neighborhood in PtBrAddressProvider.bairros def test_estado(self, faker, num_samples): for _ in range(num_samples): estado = faker.estado() assert isinstance(estado, tuple) assert estado in PtBrAddressProvider.estados def test_estado_nome(self, faker, num_samples): state_names = [state_name for state_abbr, state_name in PtBrAddressProvider.estados] for _ in range(num_samples): estado_nome = faker.estado_nome() assert isinstance(estado_nome, str) assert estado_nome in state_names def test_estado_sigla(self, faker, num_samples): state_abbrs = [state_abbr for state_abbr, state_name in PtBrAddressProvider.estados] for _ in range(num_samples): estado_sigla = faker.estado_sigla() assert isinstance(estado_sigla, str) assert estado_sigla in state_abbrs def test_address(self, faker, num_samples): for _ in range(num_samples): street = faker.street_name() assert isinstance(street, str) city = faker.street_address() assert isinstance(city, str) address = faker.address() assert isinstance(address, str) def test_raw_postcode(self, faker, num_samples): for _ in range(num_samples): postcode = faker.postcode(formatted=False) assert isinstance(postcode, str) assert re.fullmatch(r"\d{8}", postcode) def test_formatted_postcode(self, faker, num_samples): for _ in range(num_samples): postcode = faker.postcode() assert isinstance(postcode, str) assert re.fullmatch(r"\d{5}-?\d{3}", postcode) class TestPtPt: """Test pt_PT address provider methods""" def test_distrito(self, faker, num_samples): for _ in range(num_samples): distrito = faker.distrito() assert isinstance(distrito, str) assert distrito in PtPtAddressProvider.distritos def test_concelho(self, faker, num_samples): for _ in range(num_samples): concelho = faker.concelho() assert isinstance(concelho, str) assert concelho in PtPtAddressProvider.concelhos def test_freguesia(self, faker, num_samples): for _ in range(num_samples): freguesia = faker.freguesia() assert isinstance(freguesia, str) assert freguesia in PtPtAddressProvider.freguesias def test_place_name(self, faker, num_samples): for _ in range(num_samples): place_name = faker.place_name() assert isinstance(place_name, str) assert place_name in PtPtAddressProvider.places class TestEnPh: """Test en_PH address provider methods""" @classmethod def setup_class(cls): cls.building_number_pattern: Pattern = re.compile( r"(?:[1-9]|[1-9]\d{1,3})(?:[A-J]|\s[A-J]|-[A-J]|\sUnit\s[A-J])?", ) cls.address_pattern: Pattern = re.compile( r"(?P<street_address>.*), (?P<lgu>.*?), (?P<postcode>\d{4}) (?P<province>.*?)", ) cls.metro_manila_postcodes = EnPhAddressProvider.metro_manila_postcodes cls.luzon_province_postcodes = EnPhAddressProvider.luzon_province_postcodes cls.visayas_province_postcodes = EnPhAddressProvider.visayas_province_postcodes cls.mindanao_province_postcodes = EnPhAddressProvider.mindanao_province_postcodes cls.postcodes = EnPhAddressProvider.postcodes cls.provinces = EnPhAddressProvider.provinces cls.province_lgus = EnPhAddressProvider.province_lgus cls.metro_manila_lgus = EnPhAddressProvider.metro_manila_lgus def test_metro_manila_postcode(self, faker, num_samples): for _ in range(num_samples): assert int(faker.metro_manila_postcode()) in self.metro_manila_postcodes def test_luzon_province_postcode(self, faker, num_samples): for _ in range(num_samples): assert int(faker.luzon_province_postcode()) in self.luzon_province_postcodes def test_visayas_province_postcode(self, faker, num_samples): for _ in range(num_samples): assert int(faker.visayas_province_postcode()) in self.visayas_province_postcodes def test_mindanao_province_postcode(self, faker, num_samples): for _ in range(num_samples): assert int(faker.mindanao_province_postcode()) in self.mindanao_province_postcodes def test_postcode(self, faker, num_samples): for _ in range(num_samples): assert int(faker.postcode()) in self.postcodes def test_building_number(self, faker, num_samples): for _ in range(num_samples): assert self.building_number_pattern.fullmatch(faker.building_number()) def test_floor_unit_number(self, faker, num_samples): for _ in range(num_samples): number = faker.floor_unit_number() assert 2 <= int(number[:-2]) <= 99 assert 1 <= int(number[-2:]) <= 40 def test_ordinal_floor_number(self, faker, num_samples): for _ in range(num_samples): floor_number = faker.ordinal_floor_number() assert floor_number[-2:] in ["th", "st", "nd", "rd"] def test_address(self, faker, num_samples): for _ in range(num_samples): address = faker.address() match = self.address_pattern.fullmatch(address) street_address = match.group("street_address") lgu = match.group("lgu") postcode = match.group("postcode") province = match.group("province") assert match assert street_address assert lgu in self.province_lgus or lgu in self.metro_manila_lgus assert int(postcode) in self.postcodes assert province in self.provinces or province == "Metro Manila" class TestFilPh(TestEnPh): """Test fil_PH address provider methods""" pass class TestTlPh(TestEnPh): """Test tl_PH address provider methods""" pass class TestRuRu: """Test ru_RU address provider methods""" def test_city_name(self, faker, num_samples): for _ in range(num_samples): city = faker.city_name() assert isinstance(city, str) assert city in RuRuAddressProvider.city_names def test_country(self, faker, num_samples): for _ in range(num_samples): country = faker.country() assert isinstance(country, str) assert country in RuRuAddressProvider.countries def test_region(self, faker, num_samples): region_pattern: Pattern = re.compile( r"(?:респ\. (?P<region_republic>.*))|" r"(?:(?P<region_krai>.*?) край)|" r"(?:(?P<region_oblast>.*?) обл.)|" r"(?:(?P<region_ao>.*?) АО)", ) for _ in range(num_samples): region = faker.region() assert isinstance(region, str) match = region_pattern.fullmatch(region) assert match groupdict = match.groupdict() assert any( [ groupdict.get("region_republic") in RuRuAddressProvider.region_republics, groupdict.get("region_krai") in RuRuAddressProvider.region_krai, groupdict.get("region_oblast") in RuRuAddressProvider.region_oblast, groupdict.get("region_ao") in RuRuAddressProvider.region_ao, ] ) def test_postcode(self, faker, num_samples): for _ in range(num_samples): postcode = faker.postcode() assert isinstance(postcode, str) assert re.fullmatch(r"\d{6}", postcode) def test_city_prefix(self, faker, num_samples): for _ in range(num_samples): city_prefix = faker.city_prefix() assert isinstance(city_prefix, str) assert city_prefix in RuRuAddressProvider.city_prefixes def test_street_suffix(self, faker, num_samples): for _ in range(num_samples): street_suffix = faker.street_suffix() assert isinstance(street_suffix, str) assert street_suffix in RuRuAddressProvider.street_suffixes def test_street_title(self, faker, num_samples): for _ in range(num_samples): street_title = faker.street_title() assert isinstance(street_title, str) def test_street_name(self, faker, num_samples): for _ in range(num_samples): street_name = faker.street_name() assert isinstance(street_name, str) @pytest.mark.parametrize( "street_title,street_suffix,expected", [ ("Фрунзе", "ул.", "ул. Фрунзе"), ("Ставропольская", "ул.", "ул. Ставропольская"), ("Фрунзе", "пр.", "пр. Фрунзе"), ("Осенняя", "пр.", "пр. Осенний"), ("Гвардейская", "пр.", "пр. Гвардейский"), ("Рыбацкая", "пр.", "пр. Рыбацкий"), ("Безымянная", "пр.", "пр. Безымянный"), ("Проезжая", "ш.", "ш. Проезжее"), ("Магистральная", "ш.", "ш. Магистральное"), ], ids=[ "feminine_suffix_and_noflex_title", "feminine_suffix_and_flex_title", "non_feminine_suffix_and_noflex_title", "masc_suffix_and_irregular_masc_title", "masc_suffix_and_ck_street_stem", "masc_suffix_and_uk_street_stem", "masc_suffix_and_other_stem", "neu_suffx_and_iregular_neu_street_title", "neu_suffix_and_regular_street_title", ], ) def test_street_name_lexical(self, faker, street_title, street_suffix, expected): """Test that random street names are formed correctly, given the case of suffixes and streets that have been randomly selected. """ title_patch = mock.patch( "faker.providers.address.ru_RU.Provider.street_title", autospec=True, return_value=street_title, ) suffix_patch = mock.patch( "faker.providers.address.ru_RU.Provider.street_suffix", autospec=True, return_value=street_suffix, ) with title_patch, suffix_patch: result = faker.street_name() assert result == expected class TestThTh: """Test th_TH address provider methods""" def test_country(self, faker, num_samples): for _ in range(num_samples): country = faker.country() assert isinstance(country, str) assert country in ThThAddressProvider.countries def test_city_name(self, faker, num_samples): for _ in range(num_samples): city = faker.city_name() assert isinstance(city, str) assert city in ThThAddressProvider.cities def test_province(self, faker, num_samples): for _ in range(num_samples): province = faker.province() assert isinstance(province, str) assert province in ThThAddressProvider.provinces def test_amphoe(self, faker, num_samples): for _ in range(num_samples): amphoe = faker.amphoe() assert isinstance(amphoe, str) assert amphoe in ThThAddressProvider.amphoes def test_tambon(self, faker, num_samples): for _ in range(num_samples): tambon = faker.tambon() assert isinstance(tambon, str) def test_postcode(self, faker, num_samples): for _ in range(num_samples): postcode = faker.postcode() assert isinstance(postcode, str) assert re.fullmatch(r"[1-9]\d{4}", postcode) class TestEnIn: """Test en_IN address provider methods""" def test_city_name(self, faker, num_samples): for _ in range(num_samples): city_name = faker.city_name() assert isinstance(city_name, str) assert city_name in EnInAddressProvider.cities def test_state(self, faker, num_samples): for _ in range(num_samples): state = faker.state() assert isinstance(state, str) assert state in EnInAddressProvider.states class TestSkSk: """Test sk_SK address provider methods""" def test_street_suffix_short(self, faker, num_samples): for _ in range(num_samples): street_suffix_short = faker.street_suffix_short() assert isinstance(street_suffix_short, str) assert street_suffix_short in SkSkAddressProvider.street_suffixes_short def test_street_suffix_long(self, faker, num_samples): for _ in range(num_samples): street_suffix_long = faker.street_suffix_long() assert isinstance(street_suffix_long, str) assert street_suffix_long in SkSkAddressProvider.street_suffixes_long def test_city_name(self, faker, num_samples): for _ in range(num_samples): city = faker.city_name() assert isinstance(city, str) assert city in SkSkAddressProvider.cities def test_street_name(self, faker, num_samples): for _ in range(num_samples): street_name = faker.street_name() assert isinstance(street_name, str) assert street_name in SkSkAddressProvider.streets def test_state(self, faker, num_samples): for _ in range(num_samples): state = faker.state() assert isinstance(state, str) assert state in SkSkAddressProvider.states def test_postcode(self, faker, num_samples): for _ in range(num_samples): postcode = faker.postcode() assert isinstance(postcode, str) assert re.fullmatch(r"\d{3} \d{2}", postcode) def test_city_with_postcode(self, faker, num_samples): for _ in range(num_samples): city_with_postcode = faker.city_with_postcode() assert isinstance(city_with_postcode, str) match = re.fullmatch(r"\d{3} \d{2} (?P<city>.*)", city_with_postcode) assert match.group("city") in SkSkAddressProvider.cities class TestDeCh: """Test de_CH address provider methods""" def test_canton_name(self, faker, num_samples): for _ in range(num_samples): canton_name = faker.canton_name() assert isinstance(canton_name, str) assert any(canton_name == cantons[1] for cantons in DeChAddressProvider.cantons) def test_canton_code(self, faker, num_samples): for _ in range(num_samples): canton_code = faker.canton_code() assert isinstance(canton_code, str) assert any(canton_code == cantons[0] for cantons in DeChAddressProvider.cantons) def test_canton(self, faker, num_samples): for _ in range(num_samples): canton = faker.canton() assert isinstance(canton, tuple) assert canton in DeChAddressProvider.cantons class TestRoRo: """Test ro_RO address provider methods""" def test_address(self, faker, num_samples): for _ in range(num_samples): address = faker.address() assert isinstance(address, str) def test_street_address(self, faker, num_samples): for _ in range(num_samples): street_address = faker.street_address() assert isinstance(street_address, str) def test_street_name(self, faker, num_samples): for _ in range(num_samples): street_name = faker.street_name() assert isinstance(street_name, str) def test_street_prefix(self, faker, num_samples): for _ in range(num_samples): street_prefix = faker.street_prefix() assert isinstance(street_prefix, str) assert street_prefix in RoRoAddressProvider.street_prefixes def test_building_number(self, faker, num_samples): for _ in range(num_samples): building_number = faker.building_number() assert isinstance(building_number, str) assert building_number[:3] == "Nr." def test_secondary_address(self, faker, num_samples): for _ in range(num_samples): secondary_address = faker.secondary_address() assert isinstance(secondary_address, str) assert re.fullmatch( r"Bl. \d{2} Sc. \d{2} Ap. \d{3}", secondary_address, ) def test_city(self, faker, num_samples): for _ in range(num_samples): city = faker.city() assert isinstance(city, str) assert city in RoRoAddressProvider.cities def test_city_name(self, faker, num_samples): for _ in range(num_samples): city = faker.city_name() assert isinstance(city, str) assert city in RoRoAddressProvider.cities def test_state(self, faker, num_samples): states = [state_name for state_abbr, state_name in RoRoAddressProvider.states] for _ in range(num_samples): state = faker.state() assert isinstance(state, str) assert state in states def test_state_abbr(self, faker, num_samples): state_abbrs = [state_abbr for state_abbr, state_name in RoRoAddressProvider.states] for _ in range(num_samples): state_abbr = faker.state_abbr() assert isinstance(state_abbr, str) assert state_abbr in state_abbrs assert state_abbr.isupper() def test_postcode(self, faker, num_samples): for _ in range(num_samples): postcode = faker.postcode() assert isinstance(postcode, str) assert re.fullmatch(r"\d{6}", postcode) def test_city_with_postcode(self, faker, num_samples): for _ in range(num_samples): city_with_postcode = faker.city_with_postcode() assert isinstance(city_with_postcode, str) match = re.fullmatch(r"\d{6} (?P<city>.*)", city_with_postcode) assert match.group("city") in RoRoAddressProvider.cities
tests/providers/test_address.py
68,001
Test address provider methods Test cs_CZ address provider methods Test dk_DK address provider methods Test de_AT address provider methods Test de_CH address provider methods Test de_DE address provider methods Test el_GR address provider methods Test en_AU address provider methods Test en_CA address provider methods Test en_GB address provider methods Test en_IE address provider methods Test en_IN address provider methods Test en_NZ address provider methods Test en_PH address provider methods Test en_US address provider methods Test es_ES address provider methods Test es_MX address provider methods Test fa_IR address provider methods Test fi_FI address provider methods Test fil_PH address provider methods Test fr_FR address provider methods Test he_IL address provider methods Test hi_IN address provider methods Test hr_HR address provider methods Test hu_HU address provider methods Test hy_AM address provider methods Test ja_JP address provider methods Test ko_KR address provider methods Test ne_NP address provider methods Test no_NO address provider methods Test pt_BR address provider methods Test pt_PT address provider methods Test ro_RO address provider methods Test ru_RU address provider methods Test sk_SK address provider methods Test ta_IN address provider methods Test th_TH address provider methods Test tl_PH address provider methods Test zh_CN address provider methods Test zh_TW address provider methods https://stackoverflow.com/questions/33391412/validation-for-irish-eircode Tests street address. A street address must consist of a street name, a place type and a number, and end in a period point. Tests street address with country. A street address must be: - in three rows, - starting with a valid street address, - contain a valid post code, - contain the place name validly capitalized. Test that random street names are formed correctly, given the case of suffixes and streets that have been randomly selected. No states in New Zealand Spanish regions, also known as "autonomous communities" Hungarian postcodes begin with 'H-' followed by 4 digits. The first digit may not begin with a zero. Check for correct capitalisation of place type Check for street number format Number of rows Test street address Test county line Test postcode Test place name capitalization
2,310
en
0.807301
from map.models import * import requests # initialize geo_info table, used to show choropleth map def run(): try: response = requests.get('http://www.ourd3js.com/map/china_provinces/beijing.json') json_result = response.json() for area in json_result.get('features'): properties = area.get('properties') id = properties.get('id') geometry = area.get('geometry') district = properties.get('name') Geoinfo.create(id, district, properties, geometry).save() except: print("Load failed!")
scripts/geoinfo.py
586
initialize geo_info table, used to show choropleth map
54
en
0.328543
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved # type: ignore import copy import os import platform from dataclasses import dataclass from pathlib import Path from typing import List import nox from nox.logger import logger BASE = os.path.abspath(os.path.dirname(__file__)) DEFAULT_PYTHON_VERSIONS = ["3.6", "3.7", "3.8", "3.9"] DEFAULT_OS_NAMES = ["Linux", "MacOS", "Windows"] PYTHON_VERSIONS = os.environ.get( "NOX_PYTHON_VERSIONS", ",".join(DEFAULT_PYTHON_VERSIONS) ).split(",") INSTALL_EDITABLE_MODE = os.environ.get("INSTALL_EDITABLE_MODE", 0) INSTALL_COMMAND = ( ["pip", "install", "-e"] if INSTALL_EDITABLE_MODE else ["pip", "install"] ) # Allow limiting testing to specific plugins # The list ['ALL'] indicates all plugins PLUGINS = os.environ.get("PLUGINS", "ALL").split(",") SKIP_CORE_TESTS = "0" SKIP_CORE_TESTS = os.environ.get("SKIP_CORE_TESTS", SKIP_CORE_TESTS) != "0" FIX = os.environ.get("FIX", "0") == "1" VERBOSE = os.environ.get("VERBOSE", "0") SILENT = VERBOSE == "0" @dataclass class Plugin: name: str path: str module: str def get_current_os() -> str: current_os = platform.system() if current_os == "Darwin": current_os = "MacOS" return current_os print(f"Operating system\t:\t{get_current_os()}") print(f"NOX_PYTHON_VERSIONS\t:\t{PYTHON_VERSIONS}") print(f"PLUGINS\t\t\t:\t{PLUGINS}") print(f"SKIP_CORE_TESTS\t\t:\t{SKIP_CORE_TESTS}") print(f"FIX\t\t\t:\t{FIX}") print(f"VERBOSE\t\t\t:\t{VERBOSE}") print(f"INSTALL_EDITABLE_MODE\t:\t{INSTALL_EDITABLE_MODE}") def _upgrade_basic(session): session.run( "python", "-m", "pip", "install", "--upgrade", "setuptools", "pip", silent=SILENT, ) def find_dirs(path: str): for file in os.listdir(path): fullname = os.path.join(path, file) if os.path.isdir(fullname): yield fullname def install_hydra(session, cmd): # clean install hydra session.chdir(BASE) session.run(*cmd, ".", silent=SILENT) if not SILENT: session.install("pipdeptree", silent=SILENT) session.run("pipdeptree", "-p", "hydra-core") def pytest_args(*args): ret = ["pytest", "-Werror"] ret.extend(args) return ret def run_pytest(session, directory=".", *args): pytest_cmd = pytest_args(directory, *args) # silent=False to enable some output on CI # (otherwise we risk no-output timeout) session.run(*pytest_cmd, silent=False) def get_setup_python_versions(classifiers): pythons = filter(lambda line: "Programming Language :: Python" in line, classifiers) return [p[len("Programming Language :: Python :: ") :] for p in pythons] def get_plugin_os_names(classifiers: List[str]) -> List[str]: oses = list(filter(lambda line: "Operating System" in line, classifiers)) if len(oses) == 0: # No Os is specified so all oses are supported return DEFAULT_OS_NAMES if len(oses) == 1 and oses[0] == "Operating System :: OS Independent": # All oses are supported return DEFAULT_OS_NAMES else: return [p.split("::")[-1].strip() for p in oses] def select_plugins(session, directory: str) -> List[Plugin]: """ Select all plugins that should be tested in this session. Considers the current Python version and operating systems against the supported ones, as well as the user plugins selection (via the PLUGINS environment variable). """ assert session.python is not None, "Session python version is not specified" blacklist = [".isort.cfg", "examples"] plugins = [ {"dir_name": x, "path": x} for x in sorted(os.listdir(os.path.join(BASE, directory))) if x not in blacklist ] ret = [] skipped = [] for plugin in plugins: if not (plugin["dir_name"] in PLUGINS or PLUGINS == ["ALL"]): skipped.append(f"Deselecting {plugin['dir_name']}: User request") continue setup_py = os.path.join(BASE, directory, plugin["path"], "setup.py") classifiers = session.run( "python", setup_py, "--name", "--classifiers", silent=True ).splitlines() plugin_name = classifiers.pop(0) plugin_python_versions = get_setup_python_versions(classifiers) python_supported = session.python in plugin_python_versions plugin_os_names = get_plugin_os_names(classifiers) os_supported = get_current_os() in plugin_os_names if not python_supported: py_str = ", ".join(plugin_python_versions) skipped.append( f"Deselecting {plugin['dir_name']} : Incompatible Python {session.python}. Supports [{py_str}]" ) continue # Verify this plugin supports the OS we are testing on, skip otherwise if not os_supported: os_str = ", ".join(plugin_os_names) skipped.append( f"Deselecting {plugin['dir_name']}: Incompatible OS {get_current_os()}. Supports [{os_str}]" ) continue ret.append( Plugin( name=plugin_name, path=plugin["path"], module="hydra_plugins." + plugin["dir_name"], ) ) for msg in skipped: logger.warn(msg) if len(ret) == 0: logger.warn("No plugins selected") return ret def install_dev_deps(session): _upgrade_basic(session) session.run("pip", "install", "-r", "requirements/dev.txt", silent=SILENT) def _black_cmd(): black = ["black", "."] if not FIX: black += ["--check"] return black def _isort_cmd(): isort = ["isort", "."] if not FIX: isort += ["--check", "--diff"] return isort @nox.session(python=PYTHON_VERSIONS) def lint(session): install_dev_deps(session) install_hydra(session, ["pip", "install", "-e"]) apps = _get_standalone_apps_dirs() session.log("Installing standalone apps") for subdir in apps: session.chdir(str(subdir)) session.run(*_black_cmd(), silent=SILENT) session.run(*_isort_cmd(), silent=SILENT) session.chdir(BASE) session.run(*_black_cmd(), silent=SILENT) skiplist = apps + [ ".git", "website", "plugins", "tools", ".nox", "hydra/grammar/gen", "tools/configen/example/gen", "tools/configen/tests/test_modules/expected", "temp", ] isort = _isort_cmd() + [f"--skip={skip}" for skip in skiplist] session.run(*isort, silent=SILENT) session.run("mypy", ".", "--strict", silent=SILENT) session.run("flake8", "--config", ".flake8") session.run("yamllint", ".") example_dirs = [ "examples/advanced/", "examples/configure_hydra", "examples/patterns", "examples/instantiate", "examples/tutorials/basic/your_first_hydra_app", "examples/tutorials/basic/running_your_hydra_app", "examples/tutorials/structured_configs/", ] for edir in example_dirs: dirs = find_dirs(path=edir) for d in dirs: session.run("mypy", d, "--strict", silent=SILENT) # lint example plugins lint_plugins_in_dir(session=session, directory="examples/plugins") # bandit static security analysis session.run("bandit", "--exclude", "./.nox/**", "-ll", "-r", ".", silent=SILENT) @nox.session(python=PYTHON_VERSIONS) def lint_plugins(session): lint_plugins_in_dir(session, "plugins") def lint_plugins_in_dir(session, directory: str) -> None: install_cmd = ["pip", "install", "-e"] install_hydra(session, install_cmd) plugins = select_plugins(session=session, directory=directory) # plugin linting requires the plugins and their dependencies to be installed for plugin in plugins: cmd = install_cmd + [os.path.join(directory, plugin.path)] session.run(*cmd, silent=SILENT) install_dev_deps(session) session.run("flake8", "--config", ".flake8", directory) # Mypy for plugins for plugin in plugins: path = os.path.join(directory, plugin.path) session.chdir(path) session.run(*_black_cmd(), silent=SILENT) session.run(*_isort_cmd(), silent=SILENT) session.chdir(BASE) files = [] for file in ["tests", "example"]: abs = os.path.join(path, file) if os.path.exists(abs): files.append(abs) session.run( "mypy", "--strict", f"{path}/hydra_plugins", "--config-file", f"{BASE}/.mypy.ini", silent=SILENT, ) session.run( "mypy", "--strict", "--namespace-packages", "--config-file", f"{BASE}/.mypy.ini", *files, silent=SILENT, ) @nox.session(python=PYTHON_VERSIONS) def test_tools(session): install_cmd = ["pip", "install"] _upgrade_basic(session) session.install("pytest") install_hydra(session, install_cmd) tools = [ x for x in sorted(os.listdir(os.path.join(BASE, "tools"))) if not os.path.isfile(x) ] for tool in tools: tool_path = os.path.join("tools", tool) session.chdir(BASE) if (Path(tool_path) / "setup.py").exists(): cmd = list(install_cmd) + ["-e", tool_path] session.run(*cmd, silent=SILENT) session.run("pytest", tool_path) session.chdir(BASE) def _get_standalone_apps_dirs(): standalone_apps_dir = Path(f"{BASE}/tests/standalone_apps") apps = [standalone_apps_dir / subdir for subdir in os.listdir(standalone_apps_dir)] apps.append(f"{BASE}/examples/advanced/hydra_app_example") return apps @nox.session(python=PYTHON_VERSIONS) def test_core(session): _upgrade_basic(session) install_hydra(session, INSTALL_COMMAND) session.install("pytest") if not SKIP_CORE_TESTS: run_pytest(session, "build_helpers", "tests", *session.posargs) else: session.log("Skipping Hydra core tests") apps = _get_standalone_apps_dirs() session.log("Testing standalone apps") for subdir in apps: session.chdir(subdir) session.run(*INSTALL_COMMAND, ".", silent=SILENT) run_pytest(session, ".") session.chdir(BASE) test_plugins_in_directory( session, install_cmd=INSTALL_COMMAND, directory="examples/plugins", test_hydra_core=False, ) @nox.session(python=PYTHON_VERSIONS) def test_plugins(session): test_plugins_in_directory( session=session, install_cmd=INSTALL_COMMAND, directory="plugins", test_hydra_core=True, ) def test_plugins_in_directory( session, install_cmd, directory: str, test_hydra_core: bool ): _upgrade_basic(session) session.install("pytest") install_hydra(session, install_cmd) selected_plugin = select_plugins(session=session, directory=directory) for plugin in selected_plugin: cmd = list(install_cmd) + [os.path.join(directory, plugin.path)] session.run(*cmd, silent=SILENT) if not SILENT: session.run("pipdeptree", "-p", plugin.name) # Test that we can import Hydra session.run("python", "-c", "from hydra import main", silent=SILENT) # Test that we can import all installed plugins for plugin in selected_plugin: session.run("python", "-c", f"import {plugin.module}") # Run Hydra tests to verify installed plugins did not break anything if test_hydra_core: if not SKIP_CORE_TESTS: # exclude test_completion for plugins tests. # 1. It's tested during normal core tests. # 2. it's somewhat fragile and tend to timeout in mac. # 3. it's expensive and it's not worth the cost to run it for plugins as well. run_pytest(session, "tests", "--ignore=tests/test_completion.py") else: session.log("Skipping Hydra core tests") # Run tests for all installed plugins for plugin in selected_plugin: # install all other plugins that are compatible with the current Python version session.chdir(os.path.join(BASE, directory, plugin.path)) run_pytest(session) @nox.session(python="3.8") def coverage(session): coverage_env = { "COVERAGE_HOME": BASE, "COVERAGE_FILE": f"{BASE}/.coverage", "COVERAGE_RCFILE": f"{BASE}/.coveragerc", } _upgrade_basic(session) session.install("coverage", "pytest") install_hydra(session, ["pip", "install", "-e"]) session.run("coverage", "erase", env=coverage_env) for directory in ["plugins", "examples/plugins"]: selected_plugins = select_plugins(session=session, directory=directory) for plugin in selected_plugins: session.run( "pip", "install", "-e", os.path.join(directory, plugin.path), silent=SILENT, ) # run plugin coverage for plugin in selected_plugins: session.chdir(os.path.join(directory, plugin.path)) cov_args = ["coverage", "run", "--append", "-m"] cov_args.extend(pytest_args()) session.run(*cov_args, silent=SILENT, env=coverage_env) session.chdir(BASE) # run hydra-core coverage session.run( "coverage", "run", "--append", "-m", silent=SILENT, env=coverage_env, *pytest_args(), ) # Increase the fail_under as coverage improves session.run("coverage", "report", "--fail-under=80", env=coverage_env) session.run("coverage", "erase", env=coverage_env) @nox.session(python=PYTHON_VERSIONS) def test_jupyter_notebooks(session): versions = copy.copy(DEFAULT_PYTHON_VERSIONS) if session.python not in versions: session.skip( f"Not testing Jupyter notebook on Python {session.python}, supports [{','.join(versions)}]" ) session.install("jupyter", "nbval", "pyzmq") install_hydra(session, ["pip", "install", "-e"]) args = pytest_args( "--nbval", "examples/jupyter_notebooks/compose_configs_in_notebook.ipynb" ) # Jupyter notebook test on Windows yield warnings args = [x for x in args if x != "-Werror"] session.run(*args, silent=SILENT) notebooks_dir = Path("tests/jupyter") for notebook in [ file for file in notebooks_dir.iterdir() if str(file).endswith(".ipynb") ]: args = pytest_args("--nbval", str(notebook)) args = [x for x in args if x != "-Werror"] session.run(*args, silent=SILENT) @nox.session(python=PYTHON_VERSIONS) def benchmark(session): _upgrade_basic(session) install_dev_deps(session) install_hydra(session, INSTALL_COMMAND) session.install("pytest") run_pytest(session, "build_helpers", "tests/benchmark.py", *session.posargs)
noxfile.py
15,088
Select all plugins that should be tested in this session. Considers the current Python version and operating systems against the supported ones, as well as the user plugins selection (via the PLUGINS environment variable). Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved type: ignore Allow limiting testing to specific plugins The list ['ALL'] indicates all plugins clean install hydra silent=False to enable some output on CI (otherwise we risk no-output timeout) No Os is specified so all oses are supported All oses are supported Verify this plugin supports the OS we are testing on, skip otherwise lint example plugins bandit static security analysis plugin linting requires the plugins and their dependencies to be installed Mypy for plugins Test that we can import Hydra Test that we can import all installed plugins Run Hydra tests to verify installed plugins did not break anything exclude test_completion for plugins tests. 1. It's tested during normal core tests. 2. it's somewhat fragile and tend to timeout in mac. 3. it's expensive and it's not worth the cost to run it for plugins as well. Run tests for all installed plugins install all other plugins that are compatible with the current Python version run plugin coverage run hydra-core coverage Increase the fail_under as coverage improves Jupyter notebook test on Windows yield warnings
1,377
en
0.899005
#vim: set encoding=utf-8 from django.core.urlresolvers import reverse from django.http import Http404 from django.views.generic.base import TemplateView from regulations.generator import generator from regulations.generator.html_builder import HTMLBuilder from regulations.generator.node_types import EMPTYPART, REGTEXT, label_to_text from regulations.views import navigation, utils def generate_html(regulation_tree, layer_appliers): builder = HTMLBuilder(*layer_appliers) builder.tree = regulation_tree builder.generate_html() return builder class PartialView(TemplateView): """Base class of various partial markup views. sectional_links indicates whether this view should use section links (url to a path) or just hash links (to an anchor on the page)""" sectional_links = True def determine_appliers(self, label_id, version): """Figure out which layers to apply by checking the GET args""" if 'layers' in self.request.GET.keys(): return utils.handle_specified_layers( self.request.GET['layers'], label_id, version, self.__class__.sectional_links) else: layer_creator = generator.LayerCreator() layer_creator.add_layers( generator.LayerCreator.LAYERS.keys(), label_id, version, self.__class__.sectional_links) return layer_creator.get_appliers() def get_context_data(self, **kwargs): context = super(PartialView, self).get_context_data(**kwargs) label_id = context['label_id'] version = context['version'] tree = generator.get_tree_paragraph(label_id, version) if tree is None: raise Http404 inline_applier, p_applier, s_applier = self.determine_appliers( label_id, version) builder = generate_html(tree, (inline_applier, p_applier, s_applier)) return self.transform_context(context, builder) class PartialSectionView(PartialView): """ Single section of reg text """ template_name = 'regulations/regulation-content.html' def section_navigation(self, label, version): nav_sections = navigation.nav_sections(label, version) if nav_sections: p_sect, n_sect = nav_sections nav = {'previous': p_sect, 'next': n_sect} return nav def transform_context(self, context, builder): child_of_root = builder.tree # Add a layer to account for subpart if this is regtext if builder.tree['node_type'] == REGTEXT: child_of_root = { 'node_type': EMPTYPART, 'children': [builder.tree]} context['markup_page_type'] = 'reg-section' context['tree'] = {'children': [child_of_root]} context['navigation'] = self.section_navigation( context['label_id'], context['version']) return context class PartialParagraphView(PartialSectionView): """ Single paragraph of a regtext """ def transform_context(self, context, builder): node = builder.tree # Wrap with layers until we reach a section while len(node['label']) > 2: node = {'node_type': node['node_type'], 'children': [node], 'label': node['label'][:-1]} # added to give the proper parent container ID # when interp headers are rendered node['markup_id'] = context['label_id'] # One more layer for regtext if node['node_type'] == REGTEXT: node = {'node_type': EMPTYPART, 'children': [node], 'label': node['label'][:1] + ['Subpart']} context['markup_page_type'] = 'reg-section' context['tree'] = {'children': [node], 'label': node['label'][:1], 'node_type': REGTEXT} context['navigation'] = self.section_navigation( context['label_id'], context['version']) return context class PartialDefinitionView(PartialView): """ Single paragraph of a regtext formatted for display as an inline interpretation """ template_name = "regulations/partial-definition.html" def transform_context(self, context, builder): context['node'] = builder.tree context['formatted_label'] = label_to_text( builder.tree['label'], True, True) context['node']['section_id'] = '%s-%s' % ( builder.tree['label'][0], builder.tree['label'][1]) return context class PartialRegulationView(PartialView): """ Entire regulation without chrome """ template_name = 'regulations/regulation-content.html' sectional_links = False def transform_context(self, context, builder): context['tree'] = builder.tree return context
regulations/views/partial.py
4,836
Single paragraph of a regtext formatted for display as an inline interpretation Single paragraph of a regtext Entire regulation without chrome Single section of reg text Base class of various partial markup views. sectional_links indicates whether this view should use section links (url to a path) or just hash links (to an anchor on the page) Figure out which layers to apply by checking the GET args vim: set encoding=utf-8 Add a layer to account for subpart if this is regtext Wrap with layers until we reach a section added to give the proper parent container ID when interp headers are rendered One more layer for regtext
634
en
0.800392
# -*- coding: utf-8 -*- import unittest from pathlib import Path from knipse.db import KnipseDB from knipse.scan import scan_images from knipse.lists import image_id_from_string from .test_walk import EXPECTED_IMAGES class TestKnipseDatabase(unittest.TestCase): def setUp(self) -> None: self.src = Path(__file__).resolve().parent / 'images' / 'various' self.db = KnipseDB(':memory:') def test_getting_image_id(self) -> None: cnt = 0 for file_path, progress in scan_images(self.db, self.src, skip_thumbnail_folders=True): cnt += 1 self.assertEqual(len(EXPECTED_IMAGES), cnt) recgn = self.db.get_recognizer() image_id = image_id_from_string(str(self.src / 'img_0002.jpg'), self.src, recgn) self.assertEqual(1, image_id) image_id = image_id_from_string('I002', self.src, recgn) self.assertEqual(2, image_id)
tests/test_lists.py
998
-*- coding: utf-8 -*-
21
en
0.767281
import user import db if __name__ == "__main__": # Initializes the database if it doesn't already exist engine = db.open_db('maintenance.db') db.create_tables(engine) # TODO: Make this selectable with arrow keys while True: print('\nSelect an option:\n1. View Service History\n2. Add a Car\n3. Add a Service\n4. Exit') userInput = input() if userInput[0] == '1': user.view_services(engine) elif userInput[0] == '2': user.insert_car(engine) elif userInput[0] == '3': user.insert_service(engine) elif userInput[0] == '4': break
src/main.py
566
Initializes the database if it doesn't already exist TODO: Make this selectable with arrow keys
95
en
0.804921
#!/usr/bin/env python import logging from typing import ( Optional, Dict, List, Any) from hummingbot.core.data_type.order_book import OrderBook from sqlalchemy.engine import RowProxy import hummingbot.connector.exchange.binarz.binarz_constants as constants from hummingbot.connector.exchange.binarz.binarz_order_book_message import BinarzOrderBookMessage from hummingbot.connector.exchange.binarz.binarz_websocket import BinarzTrade from hummingbot.core.data_type.order_book_message import ( OrderBookMessage, OrderBookMessageType ) from hummingbot.logger import HummingbotLogger _logger = None class BinarzOrderMatched: def __init__(self): pass class BinarzOrderBook(OrderBook): @classmethod def logger(cls) -> HummingbotLogger: global _logger if _logger is None: _logger = logging.getLogger(__name__) return _logger @classmethod def snapshot_message_from_exchange(cls, msg: Dict[str, Any], timestamp: float, *args, **kwargs): """ Convert json snapshot data into standard OrderBookMessage format :param msg: json snapshot data from live web socket stream :param timestamp: timestamp attached to incoming data :return: BinarzOrderBookMessage """ return BinarzOrderBookMessage( message_type=OrderBookMessageType.SNAPSHOT, content=msg, timestamp=timestamp, *args, **kwargs) @classmethod def snapshot_message_from_db(cls, record: RowProxy): """ *used for backtesting Convert a row of snapshot data into standard OrderBookMessage format :param record: a row of snapshot data from the database :return: BinarzBookMessage """ return BinarzOrderBookMessage( message_type=OrderBookMessageType.SNAPSHOT, content=record.json, timestamp=record.timestamp ) @classmethod def diff_message_from_exchange(cls, msg: Dict[str, any], timestamp: Optional[float] = None): """ Convert json diff data into standard OrderBookMessage format :param msg: json diff data from live web socket stream :param timestamp: timestamp attached to incoming data :return: BinarzOrderBookMessage """ return BinarzOrderBookMessage( message_type=OrderBookMessageType.DIFF, content=msg, timestamp=timestamp ) @classmethod def diff_message_from_db(cls, record: RowProxy): """ *used for backtesting Convert a row of diff data into standard OrderBookMessage format :param record: a row of diff data from the database :return: BinarzBookMessage """ return BinarzOrderBookMessage( message_type=OrderBookMessageType.DIFF, content=record.json, timestamp=record.timestamp ) @classmethod def trade_message_from_exchange(cls, msg: BinarzTrade, timestamp: Optional[float] = None, ): """ Convert a trade data into standard OrderBookMessage format """ msg = { "exchange_order_id": msg.order_id, "trade_type": msg.type, "price": msg.price, "amount": msg.amount, } return BinarzOrderBookMessage( message_type=OrderBookMessageType.TRADE, content=msg, timestamp=timestamp ) @classmethod def trade_message_from_db(cls, record: RowProxy, metadata: Optional[Dict] = None): """ *used for backtesting Convert a row of trade data into standard OrderBookMessage format :param record: a row of trade data from the database :return: BinarzOrderBookMessage """ return BinarzOrderBookMessage( message_type=OrderBookMessageType.TRADE, content=record.json, timestamp=record.timestamp ) @classmethod def from_snapshot(cls, snapshot: OrderBookMessage): raise NotImplementedError(constants.EXCHANGE_NAME + " order book needs to retain individual order data.") @classmethod def restore_from_snapshot_and_diffs(self, snapshot: OrderBookMessage, diffs: List[OrderBookMessage]): raise NotImplementedError(constants.EXCHANGE_NAME + " order book needs to retain individual order data.")
hummingbot/connector/exchange/binarz/binarz_order_book.py
4,716
*used for backtesting Convert a row of diff data into standard OrderBookMessage format :param record: a row of diff data from the database :return: BinarzBookMessage Convert json diff data into standard OrderBookMessage format :param msg: json diff data from live web socket stream :param timestamp: timestamp attached to incoming data :return: BinarzOrderBookMessage *used for backtesting Convert a row of snapshot data into standard OrderBookMessage format :param record: a row of snapshot data from the database :return: BinarzBookMessage Convert json snapshot data into standard OrderBookMessage format :param msg: json snapshot data from live web socket stream :param timestamp: timestamp attached to incoming data :return: BinarzOrderBookMessage *used for backtesting Convert a row of trade data into standard OrderBookMessage format :param record: a row of trade data from the database :return: BinarzOrderBookMessage Convert a trade data into standard OrderBookMessage format !/usr/bin/env python
1,005
en
0.623199
import pygame class TextSprite(pygame.sprite.Sprite): """Subclass of sprite to draw text to the screen""" def __init__(self, position, text_lines, font, fg=(0, 0, 0), bg=None, border_width=0, border_color=(0, 0, 0), bold=False, italic=False, underline=False, line_spacing=3, padding=5): pygame.sprite.Sprite.__init__(self) self.position = position self.font = font self.fg = fg self.bg = bg self.border_width = border_width self.border_color = border_color self.line_spacing = line_spacing self.padding = padding self.font.set_bold(bold) self.font.set_italic(italic) self.font.set_underline(underline) self.rect = None self.image = None self.text_lines = text_lines self.update() def update(self): """""" # Render all lines of text text_images = [self.font.render(t, False, self.fg, self.bg) for t in self.text_lines] # Find the largest width line of text max_width = max(text_images, key=lambda x: x.get_width()).get_width() # Produce an image to hold all of the text strings self.image = pygame.Surface( (max_width + 2 * (self.border_width + self.padding), text_images[0].get_height() * len(text_images) + self.line_spacing * (len(text_images) - 1) + 2 * ( self.border_width + self.padding) ) ) self.image.fill(self.bg) if self.border_width > 0: pygame.draw.rect(self.image, self.border_color, (0, 0, self.image.get_width(), self.image.get_height()), self.border_width) for n, t in enumerate(text_images): self.image.blit(t, (self.border_width + self.padding, self.border_width + self.padding + (self.line_spacing + t.get_height()) * n)) # Store the last rect so if the new one is smaller we can update those bits of the screen too last_rect = self.rect self.rect = pygame.Rect(self.position[0], self.position[1], self.image.get_width(), self.image.get_height()) if last_rect is None: return self.rect else: return last_rect.union(self.rect)
text_sprite.py
2,344
Subclass of sprite to draw text to the screen Render all lines of text Find the largest width line of text Produce an image to hold all of the text strings Store the last rect so if the new one is smaller we can update those bits of the screen too
249
en
0.834724
#!/usr/bin/env python u""" combine_kernels.py by Yara Mohajerani Combine the sensitivity kernels of the sum of the 'fixed points' and produce netcdf and png outputs Last Update 12/2020 """ #-- load required modules import os import sys import numpy as np import geopandas as gpd import matplotlib.pyplot as plt from mpl_toolkits.axes_grid1 import make_axes_locatable #-- also import gravity toolkit modules from gravity_toolkit.ncdf_write import ncdf_write from gravity_toolkit.ncdf_read import ncdf_read #------------------------------------------------------------------------------ #-- create sensitivity kernels for given voronoi harmonics #------------------------------------------------------------------------------ def combine_kernels(parameters): DDEG_RASTER = float(parameters['DDEG_RASTER']) #-- read harmonic parameters LMAX = int(parameters['LMAX']) #-- get output directory ddir = os.path.expanduser(parameters['DIRECTORY']) #-- smoothing radius RAD = int(parameters['RAD']) #-- ocn redistribution label OCN = '_OCN' if parameters['MASCON_OCEAN'] in ['Y','y'] else '' #-- load mascon configuration of interest mascon_nums = np.array(parameters['MSCN_NUMS'].split(','),dtype=int) mascon_name = parameters['MSCN_NAME'] out_lbl = '{0}_{1}'.format(mascon_name,parameters['MSCN_NUMS'].replace(',','+')) #---------------------------------------------------------------------- #-- Read and sum up kernels corresponding to fixed points #---------------------------------------------------------------------- kerns = {} for i in mascon_nums: #- read the netcdf files kern_file = os.path.join(ddir,'MASCON_{0:d}_YLMS_{1:.2f}DEG_SKERNEL{2}_L{3:02d}_r{4:d}km.nc'.format(i,DDEG_RASTER,OCN,LMAX,RAD)) kerns[i] = ncdf_read(kern_file,DATE=False) #-- sum up the kernels kern_sum = kerns[mascon_nums[0]]['data'] for i in mascon_nums[1:]: kern_sum += kerns[i]['data'] #-- get grid for saving combined sensitivity kernel glat = kerns[mascon_nums[0]]['lat'] glon = kerns[mascon_nums[0]]['lon'] #---------------------------------------------------------------------- #-- write kernel sum to file #---------------------------------------------------------------------- outfile = os.path.join(ddir,'MASCON_{0}_YLMS_{1:.2f}DEG_SKERNEL_OCN_L{2:02d}_r{3:d}km.nc'.format(out_lbl,DDEG_RASTER,LMAX,RAD)) ncdf_write(kern_sum,glon,glat,0,FILENAME=outfile,DATE=False,UNITS='unitless',LONGNAME='Sensitivity_Kernel') #---------------------------------------------------------------------- #-- plot summed kernel #---------------------------------------------------------------------- #-- load in world map for plotting in background world = gpd.read_file(gpd.datasets.get_path('naturalearth_lowres')) #-- plot summed kernel fig, ax = plt.subplots(1,figsize = (10,6),dpi=100) klim = np.max(np.abs(kern_sum))*0.95 c = ax.contourf(glon,glat,kern_sum,cmap='bwr',levels=np.linspace(-klim,klim,16)) #-- use an axis divider for the colorbar drx = make_axes_locatable(ax) cax = drx.append_axes("right", size="5%", pad=0.1) cbar = fig.colorbar(c,cax=cax) cbar.set_label('Sensitivity Kernel (min:{0:.1f}, max:{1:.1f})'.format(np.min(kern_sum),np.max(kern_sum))) world.plot(ax=ax,alpha=0.3,fc='none',ec='k',linewidth=1.2,rasterized=True) plt.tight_layout() plt.savefig(outfile.replace('.nc','.png'),format='PNG') plt.close(fig=fig) #------------------------------------------------------------------------------ #-- main function #------------------------------------------------------------------------------ def main(): if len(sys.argv) == 1: sys.exit('No paramter file given') else: #-- read input files input_files = sys.argv[1:] parameters = {} for infile in input_files: #-- for each paramter file, extract parameters fid = open(infile, 'r') for fileline in fid: part = fileline.split() parameters[part[0]] = part[1] fid.close() #-- feed parameters to function to combine and plot kernels combine_kernels(parameters) #------------------------------------------------------------------------------ #-- run main program #------------------------------------------------------------------------------ if __name__ == '__main__': main()
combine_kernels.py
4,209
combine_kernels.py by Yara Mohajerani Combine the sensitivity kernels of the sum of the 'fixed points' and produce netcdf and png outputs Last Update 12/2020 !/usr/bin/env python-- load required modules-- also import gravity toolkit modules-------------------------------------------------------------------------------- create sensitivity kernels for given voronoi harmonics-------------------------------------------------------------------------------- read harmonic parameters-- get output directory-- smoothing radius-- ocn redistribution label-- load mascon configuration of interest------------------------------------------------------------------------ Read and sum up kernels corresponding to fixed points----------------------------------------------------------------------- read the netcdf files-- sum up the kernels-- get grid for saving combined sensitivity kernel------------------------------------------------------------------------ write kernel sum to file---------------------------------------------------------------------------------------------------------------------------------------------- plot summed kernel------------------------------------------------------------------------ load in world map for plotting in background-- plot summed kernel-- use an axis divider for the colorbar-------------------------------------------------------------------------------- main function-------------------------------------------------------------------------------- read input files-- for each paramter file, extract parameters-- feed parameters to function to combine and plot kernels-------------------------------------------------------------------------------- run main program------------------------------------------------------------------------------
1,786
en
0.311202
# coding: utf8 """ Delphi Decision Maker - Controllers """ module = request.controller resourcename = request.function if not settings.has_module(module): raise HTTP(404, body="Module disabled: %s" % module) # ============================================================================= def index(): """ Module Home Page - provide the list of currently-Active Problems """ # Simply redirect to the Problems REST controller redirect(URL(f="problem")) # Alternative dashboard module_name = settings.modules[module].name_nice table = s3db.delphi_group groups = db(table.active == True).select() result = [] for group in groups: actions = [] duser = s3db.delphi_DelphiUser(group) if duser.authorised: actions.append(("group/%d/update" % group.id, T("Edit"))) actions.append(("new_problem/create/?group=%s&next=%s" % \ (group.id, URL(f="group_summary", args=group.id)), "Add New Problem")) actions.append(("group_summary/%s/#request" % group.id, T("Review Requests"))) else: actions.append(("group_summary/%s/#request" % group.id, "Role: %s%s" % (duser.status, (duser.membership and duser.membership.req) and "*" or ""))) table = s3db.delphi_problem query = (table.group_id == group.id) & \ (table.active == True) latest_problems = db(query).select(orderby =~ table.modified_on) result.append((group, latest_problems, actions)) response.title = module_name return dict(groups_problems = result, name = T("Active Problems"), module_name = module_name, ) # ============================================================================= # Groups # ============================================================================= def group_rheader(r, tabs = []): """ Group rheader """ if r.representation == "html": if r.record is None: # List or Create form: rheader makes no sense here return None tabs = [(T("Basic Details"), None), (T("Problems"), "problem"), ] group = r.record # Get this User's permissions for this Group duser = s3db.delphi_DelphiUser(group.id) if duser.authorised: tabs.append((T("Membership"), "membership")) rheader_tabs = s3_rheader_tabs(r, tabs) rheader = DIV( TABLE( TR(TH("%s: " % T("Group")), group.name, ), TR(TH("%s: " % T("Description")), group.description, ), TR(TH("%s: " % T("Active")), group.active, ), ), rheader_tabs ) return rheader # ----------------------------------------------------------------------------- def group(): """ Problem Group REST Controller """ if not s3_has_role("DelphiAdmin"): s3db.configure("delphi_group", deletable=False, # Remove ability to create new Groups #insertable=False ) def prep(r): if r.interactive: if r.component: tablename = r.component.tablename list_fields = s3db.get_config(tablename, "list_fields") try: list_fields.remove("group_id") except: pass s3db.configure(tablename, deletable = s3_has_role("DelphiAdmin"), list_fields = list_fields) return True s3.prep = prep rheader = group_rheader return s3_rest_controller(rheader = rheader, # Allow components with components (such as problem) to breakout from tabs native = True, ) # ============================================================================= # Problems # ============================================================================= def problem_rheader(r, tabs = []): """ Problem rheader """ if r.representation == "html": if r.record is None: # List or Create form: rheader makes no sense here return None problem = r.record tabs = [# Components & Custom Methods (T("Problems"), "problems"), (T("Solutions"), "solution"), (T("Discuss"), "discuss"), (T("Vote"), "vote"), (T("Scale of Results"), "results"), ] # Get this User's permissions for this Group duser = s3db.delphi_DelphiUser(problem.group_id) if duser.authorised: tabs.append((T("Edit"), None)) rheader_tabs = s3_rheader_tabs(r, tabs) rtable = TABLE(TR(TH("%s: " % T("Problem")), problem.name, TH("%s: " % T("Active")), problem.active, ), TR(TH("%s: " % T("Description")), problem.description, ), TR(TH("%s: " % T("Criteria")), problem.criteria, ), ) if r.component and \ r.component_name == "solution" and \ r.component_id: stable = s3db.delphi_solution query = (stable.id == r.component_id) solution = db(query).select(stable.name, stable.description, limitby=(0, 1)).first() rtable.append(DIV(TR(TH("%s: " % T("Solution")), solution.name, ), TR(TH("%s: " % T("Description")), solution.description, ), )) rheader = DIV(rtable, rheader_tabs) return rheader # ----------------------------------------------------------------------------- def problem(): """ Problem REST Controller """ tablename = "%s_%s" % (module, resourcename) table = s3db[tablename] # Custom Methods set_method = s3db.set_method set_method(module, resourcename, method="problems", action=problems) set_method(module, resourcename, method="discuss", action=discuss) # Discussion can also be done at the Solution component level set_method(module, resourcename, component_name="solution", method="discuss", action=discuss) set_method(module, resourcename, method="vote", action=vote) set_method(module, resourcename, method="results", action=results) # Filter to just Active Problems s3.filter = (table.active == True) if not s3_has_role("DelphiAdmin"): s3db.configure(tablename, deletable = False, # Remove ability to create new Problems #insertable = False ) def prep(r): if r.interactive: if r.record: duser = s3db.delphi_DelphiUser(r.record.group_id) if duser.authorised: s3db.configure(tablename, deletable = True, ) if r.component_name == "solution": r.component.table.modified_on.label = T("Last Updated") s3db.configure(r.component.tablename, deletable = duser.authorised, ) return True s3.prep = prep def postp(r, output): if r.interactive: if not r.component: s3.actions = [ dict(label=str(T("Solutions")), _class="action-btn", url=URL(args=["[id]", "solution"])), dict(label=str(T("Vote")), _class="action-btn", url=URL(args=["[id]", "vote"])), ] elif r.component_name == "solution": s3.actions = [ dict(label=str(T("Discuss")), _class="action-btn", url=URL(args=[r.id, "solution", "[id]", "discuss"])), ] return output s3.postp = postp rheader = problem_rheader return s3_rest_controller(rheader=rheader) # ----------------------------------------------------------------------------- def problems(r, **attr): """ Redirect to the list of Problems for the Group - used for a Tab """ try: group_id = r.record.group_id except: raise HTTP(400) else: redirect(URL(f="group", args=[group_id, "problem"])) # ----------------------------------------------------------------------------- def solution(): """ Used for Imports """ return s3_rest_controller() # ============================================================================= # Voting # ============================================================================= def vote(r, **attr): """ Custom Method to allow Voting on Solutions to a Problem """ problem = r.record # Get this User's permissions for this Group duser = s3db.delphi_DelphiUser(problem.group_id) # Add the RHeader to maintain consistency with the other pages rheader = problem_rheader(r) # Lookup Solution Options stable = s3db.delphi_solution query = (stable.problem_id == problem.id) rows = db(query).select(stable.id, stable.name) options = Storage() for row in rows: options[row.id] = row.name if duser.user_id: vtable = s3db.delphi_vote query = (vtable.problem_id == problem.id) & \ (vtable.created_by == auth.user.id) votes = db(query).select(vtable.solution_id, orderby = vtable.rank) else: votes = [] rankings = OrderedDict() for v in votes: # Add to the list of ranked options rankings[v.solution_id] = options[v.solution_id] # Remove from the unranked options options.pop(v.solution_id) # Add Custom CSS from Static (cacheable) s3.stylesheets.append("S3/delphi.css") # Add Custom Javascript # Settings to be picked up by Static code js = "".join(( '''var problem_id=''', str(problem.id), ''' i18n.delphi_failed="''', str(T("Failed!")), '''" i18n.delphi_saving="''', str(T("Saving...")), '''" i18n.delphi_saved="''', str(T("Saved.")), '''" i18n.delphi_vote="''', str(T("Save Vote")), '''"''')) s3.js_global.append(js) # Static code which can be cached s3.scripts.append(URL(c="static", f="scripts", args=["S3", "s3.delphi.js"])) response.view = "delphi/vote.html" return dict(rheader = rheader, duser = duser, votes = votes, options = options, rankings = rankings, ) # ----------------------------------------------------------------------------- def save_vote(): """ Function accessed by AJAX from vote() to save the results of a Vote """ try: problem_id = request.args[0] except: raise HTTP(400) ptable = s3db.delphi_problem query = (ptable.id == problem_id) problem = db(query).select(ptable.group_id, limitby=(0, 1)).first() if not problem: raise HTTP(404) # Get this User's permissions for this Group duser = s3db.delphi_DelphiUser(problem.group_id) if not duser.can_vote: auth.permission.fail() # Decode the data try: rankings = request.post_vars.keys()[0].split(",") except IndexError: status = current.xml.json_message(False, 400, "No Options Ranked") raise HTTP(400, body=status) # Check the votes are valid stable = s3db.delphi_solution query = (stable.problem_id == problem_id) solutions = db(query).select(stable.id) options = [] for row in solutions: options.append(row.id) for ranked in rankings: if int(ranked) not in options: status = current.xml.json_message(False, 400, "Option isn't valid!") raise HTTP(400, body=status) # Convert to a format suitable for comparisons votes = [] count = 1 for ranked in rankings: votes.append(Storage(solution_id=int(ranked), rank=count)) count += 1 # Read the old votes vtable = s3db.delphi_vote query = (vtable.problem_id == problem_id) & \ (vtable.created_by == auth.user.id) old_votes = db(query).select(vtable.solution_id, vtable.rank) if old_votes: # Calculate changes ranks = {} old_ranks = {} used = [] for solution in solutions: s1 = solution.id ranks[s1] = 0 old_ranks[s1] = 0 for vote in votes: if vote.solution_id == s1: ranks[s1] = vote.rank continue for vote in old_votes: if vote.solution_id == s1: old_ranks[s1] = vote.rank continue for sol_2 in solutions: changed = False s2 = sol_2.id if s2 == s1: continue if (s2, s1) in used: # We've already evaluated this pair continue ranks[s2] = 0 old_ranks[s2] = 0 for vote in votes: if vote.solution_id == s2: ranks[s2] = vote.rank continue for vote in old_votes: if vote.solution_id == s2: old_ranks[s2] = vote.rank continue if (ranks[s1] > ranks[s2]) and \ (old_ranks[s1] < old_ranks[s2]): changed = True elif (ranks[s1] < ranks[s2]) and \ (old_ranks[s1] > old_ranks[s2]): changed = True elif (ranks[s1] == ranks[s2]) and \ (old_ranks[s1] != old_ranks[s2]): changed = True elif (ranks[s1] != ranks[s2]) and \ (old_ranks[s1] == old_ranks[s2]): changed = True if changed: # This pair has changed places, so update Solution db(stable.id.belongs((s1, s2))).update(changes=stable.changes + 1) used.append((s1, s2)) # Clear the old votes db(query).delete() # Save the new votes count = 1 for ranked in rankings: vtable.insert(problem_id=problem_id, solution_id=ranked, rank=count) count += 1 status = current.xml.json_message(True, 200, "Vote saved") return status # ----------------------------------------------------------------------------- def _getUnitNormalDeviation(zscore): """ Utility function used by Scale of Results Looks up the Unit Normal Deviation based on the Z-Score (Proportion/Probability) http://en.wikipedia.org/wiki/Standard_normal_table @ToDo: Move to S3Statistics module """ UNIT_NORMAL = ( ( 0.0, .0, .01, .02, .03, .04, .05, .06, .07, .08, .09 ), ( .0, .5000, .5040, .5080, .5120, .5160, .5199, .5239, .5279, .5319, .5359 ), ( .1, .5398, .5438, .5478, .5517, .5557, .5596, .5636, .5675, .5714, .5753 ), ( .2, .5793, .5832, .5871, .5910, .5948, .5987, .6026, .6064, .6103, .6141 ), ( .3, .6179, .6217, .6255, .6293, .6331, .6368, .6406, .6443, .6480, .6517 ), ( .4, .6554, .6591, .6628, .6664, .6700, .6736, .6772, .6808, .6844, .6879 ), ( .5, .6915, .6950, .6985, .7019, .7054, .7088, .7123, .7157, .7190, .7224 ), ( .6, .7257, .7291, .7324, .7357, .7389, .7422, .7454, .7486, .7517, .7549 ), ( .7, .7580, .7611, .7642, .7673, .7703, .7734, .7764, .7794, .7823, .7852 ), ( .8, .7881, .7910, .7939, .7967, .7995, .8023, .8051, .8078, .8106, .8133 ), ( .9, .8159, .8186, .8212, .8238, .8264, .8289, .8315, .8340, .8365, .8389 ), ( 1.0, .8415, .8438, .8461, .8485, .8508, .8531, .8554, .8577, .8509, .8621 ), ( 1.1, .8643, .8665, .8686, .8708, .8729, .8749, .8770, .8790, .8810, .8830 ), ( 1.2, .8849, .8869, .8888, .8907, .8925, .8944, .8962, .8980, .8997, .90147 ), ( 1.3, .90320, .90490, .90658, .90824, .90988, .91149, .91309, .91466, .91621, .91774 ), ( 1.4, .91924, .92073, .92220, .92364, .92507, .92647, .92785, .92922, .93056, .93189 ), ( 1.5, .93319, .93448, .93574, .93699, .93822, .93943, .94062, .94179, .94295, .94408 ), ( 1.6, .94520, .94630, .94738, .94845, .94950, .95053, .95154, .95254, .95352, .95449 ), ( 1.7, .95543, .95637, .95728, .95818, .95907, .95994, .96080, .96164, .96246, .96327 ), ( 1.8, .96407, .96485, .96562, .96638, .96712, .96784, .97856, .96926, .96995, .97062 ), ( 1.9, .97128, .97193, .97257, .97320, .97381, .97441, .97500, .97558, .97615, .97670 ), ( 2.0, .97725, .97778, .97831, .97882, .97932, .97982, .98030, .98077, .98124, .98169 ), ( 2.1, .98214, .98257, .98300, .98341, .98382, .98422, .98461, .98500, .98537, .98574 ), ( 2.2, .98610, .98645, .98679, .98713, .98745, .98778, .98809, .98840, .98870, .98899 ), ( 2.3, .98928, .98956, .98983, .990097, .990358, .990613, .990863, .991106, .991344, .991576 ), ( 2.4, .991802, .992024, .992240, .992451, .992656, .992857, .993053, .993244, .993431, .993613 ), ( 2.5, .993790, .993963, .994132, .994297, .994457, .994614, .994766, .994915, .995060, .995201 ), ( 2.6, .995339, .995473, .995604, .995731, .995855, .995975, .996093, .996207, .996319, .996427 ), ( 2.7, .996533, .996636, .996736, .996833, .996928, .997020, .997110, .997197, .997282, .997365 ), ( 2.8, .997445, .997523, .997599, .997673, .997744, .997814, .997882, .997948, .998012, .998074 ), ( 2.9, .998134, .998193, .998250, .998305, .998359, .998411, .998460, .998511, .998559, .998605 ), ( 3.0, .998650, .998694, .998736, .998777, .998817, .998856, .998893, .998930, .998965, .998999 ), ( 3.1, .9990324, .9990646, .9990957, .9991260, .9991553, .9991836, .9992112, .9992378, .9992636, .9992886 ), ( 3.2, .9993129, .9993363, .9993590, .9993810, .9994024, .9994230, .9994429, .9994623, .9994810, .9994991 ), ( 3.3, .9995166, .9995335, .9995499, .9995658, .9995811, .9995959, .9996103, .9996242, .9996376, .9996505 ), ( 3.4, .9996631, .9996752, .9996869, .9996982, .9997091, .9997197, .9997299, .9997398, .9997493, .9997585 ), ( 3.5, .9997674, .9997759, .9997842, .9997922, .9997999, .9998074, .9998146, .9998215, .9998282, .9998347 ), ( 3.6, .9998409, .9998469, .9998527, .9998583, .9998637, .9998689, .9998739, .9998787, .9998834, .9998879 ), ( 3.7, .9998922, .9998964, .99990039, .99990426, .99990799, .99991158, .99991504, .99991838, .99992159, .99992468 ), ( 3.8, .99992765, .99993052, .99993327, .99993593, .99993848, .99994094, .99994331, .99994558, .99994777, .99994988 ), ( 3.9, .99995190, .99995385, .99995573, .99995753, .99995926, .99996092, .99996253, .99996406, .99996554, .99996696 ), ( 4.0, .99996833, .99996964, .99997090, .99997211, .99997327, .99997439, .99997546, .99997649, .99997748, .99997843 ), ( 4.1, .99997934, .99998022, .99998106, .99998186, .99998263, .99998338, .99998409, .99998477, .99998542, .99998605 ), ( 4.2, .99998665, .99998723, .99998778, .99998832, .99998882, .99998931, .99998978, .999990226, .999990655, .999991066 ), ( 4.3, .999991460, .999991837, .999992199, .999992545, .999992876, .999993193, .999993497, .999993788, .999994066, .999994332 ), ( 4.4, .999994587, .999994831, .999995065, .999995288, .999995502, .999995706, .999995902, .999996089, .999996268, .999996439 ), ( 4.5, .999996602, .999996759, .999996908, .999997051, .999997187, .999997318, .999997442, .999997561, .999997675, .999997784 ), ( 4.6, .999997888, .999997987, .999998081, .999998172, .999998258, .999998340, .999998419, .999998494, .999998566, .999998634 ), ( 4.7, .999998699, .999998761, .999998821, .999998877, .999998931, .999998983, .9999990320, .9999990789, .9999991235, .9999991661 ), ( 4.8, .9999992067, .9999992453, .9999992822, .9999993173, .9999993508, .9999993827, .9999994131, .9999994420, .9999994696, .9999994958 ), ( 4.9, .9999995208, .9999995446, .9999995673, .9999995889, .9999996094, .9999996289, .9999996475, .9999996652, .9999996821, .9999996981 ) ) # Assume indifference unitDeviation = 0.0 for j in range(1, 50): if zscore == UNIT_NORMAL[j][1]: unitDeviation = UNIT_NORMAL[j][0] elif (UNIT_NORMAL[j][1] < zscore) and (zscore < UNIT_NORMAL[j + 1][1]): for i in range(2, 10): if (UNIT_NORMAL[j][i - 1] < zscore) and (zscore <= UNIT_NORMAL[j][i]): unitDeviation = UNIT_NORMAL[j][0] + UNIT_NORMAL[0][i] if zscore > UNIT_NORMAL[j][10]: unitDeviation = UNIT_NORMAL[j + 1][0] if zscore > UNIT_NORMAL[50][10]: # maximum value unitDeviation = 5.0 return unitDeviation # ----------------------------------------------------------------------------- def online_variance(data): """ A numerically stable algorithm for calculating variance http://en.wikipedia.org/wiki/Algorithms_for_calculating_variance#On-line_algorithm """ n = 0 mean = 0 M2 = 0 for x in data: n = n + 1 delta = x - mean mean = mean + delta/n M2 = M2 + delta*(x - mean) variance_n = M2/n variance = M2/(n - 1) return (variance, variance_n) # ----------------------------------------------------------------------------- def results(r, **attr): """ Custom Method to show the Scale of Results """ def NBSP(): return XML("&nbsp;") # Add the RHeader to maintain consistency with the other pages rheader = problem_rheader(r) response.view = "delphi/results.html" empty = dict(rheader=rheader, num_voted=0, chart="", table_color="", grids="", summary="" ) problem = r.record # Lookup Votes if problem: vtable = s3db.delphi_vote query = (vtable.problem_id == problem.id) votes = db(query).select(vtable.solution_id, vtable.rank, vtable.created_by) else: votes = None if not votes: return empty # Lookup Solutions stable = s3db.delphi_solution query = (stable.problem_id == problem.id) solutions = db(query).select(stable.id, stable.name, stable.problem_id, # Needed for Votes virtual field stable.changes) if not solutions: return empty # Initialise arrays of pairwise comparisons arrayF = {} arrayP = {} arrayX = {} arrayP2 = {} arrayU = {} for solution in solutions: s1 = solution.id for sol_2 in solutions: s2 = sol_2.id if s1 == s2: arrayF[(s1, s2)] = None arrayP[(s1, s2)] = None arrayX[(s1, s2)] = None arrayP2[(s1, s2)] = None arrayU[(s1, s2)] = None continue arrayF[(s1, s2)] = 0 # Allow new solutions to start at an indifferent probability arrayP[(s1, s2)] = 0.5 arrayX[(s1, s2)] = 0 arrayP2[(s1, s2)] = 0.5 arrayU[(s1, s2)] = 0.5 # List of Voters voters = [] for vote in votes: voter = vote.created_by if voter not in voters: voters.append(voter) num_voted = len(voters) # Update array of pairwise comparisons based on votes # Create array F which is the number of time a solution has been preferred compared to it'a partner for voter in voters: ranks = {} for vote in votes: if vote.created_by != voter: continue ranks[vote.rank] = vote.solution_id for rank_1 in range(1, len(ranks)): for rank_2 in range(rank_1 + 1, len(ranks) + 1): arrayF[(ranks[rank_1], ranks[rank_2])] += 1 grids = DIV() header = TR(TD()) rows = TBODY() for solution in solutions: header.append(TH(solution.name)) s1 = solution.id row = TR(TH(solution.name)) for sol_2 in solutions: s2 = sol_2.id # Preferred should be the columns value = arrayF[(s2, s1)] if value is None: row.append(TD("-")) else: row.append(TD(value)) rows.append(row) output = TABLE(THEAD(header), rows, _class="delphi_wide") output = DIV(H4(T("Array F: # times that solution in column is preferred over it's partner in row")), output) grids.append(output) grids.append(NBSP()) # Use the pairwise comparisons to build a Dynamic Thurstone scale of results # http://en.wikipedia.org/wiki/Thurstone_scale # http://www.brocku.ca/MeadProject/Thurstone/Thurstone_1927a.html # http://www.brocku.ca/MeadProject/Thurstone/Thurstone_1927f.html # @ToDo: For incomplete data, the calculation is more complex: Gulliksen # Convert array F to array P by converting totals to proportions # Convert array P to array X, which is the unit normal deviate for solution in solutions: s1 = solution.id for sol_2 in solutions: s2 = sol_2.id if s1 == s2: continue total = float(arrayF[(s1, s2)] + arrayF[(s2, s1)]) # Preferred should be the columns if total: proportion = arrayF[(s2, s1)] / total else: # No votes yet, so assume indifference proportion = 0.5 arrayP[(s2, s1)] = proportion # Cannot do unit normal deviation for 0/1 so approximate in order to not have to do the incomplete data maths if proportion == 0.0: arrayX[(s2, s1)] = _getUnitNormalDeviation(0.01) elif proportion == 1.0: arrayX[(s2, s1)] = _getUnitNormalDeviation(0.99) else: arrayX[(s2, s1)] = _getUnitNormalDeviation(proportion) # Now calculate the uncertainty scale # i.e. assume that every user who didn't vote on a particular pair drags that back towards indifference novotes = num_voted - total if proportion == 0.5: pass elif proportion > 0.5: # Assume the novotes vote against proportion = (arrayF[s2, s1] - novotes) / num_voted else: # Assume the novotes vote for proportion = (arrayF[s2, s1] + novotes) / num_voted arrayP2[(s2, s1)] = proportion # Cannot do unit normal deviation for 0/1 so approximate in order to not have to do the incomplete data maths if proportion == 0.0: arrayU[(s2, s1)] = _getUnitNormalDeviation(0.01) elif proportion == 1.0: arrayU[(s2, s1)] = _getUnitNormalDeviation(0.99) else: arrayU[(s2, s1)] = _getUnitNormalDeviation(proportion) header = TR(TD()) rows = TBODY() for solution in solutions: header.append(TH(solution.name)) s1 = solution.id row = TR(TH(solution.name)) for sol_2 in solutions: s2 = sol_2.id # Preferred should be the columns value = arrayP[(s2, s1)] if value is None: row.append(TD("-")) else: row.append(TD(value)) rows.append(row) output = TABLE(THEAD(header), rows, _class="delphi_wide") output = DIV(H4(T("Array P: proportion of times that solution in column is preferred over it's partner in row, assuming that pairs not ranked start at the level of indifference (0.5)")), output) grids.append(output) grids.append(NBSP()) header = TR(TD()) rows = TBODY() footer = TR(TH("Total")) footer2 = TR(TH("Scale")) totals = {} counts = {} for solution in solutions: s1 = solution.id totals[s1] = 0 counts[s1] = 0 for solution in solutions: header.append(TH(solution.name)) s1 = solution.id row = TR(TH(solution.name)) for sol_2 in solutions: s2 = sol_2.id # Preferred should be the columns value = arrayX[(s2, s1)] if value is None: row.append(TD("-")) else: row.append(TD(value)) if value is not None: totals[s2] += value counts[s2] += 1 rows.append(row) # Least-squares estimate of the scale values # Average of the columns for solution in solutions: s1 = solution.id footer.append(TH(totals[s1])) if counts[s1]: solution.scale = totals[s1]/counts[s1] footer2.append(TH(solution.scale)) else: solution.scale = 0 footer2.append(TH()) output = TABLE(THEAD(header), rows, footer, footer2, _class="delphi_wide") output = DIV(H4(T("Array X: unit normal deviate")), output) grids.append(output) grids.append(NBSP()) header = TR(TD()) rows = TBODY() for solution in solutions: header.append(TH(solution.name)) s1 = solution.id row = TR(TH(solution.name)) for sol_2 in solutions: s2 = sol_2.id # Preferred should be the columns value = arrayP2[(s2, s1)] if value is None: row.append(TD("-")) else: row.append(TD(value)) rows.append(row) output = TABLE(THEAD(header), rows, _class="delphi_wide") output = DIV(H4(T("Array P2: proportion of times that solution in column is preferred over it's partner in row, assuming that non-votes move towards indifference")), output) grids.append(output) grids.append(NBSP()) header = TR(TD()) rows = TBODY() footer = TR(TH("Total")) footer2 = TR(TH("Scale")) totals = {} counts = {} for solution in solutions: s1 = solution.id totals[s1] = 0 counts[s1] = 0 for solution in solutions: header.append(TH(solution.name)) s1 = solution.id row = TR(TH(solution.name)) for sol_2 in solutions: s2 = sol_2.id # Preferred should be the columns value = arrayU[(s2, s1)] if value is None: row.append(TD("-")) else: row.append(TD(value)) if value is not None: totals[s2] += value counts[s2] += 1 rows.append(row) # Least-squares estimate of the uncertainty values # Average of the columns for solution in solutions: s1 = solution.id footer.append(TH(totals[s1])) if counts[s1]: solution.uncertainty = totals[s1]/counts[s1] footer2.append(TH(solution.uncertainty)) else: solution.uncertainty = 0 footer2.append(TH()) output = TABLE(THEAD(header), rows, footer, footer2, _class="delphi_wide") output = DIV(H4(T("Array U: unit normal deviate of the uncertainty value (assuming that all unvoted items return the probability towards indifference)")), output) grids.append(output) # Sort the Solutions by Scale def scale(solution): return float(solution.scale) solutions = solutions.sort(scale, reverse=True) n = len(solutions) # @ToDo: deployment_setting image = "" if image: # Canvas of 900x600 from s3chart import S3Chart chart = S3Chart(9, 6) fig = chart.fig # Add Axes with padding of 10px for the labels (fractional left, bottom, width, height) ax = fig.add_axes([0.35, 0.1, 0.6, 0.8]) problem = r.record ax.set_title(problem.name) labels = [] scales = [] uncertainties = [] for solution in solutions: labels.append(solution.name) scales.append(solution.scale) uncertainties.append(solution.uncertainty) from numpy import arange ind = arange(n) width = .35 ax.set_yticks(ind + width) ax.set_yticklabels(labels) labels = ax.get_yticklabels() for label in labels: label.set_size(8) ax.set_xlabel("Scale") # rotation="vertical" or rotation = 45 ax.xaxis.grid(True) rects1 = ax.barh(ind, scales, width, linewidth=0) # color="blue" rects2 = ax.barh(ind + width, uncertainties, width, linewidth=0, color="red") ax.legend( (rects1[0], rects2[0]), ("Scale", "Uncertainty") ) image = chart.draw() # Colour the rows # Calculate Breaks classes = 5 q = [] qappend = q.append for i in range(classes - 1): qappend(1.0 / classes * (i + 1)) values = [float(solution.scale) for solution in solutions] breaks = s3db.stats_quantile(values, q) # Make mutable breaks = list(breaks) values_min = min(values) values_max = max(values) breaks.insert(0, values_min) breaks.append(values_max) # Apply colours # 5-class BuGn from ColorBrewer.org colours = ["edf8fb", "b2e2e2", "66c2a4", "2ca25f", "006d2c", ] for solution in solutions: for i in range(classes): value = solution.scale if value >= breaks[i] and \ value <= breaks[i + 1]: solution.color = colours[i] break # A table showing overall rankings thead = THEAD( TR( TH(T("Solution Item"), _rowspan="2"), TH(T("Scale"), _rowspan="2"), TH(T("Uncertainty"), _rowspan="2"), TH(T("Activity Level"), _colspan="3"), ), TR( TH(T("Voted on")), TH(T("Times Changed")), TH(T("Comments")), ), ) tbody = TBODY() for solution in solutions: rows = True tbody.append( TR( TD(solution.name), TD(solution.scale, _class="taright"), TD(solution.uncertainty, _class="taright"), TD(solution.votes(), _class="tacenter"), TD(solution.changes, _class="tacenter"), TD(solution.comments(), _class="tacenter"), _style="background:#%s" % solution.color ) ) summary = TABLE(thead, tbody, _class="delphi_wide") # Add Custom CSS from Static (cacheable) s3.stylesheets.append("S3/delphi.css") return dict(rheader=rheader, num_voted=num_voted, chart=image, summary=summary, grids=grids ) # ============================================================================= # Discussions # ============================================================================= def discuss(r, **attr): """ Custom Method to manage the discussion of a Problem or Solution """ if r.component: resourcename = "solution" id = r.component_id else: resourcename = "problem" id = r.id # Add the RHeader to maintain consistency with the other pages rheader = problem_rheader(r) ckeditor = URL(c="static", f="ckeditor", args="ckeditor.js") s3.scripts.append(ckeditor) adapter = URL(c="static", f="ckeditor", args=["adapters", "jquery.js"]) s3.scripts.append(adapter) # Toolbar options: http://docs.cksource.com/CKEditor_3.x/Developers_Guide/Toolbar js = "".join(( '''i18n.reply="''', str(T("Reply")), '''" var img_path=S3.Ap.concat('/static/img/jCollapsible/') var ck_config={toolbar:[['Bold','Italic','-','NumberedList','BulletedList','-','Link','Unlink','-','Smiley','-','Source','Maximize']],toolbarCanCollapse:false,removePlugins:'elementspath'} function comment_reply(id){ $('#delphi_comment_solution_id__row').hide() $('#delphi_comment_solution_id__row1').hide() $('#comment-title').html(i18n.reply) var ed = $('#delphi_comment_body').ckeditorGet() ed.destroy() $('#delphi_comment_body').ckeditor(ck_config) $('#comment-form').insertAfter($('#comment-'+id)) $('#delphi_comment_parent').val(id) var solution_id=$('#comment-'+id).attr('solution_id') if(undefined!=solution_id){ $('#delphi_comment_solution_id').val(solution_id) } }''')) s3.js_global.append(js) response.view = "delphi/discuss.html" return dict(rheader=rheader, resourcename=resourcename, id=id) # ----------------------------------------------------------------------------- def comment_parse(comment, comments, solution_id=None): """ Parse a Comment @param: comment - a gluon.sql.Row: the current comment @param: comments - a gluon.sql.Rows: full list of comments @param: solution_id - a reference ID: optional solution commented on """ author = B(T("Anonymous")) if comment.created_by: utable = s3db.auth_user ptable = s3db.pr_person ltable = s3db.pr_person_user query = (utable.id == comment.created_by) left = [ltable.on(ltable.user_id == utable.id), ptable.on(ptable.pe_id == ltable.pe_id)] row = db(query).select(utable.email, ptable.first_name, ptable.middle_name, ptable.last_name, left=left, limitby=(0, 1)).first() if row: person = row.pr_person user = row[utable._tablename] username = s3_fullname(person) email = user.email.strip().lower() import hashlib hash = hashlib.md5(email).hexdigest() url = "http://www.gravatar.com/%s" % hash author = B(A(username, _href=url, _target="top")) if not solution_id and comment.solution_id: solution = "re: %s" % s3db.delphi_solution_represent(comment.solution_id) header = DIV(author, " ", solution) solution_id = comment.solution_id else: header = author thread = LI(DIV(s3base.s3_avatar_represent(comment.created_by), DIV(DIV(header, _class="comment-header"), DIV(XML(comment.body)), _class="comment-text"), DIV(DIV(comment.created_on, _class="comment-date"), DIV(A(T("Reply"), _class="action-btn"), _onclick="comment_reply(%i);" % comment.id, _class="comment-reply"), _class="fright"), _id="comment-%i" % comment.id, _solution_id=solution_id, _class="comment-box")) # Add the children of this thread children = UL(_class="children") id = comment.id count = 0 for comment in comments: if comment.parent == id: count = 1 child = comment_parse(comment, comments, solution_id=solution_id) children.append(child) if count == 1: thread.append(children) return thread # ----------------------------------------------------------------------------- def comments(): """ Function accessed by AJAX from discuss() to handle Comments """ try: resourcename = request.args[0] except: raise HTTP(400) try: id = request.args[1] except: raise HTTP(400) if resourcename == "problem": problem_id = id solution_id = None elif resourcename == "solution": stable = s3db.delphi_solution query = (stable.id == id) solution = db(query).select(stable.problem_id, limitby=(0, 1)).first() if solution: problem_id = solution.problem_id solution_id = id else: raise HTTP(400) else: raise HTTP(400) table = s3db.delphi_comment field = table.problem_id field.default = problem_id field.writable = field.readable = False sfield = table.solution_id if solution_id: sfield.default = solution_id sfield.writable = sfield.readable = False else: sfield.label = T("Related to Solution (optional)") sfield.requires = IS_EMPTY_OR( IS_ONE_OF(db, "delphi_solution.id", s3.delphi_solution_represent, filterby="problem_id", filter_opts=(problem_id,) )) # Form to add a new Comment from gluon.tools import Crud form = Crud(db).create(table, formname="delphi_%s/%s" % (resourcename, id)) # List of existing Comments if solution_id: comments = db(sfield == solution_id).select(table.id, table.parent, table.body, table.created_by, table.created_on) else: comments = db(field == problem_id).select(table.id, table.parent, table.solution_id, table.body, table.created_by, table.created_on) output = UL(_id="comments") for comment in comments: if not comment.parent: # Show top-level threads at top-level thread = comment_parse(comment, comments, solution_id=solution_id) output.append(thread) # Also see the outer discuss() script = \ '''$('#comments').collapsible({xoffset:'-5',yoffset:'50',imagehide:img_path+'arrow-down.png',imageshow:img_path+'arrow-right.png',defaulthide:false}) $('#delphi_comment_parent__row1').hide() $('#delphi_comment_parent__row').hide() $('#delphi_comment_body').ckeditor(ck_config) $('#submit_record__row input').click(function(){$('#comment-form').hide();$('#delphi_comment_body').ckeditorGet().destroy();return true;})''' # No layout in this output! #s3.jquery_ready.append(script) output = DIV(output, DIV(H4(T("New Post"), _id="comment-title"), form, _id="comment-form", _class="clear"), SCRIPT(script)) return XML(output) # END =========================================================================
controllers/delphi.py
45,285
Utility function used by Scale of Results Looks up the Unit Normal Deviation based on the Z-Score (Proportion/Probability) http://en.wikipedia.org/wiki/Standard_normal_table @ToDo: Move to S3Statistics module Parse a Comment @param: comment - a gluon.sql.Row: the current comment @param: comments - a gluon.sql.Rows: full list of comments @param: solution_id - a reference ID: optional solution commented on Function accessed by AJAX from discuss() to handle Comments Custom Method to manage the discussion of a Problem or Solution Problem Group REST Controller Group rheader Module Home Page - provide the list of currently-Active Problems A numerically stable algorithm for calculating variance http://en.wikipedia.org/wiki/Algorithms_for_calculating_variance#On-line_algorithm Problem REST Controller Problem rheader Redirect to the list of Problems for the Group - used for a Tab Custom Method to show the Scale of Results Function accessed by AJAX from vote() to save the results of a Vote Used for Imports Custom Method to allow Voting on Solutions to a Problem Delphi Decision Maker - Controllers coding: utf8 ============================================================================= Simply redirect to the Problems REST controller Alternative dashboard ============================================================================= Groups ============================================================================= List or Create form: rheader makes no sense here Get this User's permissions for this Group ----------------------------------------------------------------------------- Remove ability to create new Groupsinsertable=False Allow components with components (such as problem) to breakout from tabs ============================================================================= Problems ============================================================================= List or Create form: rheader makes no sense here Components & Custom Methods Get this User's permissions for this Group ----------------------------------------------------------------------------- Custom Methods Discussion can also be done at the Solution component level Filter to just Active Problems Remove ability to create new Problemsinsertable = False ----------------------------------------------------------------------------- ----------------------------------------------------------------------------- ============================================================================= Voting ============================================================================= Get this User's permissions for this Group Add the RHeader to maintain consistency with the other pages Lookup Solution Options Add to the list of ranked options Remove from the unranked options Add Custom CSS from Static (cacheable) Add Custom Javascript Settings to be picked up by Static code Static code which can be cached ----------------------------------------------------------------------------- Get this User's permissions for this Group Decode the data Check the votes are valid Convert to a format suitable for comparisons Read the old votes Calculate changes We've already evaluated this pair This pair has changed places, so update Solution Clear the old votes Save the new votes ----------------------------------------------------------------------------- Assume indifference maximum value ----------------------------------------------------------------------------- ----------------------------------------------------------------------------- Add the RHeader to maintain consistency with the other pages Lookup Votes Lookup Solutions Needed for Votes virtual field Initialise arrays of pairwise comparisons Allow new solutions to start at an indifferent probability List of Voters Update array of pairwise comparisons based on votes Create array F which is the number of time a solution has been preferred compared to it'a partner Preferred should be the columns Use the pairwise comparisons to build a Dynamic Thurstone scale of results http://en.wikipedia.org/wiki/Thurstone_scale http://www.brocku.ca/MeadProject/Thurstone/Thurstone_1927a.html http://www.brocku.ca/MeadProject/Thurstone/Thurstone_1927f.html @ToDo: For incomplete data, the calculation is more complex: Gulliksen Convert array F to array P by converting totals to proportions Convert array P to array X, which is the unit normal deviate Preferred should be the columns No votes yet, so assume indifference Cannot do unit normal deviation for 0/1 so approximate in order to not have to do the incomplete data maths Now calculate the uncertainty scale i.e. assume that every user who didn't vote on a particular pair drags that back towards indifference Assume the novotes vote against Assume the novotes vote for Cannot do unit normal deviation for 0/1 so approximate in order to not have to do the incomplete data maths Preferred should be the columns Preferred should be the columns Least-squares estimate of the scale values Average of the columns Preferred should be the columns Preferred should be the columns Least-squares estimate of the uncertainty values Average of the columns Sort the Solutions by Scale @ToDo: deployment_setting Canvas of 900x600 Add Axes with padding of 10px for the labels (fractional left, bottom, width, height) rotation="vertical" or rotation = 45 color="blue" Colour the rows Calculate Breaks Make mutable Apply colours 5-class BuGn from ColorBrewer.org A table showing overall rankings Add Custom CSS from Static (cacheable) ============================================================================= Discussions ============================================================================= Add the RHeader to maintain consistency with the other pages Toolbar options: http://docs.cksource.com/CKEditor_3.x/Developers_Guide/Toolbar ----------------------------------------------------------------------------- Add the children of this thread ----------------------------------------------------------------------------- Form to add a new Comment List of existing Comments Show top-level threads at top-level Also see the outer discuss() No layout in this output!s3.jquery_ready.append(script) END =========================================================================
6,274
en
0.6501
#Copyright (c) 2013 Marion Zepf #Copyright (c) 2014 Walter Bender #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. """ type system for Primitives and their arguments """ import ast from tablock import Media from taconstants import (Color, ColorObj, CONSTANTS, Vector) class Type(object): """ A type in the type hierarchy. """ def __init__(self, constant_name, value): """ constant_name -- the name of the constant that points to this Type object value -- an arbitrary integer that is different from the values of all other Types. The order of the integers doesn't matter. """ self.constant_name = constant_name self.value = value def __eq__(self, other): if other is None: return False if not isinstance(other, Type): return False return self.value == other.value def __str__(self): return str(self.constant_name) __repr__ = __str__ class TypeDisjunction(tuple, Type): """ Disjunction of two or more Types (from the type hierarchy) """ def __init__(self, iterable): self = tuple(iterable) def __str__(self): s = ["("] for disj in self: s.append(str(disj)) s.append(" or ") s.pop() s.append(")") return "".join(s) # individual types TYPE_OBJECT = Type('TYPE_OBJECT', 0) TYPE_CHAR = Type('TYPE_CHAR', 1) TYPE_COLOR = Type('TYPE_COLOR', 2) TYPE_FLOAT = Type('TYPE_FLOAT', 3) TYPE_INT = Type('TYPE_INT', 4) TYPE_BOOL = Type('TYPE_BOOL', 5) # shortcut to avoid a TypeDisjunction between TYPE_FLOAT and TYPE_INT TYPE_NUMBER = Type('TYPE_NUMBER', 6) TYPE_NUMERIC_STRING = Type('TYPE_NUMERIC_STRING', 7) TYPE_BOX = Type('TYPE_BOX', 8) # special type for the unknown content of a box TYPE_STRING = Type('TYPE_STRING', 9) TYPE_MEDIA = Type('TYPE_MEDIA', 10) # An array of numbers used by the food plugin et al. TYPE_VECTOR = Type('TYPE_VECTOR', 11) # groups/ classes of types TYPES_NUMERIC = (TYPE_FLOAT, TYPE_INT, TYPE_NUMBER) BOX_AST = ast.Name(id='BOX', ctx=ast.Load) ACTION_AST = ast.Name(id='ACTION', ctx=ast.Load) def get_type(x): """ Return the most specific type in the type hierarchy that applies to x and a boolean indicating whether x is an AST. If the type cannot be determined, return TYPE_OBJECT as the type. """ # non-AST types if isinstance(x, (int, long)): return (TYPE_INT, False) elif isinstance(x, float): return (TYPE_FLOAT, False) elif isinstance(x, basestring): if len(x) == 1: return (TYPE_CHAR, False) try: float(x) except ValueError: return (TYPE_STRING, False) else: return (TYPE_NUMERIC_STRING, False) elif isinstance(x, Color): return (TYPE_COLOR, False) elif isinstance(x, Media): return (TYPE_MEDIA, False) elif isinstance(x, Vector): return (TYPE_VECTOR, False) elif hasattr(x, "return_type"): return (x.return_type, False) # AST types elif isinstance(x, ast.Num): return (get_type(x.n)[0], True) elif isinstance(x, ast.Str): return (get_type(x.s)[0], True) elif isinstance(x, ast.Name): try: # we need to have imported CONSTANTS for this to work value = eval(x.id) except NameError: return (TYPE_OBJECT, True) else: return (get_type(value)[0], True) elif isinstance(x, ast.Subscript): if x.value == BOX_AST: return (TYPE_BOX, True) elif isinstance(x, ast.Call): if isinstance(x.func, ast.Name): if x.func.id == 'float': return (TYPE_FLOAT, True) elif x.func.id in ('int', 'ord'): return (TYPE_INT, True) elif x.func.id == 'chr': return (TYPE_CHAR, True) elif x.func.id in ('repr', 'str', 'unicode'): return (TYPE_STRING, True) elif x.func.id == 'Color': return (TYPE_COLOR, True) elif x.func.id == 'Media': return (TYPE_MEDIA, True) # unary operands never change the type of their argument elif isinstance(x, ast.UnaryOp): if issubclass(x.op, ast.Not): # 'not' always returns a boolean return (TYPE_BOOL, True) else: return get_type(x.operand) # boolean and comparison operators always return a boolean if isinstance(x, (ast.BoolOp, ast.Compare)): return (TYPE_BOOL, True) # other binary operators elif isinstance(x, ast.BinOp): type_left = get_type(x.left)[0] type_right = get_type(x.right)[0] if type_left == TYPE_STRING or type_right == TYPE_STRING: return (TYPE_STRING, True) if type_left == type_right == TYPE_INT: return (TYPE_INT, True) else: return (TYPE_FLOAT, True) return (TYPE_OBJECT, isinstance(x, ast.AST)) def is_instancemethod(method): # TODO how to access the type `instancemethod` directly? return type(method).__name__ == "instancemethod" def is_bound_method(method): return ((is_instancemethod(method) and method.im_self is not None) or (hasattr(method, '__self__') and method.__self__ is not None)) def is_staticmethod(method): # TODO how to access the type `staticmethod` directly? return type(method).__name__ == "staticmethod" def identity(x): return x TYPE_CONVERTERS = { # Type hierarchy: If there is a converter A -> B, then A is a subtype of B. # The converter from A to B is stored under TYPE_CONVERTERS[A][B]. # The relation describing the type hierarchy must be transitive, i.e. # converting A -> C must yield the same result as converting A -> B -> C. # TYPE_OBJECT is the supertype of everything. TYPE_BOX: { TYPE_COLOR: ColorObj, # FIXME: should be Color.name TYPE_VECTOR: Vector, TYPE_FLOAT: float, TYPE_INT: int, TYPE_NUMBER: float, TYPE_STRING: str}, TYPE_CHAR: { TYPE_INT: ord, TYPE_STRING: identity}, TYPE_COLOR: { TYPE_FLOAT: float, TYPE_INT: int, TYPE_NUMBER: int, TYPE_STRING: Color.get_number_string}, TYPE_FLOAT: { TYPE_INT: int, TYPE_NUMBER: identity, TYPE_STRING: str}, TYPE_INT: { TYPE_FLOAT: float, TYPE_NUMBER: identity, TYPE_STRING: str}, TYPE_NUMBER: { TYPE_FLOAT: float, TYPE_INT: int, TYPE_STRING: str}, TYPE_NUMERIC_STRING: { TYPE_FLOAT: float, TYPE_STRING: identity} } class TATypeError(BaseException): """ TypeError with the types from the hierarchy, not with Python types """ def __init__(self, bad_value, bad_type=None, req_type=None, message=''): """ bad_value -- the mis-typed value that caused the error bad_type -- the type of the bad_value req_type -- the type that the value was expected to have message -- short statement about the cause of the error. It is not shown to the user, but may appear in debugging output. """ self.bad_value = bad_value self.bad_type = bad_type self.req_type = req_type self.message = message def __str__(self): msg = [] if self.message: msg.append(self.message) msg.append(" (") msg.append("bad value: ") msg.append(repr(self.bad_value)) if self.bad_type is not None: msg.append(", bad type: ") msg.append(repr(self.bad_type)) if self.req_type is not None: msg.append(", req type: ") msg.append(repr(self.req_type)) if self.message: msg.append(")") return "".join(msg) __repr__ = __str__ def get_converter(old_type, new_type): """ If there is a converter old_type -> new_type, return it. Else return None. If a chain of converters is necessary, return it as a tuple or list (starting with the innermost, first-to-apply converter). """ # every type can be converted to TYPE_OBJECT if new_type == TYPE_OBJECT: return identity # every type can be converted to itself if old_type == new_type: return identity # is there a converter for this pair of types? converters_from_old = TYPE_CONVERTERS.get(old_type) if converters_from_old is None: return None converter = converters_from_old.get(new_type) if converter is not None: return converter else: # form the transitive closure of all types that old_type can be # converted to, and look for new_type there backtrace = converters_from_old.copy() new_backtrace = backtrace.copy() break_all = False while True: newest_backtrace = {} for t in new_backtrace: for new_t in TYPE_CONVERTERS.get(t, {}): if new_t not in backtrace: newest_backtrace[new_t] = t backtrace[new_t] = t if new_t == new_type: break_all = True break if break_all: break if break_all or not newest_backtrace: break new_backtrace = newest_backtrace # use the backtrace to find the path from old_type to new_type if new_type in backtrace: converter_chain = [] t = new_type while t in backtrace and isinstance(backtrace[t], Type): converter_chain.insert(0, TYPE_CONVERTERS[backtrace[t]][t]) t = backtrace[t] converter_chain.insert(0, TYPE_CONVERTERS[old_type][t]) return converter_chain return None def convert(x, new_type, old_type=None, converter=None): """ Convert x to the new type if possible. old_type -- the type of x. If not given, it is computed. """ if not isinstance(new_type, Type): raise ValueError('%s is not a type in the type hierarchy' % (repr(new_type))) # every type can be converted to TYPE_OBJECT if new_type == TYPE_OBJECT: return x if not isinstance(old_type, Type): (old_type, is_an_ast) = get_type(x) else: is_an_ast = isinstance(x, ast.AST) # every type can be converted to itself if old_type == new_type: return x # special case: 'box' block (or 'pop' block) as an AST if is_an_ast and old_type == TYPE_BOX: new_type_ast = ast.Name(id=new_type.constant_name) return get_call_ast('convert', [x, new_type_ast], return_type=new_type) # if the converter is not given, try to find one if converter is None: converter = get_converter(old_type, new_type) if converter is None: # no converter available raise TATypeError(bad_value=x, bad_type=old_type, req_type=new_type, message=("found no converter" " for this type combination")) def _apply_converter(converter, y): try: if is_an_ast: if converter == identity: return y elif is_instancemethod(converter): func = ast.Attribute(value=y, attr=converter.im_func.__name__, ctx=ast.Load) return get_call_ast(func) else: func_name = converter.__name__ return get_call_ast(func_name, [y]) else: return converter(y) except BaseException: raise TATypeError(bad_value=x, bad_type=old_type, req_type=new_type, message=("error during " "conversion")) if isinstance(converter, (list, tuple)): # apply the converter chain recursively result = x for conv in converter: result = _apply_converter(conv, result) return result elif converter is not None: return _apply_converter(converter, x) class TypedAST(ast.AST): @property def return_type(self): if self._return_type is None: return get_type(self.func)[0] else: return self._return_type class TypedCall(ast.Call,TypedAST): """ Like a Call AST, but with a return type """ def __init__(self, func, args=None, keywords=None, starargs=None, kwargs=None, return_type=None): if args is None: args = [] if keywords is None: keywords = [] ast.Call.__init__(self, func=func, args=args, keywords=keywords, starargs=starargs, kwargs=kwargs) self._return_type = return_type class TypedSubscript(ast.Subscript,TypedAST): """ Like a Subscript AST, but with a type """ def __init__(self, value, slice_, ctx=ast.Load, return_type=None): ast.Subscript.__init__(self, value=value, slice=slice_, ctx=ctx) self._return_type = return_type class TypedName(ast.Name,TypedAST): """ Like a Name AST, but with a type """ def __init__(self, id_, ctx=ast.Load, return_type=None): ast.Name.__init__(self, id=id_, ctx=ctx) self._return_type = return_type def get_call_ast(func_name, args=None, kwargs=None, return_type=None): """ Return an AST representing the call to a function with the name func_name, passing it the arguments args (given as a list) and the keyword arguments kwargs (given as a dictionary). func_name -- either the name of a callable as a string, or an AST representing a callable expression return_type -- if this is not None, return a TypedCall object with this return type instead """ if args is None: args = [] # convert keyword argument dict to a list of (key, value) pairs keywords = [] if kwargs is not None: for (key, value) in kwargs.iteritems(): keywords.append(ast.keyword(arg=key, value=value)) # get or generate the AST representing the callable if isinstance(func_name, ast.AST): func_ast = func_name else: func_ast = ast.Name(id=func_name, ctx=ast.Load) # if no return type is given, return a simple Call AST if return_type is None: return ast.Call(func=func_ast, args=args, keywords=keywords, starargs=None, kwargs=None) # if a return type is given, return a TypedCall AST else: return TypedCall(func=func_ast, args=args, keywords=keywords, return_type=return_type)
TurtleArt/tatype.py
15,843
TypeError with the types from the hierarchy, not with Python types A type in the type hierarchy. Disjunction of two or more Types (from the type hierarchy) Like a Call AST, but with a return type Like a Name AST, but with a type Like a Subscript AST, but with a type constant_name -- the name of the constant that points to this Type object value -- an arbitrary integer that is different from the values of all other Types. The order of the integers doesn't matter. bad_value -- the mis-typed value that caused the error bad_type -- the type of the bad_value req_type -- the type that the value was expected to have message -- short statement about the cause of the error. It is not shown to the user, but may appear in debugging output. Convert x to the new type if possible. old_type -- the type of x. If not given, it is computed. Return an AST representing the call to a function with the name func_name, passing it the arguments args (given as a list) and the keyword arguments kwargs (given as a dictionary). func_name -- either the name of a callable as a string, or an AST representing a callable expression return_type -- if this is not None, return a TypedCall object with this return type instead If there is a converter old_type -> new_type, return it. Else return None. If a chain of converters is necessary, return it as a tuple or list (starting with the innermost, first-to-apply converter). Return the most specific type in the type hierarchy that applies to x and a boolean indicating whether x is an AST. If the type cannot be determined, return TYPE_OBJECT as the type. type system for Primitives and their arguments Copyright (c) 2013 Marion ZepfCopyright (c) 2014 Walter BenderPermission is hereby granted, free of charge, to any person obtaining a copyof this software and associated documentation files (the "Software"), to dealin the Software without restriction, including without limitation the rightsto use, copy, modify, merge, publish, distribute, sublicense, and/or sellcopies of the Software, and to permit persons to whom the Software isfurnished to do so, subject to the following conditions:The above copyright notice and this permission notice shall be included inall copies or substantial portions of the Software.THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS ORIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THEAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHERLIABILITY, 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 INTHE SOFTWARE. individual types shortcut to avoid a TypeDisjunction between TYPE_FLOAT and TYPE_INT special type for the unknown content of a box An array of numbers used by the food plugin et al. groups/ classes of types non-AST types AST types we need to have imported CONSTANTS for this to work unary operands never change the type of their argument 'not' always returns a boolean boolean and comparison operators always return a boolean other binary operators TODO how to access the type `instancemethod` directly? TODO how to access the type `staticmethod` directly? Type hierarchy: If there is a converter A -> B, then A is a subtype of B. The converter from A to B is stored under TYPE_CONVERTERS[A][B]. The relation describing the type hierarchy must be transitive, i.e. converting A -> C must yield the same result as converting A -> B -> C. TYPE_OBJECT is the supertype of everything. FIXME: should be Color.name every type can be converted to TYPE_OBJECT every type can be converted to itself is there a converter for this pair of types? form the transitive closure of all types that old_type can be converted to, and look for new_type there use the backtrace to find the path from old_type to new_type every type can be converted to TYPE_OBJECT every type can be converted to itself special case: 'box' block (or 'pop' block) as an AST if the converter is not given, try to find one no converter available apply the converter chain recursively convert keyword argument dict to a list of (key, value) pairs get or generate the AST representing the callable if no return type is given, return a simple Call AST if a return type is given, return a TypedCall AST
4,396
en
0.809966
#!/usr/bin/python # -*- coding: utf-8 -*- # Copyright (c) 2021, Cisco Systems # GNU General Public License v3.0+ (see LICENSE or https://www.gnu.org/licenses/gpl-3.0.txt) DOCUMENTATION = r""" --- module: anc_endpoint_apply short_description: Resource module for Anc Endpoint Apply description: - Manage operation update of the resource Anc Endpoint Apply. version_added: '1.0.0' extends_documentation_fragment: - cisco.ise.module author: Rafael Campos (@racampos) options: additionalData: description: Anc Endpoint Apply's additionalData. suboptions: name: description: Anc Endpoint Apply's name. type: str value: description: Anc Endpoint Apply's value. type: str type: list requirements: - ciscoisesdk >= 1.1.0 - python >= 3.5 seealso: # Reference by Internet resource - name: Anc Endpoint Apply reference description: Complete reference of the Anc Endpoint Apply object model. link: https://ciscoisesdk.readthedocs.io/en/latest/api/api.html#v3-0-0-summary """ EXAMPLES = r""" - name: Update all cisco.ise.anc_endpoint_apply: ise_hostname: "{{ise_hostname}}" ise_username: "{{ise_username}}" ise_password: "{{ise_password}}" ise_verify: "{{ise_verify}}" additionalData: - name: macAddress value: MAC address - name: ipAddress value: IP address - name: policyName value: Policy Name """ RETURN = r""" ise_response: description: A dictionary or list with the response returned by the Cisco ISE Python SDK returned: always type: dict sample: > {} """
venv/lib/python3.8/site-packages/ansible_collections/cisco/ise/plugins/modules/anc_endpoint_apply.py
1,583
!/usr/bin/python -*- coding: utf-8 -*- Copyright (c) 2021, Cisco Systems GNU General Public License v3.0+ (see LICENSE or https://www.gnu.org/licenses/gpl-3.0.txt)
163
en
0.65351
# -*- coding:utf-8 -*- # =========================================================================== # # Project : MLStudio # # File : \test_preprocessing.py # # Python : 3.8.3 # # --------------------------------------------------------------------------- # # Author : John James # # Company : nov8.ai # # Email : jjames@nov8.ai # # URL : https://github.com/nov8ai/MLStudio # # --------------------------------------------------------------------------- # # Created : Saturday, July 25th 2020, 9:54:15 pm # # Last Modified : Saturday, July 25th 2020, 9:54:15 pm # # Modified By : John James (jjames@nov8.ai) # # --------------------------------------------------------------------------- # # License : BSD # # Copyright (c) 2020 nov8.ai # # =========================================================================== # """Tests data preprocessing pipeline.""" #%% import numpy as np import pytest from pytest import mark from scipy.sparse import csr_matrix from sklearn.datasets import make_classification, make_regression from mlstudio.factories.data import DataProcessors # -------------------------------------------------------------------------- # def check_add_bias(X, X_train, test): assert X_train.shape[1] == X.shape[1] + 1, test + ": bias term wasn't added." def check_split(X, y, X_train, y_train, X_val, y_val, test): assert X_train.shape[1] == X.shape[1] + 1, test + ": bias term wasn't added." assert X.shape[0] > X_train.shape[0], test + ": split didn't happen." assert X_train.shape[0] == y_train.shape[0], test + ": X, y shape mismatch." assert X_val.shape[0] == y_val.shape[0], test + ": X, y shape mismatch." assert X_train.shape[0] > X_val.shape[0], test + ": Train size not greater than test." def check_label_encoder(y, test): assert all(y) in range(len(np.unique(y))), test + ": label encoding didn't work" def check_one_hot_label_encoder(y, test): assert np.sum(y) == y.shape[0], test + ": one-hot-label encoding didn't binarize" assert y.shape[1] > 2, test + ": one-hot-label encoding didn't create vector." @mark.data_processing @mark.regression_data class RegressionDataTests: _test = "Regression data" def test_regression_train_data(self, get_regression_data): X, y = get_regression_data data_processor = DataProcessors.regression data = data_processor().process_train_data(X, y) check_add_bias(X, data['X_train']['data'],test = self._test) def test_regression_train_val_data(self, get_regression_data): X, y = get_regression_data data_processor = DataProcessors.regression data = data_processor().process_train_val_data(X, y, val_size=0.3) check_add_bias(X, data['X_train']['data'], test = self._test) check_add_bias(X, data['X_val']['data'], test = self._test) check_split(X, y, data['X_train']['data'], data['y_train']['data'], data['X_val']['data'], data['y_val']['data'], test=self._test) def test_regression_X_test_data(self, get_regression_data): X, y = get_regression_data data_processor = DataProcessors.regression data = data_processor().process_X_test_data(X) check_add_bias(X, data['X_test']['data'], test = self._test) @mark.data_processing @mark.binaryclass_data class BinaryClassDataTests: _test = "Binary classification data" def test_binaryclass_train_data(self, get_logistic_regression_data): X, y = get_logistic_regression_data y = np.random.choice(["hat", "bowl"], size=y.shape[0]) data_processor = DataProcessors.binaryclass data = data_processor().process_train_data(X, y) check_add_bias(X, data['X_train']['data'],test = self._test) def test_binaryclass_train_val_data(self, get_logistic_regression_data): X, y = get_logistic_regression_data y = np.random.choice(["hat", "bowl"], size=y.shape[0]) data_processor = DataProcessors.binaryclass data = data_processor().process_train_val_data(X, y, val_size=0.3) check_add_bias(X, data['X_train']['data'], test = self._test) check_add_bias(X, data['X_val']['data'], test = self._test) check_split(X, y, data['X_train']['data'], data['y_train']['data'], data['X_val']['data'], data['y_val']['data'], test=self._test) check_label_encoder(data['y_train']['data'], test=self._test) check_label_encoder(data['y_val']['data'], test=self._test) def test_binaryclass_X_test_data(self, get_logistic_regression_data): X, y = get_logistic_regression_data y = np.random.choice(["hat", "bowl"], size=y.shape[0]) data_processor = DataProcessors.binaryclass data = data_processor().process_X_test_data(X) check_add_bias(X, data['X_test']['data'],test = self._test) def test_binaryclass_y_test_data(self, get_logistic_regression_data): X, y = get_logistic_regression_data y = np.random.choice(["hat", "bowl"], size=y.shape[0]) data_processor = DataProcessors.binaryclass data = data_processor().process_y_test_data(y) check_label_encoder(data['y_test']['data'], test=self._test) @mark.data_processing @mark.multiclass_data class MultiClassDataTests: _test = "Multi classification data" def test_multiclass_train_data(self, get_multiclass_data): X, y = get_multiclass_data y = np.random.choice(["hat", "bowl", "junky", "riding", "happy"], size=y.shape[0]) data_processor = DataProcessors.multiclass data = data_processor().process_train_data(X, y) check_add_bias(X, data['X_train']['data'],test = self._test) def test_multiclass_train_val_data(self, get_multiclass_data): X, y = get_multiclass_data y = np.random.choice(["hat", "bowl", "junky", "riding", "happy"], size=y.shape[0]) data_processor = DataProcessors.multiclass data = data_processor().process_train_val_data(X, y, val_size=0.3) check_add_bias(X, data['X_train']['data'], test = self._test) check_add_bias(X, data['X_val']['data'], test = self._test) check_split(X, y, data['X_train']['data'], data['y_train']['data'], data['X_val']['data'], data['y_val']['data'], test=self._test) check_one_hot_label_encoder(data['y_train']['data'], test=self._test) check_one_hot_label_encoder(data['y_val']['data'], test=self._test) def test_multiclass_X_test_data(self, get_multiclass_data): X, y = get_multiclass_data y = np.random.choice(["hat", "bowl", "junky", "riding", "happy"], size=y.shape[0]) data_processor = DataProcessors.multiclass data = data_processor().process_X_test_data(X) check_add_bias(X, data['X_test']['data'],test = self._test) def test_multiclass_y_test_data(self, get_multiclass_data): X, y = get_multiclass_data y = np.random.choice(["hat", "bowl", "junky", "riding", "happy"], size=y.shape[0]) data_processor = DataProcessors.multiclass data = data_processor().process_y_test_data(y) check_one_hot_label_encoder(data['y_test']['data'], test=self._test)
tests/test_data_services/test_preprocessing.py
7,863
Tests data preprocessing pipeline. -*- coding:utf-8 -*- =========================================================================== Project : MLStudio File : \test_preprocessing.py Python : 3.8.3 --------------------------------------------------------------------------- Author : John James Company : nov8.ai Email : jjames@nov8.ai URL : https://github.com/nov8ai/MLStudio --------------------------------------------------------------------------- Created : Saturday, July 25th 2020, 9:54:15 pm Last Modified : Saturday, July 25th 2020, 9:54:15 pm Modified By : John James (jjames@nov8.ai) --------------------------------------------------------------------------- License : BSD Copyright (c) 2020 nov8.ai =========================================================================== %% --------------------------------------------------------------------------
1,443
en
0.37802
# -*- coding: utf-8 -*- # TheQube profile dialog # A part of TheQube accessible social networking client # Copyright © Andre Polykanine A.K.A. Menelion Elensúlë, 2014 — 2015 from logger import logger logging = logger.getChild("sessions.twitter.gui.profile") import config import sessions import wx from core.gui import SquareDialog import calendar import time import rfc822 class TwitterProfileDialog (SquareDialog): def __init__ (self, user, *args, **kwargs): super(TwitterProfileDialog, self).__init__(title=_("Profile for %s" % user['screen_name']), *args, **kwargs) self.user = user full_url = unicode(self.user['entities']['url']['urls'][0]['expanded_url']) if 'url' in self.user['entities'] else '' self.screen_name = self.labeled_control(_("Screen name:"), wx.TextCtrl, style=wx.TE_MULTILINE | wx.TE_READONLY | wx.WANTS_CHARS, value=unicode(user['screen_name'])) self.screen_name.Bind(wx.EVT_CHAR, self.charPressed) self.name = self.labeled_control(_("Real name:"), wx.TextCtrl, style=wx.TE_MULTILINE | wx.TE_READONLY | wx.WANTS_CHARS, value=unicode(user['name'])) self.name.Bind(wx.EVT_CHAR, self.charPressed) if unicode(user['location']) != '' and unicode(user['location']).lower() != 'none': self.location = self.labeled_control(_("Location:"), wx.TextCtrl, style=wx.TE_MULTILINE | wx.TE_READONLY | wx.WANTS_CHARS, value=unicode(user['location'])) self.location.Bind(wx.EVT_CHAR, self.charPressed) self.account_id = self.labeled_control(_("Account ID:"), wx.TextCtrl, style=wx.TE_MULTILINE | wx.TE_READONLY | wx.WANTS_CHARS, value=unicode(user['id'])) self.account_id.Bind(wx.EVT_CHAR, self.charPressed) if full_url != '' and full_url.lower() != 'none' and full_url.lower() != 'http://none': self.url = self.labeled_control(_("URL:"), wx.TextCtrl, style=wx.TE_RICH2 | wx.TE_MULTILINE | wx.TE_AUTO_URL | wx.TE_READONLY | wx.WANTS_CHARS, value=full_url) self.url.Bind(wx.EVT_CHAR, self.charPressed) if unicode(user['description']) != '' and unicode(user['description']).lower() != 'none': size = self.Size size[0] = size[0] / 2 size[1] = -1 self.description = self.labeled_control(_("Bio:"), wx.TextCtrl, style=wx.TE_RICH2 | wx.TE_MULTILINE | wx.TE_READONLY, size=size, value=unicode(user['description'])) self.description.Bind(wx.EVT_CHAR, self.charPressed) self.protected = self.labeled_control(_("Tweets are protected:"), wx.TextCtrl, style=wx.TE_MULTILINE | wx.TE_READONLY | wx.WANTS_CHARS) if user['protected']: self.protected.SetValue(_("Yes")) else: self.protected.SetValue(_("No")) self.protected.Bind(wx.EVT_CHAR, self.charPressed) self.followers_count = self.labeled_control(_("Number of followers:"), wx.TextCtrl, style=wx.TE_MULTILINE | wx.TE_READONLY | wx.WANTS_CHARS, value=unicode(user['followers_count'])) self.followers_count.Bind(wx.EVT_CHAR, self.charPressed) self.friends_count = self.labeled_control(_("Number of friends:"), wx.TextCtrl, style=wx.TE_MULTILINE | wx.TE_READONLY | wx.WANTS_CHARS, value=unicode(user['friends_count'])) self.friends_count.Bind(wx.EVT_CHAR, self.charPressed) self.listed_count = self.labeled_control(_("Number of having this user in their lists:"), wx.TextCtrl, style=wx.TE_MULTILINE | wx.TE_READONLY | wx.WANTS_CHARS, value=unicode(user['listed_count'])) self.listed_count.Bind(wx.EVT_CHAR, self.charPressed) self.statuses_count = self.labeled_control(_("Number of tweets:"), wx.TextCtrl, parent=self.pane, style=wx.TE_MULTILINE | wx.TE_READONLY | wx.WANTS_CHARS, value=unicode(user['statuses_count'])) self.statuses_count.Bind(wx.EVT_CHAR, self.charPressed) self.average_tweets = self.labeled_control(_("Average tweets per day since joining Twitter:"), wx.TextCtrl, style=wx.TE_MULTILINE | wx.TE_READONLY | wx.WANTS_CHARS) self.average_tweets.SetValue(unicode(int(round(int(unicode(user['statuses_count'])) * 86400 / (time.time() - time.mktime(rfc822.parsedate(user['created_at']))))))) self.average_tweets.Bind(wx.EVT_CHAR, self.charPressed) self.status_created_at = self.labeled_control(_("Date of last tweet:"), wx.TextCtrl, style=wx.TE_MULTILINE | wx.TE_READONLY | wx.WANTS_CHARS) if 'status' in user: self.status_created_at.SetValue(time.strftime('%c', time.localtime(calendar.timegm(rfc822.parsedate(user['status']['created_at']))))) else: self.status_created_at.SetValue(_("Not available")) self.status_created_at.Bind(wx.EVT_CHAR, self.charPressed) self.created_at = self.labeled_control(_("Date joined Twitter:"), wx.TextCtrl, style=wx.TE_MULTILINE | wx.TE_READONLY | wx.WANTS_CHARS) self.created_at.SetValue(time.strftime('%c', time.localtime(calendar.timegm(rfc822.parsedate(user['created_at']))))) self.created_at.Bind(wx.EVT_CHAR, self.charPressed) self.setup_follow_button(user) self.btn_close = wx.Button(parent=self.pane, id=wx.ID_CLOSE) self.btn_close.SetSizerProps(expand = True) self.SetEscapeId(wx.ID_CLOSE) self.finish_setup(create_buttons=False) def charPressed(self, evt): object = evt.GetEventObject() key = evt.GetKeyCode() modifiers = evt.GetModifiers() if config.main['UI']['stdKeyHandling'] and key in (wx.WXK_END, wx.WXK_HOME): evt.Skip() elif key == wx.WXK_HOME and not modifiers: object.SetInsertionPoint(0) elif key == wx.WXK_END and not modifiers: object.SetInsertionPointEnd() elif key == wx.WXK_HOME and modifiers == wx.MOD_SHIFT: object.SetSelection(object.GetInsertionPoint(), 0) elif key == wx.WXK_END and modifiers == wx.MOD_SHIFT: object.SetSelection(object.GetInsertionPoint(), len(object.GetValue())) elif key == 1 and modifiers == wx.MOD_CONTROL: object.SetInsertionPoint(0) object.SetSelection(0, len(object.GetValue())) else: evt.Skip() def setup_follow_button (self, user): if sessions.current_session.is_current_user(user['screen_name']): return if not user['following']: self.follow_button = wx.Button(parent=self.pane, label=_("Follow %s") % user['name']) self.follow_button.Bind(wx.EVT_BUTTON, self.follow) else: self.follow_button = wx.Button(parent=self.pane, label=_("Unfollow %s") % user['name']) self.follow_button.Bind(wx.EVT_BUTTON, self.unfollow) self.follow_button.SetSizerProps(expand=True) def follow (self, evt): evt.Skip() sessions.current_session.follow(screen_name=self.user['screen_name']) def unfollow (self, evt): evt.Skip() sessions.current_session.do_unfollow(screen_name=self.user['screen_name'], action=0)
src/session/twitter/gui/profile.py
6,565
-*- coding: utf-8 -*- TheQube profile dialog A part of TheQube accessible social networking client Copyright © Andre Polykanine A.K.A. Menelion Elensúlë, 2014 — 2015
165
en
0.701812
# # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. import hashlib import os from datetime import timedelta from time import sleep from typing import Any, Dict, Iterable from airflow.exceptions import ( AirflowException, AirflowRescheduleException, AirflowSensorTimeout, AirflowSkipException, ) from airflow.models import BaseOperator, SkipMixin, TaskReschedule from airflow.ti_deps.deps.ready_to_reschedule import ReadyToRescheduleDep from airflow.utils import timezone from airflow.utils.decorators import apply_defaults class BaseSensorOperator(BaseOperator, SkipMixin): """ Sensor operators are derived from this class and inherit these attributes. Sensor operators keep executing at a time interval and succeed when a criteria is met and fail if and when they time out. :param soft_fail: Set to true to mark the task as SKIPPED on failure :type soft_fail: bool :param poke_interval: Time in seconds that the job should wait in between each tries :type poke_interval: float :param timeout: Time, in seconds before the task times out and fails. :type timeout: float :param mode: How the sensor operates. Options are: ``{ poke | reschedule }``, default is ``poke``. When set to ``poke`` the sensor is taking up a worker slot for its whole execution time and sleeps between pokes. Use this mode if the expected runtime of the sensor is short or if a short poke interval is required. Note that the sensor will hold onto a worker slot and a pool slot for the duration of the sensor's runtime in this mode. When set to ``reschedule`` the sensor task frees the worker slot when the criteria is not yet met and it's rescheduled at a later time. Use this mode if the time before the criteria is met is expected to be quite long. The poke interval should be more than one minute to prevent too much load on the scheduler. :type mode: str :param exponential_backoff: allow progressive longer waits between pokes by using exponential backoff algorithm :type exponential_backoff: bool """ ui_color = '#e6f1f2' # type: str valid_modes = ['poke', 'reschedule'] # type: Iterable[str] @apply_defaults def __init__(self, poke_interval: float = 60, timeout: float = 60 * 60 * 24 * 7, soft_fail: bool = False, mode: str = 'poke', exponential_backoff: bool = False, *args, **kwargs) -> None: super().__init__(*args, **kwargs) self.poke_interval = poke_interval self.soft_fail = soft_fail self.timeout = timeout self.mode = mode self.exponential_backoff = exponential_backoff self._validate_input_values() def _validate_input_values(self) -> None: if not isinstance(self.poke_interval, (int, float)) or self.poke_interval < 0: raise AirflowException( "The poke_interval must be a non-negative number") if not isinstance(self.timeout, (int, float)) or self.timeout < 0: raise AirflowException( "The timeout must be a non-negative number") if self.mode not in self.valid_modes: raise AirflowException( "The mode must be one of {valid_modes}," "'{d}.{t}'; received '{m}'." .format(valid_modes=self.valid_modes, d=self.dag.dag_id if self.dag else "", t=self.task_id, m=self.mode)) def poke(self, context: Dict) -> bool: """ Function that the sensors defined while deriving this class should override. """ raise AirflowException('Override me.') def execute(self, context: Dict) -> Any: started_at = timezone.utcnow() try_number = 1 log_dag_id = self.dag.dag_id if self.has_dag() else "" if self.reschedule: # If reschedule, use first start date of current try task_reschedules = TaskReschedule.find_for_task_instance(context['ti']) if task_reschedules: started_at = task_reschedules[0].start_date try_number = len(task_reschedules) + 1 while not self.poke(context): if (timezone.utcnow() - started_at).total_seconds() > self.timeout: # If sensor is in soft fail mode but will be retried then # give it a chance and fail with timeout. # This gives the ability to set up non-blocking AND soft-fail sensors. if self.soft_fail and not context['ti'].is_eligible_to_retry(): self._do_skip_downstream_tasks(context) raise AirflowSkipException( f"Snap. Time is OUT. DAG id: {log_dag_id}") else: raise AirflowSensorTimeout( f"Snap. Time is OUT. DAG id: {log_dag_id}") if self.reschedule: reschedule_date = timezone.utcnow() + timedelta( seconds=self._get_next_poke_interval(started_at, try_number)) raise AirflowRescheduleException(reschedule_date) else: sleep(self._get_next_poke_interval(started_at, try_number)) try_number += 1 self.log.info("Success criteria met. Exiting.") def _do_skip_downstream_tasks(self, context: Dict) -> None: downstream_tasks = context['task'].get_flat_relatives(upstream=False) self.log.debug("Downstream task_ids %s", downstream_tasks) if downstream_tasks: self.skip(context['dag_run'], context['ti'].execution_date, downstream_tasks) def _get_next_poke_interval(self, started_at, try_number): """ Using the similar logic which is used for exponential backoff retry delay for operators. """ if self.exponential_backoff: min_backoff = int(self.poke_interval * (2 ** (try_number - 2))) current_time = timezone.utcnow() run_hash = int(hashlib.sha1("{}#{}#{}#{}".format( self.dag_id, self.task_id, started_at, try_number ).encode("utf-8")).hexdigest(), 16) modded_hash = min_backoff + run_hash % min_backoff delay_backoff_in_seconds = min( modded_hash, timedelta.max.total_seconds() - 1 ) new_interval = min(self.timeout - int((current_time - started_at).total_seconds()), delay_backoff_in_seconds) self.log.info("new %s interval is %s", self.mode, new_interval) return new_interval else: return self.poke_interval @property def reschedule(self): """Define mode rescheduled sensors.""" return self.mode == 'reschedule' # pylint: disable=no-member @property def deps(self): """ Adds one additional dependency for all sensor operators that checks if a sensor task instance can be rescheduled. """ if self.reschedule: return BaseOperator.deps.fget(self) | {ReadyToRescheduleDep()} return BaseOperator.deps.fget(self) def poke_mode_only(cls): """ Class Decorator for child classes of BaseSensorOperator to indicate that instances of this class are only safe to use poke mode. Will decorate all methods in the class to assert they did not change the mode from 'poke'. :param cls: BaseSensor class to enforce methods only use 'poke' mode. :type cls: type """ def decorate(cls_type): def mode_getter(_): return 'poke' def mode_setter(_, value): if value != 'poke': raise ValueError( f"cannot set mode to 'poke'.") if not issubclass(cls_type, BaseSensorOperator): raise ValueError(f"poke_mode_only decorator should only be " f"applied to subclasses of BaseSensorOperator," f" got:{cls_type}.") cls_type.mode = property(mode_getter, mode_setter) return cls_type return decorate(cls) if 'BUILDING_AIRFLOW_DOCS' in os.environ: # flake8: noqa: F811 # Monkey patch hook to get good function headers while building docs apply_defaults = lambda x: x
airflow/sensors/base_sensor_operator.py
9,231
Sensor operators are derived from this class and inherit these attributes. Sensor operators keep executing at a time interval and succeed when a criteria is met and fail if and when they time out. :param soft_fail: Set to true to mark the task as SKIPPED on failure :type soft_fail: bool :param poke_interval: Time in seconds that the job should wait in between each tries :type poke_interval: float :param timeout: Time, in seconds before the task times out and fails. :type timeout: float :param mode: How the sensor operates. Options are: ``{ poke | reschedule }``, default is ``poke``. When set to ``poke`` the sensor is taking up a worker slot for its whole execution time and sleeps between pokes. Use this mode if the expected runtime of the sensor is short or if a short poke interval is required. Note that the sensor will hold onto a worker slot and a pool slot for the duration of the sensor's runtime in this mode. When set to ``reschedule`` the sensor task frees the worker slot when the criteria is not yet met and it's rescheduled at a later time. Use this mode if the time before the criteria is met is expected to be quite long. The poke interval should be more than one minute to prevent too much load on the scheduler. :type mode: str :param exponential_backoff: allow progressive longer waits between pokes by using exponential backoff algorithm :type exponential_backoff: bool Using the similar logic which is used for exponential backoff retry delay for operators. Adds one additional dependency for all sensor operators that checks if a sensor task instance can be rescheduled. Function that the sensors defined while deriving this class should override. Class Decorator for child classes of BaseSensorOperator to indicate that instances of this class are only safe to use poke mode. Will decorate all methods in the class to assert they did not change the mode from 'poke'. :param cls: BaseSensor class to enforce methods only use 'poke' mode. :type cls: type Define mode rescheduled sensors. Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to you under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. type: str type: Iterable[str] If reschedule, use first start date of current try If sensor is in soft fail mode but will be retried then give it a chance and fail with timeout. This gives the ability to set up non-blocking AND soft-fail sensors. pylint: disable=no-member flake8: noqa: F811 Monkey patch hook to get good function headers while building docs
3,185
en
0.884103
import numpy as np import matplotlib.pyplot as plt import bisect from lmfit import Parameters import astropy.constants as cst from edibles.models import ContinuumModel, VoigtModel from edibles.utils.edibles_spectrum import EdiblesSpectrum class Sightline: '''A model of the sightline between the telescope and the target star. Args: Spectrum (EdiblesSpectrum): The input spectrum object n_anchors (int): Optional, The number of anchors in the ContinuumSpline ''' def __init__(self, Spectrum, init_cont=True, n_anchors=4): self.__dict__.update(Spectrum.__dict__) self.wave = Spectrum.wave self.flux = Spectrum.flux self.Spectrum = Spectrum if init_cont: cont_model = ContinuumModel(n_anchors=n_anchors) cont_pars = cont_model.guess(self.flux, x=self.wave) for yname in cont_model.ynames: flux_range = np.max(self.flux) - np.min(self.flux) ymin = cont_pars[yname].value - (flux_range / 2) ymax = cont_pars[yname].value + (flux_range / 2) cont_pars[yname].set(min=ymin, max=ymax) self.cont_model = cont_model self.cont_model_pars = cont_pars self.complete_model = cont_model self.all_pars = cont_pars self.peaks = [] self.n_anchors = n_anchors self.n_lines = 0 self.num_prior_lines = 0 self.source_names = [] self.add_source("Telluric", similar={'b': 2}) self.add_source("Nontelluric", similar=None) def add_source(self, name, similar=None): '''Adds a new source of absorption to the sightline. The purpose of a source is to hold multiple line models together, sometiimes with similar parameters Args: name (str): The name of the absorption source similar (dict): A dict of parameters that change with the source, not the specific line, default: None, example: similar={'b': 3} ''' self.source_names.append(name) if name == "Telluric" and similar is not None: par = Parameters() for key in similar: par.add(name + '_' + key, value=similar[key], min=0, max=30) self.telluric_pars = par self.all_pars = self.all_pars + par def add_line(self, name, source=None, pars=None, guess_data=None): '''Adds a new line to a given absorption source. If no source is given, a new one will be created. Args: name (str): The name of the line source (str): the name of the source this line will belong to pars (dict): user input parameters guess_data (1darray): flux data to guess with ''' assert source is not None, "Source must not be None" if source not in self.source_names: print() print('Could not find source \'{}\' in source_names.'.format(source)) print('Creating source \'{}\''.format(source)) self.add_source(source) new_line = VoigtModel(prefix=source + '_' + name + '_') if guess_data is not None: new_pars = new_line.guess(guess_data, x=self.wave) else: new_pars = new_line.guess(self.flux, x=self.wave) if pars is not None: for par in pars: # lam_0... par_name = source + '_' + name + '_' + par # telluric_line1_lam_0... new_pars[par_name].set(value=pars[par]) if source == "Telluric": b_name = source + '_b' new_pars[source + '_' + name + '_b'].set(expr=b_name) new_pars[source + '_' + name + '_lam_0'].set( min=self.Spectrum.xmin, max=self.Spectrum.xmax ) self.old_complete_model = self.complete_model self.complete_model = self.complete_model * new_line self.old_all_pars = self.all_pars self.all_pars = self.all_pars + new_pars self.old_cont_model = self.cont_model self.old_cont_pars = self.cont_model_pars if source == "Telluric": try: self.old_telluric_model = self.telluric_model self.telluric_model = self.telluric_model * new_line except AttributeError: self.old_telluric_model = new_line self.telluric_model = new_line try: self.old_telluric_pars = self.telluric_pars self.telluric_pars = self.telluric_pars + new_pars except AttributeError: print('Something bad is probably happening') self.old_telluric_pars = new_pars self.telluric_pars = new_pars else: try: self.old_nontelluric_model = self.nontelluric_model self.nontelluric_model = self.nontelluric_model * new_line except AttributeError: self.old_nontelluric_model = new_line self.nontelluric_model = new_line try: self.old_nontelluric_pars = self.nontelluric_pars self.nontelluric_pars = self.nontelluric_pars + new_pars except AttributeError: self.old_nontelluric_pars = new_pars self.nontelluric_pars = new_pars lambda_name = source + '_' + name + '_lam_0' index = bisect.bisect(self.peaks, new_pars[lambda_name]) self.peaks.insert(index, new_pars[lambda_name]) self.most_recent = source + '_' + name self.n_lines += 1 def fit(self, data=None, old=False, x=None, report=False, plot=False, weights=None, method='leastsq', **kwargs): '''Fits a model to the sightline data given by the EdiblesSpectrum object. Args: data (1darray): Flux data to fit params (lmfit.parameter.Parameters): Initial parameters to fit model (lmfit.model.CompositeModel): The model to fit, default: self.complete_model x (1darray): Wavelength data to fit report (bool): default False: If true, prints the report from the fit. plot (bool): default False: If true, plots the data and the fit model. method (str): The method of fitting. default: leastsq ''' if data is None: data = self.flux if x is None: x = self.wave if old is True: model = self.old_complete_model params = self.old_all_pars else: model = self.complete_model params = self.all_pars self.result = model.fit(data=data, params=params, x=x, weights=weights, method=method, **kwargs) if report: print(self.result.fit_report()) self.result.params.pretty_print() if plot: self.result.plot_fit() plt.show() # Update parameter values after fit - for use in model separation self.all_pars = self.result.params # create new parameters object and add to it from the results parameters if old is False: try: tell_pars = Parameters() for par_name in self.telluric_pars: tell_pars.add(self.all_pars[par_name]) # update attribute assert len(self.telluric_pars) == len(tell_pars) self.telluric_pars = tell_pars except AttributeError: pass try: non_tell_pars = Parameters() for par_name in self.nontelluric_pars: non_tell_pars.add(self.all_pars[par_name]) assert len(self.nontelluric_pars) == len(non_tell_pars) self.nontelluric_pars = non_tell_pars except AttributeError: pass try: cont_pars = Parameters() for par_name in self.cont_model_pars: cont_pars.add(self.all_pars[par_name]) assert len(self.cont_model_pars) == len(cont_pars) self.cont_model_pars = cont_pars except AttributeError: pass def freeze(self, pars=None, prefix=None, freeze_cont=True, unfreeze=False): '''Freezes the current params, so you can still add to the model but the 'old' parameters will not change Args: prefix (str): Prefix of parameters to freeze, default: None, example: 'Telluric' freeze_cont (bool): Freeze the continuum or not, default: True unfreeze (bool): unfreezes all parameters except x values of spline anchors, default=False ''' if pars is None: pars = self.all_pars if unfreeze is False: if prefix: for par in pars: if prefix in par: pars[par].set(vary=False) else: for par in pars: pars[par].set(vary=False) if not freeze_cont: for par in pars: if 'y_' in par: pars[par].set(vary=True) if unfreeze is True: for par in pars: if ('y_' in par): pars[par].set(vary=True) if ('Telluric' in par) and (par[-2:] != '_b'): pars[par].set(vary=True) pars['Telluric_b'].set(vary=True) if ('Nontelluric' in par) and (par[-2:] != '_d'): pars[par].set(vary=True) def separate(self, data, x, old=False, plot=True): '''Separate the sources that were added to Sightline. Args: data (1darray): FLux data to use for separation x (1darray): Wavelength array to use old (bool): If true, uses the older, second-most recent model and parameters plot (bool): If true, plots separted spectrum ''' assert len(self.telluric_pars) > 0 assert len(self.nontelluric_pars) > 0 if old is True: model = self.old_complete_model params = self.old_all_pars telluric_model = self.old_telluric_model telluric_params = self.old_telluric_pars nontelluric_model = self.old_nontelluric_model nontelluric_params = self.old_nontelluric_pars cont_model = self.old_cont_model cont_params = self.old_cont_pars else: model = self.complete_model params = self.all_pars telluric_model = self.telluric_model telluric_params = self.telluric_pars nontelluric_model = self.nontelluric_model nontelluric_params = self.nontelluric_pars cont_model = self.cont_model cont_params = self.cont_model_pars if len(self.source_names) == 2: complete_out = model.eval( data=data, params=params, x=x ) telluric_out = telluric_model.eval( data=data, params=telluric_params, x=x ) nontelluric_out = nontelluric_model.eval( data=data, params=nontelluric_params, x=x ) cont_out = cont_model.eval( data=data, params=cont_params, x=x ) if plot: plt.plot(x, data, label='Data', color='k') plt.plot(x, complete_out, label='Final model', color='r') plt.plot(x, data - complete_out, label='Residual', color='g') plt.plot(x, telluric_out * cont_out, label='Telluric model') plt.plot(x, nontelluric_out * cont_out, label='Non-telluric model') plt.xlabel(r'Wavelength ($\AA$)', fontsize=14) plt.ylabel('Flux', fontsize=14) plt.legend() plt.show() return complete_out, telluric_out, nontelluric_out, cont_out if __name__ == "__main__": FILE1 = "/HD170740/RED_860/HD170740_w860_redl_20140915_O12.fits" xmin = 7661.75 xmax = 7669 sp1 = EdiblesSpectrum(FILE1) sp1.getSpectrum(xmin=xmin, xmax=xmax) sightline = Sightline(sp1, n_anchors=5) # Add line with auto-guessed params sightline.add_line(name='line1', source='Telluric') # Add line with user defined params pars = {'d': 0.01, 'tau_0': 0.6, 'lam_0': 7664.8} sightline.add_line(name='line2', pars=pars, source='Telluric') # # ############################################################### # # Fit and plot sightline.fit(report=True, plot=False, method='leastsq') out = sightline.complete_model.eval(data=sp1.flux, params=sightline.result.params, x=sp1.wave) resid = sp1.flux - out # Add line with different source lam_0 = 7665.25 K_Gamma = 3.820e7 K_d = K_Gamma * lam_0**2 / (4 * np.pi * (cst.c.to("cm/s").value * 1e8)) pars = {'d': K_d, 'tau_0': 0.07, 'lam_0': lam_0} sightline.add_line(name='line3', source='Nontelluric', pars=pars) sightline.all_pars['Nontelluric_line3_d'].set(vary=False) # sightline.fit(report=True, plot=False, method='leastsq') # out = sightline.complete_model.eval(data=sp1.flux, params=sightline.result.params, x=sp1.wave) # resid = sp1.flux - out lam_0 = 7665.33 pars = {'d': K_d, 'tau_0': 0.01, 'b': 1, 'lam_0': lam_0} sightline.add_line(name='line4', source='Nontelluric', pars=pars) sightline.all_pars['Nontelluric_line4_d'].set(vary=False) # sightline.fit(report=True, plot=False, method='leastsq') lam_0 = 7665.15 pars = {'d': K_d, 'tau_0': 0.001, 'b': 1, 'lam_0': lam_0} sightline.add_line(name='line5', source='Nontelluric', pars=pars) sightline.all_pars['Nontelluric_line5_d'].set(vary=False) sightline.fit(report=True, plot=False, method='leastsq') pars = {'d': 0.01, 'tau_0': 0.01, 'b': 1, 'lam_0': 7662} sightline.add_line(name='line6', source='Telluric', pars=pars) sightline.fit(report=True, plot=False, method='leastsq') pars = {'d': 0.01, 'tau_0': 0.01, 'b': 1, 'lam_0': 7663.7} sightline.add_line(name='line7', source='Telluric', pars=pars) sightline.fit(report=True, plot=False, method='leastsq') pars = {'d': 0.01, 'tau_0': 0.01, 'b': 1, 'lam_0': 7666.5} sightline.add_line(name='line8', source='Telluric', pars=pars) sightline.fit(report=True, plot=False, method='leastsq') pars = {'d': 0.01, 'tau_0': 0.01, 'b': 1, 'lam_0': 7667.5} sightline.add_line(name='line9', source='Telluric', pars=pars) sightline.fit(report=True, plot=False, method='leastsq') out = sightline.complete_model.eval(data=sp1.interp_flux, params=sightline.result.params, x=sp1.grid) resid = sp1.interp_flux - out plt.plot(sp1.grid, sp1.interp_flux) plt.plot(sp1.grid, out) plt.plot(sp1.grid, resid) plt.show() sightline.separate(data=sp1.interp_flux, x=sp1.grid)
edibles/sightline.py
15,433
A model of the sightline between the telescope and the target star. Args: Spectrum (EdiblesSpectrum): The input spectrum object n_anchors (int): Optional, The number of anchors in the ContinuumSpline Adds a new line to a given absorption source. If no source is given, a new one will be created. Args: name (str): The name of the line source (str): the name of the source this line will belong to pars (dict): user input parameters guess_data (1darray): flux data to guess with Adds a new source of absorption to the sightline. The purpose of a source is to hold multiple line models together, sometiimes with similar parameters Args: name (str): The name of the absorption source similar (dict): A dict of parameters that change with the source, not the specific line, default: None, example: similar={'b': 3} Fits a model to the sightline data given by the EdiblesSpectrum object. Args: data (1darray): Flux data to fit params (lmfit.parameter.Parameters): Initial parameters to fit model (lmfit.model.CompositeModel): The model to fit, default: self.complete_model x (1darray): Wavelength data to fit report (bool): default False: If true, prints the report from the fit. plot (bool): default False: If true, plots the data and the fit model. method (str): The method of fitting. default: leastsq Freezes the current params, so you can still add to the model but the 'old' parameters will not change Args: prefix (str): Prefix of parameters to freeze, default: None, example: 'Telluric' freeze_cont (bool): Freeze the continuum or not, default: True unfreeze (bool): unfreezes all parameters except x values of spline anchors, default=False Separate the sources that were added to Sightline. Args: data (1darray): FLux data to use for separation x (1darray): Wavelength array to use old (bool): If true, uses the older, second-most recent model and parameters plot (bool): If true, plots separted spectrum lam_0... telluric_line1_lam_0... Update parameter values after fit - for use in model separation create new parameters object and add to it from the results parameters update attribute Add line with auto-guessed params Add line with user defined params Fit and plot Add line with different source sightline.fit(report=True, plot=False, method='leastsq') out = sightline.complete_model.eval(data=sp1.flux, params=sightline.result.params, x=sp1.wave) resid = sp1.flux - out sightline.fit(report=True, plot=False, method='leastsq')
2,561
en
0.579832
# _tmp_ import datetime from copy import deepcopy # _tmp_ from pymongo import MongoClient import pymongo import pandas as pd import numpy as np import sys pd.options.mode.chained_assignment = None class AnalyzerDatabaseManager(object): def __init__(self, db_config, config): self._db_config = db_config self._config = config def aggregate_data(self, model_type, agg_minutes=60, start_time=None, end_time=None, ids_to_exclude=[], metric=None, threshold=None): if model_type == "failed_request_ratio": return self._aggregate_data_for_failed_request_ratio_model(agg_minutes=agg_minutes, start_time=start_time, end_time=end_time, ids_to_exclude=ids_to_exclude) elif model_type == "duplicate_message_ids": return self._aggregate_data_for_duplicate_message_id_model(agg_minutes=agg_minutes, start_time=start_time, end_time=end_time, ids_to_exclude=ids_to_exclude) elif model_type == "time_sync_errors": return self._aggregate_data_for_time_sync_model(relevant_metric=metric, threshold=threshold, agg_minutes=agg_minutes, start_time=start_time, end_time=end_time, ids_to_exclude=ids_to_exclude) else: return None def aggregate_data_for_historic_averages_model(self, agg_minutes=60, start_time=None, end_time=None, ids_to_exclude=[], service_calls=None): # create connection clean_data = self._get_clean_data_collection() # nested fields need to be projected (select field from client if, exists, else from producer) project_dict = self._get_clean_data_projection_dict() # conditions to filter the data before processing filter_dict_elems = [{'succeeded': True, 'correctorStatus': 'done'}] if len(ids_to_exclude) > 0: id_exclude_query = {'_id': {'$nin': ids_to_exclude}} filter_dict_elems.append(id_exclude_query) if start_time is not None: start_time_query = {self._config.timestamp_field: {"$gte": start_time}} filter_dict_elems.append(start_time_query) if end_time is not None: end_time_query = {self._config.timestamp_field: {"$lt": end_time}} filter_dict_elems.append(end_time_query) if service_calls is not None and len(service_calls) > 0: for col in self._config.service_call_fields: service_calls.loc[service_calls[col] == "-", col] = None service_call_query = {"$or": service_calls.to_dict(orient="records")} filter_dict_elems.append(service_call_query) if len(filter_dict_elems) == 1: filter_dict = filter_dict_elems[0] elif len(filter_dict_elems) > 1: filter_dict = {"$and": filter_dict_elems} # set up elements to group by (service call fields and temporal aggregation window) group_dict = {col: "$%s" % col for col in self._config.service_call_fields} group_dict[self._config.timestamp_field] = { "$subtract": [ "$%s" % self._config.timestamp_field, {"$mod": ["$%s" % self._config.timestamp_field, 1000 * 60 * agg_minutes]} ]} res = clean_data.aggregate([ {'$project': project_dict}, {'$match': filter_dict}, {'$group': { "_id": group_dict, "request_count": {"$sum": 1}, "mean_request_size": {"$avg": "$requestSize"}, "mean_response_size": {"$avg": "$responseSize"}, "mean_client_duration": {"$avg": "$totalDuration"}, "mean_producer_duration": {"$avg": "$producerDurationProducerView"}, "request_ids": {"$push": "$_id"}}}], allowDiskUse=True, maxTimeMS=14400000) # _tmp_ print(datetime.datetime.now().strftime('%H:%M:%s') + " aggregate_data_for_historic_averages_model_start ") results = [] for item_tmp in res: # print(datetime.datetime.now().strftime('%H:%M:%s') + " aggregate_data_for_historic_averages_model " + str(item_tmp)) results.append(item_tmp) print(datetime.datetime.now().strftime('%H:%M:%s') + " aggregate_data_for_historic_averages_model_end ") # _tmp_ # return self._generate_dataframe(list(res)) return self._generate_dataframe(results) def add_first_request_timestamps_from_clean_data(self, data=None): # create connection clean_data = self._get_clean_data_collection() # nested fields need to be projected (select field from client if, exists, else from producer) project_dict = self._get_clean_data_projection_dict() # conditions to filter the data before processing filter_dict = {'correctorStatus': 'done'} if data is not None: for col in self._config.service_call_fields: data.loc[data[col] == "-", col] = None filter_dict["$or"] = data.to_dict(orient="records") # set up elements to group by (service call fields and temporal aggregation window) group_dict = {col: "$%s" % col for col in self._config.service_call_fields} res = clean_data.aggregate([ {'$project': project_dict}, {'$match': filter_dict}, {'$group': { "_id": group_dict, self._config.timestamp_field: {"$min": "$%s" % self._config.timestamp_field}}}], allowDiskUse=True, maxTimeMS=14400000) # _tmp_ results = [] print(datetime.datetime.now().strftime('%H:%M:%s') + " add_first_request_timestamps_from_clean_data_start ") for item_tmp in res: # print(datetime.datetime.now().strftime('%H:%M:%s') + " add_first_request_timestamps_from_clean_data " + str(item_tmp)) results.append(item_tmp) print(datetime.datetime.now().strftime('%H:%M:%s') + " add_first_request_timestamps_from_clean_data_end ") # _tmp_ # res = list(res) res = deepcopy(results) if len(res) == 0: return # res = self._generate_dataframe(list(res)) res = self._generate_dataframe(res) res = res.sort_values(self._config.timestamp_field, ascending=True).drop_duplicates(self._config.service_call_fields) # exclude service calls that already exist in the first timestamps table existing_first_timestamps = self.get_first_timestamps_for_service_calls() if len(existing_first_timestamps) > 0: res = res.merge(existing_first_timestamps[self._config.service_call_fields + ["first_request_timestamp"]], on=self._config.service_call_fields, how="left") res = res[pd.isnull(res.first_request_timestamp)].drop("first_request_timestamp", axis=1) res = res.rename(columns={self._config.timestamp_field: "first_request_timestamp"}) res.first_request_timestamp = pd.to_datetime(res.first_request_timestamp, unit='ms') res = res.assign(first_incident_timestamp=None) res = res.assign(first_model_retrain_timestamp=None) res = res.assign(first_model_train_timestamp=None) # add new service calls scft = self._get_service_call_first_timestamps_collection() if len(res) > 0: scft.insert_many(res.to_dict('records')) def update_first_timestamps(self, field, value, service_calls=None): scft = self._get_service_call_first_timestamps_collection() scft.update({"$or": service_calls.to_dict(orient="records")}, {"$set": {field: value}}, upsert=False, multi=True) def update_first_train_retrain_timestamps(self, sc_first_model, sc_second_model, current_time): if len(sc_first_model) > 0: self.update_first_timestamps(field="first_model_train_timestamp", value=current_time, service_calls=sc_first_model[self._config.service_call_fields]) if len(sc_second_model) > 0: self.update_first_timestamps(field="first_model_retrain_timestamp", value=current_time, service_calls=sc_second_model[self._config.service_call_fields]) def _aggregate_data_for_failed_request_ratio_model(self, agg_minutes=60, start_time=None, end_time=None, ids_to_exclude=[]): # create connection clean_data = self._get_clean_data_collection() # nested fields need to be projected (select field from client if, exists, else from producer) project_dict = self._get_clean_data_projection_dict() filter_dict_elems = [{'correctorStatus': 'done'}] # conditions to filter the data before processing if len(ids_to_exclude) > 0: id_exclude_query = {'_id': {'$nin': ids_to_exclude}} filter_dict_elems.append(id_exclude_query) if start_time is not None: start_time_query = {self._config.timestamp_field: {"$gte": start_time}} filter_dict_elems.append(start_time_query) if end_time is not None: end_time_query = {self._config.timestamp_field: {"$lt": end_time}} filter_dict_elems.append(end_time_query) if len(filter_dict_elems) == 1: filter_dict = filter_dict_elems[0] elif len(filter_dict_elems) > 1: filter_dict = {"$and": filter_dict_elems} else: filter_dict = {} # set up elements to group by (service call fields and temporal aggregation window) group_dict = {col: "$%s" % col for col in self._config.service_call_fields} group_dict[self._config.timestamp_field] = { "$subtract": [ "$%s" % self._config.timestamp_field, {"$mod": ["$%s" % self._config.timestamp_field, 1000 * 60 * agg_minutes]} ]} group_dict['succeeded'] = '$succeeded' res = clean_data.aggregate([ {'$project': project_dict}, {'$match': filter_dict}, {'$group': { "_id": group_dict, 'count': {'$sum': 1}, "request_ids": {"$push": "$_id"}}}], allowDiskUse=True, maxTimeMS=14400000) # _tmp_ print(datetime.datetime.now().strftime('%H:%M:%s') + " _aggregate_data_for_failed_request_ratio_model_start ") results = [] for item_tmp in res: # print(datetime.datetime.now().strftime('%H:%M:%s') + " _aggregate_data_for_failed_request_ratio_model " + str(item_tmp)) results.append(item_tmp) print(datetime.datetime.now().strftime('%H:%M:%s') + " _aggregate_data_for_failed_request_ratio_model_end ") # _tmp_ # return self._generate_dataframe(list(res)) return self._generate_dataframe(results) def _aggregate_data_for_duplicate_message_id_model(self, agg_minutes=60, start_time=None, end_time=None, ids_to_exclude=[]): # create connection clean_data = self._get_clean_data_collection() # nested fields need to be projected (select field from client if, exists, else from producer) project_dict = self._get_clean_data_projection_dict() # conditions to filter the data before processing filter_dict_elems = [{'succeeded': True, 'correctorStatus': 'done'}] if len(ids_to_exclude) > 0: id_exclude_query = {'_id': {'$nin': ids_to_exclude}} filter_dict_elems.append(id_exclude_query) if start_time is not None: start_time_query = {self._config.timestamp_field: {"$gte": start_time}} filter_dict_elems.append(start_time_query) if end_time is not None: end_time_query = {self._config.timestamp_field: {"$lt": end_time}} filter_dict_elems.append(end_time_query) if len(filter_dict_elems) == 1: filter_dict = filter_dict_elems[0] elif len(filter_dict_elems) > 1: filter_dict = {"$and": filter_dict_elems} # set up elements to group by (service call fields and temporal aggregation window) group_dict = {col: "$%s" % col for col in self._config.service_call_fields} group_dict[self._config.timestamp_field] = { "$subtract": [ "$%s" % self._config.timestamp_field, {"$mod": ["$%s" % self._config.timestamp_field, 1000 * 60 * agg_minutes]} ]} group_dict['messageId'] = '$messageId' res = clean_data.aggregate([ {'$project': project_dict}, {'$match': filter_dict}, {'$group': {"_id": group_dict, 'message_id_count': {'$sum': 1}, "request_ids": {"$push": "$_id"}}}, {'$match': {'message_id_count': {"$gt": 1}}}], allowDiskUse=True, maxTimeMS=14400000) # _tmp_ print(datetime.datetime.now().strftime('%H:%M:%s') + " _aggregate_data_for_duplicate_message_id_model_start ") results = [] for item_tmp in res: # print(datetime.datetime.now().strftime('%H:%M:%s') + " _aggregate_data_for_duplicate_message_id_model " + str(item_tmp)) results.append(item_tmp) print(datetime.datetime.now().strftime('%H:%M:%s') + " _aggregate_data_for_duplicate_message_id_model_end ") # _tmp_ # return self._generate_dataframe(list(res)) return self._generate_dataframe(results) def _aggregate_data_for_time_sync_model(self, relevant_metric, threshold, agg_minutes=60, start_time=None, end_time=None, ids_to_exclude=[]): # create connection clean_data = self._get_clean_data_collection() # nested fields need to be projected (select field from client if, exists, else from producer) project_dict = self._get_clean_data_projection_dict() # conditions to filter the data before processing filter_dict_elems = [{'succeeded': True, 'correctorStatus': 'done'}] if len(ids_to_exclude) > 0: id_exclude_query = {'_id': {'$nin': ids_to_exclude}} filter_dict_elems.append(id_exclude_query) if start_time is not None: start_time_query = {self._config.timestamp_field: {"$gte": start_time}} filter_dict_elems.append(start_time_query) if end_time is not None: end_time_query = {self._config.timestamp_field: {"$lt": end_time}} filter_dict_elems.append(end_time_query) if len(filter_dict_elems) == 1: filter_dict = filter_dict_elems[0] elif len(filter_dict_elems) > 1: filter_dict = {"$and": filter_dict_elems} # set up elements to group by (service call fields and temporal aggregation window) group_dict = {col: "$%s" % col for col in self._config.service_call_fields} group_dict[self._config.timestamp_field] = { "$subtract": [ "$%s" % self._config.timestamp_field, {"$mod": ["$%s" % self._config.timestamp_field, 1000 * 60 * agg_minutes]} ]} res = clean_data.aggregate([ {'$project': project_dict}, {'$match': filter_dict}, {'$group': {"_id": group_dict, 'request_count': {'$sum': 1}, "docs": {"$push": {relevant_metric: "$%s" % relevant_metric, "id": "$_id"}}}}, {"$unwind": "$docs"}, {'$match': {'docs.%s' % relevant_metric: {"$lt": threshold}}}, {'$group': {"_id": "$_id", 'erroneous_count': {'$sum': 1}, 'avg_erroneous_diff': {'$avg': '$docs.%s' % relevant_metric}, "request_count": {"$first": "$request_count"}, "request_ids": {"$push": "$docs.id"}}} ], allowDiskUse=True, maxTimeMS=14400000) # _tmp_ print(datetime.datetime.now().strftime('%H:%M:%s') + " _aggregate_data_for_time_sync_model_start ") results = [] for item_tmp in res: # print(datetime.datetime.now().strftime('%H:%M:%s') + " _aggregate_data_for_time_sync_model " + str(item_tmp)) results.append(item_tmp) print(datetime.datetime.now().strftime('%H:%M:%s') + " _aggregate_data_for_time_sync_model_end ") # _tmp_ # return self._generate_dataframe(list(res)) return self._generate_dataframe(results) def get_request_ids_from_incidents(self, incident_status=["new", "showed", "normal", "incident", "viewed"], relevant_anomalous_metrics=None, max_incident_creation_timestamp=None): filter_dict = {"incident_status": {"$in": incident_status}} if relevant_anomalous_metrics is not None: filter_dict["anomalous_metric"] = {"$in": relevant_anomalous_metrics} if max_incident_creation_timestamp is not None: filter_dict["incident_creation_timestamp"] = {"$lte": max_incident_creation_timestamp} incident_collection = self._get_incident_collection() # request_ids = incident_collection.distinct("request_ids", filter_dict) request_ids = [doc['_id'] for doc in incident_collection.aggregate([{'$match': filter_dict}, {'$group': {'_id': '$request_ids'}}], allowDiskUse=True)] return request_ids def delete_incidents(self, field=None, value=None): incident_collection = self._get_incident_collection() if field is None or value is None: incident_collection.delete_many({}) else: incident_collection.delete_many({field: value}) def insert_incidents(self, dt_incidents): incident_collection = self._get_incident_collection() incident_collection.insert_many(dt_incidents.to_dict('records')) def get_timestamp(self, ts_type, model_type): ts_collection = self._get_incident_timestamp_collection() ts = ts_collection.find_one({"type": ts_type, "model": model_type}) if ts: return ts["timestamp"] return ts def load_model(self, model_name, version=None): incident_model_collection = self._get_incident_model_collection() filter_dict = {"model_name": model_name} if version is not None: filter_dict["version"] = version result = incident_model_collection.find(filter_dict) # _tmp_ print(datetime.datetime.now().strftime('%H:%M:%s') + " load_model_start ") results = [] for item_tmp in result: # print(datetime.datetime.now().strftime('%H:%M:%s') + " load_model " + str(item_tmp)) results.append(item_tmp) print(datetime.datetime.now().strftime('%H:%M:%s') + " load_model_end ") # _tmp_ # return pd.DataFrame(list(result)).drop("_id", axis=1) return pd.DataFrame(results).drop("_id", axis=1) def save_model(self, df, delete_old_version=True): incident_model_collection = self._get_incident_model_collection() df = df.to_dict('records') if delete_old_version and len(df) > 0: model_name = df[0]["model_name"] incident_model_collection.delete_many({"model_name": model_name}) incident_model_collection.insert_many(df) def set_timestamp(self, ts_type, model_type, value): ts_collection = self._get_incident_timestamp_collection() ts_collection.update({"type": ts_type, "model": model_type}, {"type": ts_type, "model": model_type, "timestamp": value}, upsert=True) def get_first_timestamps_for_service_calls(self): scft = self._get_service_call_first_timestamps_collection() # results = list(scft.find()) # _tmp_ print(datetime.datetime.now().strftime('%H:%M:%s') + " get_first_timestamps_for_service_calls_start1 ") results = [] results_tmp = scft.find() print(datetime.datetime.now().strftime('%H:%M:%s') + " get_first_timestamps_for_service_calls_start2 ") for item_tmp in results_tmp: # print(datetime.datetime.now().strftime('%H:%M:%s') + " get_first_timestamps_for_service_calls " + str(item_tmp)) results.append(item_tmp) print(datetime.datetime.now().strftime('%H:%M:%s') + " get_first_timestamps_for_service_calls_end ") # _tmp_ if len(results) == 0: return pd.DataFrame() data = pd.DataFrame(results).drop("_id", axis=1) for col in ["first_request_timestamp", "first_model_train_timestamp", "first_incident_timestamp", "first_model_retrain_timestamp"]: data.loc[:, col] = pd.to_datetime(data.loc[:, col]) return data def get_service_calls_for_train_stages(self, time_first_model, time_second_model): first_timestamps = self.get_first_timestamps_for_service_calls() if len(first_timestamps) == 0: return pd.DataFrame(), pd.DataFrame(), pd.DataFrame() first_model_to_be_trained = first_timestamps[(pd.isnull(first_timestamps.first_model_train_timestamp)) & (first_timestamps.first_request_timestamp <= time_first_model)] model_to_be_retrained = first_timestamps[(pd.isnull(first_timestamps.first_model_retrain_timestamp)) & (first_timestamps.first_incident_timestamp <= time_second_model)] first_timestamps = first_timestamps[~pd.isnull(first_timestamps.first_model_retrain_timestamp)] return first_timestamps, first_model_to_be_trained, model_to_be_retrained def get_service_calls_for_transform_stages(self): first_timestamps = self.get_first_timestamps_for_service_calls() first_incidents_to_be_reported = first_timestamps[(pd.isnull(first_timestamps.first_incident_timestamp)) & (~pd.isnull(first_timestamps.first_model_train_timestamp))] regular_service_calls = first_timestamps[~pd.isnull(first_timestamps.first_incident_timestamp)] return regular_service_calls, first_incidents_to_be_reported def get_data_for_train_stages(self, sc_regular, sc_first_model, sc_second_model, relevant_anomalous_metrics, max_incident_creation_timestamp, last_fit_timestamp, agg_minutes, max_request_timestamp): # exclude requests that are part of a "true" incident ids_to_exclude = self.get_request_ids_from_incidents( incident_status=["incident"], relevant_anomalous_metrics=relevant_anomalous_metrics, max_incident_creation_timestamp=max_incident_creation_timestamp) # make the timestamps correspond to the millisecond format if max_request_timestamp is not None: max_request_timestamp = max_request_timestamp.timestamp() * 1000 if last_fit_timestamp is not None: last_fit_timestamp = last_fit_timestamp.timestamp() * 1000 data_regular = pd.DataFrame() data_first_train = pd.DataFrame() data_first_retrain = pd.DataFrame() # for the first-time training, don't exclude anything if len(sc_first_model) > 0: if len(sc_first_model) > 100: data_first_train = self.aggregate_data_for_historic_averages_model(agg_minutes=agg_minutes, end_time=max_request_timestamp) if len(data_first_train) > 0: data_first_train = data_first_train.merge(sc_first_model[self._config.service_call_fields]) else: data_first_train = self.aggregate_data_for_historic_averages_model( agg_minutes=agg_minutes, end_time=max_request_timestamp, service_calls=sc_first_model[self._config.service_call_fields]) # for the second model, exclude queries that were marked as "incident" after the first training, # but don't limit the start time if len(sc_second_model) > 0: if len(sc_second_model) > 100: data_first_retrain = self.aggregate_data_for_historic_averages_model(agg_minutes=agg_minutes, end_time=max_request_timestamp, ids_to_exclude=ids_to_exclude) if len(data_first_retrain) > 0: data_first_retrain = data_first_retrain.merge(sc_second_model[self._config.service_call_fields]) else: data_first_retrain = self.aggregate_data_for_historic_averages_model( agg_minutes=agg_minutes, service_calls=sc_second_model[self._config.service_call_fields], end_time=max_request_timestamp, ids_to_exclude=ids_to_exclude) # for regular training, exclude the incidents and limit the start time if len(sc_regular) > 0: data_regular = self.aggregate_data_for_historic_averages_model( agg_minutes=agg_minutes, start_time=last_fit_timestamp, end_time=max_request_timestamp, ids_to_exclude=ids_to_exclude) if len(data_regular) > 0: data_regular = data_regular.merge(sc_regular[self._config.service_call_fields]) return data_regular, data_first_train, data_first_retrain def get_data_for_transform_stages(self, agg_minutes, last_transform_timestamp, current_transform_timestamp, sc_regular, sc_first_incidents): data_regular = pd.DataFrame() data_first_incidents = pd.DataFrame() # retrieve all data that have appeared after the last transform time data = self.aggregate_data_for_historic_averages_model(agg_minutes=agg_minutes, start_time=last_transform_timestamp, end_time=current_transform_timestamp) if len(data) > 0: # exclude service calls that are not past the training period data_regular = data.merge(sc_regular[self._config.service_call_fields]) if len(sc_first_incidents) > 100: # for first-time incdent reporting, retrieve all data for these service calls data_first_incidents = self.aggregate_data_for_historic_averages_model(agg_minutes=agg_minutes, end_time=current_transform_timestamp) if len(data_first_incidents) > 0: data_first_incidents = data_first_incidents.merge(sc_first_incidents[self._config.service_call_fields]) elif len(sc_first_incidents) > 0: data_first_incidents = self.aggregate_data_for_historic_averages_model( agg_minutes=agg_minutes, end_time=current_transform_timestamp, service_calls=sc_first_incidents[self._config.service_call_fields]) return pd.concat([data_regular, data_first_incidents]) def _get_incident_collection(self): db_client = MongoClient(self._db_config.MONGODB_URI) db = db_client[self._db_config.MONGODB_AD] return db.incident def _get_incident_model_collection(self): db_client = MongoClient(self._db_config.MONGODB_URI) db = db_client[self._db_config.MONGODB_AD] return db.incident_model def _get_incident_timestamp_collection(self): db_client = MongoClient(self._db_config.MONGODB_URI) db = db_client[self._db_config.MONGODB_AD] return db.incident_timestamps def _get_service_call_first_timestamps_collection(self): db_client = MongoClient(self._db_config.MONGODB_URI) db = db_client[self._db_config.MONGODB_AD] return db.service_call_first_timestamps def _get_clean_data_collection(self): db_client = MongoClient(self._db_config.MONGODB_URI) db = db_client[self._db_config.MONGODB_QD] return db.clean_data def _get_clean_data_projection_dict(self): project_dict = {col: {"$ifNull": ["$client.%s" % col, "$producer.%s" % col]} for col in self._config.relevant_cols_nested} for col, field1, field2 in self._config.relevant_cols_general_alternative: project_dict[col] = {"$ifNull": ["$%s" % field1, "$%s" % field2]} for col in self._config.relevant_cols_general: project_dict[col] = "$%s" % col return project_dict def _generate_dataframe(self, result): data = pd.DataFrame(result) if len(data) > 0: data = pd.concat([data, pd.DataFrame(list(data["_id"]))], axis=1) data = data.drop(["_id"], axis=1) data.loc[:, self._config.timestamp_field] = pd.to_datetime(data.loc[:, self._config.timestamp_field], unit='ms') for col in self._config.service_call_fields: data.loc[:, col] = data.loc[:, col].fillna("-") return data
analysis_module/analyzer/AnalyzerDatabaseManager_tmp.py
29,763
_tmp_ _tmp_ create connection nested fields need to be projected (select field from client if, exists, else from producer) conditions to filter the data before processing set up elements to group by (service call fields and temporal aggregation window) _tmp_ print(datetime.datetime.now().strftime('%H:%M:%s') + " aggregate_data_for_historic_averages_model " + str(item_tmp)) _tmp_ return self._generate_dataframe(list(res)) create connection nested fields need to be projected (select field from client if, exists, else from producer) conditions to filter the data before processing set up elements to group by (service call fields and temporal aggregation window) _tmp_ print(datetime.datetime.now().strftime('%H:%M:%s') + " add_first_request_timestamps_from_clean_data " + str(item_tmp)) _tmp_ res = list(res) res = self._generate_dataframe(list(res)) exclude service calls that already exist in the first timestamps table add new service calls create connection nested fields need to be projected (select field from client if, exists, else from producer) conditions to filter the data before processing set up elements to group by (service call fields and temporal aggregation window) _tmp_ print(datetime.datetime.now().strftime('%H:%M:%s') + " _aggregate_data_for_failed_request_ratio_model " + str(item_tmp)) _tmp_ return self._generate_dataframe(list(res)) create connection nested fields need to be projected (select field from client if, exists, else from producer) conditions to filter the data before processing set up elements to group by (service call fields and temporal aggregation window) _tmp_ print(datetime.datetime.now().strftime('%H:%M:%s') + " _aggregate_data_for_duplicate_message_id_model " + str(item_tmp)) _tmp_ return self._generate_dataframe(list(res)) create connection nested fields need to be projected (select field from client if, exists, else from producer) conditions to filter the data before processing set up elements to group by (service call fields and temporal aggregation window) _tmp_ print(datetime.datetime.now().strftime('%H:%M:%s') + " _aggregate_data_for_time_sync_model " + str(item_tmp)) _tmp_ return self._generate_dataframe(list(res)) request_ids = incident_collection.distinct("request_ids", filter_dict) _tmp_ print(datetime.datetime.now().strftime('%H:%M:%s') + " load_model " + str(item_tmp)) _tmp_ return pd.DataFrame(list(result)).drop("_id", axis=1) results = list(scft.find()) _tmp_ print(datetime.datetime.now().strftime('%H:%M:%s') + " get_first_timestamps_for_service_calls " + str(item_tmp)) _tmp_ exclude requests that are part of a "true" incident make the timestamps correspond to the millisecond format for the first-time training, don't exclude anything for the second model, exclude queries that were marked as "incident" after the first training, but don't limit the start time for regular training, exclude the incidents and limit the start time retrieve all data that have appeared after the last transform time exclude service calls that are not past the training period for first-time incdent reporting, retrieve all data for these service calls
3,126
en
0.691746
import asyncio from typing import List import pytest from hddcoin.consensus.block_rewards import calculate_base_farmer_reward, calculate_pool_reward from hddcoin.full_node.mempool_manager import MempoolManager from hddcoin.simulator.simulator_protocol import FarmNewBlockProtocol from hddcoin.types.blockchain_format.coin import Coin from hddcoin.types.blockchain_format.sized_bytes import bytes32 from hddcoin.types.peer_info import PeerInfo from hddcoin.util.ints import uint16, uint32, uint64 from hddcoin.wallet.cc_wallet.cc_utils import cc_puzzle_hash_for_inner_puzzle_hash from hddcoin.wallet.cc_wallet.cc_wallet import CCWallet from hddcoin.wallet.puzzles.cc_loader import CC_MOD from hddcoin.wallet.transaction_record import TransactionRecord from hddcoin.wallet.wallet_coin_record import WalletCoinRecord from tests.setup_nodes import setup_simulators_and_wallets from tests.time_out_assert import time_out_assert @pytest.fixture(scope="module") def event_loop(): loop = asyncio.get_event_loop() yield loop async def tx_in_pool(mempool: MempoolManager, tx_id: bytes32): tx = mempool.get_spendbundle(tx_id) if tx is None: return False return True class TestCCWallet: @pytest.fixture(scope="function") async def wallet_node(self): async for _ in setup_simulators_and_wallets(1, 1, {}): yield _ @pytest.fixture(scope="function") async def two_wallet_nodes(self): async for _ in setup_simulators_and_wallets(1, 2, {}): yield _ @pytest.fixture(scope="function") async def three_wallet_nodes(self): async for _ in setup_simulators_and_wallets(1, 3, {}): yield _ @pytest.mark.asyncio async def test_colour_creation(self, two_wallet_nodes): num_blocks = 3 full_nodes, wallets = two_wallet_nodes full_node_api = full_nodes[0] full_node_server = full_node_api.server wallet_node, server_2 = wallets[0] wallet = wallet_node.wallet_state_manager.main_wallet ph = await wallet.get_new_puzzlehash() await server_2.start_client(PeerInfo("localhost", uint16(full_node_server._port)), None) for i in range(1, num_blocks): await full_node_api.farm_new_transaction_block(FarmNewBlockProtocol(ph)) funds = sum( [ calculate_pool_reward(uint32(i)) + calculate_base_farmer_reward(uint32(i)) for i in range(1, num_blocks - 1) ] ) await time_out_assert(15, wallet.get_confirmed_balance, funds) cc_wallet: CCWallet = await CCWallet.create_new_cc(wallet_node.wallet_state_manager, wallet, uint64(100)) tx_queue: List[TransactionRecord] = await wallet_node.wallet_state_manager.tx_store.get_not_sent() tx_record = tx_queue[0] await time_out_assert( 15, tx_in_pool, True, full_node_api.full_node.mempool_manager, tx_record.spend_bundle.name() ) for i in range(1, num_blocks): await full_node_api.farm_new_transaction_block(FarmNewBlockProtocol(32 * b"0")) await time_out_assert(15, cc_wallet.get_confirmed_balance, 100) await time_out_assert(15, cc_wallet.get_unconfirmed_balance, 100) @pytest.mark.asyncio async def test_cc_spend(self, two_wallet_nodes): num_blocks = 3 full_nodes, wallets = two_wallet_nodes full_node_api = full_nodes[0] full_node_server = full_node_api.server wallet_node, server_2 = wallets[0] wallet_node_2, server_3 = wallets[1] wallet = wallet_node.wallet_state_manager.main_wallet wallet2 = wallet_node_2.wallet_state_manager.main_wallet ph = await wallet.get_new_puzzlehash() await server_2.start_client(PeerInfo("localhost", uint16(full_node_server._port)), None) await server_3.start_client(PeerInfo("localhost", uint16(full_node_server._port)), None) for i in range(1, num_blocks): await full_node_api.farm_new_transaction_block(FarmNewBlockProtocol(ph)) funds = sum( [ calculate_pool_reward(uint32(i)) + calculate_base_farmer_reward(uint32(i)) for i in range(1, num_blocks - 1) ] ) await time_out_assert(15, wallet.get_confirmed_balance, funds) cc_wallet: CCWallet = await CCWallet.create_new_cc(wallet_node.wallet_state_manager, wallet, uint64(100)) tx_queue: List[TransactionRecord] = await wallet_node.wallet_state_manager.tx_store.get_not_sent() tx_record = tx_queue[0] await time_out_assert( 15, tx_in_pool, True, full_node_api.full_node.mempool_manager, tx_record.spend_bundle.name() ) for i in range(1, num_blocks): await full_node_api.farm_new_transaction_block(FarmNewBlockProtocol(32 * b"0")) await time_out_assert(15, cc_wallet.get_confirmed_balance, 100) await time_out_assert(15, cc_wallet.get_unconfirmed_balance, 100) assert cc_wallet.cc_info.my_genesis_checker is not None colour = cc_wallet.get_colour() cc_wallet_2: CCWallet = await CCWallet.create_wallet_for_cc(wallet_node_2.wallet_state_manager, wallet2, colour) assert cc_wallet.cc_info.my_genesis_checker == cc_wallet_2.cc_info.my_genesis_checker cc_2_hash = await cc_wallet_2.get_new_inner_hash() tx_record = await cc_wallet.generate_signed_transaction([uint64(60)], [cc_2_hash]) await wallet.wallet_state_manager.add_pending_transaction(tx_record) await time_out_assert( 15, tx_in_pool, True, full_node_api.full_node.mempool_manager, tx_record.spend_bundle.name() ) for i in range(1, num_blocks): await full_node_api.farm_new_transaction_block(FarmNewBlockProtocol(ph)) await time_out_assert(15, cc_wallet.get_confirmed_balance, 40) await time_out_assert(15, cc_wallet.get_unconfirmed_balance, 40) await time_out_assert(30, cc_wallet_2.get_confirmed_balance, 60) await time_out_assert(30, cc_wallet_2.get_unconfirmed_balance, 60) cc_hash = await cc_wallet.get_new_inner_hash() tx_record = await cc_wallet_2.generate_signed_transaction([uint64(15)], [cc_hash]) await wallet.wallet_state_manager.add_pending_transaction(tx_record) await time_out_assert( 15, tx_in_pool, True, full_node_api.full_node.mempool_manager, tx_record.spend_bundle.name() ) for i in range(1, num_blocks): await full_node_api.farm_new_transaction_block(FarmNewBlockProtocol(ph)) await time_out_assert(15, cc_wallet.get_confirmed_balance, 55) await time_out_assert(15, cc_wallet.get_unconfirmed_balance, 55) @pytest.mark.asyncio async def test_get_wallet_for_colour(self, two_wallet_nodes): num_blocks = 3 full_nodes, wallets = two_wallet_nodes full_node_api = full_nodes[0] full_node_server = full_node_api.server wallet_node, server_2 = wallets[0] wallet = wallet_node.wallet_state_manager.main_wallet ph = await wallet.get_new_puzzlehash() await server_2.start_client(PeerInfo("localhost", uint16(full_node_server._port)), None) for i in range(1, num_blocks): await full_node_api.farm_new_transaction_block(FarmNewBlockProtocol(ph)) funds = sum( [ calculate_pool_reward(uint32(i)) + calculate_base_farmer_reward(uint32(i)) for i in range(1, num_blocks - 1) ] ) await time_out_assert(15, wallet.get_confirmed_balance, funds) cc_wallet: CCWallet = await CCWallet.create_new_cc(wallet_node.wallet_state_manager, wallet, uint64(100)) for i in range(1, num_blocks): await full_node_api.farm_new_transaction_block(FarmNewBlockProtocol(32 * b"0")) colour = cc_wallet.get_colour() assert await wallet_node.wallet_state_manager.get_wallet_for_colour(colour) == cc_wallet @pytest.mark.asyncio async def test_generate_zero_val(self, two_wallet_nodes): num_blocks = 4 full_nodes, wallets = two_wallet_nodes full_node_api = full_nodes[0] full_node_server = full_node_api.server wallet_node, server_2 = wallets[0] wallet_node_2, server_3 = wallets[1] wallet = wallet_node.wallet_state_manager.main_wallet wallet2 = wallet_node_2.wallet_state_manager.main_wallet ph = await wallet.get_new_puzzlehash() await server_2.start_client(PeerInfo("localhost", uint16(full_node_server._port)), None) await server_3.start_client(PeerInfo("localhost", uint16(full_node_server._port)), None) for i in range(1, num_blocks): await full_node_api.farm_new_transaction_block(FarmNewBlockProtocol(ph)) funds = sum( [ calculate_pool_reward(uint32(i)) + calculate_base_farmer_reward(uint32(i)) for i in range(1, num_blocks - 1) ] ) await time_out_assert(15, wallet.get_confirmed_balance, funds) cc_wallet: CCWallet = await CCWallet.create_new_cc(wallet_node.wallet_state_manager, wallet, uint64(100)) await asyncio.sleep(1) ph = await wallet2.get_new_puzzlehash() for i in range(1, num_blocks): await full_node_api.farm_new_transaction_block(FarmNewBlockProtocol(ph)) await time_out_assert(15, cc_wallet.get_confirmed_balance, 100) await time_out_assert(15, cc_wallet.get_unconfirmed_balance, 100) assert cc_wallet.cc_info.my_genesis_checker is not None colour = cc_wallet.get_colour() cc_wallet_2: CCWallet = await CCWallet.create_wallet_for_cc(wallet_node_2.wallet_state_manager, wallet2, colour) await asyncio.sleep(1) assert cc_wallet.cc_info.my_genesis_checker == cc_wallet_2.cc_info.my_genesis_checker spend_bundle = await cc_wallet_2.generate_zero_val_coin() await asyncio.sleep(1) await time_out_assert(15, tx_in_pool, True, full_node_api.full_node.mempool_manager, spend_bundle.name()) for i in range(1, num_blocks): await full_node_api.farm_new_transaction_block(FarmNewBlockProtocol(ph)) async def unspent_count(): unspent: List[WalletCoinRecord] = list( await cc_wallet_2.wallet_state_manager.get_spendable_coins_for_wallet(cc_wallet_2.id()) ) return len(unspent) await time_out_assert(15, unspent_count, 1) unspent: List[WalletCoinRecord] = list( await cc_wallet_2.wallet_state_manager.get_spendable_coins_for_wallet(cc_wallet_2.id()) ) assert unspent.pop().coin.amount == 0 @pytest.mark.asyncio async def test_cc_spend_uncoloured(self, two_wallet_nodes): num_blocks = 3 full_nodes, wallets = two_wallet_nodes full_node_api = full_nodes[0] full_node_server = full_node_api.server wallet_node, server_2 = wallets[0] wallet_node_2, server_3 = wallets[1] wallet = wallet_node.wallet_state_manager.main_wallet wallet2 = wallet_node_2.wallet_state_manager.main_wallet ph = await wallet.get_new_puzzlehash() await server_2.start_client(PeerInfo("localhost", uint16(full_node_server._port)), None) await server_3.start_client(PeerInfo("localhost", uint16(full_node_server._port)), None) for i in range(1, num_blocks): await full_node_api.farm_new_transaction_block(FarmNewBlockProtocol(ph)) funds = sum( [ calculate_pool_reward(uint32(i)) + calculate_base_farmer_reward(uint32(i)) for i in range(1, num_blocks - 1) ] ) await time_out_assert(15, wallet.get_confirmed_balance, funds) cc_wallet: CCWallet = await CCWallet.create_new_cc(wallet_node.wallet_state_manager, wallet, uint64(100)) tx_queue: List[TransactionRecord] = await wallet_node.wallet_state_manager.tx_store.get_not_sent() tx_record = tx_queue[0] await time_out_assert( 15, tx_in_pool, True, full_node_api.full_node.mempool_manager, tx_record.spend_bundle.name() ) for i in range(1, num_blocks): await full_node_api.farm_new_transaction_block(FarmNewBlockProtocol(32 * b"0")) await time_out_assert(15, cc_wallet.get_confirmed_balance, 100) await time_out_assert(15, cc_wallet.get_unconfirmed_balance, 100) assert cc_wallet.cc_info.my_genesis_checker is not None colour = cc_wallet.get_colour() cc_wallet_2: CCWallet = await CCWallet.create_wallet_for_cc(wallet_node_2.wallet_state_manager, wallet2, colour) assert cc_wallet.cc_info.my_genesis_checker == cc_wallet_2.cc_info.my_genesis_checker cc_2_hash = await cc_wallet_2.get_new_inner_hash() tx_record = await cc_wallet.generate_signed_transaction([uint64(60)], [cc_2_hash]) await wallet.wallet_state_manager.add_pending_transaction(tx_record) await time_out_assert( 15, tx_in_pool, True, full_node_api.full_node.mempool_manager, tx_record.spend_bundle.name() ) for i in range(1, num_blocks): await full_node_api.farm_new_transaction_block(FarmNewBlockProtocol(32 * b"0")) await time_out_assert(15, cc_wallet.get_confirmed_balance, 40) await time_out_assert(15, cc_wallet.get_unconfirmed_balance, 40) await time_out_assert(15, cc_wallet_2.get_confirmed_balance, 60) await time_out_assert(15, cc_wallet_2.get_unconfirmed_balance, 60) cc2_ph = await cc_wallet_2.get_new_cc_puzzle_hash() tx_record = await wallet.wallet_state_manager.main_wallet.generate_signed_transaction(10, cc2_ph, 0) await wallet.wallet_state_manager.add_pending_transaction(tx_record) await time_out_assert( 15, tx_in_pool, True, full_node_api.full_node.mempool_manager, tx_record.spend_bundle.name() ) for i in range(0, num_blocks): await full_node_api.farm_new_transaction_block(FarmNewBlockProtocol(32 * b"0")) id = cc_wallet_2.id() wsm = cc_wallet_2.wallet_state_manager await time_out_assert(15, wsm.get_confirmed_balance_for_wallet, 70, id) await time_out_assert(15, cc_wallet_2.get_confirmed_balance, 60) await time_out_assert(15, cc_wallet_2.get_unconfirmed_balance, 60) @pytest.mark.asyncio async def test_cc_spend_multiple(self, three_wallet_nodes): num_blocks = 3 full_nodes, wallets = three_wallet_nodes full_node_api = full_nodes[0] full_node_server = full_node_api.server wallet_node_0, wallet_server_0 = wallets[0] wallet_node_1, wallet_server_1 = wallets[1] wallet_node_2, wallet_server_2 = wallets[2] wallet_0 = wallet_node_0.wallet_state_manager.main_wallet wallet_1 = wallet_node_1.wallet_state_manager.main_wallet wallet_2 = wallet_node_2.wallet_state_manager.main_wallet ph = await wallet_0.get_new_puzzlehash() await wallet_server_0.start_client(PeerInfo("localhost", uint16(full_node_server._port)), None) await wallet_server_1.start_client(PeerInfo("localhost", uint16(full_node_server._port)), None) await wallet_server_2.start_client(PeerInfo("localhost", uint16(full_node_server._port)), None) for i in range(1, num_blocks): await full_node_api.farm_new_transaction_block(FarmNewBlockProtocol(ph)) funds = sum( [ calculate_pool_reward(uint32(i)) + calculate_base_farmer_reward(uint32(i)) for i in range(1, num_blocks - 1) ] ) await time_out_assert(15, wallet_0.get_confirmed_balance, funds) cc_wallet_0: CCWallet = await CCWallet.create_new_cc(wallet_node_0.wallet_state_manager, wallet_0, uint64(100)) tx_queue: List[TransactionRecord] = await wallet_node_0.wallet_state_manager.tx_store.get_not_sent() tx_record = tx_queue[0] await time_out_assert( 15, tx_in_pool, True, full_node_api.full_node.mempool_manager, tx_record.spend_bundle.name() ) for i in range(1, num_blocks): await full_node_api.farm_new_transaction_block(FarmNewBlockProtocol(32 * b"0")) await time_out_assert(15, cc_wallet_0.get_confirmed_balance, 100) await time_out_assert(15, cc_wallet_0.get_unconfirmed_balance, 100) assert cc_wallet_0.cc_info.my_genesis_checker is not None colour = cc_wallet_0.get_colour() cc_wallet_1: CCWallet = await CCWallet.create_wallet_for_cc( wallet_node_1.wallet_state_manager, wallet_1, colour ) cc_wallet_2: CCWallet = await CCWallet.create_wallet_for_cc( wallet_node_2.wallet_state_manager, wallet_2, colour ) assert cc_wallet_0.cc_info.my_genesis_checker == cc_wallet_1.cc_info.my_genesis_checker assert cc_wallet_0.cc_info.my_genesis_checker == cc_wallet_2.cc_info.my_genesis_checker cc_1_hash = await cc_wallet_1.get_new_inner_hash() cc_2_hash = await cc_wallet_2.get_new_inner_hash() tx_record = await cc_wallet_0.generate_signed_transaction([uint64(60), uint64(20)], [cc_1_hash, cc_2_hash]) await wallet_0.wallet_state_manager.add_pending_transaction(tx_record) await time_out_assert( 15, tx_in_pool, True, full_node_api.full_node.mempool_manager, tx_record.spend_bundle.name() ) for i in range(1, num_blocks): await full_node_api.farm_new_transaction_block(FarmNewBlockProtocol(32 * b"0")) await time_out_assert(15, cc_wallet_0.get_confirmed_balance, 20) await time_out_assert(15, cc_wallet_0.get_unconfirmed_balance, 20) await time_out_assert(30, cc_wallet_1.get_confirmed_balance, 60) await time_out_assert(30, cc_wallet_1.get_unconfirmed_balance, 60) await time_out_assert(30, cc_wallet_2.get_confirmed_balance, 20) await time_out_assert(30, cc_wallet_2.get_unconfirmed_balance, 20) cc_hash = await cc_wallet_0.get_new_inner_hash() tx_record = await cc_wallet_1.generate_signed_transaction([uint64(15)], [cc_hash]) await wallet_1.wallet_state_manager.add_pending_transaction(tx_record) tx_record_2 = await cc_wallet_2.generate_signed_transaction([uint64(20)], [cc_hash]) await wallet_2.wallet_state_manager.add_pending_transaction(tx_record_2) await time_out_assert( 15, tx_in_pool, True, full_node_api.full_node.mempool_manager, tx_record.spend_bundle.name() ) await time_out_assert( 15, tx_in_pool, True, full_node_api.full_node.mempool_manager, tx_record_2.spend_bundle.name() ) for i in range(1, num_blocks): await full_node_api.farm_new_transaction_block(FarmNewBlockProtocol(32 * b"0")) await time_out_assert(15, cc_wallet_0.get_confirmed_balance, 55) await time_out_assert(15, cc_wallet_0.get_unconfirmed_balance, 55) await time_out_assert(30, cc_wallet_1.get_confirmed_balance, 45) await time_out_assert(30, cc_wallet_1.get_unconfirmed_balance, 45) await time_out_assert(30, cc_wallet_2.get_confirmed_balance, 0) await time_out_assert(30, cc_wallet_2.get_unconfirmed_balance, 0) @pytest.mark.asyncio async def test_cc_max_amount_send(self, two_wallet_nodes): num_blocks = 3 full_nodes, wallets = two_wallet_nodes full_node_api = full_nodes[0] full_node_server = full_node_api.server wallet_node, server_2 = wallets[0] wallet_node_2, server_3 = wallets[1] wallet = wallet_node.wallet_state_manager.main_wallet ph = await wallet.get_new_puzzlehash() await server_2.start_client(PeerInfo("localhost", uint16(full_node_server._port)), None) await server_3.start_client(PeerInfo("localhost", uint16(full_node_server._port)), None) for i in range(1, num_blocks): await full_node_api.farm_new_transaction_block(FarmNewBlockProtocol(ph)) funds = sum( [ calculate_pool_reward(uint32(i)) + calculate_base_farmer_reward(uint32(i)) for i in range(1, num_blocks - 1) ] ) await time_out_assert(15, wallet.get_confirmed_balance, funds) cc_wallet: CCWallet = await CCWallet.create_new_cc(wallet_node.wallet_state_manager, wallet, uint64(100000)) tx_queue: List[TransactionRecord] = await wallet_node.wallet_state_manager.tx_store.get_not_sent() tx_record = tx_queue[0] await time_out_assert( 15, tx_in_pool, True, full_node_api.full_node.mempool_manager, tx_record.spend_bundle.name() ) for i in range(1, num_blocks): await full_node_api.farm_new_transaction_block(FarmNewBlockProtocol(32 * b"0")) await time_out_assert(15, cc_wallet.get_confirmed_balance, 100000) await time_out_assert(15, cc_wallet.get_unconfirmed_balance, 100000) assert cc_wallet.cc_info.my_genesis_checker is not None cc_2_hash = await cc_wallet.get_new_inner_hash() amounts = [] puzzle_hashes = [] for i in range(1, 50): amounts.append(uint64(i)) puzzle_hashes.append(cc_2_hash) spent_coint = (await cc_wallet.get_cc_spendable_coins())[0].coin tx_record = await cc_wallet.generate_signed_transaction(amounts, puzzle_hashes, coins={spent_coint}) await wallet.wallet_state_manager.add_pending_transaction(tx_record) await time_out_assert( 15, tx_in_pool, True, full_node_api.full_node.mempool_manager, tx_record.spend_bundle.name() ) for i in range(1, num_blocks): await full_node_api.farm_new_transaction_block(FarmNewBlockProtocol(ph)) await asyncio.sleep(2) async def check_all_there(): spendable = await cc_wallet.get_cc_spendable_coins() spendable_name_set = set() for record in spendable: spendable_name_set.add(record.coin.name()) puzzle_hash = cc_puzzle_hash_for_inner_puzzle_hash(CC_MOD, cc_wallet.cc_info.my_genesis_checker, cc_2_hash) for i in range(1, 50): coin = Coin(spent_coint.name(), puzzle_hash, i) if coin.name() not in spendable_name_set: return False return True await time_out_assert(15, check_all_there, True) await asyncio.sleep(5) max_sent_amount = await cc_wallet.get_max_send_amount() # 1) Generate transaction that is under the limit under_limit_tx = None try: under_limit_tx = await cc_wallet.generate_signed_transaction( [max_sent_amount - 1], [ph], ) except ValueError: assert ValueError assert under_limit_tx is not None # 2) Generate transaction that is equal to limit at_limit_tx = None try: at_limit_tx = await cc_wallet.generate_signed_transaction( [max_sent_amount], [ph], ) except ValueError: assert ValueError assert at_limit_tx is not None # 3) Generate transaction that is greater than limit above_limit_tx = None try: above_limit_tx = await cc_wallet.generate_signed_transaction( [max_sent_amount + 1], [ph], ) except ValueError: pass assert above_limit_tx is None
tests/wallet/cc_wallet/test_cc_wallet.py
23,822
1) Generate transaction that is under the limit 2) Generate transaction that is equal to limit 3) Generate transaction that is greater than limit
145
en
0.878675
# -*- coding: utf-8 -*- """ Created on Thu Dec 6 11:37:06 2018 @author: dkorff """ import numpy as np import cantera as ct from assimulo.problem import Implicit_Problem from li_ion_battery_p2d_init import anode as an from li_ion_battery_p2d_init import cathode as cat from li_ion_battery_p2d_init import separator as sep from li_ion_battery_p2d_init import Inputs from li_ion_battery_p2d_init import anode_obj as anode from li_ion_battery_p2d_init import anode_surf_obj as anode_s from li_ion_battery_p2d_init import elyte_obj as elyte from li_ion_battery_p2d_init import cathode_surf_obj as cathode_s from li_ion_battery_p2d_init import cathode_obj as cathode from li_ion_battery_p2d_init import conductor_obj as conductor class Extended_Problem(Implicit_Problem): sw0 = True def Battery_Func(t, SV, SV_dot, sw): """=================================================================""" """==========================INITIALIZE=============================""" """=================================================================""" print(t) nSV = len(SV) res = np.zeros([nSV]) offset_vec = sep.offsets """ anode = an.obj['electrode'] anode_s = an.obj['surf'] elyte = an.obj['elyte'] cathode = cat.obj['electrode'] cathode_s = cat.obj['surf']""" nsp_an = anode.n_species; nsp_cat = cathode.n_species F = ct.faraday; R = ct.gas_constant; T = Inputs.T #sigma_eff_an = an.params['sigma_eff_ed']; dyInv = an.geom['dyInv'] #u_Li_elyte = an.params['u_Li_elyte']; D_Li_an = an.params['D_Li_ed'] #dr = an.dr # %% """=================================================================""" """============================ANODE================================""" """=================================================================""" # -------------------------------- # ANODE CURRENT COLLECTOR BOUNDARY # -------------------------------- # Looking at node 1, j=0, set THIS node conditions offset = an.offsets ptr = an.ptr j = 0 N_io_m = 0 i_io_m = 0 i_el_m = an.i_ext X_an_1 = SV[offset[j] + ptr['X_ed'][-1]] rho_k_elyte_1 = SV[offset[j] + ptr['rho_k_elyte']] phi_elec_an_1 = SV[offset[j] + ptr['Phi_ed']] phi_elec_elyte_1 = phi_elec_an_1 - SV[offset[j] + ptr['Phi_dl']] anode.X = [X_an_1, 1-X_an_1] anode.electric_potential = phi_elec_an_1 conductor.electric_potential = phi_elec_an_1 #elyte.TDY = Inputs.T, np.sum(rho_k_elyte_1), rho_k_elyte_1 elyte.Y = rho_k_elyte_1/np.sum(rho_k_elyte_1) elyte.electric_potential = phi_elec_elyte_1 sdot_1 = anode_s.net_production_rates # Shift forward to node 2, j=1, set NEXT node conditions j = 1; offset = int(offset_vec[j]) X_an_2 = SV[offset + an.ptr['X_ed'][-1]] rho_k_elyte_2 = SV[offset + an.ptr['rho_k_elyte']] phi_elec_an_2 = SV[offset + an.ptr['Phi_ed']] phi_elec_elyte_2 = phi_elec_an_2 - SV[offset + an.ptr['Phi_dl']] anode.X = [X_an_2, 1-X_an_2] conductor.electric_potential = phi_elec_an_2 anode.electric_potential = phi_elec_an_2 #elyte.TDY = Inputs.T, np.sum(rho_k_elyte_2), rho_k_elyte_2 elyte.Y = rho_k_elyte_2/np.sum(rho_k_elyte_2) elyte.electric_potential = phi_elec_elyte_2 sdot_2 = anode_s.net_production_rates # Shift back to node 1, j=0, set THIS node outlet conditions j = 0; offset = int(offset_vec[j]) i_el_p = an.sigma_eff_ed*(phi_elec_an_1-phi_elec_an_2)*an.dyInv N_io_p = (-an.u_Li_elyte*elyte.density_mole*(R*T*(rho_k_elyte_2 - rho_k_elyte_1) + F*(phi_elec_elyte_2 - phi_elec_elyte_1))*an.dyInv) i_io_p = np.dot(N_io_p,Inputs.z_k_elyte)*F i_Far_1 = sdot_1[an.ptr['iFar']]*F*an.A_surf/an.dyInv X_Li = 1 - SV[offset + an.ptr['X_ed']] DiffFlux = np.zeros([an.nshells+1]) DiffFlux[1:-1] = an.D_Li_ed*(X_Li[0:-1] - X_Li[1:])/an.dr DiffFlux[-1] = sdot_1[0]/anode.density_mole k_m = np.arange(0, an.nshells)/an.nshells k_p = np.arange(1, an.nshells+1)/an.nshells # print(anode_s.forward_rate_constants, phi_elec_an_1, sdot_1[an.ptr['iFar']]) """Calculate the change in X_C6 in the particle interior. Note that the DiffFlux is the diffusion of lithium toward the particle surface, and that diffusion of Li into the shell decreases the amount of C6. The fluxes must be scaled by the shell interface surface area relative to the total particle surface area""" res[offset + an.ptr['X_ed']] = (SV_dot[offset + an.ptr['X_ed']] - ((DiffFlux[1:]*k_p**2 - DiffFlux[0:-1]*k_m**2) * an.A_surf/an.eps_ed/an.V_shell)) """Change in electrolyte_composition""" res[offset + an.ptr['rho_k_elyte']] = (SV_dot[offset + an.ptr['rho_k_elyte']] - (((N_io_m - N_io_p)*an.dyInv + sdot_1[nsp_an]*an.A_surf) /elyte.density_mole/an.eps_elyte)) """Double-layer voltage""" res[offset + an.ptr['Phi_dl']] = (SV_dot[offset + an.ptr['Phi_dl']] - (i_Far_1 + i_el_m - i_el_p)*an.dyInv/an.C_dl/an.A_surf) """Algebraic equation for ANODE electric potential boundary condition""" res[offset + an.ptr['Phi_ed']] = SV[offset + an.ptr['Phi_ed']] # (i_el_m - i_el_p + i_io_m - i_io_p) # SV_dot[offset + an.ptr['V_ed']] # %% """============================ANODE================================""" """INTERIOR NODES""" for j in np.arange(2, an.npoints): # Save previous node outlet conditions as new inlet conditions N_io_m = N_io_p i_io_m = i_io_p i_el_m = i_el_p X_an_1 = X_an_2 rho_k_elyte_1 = rho_k_elyte_2 phi_elec_an_1 = phi_elec_an_2 phi_elec_elyte_1 = phi_elec_elyte_2 sdot_1 = sdot_2 # Shift forward to NEXT node offset = int(an.offsets[j]) X_an_2 = SV[offset + an.ptr['X_ed'][-1]] rho_k_elyte_2 = SV[offset + an.ptr['rho_k_elyte']] phi_elec_an_2 = SV[offset + an.ptr['Phi_ed']] phi_elec_elyte_2 = phi_elec_an_2 - SV[offset + an.ptr['Phi_dl']] anode.X = [X_an_2, 1-X_an_2] anode.electric_potential = phi_elec_an_2 conductor.electric_potential = phi_elec_an_2 elyte.Y = rho_k_elyte_2/np.sum(rho_k_elyte_2) elyte.electric_potential = phi_elec_elyte_2 sdot_2 = anode_s.net_production_rates # Shift back to THIS node, set THIS node outlet conditions offset = int(an.offsets[j - 1]) i_el_p = an.sigma_eff_ed*(phi_elec_an_1-phi_elec_an_2)*an.dyInv N_io_p = (-an.u_Li_elyte*elyte.density_mole*(R*T*(rho_k_elyte_2 - rho_k_elyte_1) + F*(phi_elec_elyte_2 - phi_elec_elyte_1))*an.dyInv) i_io_p = np.dot(N_io_p,Inputs.z_k_elyte)*F i_Far_1 = sdot_1[an.ptr['iFar']]*F*an.A_surf/an.dyInv X_Li = 1 - SV[offset + an.ptr['X_ed']] DiffFlux = np.zeros([an.nshells+1]) DiffFlux[1:-1] = an.D_Li_ed*(X_Li[0:-1] - X_Li[1:])/an.dr DiffFlux[-1] = sdot_1[0]/anode.density_mole """Calculate the change in X_C6 in the particle interior.""" res[offset + an.ptr['X_ed']] = (SV_dot[offset + an.ptr['X_ed']] - ((DiffFlux[1:]*k_p**2 - DiffFlux[0:-1]*k_m**2) * an.A_surf/an.eps_ed/an.V_shell)) """Change in electrolyte_composition""" res[offset + an.ptr['rho_k_elyte']] = (SV_dot[offset + an.ptr['rho_k_elyte']] - (((N_io_m - N_io_p)*an.dyInv + sdot_1[nsp_an]*an.A_surf) /elyte.density_mole/an.eps_elyte)) """Double-layer voltage""" res[offset + an.ptr['Phi_dl']] = (SV_dot[offset + an.ptr['Phi_dl']] - (i_Far_1 + i_el_m - i_el_p)*an.dyInv/an.C_dl/an.A_surf) """Algebraic equation for ANODE electric potential boundary condition""" res[offset + an.ptr['Phi_ed']] = (i_el_m - i_el_p + i_io_m - i_io_p) # %% """============================ANODE================================""" """Separator boundary""" # Save previous node outlet conditions as new inlet conditions N_io_m = N_io_p i_io_m = i_io_p i_el_m = i_el_p X_an_1 = X_an_2 rho_k_elyte_1 = rho_k_elyte_2 phi_elec_an_1 = phi_elec_an_2 phi_elec_elyte_1 = phi_elec_elyte_2 sdot_1 = sdot_2 # Shift forward to NEXT node (first separator node) # j = an.npoints; offset = int(offset_vec[j]) # # X_elyte_2 = SV[offset + sep.ptr['X_elyte']] # # phi_elec_elyte_2 = SV[offset + sep.ptr['V_elyte']] # Shift back to THIS node, set THIS node outlet conditions i_el_p = 0 # N_io_p = (-u_Li_elyte*elyte.density_mole*(R*T*(X_elyte_2 - X_elyte_1) # + F*(phi_elec_elyte_2 - phi_elec_elyte_1))*dyInv) # # i_io_p = N_io_p*F # Set j to final ANODE node j = an.npoints-1; offset = int(an.offsets[j]) i_Far_1 = sdot_1[an.ptr['iFar']]*F*an.A_surf/an.dyInv i_io_p = an.i_ext #THIS IS TEMPORARY, NON-GENERALIZED CODE: N_io_p = np.zeros_like(N_io_p) N_io_p[2] = i_io_p/F X_Li = 1 - SV[offset + an.ptr['X_ed']] DiffFlux = np.zeros([an.nshells+1]) DiffFlux[1:-1] = an.D_Li_ed*(X_Li[0:-1] - X_Li[1:])/an.dr DiffFlux[-1] = sdot_1[0]/anode.density_mole """Calculate the change in X_C6 in the particle interior.""" res[offset + an.ptr['X_ed']] = (SV_dot[offset + an.ptr['X_ed']] - ((DiffFlux[1:]*k_p**2 - DiffFlux[0:-1]*k_m**2) * an.A_surf/an.eps_ed/an.V_shell)) """Change in electrolyte_composition""" res[offset + an.ptr['rho_k_elyte']] = (SV_dot[offset + an.ptr['rho_k_elyte']] - (((N_io_m - N_io_p)*an.dyInv + sdot_1[nsp_an]*an.A_surf) /elyte.density_mole/an.eps_elyte)) """Double-layer voltage""" res[offset + an.ptr['Phi_dl']] = (SV_dot[offset + an.ptr['Phi_dl']] - (i_Far_1 + i_el_m - i_el_p)*an.dyInv/an.C_dl/an.A_surf) """Algebraic equation for ANODE electric potential boundary condition""" res[offset + an.ptr['Phi_ed']] = (i_el_m - i_el_p + i_io_m - i_io_p) # %% """=================================================================""" """==========================SEPARATOR==============================""" """=================================================================""" # for j in np.arange(an.npoints+1, sep.sep_max): # # X_elyte_1 = X_elyte_2 # phi_elec_elyte_1 = phi_elec_elyte_2 # N_io_m = N_io_p # i_io_m = i_io_p # Shift forward to NEXT node # offset = int(offset_vec[j]) # # X_elyte_2 = SV[offset + sep.ptr['X_elyte']] # phi_elec_elyte_2 = SV[offset + sep.ptr['V_elyte']] # Step back to THIS node to calculate outlet flux # offset = int(offset_vec[j-1]) # N_io_p = (-u_Li_elyte*elyte.density_mole*(R*T*(X_elyte_2 - X_elyte_1) # + F*(phi_elec_elyte_2 - phi_elec_elyte_1))*sep.geom['dyInv']) # # i_io_p = N_io_p*F # i_io_p = an.params['i_ext'] # N_io_p = i_io_p/F # # """Change in electrolyte_composition""" # res[offset + sep.ptr['X_elyte']] = (SV_dot[offset + sep.ptr['X_elyte']] # - (((N_io_m - N_io_p)*dyInv)/elyte.density_mole/sep.geom['phi_elyte'])) # # """Charge neutrality enforced""" # res[offset + sep.ptr['V_elyte']] = (i_io_m - i_io_p) # %% # Looking at LAST node in separator # X_elyte_1 = X_elyte_2 # phi_elec_elyte_1 = phi_elec_elyte_2 # N_io_m = N_io_p # i_io_m = i_io_p # Shift forward to NEXT node, first cathode node # j = sep.sep_max; offset = int(offset_vec[j]) # # X_cat_2 = SV[offset + cat.ptr['X_ed'][-1]] # X_elyte_2 = SV[offset + cat.ptr['X_elyte']] # # phi_elec_cat_2 = SV[offset + cat.ptr['V_ed']] # phi_elec_elyte_2 = phi_elec_cat_2 - SV[offset + cat.ptr['V_dl']] # # cathode.X = [1-X_cat_2, X_cat_2] # cathode.electric_potential = phi_elec_cat_2 # # elyte.X = [X_elyte_2, 7.8730103237e-2, 2.8328131770e-1] # elyte.electric_potential = phi_elec_elyte_2 # # sdot_2 = cathode_s.net_production_rates # Shift back to THIS node (last separator node) # j = sep.sep_max-1; offset = int(offset_vec[j]) # # i_el_p = 0 # N_io_p = (-u_Li_elyte*elyte.density_mole*(R*T*(X_elyte_2 - X_elyte_1) # + F*(phi_elec_elyte_2 - phi_elec_elyte_1))*sep.geom['dyInv']) # # i_io_p = N_io_p*F # i_io_p = an.params['i_ext'] # N_io_p = i_io_p/F # # """Change in electrolyte_composition""" # res[offset + sep.ptr['X_elyte']] = (SV_dot[offset + sep.ptr['X_elyte']] # - (((N_io_m - N_io_p)*dyInv)/elyte.density_mole/sep.geom['phi_elyte'])) # # """Charge neutrality enforced""" # res[offset + sep.ptr['V_elyte']] = (i_io_m - i_io_p) # print(SV, res) # SV[offset + sep.ptr['V_elyte']] # (i_io_m - i_io_p) # %% """=================================================================""" """===========================CATHODE===============================""" """=================================================================""" # Alrighty, CATHODE time # sigma_eff_cat = cat.params['sigma_eff_ed']; dyInv = cat.geom['dyInv'] # D_Li_cat = cat.params['D_Li_ed'] # # i_io_m = i_io_p # N_io_m = N_io_p # i_el_m = i_el_p # X_cat_1 = X_cat_2 # X_elyte_1 = X_elyte_2 # phi_elec_cat_1 = phi_elec_cat_2 # phi_elec_elyte_1 = phi_elec_elyte_2 # sdot_1 = sdot_2 # j = sep.cat_max-1; offset = int(offset_vec[j]) # i_el_p = -an.params['i_ext'] # i_io_p = 0 # N_io_p = i_io_p/F # # i_Far_1 = sdot_1[cat.ptr['iFar']]*F*cat.geom['A_surf']/dyInv # print(cathode_s.forward_rate_constants, phi_elec_cat_1, sdot_1[cat.ptr['iFar']]) # X_Li = 1 - SV[offset + cat.ptr['X_ed']] # DiffFlux = np.zeros([cat.nshells+1]) # DiffFlux[1:-1] = D_Li_cat*(X_Li[0:-1] - X_Li[1:])/dr # DiffFlux[-1] = sdot_1[0]/cathode.density_mole # # """Calculate the change in CoO2 in the particle interior.""" # res[offset + cat.ptr['X_ed']] = (SV_dot[offset + cat.ptr['X_ed']] # - ((DiffFlux[1:]*k_p**2 - DiffFlux[0:-1]*k_m**2) # * cat.geom['A_surf']/cat.geom['phi_ed']/cat.params['V_shell'])) # # """Change in electrolyte_composition""" # res[offset + cat.ptr['X_elyte']] = (SV_dot[offset + cat.ptr['X_elyte']] # - (((N_io_m - N_io_p)*dyInv + sdot_1[nsp_cat]*cat.geom['A_surf']) # /elyte.density_mole/cat.geom['phi_elyte'])) # # """Double-layer voltage""" # res[offset + cat.ptr['V_dl']] = (SV_dot[offset + cat.ptr['V_dl']] # - (i_Far_1 + i_el_m - i_el_p)*dyInv/cat.params['C_dl']/cat.geom['A_surf']) # # """Algebraic equation for CATHODE electric potential boundary condition""" # res[offset + cat.ptr['V_ed']] = (i_el_m - i_el_p + i_io_m - i_io_p) # print(SV, res) # for j in np.arange(an.npoints + sep.npoints, sep.cat_max-1): # N_io_m = N_io_p # i_io_m = i_io_p # i_el_m = i_el_p # X_cat_1 = X_cat_2 # X_elyte_1 = X_elyte_2 # phi_elec_cat_1 = phi_elec_cat_2 # phi_elec_elyte_1 = phi_elec_elyte_2 # sdot_1 = sdot_2 # # # Look at NEXT node # offset = int(offset_vec[j]) # # X_cat_2 = SV[offset + cat.ptr['X_ed'][-1]] # X_elyte_2 = SV[offset + cat.ptr['X_elyte']] # # phi_elec_cat_2 = SV[offset + cat.ptr['V_ed']] # phi_elec_elyte_2 = phi_elec_cat_2 - SV[offset + cat.ptr['V_dl']] # # cathode.X = [1-X_cat_2, X_cat_2] # cathode.electric_potential = phi_elec_cat_2 # # elyte.X = [X_elyte_2, 1-X_elyte_2] # elyte.electric_potential = phi_elec_elyte_2 # # sdot_2 = cathode_s.net_production_rates # # # Shift back to THIS node, set THIS node outlet conditions # offset = int(offset_vec[j-1]) # # i_el_p = sigma_eff_cat*(phi_elec_cat_1 - phi_elec_cat_2)*dyInv # # N_io_p = (-u_Li_elyte*elyte.density_mole*(R*T*(X_elyte_2 - X_elyte_1) # + F*(phi_elec_elyte_2 - phi_elec_elyte_1))*dyInv) # # i_io_p = N_io_p*F # # i_Far_1 = sdot_1[cat.ptr['iFar']]*F*cat.geom['A_surf']/dyInv # # X_Li = 1 - SV[offset + cat.ptr['X_ed']] # DiffFlux = np.zeros([cat.nshells+1]) # DiffFlux[1:-1] = D_Li_cat*(X_Li[0:-1] - X_Li[1:])/dr # DiffFlux[-1] = sdot_1[1]/cathode.density_mole # # """Calculate the change in CoO2 in the particle interior.""" # res[offset + cat.ptr['X_ed']] = (SV_dot[offset + cat.ptr['X_ed']]) # """- ((DiffFlux[1:]*k_p**2 - DiffFlux[0:-1]*k_m**2) # * cat.geom['A_surf']/cat.geom['phi_ed']/cat.params['V_shell']))""" # # """Change in electrolyte_composition""" # res[offset + cat.ptr['X_elyte']] = (SV_dot[offset + cat.ptr['X_elyte']]) # """- (((N_io_m - N_io_p)*dyInv + sdot_1[nsp_cat]*cat.geom['A_surf']) # /elyte.density_mole/cat.geom['phi_elyte']))""" # # """Double-layer voltage""" # res[offset + cat.ptr['V_dl']] = (SV_dot[offset + cat.ptr['V_dl']] # - (i_Far_1 + i_el_m - i_el_p)*dyInv/cat.params['C_dl']/cat.geom['A_surf']) # # """Algebraic equation for CATHODE electric potential boundary condition""" # res[offset + cat.ptr['V_ed']] = (i_el_m - i_el_p + i_io_m - i_io_p) # %% """=========================CATHODE=============================""" """current collector boundary""" # N_io_m = N_io_p # i_io_m = i_io_p # i_el_m = i_el_p # X_cat_1 = X_cat_2 # X_elyte_1 = X_elyte_2 # phi_elec_cat_1 = phi_elec_cat_2 # phi_elec_elyte_1 = phi_elec_elyte_2 # sdot_1 = sdot_2 # # # Set THIS node outlet conditions (last node BCs) # j = sep.cat_max - 1; offset = int(offset_vec[j]) # i_io_p = 0 # N_io_p = 0 # i_el_p = cat.params['i_ext'] # # i_Far_1 = sdot_1[cat.ptr['iFar']]*F*cat.geom['A_surf']/dyInv # # X_Li = 1 - SV[offset + cat.ptr['X_ed']] # DiffFlux = np.zeros([cat.nshells+1]) # DiffFlux[1:-1] = D_Li_cat*(X_Li[0:-1] - X_Li[1:])/dr # DiffFlux[-1] = sdot_1[1]/cathode.density_mole # # """Calculate the change in CoO2 in the particle interior.""" # res[offset + cat.ptr['X_ed']] = (SV_dot[offset + cat.ptr['X_ed']]) # """- ((DiffFlux[1:]*k_p**2 - DiffFlux[0:-1]*k_m**2) # * cat.geom['A_surf']/cat.geom['phi_ed']/cat.params['V_shell']))""" # # """Change in electrolyte_composition""" # res[offset + cat.ptr['X_elyte']] = (SV_dot[offset + cat.ptr['X_elyte']]) # """- (((N_io_m - N_io_p)*dyInv + sdot_1[nsp_cat]*cat.geom['A_surf']) # /elyte.density_mole/cat.geom['phi_elyte']))""" # # """Double-layer voltage""" # res[offset + cat.ptr['V_dl']] = (SV_dot[offset + cat.ptr['V_dl']] # - (i_Far_1 + i_el_m - i_el_p)*dyInv/cat.params['C_dl']/cat.geom['A_surf']) # # """Algebraic equation for CATHODE electric potential boundary condition""" # res[offset + cat.ptr['V_ed']] = (i_el_m - i_el_p + i_io_m - i_io_p) return res """=====================================================================""" """=====================================================================""" """=====================================================================""" # %% def state_events(self, t, y, yd, sw): event1 = np.zeros([an.params['npoints']]) event2 = np.zeros([an.params['npoints']]) event3 = np.zeros([an.params['nshells']]) event4 = np.zeros([an.params['nshells']]) for j in np.arange(0, an.params['npoints']): offset = j*an.params['nVars'] event1[j] = (y[offset + an.ptr['V_dl']]) event2[j] = (1 - y[offset + an.ptr['V_dl']]) for i in np.arange(0, an.params['nshells']): event3[i] = y[offset + an.ptr['X_ed'][i]] - (1 - an.params['X_Li_max']) event4[i] = (((1 - an.params['X_Li_min']) - y[offset + an.ptr['X_ed'][i]])) event5 = np.zeros([cat.params['npoints']]) event6 = np.zeros([cat.params['npoints']]) event7 = np.zeros([cat.params['nshells']]) event8 = np.zeros([cat.params['nshells']]) for j in np.arange(0, cat.params['npoints']): offset = j*cat.params['nVars'] + an.npoints*an.nVars + sep.npoints*sep.nVars event5[j] = (y[offset + cat.ptr['V_dl']]) event6[j] = (y[offset + cat.ptr['V_dl']] - 5) for i in np.arange(0, cat.params['nshells']): event7[i] = y[offset + cat.ptr['X_ed'][i]] - (1 - cat.params['X_Li_max']) event8[i] = (1 - cat.params['X_Li_min']) - y[offset + cat.ptr['X_ed'][i]] event9 = np.zeros([sep.npoints]) event10 = np.zeros([sep.npoints]) for j in np.arange(0, sep.npoints): offset = an.npoints*an.nVars event9[j] = 1 - y[offset + sep.ptr['X_elyte']] event10[j] = y[offset + sep.ptr['X_elyte']] events = np.concatenate((event1, event2, event3, event4, event5, event6, event7, event8, event9, event10)) return events """=====================================================================""" def handle_event(self, solver, event_info): while True: self.event_switch(solver, event_info) self.init_mode(solver) if not True in event_info: break def event_switch(self, solver, event_info): if not all(event_info): solver.sw = [not solver.sw] def init_mode(self, solver): an.t_flag = solver.t if an.params['i_ext'] != 0: an.params['i_ext'] = 0 cat.params['i_ext'] = 0
li_ion_battery_p2d_functions.py
22,680
================================================================= Created on Thu Dec 6 11:37:06 2018 @author: dkorff -*- coding: utf-8 -*-sigma_eff_an = an.params['sigma_eff_ed']; dyInv = an.geom['dyInv']u_Li_elyte = an.params['u_Li_elyte']; D_Li_an = an.params['D_Li_ed']dr = an.dr %% -------------------------------- ANODE CURRENT COLLECTOR BOUNDARY -------------------------------- Looking at node 1, j=0, set THIS node conditionselyte.TDY = Inputs.T, np.sum(rho_k_elyte_1), rho_k_elyte_1 Shift forward to node 2, j=1, set NEXT node conditionselyte.TDY = Inputs.T, np.sum(rho_k_elyte_2), rho_k_elyte_2 Shift back to node 1, j=0, set THIS node outlet conditions print(anode_s.forward_rate_constants, phi_elec_an_1, sdot_1[an.ptr['iFar']]) (i_el_m - i_el_p + i_io_m - i_io_p) SV_dot[offset + an.ptr['V_ed']] %% Save previous node outlet conditions as new inlet conditions Shift forward to NEXT node Shift back to THIS node, set THIS node outlet conditions %% Save previous node outlet conditions as new inlet conditions Shift forward to NEXT node (first separator node) j = an.npoints; offset = int(offset_vec[j]) X_elyte_2 = SV[offset + sep.ptr['X_elyte']] phi_elec_elyte_2 = SV[offset + sep.ptr['V_elyte']] Shift back to THIS node, set THIS node outlet conditions N_io_p = (-u_Li_elyte*elyte.density_mole*(R*T*(X_elyte_2 - X_elyte_1) + F*(phi_elec_elyte_2 - phi_elec_elyte_1))*dyInv) i_io_p = N_io_p*F Set j to final ANODE nodeTHIS IS TEMPORARY, NON-GENERALIZED CODE: %% for j in np.arange(an.npoints+1, sep.sep_max): X_elyte_1 = X_elyte_2 phi_elec_elyte_1 = phi_elec_elyte_2 N_io_m = N_io_p i_io_m = i_io_p Shift forward to NEXT node offset = int(offset_vec[j]) X_elyte_2 = SV[offset + sep.ptr['X_elyte']] phi_elec_elyte_2 = SV[offset + sep.ptr['V_elyte']] Step back to THIS node to calculate outlet flux offset = int(offset_vec[j-1]) N_io_p = (-u_Li_elyte*elyte.density_mole*(R*T*(X_elyte_2 - X_elyte_1) + F*(phi_elec_elyte_2 - phi_elec_elyte_1))*sep.geom['dyInv']) i_io_p = N_io_p*F i_io_p = an.params['i_ext'] N_io_p = i_io_p/F """Change in electrolyte_composition""" res[offset + sep.ptr['X_elyte']] = (SV_dot[offset + sep.ptr['X_elyte']] - (((N_io_m - N_io_p)*dyInv)/elyte.density_mole/sep.geom['phi_elyte'])) """Charge neutrality enforced""" res[offset + sep.ptr['V_elyte']] = (i_io_m - i_io_p) %% Looking at LAST node in separator X_elyte_1 = X_elyte_2 phi_elec_elyte_1 = phi_elec_elyte_2 N_io_m = N_io_p i_io_m = i_io_p Shift forward to NEXT node, first cathode node j = sep.sep_max; offset = int(offset_vec[j]) X_cat_2 = SV[offset + cat.ptr['X_ed'][-1]] X_elyte_2 = SV[offset + cat.ptr['X_elyte']] phi_elec_cat_2 = SV[offset + cat.ptr['V_ed']] phi_elec_elyte_2 = phi_elec_cat_2 - SV[offset + cat.ptr['V_dl']] cathode.X = [1-X_cat_2, X_cat_2] cathode.electric_potential = phi_elec_cat_2 elyte.X = [X_elyte_2, 7.8730103237e-2, 2.8328131770e-1] elyte.electric_potential = phi_elec_elyte_2 sdot_2 = cathode_s.net_production_rates Shift back to THIS node (last separator node) j = sep.sep_max-1; offset = int(offset_vec[j]) i_el_p = 0 N_io_p = (-u_Li_elyte*elyte.density_mole*(R*T*(X_elyte_2 - X_elyte_1) + F*(phi_elec_elyte_2 - phi_elec_elyte_1))*sep.geom['dyInv']) i_io_p = N_io_p*F i_io_p = an.params['i_ext'] N_io_p = i_io_p/F """Change in electrolyte_composition""" res[offset + sep.ptr['X_elyte']] = (SV_dot[offset + sep.ptr['X_elyte']] - (((N_io_m - N_io_p)*dyInv)/elyte.density_mole/sep.geom['phi_elyte'])) """Charge neutrality enforced""" res[offset + sep.ptr['V_elyte']] = (i_io_m - i_io_p) print(SV, res) SV[offset + sep.ptr['V_elyte']] (i_io_m - i_io_p) %% Alrighty, CATHODE time sigma_eff_cat = cat.params['sigma_eff_ed']; dyInv = cat.geom['dyInv'] D_Li_cat = cat.params['D_Li_ed'] i_io_m = i_io_p N_io_m = N_io_p i_el_m = i_el_p X_cat_1 = X_cat_2 X_elyte_1 = X_elyte_2 phi_elec_cat_1 = phi_elec_cat_2 phi_elec_elyte_1 = phi_elec_elyte_2 sdot_1 = sdot_2 j = sep.cat_max-1; offset = int(offset_vec[j]) i_el_p = -an.params['i_ext'] i_io_p = 0 N_io_p = i_io_p/F i_Far_1 = sdot_1[cat.ptr['iFar']]*F*cat.geom['A_surf']/dyInv print(cathode_s.forward_rate_constants, phi_elec_cat_1, sdot_1[cat.ptr['iFar']]) X_Li = 1 - SV[offset + cat.ptr['X_ed']] DiffFlux = np.zeros([cat.nshells+1]) DiffFlux[1:-1] = D_Li_cat*(X_Li[0:-1] - X_Li[1:])/dr DiffFlux[-1] = sdot_1[0]/cathode.density_mole """Calculate the change in CoO2 in the particle interior.""" res[offset + cat.ptr['X_ed']] = (SV_dot[offset + cat.ptr['X_ed']] - ((DiffFlux[1:]*k_p**2 - DiffFlux[0:-1]*k_m**2) * cat.geom['A_surf']/cat.geom['phi_ed']/cat.params['V_shell'])) """Change in electrolyte_composition""" res[offset + cat.ptr['X_elyte']] = (SV_dot[offset + cat.ptr['X_elyte']] - (((N_io_m - N_io_p)*dyInv + sdot_1[nsp_cat]*cat.geom['A_surf']) /elyte.density_mole/cat.geom['phi_elyte'])) """Double-layer voltage""" res[offset + cat.ptr['V_dl']] = (SV_dot[offset + cat.ptr['V_dl']] - (i_Far_1 + i_el_m - i_el_p)*dyInv/cat.params['C_dl']/cat.geom['A_surf']) """Algebraic equation for CATHODE electric potential boundary condition""" res[offset + cat.ptr['V_ed']] = (i_el_m - i_el_p + i_io_m - i_io_p) print(SV, res) for j in np.arange(an.npoints + sep.npoints, sep.cat_max-1): N_io_m = N_io_p i_io_m = i_io_p i_el_m = i_el_p X_cat_1 = X_cat_2 X_elyte_1 = X_elyte_2 phi_elec_cat_1 = phi_elec_cat_2 phi_elec_elyte_1 = phi_elec_elyte_2 sdot_1 = sdot_2 Look at NEXT node offset = int(offset_vec[j]) X_cat_2 = SV[offset + cat.ptr['X_ed'][-1]] X_elyte_2 = SV[offset + cat.ptr['X_elyte']] phi_elec_cat_2 = SV[offset + cat.ptr['V_ed']] phi_elec_elyte_2 = phi_elec_cat_2 - SV[offset + cat.ptr['V_dl']] cathode.X = [1-X_cat_2, X_cat_2] cathode.electric_potential = phi_elec_cat_2 elyte.X = [X_elyte_2, 1-X_elyte_2] elyte.electric_potential = phi_elec_elyte_2 sdot_2 = cathode_s.net_production_rates Shift back to THIS node, set THIS node outlet conditions offset = int(offset_vec[j-1]) i_el_p = sigma_eff_cat*(phi_elec_cat_1 - phi_elec_cat_2)*dyInv N_io_p = (-u_Li_elyte*elyte.density_mole*(R*T*(X_elyte_2 - X_elyte_1) + F*(phi_elec_elyte_2 - phi_elec_elyte_1))*dyInv) i_io_p = N_io_p*F i_Far_1 = sdot_1[cat.ptr['iFar']]*F*cat.geom['A_surf']/dyInv X_Li = 1 - SV[offset + cat.ptr['X_ed']] DiffFlux = np.zeros([cat.nshells+1]) DiffFlux[1:-1] = D_Li_cat*(X_Li[0:-1] - X_Li[1:])/dr DiffFlux[-1] = sdot_1[1]/cathode.density_mole """Calculate the change in CoO2 in the particle interior.""" res[offset + cat.ptr['X_ed']] = (SV_dot[offset + cat.ptr['X_ed']]) """- ((DiffFlux[1:]*k_p**2 - DiffFlux[0:-1]*k_m**2) * cat.geom['A_surf']/cat.geom['phi_ed']/cat.params['V_shell']))""" """Change in electrolyte_composition""" res[offset + cat.ptr['X_elyte']] = (SV_dot[offset + cat.ptr['X_elyte']]) """- (((N_io_m - N_io_p)*dyInv + sdot_1[nsp_cat]*cat.geom['A_surf']) /elyte.density_mole/cat.geom['phi_elyte']))""" """Double-layer voltage""" res[offset + cat.ptr['V_dl']] = (SV_dot[offset + cat.ptr['V_dl']] - (i_Far_1 + i_el_m - i_el_p)*dyInv/cat.params['C_dl']/cat.geom['A_surf']) """Algebraic equation for CATHODE electric potential boundary condition""" res[offset + cat.ptr['V_ed']] = (i_el_m - i_el_p + i_io_m - i_io_p) %% N_io_m = N_io_p i_io_m = i_io_p i_el_m = i_el_p X_cat_1 = X_cat_2 X_elyte_1 = X_elyte_2 phi_elec_cat_1 = phi_elec_cat_2 phi_elec_elyte_1 = phi_elec_elyte_2 sdot_1 = sdot_2 Set THIS node outlet conditions (last node BCs) j = sep.cat_max - 1; offset = int(offset_vec[j]) i_io_p = 0 N_io_p = 0 i_el_p = cat.params['i_ext'] i_Far_1 = sdot_1[cat.ptr['iFar']]*F*cat.geom['A_surf']/dyInv X_Li = 1 - SV[offset + cat.ptr['X_ed']] DiffFlux = np.zeros([cat.nshells+1]) DiffFlux[1:-1] = D_Li_cat*(X_Li[0:-1] - X_Li[1:])/dr DiffFlux[-1] = sdot_1[1]/cathode.density_mole """Calculate the change in CoO2 in the particle interior.""" res[offset + cat.ptr['X_ed']] = (SV_dot[offset + cat.ptr['X_ed']]) """- ((DiffFlux[1:]*k_p**2 - DiffFlux[0:-1]*k_m**2) * cat.geom['A_surf']/cat.geom['phi_ed']/cat.params['V_shell']))""" """Change in electrolyte_composition""" res[offset + cat.ptr['X_elyte']] = (SV_dot[offset + cat.ptr['X_elyte']]) """- (((N_io_m - N_io_p)*dyInv + sdot_1[nsp_cat]*cat.geom['A_surf']) /elyte.density_mole/cat.geom['phi_elyte']))""" """Double-layer voltage""" res[offset + cat.ptr['V_dl']] = (SV_dot[offset + cat.ptr['V_dl']] - (i_Far_1 + i_el_m - i_el_p)*dyInv/cat.params['C_dl']/cat.geom['A_surf']) """Algebraic equation for CATHODE electric potential boundary condition""" res[offset + cat.ptr['V_ed']] = (i_el_m - i_el_p + i_io_m - i_io_p) %%
9,839
en
0.233797
import asyncio import discord from discord.ext.commands import Bot from discord.ext import commands from discord import Color, Embed import backend.commands as db from backend import strikechannel # This command allows players to change their name. # # !name [new_name] # # This replaces the default nickname changing that Discord provides so # that their name will also be replaced in the spreadsheet. class Name(commands.Cog): def __init__(self, bot): self.bot = bot self.strike_channel_id = strikechannel @commands.command() async def name(self, ctx): old_name = ctx.author.display_name new_name = ctx.message.content[6:] print(old_name) print(new_name) # This changes their name in the "#strikes" channel channel = self.bot.get_channel(self.strike_channel_id) async for msg in channel.history(limit=None): text = msg.content.replace("```", "") text_lst = text.split("\n") d = {} for line in text_lst: try: name, strikes = line.rsplit(" - ", 1) except: continue d[name] = int(strikes) if old_name in d: d[new_name] = d[old_name] del d[old_name] inner_text = "" for k, v in d.items(): inner_text += f"{k} - {v}\n" full_text = f"```\n{inner_text}```" await msg.edit(content=full_text) db.change_name(old_name, new_name) await ctx.author.edit(nick=new_name) await ctx.channel.send("Name Changed!") def setup(bot): bot.add_cog(Name(bot))
commands/name.py
1,711
This command allows players to change their name. !name [new_name] This replaces the default nickname changing that Discord provides so that their name will also be replaced in the spreadsheet. This changes their name in the "strikes" channel
242
en
0.936308
# (c) Copyright 2014 Hewlett-Packard Development Company, L.P. # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. # """Fake HP client for testing LeftHand without installing the client.""" import sys import mock from cinder.tests import fake_hp_client_exceptions as hpexceptions hplefthand = mock.Mock() hplefthand.version = "1.0.4" hplefthand.exceptions = hpexceptions sys.modules['hplefthandclient'] = hplefthand
cinder/tests/fake_hp_lefthand_client.py
969
Fake HP client for testing LeftHand without installing the client. (c) Copyright 2014 Hewlett-Packard Development Company, L.P. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.
703
en
0.861639
FROM = 'vie-qs' TO = 'fee-qs' from_layer = Font.glyphs[FROM].layers[0] XHEIGHT = Font.masters[0].xHeight WIDTH = Font.masters[0].widthValue to_layer = Font.glyphs[TO].layers[0] = from_layer.copyDecomposedLayer() for path in to_layer.paths: for node in path.nodes: # mess with node.x and node.y node.y = XHEIGHT - node.y node.x = WIDTH - node.x node.x += 4*WIDTH # doesn't seem to work del(path.nodes[-1]) # get rid of tail
glyph-generation scripts/vie2fee.py
476
mess with node.x and node.y doesn't seem to work get rid of tail
64
en
0.988851
import torch import numpy as np class ScheduledOptim: """ A simple wrapper class for learning rate scheduling """ def __init__(self, model, train_config, model_config, current_step): self._optimizer = torch.optim.Adam( model.parameters(), betas=train_config["optimizer"]["betas"], eps=train_config["optimizer"]["eps"], weight_decay=train_config["optimizer"]["weight_decay"], ) self.n_warmup_steps = train_config["optimizer"]["warm_up_step"] self.anneal_steps = train_config["optimizer"]["anneal_steps"] self.anneal_rate = train_config["optimizer"]["anneal_rate"] self.current_step = current_step self.init_lr = np.power(model_config["transformer"]["encoder_hidden"], -0.5) def step_and_update_lr(self): self._update_learning_rate() self._optimizer.step() def zero_grad(self): # print(self.init_lr) self._optimizer.zero_grad() def load_state_dict(self, path): self._optimizer.load_state_dict(path) def _get_lr_scale(self): lr = np.min( [ np.power(self.current_step, -0.5), np.power(self.n_warmup_steps, -1.5) * self.current_step, ] ) for s in self.anneal_steps: if self.current_step > s: lr = lr * self.anneal_rate return lr def _update_learning_rate(self): """ Learning rate scheduling per step """ self.current_step += 1 lr = self.init_lr * self._get_lr_scale() for param_group in self._optimizer.param_groups: param_group["lr"] = lr
FastSpeech2/model/optimizer.py
1,728
A simple wrapper class for learning rate scheduling Learning rate scheduling per step print(self.init_lr)
109
en
0.519714
#!/usr/bin/env python """ Analyze docstrings to detect errors. If no argument is provided, it does a quick check of docstrings and returns a csv with all API functions and results of basic checks. If a function or method is provided in the form "pandas.function", "pandas.module.class.method", etc. a list of all errors in the docstring for the specified function or method. Usage:: $ ./validate_docstrings.py $ ./validate_docstrings.py pandas.DataFrame.head """ import os import sys import csv import re import functools import collections import argparse import pydoc import inspect import importlib import doctest try: from io import StringIO except ImportError: from cStringIO import StringIO import numpy BASE_PATH = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) sys.path.insert(0, os.path.join(BASE_PATH)) import pandas from pandas.compat import signature sys.path.insert(1, os.path.join(BASE_PATH, 'doc', 'sphinxext')) from numpydoc.docscrape import NumpyDocString from pandas.io.formats.printing import pprint_thing PRIVATE_CLASSES = ['NDFrame', 'IndexOpsMixin'] DIRECTIVES = ['versionadded', 'versionchanged', 'deprecated'] def _load_obj(obj_name): for maxsplit in range(1, obj_name.count('.') + 1): # TODO when py3 only replace by: module, *func_parts = ... func_name_split = obj_name.rsplit('.', maxsplit) module = func_name_split[0] func_parts = func_name_split[1:] try: obj = importlib.import_module(module) except ImportError: pass else: continue if 'module' not in locals(): raise ImportError('No module can be imported ' 'from "{}"'.format(obj_name)) for part in func_parts: obj = getattr(obj, part) return obj def _to_original_callable(obj): while True: if inspect.isfunction(obj) or inspect.isclass(obj): f = inspect.getfile(obj) if f.startswith('<') and f.endswith('>'): return None return obj if inspect.ismethod(obj): obj = obj.__func__ elif isinstance(obj, functools.partial): obj = obj.func elif isinstance(obj, property): obj = obj.fget else: return None def _output_header(title, width=80, char='#'): full_line = char * width side_len = (width - len(title) - 2) // 2 adj = '' if len(title) % 2 == 0 else ' ' title_line = '{side} {title}{adj} {side}'.format(side=char * side_len, title=title, adj=adj) return '\n{full_line}\n{title_line}\n{full_line}\n\n'.format( full_line=full_line, title_line=title_line) class Docstring(object): def __init__(self, method_name, method_obj): self.method_name = method_name self.method_obj = method_obj self.raw_doc = method_obj.__doc__ or '' self.clean_doc = pydoc.getdoc(self.method_obj) self.doc = NumpyDocString(self.clean_doc) def __len__(self): return len(self.raw_doc) @property def is_function_or_method(self): # TODO(py27): remove ismethod return (inspect.isfunction(self.method_obj) or inspect.ismethod(self.method_obj)) @property def source_file_name(self): fname = inspect.getsourcefile(self.method_obj) if fname: fname = os.path.relpath(fname, BASE_PATH) return fname @property def source_file_def_line(self): try: return inspect.getsourcelines(self.method_obj)[-1] except OSError: pass @property def github_url(self): url = 'https://github.com/pandas-dev/pandas/blob/master/' url += '{}#L{}'.format(self.source_file_name, self.source_file_def_line) return url @property def start_blank_lines(self): i = None if self.raw_doc: for i, row in enumerate(self.raw_doc.split('\n')): if row.strip(): break return i @property def end_blank_lines(self): i = None if self.raw_doc: for i, row in enumerate(reversed(self.raw_doc.split('\n'))): if row.strip(): break return i @property def double_blank_lines(self): prev = True for row in self.raw_doc.split('\n'): if not prev and not row.strip(): return True prev = row.strip() return False @property def summary(self): return ' '.join(self.doc['Summary']) @property def num_summary_lines(self): return len(self.doc['Summary']) @property def extended_summary(self): if not self.doc['Extended Summary'] and len(self.doc['Summary']) > 1: return ' '.join(self.doc['Summary']) return ' '.join(self.doc['Extended Summary']) @property def needs_summary(self): return not (bool(self.summary) and bool(self.extended_summary)) @property def doc_parameters(self): return collections.OrderedDict((name, (type_, ''.join(desc))) for name, type_, desc in self.doc['Parameters']) @property def signature_parameters(self): if inspect.isclass(self.method_obj): if hasattr(self.method_obj, '_accessors') and ( self.method_name.split('.')[-1] in self.method_obj._accessors): # accessor classes have a signature but don't want to show this return tuple() try: sig = signature(self.method_obj) except (TypeError, ValueError): # Some objects, mainly in C extensions do not support introspection # of the signature return tuple() params = sig.args if sig.varargs: params.append("*" + sig.varargs) if sig.keywords: params.append("**" + sig.keywords) params = tuple(params) if params and params[0] in ('self', 'cls'): return params[1:] return params @property def parameter_mismatches(self): errs = [] signature_params = self.signature_parameters doc_params = tuple(self.doc_parameters) missing = set(signature_params) - set(doc_params) if missing: errs.append( 'Parameters {} not documented'.format(pprint_thing(missing))) extra = set(doc_params) - set(signature_params) if extra: errs.append('Unknown parameters {}'.format(pprint_thing(extra))) if (not missing and not extra and signature_params != doc_params and not (not signature_params and not doc_params)): errs.append('Wrong parameters order. ' + 'Actual: {!r}. '.format(signature_params) + 'Documented: {!r}'.format(doc_params)) return errs @property def correct_parameters(self): return not bool(self.parameter_mismatches) def parameter_type(self, param): return self.doc_parameters[param][0] def parameter_desc(self, param): desc = self.doc_parameters[param][1] # Find and strip out any sphinx directives for directive in DIRECTIVES: full_directive = '.. {}'.format(directive) if full_directive in desc: # Only retain any description before the directive desc = desc[:desc.index(full_directive)] return desc @property def see_also(self): return collections.OrderedDict((name, ''.join(desc)) for name, desc, _ in self.doc['See Also']) @property def examples(self): return self.doc['Examples'] @property def returns(self): return self.doc['Returns'] @property def yields(self): return self.doc['Yields'] @property def method_source(self): return inspect.getsource(self.method_obj) @property def first_line_ends_in_dot(self): if self.doc: return self.doc.split('\n')[0][-1] == '.' @property def deprecated(self): pattern = re.compile('.. deprecated:: ') return (self.method_name.startswith('pandas.Panel') or bool(pattern.search(self.summary)) or bool(pattern.search(self.extended_summary))) @property def mentioned_private_classes(self): return [klass for klass in PRIVATE_CLASSES if klass in self.raw_doc] @property def examples_errors(self): flags = doctest.NORMALIZE_WHITESPACE | doctest.IGNORE_EXCEPTION_DETAIL finder = doctest.DocTestFinder() runner = doctest.DocTestRunner(optionflags=flags) context = {'np': numpy, 'pd': pandas} error_msgs = '' for test in finder.find(self.raw_doc, self.method_name, globs=context): f = StringIO() runner.run(test, out=f.write) error_msgs += f.getvalue() return error_msgs def get_api_items(): api_fname = os.path.join(BASE_PATH, 'doc', 'source', 'api.rst') previous_line = current_section = current_subsection = '' position = None with open(api_fname) as f: for line in f: line = line.strip() if len(line) == len(previous_line): if set(line) == set('-'): current_section = previous_line continue if set(line) == set('~'): current_subsection = previous_line continue if line.startswith('.. currentmodule::'): current_module = line.replace('.. currentmodule::', '').strip() continue if line == '.. autosummary::': position = 'autosummary' continue if position == 'autosummary': if line == '': position = 'items' continue if position == 'items': if line == '': position = None continue item = line.strip() func = importlib.import_module(current_module) for part in item.split('.'): func = getattr(func, part) yield ('.'.join([current_module, item]), func, current_section, current_subsection) previous_line = line def _csv_row(func_name, func_obj, section, subsection, in_api, seen={}): obj_type = type(func_obj).__name__ original_callable = _to_original_callable(func_obj) if original_callable is None: return [func_name, obj_type] + [''] * 12, '' else: doc = Docstring(func_name, original_callable) key = doc.source_file_name, doc.source_file_def_line shared_code = seen.get(key, '') return [func_name, obj_type, in_api, int(doc.deprecated), section, subsection, doc.source_file_name, doc.source_file_def_line, doc.github_url, int(bool(doc.summary)), int(bool(doc.extended_summary)), int(doc.correct_parameters), int(bool(doc.examples)), shared_code], key def validate_all(): writer = csv.writer(sys.stdout) cols = ('Function or method', 'Type', 'In API doc', 'Is deprecated', 'Section', 'Subsection', 'File', 'Code line', 'GitHub link', 'Has summary', 'Has extended summary', 'Parameters ok', 'Has examples', 'Shared code with') writer.writerow(cols) seen = {} api_items = list(get_api_items()) for func_name, func, section, subsection in api_items: row, key = _csv_row(func_name, func, section, subsection, in_api=1, seen=seen) seen[key] = func_name writer.writerow(row) api_item_names = set(list(zip(*api_items))[0]) for class_ in (pandas.Series, pandas.DataFrame, pandas.Panel): for member in inspect.getmembers(class_): func_name = 'pandas.{}.{}'.format(class_.__name__, member[0]) if (not member[0].startswith('_') and func_name not in api_item_names): func = _load_obj(func_name) row, key = _csv_row(func_name, func, section='', subsection='', in_api=0) writer.writerow(row) return 0 def validate_one(func_name): """ Validate the docstring for the given func_name Parameters ---------- func_name : function Function whose docstring will be evaluated Returns ------- int The number of errors found in the `func_name` docstring """ func_obj = _load_obj(func_name) doc = Docstring(func_name, func_obj) sys.stderr.write(_output_header('Docstring ({})'.format(func_name))) sys.stderr.write('{}\n'.format(doc.clean_doc)) errs = [] wrns = [] if doc.start_blank_lines != 1: errs.append('Docstring text (summary) should start in the line ' 'immediately after the opening quotes (not in the same ' 'line, or leaving a blank line in between)') if doc.end_blank_lines != 1: errs.append('Closing quotes should be placed in the line after ' 'the last text in the docstring (do not close the ' 'quotes in the same line as the text, or leave a ' 'blank line between the last text and the quotes)') if doc.double_blank_lines: errs.append('Use only one blank line to separate sections or ' 'paragraphs') if not doc.summary: errs.append('No summary found (a short summary in a single line ' 'should be present at the beginning of the docstring)') else: if not doc.summary[0].isupper(): errs.append('Summary does not start with a capital letter') if doc.summary[-1] != '.': errs.append('Summary does not end with a period') if (doc.is_function_or_method and doc.summary.split(' ')[0][-1] == 's'): errs.append('Summary must start with infinitive verb, ' 'not third person (e.g. use "Generate" instead of ' '"Generates")') if doc.num_summary_lines > 1: errs.append("Summary should fit in a single line.") if not doc.extended_summary: wrns.append('No extended summary found') param_errs = doc.parameter_mismatches for param in doc.doc_parameters: if not param.startswith("*"): # Check can ignore var / kwargs if not doc.parameter_type(param): param_errs.append('Parameter "{}" has no type'.format(param)) else: if doc.parameter_type(param)[-1] == '.': param_errs.append('Parameter "{}" type should ' 'not finish with "."'.format(param)) if not doc.parameter_desc(param): param_errs.append('Parameter "{}" ' 'has no description'.format(param)) else: if not doc.parameter_desc(param)[0].isupper(): param_errs.append('Parameter "{}" description ' 'should start with a ' 'capital letter'.format(param)) if doc.parameter_desc(param)[-1] != '.': param_errs.append('Parameter "{}" description ' 'should finish with "."'.format(param)) if param_errs: errs.append('Errors in parameters section') for param_err in param_errs: errs.append('\t{}'.format(param_err)) if doc.is_function_or_method: if not doc.returns and "return" in doc.method_source: errs.append('No Returns section found') if not doc.yields and "yield" in doc.method_source: errs.append('No Yields section found') mentioned_errs = doc.mentioned_private_classes if mentioned_errs: errs.append('Private classes ({}) should not be mentioned in public ' 'docstring.'.format(mentioned_errs)) if not doc.see_also: wrns.append('See Also section not found') else: for rel_name, rel_desc in doc.see_also.items(): if not rel_desc: errs.append('Missing description for ' 'See Also "{}" reference'.format(rel_name)) for line in doc.raw_doc.splitlines(): if re.match("^ *\t", line): errs.append('Tabs found at the start of line "{}", ' 'please use whitespace only'.format(line.lstrip())) examples_errs = '' if not doc.examples: wrns.append('No examples section found') else: examples_errs = doc.examples_errors if examples_errs: errs.append('Examples do not pass tests') sys.stderr.write(_output_header('Validation')) if errs: sys.stderr.write('Errors found:\n') for err in errs: sys.stderr.write('\t{}\n'.format(err)) if wrns: sys.stderr.write('Warnings found:\n') for wrn in wrns: sys.stderr.write('\t{}\n'.format(wrn)) if not errs: sys.stderr.write('Docstring for "{}" correct. :)\n'.format(func_name)) if examples_errs: sys.stderr.write(_output_header('Doctests')) sys.stderr.write(examples_errs) return len(errs) def main(function): if function is None: return validate_all() else: return validate_one(function) if __name__ == '__main__': argparser = argparse.ArgumentParser( description='validate pandas docstrings') argparser.add_argument('function', nargs='?', default=None, help=('function or method to validate ' '(e.g. pandas.DataFrame.head) ' 'if not provided, all docstrings ' 'are validated')) args = argparser.parse_args() sys.exit(main(args.function))
scripts/validate_docstrings.py
18,846
Validate the docstring for the given func_name Parameters ---------- func_name : function Function whose docstring will be evaluated Returns ------- int The number of errors found in the `func_name` docstring Analyze docstrings to detect errors. If no argument is provided, it does a quick check of docstrings and returns a csv with all API functions and results of basic checks. If a function or method is provided in the form "pandas.function", "pandas.module.class.method", etc. a list of all errors in the docstring for the specified function or method. Usage:: $ ./validate_docstrings.py $ ./validate_docstrings.py pandas.DataFrame.head !/usr/bin/env python TODO when py3 only replace by: module, *func_parts = ... TODO(py27): remove ismethod accessor classes have a signature but don't want to show this Some objects, mainly in C extensions do not support introspection of the signature Find and strip out any sphinx directives Only retain any description before the directive Check can ignore var / kwargs
1,034
en
0.578978
import subprocess import math import os from pipes import quote import platform class Sorolla: """ Main class which will launch ImageMagick commands to apply selected transformations to the given images. It needs ImageMagick & GhostScript installed in the system and in PATH to work properly """ @staticmethod def scale_resource(source_file, dest_file, scale): """ Scales a resource; detects if it's a nine-patch via filename in order to scale it properly Arguments: source_file Source file to convert. Path can be relative or absolute dest_file Destination file where the converted file will be saved. Path can be relative or absolute scale Scale value as a float. If it's greater than zero, the function upscales the image; if less than zero, it downscales the image Returns: Whether the action could be run or not """ if not Sorolla._check_needed_commands: return False # Default base density in dpi, set by Imagemagick base_pdf_density_dpi = 72 try: command = "" if ".9." not in source_file: # Not a resource identified as nine-patch density = int(scale * base_pdf_density_dpi) # Scales a vector resource to the desired density command = 'convert -background transparent -density {0} {1} {2}' command = command.format( density, Sorolla._shellquote(source_file), Sorolla._shellquote(dest_file), ) else: # Resource defined as nine-patch # Attributes used in Imagemagick command imagemagick_scale = scale * 100 border_size = math.ceil(scale) # The following ImageMagick command works as follows (each step # generates a temporary image) # # 0. Tell convert the image that we're going to use, and that # we want a transparent background # 1. Create a copy of (0) with our base density (72 DPI) # 2. Remove 9-patch border from (1) and replace it with # color # 3. Mix (1) & (2) so that 9-patch borders are extracted from # the transparent original image # 4. Resize (3) to 'imagemagick_scale'. We get scaled 9-patch # borders, but there will be semi-transparent pixels # 5. Apply a threshold in (4)'s alpha channel so we can make # semi-transparent pixels fully opaque # 6-7. Same process as in 2-3 to extract a bigger 9-patch # border # 8-12. Process to adjust the 9-patch border in (7) so we don't # leave extra space between the border & the image # 13. Create a raster of the original image (0), keeping # original quality if PDF or SVG # 14. Remove 9-patch border of (13) depending on the scale used # 15. Merge (14) with (12) so we finally have the result # 9-patch for the given dpi scale # 16. Delete all generated files in each step # # There might be some pixel data loss in ldpi & hdpi # resolutions as they use float scales to resize the source # files # # In order to debug the process, copy the command to your # console, remove the 'delete' parenthesis block and add # '-append' before the destination file. This'll generate a # .png with all the image steps described by the commands command = 'convert {0} -background transparent '\ '\( +clone -density {1} \) '\ '\( +clone -shave 1x1 -bordercolor transparent -border 1x1 \) '\ '\( -clone 1 +clone -compose ChangeMask -composite -compose Over \) '\ '\( +clone -resize {2}%% \) '\ '\( +clone -channel A -threshold 50%% +channel \) '\ '\( +clone -shave 1x1 -bordercolor transparent -border 1x1 \) ' \ '\( -clone 5 +clone -compose ChangeMask -composite -compose Over \) '\ '\( -clone 7 -repage +{3}+0 -background none -flatten \) '\ '\( -clone 7 -repage +0+{3} -background none -flatten \) '\ '\( -clone 7 -repage -{3}+0 -background none -flatten \) '\ '\( -clone 7 -repage +0-{3} -background none -flatten \) '\ '\( -clone 8 -clone 9 -compose Over -composite -clone 10 -composite -clone 11 -composite -shave {3}x{3} \) '\ '\( -clone 0 -scale {2}% \) '\ '\( +clone -shave {4}x{4} -bordercolor transparent -border 1x1 \) '\ '\( +clone -clone 12 -composite \) '\ '\( -delete 0-14 \) '\ '{5}'.format( Sorolla._shellquote( os.path.abspath(source_file)), base_pdf_density_dpi, imagemagick_scale, border_size - 1, border_size, Sorolla._shellquote(os.path.abspath(dest_file)) ) return Sorolla._run_command(command) except Exception as e: print e.errno, e.strerror return False @staticmethod def color_resource(source_file, dest_file, fill_color): """ Colors a raster resource; detects if it's a nine-patch via filename in order to scale it properly Arguments: source_file Source file to color. Path can be relative or absolute dest_file Destination file where the colored file will be saved. Path can be relative or absolute fill_color Color to fill the resource. Must be a RRGGBB string. Returns: Whether the action could be run or not """ if not Sorolla._check_needed_commands: return False try: command = "" if ".9." not in source_file: # Not a resource identified as nine-patch command = 'convert -background transparent {0} +level-colors "#{1}", '\ '{2}'.format( Sorolla._shellquote( os.path.abspath(source_file)), fill_color, Sorolla._shellquote(os.path.abspath(dest_file)), ) else: # nine-patch command = 'convert -background transparent {0} '\ '\( +clone -shave 1x1 -bordercolor transparent -border 1x1 +level-colors "#{1}", \) '\ '\( -clone 0 +clone -composite \) '\ '\( -delete 0-1 \) '\ '{2}'.format( Sorolla._shellquote( os.path.abspath(source_file)), fill_color, Sorolla._shellquote(os.path.abspath(dest_file)) ) return Sorolla._run_command(command) except Exception as e: print e.value return False @staticmethod def tint_resource(source_file, dest_file, tint_color): """ Tints a gray-scaled raster resource; detects if it's a nine-patch via filename in order to tint it properly Arguments: source_file Source file to tint. Path can be relative or absolute dest_file Destination file where the tinted file will be saved. Path can be relative or absolute fill_color Color to tint the resource. Must be a RRGGBB string. Returns: Whether the action could be run or not """ if not Sorolla._check_needed_commands: return False try: command = "" if ".9." not in source_file: # Not a resource identified as nine-patch # Check http://www.imagemagick.org/Usage/color_mods/#tint_overlay command = 'convert -background transparent {0} '\ '\( +clone +matte -fill "#{1}" -colorize 100%% +clone +swap -compose overlay -composite \) '\ '-compose SrcIn -composite {2}'.format( Sorolla._shellquote( os.path.abspath(source_file)), tint_color, Sorolla._shellquote(os.path.abspath(dest_file)) ) else: # nine-patch command = 'convert -background transparent {0} '\ '\( +clone -shave 1x1 -bordercolor transparent -border 1x1 \) '\ '\( +clone +matte -fill "#{1}" -colorize 100%% \) '\ '\( -clone 0 +clone -compose overlay -composite \) '\ '\( -clone 0 +clone -compose SrcIn -composite \) '\ '\( -delete 0-3 \) {2}'.format( Sorolla._shellquote( os.path.abspath(source_file)), tint_color, Sorolla._shellquote(os.path.abspath(dest_file)) ) return Sorolla._run_command(command) except Exception as e: print e.value return False @staticmethod def _run_command(command): """ Runs a given ImageMagick command """ # Windows check; remove escape sequences from parentheses so cmd can # properly launch the command if Sorolla._is_windows(): command = command.replace('\\(', '(').replace('\\)', ')') return subprocess.call(command, shell=True) == 0 @staticmethod def _shellquote(s): """ Util method to escape data in order to use it in shell commands """ # return "'" + s.replace("'", "'\\''") + "'" # Windows check if not Sorolla._is_windows(): return quote(s) else: return '"{0}"'.format(s) @staticmethod def _check_command(command, args=[]): """ Checks if a command can be executed in the file-system """ devnull = open(os.devnull, 'w') try: status = subprocess.call( [command] + args, stdout=devnull, stderr=devnull) return status == 0 except Exception as e: print e return False @staticmethod def _check_needed_commands(): """ Check needed commands: ImageMagick's convert & GhostScript """ # Imagemagick check if not Sorolla._check_command("convert"): print "Imagemagick is not installed" return False # Ghostscript check if not Sorolla._check_command("gs", ["-version"]): print "GhostScript is not installed" return False return True @staticmethod def _is_windows(): """ Check if the current platform is Windows """ return platform.uname()[0].find("Win") != -1
sorolla/sorolla.py
11,751
Default base density in dpi, set by Imagemagick Not a resource identified as nine-patch Scales a vector resource to the desired density Resource defined as nine-patch Attributes used in Imagemagick command The following ImageMagick command works as follows (each step generates a temporary image) 0. Tell convert the image that we're going to use, and that we want a transparent background 1. Create a copy of (0) with our base density (72 DPI) 2. Remove 9-patch border from (1) and replace it with color 3. Mix (1) & (2) so that 9-patch borders are extracted from the transparent original image 4. Resize (3) to 'imagemagick_scale'. We get scaled 9-patch borders, but there will be semi-transparent pixels 5. Apply a threshold in (4)'s alpha channel so we can make semi-transparent pixels fully opaque 6-7. Same process as in 2-3 to extract a bigger 9-patch border 8-12. Process to adjust the 9-patch border in (7) so we don't leave extra space between the border & the image 13. Create a raster of the original image (0), keeping original quality if PDF or SVG 14. Remove 9-patch border of (13) depending on the scale used 15. Merge (14) with (12) so we finally have the result 9-patch for the given dpi scale 16. Delete all generated files in each step There might be some pixel data loss in ldpi & hdpi resolutions as they use float scales to resize the source files In order to debug the process, copy the command to your console, remove the 'delete' parenthesis block and add '-append' before the destination file. This'll generate a .png with all the image steps described by the commands Not a resource identified as nine-patch nine-patch Not a resource identified as nine-patch Check http://www.imagemagick.org/Usage/color_mods/tint_overlay nine-patch Windows check; remove escape sequences from parentheses so cmd can properly launch the command return "'" + s.replace("'", "'\\''") + "'" Windows check Imagemagick check Ghostscript check
1,982
en
0.754653
#%% # Our numerical workhorses import numpy as np import pandas as pd import itertools # Import libraries to parallelize processes from joblib import Parallel, delayed # Import matplotlib stuff for plotting import matplotlib.pyplot as plt import matplotlib.cm as cm import matplotlib as mpl # Seaborn, useful for graphics import seaborn as sns # Pickle is useful for saving outputs that are computationally expensive # to obtain every time import pickle import os import glob import git # Import the project utils import ccutils #%% # Find home directory for repo repo = git.Repo("./", search_parent_directories=True) homedir = repo.working_dir # Read MaxEnt distributions print('Reading MaxEnt distributions') df_maxEnt_prot = pd.read_csv( "../../data/csv_maxEnt_dist/MaxEnt_Lagrange_mult_protein_IPTG_range.csv" ) # Define dictionaries to map operator to binding energy and rbs to rep copy op_dict = dict(zip(["O1", "O2", "O3"], [-15.3, -13.9, -9.7])) rbs_dict = dict( zip( ["HG104", "RBS1147", "RBS446", "RBS1027", "RBS1", "RBS1L"], [22, 60, 124, 260, 1220, 1740], ) ) # Define sample space mRNA_space = np.array([0]) protein_space = np.arange(0, 1.5E4) # Group df_maxEnt by operator and repressor copy number df_group = df_maxEnt_prot.groupby(["operator", "repressor"]) # Define column names for data frame names = ["operator", "binding_energy", "repressor", "channcap", "pc"] # Initialize data frame to save channel capacity computations df_channcap = pd.DataFrame(columns=names) # Define function to compute in parallel the channel capacity def cc_parallel_protein(df_lagrange): # Build mRNA transition matrix Qpc = ccutils.channcap.trans_matrix_maxent( df_lagrange, mRNA_space, protein_space, False) # Compute the channel capacity with the Blahut-Arimoto algorithm cc_p, pc, _ = ccutils.channcap.channel_capacity(Qpc.T, epsilon=1e-4) # Extract operator and repressor copy number op = df_lagrange.operator.unique()[0] eRA = df_lagrange.binding_energy.unique()[0] rep = df_lagrange.repressor.unique()[0] return [op, eRA, rep, cc_p, pc] print('Running Blahut algorithm in multiple cores') # Run the function in parallel ccaps = Parallel(n_jobs=6)( delayed(cc_parallel_protein)(df_lagrange) for group, df_lagrange in df_group ) # Convert to tidy data frame ccaps = pd.DataFrame(ccaps, columns=names) # Concatenate to data frame df_channcap = pd.concat([df_channcap, ccaps], axis=0) # Save results print('Saving results into memory') df_channcap.to_csv( f"{homedir}/data/csv_maxEnt_dist/chann_cap_multi_prom_protein_IPTG_range.csv", index=False, ) print('Done!')
src/theory/scripts/channcap_protein_multi_prom_iptg_range.py
2,701
%% Our numerical workhorses Import libraries to parallelize processes Import matplotlib stuff for plotting Seaborn, useful for graphics Pickle is useful for saving outputs that are computationally expensive to obtain every time Import the project utils%% Find home directory for repo Read MaxEnt distributions Define dictionaries to map operator to binding energy and rbs to rep copy Define sample space Group df_maxEnt by operator and repressor copy number Define column names for data frame Initialize data frame to save channel capacity computations Define function to compute in parallel the channel capacity Build mRNA transition matrix Compute the channel capacity with the Blahut-Arimoto algorithm Extract operator and repressor copy number Run the function in parallel Convert to tidy data frame Concatenate to data frame Save results
842
en
0.735934
from settings import settings from office365.runtime.auth.authentication_context import AuthenticationContext from office365.sharepoint.caml_query import CamlQuery from office365.sharepoint.client_context import ClientContext list_title = "Survey" view_title = "All Responses" def print_list_views(ctx): """Read list view by title example""" list_object = ctx.web.lists.get_by_title(list_title) views = list_object.views ctx.load(views) ctx.execute_query() for view in views: # print "View title: {0}".format(view.Properties["Title"]) cur_view_title = view.properties["Title"] cur_view = views.get_by_title(cur_view_title) ctx.load(cur_view) ctx.execute_query() print("View title: {0}".format(cur_view.properties["Title"])) def print_view_items(ctx): """Example demonstrates how to retrieve View items""" list_object = ctx.web.lists.get_by_title(list_title) # 1.get View query view = list_object.views.get_by_title(view_title) ctx.load(view, ["ViewQuery"]) ctx.execute_query() # 2.get View fields view_fields = view.view_fields ctx.load(view_fields) ctx.execute_query() # 3.get items for View query qry = CamlQuery() qry.ViewXml = "<View><Where>{0}</Where></View>".format(view.properties["ViewQuery"]) items = list_object.get_items(qry) ctx.load(items) ctx.execute_query() for item in items: print("Item title: {0}".format(item.properties["Title"])) if __name__ == '__main__': ctx_auth = AuthenticationContext(url=settings['url']) if ctx_auth.acquire_token_for_user(username=settings['user_credentials']['username'], password=settings['user_credentials']['password']): ctx = ClientContext(settings['url'], ctx_auth) # print_list_views(ctx) print_view_items(ctx) else: print(ctx_auth.get_last_error())
examples/sharepoint/view_operations.py
1,946
Read list view by title example Example demonstrates how to retrieve View items print "View title: {0}".format(view.Properties["Title"]) 1.get View query 2.get View fields 3.get items for View query print_list_views(ctx)
222
en
0.544039
from transform import Transform import tensorflow as tf class StyleTransferTester: def __init__(self, session, content_image, model_path): # session self.sess = session # input images self.x0 = content_image # input model self.model_path = model_path # image transform network self.transform = Transform() # build graph for style transfer self._build_graph() def _build_graph(self): # graph input self.x = tf.placeholder(tf.float32, shape=self.x0.shape, name='input') self.xi = tf.expand_dims(self.x, 0) # add one dim for batch # result image from transform-net self.y_hat = self.transform.net(self.xi/255.0) self.y_hat = tf.squeeze(self.y_hat) # remove one dim for batch self.y_hat = tf.clip_by_value(self.y_hat, 0., 255.) def test(self): # initialize parameters self.sess.run(tf.global_variables_initializer()) # load pre-trained model saver = tf.train.Saver() saver.restore(self.sess, self.model_path) # get transformed image output = self.sess.run(self.y_hat, feed_dict={self.x: self.x0}) return output
style_transfer_tester.py
1,240
session input images input model image transform network build graph for style transfer graph input add one dim for batch result image from transform-net remove one dim for batch initialize parameters load pre-trained model get transformed image
245
en
0.60208
from django.db import models from .validators import validate_resume_ext class Resume(models.Model): name = models.CharField(max_length = 20) phone = models.IntegerField() email = models.EmailField() resume = models.FileField(upload_to='resume/%Y/%m/%d/', validators=[validate_resume_ext]) uploaded_at = models.DateTimeField(auto_now_add=True) #Add name, phone number and email fields
rapidez/resumeAnalysis/models.py
406
Add name, phone number and email fields
39
en
0.516668
# Configuration file for the Sphinx documentation builder. # # This file only contains a selection of the most common options. For a full # list see the documentation: # https://www.sphinx-doc.org/en/master/usage/configuration.html # -- Path setup -------------------------------------------------------------- # If extensions (or modules to document with autodoc) are in another directory, # add these directories to sys.path here. If the directory is relative to the # documentation root, use os.path.abspath to make it absolute, like shown here. # # import os # import sys # sys.path.insert(0, os.path.abspath('.')) # -- Project information ----------------------------------------------------- project = "SeqAL" copyright = "2020, Xu Liang" author = "Xu Liang" # -- General configuration --------------------------------------------------- # Add any Sphinx extension module names here, as strings. They can be # extensions coming with Sphinx (named 'sphinx.ext.*') or your custom # ones. extensions = [ "myst_parser", ] # The suffix of source filenames. source_suffix = [".rst", ".md"] # Add any paths that contain templates here, relative to this directory. templates_path = ["_templates"] # List of patterns, relative to source directory, that match files and # directories to ignore when looking for source files. # This pattern also affects html_static_path and html_extra_path. exclude_patterns = [] # -- Options for HTML output ------------------------------------------------- # The theme to use for HTML and HTML Help pages. See the documentation for # a list of builtin themes. # html_theme = "sphinx_rtd_theme" # Add any paths that contain custom static files (such as style sheets) here, # relative to this directory. They are copied after the builtin static files, # so a file named "default.css" will overwrite the builtin "default.css". html_static_path = ["_static"]
docs/source/conf.py
1,906
Configuration file for the Sphinx documentation builder. This file only contains a selection of the most common options. For a full list see the documentation: https://www.sphinx-doc.org/en/master/usage/configuration.html -- Path setup -------------------------------------------------------------- If extensions (or modules to document with autodoc) are in another directory, add these directories to sys.path here. If the directory is relative to the documentation root, use os.path.abspath to make it absolute, like shown here. import os import sys sys.path.insert(0, os.path.abspath('.')) -- Project information ----------------------------------------------------- -- General configuration --------------------------------------------------- Add any Sphinx extension module names here, as strings. They can be extensions coming with Sphinx (named 'sphinx.ext.*') or your custom ones. The suffix of source filenames. Add any paths that contain templates here, relative to this directory. List of patterns, relative to source directory, that match files and directories to ignore when looking for source files. This pattern also affects html_static_path and html_extra_path. -- Options for HTML output ------------------------------------------------- The theme to use for HTML and HTML Help pages. See the documentation for a list of builtin themes. Add any paths that contain custom static files (such as style sheets) here, relative to this directory. They are copied after the builtin static files, so a file named "default.css" will overwrite the builtin "default.css".
1,578
en
0.665531
# -*- coding: utf-8 -*- if __name__ == "__main__": raise Exception("Test files can't be run directly. Use `python -m pytest greenery`") import pytest from greenery.fsm import fsm, null, epsilon, anything_else def test_addbug(): # Odd bug with fsm.__add__(), exposed by "[bc]*c" int5A = fsm( alphabet = {"a", "b", "c", anything_else}, states = {0, 1}, initial = 1, finals = {1}, map = { 0: {anything_else: 0, "a": 0, "b": 0, "c": 0}, 1: {anything_else: 0, "a": 0, "b": 1, "c": 1}, } ) assert int5A.accepts("") int5B = fsm( alphabet = {"a", "b", "c", anything_else}, states = {0, 1, 2}, initial = 1, finals = {0}, map = { 0: {anything_else: 2, "a": 2, "b": 2, "c": 2}, 1: {anything_else: 2, "a": 2, "b": 2, "c": 0}, 2: {anything_else: 2, "a": 2, "b": 2, "c": 2}, } ) assert int5B.accepts("c") int5C = int5A + int5B assert int5C.accepts("c") # assert int5C.initial == 0 def test_builtins(): assert not null("a").accepts("a") assert epsilon("a").accepts("") assert not epsilon("a").accepts("a") @pytest.fixture def a(): a = fsm( alphabet = {"a", "b"}, states = {0, 1, "ob"}, initial = 0, finals = {1}, map = { 0 : {"a" : 1 , "b" : "ob"}, 1 : {"a" : "ob", "b" : "ob"}, "ob" : {"a" : "ob", "b" : "ob"}, }, ) return a def test_a(a): assert not a.accepts("") assert a.accepts("a") assert not a.accepts("b") @pytest.fixture def b(): b = fsm( alphabet = {"a", "b"}, states = {0, 1, "ob"}, initial = 0, finals = {1}, map = { 0 : {"a" : "ob", "b" : 1 }, 1 : {"a" : "ob", "b" : "ob"}, "ob" : {"a" : "ob", "b" : "ob"}, }, ) return b def test_b(b): assert not b.accepts("") assert not b.accepts("a") assert b.accepts("b") def test_concatenation_aa(a): concAA = a + a assert not concAA.accepts("") assert not concAA.accepts("a") assert concAA.accepts("aa") assert not concAA.accepts("aaa") concAA = epsilon({"a", "b"}) + a + a assert not concAA.accepts("") assert not concAA.accepts("a") assert concAA.accepts("aa") assert not concAA.accepts("aaa") def test_concatenation_ab(a, b): concAB = a + b assert not concAB.accepts("") assert not concAB.accepts("a") assert not concAB.accepts("b") assert not concAB.accepts("aa") assert concAB.accepts("ab") assert not concAB.accepts("ba") assert not concAB.accepts("bb") def test_alternation_a(a): altA = a | null({"a", "b"}) assert not altA.accepts("") assert altA.accepts("a") def test_alternation_ab(a, b): altAB = a | b assert not altAB.accepts("") assert altAB.accepts("a") assert altAB.accepts("b") assert not altAB.accepts("aa") assert not altAB.accepts("ab") assert not altAB.accepts("ba") assert not altAB.accepts("bb") def test_star(a): starA = a.star() assert starA.accepts("") assert starA.accepts("a") assert not starA.accepts("b") assert starA.accepts("aaaaaaaaa") def test_multiply_0(a): zeroA = a * 0 assert zeroA.accepts("") assert not zeroA.accepts("a") def test_multiply_1(a): oneA = a * 1 assert not oneA.accepts("") assert oneA.accepts("a") assert not oneA.accepts("aa") def test_multiply_2(a): twoA = a * 2 assert not twoA.accepts("") assert not twoA.accepts("a") assert twoA.accepts("aa") assert not twoA.accepts("aaa") def test_multiply_7(a): sevenA = a * 7 assert not sevenA.accepts("aaaaaa") assert sevenA.accepts("aaaaaaa") assert not sevenA.accepts("aaaaaaaa") def test_optional_mul(a, b): unit = a + b # accepts "ab" optional = (epsilon(a.alphabet) | unit) # accepts "(ab)? assert optional.accepts([]) assert not optional.accepts(["a"]) assert not optional.accepts(["b"]) assert optional.accepts(["a", "b"]) assert not optional.accepts(["a", "a"]) optional = optional * 2 # accepts "(ab)?(ab)?" assert optional.accepts([]) assert not optional.accepts(["a"]) assert not optional.accepts(["b"]) assert not optional.accepts(["a", "a"]) assert optional.accepts(["a", "b"]) assert not optional.accepts(["b", "a"]) assert not optional.accepts(["b", "b"]) assert not optional.accepts(["a", "a", "a"]) assert optional.accepts(["a", "b", "a", "b"]) def test_intersection_ab(a, b): intAB = a & b assert not intAB.accepts("") assert not intAB.accepts("a") assert not intAB.accepts("b") def test_negation(a): everythingbutA = a.everythingbut() assert everythingbutA.accepts("") assert not everythingbutA.accepts("a") assert everythingbutA.accepts("b") assert everythingbutA.accepts("aa") assert everythingbutA.accepts("ab") def test_crawl_reduction(): # this is "0*1" in heavy disguise. crawl should resolve this duplication # Notice how states 2 and 3 behave identically. When resolved together, # states 1 and 2&3 also behave identically, so they, too should be resolved # (this is impossible to spot before 2 and 3 have been combined). # Finally, the oblivion state should be omitted. merged = fsm( alphabet = {"0", "1"}, states = {1, 2, 3, 4, "oblivion"}, initial = 1, finals = {4}, map = { 1 : {"0" : 2 , "1" : 4 }, 2 : {"0" : 3 , "1" : 4 }, 3 : {"0" : 3 , "1" : 4 }, 4 : {"0" : "oblivion", "1" : "oblivion"}, "oblivion" : {"0" : "oblivion", "1" : "oblivion"}, } ).reduce() assert len(merged.states) == 2 def test_bug_28(): # This is (ab*)* and it caused some defects. abstar = fsm( alphabet = {'a', 'b'}, states = {0, 1}, initial = 0, finals = {1}, map = { 0: {'a': 1}, 1: {'b': 1} } ) assert abstar.accepts("a") assert not abstar.accepts("b") assert abstar.accepts("ab") assert abstar.accepts("abb") abstarstar = abstar.star() assert abstarstar.accepts("a") assert not abstarstar.accepts("b") assert abstarstar.accepts("ab") assert not abstar.star().accepts("bb") def test_star_advanced(): # This is (a*ba)*. Naively connecting the final states to the initial state # gives the incorrect result here. starred = fsm( alphabet = {"a", "b"}, states = {0, 1, 2, "oblivion"}, initial = 0, finals = {2}, map = { 0 : {"a" : 0 , "b" : 1 }, 1 : {"a" : 2 , "b" : "oblivion"}, 2 : {"a" : "oblivion", "b" : "oblivion"}, "oblivion" : {"a" : "oblivion", "b" : "oblivion"}, } ).star() assert starred.alphabet == frozenset(["a", "b"]) assert starred.accepts("") assert not starred.accepts("a") assert not starred.accepts("b") assert not starred.accepts("aa") assert starred.accepts("ba") assert starred.accepts("aba") assert starred.accepts("aaba") assert not starred.accepts("aabb") assert starred.accepts("abababa") def test_reduce(): # FSM accepts no strings but has 3 states, needs only 1 asdf = fsm( alphabet = {None}, states = {0, 1, 2}, initial = 0, finals = {1}, map = { 0 : {None : 2}, 1 : {None : 2}, 2 : {None : 2}, }, ) asdf = asdf.reduce() assert len(asdf.states) == 1 def test_reverse_abc(): abc = fsm( alphabet = {"a", "b", "c"}, states = {0, 1, 2, 3, None}, initial = 0, finals = {3}, map = { 0 : {"a" : 1 , "b" : None, "c" : None}, 1 : {"a" : None, "b" : 2 , "c" : None}, 2 : {"a" : None, "b" : None, "c" : 3 }, 3 : {"a" : None, "b" : None, "c" : None}, None : {"a" : None, "b" : None, "c" : None}, }, ) cba = reversed(abc) assert cba.accepts("cba") def test_reverse_brzozowski(): # This is (a|b)*a(a|b) brzozowski = fsm( alphabet = {"a", "b"}, states = {"A", "B", "C", "D", "E"}, initial = "A", finals = {"C", "E"}, map = { "A" : {"a" : "B", "b" : "D"}, "B" : {"a" : "C", "b" : "E"}, "C" : {"a" : "C", "b" : "E"}, "D" : {"a" : "B", "b" : "D"}, "E" : {"a" : "B", "b" : "D"}, }, ) assert brzozowski.accepts("aa") assert brzozowski.accepts("ab") assert brzozowski.accepts("aab") assert brzozowski.accepts("bab") assert brzozowski.accepts("abbbbbbbab") assert not brzozowski.accepts("") assert not brzozowski.accepts("a") assert not brzozowski.accepts("b") assert not brzozowski.accepts("ba") assert not brzozowski.accepts("bb") assert not brzozowski.accepts("bbbbbbbbbbbb") # So this is (a|b)a(a|b)* b2 = reversed(brzozowski) assert b2.accepts("aa") assert b2.accepts("ba") assert b2.accepts("baa") assert b2.accepts("bab") assert b2.accepts("babbbbbbba") assert not b2.accepts("") assert not b2.accepts("a") assert not b2.accepts("b") assert not b2.accepts("ab") assert not b2.accepts("bb") assert not b2.accepts("bbbbbbbbbbbb") # Test string generator functionality. gen = b2.strings() assert next(gen) == ["a", "a"] assert next(gen) == ["b", "a"] assert next(gen) == ["a", "a", "a"] assert next(gen) == ["a", "a", "b"] assert next(gen) == ["b", "a", "a"] assert next(gen) == ["b", "a", "b"] assert next(gen) == ["a", "a", "a", "a"] def test_reverse_epsilon(): # epsilon reversed is epsilon assert reversed(epsilon("a")).accepts("") def test_binary_3(): # Binary numbers divisible by 3. # Disallows the empty string # Allows "0" on its own, but not leading zeroes. div3 = fsm( alphabet = {"0", "1"}, states = {"initial", "zero", 0, 1, 2, None}, initial = "initial", finals = {"zero", 0}, map = { "initial" : {"0" : "zero", "1" : 1 }, "zero" : {"0" : None , "1" : None}, 0 : {"0" : 0 , "1" : 1 }, 1 : {"0" : 2 , "1" : 0 }, 2 : {"0" : 1 , "1" : 2 }, None : {"0" : None , "1" : None}, }, ) assert not div3.accepts("") assert div3.accepts("0") assert not div3.accepts("1") assert not div3.accepts("00") assert not div3.accepts("01") assert not div3.accepts("10") assert div3.accepts("11") assert not div3.accepts("000") assert not div3.accepts("001") assert not div3.accepts("010") assert not div3.accepts("011") assert not div3.accepts("100") assert not div3.accepts("101") assert div3.accepts("110") assert not div3.accepts("111") assert not div3.accepts("0000") assert not div3.accepts("0001") assert not div3.accepts("0010") assert not div3.accepts("0011") assert not div3.accepts("0100") assert not div3.accepts("0101") assert not div3.accepts("0110") assert not div3.accepts("0111") assert not div3.accepts("1000") assert div3.accepts("1001") def test_invalid_fsms(): # initial state 1 is not a state try: fsm( alphabet = {}, states = {}, initial = 1, finals = set(), map = {} ) assert False except AssertionError: assert False except Exception: pass # final state 2 not a state try: fsm( alphabet = {}, states = {1}, initial = 1, finals = {2}, map = {} ) assert False except AssertionError: assert False except Exception: pass # invalid transition for state 1, symbol "a" try: fsm( alphabet = {"a"}, states = {1}, initial = 1, finals = set(), map = { 1 : {"a" : 2} } ) assert False except AssertionError: assert False except Exception: pass def test_bad_multiplier(a): try: x = a * -1 assert False except AssertionError: assert False except Exception: pass def test_anything_else_acceptance(): a = fsm( alphabet = {"a", "b", "c", anything_else}, states = {1}, initial = 1, finals = {1}, map = { 1 : {"a" : 1, "b" : 1, "c" : 1, anything_else : 1} }, ) assert a.accepts("d") def test_difference(a, b): aorb = fsm( alphabet = {"a", "b"}, states = {0, 1, None}, initial = 0, finals = {1}, map = { 0 : {"a" : 1 , "b" : 1 }, 1 : {"a" : None, "b" : None}, None : {"a" : None, "b" : None}, }, ) assert list((a ^ a).strings()) == [] assert list((b ^ b).strings()) == [] assert list((a ^ b).strings()) == [["a"], ["b"]] assert list((aorb ^ a).strings()) == [["b"]] def test_empty(a, b): assert not a.empty() assert not b.empty() assert fsm( alphabet = {}, states = {0, 1}, initial = 0, finals = {1}, map = {0:{}, 1:{}}, ).empty() assert not fsm( alphabet = {}, states = {0}, initial = 0, finals = {0}, map = {0:{}}, ).empty() assert fsm( alphabet = {"a", "b"}, states = {0, 1, None, 2}, initial = 0, finals = {2}, map = { 0 : {"a" : 1 , "b" : 1 }, 1 : {"a" : None, "b" : None}, None : {"a" : None, "b" : None}, 2 : {"a" : None, "b" : None}, }, ).empty() def test_equivalent(a, b): assert (a | b).equivalent(b | a) def test_dead_default(): ''' You may now omit a transition, or even an entire state, from the map. This affects every usage of `fsm.map`. ''' blockquote = fsm( alphabet = {"/", "*", anything_else}, states = {0, 1, 2, 3, 4, 5}, initial = 0, finals = {4}, map = { 0 : {"/" : 1}, 1 : {"*" : 2}, 2 : {"/" : 2, anything_else : 2, "*" : 3}, 3 : {"/" : 4, anything_else : 2, "*" : 3}, } ) assert blockquote.accepts(["/", "*", "whatever", "*", "/"]) assert not blockquote.accepts(["*", "*", "whatever", "*", "/"]) str(blockquote) # test stringification blockquote | blockquote blockquote & blockquote blockquote ^ blockquote reversed(blockquote) assert not blockquote.everythingbut().accepts(["/", "*", "whatever", "*", "/"]) assert blockquote.everythingbut().accepts(["*"]) # deliberately seek oblivion assert blockquote.islive(3) assert blockquote.islive(4) assert not blockquote.islive(5) gen = blockquote.strings() assert next(gen) == ["/", "*", "*", "/"] def test_alphabet_unions(): # Thanks to sparse maps it should now be possible to compute the union of FSMs # with disagreeing alphabets! a = fsm( alphabet = {"a"}, states = {0, 1}, initial = 0, finals = {1}, map = { 0 : {"a" : 1}, }, ) b = fsm( alphabet = {"b"}, states = {0, 1}, initial = 0, finals = {1}, map = { 0 : {"b" : 1}, }, ) assert (a | b).accepts(["a"]) assert (a | b).accepts(["b"]) assert (a & b).empty() assert (a + b).accepts(["a", "b"]) assert (a ^ b).accepts(["a"]) assert (a ^ b).accepts(["b"]) def test_repr(): assert repr(anything_else) == "anything_else" assert str(anything_else) == "anything_else" def test_new_set_methods(a, b): # A whole bunch of new methods were added to the FSM module to enable FSMs to # function exactly as if they were sets of strings (symbol lists), see: # https://docs.python.org/3/library/stdtypes.html#set-types-set-frozenset # But do they work? assert len(a) == 1 assert len((a | b) * 4) == 16 try: len(a.star()) assert False except OverflowError: pass # "in" assert "a" in a assert not "a" in b assert "a" not in b # List comprehension! four = (a | b) * 2 for string in four: assert string == ["a", "a"] break assert [s for s in four] == [["a", "a"], ["a", "b"], ["b", "a"], ["b", "b"]] # set.union() imitation assert fsm.union(a, b) == a.union(b) assert len(fsm.union()) == 0 assert fsm.intersection(a, b) == a.intersection(b) # This takes a little explaining. In general, `a & b & c` is equivalent to # `EVERYTHING & a & b & c` where `EVERYTHING` is an FSM accepting every # possible string. Similarly `a` is equivalent to `EVERYTHING & a`, and the # intersection of no sets at all is... `EVERYTHING`. # However, since we compute the union of alphabets, and there are no # alphabets, the union is the empty set. So the only string which `EVERYTHING` # actually recognises is the empty string, [] (or "" if you prefer). int_none = fsm.intersection() assert len(int_none) == 1 assert [] in int_none assert (a | b).difference(a) == fsm.difference((a | b), a) == (a | b) - a == b assert (a | b).difference(a, b) == fsm.difference((a | b), a, b) == (a | b) - a - b == null("ab") assert a.symmetric_difference(b) == fsm.symmetric_difference(a, b) == a ^ b assert a.isdisjoint(b) assert a <= (a | b) assert a < (a | b) assert a != (a | b) assert (a | b) > a assert (a | b) >= a assert list(a.concatenate(a, a).strings()) == [["a", "a", "a"]] assert list(a.concatenate().strings()) == [["a"]] assert list(fsm.concatenate(b, a, b).strings()) == [["b", "a", "b"]] assert list(fsm.concatenate().strings()) == [] assert not a.copy() is a def test_oblivion_crawl(a): # When crawling a new FSM, we should avoid generating an oblivion state. # `abc` has no oblivion state... all the results should not as well! abc = fsm( alphabet = {"a", "b", "c"}, states = {0, 1, 2, 3}, initial = 0, finals = {3}, map = { 0 : {"a" : 1}, 1 : {"b" : 2}, 2 : {"c" : 3}, } ) assert len((abc + abc).states) == 7 assert len(abc.star().states) == 3 assert len((abc * 3).states) == 10 assert len(reversed(abc).states) == 4 assert len((abc | abc).states) == 4 assert len((abc & abc).states) == 4 assert len((abc ^ abc).states) == 1 assert len((abc - abc).states) == 1 def test_concatenate_bug(a): # This exposes a defect in fsm.concatenate. assert fsm.concatenate(a, epsilon({"a"}), a).accepts("aa") assert fsm.concatenate(a, epsilon({"a"}), epsilon({"a"}), a).accepts("aa") def test_derive(a, b): # Just some basic tests because this is mainly a regex thing. assert a.derive("a") == epsilon({"a", "b"}) assert a.derive("b") == null({"a", "b"}) try: a.derive("c") assert False except KeyError: assert True assert (a * 3).derive("a") == a * 2 assert (a.star() - epsilon({"a", "b"})).derive("a") == a.star() def test_bug_36(): etc1 = fsm( alphabet = {anything_else}, states = {0}, initial = 0, finals = {0}, map = { 0: { anything_else: 0 } } ) etc2 = fsm( alphabet = {'s', anything_else}, states = {0, 1}, initial = 0, finals = {1}, map = { 0: { 's': 1 }, 1: { 's': 1, anything_else: 1 } } ) both = etc1 & etc2 assert etc1.accepts(["s"]) assert etc2.accepts(["s"]) assert both.alphabet == {anything_else, "s"} assert both.accepts(["s"]) def test_add_anything_else(): fsm1=fsm( # [^a] alphabet={"a",anything_else}, states={0,1}, initial=0, finals={1}, map={0:{anything_else:1}} ) fsm2=fsm( # [^b] alphabet={"b",anything_else}, states={0,1}, initial=0, finals={1}, map={0:{anything_else:1}} ) assert (fsm1+fsm2).accepts("ba")
greenery/fsm_test.py
18,126
You may now omit a transition, or even an entire state, from the map. This affects every usage of `fsm.map`. -*- coding: utf-8 -*- Odd bug with fsm.__add__(), exposed by "[bc]*c" assert int5C.initial == 0 accepts "ab" accepts "(ab)? accepts "(ab)?(ab)?" this is "0*1" in heavy disguise. crawl should resolve this duplication Notice how states 2 and 3 behave identically. When resolved together, states 1 and 2&3 also behave identically, so they, too should be resolved (this is impossible to spot before 2 and 3 have been combined). Finally, the oblivion state should be omitted. This is (ab*)* and it caused some defects. This is (a*ba)*. Naively connecting the final states to the initial state gives the incorrect result here. FSM accepts no strings but has 3 states, needs only 1 This is (a|b)*a(a|b) So this is (a|b)a(a|b)* Test string generator functionality. epsilon reversed is epsilon Binary numbers divisible by 3. Disallows the empty string Allows "0" on its own, but not leading zeroes. initial state 1 is not a state final state 2 not a state invalid transition for state 1, symbol "a" test stringification deliberately seek oblivion Thanks to sparse maps it should now be possible to compute the union of FSMs with disagreeing alphabets! A whole bunch of new methods were added to the FSM module to enable FSMs to function exactly as if they were sets of strings (symbol lists), see: https://docs.python.org/3/library/stdtypes.htmlset-types-set-frozenset But do they work? "in" List comprehension! set.union() imitation This takes a little explaining. In general, `a & b & c` is equivalent to `EVERYTHING & a & b & c` where `EVERYTHING` is an FSM accepting every possible string. Similarly `a` is equivalent to `EVERYTHING & a`, and the intersection of no sets at all is... `EVERYTHING`. However, since we compute the union of alphabets, and there are no alphabets, the union is the empty set. So the only string which `EVERYTHING` actually recognises is the empty string, [] (or "" if you prefer). When crawling a new FSM, we should avoid generating an oblivion state. `abc` has no oblivion state... all the results should not as well! This exposes a defect in fsm.concatenate. Just some basic tests because this is mainly a regex thing. [^a] [^b]
2,264
en
0.90102
"""Tools for constructing domains for expressions. """ from sympy.core import sympify from sympy.core.evalf import pure_complex from sympy.polys.domains import ZZ, QQ, ZZ_I, QQ_I, EX from sympy.polys.domains.complexfield import ComplexField from sympy.polys.domains.realfield import RealField from sympy.polys.polyoptions import build_options from sympy.polys.polyutils import parallel_dict_from_basic from sympy.utilities import public def _construct_simple(coeffs, opt): """Handle simple domains, e.g.: ZZ, QQ, RR and algebraic domains. """ rationals = floats = complexes = algebraics = False float_numbers = [] if opt.extension is True: is_algebraic = lambda coeff: coeff.is_number and coeff.is_algebraic else: is_algebraic = lambda coeff: False for coeff in coeffs: if coeff.is_Rational: if not coeff.is_Integer: rationals = True elif coeff.is_Float: if algebraics: # there are both reals and algebraics -> EX return False else: floats = True float_numbers.append(coeff) else: is_complex = pure_complex(coeff) if is_complex: complexes = True x, y = is_complex if x.is_Rational and y.is_Rational: if not (x.is_Integer and y.is_Integer): rationals = True continue else: floats = True if x.is_Float: float_numbers.append(x) if y.is_Float: float_numbers.append(y) if is_algebraic(coeff): if floats: # there are both algebraics and reals -> EX return False algebraics = True else: # this is a composite domain, e.g. ZZ[X], EX return None # Use the maximum precision of all coefficients for the RR or CC # precision max_prec = max(c._prec for c in float_numbers) if float_numbers else 53 if algebraics: domain, result = _construct_algebraic(coeffs, opt) else: if floats and complexes: domain = ComplexField(prec=max_prec) elif floats: domain = RealField(prec=max_prec) elif rationals or opt.field: domain = QQ_I if complexes else QQ else: domain = ZZ_I if complexes else ZZ result = [domain.from_sympy(coeff) for coeff in coeffs] return domain, result def _construct_algebraic(coeffs, opt): """We know that coefficients are algebraic so construct the extension. """ from sympy.polys.numberfields import primitive_element result, exts = [], set() for coeff in coeffs: if coeff.is_Rational: coeff = (None, 0, QQ.from_sympy(coeff)) else: a = coeff.as_coeff_add()[0] coeff -= a b = coeff.as_coeff_mul()[0] coeff /= b exts.add(coeff) a = QQ.from_sympy(a) b = QQ.from_sympy(b) coeff = (coeff, b, a) result.append(coeff) exts = list(exts) g, span, H = primitive_element(exts, ex=True, polys=True) root = sum([ s*ext for s, ext in zip(span, exts) ]) domain, g = QQ.algebraic_field((g, root)), g.rep.rep for i, (coeff, a, b) in enumerate(result): if coeff is not None: coeff = a*domain.dtype.from_list(H[exts.index(coeff)], g, QQ) + b else: coeff = domain.dtype.from_list([b], g, QQ) result[i] = coeff return domain, result def _construct_composite(coeffs, opt): """Handle composite domains, e.g.: ZZ[X], QQ[X], ZZ(X), QQ(X). """ numers, denoms = [], [] for coeff in coeffs: numer, denom = coeff.as_numer_denom() numers.append(numer) denoms.append(denom) polys, gens = parallel_dict_from_basic(numers + denoms) # XXX: sorting if not gens: return None if opt.composite is None: if any(gen.is_number and gen.is_algebraic for gen in gens): return None # generators are number-like so lets better use EX all_symbols = set() for gen in gens: symbols = gen.free_symbols if all_symbols & symbols: return None # there could be algebraic relations between generators else: all_symbols |= symbols n = len(gens) k = len(polys)//2 numers = polys[:k] denoms = polys[k:] if opt.field: fractions = True else: fractions, zeros = False, (0,)*n for denom in denoms: if len(denom) > 1 or zeros not in denom: fractions = True break coeffs = set() if not fractions: for numer, denom in zip(numers, denoms): denom = denom[zeros] for monom, coeff in numer.items(): coeff /= denom coeffs.add(coeff) numer[monom] = coeff else: for numer, denom in zip(numers, denoms): coeffs.update(list(numer.values())) coeffs.update(list(denom.values())) rationals = floats = complexes = False float_numbers = [] for coeff in coeffs: if coeff.is_Rational: if not coeff.is_Integer: rationals = True elif coeff.is_Float: floats = True float_numbers.append(coeff) else: is_complex = pure_complex(coeff) if is_complex is not None: complexes = True x, y = is_complex if x.is_Rational and y.is_Rational: if not (x.is_Integer and y.is_Integer): rationals = True else: floats = True if x.is_Float: float_numbers.append(x) if y.is_Float: float_numbers.append(y) max_prec = max(c._prec for c in float_numbers) if float_numbers else 53 if floats and complexes: ground = ComplexField(prec=max_prec) elif floats: ground = RealField(prec=max_prec) elif complexes: if rationals: ground = QQ_I else: ground = ZZ_I elif rationals: ground = QQ else: ground = ZZ result = [] if not fractions: domain = ground.poly_ring(*gens) for numer in numers: for monom, coeff in numer.items(): numer[monom] = ground.from_sympy(coeff) result.append(domain(numer)) else: domain = ground.frac_field(*gens) for numer, denom in zip(numers, denoms): for monom, coeff in numer.items(): numer[monom] = ground.from_sympy(coeff) for monom, coeff in denom.items(): denom[monom] = ground.from_sympy(coeff) result.append(domain((numer, denom))) return domain, result def _construct_expression(coeffs, opt): """The last resort case, i.e. use the expression domain. """ domain, result = EX, [] for coeff in coeffs: result.append(domain.from_sympy(coeff)) return domain, result @public def construct_domain(obj, **args): """Construct a minimal domain for the list of coefficients. """ opt = build_options(args) if hasattr(obj, '__iter__'): if isinstance(obj, dict): if not obj: monoms, coeffs = [], [] else: monoms, coeffs = list(zip(*list(obj.items()))) else: coeffs = obj else: coeffs = [obj] coeffs = list(map(sympify, coeffs)) result = _construct_simple(coeffs, opt) if result is not None: if result is not False: domain, coeffs = result else: domain, coeffs = _construct_expression(coeffs, opt) else: if opt.composite is False: result = None else: result = _construct_composite(coeffs, opt) if result is not None: domain, coeffs = result else: domain, coeffs = _construct_expression(coeffs, opt) if hasattr(obj, '__iter__'): if isinstance(obj, dict): return domain, dict(list(zip(monoms, coeffs))) else: return domain, coeffs else: return domain, coeffs[0]
sympy/polys/constructor.py
8,617
We know that coefficients are algebraic so construct the extension. Handle composite domains, e.g.: ZZ[X], QQ[X], ZZ(X), QQ(X). The last resort case, i.e. use the expression domain. Handle simple domains, e.g.: ZZ, QQ, RR and algebraic domains. Construct a minimal domain for the list of coefficients. Tools for constructing domains for expressions. there are both reals and algebraics -> EX there are both algebraics and reals -> EX this is a composite domain, e.g. ZZ[X], EX Use the maximum precision of all coefficients for the RR or CC precision XXX: sorting generators are number-like so lets better use EX there could be algebraic relations between generators
673
en
0.805541
import keras import os from keras import losses from keras.models import Model from keras.layers import Input,merge, concatenate, Conv2D, MaxPooling2D, Activation, UpSampling2D,Dropout,Conv2DTranspose,add,multiply,Flatten,Dense from keras.layers.normalization import BatchNormalization as bn from keras.callbacks import ModelCheckpoint, TensorBoard from keras.optimizers import RMSprop from keras import regularizers from keras import backend as K from keras.optimizers import Adam from keras.callbacks import ModelCheckpoint import numpy as np import cv2 class finalNetwork: def __init__(self, images_dir, clustering_dir, classfication_dir, output_dir = None): """ thie function initializes the network class :param images_dir: :param clustering_dir: :param classfication_dir: """ self.images_dir = images_dir self.clustering_dir = clustering_dir self.classification_dir = classfication_dir self.model = None self.output_dir = output_dir self.model_file_name = 'finalModel.h5' def load_model(self): """ this function loads model from file """ if os.path.isfile(self.model_file_name): self.model = keras.models.load_model(self.model_file_name) def UNet(self,input_shape,learn_rate=1e-3): l2_lambda = 0.0002 DropP = 0.3 kernel_size=3 inputs = Input(input_shape) conv1a = Conv2D( 12, (kernel_size, kernel_size), activation='relu', padding='same', kernel_regularizer=regularizers.l2(l2_lambda) )(inputs) conv1a = bn()(conv1a) conv1b = Conv2D(12, (kernel_size, kernel_size), activation='relu', padding='same', kernel_regularizer=regularizers.l2(l2_lambda) )(conv1a) conv1b = bn()(conv1b) merge1=concatenate([conv1a,conv1b]) conv1c = Conv2D(12, (kernel_size, kernel_size), activation='relu', padding='same', kernel_regularizer=regularizers.l2(l2_lambda) )(merge1) conv1c = bn()(conv1c) merge2=concatenate([conv1a,conv1b,conv1c]) conv1d = Conv2D(32, (kernel_size, kernel_size), activation='relu', padding='same', kernel_regularizer=regularizers.l2(l2_lambda) )(merge2) conv1d = bn()(conv1d) pool1 = MaxPooling2D(pool_size=(2, 2))(conv1d) pool1 = Dropout(DropP)(pool1) ############################# conv2a = Conv2D(12, (kernel_size, kernel_size), activation='relu', padding='same', kernel_regularizer=regularizers.l2(l2_lambda) )(pool1) conv2a = bn()(conv2a) conv2b = Conv2D(12, (kernel_size, kernel_size), activation='relu', padding='same', kernel_regularizer=regularizers.l2(l2_lambda) )(conv2a) conv2b = bn()(conv2b) merge1=concatenate([conv2a,conv2b]) conv2c = Conv2D(12, (kernel_size, kernel_size), activation='relu', padding='same', kernel_regularizer=regularizers.l2(l2_lambda) )(merge1) conv2c = bn()(conv2c) merge2=concatenate([conv2a,conv2b,conv2c]) conv2d = Conv2D(12, (kernel_size, kernel_size), activation='relu', padding='same', kernel_regularizer=regularizers.l2(l2_lambda) )(merge2) conv2d = bn()(conv2d) merge3=concatenate([conv2a,conv2b,conv2c,conv2d]) conv2e = Conv2D(12, (kernel_size, kernel_size), activation='relu', padding='same', kernel_regularizer=regularizers.l2(l2_lambda) )(merge3) conv2e = bn()(conv2e) merge4=concatenate([conv2a,conv2b,conv2c,conv2d,conv2e]) conv2f = Conv2D(12, (kernel_size, kernel_size), activation='relu', padding='same', kernel_regularizer=regularizers.l2(l2_lambda) )(merge4) conv2f = bn()(conv2f) merge5=concatenate([conv2a,conv2b,conv2c,conv2d,conv2e,conv2f]) conv2g = Conv2D(12, (kernel_size, kernel_size), activation='relu', padding='same', kernel_regularizer=regularizers.l2(l2_lambda) )(merge5) conv2g = bn()(conv2g) merge6=concatenate([conv2a,conv2b,conv2c,conv2d,conv2e,conv2f,conv2g]) conv2h = Conv2D(64, (kernel_size, kernel_size), activation='relu', padding='same', kernel_regularizer=regularizers.l2(l2_lambda) )(merge6) conv2h = bn()(conv2h) pool2 = MaxPooling2D(pool_size=(2, 2))(conv2h) pool2 = Dropout(DropP)(pool2) ############################# conv3a = Conv2D(12, (kernel_size, kernel_size), activation='relu', padding='same', kernel_regularizer=regularizers.l2(l2_lambda) )(pool2) conv3a = bn()(conv3a) conv3b = Conv2D(12, (kernel_size, kernel_size), activation='relu', padding='same', kernel_regularizer=regularizers.l2(l2_lambda) )(conv3a) conv3b = bn()(conv3b) merge1=concatenate([conv3a,conv3b]) conv3c = Conv2D(12, (kernel_size, kernel_size), activation='relu', padding='same', kernel_regularizer=regularizers.l2(l2_lambda) )(merge1) conv3c = bn()(conv3c) merge2=concatenate([conv3a,conv3b,conv3c]) conv3d = Conv2D(12, (kernel_size, kernel_size), activation='relu', padding='same', kernel_regularizer=regularizers.l2(l2_lambda) )(merge2) conv3d = bn()(conv3d) merge3=concatenate([conv3a,conv3b,conv3c,conv3d]) conv3e = Conv2D(12, (kernel_size, kernel_size), activation='relu', padding='same', kernel_regularizer=regularizers.l2(l2_lambda) )(merge3) conv3e = bn()(conv3e) merge4=concatenate([conv3a,conv3b,conv3c,conv3d,conv3e]) conv3f = Conv2D(12, (kernel_size, kernel_size), activation='relu', padding='same', kernel_regularizer=regularizers.l2(l2_lambda) )(merge4) conv3f = bn()(conv3f) merge5=concatenate([conv3a,conv3b,conv3c,conv3d,conv3e,conv3f]) conv3g = Conv2D(12, (kernel_size, kernel_size), activation='relu', padding='same', kernel_regularizer=regularizers.l2(l2_lambda) )(merge5) conv3g = bn()(conv3g) merge6=concatenate([conv3a,conv3b,conv3c,conv3d,conv3e,conv3f,conv3g]) conv3h = Conv2D(128, (kernel_size, kernel_size), activation='relu', padding='same', kernel_regularizer=regularizers.l2(l2_lambda) )(merge6) conv3h = bn()(conv3h) pool3 = MaxPooling2D(pool_size=(2, 2))(conv3h) pool3 = Dropout(DropP)(pool3) ############################# conv4a = Conv2D(12, (kernel_size, kernel_size), activation='relu', padding='same', kernel_regularizer=regularizers.l2(l2_lambda) )(pool3) conv4a = bn()(conv4a) conv4b = Conv2D(12, (kernel_size, kernel_size), activation='relu', padding='same', kernel_regularizer=regularizers.l2(l2_lambda) )(conv4a) conv4b = bn()(conv4b) merge1=concatenate([conv4a,conv4b]) conv4c = Conv2D(12, (kernel_size, kernel_size), activation='relu', padding='same', kernel_regularizer=regularizers.l2(l2_lambda) )(merge1) conv4c = bn()(conv4c) merge2=concatenate([conv4a,conv4b,conv4c]) conv4d = Conv2D(12, (kernel_size, kernel_size), activation='relu', padding='same', kernel_regularizer=regularizers.l2(l2_lambda) )(merge2) conv4d = bn()(conv4d) merge3=concatenate([conv4a,conv4b,conv4c,conv4d]) conv4e = Conv2D(12, (kernel_size, kernel_size), activation='relu', padding='same', kernel_regularizer=regularizers.l2(l2_lambda) )(merge3) conv4e = bn()(conv4e) merge4=concatenate([conv4a,conv4b,conv4c,conv4d,conv4e]) conv4f = Conv2D(12, (kernel_size, kernel_size), activation='relu', padding='same', kernel_regularizer=regularizers.l2(l2_lambda) )(merge4) conv4f = bn()(conv4f) merge5=concatenate([conv4a,conv4b,conv4c,conv4d,conv4e,conv4f]) conv4g = Conv2D(12, (kernel_size, kernel_size), activation='relu', padding='same', kernel_regularizer=regularizers.l2(l2_lambda) )(merge5) conv4g = bn()(conv4g) merge6=concatenate([conv4a,conv4b,conv4c,conv4d,conv4e,conv4f,conv4g]) conv4h = Conv2D(256, (kernel_size, kernel_size), activation='relu', padding='same', kernel_regularizer=regularizers.l2(l2_lambda) )(merge6) conv4h = bn()(conv4h) pool4 = MaxPooling2D(pool_size=(2, 2))(conv4h) pool4 = Dropout(DropP)(pool4) ############################# conv5a = Conv2D(12, (kernel_size, kernel_size), activation='relu', padding='same', kernel_regularizer=regularizers.l2(l2_lambda) )(pool4) conv5a = bn()(conv5a) conv5b = Conv2D(12, (kernel_size, kernel_size), activation='relu', padding='same', kernel_regularizer=regularizers.l2(l2_lambda) )(conv5a) conv5b = bn()(conv5b) merge1=concatenate([conv5a,conv5b]) conv5c = Conv2D(12, (kernel_size, kernel_size), activation='relu', padding='same', kernel_regularizer=regularizers.l2(l2_lambda) )(merge1) conv5c = bn()(conv5c) merge2=concatenate([conv5a,conv5b,conv5c]) conv5d = Conv2D(12, (kernel_size, kernel_size), activation='relu', padding='same', kernel_regularizer=regularizers.l2(l2_lambda) )(merge2) conv5d = bn()(conv5d) merge3=concatenate([conv5a,conv5b,conv5c,conv5d]) conv5e = Conv2D(12, (kernel_size, kernel_size), activation='relu', padding='same', kernel_regularizer=regularizers.l2(l2_lambda) )(merge3) conv5e = bn()(conv5e) merge4=concatenate([conv5a,conv5b,conv5c,conv5d,conv5e]) conv5f = Conv2D(12, (kernel_size, kernel_size), activation='relu', padding='same', kernel_regularizer=regularizers.l2(l2_lambda) )(merge4) conv5f = bn()(conv5f) merge5=concatenate([conv5a,conv5b,conv5c,conv5d,conv5e,conv5f]) conv5g = Conv2D(12, (kernel_size, kernel_size), activation='relu', padding='same', kernel_regularizer=regularizers.l2(l2_lambda) )(merge5) conv5g = bn()(conv5g) merge6=concatenate([conv5a,conv5b,conv5c,conv5d,conv5e,conv5f,conv5g]) conv5h = Conv2D(512, (kernel_size, kernel_size), activation='relu', padding='same', kernel_regularizer=regularizers.l2(l2_lambda) )(merge6) conv5h = bn()(conv5h) flatten_block=Flatten()(conv5h) ##################################### #branch 2 inputtwo=Input(shape=(1,), dtype='float32',name='inputtwo') #xmerge1=concatenate([flatten_block,inputtwo]) ##################################### #branch 3 xinputtwo=Input(shape=(1000,), dtype='float32',name='xinputtwo') xlayerone=Dense(32, activation='relu' )(xinputtwo) xlayertwo=Dense(64,activation='relu' )(xlayerone) xlayerthree=Dense(128,activation='relu' )(xlayertwo) xlayerfour=Dense(256,activation='relu' )(xlayerthree) ######################################## final_merge=concatenate([flatten_block,inputtwo,xlayerfour]) #mixing the input of the three branches after_merger_layers_1=Dense(32,activation='relu' )(final_merge) after_merger_layers_2=Dense(64,activation='relu' )(after_merger_layers_1) after_merger_layers_3=Dense(128,activation='relu' )(after_merger_layers_2) after_merger_layers_4=Dense(256,activation='relu' )(after_merger_layers_3) final_op=Dense(15000, activation='softmax',name='final_op')(after_merger_layers_4) model = Model(inputs=[inputs,inputtwo,xinputtwo], outputs=final_op) model.compile(optimizer='adagrad',loss='categorical_crossentropy',metrics=['accuracy']) model.summary() return model def train(self): """ this function trains the final network :return: """ self.load_model() if self.model is None: self.model = self.UNet(input_shape=(64,64,3)) print(self.model.summary()) for k in range(0, 4): for i in range(0, 14): print(i) X_train = np.load(os.path.join ( self.images_dir , "X_"+str(i)+".npy")) X1_train = np.load(os.path.join(self.clustering_dir, "train_X_"+str(i)+".npy")) X2_train = np.load(os.path.join(self.classification_dir, "train_X_"+str(i)+".npy")) X_train = X_train.astype('float32') X1_train = X1_train.astype('float32') X2_train = X2_train.astype('float32') #X_train=X_train.reshape(X_train.shape+(1,)) y_train = np.load(os.path.join(self.images_dir, "y_"+str(i)+".npy"))#.reshape(X_train.shape) y_train = keras.utils.to_categorical(y_train, 15000) self.model.fit([X_train, X1_train, X2_train], [y_train], batch_size=64, nb_epoch=1, shuffle=True) self.model.save('final_net_dsp.h5') def predict(self): """ this function runs the prediction over the sets :return: """ if self.model is None: self.load_model() if self.model is None: return None i =0 X_train = np.load(os.path.join(self.images_dir, "X_" + str(i) + ".npy")) X1_train = np.load(os.path.join(self.clustering_dir, "train_X_" + str(i) + ".npy")) X2_train = np.load(os.path.join(self.classification_dir, "train_X_" + str(i) + ".npy")) predicted = self.model.predict([X_train, X1_train, X2_train], batch_size=20) return predicted
src/models/final_model.py
14,199
thie function initializes the network class :param images_dir: :param clustering_dir: :param classfication_dir: this function loads model from file this function runs the prediction over the sets :return: this function trains the final network :return: branch 2xmerge1=concatenate([flatten_block,inputtwo])branch 3mixing the input of the three branchesX_train=X_train.reshape(X_train.shape+(1,)).reshape(X_train.shape)
424
en
0.603707