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 |
|---|---|---|---|---|---|---|
import logging
import os
from pathlib import Path
import typing
from logging.handlers import RotatingFileHandler
from dotenv import load_dotenv
import services.pv_simulator.constants as constants
from services.pv_simulator.main_loop import MainLoop
from services.pv_simulator.mq_receiver import MQReceiver, MQReceiverFactory
from services.pv_simulator.pv_power_value_calculator import PVPowerValueCalculator
from services.pv_simulator.typing_custom_protocols import (
MQReceiverProtocol,
PVPowerValueCalculatorProtocol
)
from services.pv_simulator import utils
current_dir_path: Path = Path(__file__).parent.absolute()
load_dotenv(dotenv_path=f"{current_dir_path}/.env")
def get_test_modules_names() -> typing.List[str]:
from services.pv_simulator.tests.unit import constants_for_tests
return constants_for_tests.TESTS_MODULES
def get_mq_receiver(callback: typing.Callable[[], bool]) -> MQReceiverProtocol:
return MQReceiverFactory.get_mq_receiver(constants.MQ_RECEIVER_TYPE, check_if_must_exit=callback)
def get_pv_power_value_calculator() -> PVPowerValueCalculatorProtocol:
return PVPowerValueCalculator(constants.MINUTES_DATA_SET, constants.PV_POWER_VALUES_DATA_SET)
def main(sys_argv: typing.List[str]) -> None:
"""PV simulator execution entry point.
Parameters
----------
sys_argv : list
contains the list of arguments passed to the CLI during its execution. The first argument contains the
executed script name.
"""
main_logger: typing.Optional[logging.Logger] = None
try:
must_exit_after_24h = os.getenv("MUST_EXIT_AFTER_24H", "0")
must_exit_after_24h = \
True if must_exit_after_24h.isdecimal() and int(must_exit_after_24h) == 1 else False
main_logger = utils.initialize_loggers(current_dir_path)
main_loop: MainLoop = MainLoop(constants.LOGGER_NAME,
constants.RESULTS_LOGGER_NAME,
current_dir_path,
must_exit_after_24h,
get_mq_receiver,
get_pv_power_value_calculator,
tests_modules_names_provider=get_test_modules_names)
main_loop.handle_arguments(sys_argv)
except KeyboardInterrupt:
if main_logger is not None:
main_logger.exception("Required to abort:")
else:
import traceback
traceback.print_exc()
except Exception:
if main_logger is not None:
main_logger.exception("Error:")
else:
import traceback
traceback.print_exc()
| services/pv_simulator/main.py | 2,714 | PV simulator execution entry point.
Parameters
----------
sys_argv : list
contains the list of arguments passed to the CLI during its execution. The first argument contains the
executed script name. | 207 | en | 0.743686 |
# -*- coding: utf-8 -*-
from __future__ import print_function
import argparse
import aerospike
from aerospike import exception as e
try:
from aerospike_helpers.operations import map_operations as mh
except:
pass # Needs Aerospike client >= 3.4.0
import datetime
import pprint
import random
import sys
import time
argparser = argparse.ArgumentParser(add_help=False)
argparser.add_argument(
"--help", dest="help", action="store_true", help="Displays this message."
)
argparser.add_argument(
"-U",
"--username",
dest="username",
metavar="<USERNAME>",
help="Username to connect to database.",
)
argparser.add_argument(
"-P",
"--password",
dest="password",
metavar="<PASSWORD>",
help="Password to connect to database.",
)
argparser.add_argument(
"-h",
"--host",
dest="host",
default="127.0.0.1",
metavar="<ADDRESS>",
help="Address of Aerospike server.",
)
argparser.add_argument(
"-p",
"--port",
dest="port",
type=int,
default=3000,
metavar="<PORT>",
help="Port of the Aerospike server.",
)
argparser.add_argument(
"-n",
"--namespace",
dest="namespace",
default="test",
metavar="<NS>",
help="Port of the Aerospike server.",
)
argparser.add_argument(
"-s",
"--set",
dest="set",
default="profiles",
metavar="<SET>",
help="Port of the Aerospike server.",
)
argparser.add_argument(
"-i",
"--interactive",
dest="interactive",
action="store_true",
help="Interactive Mode",
)
options = argparser.parse_args()
if options.help:
argparser.print_help()
print()
sys.exit(1)
def version_tuple(version):
return tuple(int(i) for i in version.split("."))
def pause():
input("Hit return to continue")
if options.namespace and options.namespace != "None":
namespace = options.namespace
else:
namespace = None
set = options.set if options.set and options.set != "None" else None
config = {"hosts": [(options.host, options.port)]}
try:
client = aerospike.client(config).connect(options.username, options.password)
policy = {"key": aerospike.POLICY_KEY_SEND}
except e.ClientError as e:
if not options.quiet:
print("Error: {0} [{1}]".format(e.msg, e.code))
sys.exit(2)
version = client.info_all("version")
release = list(version.values())[0][1].split(" ")[-1]
if version_tuple(aerospike.__version__) < version_tuple("3.4.0") or version_tuple(
release
) < version_tuple("4.6"):
print(
"\nPlease use Python client >= 3.4.0, ",
"Aerospike database >= 4.6 for this example.",
)
sys.exit(3)
pp = pprint.PrettyPrinter(indent=2)
spacer = "=" * 30
epoch = datetime.datetime(2019, 1, 1)
now = datetime.datetime.now()
try:
# Find all segments whose TTL is before this hour
key = (namespace, set, "u3")
current_hour = int((now - epoch).total_seconds() / 3600)
print("\nCurrent hour is {} hours since epoch".format(current_hour))
if options.interactive:
pause()
ops = [
mh.map_get_by_value_range(
"u",
[0, aerospike.null()],
[current_hour - 1, aerospike.null()],
aerospike.MAP_RETURN_KEY,
False,
),
mh.map_size("u"),
]
_, _, b = client.operate_ordered(key, ops)
stale_segments, total_segments = b
print("This user has a total of {} segments".format(total_segments[1]))
print(
"Of those, a total of {} segments should be cleaned".format(
len(stale_segments[1])
)
)
print("Show all segments with a segment TTL before the current hour:")
print(stale_segments)
print(spacer)
# Clean up the stale segments using a background scan with a transaction
# attached to it
print("Clean the stale segments from the entire namespace")
if options.interactive:
pause()
ops = [
mh.map_remove_by_value_range(
"u",
[0, aerospike.null()],
[current_hour - 1, aerospike.null()],
aerospike.MAP_RETURN_NONE,
False,
)
]
# _, _, _ = client.operate_ordered(key, ops)
scan = client.scan(namespace, set)
scan.add_ops(ops)
job_id = scan.execute_background()
# wait for job to finish
while True:
response = client.job_info(job_id, aerospike.JOB_SCAN)
if response["status"] != aerospike.JOB_STATUS_INPROGRESS:
break
time.sleep(0.25)
ops = [
mh.map_get_by_value_range(
"u",
[0, aerospike.null()],
[current_hour - 1, aerospike.null()],
aerospike.MAP_RETURN_KEY,
False,
),
mh.map_size("u"),
]
_, _, b = client.operate_ordered(key, ops)
stale_segments, total_segments = b
print("This user now has a total of {} segments".format(total_segments[1]))
print(
"Of those, a total of {} segments should be cleaned".format(
len(stale_segments[1])
)
)
print("Show all segments with a segment TTL before the current hour:")
print(stale_segments)
print(spacer)
except Exception as e:
print("Error: {0} [{1}]".format(e.msg, e.code))
client.close()
| trim_segments.py | 5,237 | -*- coding: utf-8 -*- Needs Aerospike client >= 3.4.0 Find all segments whose TTL is before this hour Clean up the stale segments using a background scan with a transaction attached to it _, _, _ = client.operate_ordered(key, ops) wait for job to finish | 253 | en | 0.850417 |
import copy
from enum import Enum
from jinja2 import Template
from typing import List
from dispatch.conversation.enums import ConversationButtonActions
from dispatch.incident.enums import IncidentStatus
from .config import (
DISPATCH_UI_URL,
INCIDENT_RESOURCE_CONVERSATION_REFERENCE_DOCUMENT,
INCIDENT_RESOURCE_EXECUTIVE_REPORT_DOCUMENT,
INCIDENT_RESOURCE_INCIDENT_FAQ_DOCUMENT,
INCIDENT_RESOURCE_INCIDENT_REVIEW_DOCUMENT,
INCIDENT_RESOURCE_INVESTIGATION_DOCUMENT,
INCIDENT_RESOURCE_INVESTIGATION_SHEET,
)
class MessageType(str, Enum):
incident_daily_summary = "incident-daily-summary"
incident_daily_summary_no_incidents = "incident-daily-summary-no-incidents"
incident_executive_report = "incident-executive-report"
incident_notification = "incident-notification"
incident_participant_welcome = "incident-participant-welcome"
incident_resources_message = "incident-resources-message"
incident_tactical_report = "incident-tactical-report"
incident_task_list = "incident-task-list"
incident_task_reminder = "incident-task-reminder"
incident_status_reminder = "incident-status-reminder"
incident_participant_suggested_reading = "incident-participant-suggested-reading"
INCIDENT_STATUS_DESCRIPTIONS = {
IncidentStatus.active: "This incident is under active investigation.",
IncidentStatus.stable: "This incident is stable, the bulk of the investigation has been completed or most of the risk has been mitigated.",
IncidentStatus.closed: "This no longer requires additional involvement, long term incident action items have been assigned to their respective owners.",
}
INCIDENT_TASK_REMINDER_DESCRIPTION = """
You are assigned to the following incident tasks.
This is a reminder that these tasks have passed their due date.
Please review and update them as appropriate. Resolving them will stop the reminders.""".replace(
"\n", " "
).strip()
INCIDENT_TASK_LIST_DESCRIPTION = """The following are open incident tasks."""
INCIDENT_DAILY_SUMMARY_DESCRIPTION = """
Daily Incidents Summary""".replace(
"\n", " "
).strip()
INCIDENT_DAILY_SUMMARY_ACTIVE_INCIDENTS_DESCRIPTION = f"""
Active Incidents (<{DISPATCH_UI_URL}/incidents/status|Details>)""".replace(
"\n", " "
).strip()
INCIDENT_DAILY_SUMMARY_NO_ACTIVE_INCIDENTS_DESCRIPTION = """
There are no active incidents at this moment.""".replace(
"\n", " "
).strip()
INCIDENT_DAILY_SUMMARY_STABLE_CLOSED_INCIDENTS_DESCRIPTION = """
Stable or Closed Incidents (last 24 hours)""".replace(
"\n", " "
).strip()
INCIDENT_DAILY_SUMMARY_NO_STABLE_CLOSED_INCIDENTS_DESCRIPTION = """
There are no stable or closed incidents in the last 24 hours.""".replace(
"\n", " "
).strip()
INCIDENT_COMMANDER_DESCRIPTION = """
The Incident Commander (IC) is responsible for
knowing the full context of the incident.
Contact them about any questions or concerns.""".replace(
"\n", " "
).strip()
INCIDENT_COMMANDER_READDED_DESCRIPTION = """
{{ commander_fullname }} (Incident Commander) has been re-added to the conversation.
Please, handoff the Incident Commander role before leaving the conversation.""".replace(
"\n", " "
).strip()
INCIDENT_TICKET_DESCRIPTION = """
Ticket for tracking purposes. It contains a description of
the incident and links to resources.""".replace(
"\n", " "
).strip()
INCIDENT_CONVERSATION_DESCRIPTION = """
Private conversation for real-time discussion. All incident participants get added to it.
""".replace(
"\n", " "
).strip()
INCIDENT_CONVERSATION_REFERENCE_DOCUMENT_DESCRIPTION = """
Document containing the list of slash commands available to the Incident Commander (IC)
and participants in the incident conversation.""".replace(
"\n", " "
).strip()
INCIDENT_CONFERENCE_DESCRIPTION = """
Video conference and phone bridge to be used throughout the incident. Password: {{conference_challenge if conference_challenge else 'N/A'}}
""".replace(
"\n", ""
).strip()
INCIDENT_STORAGE_DESCRIPTION = """
Common storage for all incident artifacts and
documents. Add logs, screen captures, or any other data collected during the
investigation to this drive. It is shared with all incident participants.""".replace(
"\n", " "
).strip()
INCIDENT_INVESTIGATION_DOCUMENT_DESCRIPTION = """
This is a document for all incident facts and context. All
incident participants are expected to contribute to this document.
It is shared with all incident participants.""".replace(
"\n", " "
).strip()
INCIDENT_INVESTIGATION_SHEET_DESCRIPTION = """
This is a sheet for tracking impacted assets. All
incident participants are expected to contribute to this sheet.
It is shared with all incident participants.""".replace(
"\n", " "
).strip()
INCIDENT_FAQ_DOCUMENT_DESCRIPTION = """
First time responding to an information security incident? This
document answers common questions encountered when
helping us respond to an incident.""".replace(
"\n", " "
).strip()
INCIDENT_REVIEW_DOCUMENT_DESCRIPTION = """
This document will capture all lessons learned, questions, and action items raised during the incident.""".replace(
"\n", " "
).strip()
INCIDENT_EXECUTIVE_REPORT_DOCUMENT_DESCRIPTION = """
This is a document that contains an executive report about the incident.""".replace(
"\n", " "
).strip()
INCIDENT_DOCUMENT_DESCRIPTIONS = {
INCIDENT_RESOURCE_CONVERSATION_REFERENCE_DOCUMENT: INCIDENT_CONVERSATION_REFERENCE_DOCUMENT_DESCRIPTION,
INCIDENT_RESOURCE_EXECUTIVE_REPORT_DOCUMENT: INCIDENT_EXECUTIVE_REPORT_DOCUMENT_DESCRIPTION,
INCIDENT_RESOURCE_INCIDENT_FAQ_DOCUMENT: INCIDENT_FAQ_DOCUMENT_DESCRIPTION,
INCIDENT_RESOURCE_INCIDENT_REVIEW_DOCUMENT: INCIDENT_REVIEW_DOCUMENT_DESCRIPTION,
INCIDENT_RESOURCE_INVESTIGATION_DOCUMENT: INCIDENT_INVESTIGATION_DOCUMENT_DESCRIPTION,
INCIDENT_RESOURCE_INVESTIGATION_SHEET: INCIDENT_INVESTIGATION_SHEET_DESCRIPTION,
}
INCIDENT_PARTICIPANT_WELCOME_DESCRIPTION = """
You\'re being contacted because we think you may
be able to help us during this information security incident.
Please review the content below and join us in the
incident Slack channel.""".replace(
"\n", " "
).strip()
INCIDENT_WELCOME_CONVERSATION_COPY = """
This is the incident conversation. Please pull in any
individuals you feel may be able to help resolve this incident.""".replace(
"\n", " "
).strip()
INCIDENT_PARTICIPANT_SUGGESTED_READING_DESCRIPTION = """
Dispatch thinks the following documents might be
relevant to this incident.""".replace(
"\n", " "
).strip()
INCIDENT_NOTIFICATION_PURPOSES_FYI = """
This message is for notification purposes only.""".replace(
"\n", " "
).strip()
INCIDENT_CAN_REPORT_REMINDER = """
It's time to send a new CAN report. Go to the Demisto UI and run the
CAN Report playbook from the Playground Work Plan.""".replace(
"\n", " "
).strip()
INCIDENT_VULNERABILITY_DESCRIPTION = """
We are tracking the details of the vulnerability that led to this incident
in the VUL Jira issue linked above.""".replace(
"\n", " "
).strip()
INCIDENT_STABLE_DESCRIPTION = """
The risk has been contained and the incident marked as stable.""".replace(
"\n", " "
).strip()
INCIDENT_CLOSED_DESCRIPTION = """
The incident has been resolved and marked as closed.""".replace(
"\n", " "
).strip()
INCIDENT_TACTICAL_REPORT_DESCRIPTION = """
The following conditions, actions, and needs summarize the current status of the incident.""".replace(
"\n", " "
).strip()
INCIDENT_NEW_ROLE_DESCRIPTION = """
{{assigner_fullname}} has assigned the role of {{assignee_role}} to {{assignee_fullname}}.
Please, contact {{assignee_firstname}} about any questions or concerns.""".replace(
"\n", " "
).strip()
INCIDENT_REPORT_REMINDER_DESCRIPTION = """You have not provided a {{report_type}} for this incident recently.
You can use `{{command}}` in the conversation to assist you in writing one.""".replace(
"\n", " "
).strip()
INCIDENT_STATUS_REMINDER_DESCRIPTION = """You have not updated the status for this incident recently. If the incident has been resolved,
you can use `{{command}}` in the conversation to assist you in closing your incident.""".replace(
"\n", " "
).strip()
INCIDENT_TASK_NEW_DESCRIPTION = """
The following incident task has been created in the incident document.\n\n*Description:* {{task_description}}\n\n*Assignees:* {{task_assignees|join(',')}}"""
INCIDENT_TASK_RESOLVED_DESCRIPTION = """
The following incident task has been resolved in the incident document.\n\n*Description:* {{task_description}}\n\n*Assignees:* {{task_assignees|join(',')}}"""
INCIDENT_WORKFLOW_CREATED_DESCRIPTION = """
A new workflow instance has been created.
\n\n *Creator:* {{instance_creator_name}}
"""
INCIDENT_WORKFLOW_UPDATE_DESCRIPTION = """
This workflow's status has changed from *{{ instance_status_old }}* to *{{ instance_status_new }}*.
\n\n*Workflow Description*: {{workflow_description}}
\n\n *Creator:* {{instance_creator_name}}
"""
INCIDENT_WORKFLOW_COMPLETE_DESCRIPTION = """
This workflow's status has changed from *{{ instance_status_old }}* to *{{ instance_status_new }}*.
\n\n *Workflow Description:* {{workflow_description}}
\n\n *Creator:* {{instance_creator_name}}
{% if instance_artifacts %}
\n\n *Workflow Artifacts:*
\n\n {% for a in instance_artifacts %}- <{{a.weblink}}|{{a.name}}> \n\n{% endfor %}
{% endif %}
"""
INCIDENT_TYPE_CHANGE_DESCRIPTION = """
The incident type has been changed from *{{ incident_type_old }}* to *{{ incident_type_new }}*."""
INCIDENT_STATUS_CHANGE_DESCRIPTION = """
The incident status has been changed from *{{ incident_status_old }}* to *{{ incident_status_new }}*."""
INCIDENT_PRIORITY_CHANGE_DESCRIPTION = """
The incident priority has been changed from *{{ incident_priority_old }}* to *{{ incident_priority_new }}*."""
INCIDENT_NAME_WITH_ENGAGEMENT = {
"title": "{{name}} Incident Notification",
"title_link": "{{ticket_weblink}}",
"text": INCIDENT_NOTIFICATION_PURPOSES_FYI,
"button_text": "Join Incident",
"button_value": "{{incident_id}}",
"button_action": ConversationButtonActions.invite_user,
}
INCIDENT_NAME = {
"title": "{{name}} Incident Notification",
"title_link": "{{ticket_weblink}}",
"text": INCIDENT_NOTIFICATION_PURPOSES_FYI,
}
INCIDENT_TITLE = {"title": "Incident Title", "text": "{{title}}"}
INCIDENT_DESCRIPTION = {"title": "Incident Description", "text": "{{description}}"}
INCIDENT_STATUS = {
"title": "Incident Status - {{status}}",
"status_mapping": INCIDENT_STATUS_DESCRIPTIONS,
}
INCIDENT_TYPE = {"title": "Incident Type - {{type}}", "text": "{{type_description}}"}
INCIDENT_PRIORITY = {
"title": "Incident Priority - {{priority}}",
"text": "{{priority_description}}",
}
INCIDENT_PRIORITY_FYI = {
"title": "Incident Priority - {{priority}}",
"text": "{{priority_description}}",
}
INCIDENT_COMMANDER = {
"title": "Incident Commander - {{commander_fullname}}",
"title_link": "{{commander_weblink}}",
"text": INCIDENT_COMMANDER_DESCRIPTION,
}
INCIDENT_CONFERENCE = {
"title": "Incident Conference",
"title_link": "{{conference_weblink}}",
"text": INCIDENT_CONFERENCE_DESCRIPTION,
}
INCIDENT_STORAGE = {
"title": "Incident Storage",
"title_link": "{{storage_weblink}}",
"text": INCIDENT_STORAGE_DESCRIPTION,
}
INCIDENT_CONVERSATION_COMMANDS_REFERENCE_DOCUMENT = {
"title": "Incident Conversation Commands Reference Document",
"title_link": "{{conversation_commands_reference_document_weblink}}",
"text": INCIDENT_CONVERSATION_REFERENCE_DOCUMENT_DESCRIPTION,
}
INCIDENT_INVESTIGATION_DOCUMENT = {
"title": "Incident Investigation Document",
"title_link": "{{document_weblink}}",
"text": INCIDENT_INVESTIGATION_DOCUMENT_DESCRIPTION,
}
INCIDENT_INVESTIGATION_SHEET = {
"title": "Incident Investigation Sheet",
"title_link": "{{sheet_weblink}}",
"text": INCIDENT_INVESTIGATION_SHEET_DESCRIPTION,
}
INCIDENT_REVIEW_DOCUMENT = {
"title": "Incident Review Document",
"title_link": "{{review_document_weblink}}",
"text": INCIDENT_REVIEW_DOCUMENT_DESCRIPTION,
}
INCIDENT_FAQ_DOCUMENT = {
"title": "Incident FAQ Document",
"title_link": "{{faq_weblink}}",
"text": INCIDENT_FAQ_DOCUMENT_DESCRIPTION,
}
INCIDENT_TYPE_CHANGE = {"title": "Incident Type Change", "text": INCIDENT_TYPE_CHANGE_DESCRIPTION}
INCIDENT_STATUS_CHANGE = {
"title": "Incident Status Change",
"text": INCIDENT_STATUS_CHANGE_DESCRIPTION,
}
INCIDENT_PRIORITY_CHANGE = {
"title": "Incident Priority Change",
"text": INCIDENT_PRIORITY_CHANGE_DESCRIPTION,
}
INCIDENT_PARTICIPANT_SUGGESTED_READING_ITEM = {
"title": "{{name}}",
"title_link": "{{weblink}}",
"text": "{{description}}",
}
INCIDENT_PARTICIPANT_WELCOME = {
"title": "Welcome to {{name}}",
"title_link": "{{ticket_weblink}}",
"text": INCIDENT_PARTICIPANT_WELCOME_DESCRIPTION,
}
INCIDENT_PARTICIPANT_WELCOME_MESSAGE = [
INCIDENT_PARTICIPANT_WELCOME,
INCIDENT_TITLE,
INCIDENT_STATUS,
INCIDENT_TYPE,
INCIDENT_PRIORITY,
INCIDENT_COMMANDER,
INCIDENT_INVESTIGATION_DOCUMENT,
INCIDENT_STORAGE,
INCIDENT_CONFERENCE,
INCIDENT_CONVERSATION_COMMANDS_REFERENCE_DOCUMENT,
INCIDENT_FAQ_DOCUMENT,
]
INCIDENT_RESOURCES_MESSAGE = [
INCIDENT_COMMANDER,
INCIDENT_INVESTIGATION_DOCUMENT,
INCIDENT_REVIEW_DOCUMENT,
INCIDENT_STORAGE,
INCIDENT_CONFERENCE,
INCIDENT_CONVERSATION_COMMANDS_REFERENCE_DOCUMENT,
INCIDENT_FAQ_DOCUMENT,
]
INCIDENT_NOTIFICATION_COMMON = [INCIDENT_TITLE]
INCIDENT_NOTIFICATION = INCIDENT_NOTIFICATION_COMMON.copy()
INCIDENT_NOTIFICATION.extend(
[INCIDENT_STATUS, INCIDENT_TYPE, INCIDENT_PRIORITY_FYI, INCIDENT_COMMANDER]
)
INCIDENT_TACTICAL_REPORT = [
{"title": "Incident Tactical Report", "text": INCIDENT_TACTICAL_REPORT_DESCRIPTION},
{"title": "Conditions", "text": "{{conditions}}"},
{"title": "Actions", "text": "{{actions}}"},
{"title": "Needs", "text": "{{needs}}"},
]
INCIDENT_EXECUTIVE_REPORT = [
{"title": "Incident Title", "text": "{{title}}"},
{"title": "Current Status", "text": "{{current_status}}"},
{"title": "Overview", "text": "{{overview}}"},
{"title": "Next Steps", "text": "{{next_steps}}"},
]
INCIDENT_REPORT_REMINDER = [
{
"title": "{{name}} Incident - {{report_type}} Reminder",
"title_link": "{{ticket_weblink}}",
"text": INCIDENT_REPORT_REMINDER_DESCRIPTION,
},
INCIDENT_TITLE,
]
INCIDENT_STATUS_REMINDER = [
{
"title": "{{name}} Incident - Status Reminder",
"title_link": "{{ticket_weblink}}",
"text": INCIDENT_STATUS_REMINDER_DESCRIPTION,
},
INCIDENT_TITLE,
INCIDENT_STATUS,
]
INCIDENT_TASK_REMINDER = [
{"title": "Incident - {{ name }}", "text": "{{ title }}"},
{"title": "Creator", "text": "{{ creator }}"},
{"title": "Description", "text": "{{ description }}"},
{"title": "Priority", "text": "{{ priority }}"},
{"title": "Created At", "text": "", "datetime": "{{ created_at}}"},
{"title": "Resolve By", "text": "", "datetime": "{{ resolve_by }}"},
{"title": "Link", "text": "{{ weblink }}"},
]
INCIDENT_NEW_ROLE_NOTIFICATION = [
{
"title": "New {{assignee_role}} - {{assignee_fullname}}",
"title_link": "{{assignee_weblink}}",
"text": INCIDENT_NEW_ROLE_DESCRIPTION,
}
]
INCIDENT_TASK_NEW_NOTIFICATION = [
{
"title": "New Incident Task",
"title_link": "{{task_weblink}}",
"text": INCIDENT_TASK_NEW_DESCRIPTION,
}
]
INCIDENT_TASK_RESOLVED_NOTIFICATION = [
{
"title": "Resolved Incident Task",
"title_link": "{{task_weblink}}",
"text": INCIDENT_TASK_RESOLVED_DESCRIPTION,
}
]
INCIDENT_WORKFLOW_CREATED_NOTIFICATION = [
{
"title": "Workflow Created - {{workflow_name}}",
"text": INCIDENT_WORKFLOW_CREATED_DESCRIPTION,
}
]
INCIDENT_WORKFLOW_UPDATE_NOTIFICATION = [
{
"title": "Workflow Status Change - {{workflow_name}}",
"title_link": "{{instance_weblink}}",
"text": INCIDENT_WORKFLOW_UPDATE_DESCRIPTION,
}
]
INCIDENT_WORKFLOW_COMPLETE_NOTIFICATION = [
{
"title": "Workflow Completed - {{workflow_name}}",
"title_link": "{{instance_weblink}}",
"text": INCIDENT_WORKFLOW_COMPLETE_DESCRIPTION,
}
]
INCIDENT_COMMANDER_READDED_NOTIFICATION = [
{"title": "Incident Commander Re-Added", "text": INCIDENT_COMMANDER_READDED_DESCRIPTION}
]
def render_message_template(message_template: List[dict], **kwargs):
"""Renders the jinja data included in the template itself."""
data = []
new_copy = copy.deepcopy(message_template)
for d in new_copy:
if d.get("status_mapping"):
d["text"] = d["status_mapping"][kwargs["status"]]
if d.get("datetime"):
d["datetime"] = Template(d["datetime"]).render(**kwargs)
d["text"] = Template(d["text"]).render(**kwargs)
d["title"] = Template(d["title"]).render(**kwargs)
if d.get("title_link"):
d["title_link"] = Template(d["title_link"]).render(**kwargs)
if d["title_link"] == "None": # skip blocks with no content
continue
# skip blocks that do not have new links rendered, as no real value was provided
if not d["title_link"]:
continue
if d.get("button_text"):
d["button_text"] = Template(d["button_text"]).render(**kwargs)
if d.get("button_value"):
d["button_value"] = Template(d["button_value"]).render(**kwargs)
data.append(d)
return data
| src/dispatch/messaging.py | 17,668 | Renders the jinja data included in the template itself.
skip blocks with no content skip blocks that do not have new links rendered, as no real value was provided | 164 | en | 0.962449 |
import random
import copy
from collections import defaultdict
from collections import deque
from collections import namedtuple
from matplotlib import pyplot as plt
import numpy as np
class Q():
def __init__(self, n_actions, observation_space, bin_size, low_bound=None, high_bound=None, initial_mean=0.0, initial_std=0.0):
self.n_actions = n_actions
self._observation_dimension = 1
for d in observation_space.shape:
self._observation_dimension *= d
self._bin_sizes = bin_size if isinstance(bin_size, list) else [bin_size] * self._observation_dimension
self._dimension_bins = []
for i, low, high in self._low_high_iter(observation_space, low_bound, high_bound):
b_size = self._bin_sizes[i]
bins = self._make_bins(low, high, b_size)
print(bins)
self._dimension_bins.append(bins)
# if we encounter the new observation, we initialize action evaluations
self.table = defaultdict(lambda: initial_std * np.random.randn(self.n_actions) + initial_mean)
@classmethod
def _make_bins(cls, low, high, bin_size):
bins = np.arange(low, high, (float(high) - float(low)) / (bin_size - 2)) # exclude both ends
if min(bins) < 0 and 0 not in bins:
bins = np.sort(np.append(bins, [0])) # 0 centric bins
return bins
@classmethod
def _low_high_iter(cls, observation_space, low_bound, high_bound):
lows = observation_space.low
highs = observation_space.high
for i in range(len(lows)):
low = lows[i]
if low_bound is not None:
_low_bound = low_bound if not isinstance(low_bound, list) else low_bound[i]
low = low if _low_bound is None else max(low, _low_bound)
high = highs[i]
if high_bound is not None:
_high_bound = high_bound if not isinstance(high_bound, list) else high_bound[i]
high = high if _high_bound is None else min(high, _high_bound)
yield i, low, high
def observation_to_state(self, observation):
state = 0
# caution: bin_size over 10 will not work accurately
unit = max(self._bin_sizes)
for d, o in enumerate(observation.flatten()):
state = state + np.digitize(o, self._dimension_bins[d]) * pow(unit, d) # bin_size numeral system
return state
def values(self, observation):
state = self.observation_to_state(observation)
return self.table[state]
class Agent():
def __init__(self, q, epsilon=0.05):
self.q = q
self.epsilon = epsilon
def act(self, observation):
action = -1
if np.random.random() < self.epsilon:
action = np.random.choice(self.q.n_actions)
else:
action = np.argmax(self.q.values(observation))
return action
class Trainer():
def __init__(self, agent, gamma=0.95, learning_rate=0.1, learning_rate_decay=None, epsilon=0.05, epsilon_decay=None, max_step=-1,target=500):
self.agent = agent
self.gamma = gamma
self.learning_rate = learning_rate
self.learning_rate_decay = learning_rate_decay
self.epsilon = epsilon
self.epsilon_decay = epsilon_decay
self.max_step = max_step
def train(self, env, episode_count, render=False):
mean_step_all =[]
mean_q_all=[]
goal_time_all=[]
reward_all=[]
self.agent.epsilon = self.epsilon
values = []
steps = deque(maxlen=100)
lr = self.learning_rate
for i in range(episode_count):
reward_total = 0
goal_time =0
obs = env.reset()
step = 0
done = False
while not done:
if render:
env.render()
action = self.agent.act(obs)
next_obs, reward, done,goal_time= env.step(action)
reward_total+= reward
goal_time += goal_time
state = self.agent.q.observation_to_state(obs)
future = 0 if done else np.max(self.agent.q.values(next_obs))
value = self.agent.q.table[state][action]
self.agent.q.table[state][action] += lr * (reward + self.gamma * future - value)
obs = next_obs
values.append(value)
step += 1
if self.max_step > 0 and step > self.max_step:
done = True
else:
mean = np.mean(values)
steps.append(step)
mean_step = np.mean(steps)
print("Episode {}: {}steps(avg{}). epsilon={:.3f}, lr={:.3f}, mean q value={:.2f}".format(
i, step, mean_step, self.agent.epsilon, lr, mean)
)
mean_step_all.append(mean_step)
mean_q_all.append(mean)
reward_all.append(reward_total)
if mean_step>1000:
render=True
if self.epsilon_decay is not None:
self.agent.epsilon = self.epsilon_decay(self.agent.epsilon, i)
if self.learning_rate_decay is not None:
lr = self.learning_rate_decay(lr, i)
# plot in comparsion
plt.xlabel('Episodes')
plt.ylabel('reward')
# plt.plot(mean_step_all, label='Q-learning', color='blue')
plt.plot(reward_all, label='Q-learning', color='yellow')
plt.plot(goal_time_all, label='Q-learning', color='green')
# plt.legend(['reward', 'Q-learning'], loc='upper right')
plt.title('reward/Episode')
plt.show()
# plot in comparsion
plt.xlabel('Episodes')
plt.ylabel('goal_time')
# plt.plot(mean_step_all, label='Q-learning', color='blue')
plt.plot(goal_time_all, label='Q-learning', color='green')
# plt.legend(['reward', 'Q-learning'], loc='upper right')
plt.title('goal/Episode')
plt.show()
| agent.py | 6,233 | if we encounter the new observation, we initialize action evaluations exclude both ends 0 centric bins caution: bin_size over 10 will not work accurately bin_size numeral system plot in comparsion plt.plot(mean_step_all, label='Q-learning', color='blue') plt.legend(['reward', 'Q-learning'], loc='upper right') plot in comparsion plt.plot(mean_step_all, label='Q-learning', color='blue') plt.legend(['reward', 'Q-learning'], loc='upper right') | 443 | en | 0.452352 |
# coding: utf-8
# /*##########################################################################
#
# Copyright (c) 2015-2018 European Synchrotron Radiation Facility
#
# 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.
#
# ###########################################################################*/
"""
The silx package contains the following main sub-packages:
- silx.gui: Qt widgets for data visualization and data file browsing
- silx.image: Some processing functions for 2D images
- silx.io: Reading and writing data files (HDF5/NeXus, SPEC, ...)
- silx.math: Some processing functions for 1D, 2D, 3D, nD arrays
- silx.opencl: OpenCL-based data processing
- silx.sx: High-level silx functions suited for (I)Python console.
- silx.utils: Miscellaneous convenient functions
See silx documentation: http://www.silx.org/doc/silx/latest/
"""
__authors__ = ["Jérôme Kieffer"]
__license__ = "MIT"
__date__ = "31/08/2018"
import os as _os
import logging as _logging
_logging.getLogger(__name__).addHandler(_logging.NullHandler())
project = _os.path.basename(_os.path.dirname(_os.path.abspath(__file__)))
try:
from ._version import __date__ as date # noqa
from ._version import (
version,
version_info,
hexversion,
strictversion,
dated_version,
) # noqa
except ImportError:
raise RuntimeError(
"Do NOT use %s from its sources: build it and use the built version"
% project
)
| freesas/__init__.py | 2,461 | The silx package contains the following main sub-packages:
- silx.gui: Qt widgets for data visualization and data file browsing
- silx.image: Some processing functions for 2D images
- silx.io: Reading and writing data files (HDF5/NeXus, SPEC, ...)
- silx.math: Some processing functions for 1D, 2D, 3D, nD arrays
- silx.opencl: OpenCL-based data processing
- silx.sx: High-level silx functions suited for (I)Python console.
- silx.utils: Miscellaneous convenient functions
See silx documentation: http://www.silx.org/doc/silx/latest/
coding: utf-8 /* Copyright (c) 2015-2018 European Synchrotron Radiation Facility 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. */ noqa noqa | 1,652 | en | 0.804851 |
"""Queuing Search Algorithm.
"""
import copy
import numpy as np
import opytimizer.math.random as r
import opytimizer.utils.constant as c
import opytimizer.utils.logging as l
from opytimizer.core import Optimizer
logger = l.get_logger(__name__)
class QSA(Optimizer):
"""A QSA class, inherited from Optimizer.
This is the designed class to define QSA-related
variables and methods.
References:
J. Zhang et al. Queuing search algorithm: A novel metaheuristic algorithm
for solving engineering optimization problems.
Applied Mathematical Modelling (2018).
"""
def __init__(self, params=None):
"""Initialization method.
Args:
params (dict): Contains key-value parameters to the meta-heuristics.
"""
logger.info('Overriding class: Optimizer -> QSA.')
# Overrides its parent class with the receiving params
super(QSA, self).__init__()
# Builds the class
self.build(params)
logger.info('Class overrided.')
def _calculate_queue(self, n_agents, t_1, t_2, t_3):
"""Calculates the number of agents that belongs to each queue.
Args:
n_agents (int): Number of agents.
t_1 (float): Fitness value of first agent in the population.
t_2 (float): Fitness value of second agent in the population.
t_3 (float): Fitness value of third agent in the population.
Returns:
The number of agents in first, second and third queues.
"""
# Checks if potential service time is bigger than `epsilon`
if t_1 > c.EPSILON:
# Calculates the proportion of agents in first, second and third queues
n_1 = (1 / t_1) / ((1 / t_1) + (1 / t_2) + (1 / t_3))
n_2 = (1 / t_2) / ((1 / t_1) + (1 / t_2) + (1 / t_3))
n_3 = (1 / t_3) / ((1 / t_1) + (1 / t_2) + (1 / t_3))
# If the potential service time is smaller than `epsilon`
else:
# Each queue will have 1/3 ratio
n_1 = 1 / 3
n_2 = 1 / 3
n_3 = 1 / 3
# Calculates the number of agents that belongs to each queue
q_1 = int(n_1 * n_agents)
q_2 = int(n_2 * n_agents)
q_3 = int(n_3 * n_agents)
return q_1, q_2, q_3
def _business_one(self, agents, function, beta):
"""Performs the first business phase.
Args:
agents (list): List of agents.
function (Function): A Function object that will be used as the objective function.
beta (float): Range of fluctuation.
"""
# Sorts agents
agents.sort(key=lambda x: x.fit)
# Copies temporary agents to represent `A_1`, `A_2` and `A_3`
A_1, A_2, A_3 = copy.deepcopy(agents[0]), copy.deepcopy(agents[1]), copy.deepcopy(agents[2])
# Calculates the number of agents in each queue
q_1, q_2, _ = self._calculate_queue(len(agents), A_1.fit, A_2.fit, A_3.fit)
# Represents the update patterns by eq. 4 and eq. 5
case = None
# Iterates through all agents
for i, agent in enumerate(agents):
# Creates another temporary agent
a = copy.deepcopy(agent)
# If index is smaller than the number of agents in first queue
if i < q_1:
# If it is the first agent in first queue
if i == 0:
# Defines the case as one
case = 1
# `A` will receive a copy from `A_1`
A = copy.deepcopy(A_1)
# If index is between first and second queues
elif q_1 <= i < q_1 + q_2:
# If index is the first agent in second queue
if i == q_1:
# Defines the case as one
case = 1
# `A` will receive a copy from `A_2`
A = copy.deepcopy(A_2)
# If index is between second and third queues
else:
# If index is the first agent in third queue
if i == q_1 + q_2:
# Defines the case as one
case = 1
# `A` will receive a copy from `A_3`
A = copy.deepcopy(A_3)
# Generates a uniform random number
alpha = r.generate_uniform_random_number(-1, 1)
# Generates an Erlang distribution
E = r.generate_gamma_random_number(1, 0.5, (agent.n_variables, agent.n_dimensions))
# If case is defined as one
if case == 1:
# Generates an Erlang number
e = r.generate_gamma_random_number(1, 0.5, 1)
# Calculates the fluctuation (eq. 6)
F_1 = beta * alpha * (E * np.fabs(A.position - a.position)) + \
e * (A.position - a.position)
# Updates the temporary agent's position (eq. 4)
a.position = A.position + F_1
# Evaluates the agent
a.fit = function(a.position)
# If new fitness is better than current agent's fitness
if a.fit < agent.fit:
# Replaces the current agent's position and fitness
agent.position = copy.deepcopy(a.position)
agent.fit = copy.deepcopy(a.fit)
# Defines the case as one
case = 1
# If new fitness is worse than current agent's fitness
else:
# Defines the case as two
case = 2
# If case is defined as two
else:
# Calculates the fluctuation (eq. 7)
F_2 = beta * alpha * (E * np.fabs(A.position - a.position))
# Updates the temporary agent's position (eq. 5)
a.position += F_2
# Evaluates the agent
a.fit = function(a.position)
# If new fitness is better than current agent's fitness
if a.fit < agent.fit:
# Replaces the current agent's position and fitness
agent.position = copy.deepcopy(a.position)
agent.fit = copy.deepcopy(a.fit)
# Defines the case as two
case = 2
# If new fitness is worse than current agent's fitness
else:
# Defines the case as one
case = 1
def _business_two(self, agents, function):
"""Performs the second business phase.
Args:
agents (list): List of agents.
function (Function): A Function object that will be used as the objective function.
"""
# Sorts agents
agents.sort(key=lambda x: x.fit)
# Copies temporary agents to represent `A_1`, `A_2` and `A_3`
A_1, A_2, A_3 = copy.deepcopy(agents[0]), copy.deepcopy(agents[1]), copy.deepcopy(agents[2])
# Calculates the number of agents in each queue
q_1, q_2, _ = self._calculate_queue(len(agents), A_1.fit, A_2.fit, A_3.fit)
# Calculates the probability of handling the business
pr = [i / len(agents) for i in range(1, len(agents) + 1)]
# Calculates the confusion degree
cv = A_1.fit / (A_2.fit + A_3.fit + c.EPSILON)
# Iterates through all agents
for i, agent in enumerate(agents):
# Creates another temporary agent
a = copy.deepcopy(agent)
# If index is smaller than the number of agents in first queue
if i < q_1:
# `A` will receive a copy from `A_1`
A = copy.deepcopy(A_1)
# If index is between first and second queues
elif q_1 <= i < q_1 + q_2:
# `A` will receive a copy from `A_2`
A = copy.deepcopy(A_2)
# If index is between second and third queues
else:
# `A` will receive a copy from `A_3`
A = copy.deepcopy(A_3)
# Generates a uniform random number
r1 = r.generate_uniform_random_number()
# If random number is smaller than probability of handling the business
if r1 < pr[i]:
# Randomly selects two individuals
A_1, A_2 = np.random.choice(agents, 2, replace=False)
# Generates another uniform random number
r2 = r.generate_uniform_random_number()
# Generates an Erlang number
e = r.generate_gamma_random_number(1, 0.5, 1)
# If random number is smaller than confusion degree
if r2 < cv:
# Calculates the fluctuation (eq. 14)
F_1 = e * (A_1.position - A_2.position)
# Update agent's position (eq. 12)
a.position += F_1
# If random number is bigger than confusion degree
else:
# Calculates the fluctuation (eq. 15)
F_2 = e * (A.position - A_1.position)
# Update agent's position (eq. 13)
a.position += F_2
# Evaluates the agent
a.fit = function(a.position)
# If the new fitness is better than the current agent's fitness
if a.fit < agent.fit:
# Replaces the current agent's position and fitness
agent.position = copy.deepcopy(a.position)
agent.fit = copy.deepcopy(a.fit)
def _business_three(self, agents, function):
"""Performs the third business phase.
Args:
agents (list): List of agents.
function (Function): A Function object that will be used as the objective function.
"""
# Sorts agents
agents.sort(key=lambda x: x.fit)
# Calculates the probability of handling the business
pr = [i / len(agents) for i in range(1, len(agents) + 1)]
# Iterates through all agents
for i, agent in enumerate(agents):
# Creates another temporary agent
a = copy.deepcopy(agent)
# Iterates through all decision variables
for j in range(agent.n_variables):
# Generates a uniform random number
r1 = r.generate_uniform_random_number()
# If random number is smaller than probability of handling the business
if r1 < pr[i]:
# Randomly selects two individuals
A_1, A_2 = np.random.choice(agents, 2, replace=False)
# Generates an Erlang number
e = r.generate_gamma_random_number(1, 0.5, 1)
# Updates temporary agent's position (eq. 17)
a.position[j] = A_1.position[j] + e * (A_2.position[j] - a.position[j])
# Evaluates the agent
a.fit = function(a.position)
# If the new fitness is better than the current agent's fitness
if a.fit < agent.fit:
# Replaces the current agent's position and fitness
agent.position = copy.deepcopy(a.position)
agent.fit = copy.deepcopy(a.fit)
def update(self, space, function, iteration, n_iterations):
"""Wraps Queue Search Algorithm over all agents and variables.
Args:
space (Space): Space containing agents and update-related information.
function (Function): A Function object that will be used as the objective function.
iteration (int): Current iteration.
n_iterations (int): Maximum number of iterations.
"""
# Calculates the range of fluctuation.
beta = np.exp(np.log(1 / (iteration + c.EPSILON)) * np.sqrt(iteration / n_iterations))
# Performs the first business phase
self._business_one(space.agents, function, beta)
# Performs the second business phase
self._business_two(space.agents, function)
# Performs the third business phase
self._business_three(space.agents, function)
| opytimizer/optimizers/social/qsa.py | 12,371 | A QSA class, inherited from Optimizer.
This is the designed class to define QSA-related
variables and methods.
References:
J. Zhang et al. Queuing search algorithm: A novel metaheuristic algorithm
for solving engineering optimization problems.
Applied Mathematical Modelling (2018).
Initialization method.
Args:
params (dict): Contains key-value parameters to the meta-heuristics.
Performs the first business phase.
Args:
agents (list): List of agents.
function (Function): A Function object that will be used as the objective function.
beta (float): Range of fluctuation.
Performs the third business phase.
Args:
agents (list): List of agents.
function (Function): A Function object that will be used as the objective function.
Performs the second business phase.
Args:
agents (list): List of agents.
function (Function): A Function object that will be used as the objective function.
Calculates the number of agents that belongs to each queue.
Args:
n_agents (int): Number of agents.
t_1 (float): Fitness value of first agent in the population.
t_2 (float): Fitness value of second agent in the population.
t_3 (float): Fitness value of third agent in the population.
Returns:
The number of agents in first, second and third queues.
Wraps Queue Search Algorithm over all agents and variables.
Args:
space (Space): Space containing agents and update-related information.
function (Function): A Function object that will be used as the objective function.
iteration (int): Current iteration.
n_iterations (int): Maximum number of iterations.
Queuing Search Algorithm.
Overrides its parent class with the receiving params Builds the class Checks if potential service time is bigger than `epsilon` Calculates the proportion of agents in first, second and third queues If the potential service time is smaller than `epsilon` Each queue will have 1/3 ratio Calculates the number of agents that belongs to each queue Sorts agents Copies temporary agents to represent `A_1`, `A_2` and `A_3` Calculates the number of agents in each queue Represents the update patterns by eq. 4 and eq. 5 Iterates through all agents Creates another temporary agent If index is smaller than the number of agents in first queue If it is the first agent in first queue Defines the case as one `A` will receive a copy from `A_1` If index is between first and second queues If index is the first agent in second queue Defines the case as one `A` will receive a copy from `A_2` If index is between second and third queues If index is the first agent in third queue Defines the case as one `A` will receive a copy from `A_3` Generates a uniform random number Generates an Erlang distribution If case is defined as one Generates an Erlang number Calculates the fluctuation (eq. 6) Updates the temporary agent's position (eq. 4) Evaluates the agent If new fitness is better than current agent's fitness Replaces the current agent's position and fitness Defines the case as one If new fitness is worse than current agent's fitness Defines the case as two If case is defined as two Calculates the fluctuation (eq. 7) Updates the temporary agent's position (eq. 5) Evaluates the agent If new fitness is better than current agent's fitness Replaces the current agent's position and fitness Defines the case as two If new fitness is worse than current agent's fitness Defines the case as one Sorts agents Copies temporary agents to represent `A_1`, `A_2` and `A_3` Calculates the number of agents in each queue Calculates the probability of handling the business Calculates the confusion degree Iterates through all agents Creates another temporary agent If index is smaller than the number of agents in first queue `A` will receive a copy from `A_1` If index is between first and second queues `A` will receive a copy from `A_2` If index is between second and third queues `A` will receive a copy from `A_3` Generates a uniform random number If random number is smaller than probability of handling the business Randomly selects two individuals Generates another uniform random number Generates an Erlang number If random number is smaller than confusion degree Calculates the fluctuation (eq. 14) Update agent's position (eq. 12) If random number is bigger than confusion degree Calculates the fluctuation (eq. 15) Update agent's position (eq. 13) Evaluates the agent If the new fitness is better than the current agent's fitness Replaces the current agent's position and fitness Sorts agents Calculates the probability of handling the business Iterates through all agents Creates another temporary agent Iterates through all decision variables Generates a uniform random number If random number is smaller than probability of handling the business Randomly selects two individuals Generates an Erlang number Updates temporary agent's position (eq. 17) Evaluates the agent If the new fitness is better than the current agent's fitness Replaces the current agent's position and fitness Calculates the range of fluctuation. Performs the first business phase Performs the second business phase Performs the third business phase | 5,179 | en | 0.862402 |
# coding: utf-8
#
# Copyright 2022 :Barry-Thomas-Paul: Moss
#
# 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.
#
# Struct Class
# this is a auto generated file generated by Cheetah
# Namespace: com.sun.star.ucb
# Libre Office Version: 7.3
from typing import TYPE_CHECKING
from ooo.oenv.env_const import UNO_ENVIRONMENT, UNO_RUNTIME, UNO_NONE
if (not TYPE_CHECKING) and UNO_RUNTIME and UNO_ENVIRONMENT:
import uno
def _get_class():
orig_init = None
ordered_keys = ('Source', 'Action', 'Content', 'Id')
def init(self, *args, **kwargs):
if len(kwargs) == 0 and len(args) == 1 and getattr(args[0], "__class__", None) == self.__class__:
orig_init(self, args[0])
return
kargs = kwargs.copy()
for i, arg in enumerate(args):
kargs[ordered_keys[i]] = arg
orig_init(self, **kargs)
type_name = 'com.sun.star.ucb.ContentEvent'
struct = uno.getClass(type_name)
struct.__ooo_ns__ = 'com.sun.star.ucb'
struct.__ooo_full_ns__= type_name
struct.__ooo_type_name__ = 'struct'
orig_init = struct.__init__
struct.__init__ = init
return struct
ContentEvent = _get_class()
else:
from ...lo.ucb.content_event import ContentEvent as ContentEvent
__all__ = ['ContentEvent']
| ooobuild/dyn/ucb/content_event.py | 1,850 | coding: utf-8 Copyright 2022 :Barry-Thomas-Paul: Moss 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. Struct Class this is a auto generated file generated by Cheetah Namespace: com.sun.star.ucb Libre Office Version: 7.3 | 694 | en | 0.838168 |
# A lot of failures in these tests on Mac OS X.
# Byte order related?
import unittest
from ctypes import *
from ctypes.test import need_symbol
import _ctypes_test
class CFunctions(unittest.TestCase):
_dll = CDLL(_ctypes_test.__file__)
def S(self):
return c_longlong.in_dll(self._dll, "last_tf_arg_s").value
def U(self):
return c_ulonglong.in_dll(self._dll, "last_tf_arg_u").value
def test_byte(self):
self._dll.tf_b.restype = c_byte
self._dll.tf_b.argtypes = (c_byte,)
self.assertEqual(self._dll.tf_b(-126), -42)
self.assertEqual(self.S(), -126)
def test_byte_plus(self):
self._dll.tf_bb.restype = c_byte
self._dll.tf_bb.argtypes = (c_byte, c_byte)
self.assertEqual(self._dll.tf_bb(0, -126), -42)
self.assertEqual(self.S(), -126)
def test_ubyte(self):
self._dll.tf_B.restype = c_ubyte
self._dll.tf_B.argtypes = (c_ubyte,)
self.assertEqual(self._dll.tf_B(255), 85)
self.assertEqual(self.U(), 255)
def test_ubyte_plus(self):
self._dll.tf_bB.restype = c_ubyte
self._dll.tf_bB.argtypes = (c_byte, c_ubyte)
self.assertEqual(self._dll.tf_bB(0, 255), 85)
self.assertEqual(self.U(), 255)
def test_short(self):
self._dll.tf_h.restype = c_short
self._dll.tf_h.argtypes = (c_short,)
self.assertEqual(self._dll.tf_h(-32766), -10922)
self.assertEqual(self.S(), -32766)
def test_short_plus(self):
self._dll.tf_bh.restype = c_short
self._dll.tf_bh.argtypes = (c_byte, c_short)
self.assertEqual(self._dll.tf_bh(0, -32766), -10922)
self.assertEqual(self.S(), -32766)
def test_ushort(self):
self._dll.tf_H.restype = c_ushort
self._dll.tf_H.argtypes = (c_ushort,)
self.assertEqual(self._dll.tf_H(65535), 21845)
self.assertEqual(self.U(), 65535)
def test_ushort_plus(self):
self._dll.tf_bH.restype = c_ushort
self._dll.tf_bH.argtypes = (c_byte, c_ushort)
self.assertEqual(self._dll.tf_bH(0, 65535), 21845)
self.assertEqual(self.U(), 65535)
def test_int(self):
self._dll.tf_i.restype = c_int
self._dll.tf_i.argtypes = (c_int,)
self.assertEqual(self._dll.tf_i(-2147483646), -715827882)
self.assertEqual(self.S(), -2147483646)
def test_int_plus(self):
self._dll.tf_bi.restype = c_int
self._dll.tf_bi.argtypes = (c_byte, c_int)
self.assertEqual(self._dll.tf_bi(0, -2147483646), -715827882)
self.assertEqual(self.S(), -2147483646)
def test_uint(self):
self._dll.tf_I.restype = c_uint
self._dll.tf_I.argtypes = (c_uint,)
self.assertEqual(self._dll.tf_I(4294967295), 1431655765)
self.assertEqual(self.U(), 4294967295)
def test_uint_plus(self):
self._dll.tf_bI.restype = c_uint
self._dll.tf_bI.argtypes = (c_byte, c_uint)
self.assertEqual(self._dll.tf_bI(0, 4294967295), 1431655765)
self.assertEqual(self.U(), 4294967295)
def test_long(self):
self._dll.tf_l.restype = c_long
self._dll.tf_l.argtypes = (c_long,)
self.assertEqual(self._dll.tf_l(-2147483646), -715827882)
self.assertEqual(self.S(), -2147483646)
def test_long_plus(self):
self._dll.tf_bl.restype = c_long
self._dll.tf_bl.argtypes = (c_byte, c_long)
self.assertEqual(self._dll.tf_bl(0, -2147483646), -715827882)
self.assertEqual(self.S(), -2147483646)
def test_ulong(self):
self._dll.tf_L.restype = c_ulong
self._dll.tf_L.argtypes = (c_ulong,)
self.assertEqual(self._dll.tf_L(4294967295), 1431655765)
self.assertEqual(self.U(), 4294967295)
def test_ulong_plus(self):
self._dll.tf_bL.restype = c_ulong
self._dll.tf_bL.argtypes = (c_char, c_ulong)
self.assertEqual(self._dll.tf_bL(b' ', 4294967295), 1431655765)
self.assertEqual(self.U(), 4294967295)
def test_longlong(self):
self._dll.tf_q.restype = c_longlong
self._dll.tf_q.argtypes = (c_longlong, )
self.assertEqual(self._dll.tf_q(-9223372036854775806), -3074457345618258602)
self.assertEqual(self.S(), -9223372036854775806)
def test_longlong_plus(self):
self._dll.tf_bq.restype = c_longlong
self._dll.tf_bq.argtypes = (c_byte, c_longlong)
self.assertEqual(self._dll.tf_bq(0, -9223372036854775806), -3074457345618258602)
self.assertEqual(self.S(), -9223372036854775806)
def test_ulonglong(self):
self._dll.tf_Q.restype = c_ulonglong
self._dll.tf_Q.argtypes = (c_ulonglong, )
self.assertEqual(self._dll.tf_Q(18446744073709551615), 6148914691236517205)
self.assertEqual(self.U(), 18446744073709551615)
def test_ulonglong_plus(self):
self._dll.tf_bQ.restype = c_ulonglong
self._dll.tf_bQ.argtypes = (c_byte, c_ulonglong)
self.assertEqual(self._dll.tf_bQ(0, 18446744073709551615), 6148914691236517205)
self.assertEqual(self.U(), 18446744073709551615)
def test_float(self):
self._dll.tf_f.restype = c_float
self._dll.tf_f.argtypes = (c_float,)
self.assertEqual(self._dll.tf_f(-42.), -14.)
self.assertEqual(self.S(), -42)
def test_float_plus(self):
self._dll.tf_bf.restype = c_float
self._dll.tf_bf.argtypes = (c_byte, c_float)
self.assertEqual(self._dll.tf_bf(0, -42.), -14.)
self.assertEqual(self.S(), -42)
def test_double(self):
self._dll.tf_d.restype = c_double
self._dll.tf_d.argtypes = (c_double,)
self.assertEqual(self._dll.tf_d(42.), 14.)
self.assertEqual(self.S(), 42)
def test_double_plus(self):
self._dll.tf_bd.restype = c_double
self._dll.tf_bd.argtypes = (c_byte, c_double)
self.assertEqual(self._dll.tf_bd(0, 42.), 14.)
self.assertEqual(self.S(), 42)
def test_longdouble(self):
self._dll.tf_D.restype = c_longdouble
self._dll.tf_D.argtypes = (c_longdouble,)
self.assertEqual(self._dll.tf_D(42.), 14.)
self.assertEqual(self.S(), 42)
def test_longdouble_plus(self):
self._dll.tf_bD.restype = c_longdouble
self._dll.tf_bD.argtypes = (c_byte, c_longdouble)
self.assertEqual(self._dll.tf_bD(0, 42.), 14.)
self.assertEqual(self.S(), 42)
def test_callwithresult(self):
def process_result(result):
return result * 2
self._dll.tf_i.restype = process_result
self._dll.tf_i.argtypes = (c_int,)
self.assertEqual(self._dll.tf_i(42), 28)
self.assertEqual(self.S(), 42)
self.assertEqual(self._dll.tf_i(-42), -28)
self.assertEqual(self.S(), -42)
def test_void(self):
self._dll.tv_i.restype = None
self._dll.tv_i.argtypes = (c_int,)
self.assertEqual(self._dll.tv_i(42), None)
self.assertEqual(self.S(), 42)
self.assertEqual(self._dll.tv_i(-42), None)
self.assertEqual(self.S(), -42)
# The following repeats the above tests with stdcall functions (where
# they are available)
try:
WinDLL
except NameError:
def stdcall_dll(*_): pass
else:
class stdcall_dll(WinDLL):
def __getattr__(self, name):
if name[:2] == '__' and name[-2:] == '__':
raise AttributeError(name)
func = self._FuncPtr(("s_" + name, self))
setattr(self, name, func)
return func
@need_symbol('WinDLL')
class stdcallCFunctions(CFunctions):
_dll = stdcall_dll(_ctypes_test.__file__)
if __name__ == '__main__':
unittest.main()
| Python36_x64_Template/Lib/ctypes/test/test_cfuncs.py | 7,892 | A lot of failures in these tests on Mac OS X. Byte order related? The following repeats the above tests with stdcall functions (where they are available) | 153 | en | 0.896635 |
# coding: utf-8
# Copyright (c) 2016, 2022, Oracle and/or its affiliates. All rights reserved.
# This software is dual-licensed to you under the Universal Permissive License (UPL) 1.0 as shown at https://oss.oracle.com/licenses/upl or Apache License 2.0 as shown at http://www.apache.org/licenses/LICENSE-2.0. You may choose either license.
from oci.util import formatted_flat_dict, NONE_SENTINEL, value_allowed_none_or_none_sentinel # noqa: F401
from oci.decorators import init_model_state_from_kwargs
@init_model_state_from_kwargs
class WorkRequestLogEntryCollection(object):
"""
Wrapper object for an array of WorkRequestLogEntry objects.
"""
def __init__(self, **kwargs):
"""
Initializes a new WorkRequestLogEntryCollection object with values from keyword arguments.
The following keyword arguments are supported (corresponding to the getters/setters of this class):
:param items:
The value to assign to the items property of this WorkRequestLogEntryCollection.
:type items: list[oci.network_load_balancer.models.WorkRequestLogEntry]
"""
self.swagger_types = {
'items': 'list[WorkRequestLogEntry]'
}
self.attribute_map = {
'items': 'items'
}
self._items = None
@property
def items(self):
"""
Gets the items of this WorkRequestLogEntryCollection.
An array of WorkRequestLogEntry objects.
:return: The items of this WorkRequestLogEntryCollection.
:rtype: list[oci.network_load_balancer.models.WorkRequestLogEntry]
"""
return self._items
@items.setter
def items(self, items):
"""
Sets the items of this WorkRequestLogEntryCollection.
An array of WorkRequestLogEntry objects.
:param items: The items of this WorkRequestLogEntryCollection.
:type: list[oci.network_load_balancer.models.WorkRequestLogEntry]
"""
self._items = items
def __repr__(self):
return formatted_flat_dict(self)
def __eq__(self, other):
if other is None:
return False
return self.__dict__ == other.__dict__
def __ne__(self, other):
return not self == other
| src/oci/network_load_balancer/models/work_request_log_entry_collection.py | 2,272 | Wrapper object for an array of WorkRequestLogEntry objects.
Initializes a new WorkRequestLogEntryCollection object with values from keyword arguments.
The following keyword arguments are supported (corresponding to the getters/setters of this class):
:param items:
The value to assign to the items property of this WorkRequestLogEntryCollection.
:type items: list[oci.network_load_balancer.models.WorkRequestLogEntry]
Gets the items of this WorkRequestLogEntryCollection.
An array of WorkRequestLogEntry objects.
:return: The items of this WorkRequestLogEntryCollection.
:rtype: list[oci.network_load_balancer.models.WorkRequestLogEntry]
Sets the items of this WorkRequestLogEntryCollection.
An array of WorkRequestLogEntry objects.
:param items: The items of this WorkRequestLogEntryCollection.
:type: list[oci.network_load_balancer.models.WorkRequestLogEntry]
coding: utf-8 Copyright (c) 2016, 2022, Oracle and/or its affiliates. All rights reserved. This software is dual-licensed to you under the Universal Permissive License (UPL) 1.0 as shown at https://oss.oracle.com/licenses/upl or Apache License 2.0 as shown at http://www.apache.org/licenses/LICENSE-2.0. You may choose either license. noqa: F401 | 1,219 | en | 0.629945 |
class Solution:
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
lookup = dict(((v, i) for i, v in enumerate(nums)))
return next(( (i+1, lookup.get(target-v)+1)
for i, v in enumerate(nums)
if lookup.get(target-v, i) != i), None)
a = Solution()
print(a.twoSum([2, 11, 7, 15],9))
# 越简单的问题越要小心 | array/twosum.py | 459 | :type nums: List[int]
:type target: int
:rtype: List[int]
越简单的问题越要小心 | 70 | zh | 0.206891 |
#
# @lc app=leetcode id=102 lang=python3
#
# [102] Binary Tree Level Order Traversal
#
# @lc code=start
# Definition for a binary tree node.
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
from typing import List, Optional
class Solution:
def levelOrder(self, root: Optional[TreeNode]) -> List[List[int]]:
ans = []
def _larger(n):
for i in range(len(ans), n + 1):
ans.append([])
def _traversal(node, depth):
if node != None:
_larger(depth)
tmp = ans[depth]
tmp.append(node.val)
_traversal(node.left, depth + 1)
_traversal(node.right, depth + 1)
_traversal(root, 0)
return ans
# @lc code=end
| Difficulty/Medium/102.binary-tree-level-order-traversal.py | 863 | @lc app=leetcode id=102 lang=python3 [102] Binary Tree Level Order Traversal @lc code=start Definition for a binary tree node. @lc code=end | 139 | en | 0.527351 |
# --------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# --------------------------------------------------------------------------------------------
from azure.cli.command_modules.monitor.util import get_operator_map, get_aggregation_map
from knack.log import get_logger
logger = get_logger(__name__)
def create_metric_alert(client, resource_group_name, rule_name, scopes, condition, disabled=False, description=None,
tags=None, actions=None, severity=2, window_size='5m', evaluation_frequency='1m',
auto_mitigate=None):
from azure.mgmt.monitor.models import (MetricAlertResource,
MetricAlertSingleResourceMultipleMetricCriteria,
MetricAlertMultipleResourceMultipleMetricCriteria)
# generate names for the conditions
for i, cond in enumerate(condition):
cond.name = 'cond{}'.format(i)
criteria = None
target_resource_type = None
target_resource_region = None
if len(scopes) == 1:
criteria = MetricAlertSingleResourceMultipleMetricCriteria(all_of=condition)
else:
criteria = MetricAlertMultipleResourceMultipleMetricCriteria(all_of=condition)
target_resource_type = _parse_resource_type(scopes)
target_resource_region = 'global'
kwargs = {
'description': description,
'severity': severity,
'enabled': not disabled,
'scopes': scopes,
'evaluation_frequency': evaluation_frequency,
'window_size': window_size,
'criteria': criteria,
'target_resource_type': target_resource_type,
'target_resource_region': target_resource_region,
'actions': actions,
'tags': tags,
'location': 'global',
'auto_mitigate': auto_mitigate
}
return client.create_or_update(resource_group_name, rule_name, MetricAlertResource(**kwargs))
def update_metric_alert(instance, scopes=None, description=None, enabled=None, tags=None,
severity=None, window_size=None, evaluation_frequency=None, auto_mitigate=None,
add_actions=None, remove_actions=None, add_conditions=None, remove_conditions=None):
if scopes is not None:
instance.scopes = scopes
if description is not None:
instance.description = description
if enabled is not None:
instance.enabled = enabled
if tags is not None:
instance.tags = tags
if severity is not None:
instance.severity = severity
if window_size is not None:
instance.window_size = window_size
if evaluation_frequency is not None:
instance.evaluation_frequency = evaluation_frequency
if auto_mitigate is not None:
instance.auto_mitigate = auto_mitigate
# process action removals
if remove_actions is not None:
instance.actions = [x for x in instance.actions if x.action_group_id.lower() not in remove_actions]
# process action additions
if add_actions is not None:
for action in add_actions:
match = next(
(x for x in instance.actions if action.action_group_id.lower() == x.action_group_id.lower()), None
)
if match:
match.webhook_properties = action.webhook_properties
else:
instance.actions.append(action)
# process condition removals
if remove_conditions is not None:
instance.criteria.all_of = [x for x in instance.criteria.all_of if x.name not in remove_conditions]
def _get_next_name():
i = 0
while True:
possible_name = 'cond{}'.format(i)
match = next((x for x in instance.criteria.all_of if x.name == possible_name), None)
if match:
i = i + 1
continue
return possible_name
# process condition additions
if add_conditions is not None:
for condition in add_conditions:
condition.name = _get_next_name()
instance.criteria.all_of.append(condition)
return instance
def list_metric_alerts(client, resource_group_name=None):
if resource_group_name:
return client.list_by_resource_group(resource_group_name)
return client.list_by_subscription()
def create_metric_rule(client, resource_group_name, rule_name, target, condition, description=None, disabled=False,
location=None, tags=None, email_service_owners=False, actions=None):
from azure.mgmt.monitor.models import AlertRuleResource, RuleEmailAction
condition.data_source.resource_uri = target
custom_emails, webhooks, _ = _parse_actions(actions)
actions = [
RuleEmailAction(send_to_service_owners=email_service_owners, custom_emails=custom_emails)
] + (webhooks or [])
rule = AlertRuleResource(
location=location, alert_rule_resource_name=rule_name, is_enabled=not disabled,
condition=condition, tags=tags, description=description, actions=actions)
return client.create_or_update(resource_group_name, rule_name, rule)
def update_metric_rule(instance, target=None, condition=None, description=None, enabled=None, metric=None,
operator=None, threshold=None, aggregation=None, period=None, tags=None,
email_service_owners=None, add_actions=None, remove_actions=None):
# Update general properties
if description is not None:
instance.description = description
if enabled is not None:
instance.is_enabled = enabled
if tags is not None:
instance.tags = tags
# Update conditions
if condition is not None:
target = target or instance.condition.data_source.resource_uri
instance.condition = condition
if metric is not None:
instance.condition.data_source.metric_name = metric
if operator is not None:
instance.condition.operator = get_operator_map()[operator]
if threshold is not None:
instance.condition.threshold = threshold
if aggregation is not None:
instance.condition.time_aggregation = get_aggregation_map()[aggregation]
if period is not None:
instance.condition.window_size = period
if target is not None:
instance.condition.data_source.resource_uri = target
# Update actions
emails, webhooks, curr_email_service_owners = _parse_actions(instance.actions)
# process removals
if remove_actions is not None:
removed_emails, removed_webhooks = _parse_action_removals(remove_actions)
emails = [x for x in emails if x not in removed_emails]
webhooks = [x for x in webhooks if x.service_uri not in removed_webhooks]
# process additions
if add_actions is not None:
added_emails, added_webhooks, _ = _parse_actions(add_actions)
emails = list(set(emails) | set(added_emails))
webhooks = webhooks + added_webhooks
# Replace the existing actions array. This potentially restructures rules that were created
# via other methods (Portal, ARM template). However, the functionality of these rules should
# be the same.
from azure.mgmt.monitor.models import RuleEmailAction
if email_service_owners is None:
email_service_owners = curr_email_service_owners
actions = [RuleEmailAction(send_to_service_owners=email_service_owners, custom_emails=emails)] + webhooks
instance.actions = actions
return instance
def _parse_actions(actions):
""" Actions come in as a combined list. This method separates the webhook actions into a
separate collection and combines any number of email actions into a single email collection
and a single value for `email_service_owners`. If any email action contains a True value
for `send_to_service_owners` then it is assumed the entire value should be True. """
from azure.mgmt.monitor.models import RuleEmailAction, RuleWebhookAction
actions = actions or []
email_service_owners = None
webhooks = [x for x in actions if isinstance(x, RuleWebhookAction)]
custom_emails = set()
for action in actions:
if isinstance(action, RuleEmailAction):
if action.send_to_service_owners:
email_service_owners = True
custom_emails = custom_emails | set(action.custom_emails)
return list(custom_emails), webhooks, email_service_owners
def _parse_action_removals(actions):
""" Separates the combined list of keys to remove into webhooks and emails. """
flattened = list({x for sublist in actions for x in sublist})
emails = []
webhooks = []
for item in flattened:
if item.startswith('http://') or item.startswith('https://'):
webhooks.append(item)
else:
emails.append(item)
return emails, webhooks
def _parse_resource_type(scopes):
from msrestazure.tools import parse_resource_id
from azure.cli.core import CLIError
namespace = None
resource_type = None
for item in scopes:
item_namespace = parse_resource_id(item)['namespace']
item_resource_type = parse_resource_id(item)['resource_type']
if namespace is None and resource_type is None:
namespace = item_namespace
resource_type = item_resource_type
else:
if namespace != item_namespace or resource_type != item_resource_type:
raise CLIError('Multiple scopes should be the same resource type.')
return namespace + '/' + resource_type
| src/azure-cli/azure/cli/command_modules/monitor/operations/metric_alert.py | 9,763 | Separates the combined list of keys to remove into webhooks and emails.
Actions come in as a combined list. This method separates the webhook actions into a
separate collection and combines any number of email actions into a single email collection
and a single value for `email_service_owners`. If any email action contains a True value
for `send_to_service_owners` then it is assumed the entire value should be True.
-------------------------------------------------------------------------------------------- Copyright (c) Microsoft Corporation. All rights reserved. Licensed under the MIT License. See License.txt in the project root for license information. -------------------------------------------------------------------------------------------- generate names for the conditions process action removals process action additions process condition removals process condition additions Update general properties Update conditions Update actions process removals process additions Replace the existing actions array. This potentially restructures rules that were created via other methods (Portal, ARM template). However, the functionality of these rules should be the same. | 1,185 | en | 0.790578 |
# -*- coding: utf-8 -*-
# cox regression
if __name__ == "__main__":
import pandas as pd
import time
import numpy as np
from lifelines import CoxPHFitter
from lifelines.datasets import load_rossi, load_regression_dataset
reps = 1
df = load_rossi()
df = pd.concat([df] * reps)
cp_breslow = CoxPHFitter(penalizer=0.01, l1_ratio=0.0, baseline_estimation_method="breslow")
start_time = time.time()
cp_breslow.fit(df, duration_col="week", event_col="arrest", show_progress=True)
print("--- %s seconds ---" % (time.time() - start_time))
cp_breslow.print_summary(2)
print(cp_breslow.score(df))
print(cp_breslow.score(df, scoring_method="concordance_index"))
| perf_tests/cp_perf_test.py | 714 | -*- coding: utf-8 -*- cox regression | 36 | en | 0.608391 |
# Copyright 2010 OpenStack Foundation
# 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 datetime
import uuid
from oslo_serialization import jsonutils
from oslo_utils import netutils
from oslo_utils import timeutils
import routes
import six
from six.moves import range
import webob
import webob.dec
import webob.request
from nova.api import auth as api_auth
from nova.api import openstack as openstack_api
from nova.api.openstack import api_version_request as api_version
from nova.api.openstack import auth
from nova.api.openstack import compute
from nova.api.openstack.compute.legacy_v2 import limits
from nova.api.openstack.compute import versions
from nova.api.openstack import urlmap
from nova.api.openstack import wsgi as os_wsgi
from nova.compute import api as compute_api
from nova.compute import flavors
from nova.compute import vm_states
from nova import context
from nova.db.sqlalchemy import models
from nova import exception as exc
import nova.netconf
from nova.network import api as network_api
from nova import objects
from nova.objects import base
from nova import quota
from nova.tests.unit import fake_block_device
from nova.tests.unit import fake_network
from nova.tests.unit.objects import test_keypair
from nova import utils
from nova import wsgi
QUOTAS = quota.QUOTAS
FAKE_UUID = 'aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa'
FAKE_UUIDS = {}
class Context(object):
pass
class FakeRouter(wsgi.Router):
def __init__(self, ext_mgr=None):
pass
@webob.dec.wsgify
def __call__(self, req):
res = webob.Response()
res.status = '200'
res.headers['X-Test-Success'] = 'True'
return res
@webob.dec.wsgify
def fake_wsgi(self, req):
return self.application
def wsgi_app(inner_app_v2=None, fake_auth_context=None,
use_no_auth=False, ext_mgr=None, init_only=None):
if not inner_app_v2:
inner_app_v2 = compute.APIRouter(ext_mgr, init_only)
if use_no_auth:
api_v2 = openstack_api.FaultWrapper(auth.NoAuthMiddleware(
limits.RateLimitingMiddleware(inner_app_v2)))
else:
if fake_auth_context is not None:
ctxt = fake_auth_context
else:
ctxt = context.RequestContext('fake', 'fake', auth_token=True)
api_v2 = openstack_api.FaultWrapper(api_auth.InjectContext(ctxt,
limits.RateLimitingMiddleware(inner_app_v2)))
mapper = urlmap.URLMap()
mapper['/v2'] = api_v2
mapper['/v1.1'] = api_v2
mapper['/'] = openstack_api.FaultWrapper(versions.Versions())
return mapper
def wsgi_app_v21(inner_app_v21=None, fake_auth_context=None,
use_no_auth=False, ext_mgr=None, init_only=None, v2_compatible=False):
if not inner_app_v21:
inner_app_v21 = compute.APIRouterV21(init_only)
if v2_compatible:
inner_app_v21 = openstack_api.LegacyV2CompatibleWrapper(inner_app_v21)
if use_no_auth:
api_v21 = openstack_api.FaultWrapper(auth.NoAuthMiddlewareV3(
limits.RateLimitingMiddleware(inner_app_v21)))
else:
if fake_auth_context is not None:
ctxt = fake_auth_context
else:
ctxt = context.RequestContext('fake', 'fake', auth_token=True)
api_v21 = openstack_api.FaultWrapper(api_auth.InjectContext(ctxt,
limits.RateLimitingMiddleware(inner_app_v21)))
mapper = urlmap.URLMap()
mapper['/v2'] = api_v21
mapper['/v2.1'] = api_v21
mapper['/'] = openstack_api.FaultWrapper(versions.Versions())
return mapper
def stub_out_key_pair_funcs(stubs, have_key_pair=True, **kwargs):
def key_pair(context, user_id):
return [dict(test_keypair.fake_keypair,
name='key', public_key='public_key', **kwargs)]
def one_key_pair(context, user_id, name):
if name == 'key':
return dict(test_keypair.fake_keypair,
name='key', public_key='public_key', **kwargs)
else:
raise exc.KeypairNotFound(user_id=user_id, name=name)
def no_key_pair(context, user_id):
return []
if have_key_pair:
stubs.Set(nova.db, 'key_pair_get_all_by_user', key_pair)
stubs.Set(nova.db, 'key_pair_get', one_key_pair)
else:
stubs.Set(nova.db, 'key_pair_get_all_by_user', no_key_pair)
def stub_out_rate_limiting(stubs):
def fake_rate_init(self, app):
super(limits.RateLimitingMiddleware, self).__init__(app)
self.application = app
v2_limits = nova.api.openstack.compute.legacy_v2.limits
stubs.Set(v2_limits.RateLimitingMiddleware, '__init__', fake_rate_init)
stubs.Set(v2_limits.RateLimitingMiddleware, '__call__', fake_wsgi)
def stub_out_instance_quota(stubs, allowed, quota, resource='instances'):
def fake_reserve(context, **deltas):
requested = deltas.pop(resource, 0)
if requested > allowed:
quotas = dict(instances=1, cores=1, ram=1)
quotas[resource] = quota
usages = dict(instances=dict(in_use=0, reserved=0),
cores=dict(in_use=0, reserved=0),
ram=dict(in_use=0, reserved=0))
usages[resource]['in_use'] = (quotas[resource] * 0.9 -
allowed)
usages[resource]['reserved'] = quotas[resource] * 0.1
raise exc.OverQuota(overs=[resource], quotas=quotas,
usages=usages)
stubs.Set(QUOTAS, 'reserve', fake_reserve)
def stub_out_networking(stubs):
def get_my_ip():
return '127.0.0.1'
stubs.Set(netutils, 'get_my_ipv4', get_my_ip)
def stub_out_compute_api_snapshot(stubs):
def snapshot(self, context, instance, name, extra_properties=None):
# emulate glance rejecting image names which are too long
if len(name) > 256:
raise exc.Invalid
return dict(id='123', status='ACTIVE', name=name,
properties=extra_properties)
stubs.Set(compute_api.API, 'snapshot', snapshot)
class stub_out_compute_api_backup(object):
def __init__(self, stubs):
self.stubs = stubs
self.extra_props_last_call = None
stubs.Set(compute_api.API, 'backup', self.backup)
def backup(self, context, instance, name, backup_type, rotation,
extra_properties=None):
self.extra_props_last_call = extra_properties
props = dict(backup_type=backup_type,
rotation=rotation)
props.update(extra_properties or {})
return dict(id='123', status='ACTIVE', name=name, properties=props)
def stub_out_nw_api_get_instance_nw_info(stubs, num_networks=1, func=None):
fake_network.stub_out_nw_api_get_instance_nw_info(stubs)
def stub_out_nw_api(stubs, cls=None, private=None, publics=None):
if not private:
private = '192.168.0.3'
if not publics:
publics = ['1.2.3.4']
class Fake(object):
def __init__(self, skip_policy_check=False):
pass
def get_instance_nw_info(*args, **kwargs):
pass
def get_floating_ips_by_fixed_address(*args, **kwargs):
return publics
def validate_networks(self, context, networks, max_count):
return max_count
def create_pci_requests_for_sriov_ports(self, context,
system_metadata,
requested_networks):
pass
if cls is None:
cls = Fake
stubs.Set(network_api, 'API', cls)
fake_network.stub_out_nw_api_get_instance_nw_info(stubs)
class FakeToken(object):
id_count = 0
def __getitem__(self, key):
return getattr(self, key)
def __init__(self, **kwargs):
FakeToken.id_count += 1
self.id = FakeToken.id_count
for k, v in six.iteritems(kwargs):
setattr(self, k, v)
class FakeRequestContext(context.RequestContext):
def __init__(self, *args, **kwargs):
kwargs['auth_token'] = kwargs.get('auth_token', 'fake_auth_token')
super(FakeRequestContext, self).__init__(*args, **kwargs)
class HTTPRequest(os_wsgi.Request):
@staticmethod
def blank(*args, **kwargs):
kwargs['base_url'] = 'http://localhost/v2'
use_admin_context = kwargs.pop('use_admin_context', False)
version = kwargs.pop('version', os_wsgi.DEFAULT_API_VERSION)
out = os_wsgi.Request.blank(*args, **kwargs)
out.environ['nova.context'] = FakeRequestContext('fake_user', 'fake',
is_admin=use_admin_context)
out.api_version_request = api_version.APIVersionRequest(version)
return out
class HTTPRequestV21(os_wsgi.Request):
@staticmethod
def blank(*args, **kwargs):
kwargs['base_url'] = 'http://localhost/v3'
use_admin_context = kwargs.pop('use_admin_context', False)
version = kwargs.pop('version', os_wsgi.DEFAULT_API_VERSION)
out = os_wsgi.Request.blank(*args, **kwargs)
out.api_version_request = api_version.APIVersionRequest(version)
out.environ['nova.context'] = FakeRequestContext('fake_user', 'fake',
is_admin=use_admin_context)
return out
class TestRouter(wsgi.Router):
def __init__(self, controller, mapper=None):
if not mapper:
mapper = routes.Mapper()
mapper.resource("test", "tests",
controller=os_wsgi.Resource(controller))
super(TestRouter, self).__init__(mapper)
class TestRouterV21(wsgi.Router):
def __init__(self, controller, mapper=None):
if not mapper:
mapper = routes.Mapper()
mapper.resource("test", "tests",
controller=os_wsgi.ResourceV21(controller))
super(TestRouterV21, self).__init__(mapper)
class FakeAuthDatabase(object):
data = {}
@staticmethod
def auth_token_get(context, token_hash):
return FakeAuthDatabase.data.get(token_hash, None)
@staticmethod
def auth_token_create(context, token):
fake_token = FakeToken(created_at=timeutils.utcnow(), **token)
FakeAuthDatabase.data[fake_token.token_hash] = fake_token
FakeAuthDatabase.data['id_%i' % fake_token.id] = fake_token
return fake_token
@staticmethod
def auth_token_destroy(context, token_id):
token = FakeAuthDatabase.data.get('id_%i' % token_id)
if token and token.token_hash in FakeAuthDatabase.data:
del FakeAuthDatabase.data[token.token_hash]
del FakeAuthDatabase.data['id_%i' % token_id]
class FakeRateLimiter(object):
def __init__(self, application):
self.application = application
@webob.dec.wsgify
def __call__(self, req):
return self.application
def create_info_cache(nw_cache):
if nw_cache is None:
pub0 = ('192.168.1.100',)
pub1 = ('2001:db8:0:1::1',)
def _ip(ip):
return {'address': ip, 'type': 'fixed'}
nw_cache = [
{'address': 'aa:aa:aa:aa:aa:aa',
'id': 1,
'network': {'bridge': 'br0',
'id': 1,
'label': 'test1',
'subnets': [{'cidr': '192.168.1.0/24',
'ips': [_ip(ip) for ip in pub0]},
{'cidr': 'b33f::/64',
'ips': [_ip(ip) for ip in pub1]}]}}]
if not isinstance(nw_cache, six.string_types):
nw_cache = jsonutils.dumps(nw_cache)
return {
"info_cache": {
"network_info": nw_cache,
"deleted": False,
"created_at": None,
"deleted_at": None,
"updated_at": None,
}
}
def get_fake_uuid(token=0):
if token not in FAKE_UUIDS:
FAKE_UUIDS[token] = str(uuid.uuid4())
return FAKE_UUIDS[token]
def fake_instance_get(**kwargs):
def _return_server(context, uuid, columns_to_join=None, use_slave=False):
return stub_instance(1, **kwargs)
return _return_server
def fake_compute_get(**kwargs):
def _return_server_obj(context, uuid, want_objects=False,
expected_attrs=None):
return stub_instance_obj(context, **kwargs)
return _return_server_obj
def fake_actions_to_locked_server(self, context, instance, *args, **kwargs):
raise exc.InstanceIsLocked(instance_uuid=instance['uuid'])
def fake_instance_get_all_by_filters(num_servers=5, **kwargs):
def _return_servers(context, *args, **kwargs):
servers_list = []
marker = None
limit = None
found_marker = False
if "marker" in kwargs:
marker = kwargs["marker"]
if "limit" in kwargs:
limit = kwargs["limit"]
if 'columns_to_join' in kwargs:
kwargs.pop('columns_to_join')
if 'use_slave' in kwargs:
kwargs.pop('use_slave')
if 'sort_keys' in kwargs:
kwargs.pop('sort_keys')
if 'sort_dirs' in kwargs:
kwargs.pop('sort_dirs')
for i in range(num_servers):
uuid = get_fake_uuid(i)
server = stub_instance(id=i + 1, uuid=uuid,
**kwargs)
servers_list.append(server)
if marker is not None and uuid == marker:
found_marker = True
servers_list = []
if marker is not None and not found_marker:
raise exc.MarkerNotFound(marker=marker)
if limit is not None:
servers_list = servers_list[:limit]
return servers_list
return _return_servers
def fake_compute_get_all(num_servers=5, **kwargs):
def _return_servers_objs(context, search_opts=None, limit=None,
marker=None, want_objects=False,
expected_attrs=None, sort_keys=None,
sort_dirs=None):
db_insts = fake_instance_get_all_by_filters()(None,
limit=limit,
marker=marker)
expected = ['metadata', 'system_metadata', 'flavor',
'info_cache', 'security_groups']
return base.obj_make_list(context, objects.InstanceList(),
objects.Instance, db_insts,
expected_attrs=expected)
return _return_servers_objs
def stub_instance(id=1, user_id=None, project_id=None, host=None,
node=None, vm_state=None, task_state=None,
reservation_id="", uuid=FAKE_UUID, image_ref="10",
flavor_id="1", name=None, key_name='',
access_ipv4=None, access_ipv6=None, progress=0,
auto_disk_config=False, display_name=None,
include_fake_metadata=True, config_drive=None,
power_state=None, nw_cache=None, metadata=None,
security_groups=None, root_device_name=None,
limit=None, marker=None,
launched_at=timeutils.utcnow(),
terminated_at=timeutils.utcnow(),
availability_zone='', locked_by=None, cleaned=False,
memory_mb=0, vcpus=0, root_gb=0, ephemeral_gb=0,
instance_type=None, launch_index=0, kernel_id="",
ramdisk_id="", user_data=None):
if user_id is None:
user_id = 'fake_user'
if project_id is None:
project_id = 'fake_project'
if metadata:
metadata = [{'key': k, 'value': v} for k, v in metadata.items()]
elif include_fake_metadata:
metadata = [models.InstanceMetadata(key='seq', value=str(id))]
else:
metadata = []
inst_type = flavors.get_flavor_by_flavor_id(int(flavor_id))
sys_meta = flavors.save_flavor_info({}, inst_type)
if host is not None:
host = str(host)
if key_name:
key_data = 'FAKE'
else:
key_data = ''
if security_groups is None:
security_groups = [{"id": 1, "name": "test", "description": "Foo:",
"project_id": "project", "user_id": "user",
"created_at": None, "updated_at": None,
"deleted_at": None, "deleted": False}]
# ReservationID isn't sent back, hack it in there.
server_name = name or "server%s" % id
if reservation_id != "":
server_name = "reservation_%s" % (reservation_id, )
info_cache = create_info_cache(nw_cache)
if instance_type is None:
instance_type = flavors.get_default_flavor()
flavorinfo = jsonutils.dumps({
'cur': instance_type.obj_to_primitive(),
'old': None,
'new': None,
})
instance = {
"id": int(id),
"created_at": datetime.datetime(2010, 10, 10, 12, 0, 0),
"updated_at": datetime.datetime(2010, 11, 11, 11, 0, 0),
"deleted_at": datetime.datetime(2010, 12, 12, 10, 0, 0),
"deleted": None,
"user_id": user_id,
"project_id": project_id,
"image_ref": image_ref,
"kernel_id": kernel_id,
"ramdisk_id": ramdisk_id,
"launch_index": launch_index,
"key_name": key_name,
"key_data": key_data,
"config_drive": config_drive,
"vm_state": vm_state or vm_states.BUILDING,
"task_state": task_state,
"power_state": power_state,
"memory_mb": memory_mb,
"vcpus": vcpus,
"root_gb": root_gb,
"ephemeral_gb": ephemeral_gb,
"ephemeral_key_uuid": None,
"hostname": display_name or server_name,
"host": host,
"node": node,
"instance_type_id": 1,
"instance_type": inst_type,
"user_data": user_data,
"reservation_id": reservation_id,
"mac_address": "",
"launched_at": launched_at,
"terminated_at": terminated_at,
"availability_zone": availability_zone,
"display_name": display_name or server_name,
"display_description": "",
"locked": locked_by is not None,
"locked_by": locked_by,
"metadata": metadata,
"access_ip_v4": access_ipv4,
"access_ip_v6": access_ipv6,
"uuid": uuid,
"progress": progress,
"auto_disk_config": auto_disk_config,
"name": "instance-%s" % id,
"shutdown_terminate": True,
"disable_terminate": False,
"security_groups": security_groups,
"root_device_name": root_device_name,
"system_metadata": utils.dict_to_metadata(sys_meta),
"pci_devices": [],
"vm_mode": "",
"default_swap_device": "",
"default_ephemeral_device": "",
"launched_on": "",
"cell_name": "",
"architecture": "",
"os_type": "",
"extra": {"numa_topology": None,
"pci_requests": None,
"flavor": flavorinfo,
},
"cleaned": cleaned}
instance.update(info_cache)
instance['info_cache']['instance_uuid'] = instance['uuid']
return instance
def stub_instance_obj(ctxt, *args, **kwargs):
db_inst = stub_instance(*args, **kwargs)
expected = ['metadata', 'system_metadata', 'flavor',
'info_cache', 'security_groups']
inst = objects.Instance._from_db_object(ctxt, objects.Instance(),
db_inst,
expected_attrs=expected)
inst.fault = None
return inst
def stub_volume(id, **kwargs):
volume = {
'id': id,
'user_id': 'fakeuser',
'project_id': 'fakeproject',
'host': 'fakehost',
'size': 1,
'availability_zone': 'fakeaz',
'instance_uuid': 'fakeuuid',
'mountpoint': '/',
'status': 'fakestatus',
'attach_status': 'attached',
'name': 'vol name',
'display_name': 'displayname',
'display_description': 'displaydesc',
'created_at': datetime.datetime(1999, 1, 1, 1, 1, 1),
'snapshot_id': None,
'volume_type_id': 'fakevoltype',
'volume_metadata': [],
'volume_type': {'name': 'vol_type_name'}}
volume.update(kwargs)
return volume
def stub_volume_create(self, context, size, name, description, snapshot,
**param):
vol = stub_volume('1')
vol['size'] = size
vol['display_name'] = name
vol['display_description'] = description
try:
vol['snapshot_id'] = snapshot['id']
except (KeyError, TypeError):
vol['snapshot_id'] = None
vol['availability_zone'] = param.get('availability_zone', 'fakeaz')
return vol
def stub_volume_update(self, context, *args, **param):
pass
def stub_volume_delete(self, context, *args, **param):
pass
def stub_volume_get(self, context, volume_id):
return stub_volume(volume_id)
def stub_volume_notfound(self, context, volume_id):
raise exc.VolumeNotFound(volume_id=volume_id)
def stub_volume_get_all(context, search_opts=None):
return [stub_volume(100, project_id='fake'),
stub_volume(101, project_id='superfake'),
stub_volume(102, project_id='superduperfake')]
def stub_volume_check_attach(self, context, *args, **param):
pass
def stub_snapshot(id, **kwargs):
snapshot = {
'id': id,
'volume_id': 12,
'status': 'available',
'volume_size': 100,
'created_at': timeutils.utcnow(),
'display_name': 'Default name',
'display_description': 'Default description',
'project_id': 'fake'
}
snapshot.update(kwargs)
return snapshot
def stub_snapshot_create(self, context, volume_id, name, description):
return stub_snapshot(100, volume_id=volume_id, display_name=name,
display_description=description)
def stub_compute_volume_snapshot_create(self, context, volume_id, create_info):
return {'snapshot': {'id': 100, 'volumeId': volume_id}}
def stub_snapshot_delete(self, context, snapshot_id):
if snapshot_id == '-1':
raise exc.SnapshotNotFound(snapshot_id=snapshot_id)
def stub_compute_volume_snapshot_delete(self, context, volume_id, snapshot_id,
delete_info):
pass
def stub_snapshot_get(self, context, snapshot_id):
if snapshot_id == '-1':
raise exc.SnapshotNotFound(snapshot_id=snapshot_id)
return stub_snapshot(snapshot_id)
def stub_snapshot_get_all(self, context):
return [stub_snapshot(100, project_id='fake'),
stub_snapshot(101, project_id='superfake'),
stub_snapshot(102, project_id='superduperfake')]
def stub_bdm_get_all_by_instance(context, instance_uuid, use_slave=False):
return [fake_block_device.FakeDbBlockDeviceDict(
{'id': 1, 'source_type': 'volume', 'destination_type': 'volume',
'volume_id': 'volume_id1', 'instance_uuid': instance_uuid}),
fake_block_device.FakeDbBlockDeviceDict(
{'id': 2, 'source_type': 'volume', 'destination_type': 'volume',
'volume_id': 'volume_id2', 'instance_uuid': instance_uuid})]
def fake_get_available_languages():
existing_translations = ['en_GB', 'en_AU', 'de', 'zh_CN', 'en_US']
return existing_translations
def fake_not_implemented(*args, **kwargs):
raise NotImplementedError()
| nova/tests/unit/api/openstack/fakes.py | 24,031 | Copyright 2010 OpenStack Foundation 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. emulate glance rejecting image names which are too long ReservationID isn't sent back, hack it in there. | 711 | en | 0.895235 |
"""Support for Aqualink temperature sensors."""
from __future__ import annotations
from openpeerpower.components.sensor import DOMAIN, SensorEntity
from openpeerpower.config_entries import ConfigEntry
from openpeerpower.const import DEVICE_CLASS_TEMPERATURE, TEMP_CELSIUS, TEMP_FAHRENHEIT
from openpeerpower.core import OpenPeerPower
from . import AqualinkEntity
from .const import DOMAIN as AQUALINK_DOMAIN
PARALLEL_UPDATES = 0
async def async_setup_entry(
opp: OpenPeerPower, config_entry: ConfigEntry, async_add_entities
) -> None:
"""Set up discovered sensors."""
devs = []
for dev in opp.data[AQUALINK_DOMAIN][DOMAIN]:
devs.append(OppAqualinkSensor(dev))
async_add_entities(devs, True)
class OppAqualinkSensor(AqualinkEntity, SensorEntity):
"""Representation of a sensor."""
@property
def name(self) -> str:
"""Return the name of the sensor."""
return self.dev.label
@property
def unit_of_measurement(self) -> str | None:
"""Return the measurement unit for the sensor."""
if self.dev.name.endswith("_temp"):
if self.dev.system.temp_unit == "F":
return TEMP_FAHRENHEIT
return TEMP_CELSIUS
return None
@property
def state(self) -> str | None:
"""Return the state of the sensor."""
if self.dev.state == "":
return None
try:
state = int(self.dev.state)
except ValueError:
state = float(self.dev.state)
return state
@property
def device_class(self) -> str | None:
"""Return the class of the sensor."""
if self.dev.name.endswith("_temp"):
return DEVICE_CLASS_TEMPERATURE
return None
| openpeerpower/components/iaqualink/sensor.py | 1,750 | Representation of a sensor.
Return the class of the sensor.
Return the name of the sensor.
Return the state of the sensor.
Return the measurement unit for the sensor.
Support for Aqualink temperature sensors. | 208 | en | 0.725414 |
"""
Copyright (C) 2020 Piek Solutions LLC
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.
3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
"""
import requests
import binascii
from codecs import getencoder
import time
def enforce_hex(addr):
if type(addr) == int and addr < 256:
return hex(addr).lstrip('0x')
elif type(addr) == str:
return addr.lstrip('0x')
else:
raise ValueError('addr must be hex string or int < 256')
def scanI2c(ip):
"""
scans devices on i2c bus
:return: list of hex string addresses present on i2c bus
"""
try:
req_url = 'http://' + ip + '/i2c/scan'
resp = requests.get(url=req_url)
return resp.content.decode('utf-8')
except ValueError:
print("i2c failed scan")
class I2cHttpDevice:
def __init__(self, ip, dev_addr):
# device address should be hex string
self.url = 'http://' + ip + '/i2c/'
self.dev_addr = enforce_hex(dev_addr)
def read(self, reg_addr, len_read):
"""
read len_read bytes starting from register reg_addr
:param reg_addr: (str) register address to read in hex
:param len_read: (int) number of bytes to read
:return: bytestring of data
"""
assert len_read < 256, "num of bytes to read cannot exceed 255"
hex_reg_addr = enforce_hex(reg_addr)
try:
req_url = '%sread/%s/%s/%d' % (self.url, self.dev_addr, hex_reg_addr, len_read)
resp = requests.get(url=req_url)
return binascii.a2b_hex(resp.content)
except ValueError:
print("i2c failed read")
def write(self, reg_addr, data, len_data=0):
"""
:param reg_addr: (str) register address to write to in hex
:param data: (str or bytes) hex-encoded bytes, ie: '014ce8'
:param len_data: (optional int) dummy variable to support code portability
:return: None
"""
hex_reg_addr = enforce_hex(reg_addr)
if type(data) == bytes:
# to work across python 2+3:
# https://izziswift.com/whats-the-correct-way-to-convert-bytes-to-a-hex-string-in-python-3/
data = getencoder('hex')(data)[0].decode('ascii')
try:
req_url = '%swrite/%s/%s/%s' % (self.url, self.dev_addr, hex_reg_addr, data)
requests.get(url=req_url)
except ValueError:
print("i2c device 0x%s failed write" % self.dev_addr)
class BME280(I2cHttpDevice):
"""
Bosch BME280
https://www.bosch-sensortec.com/media/boschsensortec/downloads/datasheets/bst-bme280-ds002.pdf
code adapted from BME280.py, http://abyz.me.uk/rpi/pigpio/examples.html (2016-08-05)
This example shows that porting the original code to use the Wifi
Papaya Controller is straightforward and minimal
"""
_calib00 = 0x88
_T1 = 0x88 - _calib00
_T2 = 0x8A - _calib00
_T3 = 0x8C - _calib00
_P1 = 0x8E - _calib00
_P2 = 0x90 - _calib00
_P3 = 0x92 - _calib00
_P4 = 0x94 - _calib00
_P5 = 0x96 - _calib00
_P6 = 0x98 - _calib00
_P7 = 0x9A - _calib00
_P8 = 0x9C - _calib00
_P9 = 0x9E - _calib00
_H1 = 0xA1 - _calib00
_chip_id = 0xD0
_reset = 0xE0
_calib26 = 0xE1
_H2 = 0xE1 - _calib26
_H3 = 0xE3 - _calib26
_xE4 = 0xE4 - _calib26
_xE5 = 0xE5 - _calib26
_xE6 = 0xE6 - _calib26
_H6 = 0xE7 - _calib26
_ctrl_hum = 0xF2
_status = 0xF3
_ctrl_meas = 0xF4
_config = 0xF5
_rawdata = 0xF7
_press = 0xF7
_temp = 0xFA
_humid = 0xFD
_p_msb = 0xF7 - _rawdata
_p_lsb = 0xF8 - _rawdata
_p_xlsb = 0xF9 - _rawdata
_t_msb = 0xFA - _rawdata
_t_lsb = 0xFB - _rawdata
_t_xlsb = 0xFC - _rawdata
_h_msb = 0xFD - _rawdata
_h_lsb = 0xFE - _rawdata
_os_ms = [0, 1, 2, 4, 8, 16]
def __init__(self, i2c_conn, gpib_addr, sampling):
super().__init__(i2c_conn, gpib_addr)
# additional initialization procedure
self.sampling = sampling
self._load_calibration()
self.measure_delay = self._measurement_time(sampling, sampling, sampling)
self.t_fine = 0.0
def _s16(self, _calib, off):
v = self._u16(_calib, off)
if v > 32767:
v -= 65536
return v
def _u16(self, _calib, off):
return _calib[off] | (_calib[off + 1] << 8)
def _u8(self, _calib, off):
return _calib[off]
def _s8(self, _calib, off):
v = self._u8(_calib, off)
if v > 127:
v -= 256
return v
def _measurement_time(self, os_temp, os_press, os_hum):
ms = ((1.25 + 2.3 * self._os_ms[os_temp]) +
(0.575 + 2.3 * self._os_ms[os_press]) +
(0.575 + 2.3 * self._os_ms[os_hum]))
return ms / 1000.0
def _load_calibration(self):
d1 = self.read(self._calib00, 26)
self.T1 = self._u16(d1, self._T1)
self.T2 = self._s16(d1, self._T2)
self.T3 = self._s16(d1, self._T3)
self.P1 = self._u16(d1, self._P1)
self.P2 = self._s16(d1, self._P2)
self.P3 = self._s16(d1, self._P3)
self.P4 = self._s16(d1, self._P4)
self.P5 = self._s16(d1, self._P5)
self.P6 = self._s16(d1, self._P6)
self.P7 = self._s16(d1, self._P7)
self.P8 = self._s16(d1, self._P8)
self.P9 = self._s16(d1, self._P9)
self.H1 = self._u8(d1, self._H1)
d2 = self.read(self._calib26, 7)
self.H2 = self._s16(d2, self._H2)
self.H3 = self._u8(d2, self._H3)
t = self._u8(d2, self._xE5)
t_l = t & 15
t_h = (t >> 4) & 15
self.H4 = (self._u8(d2, self._xE4) << 4) | t_l
if self.H4 > 2047:
self.H4 -= 4096
self.H5 = (self._u8(d2, self._xE6) << 4) | t_h
if self.H5 > 2047:
self.H5 -= 4096
self.H6 = self._s8(d2, self._H6)
def _read_raw_data(self):
# write control bytes for oversampling config
self.write(self._ctrl_hum, bytes([self.sampling]), 1)
self.write(self._ctrl_meas, bytes([self.sampling << 5 | self.sampling << 2 | 1]), 1)
time.sleep(self.measure_delay)
# read 8 bytes starting from register self._rawdata
d = self.read(self._rawdata, 8)
# print(''.join(format(x, '02x') for x in d))
msb = d[self._t_msb]
lsb = d[self._t_lsb]
xlsb = d[self._t_xlsb]
raw_t = ((msb << 16) | (lsb << 8) | xlsb) >> 4
msb = d[self._p_msb]
lsb = d[self._p_lsb]
xlsb = d[self._p_xlsb]
raw_p = ((msb << 16) | (lsb << 8) | xlsb) >> 4
msb = d[self._h_msb]
lsb = d[self._h_lsb]
raw_h = (msb << 8) | lsb
return raw_t, raw_p, raw_h
def read_temp(self):
# write measurement control byte
self.write(self._ctrl_meas, bytes([self.sampling << 5 | self.sampling << 2 | 1]), 1)
time.sleep(self.measure_delay)
# read 3 bytes starting from register self._temp
d = self.read(self._temp, 3)
# print(''.join(format(x, '02x') for x in d))
msb, lsb, xlsb = d
raw_t = ((msb << 16) | (lsb << 8) | xlsb) >> 4
var1 = (raw_t / 16384.0 - (self.T1) / 1024.0) * float(self.T2)
var2 = (((raw_t) / 131072.0 - (self.T1) / 8192.0) *
((raw_t) / 131072.0 - (self.T1) / 8192.0)) * (self.T3)
self.t_fine = var1 + var2
t = (var1 + var2) / 5120.0
return t
def read_data(self):
raw_t, raw_p, raw_h = self._read_raw_data()
var1 = (raw_t / 16384.0 - (self.T1) / 1024.0) * float(self.T2)
var2 = (((raw_t) / 131072.0 - (self.T1) / 8192.0) *
((raw_t) / 131072.0 - (self.T1) / 8192.0)) * (self.T3)
self.t_fine = var1 + var2
t = (var1 + var2) / 5120.0
var1 = (self.t_fine / 2.0) - 64000.0
var2 = var1 * var1 * self.P6 / 32768.0
var2 = var2 + (var1 * self.P5 * 2.0)
var2 = (var2 / 4.0) + (self.P4 * 65536.0)
var1 = ((self.P3 * var1 * var1 / 524288.0) + (self.P2 * var1)) / 524288.0
var1 = (1.0 + var1 / 32768.0) * self.P1
if var1 != 0.0:
p = 1048576.0 - raw_p
p = (p - (var2 / 4096.0)) * 6250.0 / var1
var1 = self.P9 * p * p / 2147483648.0
var2 = p * self.P8 / 32768.0
p = p + (var1 + var2 + self.P7) / 16.0
else:
p = 0
h = self.t_fine - 76800.0
h = ((raw_h - ((self.H4) * 64.0 + (self.H5) / 16384.0 * h)) *
((self.H2) / 65536.0 * (1.0 + (self.H6) / 67108864.0 * h *
(1.0 + (self.H3) / 67108864.0 * h))))
h = h * (1.0 - self.H1 * h / 524288.0)
if h > 100.0:
h = 100.0
elif h < 0.0:
h = 0.0
return t, p, h
| python/papaya_i2chttpinst.py | 10,523 | Bosch BME280
https://www.bosch-sensortec.com/media/boschsensortec/downloads/datasheets/bst-bme280-ds002.pdf
code adapted from BME280.py, http://abyz.me.uk/rpi/pigpio/examples.html (2016-08-05)
This example shows that porting the original code to use the Wifi
Papaya Controller is straightforward and minimal
read len_read bytes starting from register reg_addr
:param reg_addr: (str) register address to read in hex
:param len_read: (int) number of bytes to read
:return: bytestring of data
scans devices on i2c bus
:return: list of hex string addresses present on i2c bus
:param reg_addr: (str) register address to write to in hex
:param data: (str or bytes) hex-encoded bytes, ie: '014ce8'
:param len_data: (optional int) dummy variable to support code portability
:return: None
Copyright (C) 2020 Piek Solutions LLC
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.
3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
device address should be hex string to work across python 2+3: https://izziswift.com/whats-the-correct-way-to-convert-bytes-to-a-hex-string-in-python-3/ additional initialization procedure write control bytes for oversampling config read 8 bytes starting from register self._rawdata print(''.join(format(x, '02x') for x in d)) write measurement control byte read 3 bytes starting from register self._temp print(''.join(format(x, '02x') for x in d)) | 2,702 | en | 0.82415 |
# You should modify this for your own use.
# In particular, set the FQDN to your domain name, and
# pick and set a secure SECRET_KEY. If you are going
# to run HA, you will want to modify the SQLALCHEMY
# variables to point to your shared server rather than
# SQLite3.
import os
ENV = os.environ.get("ENV", "dev")
SECRET_KEY = 'top-secret'
SQLALCHEMY_DATABASE_URI = 'sqlite:///db.sqlite'
SQLALCHEMY_TRACK_MODIFICATIONS = False
PERMANENT_SESSION_LIFETIME = 60 * 60 * 20
BOOTSTRAP_CDN_FORCE_SSL = True
BOOTSTRAP_SERVE_LOCAL = True
SCHEME = "https"
FQDN = f'fed-{ENV}.bortels.us'
URL = f'{SCHEME}://{FQDN}'
| app/config.py | 606 | You should modify this for your own use. In particular, set the FQDN to your domain name, and pick and set a secure SECRET_KEY. If you are going to run HA, you will want to modify the SQLALCHEMY variables to point to your shared server rather than SQLite3. | 256 | en | 0.888164 |
# Copyright 2009-2015 Eucalyptus Systems, Inc.
#
# Redistribution and use of this software in source and binary forms,
# with or without modification, are permitted provided that the following
# conditions are met:
#
# Redistributions of source code must retain the above copyright notice,
# this list of conditions and the following disclaimer.
#
# Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in the
# documentation and/or other materials provided with the distribution.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
from requestbuilder import Arg
from euca2ools.commands.iam import IAMRequest, arg_account_name
class DeleteAccount(IAMRequest):
DESCRIPTION = '[Eucalyptus cloud admin only] Delete an account'
ARGS = [arg_account_name(
help='name or ID of the account to delete (required)'),
Arg('-r', '--recursive', dest='Recursive', action='store_const',
const='true', help='''delete all users, groups, and policies
associated with the account as well''')]
| paws/lib/python2.7/site-packages/euca2ools-3.4.1_2_g6b3f62f2-py2.7.egg/euca2ools/commands/iam/deleteaccount.py | 1,881 | Copyright 2009-2015 Eucalyptus Systems, Inc. Redistribution and use of this software in source and binary forms, with or without modification, are permitted provided that the following conditions are met: Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. | 1,297 | en | 0.881214 |
# evaluate cnn for monthly car sales dataset
from math import sqrt
from numpy import array
from numpy import mean
from numpy import std
from pandas import DataFrame
from pandas import concat
from pandas import read_csv
from sklearn.metrics import mean_squared_error
from keras.models import Sequential
from keras.layers import Dense
from keras.layers import Flatten
from keras.layers.convolutional import Conv1D
from keras.layers.convolutional import MaxPooling1D
from matplotlib import pyplot
# split a univariate dataset into train/test sets
def train_test_split(data, n_test):
return data[:-n_test], data[-n_test:]
# transform list into supervised learning format
def series_to_supervised(data, n_in, n_out=1):
df = DataFrame(data)
cols = list()
# input sequence (t-n, ... t-1)
for i in range(n_in, 0, -1):
cols.append(df.shift(i))
# forecast sequence (t, t+1, ... t+n)
for i in range(0, n_out):
cols.append(df.shift(-i))
# put it all together
agg = concat(cols, axis=1)
# drop rows with NaN values
agg.dropna(inplace=True)
return agg.values
# root mean squared error or rmse
def measure_rmse(actual, predicted):
return sqrt(mean_squared_error(actual, predicted))
# fit a model
def model_fit(train, config):
# unpack config
n_input, n_filters, n_kernel, n_epochs, n_batch = config
# prepare data
data = series_to_supervised(train, n_input)
train_x, train_y = data[:, :-1], data[:, -1]
train_x = train_x.reshape((train_x.shape[0], train_x.shape[1], 1))
# define model
model = Sequential()
model.add(Conv1D(n_filters, n_kernel, activation='relu', input_shape=(n_input, 1)))
model.add(Conv1D(n_filters, n_kernel, activation='relu'))
model.add(MaxPooling1D())
model.add(Flatten())
model.add(Dense(1))
model.compile(loss='mse', optimizer='adam')
# fit
model.fit(train_x, train_y, epochs=n_epochs, batch_size=n_batch, verbose=0)
return model
# forecast with a pre-fit model
def model_predict(model, history, config):
# unpack config
n_input, _, _, _, _ = config
# prepare data
x_input = array(history[-n_input:]).reshape((1, n_input, 1))
# forecast
yhat = model.predict(x_input, verbose=0)
return yhat[0]
# walk-forward validation for univariate data
def walk_forward_validation(data, n_test, cfg):
predictions = list()
# split dataset
train, test = train_test_split(data, n_test)
# fit model
model = model_fit(train, cfg)
# seed history with training dataset
history = [x for x in train]
# step over each time-step in the test set
for i in range(len(test)):
# fit model and make forecast for history
yhat = model_predict(model, history, cfg)
# store forecast in list of predictions
predictions.append(yhat)
# add actual observation to history for the next loop
history.append(test[i])
# estimate prediction error
error = measure_rmse(test, predictions)
print(' > %.3f' % error)
return error
# repeat evaluation of a config
def repeat_evaluate(data, config, n_test, n_repeats=30):
# fit and evaluate the model n times
scores = [walk_forward_validation(data, n_test, config) for _ in range(n_repeats)]
return scores
# summarize model performance
def summarize_scores(name, scores):
# print a summary
scores_m, score_std = mean(scores), std(scores)
print('%s: %.3f RMSE (+/- %.3f)' % (name, scores_m, score_std))
# box and whisker plot
pyplot.boxplot(scores)
pyplot.show()
series = read_csv('monthly-car-sales.csv', header=0, index_col=0)
data = series.values
# data split
n_test = 12
# define config
config = [36, 256, 3, 100, 100]
# grid search
scores = repeat_evaluate(data, config, n_test)
# summarize scores
summarize_scores('cnn', scores) | Resources/books/deep_learning_time_series_forecasting/code/chapter_14/03_cnn_forecast_model.py | 3,624 | evaluate cnn for monthly car sales dataset split a univariate dataset into train/test sets transform list into supervised learning format input sequence (t-n, ... t-1) forecast sequence (t, t+1, ... t+n) put it all together drop rows with NaN values root mean squared error or rmse fit a model unpack config prepare data define model fit forecast with a pre-fit model unpack config prepare data forecast walk-forward validation for univariate data split dataset fit model seed history with training dataset step over each time-step in the test set fit model and make forecast for history store forecast in list of predictions add actual observation to history for the next loop estimate prediction error repeat evaluation of a config fit and evaluate the model n times summarize model performance print a summary box and whisker plot data split define config grid search summarize scores | 888 | en | 0.714504 |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import cv2
import numpy as np
from progress.bar import Bar
import time
import torch
import os
try:
from external.nms import soft_nms
except:
print('NMS not imported! If you need it,'
' do \n cd $CenterNet_ROOT/src/lib/external \n make')
from models.decode import ctdet_decode
from models.utils import flip_tensor
from utils.image import get_affine_transform
from utils.post_process import ctdet_post_process
from utils.debugger import Debugger
from .base_detector import BaseDetector
class CtdetDetector(BaseDetector):
def __init__(self, opt):
super(CtdetDetector, self).__init__(opt)
def process(self, images, return_time=False):
with torch.no_grad():
output = self.model(images)[-1]
hm = output['hm'].sigmoid_()
wh = output['wh']
reg = output['reg'] if self.opt.reg_offset else None
if self.opt.flip_test:
hm = (hm[0:1] + flip_tensor(hm[1:2])) / 2
wh = (wh[0:1] + flip_tensor(wh[1:2])) / 2
reg = reg[0:1] if reg is not None else None
torch.cuda.synchronize()
forward_time = time.time()
dets = ctdet_decode(hm, wh, reg=reg, cat_spec_wh=self.opt.cat_spec_wh, K=self.opt.K)
if return_time:
return output, dets, forward_time
else:
return output, dets
def post_process(self, dets, meta, scale=1):
dets = dets.detach().cpu().numpy()
dets = dets.reshape(1, -1, dets.shape[2])
dets = ctdet_post_process(
dets.copy(), [meta['c']], [meta['s']],
meta['out_height'], meta['out_width'], self.opt.num_classes)
for j in range(1, self.num_classes + 1):
dets[0][j] = np.array(dets[0][j], dtype=np.float32).reshape(-1, 5)
dets[0][j][:, :4] /= scale
return dets[0]
def merge_outputs(self, detections):
results = {}
for j in range(1, self.num_classes + 1):
results[j] = np.concatenate(
[detection[j] for detection in detections], axis=0).astype(np.float32)
if len(self.scales) > 1 or self.opt.nms:
soft_nms(results[j], Nt=0.5, method=2)
scores = np.hstack(
[results[j][:, 4] for j in range(1, self.num_classes + 1)])
if len(scores) > self.max_per_image:
kth = len(scores) - self.max_per_image
thresh = np.partition(scores, kth)[kth]
for j in range(1, self.num_classes + 1):
keep_inds = (results[j][:, 4] >= thresh)
results[j] = results[j][keep_inds]
return results
def debug(self, debugger, images, dets, output, scale=1):
detection = dets.detach().cpu().numpy().copy()
detection[:, :, :4] *= self.opt.down_ratio
for i in range(1):
img = images[i].detach().cpu().numpy().transpose(1, 2, 0)
img = ((img * self.std + self.mean) * 255).astype(np.uint8)
pred = debugger.gen_colormap(output['hm'][i].detach().cpu().numpy())
debugger.add_blend_img(img, pred, 'pred_hm_{:.1f}'.format(scale))
debugger.add_img(img, img_id='out_pred_{:.1f}'.format(scale))
for k in range(len(dets[i])):
if detection[i, k, 4] > self.opt.center_thresh:
debugger.add_coco_bbox(detection[i, k, :4], detection[i, k, -1],
detection[i, k, 4],
img_id='out_pred_{:.1f}'.format(scale))
def show_results(self, debugger, image, results):
debugger.add_img(image, img_id='ctdet')
for j in range(1, self.num_classes + 1):
for bbox in results[j]:
if bbox[4] > self.opt.vis_thresh:
debugger.add_coco_bbox(bbox[:4], j - 1, bbox[4], img_id='ctdet')
debugger.show_all_imgs(pause=self.pause)
#prefix = image_name.split('.')[0]
#path = os.path.dirname(self.opt.det_output_path) + '/img'
#debugger.save_all_imgs(path, prefix)
def save_results_only(self, debugger, image, results, image_name):
debugger.add_img(image, img_id='ctdet')
for j in range(1, self.num_classes + 1):
for bbox in results[j]:
if bbox[4] > self.opt.vis_thresh:
debugger.add_coco_bbox(bbox[:4], j - 1, bbox[4], img_id='ctdet')
prefix = image_name.split('.')[0]
path = os.path.dirname(self.opt.det_output_path) + '/img'
debugger.save_all_imgs(path, prefix)
| src/lib/detectors/ctdet.py | 4,275 | prefix = image_name.split('.')[0]path = os.path.dirname(self.opt.det_output_path) + '/img'debugger.save_all_imgs(path, prefix) | 126 | en | 0.156208 |
import abc
from abc import ABCMeta
from typing import Callable
from typing import Iterator
from typing import List
from typing import Optional
from xsdata.codegen.models import Attr
from xsdata.codegen.models import Class
from xsdata.models.config import GeneratorConfig
from xsdata.utils.constants import return_true
class ContainerInterface(abc.ABC):
"""Wrap a list of classes and expose a simple api for easy access and
process."""
__slots__ = ("config",)
def __init__(self, config: GeneratorConfig):
self.config = config
@abc.abstractmethod
def __iter__(self) -> Iterator[Class]:
"""Create an iterator for the class map values."""
@abc.abstractmethod
def find(self, qname: str, condition: Callable = return_true) -> Optional[Class]:
"""Search by qualified name for a specific class with an optional
condition callable."""
@abc.abstractmethod
def find_inner(self, source: Class, qname: str) -> Class:
"""Search by qualified name for a specific inner class or fail."""
@abc.abstractmethod
def add(self, item: Class):
"""Add class item to the container."""
@abc.abstractmethod
def extend(self, items: List[Class]):
"""Add a list of classes the container."""
@abc.abstractmethod
def reset(self, item: Class, qname: str):
"""Update the given class qualified name."""
class HandlerInterface(abc.ABC):
"""Class handler interface."""
__slots__ = ()
@abc.abstractmethod
def process(self, target: Class):
"""Process the given target class."""
class RelativeHandlerInterface(HandlerInterface, metaclass=ABCMeta):
"""Class handler interface with access to the complete classes
container."""
__slots__ = "container"
def __init__(self, container: ContainerInterface):
self.container = container
def base_attrs(self, target: Class) -> List[Attr]:
attrs: List[Attr] = []
for extension in target.extensions:
base = self.container.find(extension.type.qname)
assert base is not None
attrs.extend(base.attrs)
attrs.extend(self.base_attrs(base))
return attrs
class ContainerHandlerInterface(abc.ABC):
"""Class container."""
__slots__ = "container"
def __init__(self, container: ContainerInterface):
self.container = container
@abc.abstractmethod
def run(self):
"""Run the process for the whole container."""
| xsdata/codegen/mixins.py | 2,507 | Class container.
Wrap a list of classes and expose a simple api for easy access and
process.
Class handler interface.
Class handler interface with access to the complete classes
container.
Create an iterator for the class map values.
Add class item to the container.
Add a list of classes the container.
Search by qualified name for a specific class with an optional
condition callable.
Search by qualified name for a specific inner class or fail.
Process the given target class.
Update the given class qualified name.
Run the process for the whole container. | 559 | en | 0.736485 |
"""
Django settings for project project.
Generated by 'django-admin startproject' using Django 1.8.1.
For more information on this file, see
https://docs.djangoproject.com/en/1.8/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.8/ref/settings/
"""
import django
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
import os
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.8/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'y*b^6p#z&cm2)8rzgbp2i4k*+rg2h%60l*bmf6hg&ro!z0-ael'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
# SECURITY WARNING: do not use '*' on production or use some HTTP(S) proxy
ALLOWED_HOSTS = ['*']
# Application definition
INSTALLED_APPS = (
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
)
# Django 1
if django.VERSION[0] == 1:
MIDDLEWARE_CLASSES = (
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
'django.middleware.security.SecurityMiddleware',
)
else:
# Django 2+
MIDDLEWARE = (
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
'django.middleware.security.SecurityMiddleware',
)
ROOT_URLCONF = 'project.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
WSGI_APPLICATION = 'project.wsgi.application'
# Database
# https://docs.djangoproject.com/en/1.8/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
# Internationalization
# https://docs.djangoproject.com/en/1.8/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.8/howto/static-files/
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')
| examples/django-different-port-test-app/project/settings.py | 3,334 | Django settings for project project.
Generated by 'django-admin startproject' using Django 1.8.1.
For more information on this file, see
https://docs.djangoproject.com/en/1.8/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.8/ref/settings/
Build paths inside the project like this: os.path.join(BASE_DIR, ...) Quick-start development settings - unsuitable for production See https://docs.djangoproject.com/en/1.8/howto/deployment/checklist/ SECURITY WARNING: keep the secret key used in production secret! SECURITY WARNING: don't run with debug turned on in production! SECURITY WARNING: do not use '*' on production or use some HTTP(S) proxy Application definition Django 1 Django 2+ Database https://docs.djangoproject.com/en/1.8/ref/settings/databases Internationalization https://docs.djangoproject.com/en/1.8/topics/i18n/ Static files (CSS, JavaScript, Images) https://docs.djangoproject.com/en/1.8/howto/static-files/ | 984 | en | 0.650118 |
from flask import current_app, render_template
from flask_restful import Resource, reqparse
from flask_mail import Message
from utils.authorizations import admin_required
from models.user import UserModel
class Email(Resource):
NO_REPLY = "noreply@codeforpdx.org" # Should this be dwellingly address?
parser = reqparse.RequestParser()
parser.add_argument("user_id", required=True)
parser.add_argument("subject", required=True)
parser.add_argument("body", required=True)
@admin_required
def post(self):
data = Email.parser.parse_args()
user = UserModel.find_by_id(data.user_id)
message = Message(data.subject, sender=Email.NO_REPLY, body=data.body)
message.recipients = [user.email]
current_app.mail.send(message)
return {"message": "Message sent"}
@staticmethod
def send_reset_password_msg(user):
token = user.reset_password_token()
msg = Message(
"Reset password for Dwellingly",
sender=Email.NO_REPLY,
recipients=[user.email],
)
msg.body = render_template("emails/reset_msg.txt", user=user, token=token)
msg.html = render_template("emails/reset_msg.html", user=user, token=token)
current_app.mail.send(msg)
@staticmethod
def send_user_invite_msg(user):
token = user.reset_password_token()
msg = Message(
"Create Your Dwellingly Account",
sender=Email.NO_REPLY,
recipients=[user.email],
)
msg.body = render_template("emails/invite_user_msg.txt", user=user, token=token)
msg.html = render_template(
"emails/invite_user_msg.html", user=user, token=token
)
current_app.mail.send(msg)
| resources/email.py | 1,772 | Should this be dwellingly address? | 34 | en | 0.938511 |
# coding=utf-8
"""
API for dataset indexing, access and search.
"""
from __future__ import absolute_import
import logging
from cachetools.func import lru_cache
from datacube import compat
from datacube.model import Dataset, DatasetType, MetadataType
from datacube.utils import InvalidDocException, check_doc_unchanged, jsonify_document, get_doc_changes, contains
from . import fields
from .exceptions import DuplicateRecordError, UnknownFieldError
_LOG = logging.getLogger(__name__)
class MetadataTypeResource(object):
def __init__(self, db):
"""
:type db: datacube.index.postgres._api.PostgresDb
"""
self._db = db
def add(self, definition, allow_table_lock=False):
"""
:type definition: dict
:param allow_table_lock:
Allow an exclusive lock to be taken on the table while creating the indexes.
This will halt other user's requests until completed.
If false, creation will be slightly slower and cannot be done in a transaction.
:rtype: datacube.model.MetadataType
"""
# This column duplication is getting out of hand:
MetadataType.validate(definition)
name = definition['name']
existing = self._db.get_metadata_type_by_name(name)
if existing:
# They've passed us the same one again. Make sure it matches what is stored.
# TODO: Support for adding/updating search fields?
check_doc_unchanged(
existing.definition,
definition,
'Metadata Type {}'.format(name)
)
else:
self._db.add_metadata_type(
name=name,
definition=definition,
concurrently=not allow_table_lock
)
return self.get_by_name(name)
@lru_cache()
def get(self, id_):
"""
:rtype: datacube.model.MetadataType
"""
return self._make(self._db.get_metadata_type(id_))
@lru_cache()
def get_by_name(self, name):
"""
:rtype: datacube.model.MetadataType
"""
record = self._db.get_metadata_type_by_name(name)
if not record:
return None
return self._make(record)
def check_field_indexes(self, allow_table_lock=False, rebuild_all=False):
"""
Create or replace per-field indexes and views.
:param allow_table_lock:
Allow an exclusive lock to be taken on the table while creating the indexes.
This will halt other user's requests until completed.
If false, creation will be slightly slower and cannot be done in a transaction.
"""
self._db.check_dynamic_fields(concurrently=not allow_table_lock, rebuild_all=rebuild_all)
def _make_many(self, query_rows):
return (self._make(c) for c in query_rows)
def _make(self, query_row):
"""
:rtype list[datacube.model.MetadataType]
"""
definition = query_row['definition']
dataset_ = definition['dataset']
return MetadataType(
query_row['name'],
dataset_,
dataset_search_fields=self._db.get_dataset_fields(query_row),
id_=query_row['id']
)
class DatasetTypeResource(object):
"""
:type _db: datacube.index.postgres._api.PostgresDb
:type metadata_type_resource: MetadataTypeResource
"""
def __init__(self, db, metadata_type_resource):
"""
:type db: datacube.index.postgres._api.PostgresDb
:type metadata_type_resource: MetadataTypeResource
"""
self._db = db
self.metadata_type_resource = metadata_type_resource
def from_doc(self, definition):
"""
Create a Product from its definitions
:param dict definition: product definition document
:rtype: datacube.model.DatasetType
"""
# This column duplication is getting out of hand:
DatasetType.validate(definition)
metadata_type = definition['metadata_type']
# They either specified the name of a metadata type, or specified a metadata type.
# Is it a name?
if isinstance(metadata_type, compat.string_types):
metadata_type = self.metadata_type_resource.get_by_name(metadata_type)
else:
# Otherwise they embedded a document, add it if needed:
metadata_type = self.metadata_type_resource.add(metadata_type, allow_table_lock=False)
if not metadata_type:
raise InvalidDocException('Unknown metadata type: %r' % definition['metadata_type'])
return DatasetType(metadata_type, definition)
def add(self, type_):
"""
Add a Product
:param datacube.model.DatasetType type_: Product to add
:rtype: datacube.model.DatasetType
"""
DatasetType.validate(type_.definition)
existing = self._db.get_dataset_type_by_name(type_.name)
if existing:
# TODO: Support for adding/updating match rules?
# They've passed us the same collection again. Make sure it matches what is stored.
check_doc_unchanged(
existing.definition,
jsonify_document(type_.definition),
'Dataset type {}'.format(type_.name)
)
else:
self._db.add_dataset_type(
name=type_.name,
metadata=type_.metadata_doc,
metadata_type_id=type_.metadata_type.id,
definition=type_.definition
)
return self.get_by_name(type_.name)
def update(self, type_, allow_unsafe_updates=False):
"""
Update a product. Unsafe changes will throw a ValueError by default.
(An unsafe change is anything that may potentially make the product
incompatible with existing datasets of that type)
:param datacube.model.DatasetType type_: Product to add
:param allow_unsafe_updates bool: Allow unsafe changes. Use with caution.
:rtype: datacube.model.DatasetType
"""
DatasetType.validate(type_.definition)
existing = self._db.get_dataset_type_by_name(type_.name)
if not existing:
raise ValueError('Unknown product %s, cannot update – did you intend to add it?' % type_.name)
def handle_unsafe(msg):
if not allow_unsafe_updates:
raise ValueError(msg)
else:
_LOG.warning("Ignoring %s", msg)
# We'll probably want to use offsets in the future (ie. nested dicts), not just keys, but for now this suffices.
safe_keys_to_change = ('description', 'metadata')
doc_changes = get_doc_changes(existing.definition, jsonify_document(type_.definition))
for offset, old_value, new_value in doc_changes:
_LOG.info('Changing %s %s: %r -> %r', type_.name, '.'.join(offset), old_value, new_value)
key_name = offset[0]
if key_name not in safe_keys_to_change:
handle_unsafe('Potentially unsafe update: changing %r of product definition.' % key_name)
# You can safely make the match rules looser but not tighter.
if key_name == 'metadata':
# Tightening them could exclude datasets already matched to the product.
# (which would make search results wrong)
if not contains(old_value, new_value, case_sensitive=True):
handle_unsafe('Unsafe update: new product match rules are not a superset of old ones.')
if doc_changes:
_LOG.info("Updating product %s", type_.name)
self._db.update_dataset_type(
name=type_.name,
metadata=type_.metadata_doc,
metadata_type_id=type_.metadata_type.id,
definition=type_.definition
)
# Clear our local cache. Note that other users may still have
# cached copies for the duration of their connections.
self.get_by_name.cache_clear()
self.get.cache_clear()
else:
_LOG.info("No changes detected for product %s", type_.name)
def update_document(self, definition, allow_unsafe_update=False):
"""
Update a Product using its difinition
:param dict definition: product definition document
:rtype: datacube.model.DatasetType
"""
type_ = self.from_doc(definition)
return self.update(type_, allow_unsafe_updates=allow_unsafe_update)
def add_document(self, definition):
"""
Add a Product using its difinition
:param dict definition: product definition document
:rtype: datacube.model.DatasetType
"""
type_ = self.from_doc(definition)
return self.add(type_)
@lru_cache()
def get(self, id_):
"""
Retrieve Product by id
:param int id_: id of the Product
:rtype: datacube.model.DatasetType
"""
return self._make(self._db.get_dataset_type(id_))
@lru_cache()
def get_by_name(self, name):
"""
Retrieve Product by name
:param str name: name of the Product
:rtype: datacube.model.DatasetType
"""
result = self._db.get_dataset_type_by_name(name)
if not result:
return None
return self._make(result)
def get_with_fields(self, field_names):
"""
Return dataset types that have all the given fields.
:param tuple[str] field_names:
:rtype: __generator[DatasetType]
"""
for type_ in self.get_all():
for name in field_names:
if name not in type_.metadata_type.dataset_fields:
break
else:
yield type_
def search(self, **query):
"""
Return dataset types that have all the given fields.
:param dict query:
:rtype: __generator[DatasetType]
"""
for type_, q in self.search_robust(**query):
if not q:
yield type_
def search_robust(self, **query):
"""
Return dataset types that match match-able fields and dict of remaining un-matchable fields.
:param dict query:
:rtype: __generator[(DatasetType, dict)]
"""
for type_ in self.get_all():
q = query.copy()
if q.pop('product', type_.name) != type_.name:
continue
if q.pop('metadata_type', type_.metadata_type.name) != type_.metadata_type.name:
continue
for key, value in list(q.items()):
try:
exprs = fields.to_expressions(type_.metadata_type.dataset_fields.get, **{key: value})
except UnknownFieldError as e:
break
try:
if all(expr.evaluate(type_.metadata_doc) for expr in exprs):
q.pop(key)
else:
break
except (AttributeError, KeyError, ValueError) as e:
continue
else:
yield type_, q
def get_all(self):
"""
Retrieve all Products
:rtype: iter[datacube.model.DatasetType]
"""
return (self._make(record) for record in self._db.get_all_dataset_types())
def _make_many(self, query_rows):
return (self._make(c) for c in query_rows)
def _make(self, query_row):
"""
:rtype datacube.model.DatasetType
"""
return DatasetType(
definition=query_row['definition'],
metadata_type=self.metadata_type_resource.get(query_row['metadata_type_ref']),
id_=query_row['id'],
)
class DatasetResource(object):
"""
:type _db: datacube.index.postgres._api.PostgresDb
:type types: datacube.index._datasets.DatasetTypeResource
"""
def __init__(self, db, dataset_type_resource):
"""
:type db: datacube.index.postgres._api.PostgresDb
:type dataset_type_resource: datacube.index._datasets.DatasetTypeResource
"""
self._db = db
self.types = dataset_type_resource
def get(self, id_, include_sources=False):
"""
Get dataset by id
:param uuid id_: id of the dataset to retrieve
:param bool include_sources: get the full provenance graph?
:rtype: datacube.model.Dataset
"""
if not include_sources:
return self._make(self._db.get_dataset(id_), full_info=True)
datasets = {result['id']: (self._make(result, full_info=True), result)
for result in self._db.get_dataset_sources(id_)}
for dataset, result in datasets.values():
dataset.metadata_doc['lineage']['source_datasets'] = {
classifier: datasets[str(source)][0].metadata_doc
for source, classifier in zip(result['sources'], result['classes']) if source
}
dataset.sources = {
classifier: datasets[str(source)][0]
for source, classifier in zip(result['sources'], result['classes']) if source
}
return datasets[id_][0]
def get_derived(self, id_):
"""
Get drived datasets
:param uuid id_: dataset id
:rtype: list[datacube.model.Dataset]
"""
return [self._make(result) for result in self._db.get_derived_datasets(id_)]
def has(self, dataset):
"""
Have we already indexed this dataset?
:param datacube.model.Dataset dataset: dataset to check
:rtype: bool
"""
return self._db.contains_dataset(dataset.id)
def add(self, dataset, skip_sources=False):
"""
Ensure a dataset is in the index. Add it if not present.
:param datacube.model.Dataset dataset: dataset to add
:param bool skip_sources: don't attempt to index source (use when sources are already indexed)
:rtype: datacube.model.Dataset
"""
if not skip_sources:
for source in dataset.sources.values():
self.add(source)
was_inserted = False
sources_tmp = dataset.type.dataset_reader(dataset.metadata_doc).sources
dataset.type.dataset_reader(dataset.metadata_doc).sources = {}
try:
_LOG.info('Indexing %s', dataset.id)
with self._db.begin() as transaction:
try:
was_inserted = transaction.insert_dataset(dataset.metadata_doc, dataset.id, dataset.type.id)
for classifier, source_dataset in dataset.sources.items():
transaction.insert_dataset_source(classifier, dataset.id, source_dataset.id)
# try to update location in the same transaction as insertion.
# if insertion fails we'll try updating location later
# if insertion succeeds the location bit can't possibly fail
if dataset.local_uri:
transaction.ensure_dataset_location(dataset.id, dataset.local_uri)
except DuplicateRecordError as e:
_LOG.warning(str(e))
if not was_inserted:
existing = self.get(dataset.id)
if existing:
check_doc_unchanged(
existing.metadata_doc,
jsonify_document(dataset.metadata_doc),
'Dataset {}'.format(dataset.id)
)
# reinsert attempt? try updating the location
if dataset.local_uri:
try:
self._db.ensure_dataset_location(dataset.id, dataset.local_uri)
except DuplicateRecordError as e:
_LOG.warning(str(e))
finally:
dataset.type.dataset_reader(dataset.metadata_doc).sources = sources_tmp
return dataset
def archive(self, ids):
"""
Mark datasets as archived
:param list[uuid] ids: list of dataset ids to archive
"""
with self._db.begin() as transaction:
for id_ in ids:
transaction.archive_dataset(id_)
def restore(self, ids):
"""
Mark datasets as not archived
:param list[uuid] ids: list of dataset ids to restore
"""
with self._db.begin() as transaction:
for id_ in ids:
transaction.restore_dataset(id_)
def get_field_names(self, type_name=None):
"""
:param str type_name:
:rtype: __generator[str]
"""
if type_name is None:
types = self.types.get_all()
else:
types = [self.types.get_by_name(type_name)]
for type_ in types:
for name in type_.metadata_type.dataset_fields:
yield name
def get_locations(self, dataset):
"""
:param datacube.model.Dataset dataset: dataset
:rtype: list[str]
"""
return self._db.get_locations(dataset.id)
def _make(self, dataset_res, full_info=False):
"""
:rtype datacube.model.Dataset
:param bool full_info: Include all available fields
"""
return Dataset(
self.types.get(dataset_res.dataset_type_ref),
dataset_res.metadata,
dataset_res.local_uri,
indexed_by=dataset_res.added_by if full_info else None,
indexed_time=dataset_res.added if full_info else None
)
def _make_many(self, query_result):
"""
:rtype list[datacube.model.Dataset]
"""
return (self._make(dataset) for dataset in query_result)
def search_by_metadata(self, metadata):
"""
Perform a search using arbitrary metadata, returning results as Dataset objects.
Caution – slow! This will usually not use indexes.
:param dict metadata:
:rtype: list[datacube.model.Dataset]
"""
return self._make_many(self._db.search_datasets_by_metadata(metadata))
def search(self, **query):
"""
Perform a search, returning results as Dataset objects.
:param dict[str,str|float|datacube.model.Range] query:
:rtype: __generator[datacube.model.Dataset]
"""
for dataset_type, datasets in self._do_search_by_product(query):
for dataset in self._make_many(datasets):
yield dataset
def search_by_product(self, **query):
"""
Perform a search, returning datasets grouped by product type.
:param dict[str,str|float|datacube.model.Range] query:
:rtype: __generator[(datacube.model.DatasetType, __generator[datacube.model.Dataset])]]
"""
for dataset_type, datasets in self._do_search_by_product(query):
yield dataset_type, self._make_many(datasets)
def count(self, **query):
"""
Perform a search, returning count of results.
:param dict[str,str|float|datacube.model.Range] query:
:rtype: int
"""
# This may be optimised into one query in the future.
result = 0
for product_type, count in self._do_count_by_product(query):
result += count
return result
def count_by_product(self, **query):
"""
Perform a search, returning a count of for each matching product type.
:param dict[str,str|float|datacube.model.Range] query:
:returns: Sequence of (product, count)
:rtype: __generator[(datacube.model.DatasetType, int)]]
"""
return self._do_count_by_product(query)
def count_by_product_through_time(self, period, **query):
"""
Perform a search, returning counts for each product grouped in time slices
of the given period.
:param dict[str,str|float|datacube.model.Range] query:
:param str period: Time range for each slice: '1 month', '1 day' etc.
:returns: For each matching product type, a list of time ranges and their count.
:rtype: __generator[(datacube.model.DatasetType, list[(datetime.datetime, datetime.datetime), int)]]
"""
return self._do_time_count(period, query)
def count_product_through_time(self, period, **query):
"""
Perform a search, returning counts for a single product grouped in time slices
of the given period.
Will raise an error if the search terms match more than one product.
:param dict[str,str|float|datacube.model.Range] query:
:param str period: Time range for each slice: '1 month', '1 day' etc.
:returns: For each matching product type, a list of time ranges and their count.
:rtype: list[(str, list[(datetime.datetime, datetime.datetime), int)]]
"""
return next(self._do_time_count(period, query, ensure_single=True))[1]
def _get_dataset_types(self, q):
types = set()
if 'product' in q.keys():
types.add(self.types.get_by_name(q['product']))
else:
# Otherwise search any metadata type that has all the given search fields.
types = self.types.get_with_fields(tuple(q.keys()))
if not types:
raise ValueError('No type of dataset has fields: %r', tuple(q.keys()))
return types
def _get_product_queries(self, query):
for dataset_type, q in self.types.search_robust(**query):
q['dataset_type_id'] = dataset_type.id
yield q, dataset_type
def _do_search_by_product(self, query, return_fields=False, with_source_ids=False):
for q, dataset_type in self._get_product_queries(query):
dataset_fields = dataset_type.metadata_type.dataset_fields
query_exprs = tuple(fields.to_expressions(dataset_fields.get, **q))
select_fields = None
if return_fields:
select_fields = tuple(dataset_fields.values())
yield (dataset_type,
self._db.search_datasets(
query_exprs,
select_fields=select_fields,
with_source_ids=with_source_ids
))
def _do_count_by_product(self, query):
for q, dataset_type in self._get_product_queries(query):
dataset_fields = dataset_type.metadata_type.dataset_fields
query_exprs = tuple(fields.to_expressions(dataset_fields.get, **q))
count = self._db.count_datasets(query_exprs)
if count > 0:
yield dataset_type, count
def _do_time_count(self, period, query, ensure_single=False):
if 'time' not in query:
raise ValueError('Counting through time requires a "time" range query argument')
query = dict(query)
start, end = query['time']
del query['time']
product_quries = list(self._get_product_queries(query))
if ensure_single:
if len(product_quries) == 0:
raise ValueError('No products match search terms: %r' % query)
if len(product_quries) > 1:
raise ValueError('Multiple products match single query search: %r' %
([dt.name for q, dt in product_quries],))
for q, dataset_type in product_quries:
dataset_fields = dataset_type.metadata_type.dataset_fields
query_exprs = tuple(fields.to_expressions(dataset_fields.get, **q))
yield dataset_type, list(self._db.count_datasets_through_time(
start,
end,
period,
dataset_fields.get('time'),
query_exprs
))
def search_summaries(self, **query):
"""
Perform a search, returning just the search fields of each dataset.
:param dict[str,str|float|datacube.model.Range] query:
:rtype: dict
"""
for dataset_type, results in self._do_search_by_product(query, return_fields=True):
for columns in results:
yield dict(columns)
def search_eager(self, **query):
"""
Perform a search, returning results as Dataset objects.
:param dict[str,str|float|datacube.model.Range] query:
:rtype: list[datacube.model.Dataset]
"""
return list(self.search(**query))
| datacube/index/_datasets.py | 24,690 | :type _db: datacube.index.postgres._api.PostgresDb
:type types: datacube.index._datasets.DatasetTypeResource
:type _db: datacube.index.postgres._api.PostgresDb
:type metadata_type_resource: MetadataTypeResource
:type db: datacube.index.postgres._api.PostgresDb
:type db: datacube.index.postgres._api.PostgresDb
:type metadata_type_resource: MetadataTypeResource
:type db: datacube.index.postgres._api.PostgresDb
:type dataset_type_resource: datacube.index._datasets.DatasetTypeResource
:rtype list[datacube.model.MetadataType]
:rtype datacube.model.DatasetType
:rtype datacube.model.Dataset
:param bool full_info: Include all available fields
:rtype list[datacube.model.Dataset]
:type definition: dict
:param allow_table_lock:
Allow an exclusive lock to be taken on the table while creating the indexes.
This will halt other user's requests until completed.
If false, creation will be slightly slower and cannot be done in a transaction.
:rtype: datacube.model.MetadataType
Add a Product
:param datacube.model.DatasetType type_: Product to add
:rtype: datacube.model.DatasetType
Ensure a dataset is in the index. Add it if not present.
:param datacube.model.Dataset dataset: dataset to add
:param bool skip_sources: don't attempt to index source (use when sources are already indexed)
:rtype: datacube.model.Dataset
Add a Product using its difinition
:param dict definition: product definition document
:rtype: datacube.model.DatasetType
Mark datasets as archived
:param list[uuid] ids: list of dataset ids to archive
Create or replace per-field indexes and views.
:param allow_table_lock:
Allow an exclusive lock to be taken on the table while creating the indexes.
This will halt other user's requests until completed.
If false, creation will be slightly slower and cannot be done in a transaction.
Perform a search, returning count of results.
:param dict[str,str|float|datacube.model.Range] query:
:rtype: int
Perform a search, returning a count of for each matching product type.
:param dict[str,str|float|datacube.model.Range] query:
:returns: Sequence of (product, count)
:rtype: __generator[(datacube.model.DatasetType, int)]]
Perform a search, returning counts for each product grouped in time slices
of the given period.
:param dict[str,str|float|datacube.model.Range] query:
:param str period: Time range for each slice: '1 month', '1 day' etc.
:returns: For each matching product type, a list of time ranges and their count.
:rtype: __generator[(datacube.model.DatasetType, list[(datetime.datetime, datetime.datetime), int)]]
Perform a search, returning counts for a single product grouped in time slices
of the given period.
Will raise an error if the search terms match more than one product.
:param dict[str,str|float|datacube.model.Range] query:
:param str period: Time range for each slice: '1 month', '1 day' etc.
:returns: For each matching product type, a list of time ranges and their count.
:rtype: list[(str, list[(datetime.datetime, datetime.datetime), int)]]
Create a Product from its definitions
:param dict definition: product definition document
:rtype: datacube.model.DatasetType
:rtype: datacube.model.MetadataType
Retrieve Product by id
:param int id_: id of the Product
:rtype: datacube.model.DatasetType
Get dataset by id
:param uuid id_: id of the dataset to retrieve
:param bool include_sources: get the full provenance graph?
:rtype: datacube.model.Dataset
Retrieve all Products
:rtype: iter[datacube.model.DatasetType]
:rtype: datacube.model.MetadataType
Retrieve Product by name
:param str name: name of the Product
:rtype: datacube.model.DatasetType
Get drived datasets
:param uuid id_: dataset id
:rtype: list[datacube.model.Dataset]
:param str type_name:
:rtype: __generator[str]
:param datacube.model.Dataset dataset: dataset
:rtype: list[str]
Return dataset types that have all the given fields.
:param tuple[str] field_names:
:rtype: __generator[DatasetType]
Have we already indexed this dataset?
:param datacube.model.Dataset dataset: dataset to check
:rtype: bool
Mark datasets as not archived
:param list[uuid] ids: list of dataset ids to restore
Return dataset types that have all the given fields.
:param dict query:
:rtype: __generator[DatasetType]
Perform a search, returning results as Dataset objects.
:param dict[str,str|float|datacube.model.Range] query:
:rtype: __generator[datacube.model.Dataset]
Perform a search using arbitrary metadata, returning results as Dataset objects.
Caution – slow! This will usually not use indexes.
:param dict metadata:
:rtype: list[datacube.model.Dataset]
Perform a search, returning datasets grouped by product type.
:param dict[str,str|float|datacube.model.Range] query:
:rtype: __generator[(datacube.model.DatasetType, __generator[datacube.model.Dataset])]]
Perform a search, returning results as Dataset objects.
:param dict[str,str|float|datacube.model.Range] query:
:rtype: list[datacube.model.Dataset]
Return dataset types that match match-able fields and dict of remaining un-matchable fields.
:param dict query:
:rtype: __generator[(DatasetType, dict)]
Perform a search, returning just the search fields of each dataset.
:param dict[str,str|float|datacube.model.Range] query:
:rtype: dict
Update a product. Unsafe changes will throw a ValueError by default.
(An unsafe change is anything that may potentially make the product
incompatible with existing datasets of that type)
:param datacube.model.DatasetType type_: Product to add
:param allow_unsafe_updates bool: Allow unsafe changes. Use with caution.
:rtype: datacube.model.DatasetType
Update a Product using its difinition
:param dict definition: product definition document
:rtype: datacube.model.DatasetType
API for dataset indexing, access and search.
coding=utf-8 This column duplication is getting out of hand: They've passed us the same one again. Make sure it matches what is stored. TODO: Support for adding/updating search fields? This column duplication is getting out of hand: They either specified the name of a metadata type, or specified a metadata type. Is it a name? Otherwise they embedded a document, add it if needed: TODO: Support for adding/updating match rules? They've passed us the same collection again. Make sure it matches what is stored. We'll probably want to use offsets in the future (ie. nested dicts), not just keys, but for now this suffices. You can safely make the match rules looser but not tighter. Tightening them could exclude datasets already matched to the product. (which would make search results wrong) Clear our local cache. Note that other users may still have cached copies for the duration of their connections. try to update location in the same transaction as insertion. if insertion fails we'll try updating location later if insertion succeeds the location bit can't possibly fail reinsert attempt? try updating the location This may be optimised into one query in the future. Otherwise search any metadata type that has all the given search fields. | 7,016 | en | 0.662909 |
"""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
"""
import configparser
# -- 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('.'))
# Get the global config info as currently stated
# (we use the config file to avoid actually loading any python here)
config = configparser.ConfigParser()
config.read(["../../src/sqlfluff/config.ini"])
stable_version = config.get("sqlfluff", "stable_version")
# -- Project information -----------------------------------------------------
project = "SQLFluff"
copyright = "2019, Alan Cruickshank"
author = "Alan Cruickshank"
# The full version, including alpha/beta/rc tags
release = stable_version
# -- 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 = [
# Autodocumentation from docstrings
"sphinx.ext.autodoc",
# Allow Google style docstrings
"sphinx.ext.napoleon",
# Documenting click commands
"sphinx_click.ext",
]
# 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 = []
# Master doc
master_doc = "index"
# If true, the current module name will be prepended to all description
# unit titles (such as .. function::).
add_module_names = False
# -- Options for HTML output -------------------------------------------------
# The theme to use for HTML and HTML Help pages. See the documentation for
# a list of builtin themes.
#
html_theme = "alabaster"
html_favicon = "favicon-fluff.png"
# Add any paths that contain custom static files (such as style sheets) here,
# relative to this directory. They are copied after the builtin static files,
# so a file named "default.css" will overwrite the builtin "default.css".
html_static_path = ["_static"]
# -- Options for Alabaster Theme ---------------------------------------------
html_theme_options = {
"logo": "images/sqlfluff-lrg.png",
# Icon for iOS shortcuts
"touch_icon": "images/sqlfluff-sm2-sq.png",
"github_user": "sqlfluff",
"github_repo": "sqlfluff",
# Github Fork button
"github_banner": True,
# Github link button
"github_button": True,
# Codecov button
"codecov_button": True,
}
def ultimate_replace(app, docname, source):
"""Replaces variables in docs, including code blocks.
From: https://github.com/sphinx-doc/sphinx/issues/4054#issuecomment-329097229
"""
result = source[0]
for key in app.config.ultimate_replacements:
result = result.replace(key, app.config.ultimate_replacements[key])
source[0] = result
ultimate_replacements = {"|release|": release}
def setup(app):
"""Configures the documentation app."""
app.add_config_value("ultimate_replacements", {}, True)
app.connect("source-read", ultimate_replace)
| docs/source/conf.py | 3,715 | Configures the documentation app.
Replaces variables in docs, including code blocks.
From: https://github.com/sphinx-doc/sphinx/issues/4054#issuecomment-329097229
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('.')) Get the global config info as currently stated (we use the config file to avoid actually loading any python here) -- Project information ----------------------------------------------------- The full version, including alpha/beta/rc tags -- 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. Autodocumentation from docstrings Allow Google style docstrings Documenting click commands 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. Master doc If true, the current module name will be prepended to all description unit titles (such as .. function::). -- 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". -- Options for Alabaster Theme --------------------------------------------- Icon for iOS shortcuts Github Fork button Github link button Codecov button | 2,236 | en | 0.647587 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright 1999-2021 Alibaba Group Holding Ltd.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import numpy as np
from ... import opcodes as OperandDef
from ..utils import infer_dtype
from .core import TensorBinOp
from .utils import arithmetic_operand
@arithmetic_operand(sparse_mode='binary_and')
class TensorHypot(TensorBinOp):
_op_type_ = OperandDef.HYPOT
_func_name = 'hypot'
@infer_dtype(np.hypot)
def hypot(x1, x2, out=None, where=None, **kwargs):
"""
Given the "legs" of a right triangle, return its hypotenuse.
Equivalent to ``sqrt(x1**2 + x2**2)``, element-wise. If `x1` or
`x2` is scalar_like (i.e., unambiguously cast-able to a scalar type),
it is broadcast for use with each element of the other argument.
(See Examples)
Parameters
----------
x1, x2 : array_like
Leg of the triangle(s).
out : Tensor, None, or tuple of Tensor and None, optional
A location into which the result is stored. If provided, it must have
a shape that the inputs broadcast to. If not provided or `None`,
a freshly-allocated array is returned. A tuple (possible only as a
keyword argument) must have length equal to the number of outputs.
where : array_like, optional
Values of True indicate to calculate the ufunc at that position, values
of False indicate to leave the value in the output alone.
**kwargs
Returns
-------
z : Tensor
The hypotenuse of the triangle(s).
Examples
--------
>>> import mars.tensor as mt
>>> mt.hypot(3*mt.ones((3, 3)), 4*mt.ones((3, 3))).execute()
array([[ 5., 5., 5.],
[ 5., 5., 5.],
[ 5., 5., 5.]])
Example showing broadcast of scalar_like argument:
>>> mt.hypot(3*mt.ones((3, 3)), [4]).execute()
array([[ 5., 5., 5.],
[ 5., 5., 5.],
[ 5., 5., 5.]])
"""
op = TensorHypot(**kwargs)
return op(x1, x2, out=out, where=where)
| mars/tensor/arithmetic/hypot.py | 2,532 | Given the "legs" of a right triangle, return its hypotenuse.
Equivalent to ``sqrt(x1**2 + x2**2)``, element-wise. If `x1` or
`x2` is scalar_like (i.e., unambiguously cast-able to a scalar type),
it is broadcast for use with each element of the other argument.
(See Examples)
Parameters
----------
x1, x2 : array_like
Leg of the triangle(s).
out : Tensor, None, or tuple of Tensor and None, optional
A location into which the result is stored. If provided, it must have
a shape that the inputs broadcast to. If not provided or `None`,
a freshly-allocated array is returned. A tuple (possible only as a
keyword argument) must have length equal to the number of outputs.
where : array_like, optional
Values of True indicate to calculate the ufunc at that position, values
of False indicate to leave the value in the output alone.
**kwargs
Returns
-------
z : Tensor
The hypotenuse of the triangle(s).
Examples
--------
>>> import mars.tensor as mt
>>> mt.hypot(3*mt.ones((3, 3)), 4*mt.ones((3, 3))).execute()
array([[ 5., 5., 5.],
[ 5., 5., 5.],
[ 5., 5., 5.]])
Example showing broadcast of scalar_like argument:
>>> mt.hypot(3*mt.ones((3, 3)), [4]).execute()
array([[ 5., 5., 5.],
[ 5., 5., 5.],
[ 5., 5., 5.]])
!/usr/bin/env python -*- coding: utf-8 -*- Copyright 1999-2021 Alibaba Group Holding Ltd. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. | 1,903 | en | 0.707323 |
from enum import Enum
class IndexMethod(str, Enum):
"""
Used to specify the index method for a
:class:`Column <piccolo.columns.base.Column>`.
"""
btree = "btree"
hash = "hash"
gist = "gist"
gin = "gin"
def __str__(self):
return f"{self.__class__.__name__}.{self.name}"
def __repr__(self):
return self.__str__()
| piccolo/columns/indexes.py | 372 | Used to specify the index method for a
:class:`Column <piccolo.columns.base.Column>`. | 85 | en | 0.11755 |
# -*- coding: utf-8 -*-
#
# Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# DO NOT EDIT! This is a generated sample ("Request", "language_entities_gcs")
# To install the latest published package dependency, execute the following:
# pip install google-cloud-language
# sample-metadata
# title: Analyzing Entities (GCS)
# description: Analyzing Entities in text file stored in Cloud Storage
# usage: python3 samples/v1/language_entities_gcs.py [--gcs_content_uri "gs://cloud-samples-data/language/entity.txt"]
# [START language_entities_gcs]
from google.cloud import language_v1
from google.cloud.language_v1 import enums
def sample_analyze_entities(gcs_content_uri):
"""
Analyzing Entities in text file stored in Cloud Storage
Args:
gcs_content_uri Google Cloud Storage URI where the file content is located.
e.g. gs://[Your Bucket]/[Path to File]
"""
client = language_v1.LanguageServiceClient()
# gcs_content_uri = 'gs://cloud-samples-data/language/entity.txt'
# Available types: PLAIN_TEXT, HTML
type_ = enums.Document.Type.PLAIN_TEXT
# Optional. If not specified, the language is automatically detected.
# For list of supported languages:
# https://cloud.google.com/natural-language/docs/languages
language = "en"
document = {"gcs_content_uri": gcs_content_uri, "type": type_, "language": language}
# Available values: NONE, UTF8, UTF16, UTF32
encoding_type = enums.EncodingType.UTF8
response = client.analyze_entities(document, encoding_type=encoding_type)
# Loop through entitites returned from the API
for entity in response.entities:
print(u"Representative name for the entity: {}".format(entity.name))
# Get entity type, e.g. PERSON, LOCATION, ADDRESS, NUMBER, et al
print(u"Entity type: {}".format(enums.Entity.Type(entity.type).name))
# Get the salience score associated with the entity in the [0, 1.0] range
print(u"Salience score: {}".format(entity.salience))
# Loop over the metadata associated with entity. For many known entities,
# the metadata is a Wikipedia URL (wikipedia_url) and Knowledge Graph MID (mid).
# Some entity types may have additional metadata, e.g. ADDRESS entities
# may have metadata for the address street_name, postal_code, et al.
for metadata_name, metadata_value in entity.metadata.items():
print(u"{}: {}".format(metadata_name, metadata_value))
# Loop over the mentions of this entity in the input document.
# The API currently supports proper noun mentions.
for mention in entity.mentions:
print(u"Mention text: {}".format(mention.text.content))
# Get the mention type, e.g. PROPER for proper noun
print(
u"Mention type: {}".format(enums.EntityMention.Type(mention.type).name)
)
# Get the language of the text, which will be the same as
# the language specified in the request or, if not specified,
# the automatically-detected language.
print(u"Language of the text: {}".format(response.language))
# [END language_entities_gcs]
def main():
import argparse
parser = argparse.ArgumentParser()
parser.add_argument(
"--gcs_content_uri",
type=str,
default="gs://cloud-samples-data/language/entity.txt",
)
args = parser.parse_args()
sample_analyze_entities(args.gcs_content_uri)
if __name__ == "__main__":
main()
| samples/v1/language_entities_gcs.py | 4,040 | Analyzing Entities in text file stored in Cloud Storage
Args:
gcs_content_uri Google Cloud Storage URI where the file content is located.
e.g. gs://[Your Bucket]/[Path to File]
-*- coding: utf-8 -*- Copyright 2020 Google LLC Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at https://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. DO NOT EDIT! This is a generated sample ("Request", "language_entities_gcs") To install the latest published package dependency, execute the following: pip install google-cloud-language sample-metadata title: Analyzing Entities (GCS) description: Analyzing Entities in text file stored in Cloud Storage usage: python3 samples/v1/language_entities_gcs.py [--gcs_content_uri "gs://cloud-samples-data/language/entity.txt"] [START language_entities_gcs] gcs_content_uri = 'gs://cloud-samples-data/language/entity.txt' Available types: PLAIN_TEXT, HTML Optional. If not specified, the language is automatically detected. For list of supported languages: https://cloud.google.com/natural-language/docs/languages Available values: NONE, UTF8, UTF16, UTF32 Loop through entitites returned from the API Get entity type, e.g. PERSON, LOCATION, ADDRESS, NUMBER, et al Get the salience score associated with the entity in the [0, 1.0] range Loop over the metadata associated with entity. For many known entities, the metadata is a Wikipedia URL (wikipedia_url) and Knowledge Graph MID (mid). Some entity types may have additional metadata, e.g. ADDRESS entities may have metadata for the address street_name, postal_code, et al. Loop over the mentions of this entity in the input document. The API currently supports proper noun mentions. Get the mention type, e.g. PROPER for proper noun Get the language of the text, which will be the same as the language specified in the request or, if not specified, the automatically-detected language. [END language_entities_gcs] | 2,321 | en | 0.803386 |
# coding=utf-8
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import copy
import logging
import math
import torch
import torch.nn as nn
import torch.nn.functional as nnf
from torch.nn import Dropout, Softmax, Linear, Conv3d, LayerNorm
from torch.nn.modules.utils import _pair, _triple
import configs as configs
from torch.distributions.normal import Normal
logger = logging.getLogger(__name__)
ATTENTION_Q = "MultiHeadDotProductAttention_1/query"
ATTENTION_K = "MultiHeadDotProductAttention_1/key"
ATTENTION_V = "MultiHeadDotProductAttention_1/value"
ATTENTION_OUT = "MultiHeadDotProductAttention_1/out"
FC_0 = "MlpBlock_3/Dense_0"
FC_1 = "MlpBlock_3/Dense_1"
ATTENTION_NORM = "LayerNorm_0"
MLP_NORM = "LayerNorm_2"
def np2th(weights, conv=False):
"""Possibly convert HWIO to OIHW."""
if conv:
weights = weights.transpose([3, 2, 0, 1])
return torch.from_numpy(weights)
def swish(x):
return x * torch.sigmoid(x)
ACT2FN = {"gelu": torch.nn.functional.gelu, "relu": torch.nn.functional.relu, "swish": swish}
class Attention(nn.Module):
def __init__(self, config, vis):
super(Attention, self).__init__()
self.vis = vis
self.num_attention_heads = config.transformer["num_heads"]
self.attention_head_size = int(config.hidden_size / self.num_attention_heads)
self.all_head_size = self.num_attention_heads * self.attention_head_size
self.query = Linear(config.hidden_size, self.all_head_size)
self.key = Linear(config.hidden_size, self.all_head_size)
self.value = Linear(config.hidden_size, self.all_head_size)
self.out = Linear(config.hidden_size, config.hidden_size)
self.attn_dropout = Dropout(config.transformer["attention_dropout_rate"])
self.proj_dropout = Dropout(config.transformer["attention_dropout_rate"])
self.softmax = Softmax(dim=-1)
def transpose_for_scores(self, x):
new_x_shape = x.size()[:-1] + (self.num_attention_heads, self.attention_head_size)
x = x.view(*new_x_shape)
return x.permute(0, 2, 1, 3)
def forward(self, hidden_states):
mixed_query_layer = self.query(hidden_states)
mixed_key_layer = self.key(hidden_states)
mixed_value_layer = self.value(hidden_states)
query_layer = self.transpose_for_scores(mixed_query_layer)
key_layer = self.transpose_for_scores(mixed_key_layer)
value_layer = self.transpose_for_scores(mixed_value_layer)
attention_scores = torch.matmul(query_layer, key_layer.transpose(-1, -2))
attention_scores = attention_scores / math.sqrt(self.attention_head_size)
attention_probs = self.softmax(attention_scores)
weights = attention_probs if self.vis else None
attention_probs = self.attn_dropout(attention_probs)
context_layer = torch.matmul(attention_probs, value_layer)
context_layer = context_layer.permute(0, 2, 1, 3).contiguous()
new_context_layer_shape = context_layer.size()[:-2] + (self.all_head_size,)
context_layer = context_layer.view(*new_context_layer_shape)
attention_output = self.out(context_layer)
attention_output = self.proj_dropout(attention_output)
return attention_output, weights
class Mlp(nn.Module):
def __init__(self, config):
super(Mlp, self).__init__()
self.fc1 = Linear(config.hidden_size, config.transformer["mlp_dim"])
self.fc2 = Linear(config.transformer["mlp_dim"], config.hidden_size)
self.act_fn = ACT2FN["gelu"]
self.dropout = Dropout(config.transformer["dropout_rate"])
self._init_weights()
def _init_weights(self):
nn.init.xavier_uniform_(self.fc1.weight)
nn.init.xavier_uniform_(self.fc2.weight)
nn.init.normal_(self.fc1.bias, std=1e-6)
nn.init.normal_(self.fc2.bias, std=1e-6)
def forward(self, x):
x = self.fc1(x)
x = self.act_fn(x)
x = self.dropout(x)
x = self.fc2(x)
x = self.dropout(x)
return x
class Embeddings(nn.Module):
"""Construct the embeddings from patch, position embeddings.
"""
def __init__(self, config, img_size):
super(Embeddings, self).__init__()
self.config = config
down_factor = config.down_factor
patch_size = _triple(config.patches["size"])
n_patches = int((img_size[0]/2**down_factor// patch_size[0]) * (img_size[1]/2**down_factor// patch_size[1]) * (img_size[2]/2**down_factor// patch_size[2]))
self.hybrid_model = CNNEncoder(config, n_channels=2)
in_channels = config['encoder_channels'][-1]
self.patch_embeddings = Conv3d(in_channels=in_channels,
out_channels=config.hidden_size,
kernel_size=patch_size,
stride=patch_size)
self.position_embeddings = nn.Parameter(torch.zeros(1, n_patches, config.hidden_size))
self.dropout = Dropout(config.transformer["dropout_rate"])
def forward(self, x):
x, features = self.hybrid_model(x)
x = self.patch_embeddings(x) # (B, hidden. n_patches^(1/2), n_patches^(1/2))
x = x.flatten(2)
x = x.transpose(-1, -2) # (B, n_patches, hidden)
embeddings = x + self.position_embeddings
embeddings = self.dropout(embeddings)
return embeddings, features
class Block(nn.Module):
def __init__(self, config, vis):
super(Block, self).__init__()
self.hidden_size = config.hidden_size
self.attention_norm = LayerNorm(config.hidden_size, eps=1e-6)
self.ffn_norm = LayerNorm(config.hidden_size, eps=1e-6)
self.ffn = Mlp(config)
self.attn = Attention(config, vis)
def forward(self, x):
h = x
x = self.attention_norm(x)
x, weights = self.attn(x)
x = x + h
h = x
x = self.ffn_norm(x)
x = self.ffn(x)
x = x + h
return x, weights
class Encoder(nn.Module):
def __init__(self, config, vis):
super(Encoder, self).__init__()
self.vis = vis
self.layer = nn.ModuleList()
self.encoder_norm = LayerNorm(config.hidden_size, eps=1e-6)
for _ in range(config.transformer["num_layers"]):
layer = Block(config, vis)
self.layer.append(copy.deepcopy(layer))
def forward(self, hidden_states):
attn_weights = []
for layer_block in self.layer:
hidden_states, weights = layer_block(hidden_states)
if self.vis:
attn_weights.append(weights)
encoded = self.encoder_norm(hidden_states)
return encoded, attn_weights
class Transformer(nn.Module):
def __init__(self, config, img_size, vis):
super(Transformer, self).__init__()
self.embeddings = Embeddings(config, img_size=img_size)
self.encoder = Encoder(config, vis)
def forward(self, input_ids):
embedding_output, features = self.embeddings(input_ids)
encoded, attn_weights = self.encoder(embedding_output) # (B, n_patch, hidden)
return encoded, attn_weights, features
class Conv3dReLU(nn.Sequential):
def __init__(
self,
in_channels,
out_channels,
kernel_size,
padding=0,
stride=1,
use_batchnorm=True,
):
conv = nn.Conv3d(
in_channels,
out_channels,
kernel_size,
stride=stride,
padding=padding,
bias=not (use_batchnorm),
)
relu = nn.ReLU(inplace=True)
bn = nn.BatchNorm3d(out_channels)
super(Conv3dReLU, self).__init__(conv, bn, relu)
class DecoderBlock(nn.Module):
def __init__(
self,
in_channels,
out_channels,
skip_channels=0,
use_batchnorm=True,
):
super().__init__()
self.conv1 = Conv3dReLU(
in_channels + skip_channels,
out_channels,
kernel_size=3,
padding=1,
use_batchnorm=use_batchnorm,
)
self.conv2 = Conv3dReLU(
out_channels,
out_channels,
kernel_size=3,
padding=1,
use_batchnorm=use_batchnorm,
)
self.up = nn.Upsample(scale_factor=2, mode='trilinear', align_corners=False)
def forward(self, x, skip=None):
x = self.up(x)
if skip is not None:
x = torch.cat([x, skip], dim=1)
x = self.conv1(x)
x = self.conv2(x)
return x
class DecoderCup(nn.Module):
def __init__(self, config, img_size):
super().__init__()
self.config = config
self.down_factor = config.down_factor
head_channels = config.conv_first_channel
self.img_size = img_size
self.conv_more = Conv3dReLU(
config.hidden_size,
head_channels,
kernel_size=3,
padding=1,
use_batchnorm=True,
)
decoder_channels = config.decoder_channels
in_channels = [head_channels] + list(decoder_channels[:-1])
out_channels = decoder_channels
self.patch_size = _triple(config.patches["size"])
skip_channels = self.config.skip_channels
blocks = [
DecoderBlock(in_ch, out_ch, sk_ch) for in_ch, out_ch, sk_ch in zip(in_channels, out_channels, skip_channels)
]
self.blocks = nn.ModuleList(blocks)
def forward(self, hidden_states, features=None):
B, n_patch, hidden = hidden_states.size() # reshape from (B, n_patch, hidden) to (B, h, w, hidden)
l, h, w = (self.img_size[0]//2**self.down_factor//self.patch_size[0]), (self.img_size[1]//2**self.down_factor//self.patch_size[1]), (self.img_size[2]//2**self.down_factor//self.patch_size[2])
x = hidden_states.permute(0, 2, 1)
x = x.contiguous().view(B, hidden, l, h, w)
x = self.conv_more(x)
for i, decoder_block in enumerate(self.blocks):
if features is not None:
skip = features[i] if (i < self.config.n_skip) else None
#print(skip.shape)
else:
skip = None
x = decoder_block(x, skip=skip)
return x
class SpatialTransformer(nn.Module):
"""
N-D Spatial Transformer
Obtained from https://github.com/voxelmorph/voxelmorph
"""
def __init__(self, size, mode='bilinear'):
super().__init__()
self.mode = mode
# create sampling grid
vectors = [torch.arange(0, s) for s in size]
grids = torch.meshgrid(vectors)
grid = torch.stack(grids)
grid = torch.unsqueeze(grid, 0)
grid = grid.type(torch.FloatTensor)
# registering the grid as a buffer cleanly moves it to the GPU, but it also
# adds it to the state dict. this is annoying since everything in the state dict
# is included when saving weights to disk, so the model files are way bigger
# than they need to be. so far, there does not appear to be an elegant solution.
# see: https://discuss.pytorch.org/t/how-to-register-buffer-without-polluting-state-dict
self.register_buffer('grid', grid)
def forward(self, src, flow):
# new locations
new_locs = self.grid + flow
shape = flow.shape[2:]
# need to normalize grid values to [-1, 1] for resampler
for i in range(len(shape)):
new_locs[:, i, ...] = 2 * (new_locs[:, i, ...] / (shape[i] - 1) - 0.5)
# move channels dim to last position
# also not sure why, but the channels need to be reversed
if len(shape) == 2:
new_locs = new_locs.permute(0, 2, 3, 1)
new_locs = new_locs[..., [1, 0]]
elif len(shape) == 3:
new_locs = new_locs.permute(0, 2, 3, 4, 1)
new_locs = new_locs[..., [2, 1, 0]]
return nnf.grid_sample(src, new_locs, align_corners=True, mode=self.mode)
class DoubleConv(nn.Module):
"""(convolution => [BN] => ReLU) * 2"""
def __init__(self, in_channels, out_channels, mid_channels=None):
super().__init__()
if not mid_channels:
mid_channels = out_channels
self.double_conv = nn.Sequential(
nn.Conv3d(in_channels, mid_channels, kernel_size=3, padding=1),
nn.ReLU(inplace=True),
nn.Conv3d(mid_channels, out_channels, kernel_size=3, padding=1),
nn.ReLU(inplace=True)
)
def forward(self, x):
return self.double_conv(x)
class Down(nn.Module):
"""Downscaling with maxpool then double conv"""
def __init__(self, in_channels, out_channels):
super().__init__()
self.maxpool_conv = nn.Sequential(
nn.MaxPool3d(2),
DoubleConv(in_channels, out_channels)
)
def forward(self, x):
return self.maxpool_conv(x)
class CNNEncoder(nn.Module):
def __init__(self, config, n_channels=2):
super(CNNEncoder, self).__init__()
self.n_channels = n_channels
decoder_channels = config.decoder_channels
encoder_channels = config.encoder_channels
self.down_num = config.down_num
self.inc = DoubleConv(n_channels, encoder_channels[0])
self.down1 = Down(encoder_channels[0], encoder_channels[1])
self.down2 = Down(encoder_channels[1], encoder_channels[2])
self.width = encoder_channels[-1]
def forward(self, x):
features = []
x1 = self.inc(x)
features.append(x1)
x2 = self.down1(x1)
features.append(x2)
feats = self.down2(x2)
features.append(feats)
feats_down = feats
for i in range(self.down_num):
feats_down = nn.MaxPool3d(2)(feats_down)
features.append(feats_down)
return feats, features[::-1]
class RegistrationHead(nn.Sequential):
def __init__(self, in_channels, out_channels, kernel_size=3, upsampling=1):
conv3d = nn.Conv3d(in_channels, out_channels, kernel_size=kernel_size, padding=kernel_size // 2)
conv3d.weight = nn.Parameter(Normal(0, 1e-5).sample(conv3d.weight.shape))
conv3d.bias = nn.Parameter(torch.zeros(conv3d.bias.shape))
super().__init__(conv3d)
class ViTVNet(nn.Module):
def __init__(self, config, img_size=(64, 256, 256), int_steps=7, vis=False):
super(ViTVNet, self).__init__()
self.transformer = Transformer(config, img_size, vis)
self.decoder = DecoderCup(config, img_size)
self.reg_head = RegistrationHead(
in_channels=config.decoder_channels[-1],
out_channels=config['n_dims'],
kernel_size=3,
)
self.spatial_trans = SpatialTransformer(img_size)
self.config = config
#self.integrate = VecInt(img_size, int_steps)
def forward(self, x):
source = x[:,0:1,:,:]
x, attn_weights, features = self.transformer(x) # (B, n_patch, hidden)
x = self.decoder(x, features)
flow = self.reg_head(x)
#flow = self.integrate(flow)
out = self.spatial_trans(source, flow)
return out, flow
class VecInt(nn.Module):
"""
Integrates a vector field via scaling and squaring.
Obtained from https://github.com/voxelmorph/voxelmorph
"""
def __init__(self, inshape, nsteps):
super().__init__()
assert nsteps >= 0, 'nsteps should be >= 0, found: %d' % nsteps
self.nsteps = nsteps
self.scale = 1.0 / (2 ** self.nsteps)
self.transformer = SpatialTransformer(inshape)
def forward(self, vec):
vec = vec * self.scale
for _ in range(self.nsteps):
vec = vec + self.transformer(vec, vec)
return vec
CONFIGS = {
'ViT-V-Net': configs.get_3DReg_config(),
}
| ViT-V-Net/models.py | 16,449 | (convolution => [BN] => ReLU) * 2
Downscaling with maxpool then double conv
Construct the embeddings from patch, position embeddings.
N-D Spatial Transformer
Obtained from https://github.com/voxelmorph/voxelmorph
Integrates a vector field via scaling and squaring.
Obtained from https://github.com/voxelmorph/voxelmorph
Possibly convert HWIO to OIHW.
coding=utf-8 (B, hidden. n_patches^(1/2), n_patches^(1/2)) (B, n_patches, hidden) (B, n_patch, hidden) reshape from (B, n_patch, hidden) to (B, h, w, hidden)print(skip.shape) create sampling grid registering the grid as a buffer cleanly moves it to the GPU, but it also adds it to the state dict. this is annoying since everything in the state dict is included when saving weights to disk, so the model files are way bigger than they need to be. so far, there does not appear to be an elegant solution. see: https://discuss.pytorch.org/t/how-to-register-buffer-without-polluting-state-dict new locations need to normalize grid values to [-1, 1] for resampler move channels dim to last position also not sure why, but the channels need to be reversedself.integrate = VecInt(img_size, int_steps) (B, n_patch, hidden)flow = self.integrate(flow) | 1,201 | en | 0.843448 |
import keras
from keras.datasets import mnist
# input image dimensions
img_rows, img_cols = 28, 28
input_shape = (img_rows, img_cols, 1)
num_classes = 10
def get_mnist_data():
# the data, shuffled and split between train and test sets
(x_train, y_train), (x_test, y_test) = mnist.load_data()
x_train = x_train.reshape(x_train.shape[0], img_rows, img_cols, 1)
x_test = x_test.reshape(x_test.shape[0], img_rows, img_cols, 1)
x_train = x_train.astype('float32')
x_test = x_test.astype('float32')
x_train /= 255
x_test /= 255
print('x_train shape:', x_train.shape)
print(x_train.shape[0], 'train samples')
print(x_test.shape[0], 'test samples')
# convert class vectors to binary class matrices
y_train = keras.utils.to_categorical(y_train, num_classes)
y_test = keras.utils.to_categorical(y_test, num_classes)
return x_train, y_train, x_test, y_test
| examples/data.py | 912 | input image dimensions the data, shuffled and split between train and test sets convert class vectors to binary class matrices | 126 | en | 0.846062 |
# -*- coding: utf-8 -*-
import random
import itertools
from collections import defaultdict
class Chat(object):
cache_size = 200
# user_num = list(range(1, 100))
# random.shuffle(user_num)
colors = ['赤', '青', '黄', '緑', '紫', '黒', '茶', '灰色', '金', '銀']
fruits = ['りんご', 'みかん', 'メロン', 'パイナップル', 'ぶどう', '梨', 'いちご', 'もも', 'さくらんぼ', 'バナナ']
fruits_with_color = itertools.product(colors, fruits)
user_name = list(map(lambda n: n[0]+n[1], fruits_with_color))
random.shuffle(user_name)
def __init__(self):
self.cache = defaultdict(list)
self.nickname_dic = defaultdict(dict)
def set_nickname(self, room_id, client_name):
self.nickname_dic[room_id].update({client_name:str(self.__get_random_name())})
def get_nickname(self, room_id, client_name):
return self.nickname_dic[room_id][client_name]
def update_cache(self, chat, room_id):
self.cache[room_id].append(chat)
if len(self.cache[room_id]) > self.cache_size:
self.cache[room_id] = self.cache[-self.cache_size:]
def __get_random_name(self):
return self.user_name.pop()
def clear_caches(self, room_id):
del self.cache[room_id]
del self.nickname_dic[room_id]
| handlers/brainstorming/chat.py | 1,331 | -*- coding: utf-8 -*- user_num = list(range(1, 100)) random.shuffle(user_num) | 77 | en | 0.242868 |
"""
Argo Server API
You can get examples of requests and responses by using the CLI with `--gloglevel=9`, e.g. `argo list --gloglevel=9` # noqa: E501
The version of the OpenAPI document: VERSION
Generated by: https://openapi-generator.tech
"""
import re # noqa: F401
import sys # noqa: F401
from openapi_client.model_utils import ( # noqa: F401
ApiTypeError,
ModelComposed,
ModelNormal,
ModelSimple,
cached_property,
change_keys_js_to_python,
convert_js_args_to_python_args,
date,
datetime,
file_type,
none_type,
validate_get_composed_info,
)
from ..model_utils import OpenApiModel
from openapi_client.exceptions import ApiAttributeError
class FCVolumeSource(ModelNormal):
"""NOTE: This class is auto generated by OpenAPI Generator.
Ref: https://openapi-generator.tech
Do not edit the class manually.
Attributes:
allowed_values (dict): The key is the tuple path to the attribute
and the for var_name this is (var_name,). The value is a dict
with a capitalized key describing the allowed value and an allowed
value. These dicts store the allowed enum values.
attribute_map (dict): The key is attribute name
and the value is json key in definition.
discriminator_value_class_map (dict): A dict to go from the discriminator
variable value to the discriminator class name.
validations (dict): The key is the tuple path to the attribute
and the for var_name this is (var_name,). The value is a dict
that stores validations for max_length, min_length, max_items,
min_items, exclusive_maximum, inclusive_maximum, exclusive_minimum,
inclusive_minimum, and regex.
additional_properties_type (tuple): A tuple of classes accepted
as additional properties values.
"""
allowed_values = {
}
validations = {
}
@cached_property
def additional_properties_type():
"""
This must be a method because a model may have properties that are
of type self, this must run after the class is loaded
"""
return (bool, date, datetime, dict, float, int, list, str, none_type,) # noqa: E501
_nullable = False
@cached_property
def openapi_types():
"""
This must be a method because a model may have properties that are
of type self, this must run after the class is loaded
Returns
openapi_types (dict): The key is attribute name
and the value is attribute type.
"""
return {
'fs_type': (str,), # noqa: E501
'lun': (int,), # noqa: E501
'read_only': (bool,), # noqa: E501
'target_wwns': ([str],), # noqa: E501
'wwids': ([str],), # noqa: E501
}
@cached_property
def discriminator():
return None
attribute_map = {
'fs_type': 'fsType', # noqa: E501
'lun': 'lun', # noqa: E501
'read_only': 'readOnly', # noqa: E501
'target_wwns': 'targetWWNs', # noqa: E501
'wwids': 'wwids', # noqa: E501
}
read_only_vars = {
}
_composed_schemas = {}
@classmethod
@convert_js_args_to_python_args
def _from_openapi_data(cls, *args, **kwargs): # noqa: E501
"""FCVolumeSource - a model defined in OpenAPI
Keyword Args:
_check_type (bool): if True, values for parameters in openapi_types
will be type checked and a TypeError will be
raised if the wrong type is input.
Defaults to True
_path_to_item (tuple/list): This is a list of keys or values to
drill down to the model in received_data
when deserializing a response
_spec_property_naming (bool): True if the variable names in the input data
are serialized names, as specified in the OpenAPI document.
False if the variable names in the input data
are pythonic names, e.g. snake case (default)
_configuration (Configuration): the instance to use when
deserializing a file_type parameter.
If passed, type conversion is attempted
If omitted no type conversion is done.
_visited_composed_classes (tuple): This stores a tuple of
classes that we have traveled through so that
if we see that class again we will not use its
discriminator again.
When traveling through a discriminator, the
composed schema that is
is traveled through is added to this set.
For example if Animal has a discriminator
petType and we pass in "Dog", and the class Dog
allOf includes Animal, we move through Animal
once using the discriminator, and pick Dog.
Then in Dog, we will make an instance of the
Animal class but this time we won't travel
through its discriminator because we passed in
_visited_composed_classes = (Animal,)
fs_type (str): Filesystem type to mount. Must be a filesystem type supported by the host operating system. Ex. \"ext4\", \"xfs\", \"ntfs\". Implicitly inferred to be \"ext4\" if unspecified.. [optional] # noqa: E501
lun (int): Optional: FC target lun number. [optional] # noqa: E501
read_only (bool): Optional: Defaults to false (read/write). ReadOnly here will force the ReadOnly setting in VolumeMounts.. [optional] # noqa: E501
target_wwns ([str]): Optional: FC target worldwide names (WWNs). [optional] # noqa: E501
wwids ([str]): Optional: FC volume world wide identifiers (wwids) Either wwids or combination of targetWWNs and lun must be set, but not both simultaneously.. [optional] # noqa: E501
"""
_check_type = kwargs.pop('_check_type', True)
_spec_property_naming = kwargs.pop('_spec_property_naming', False)
_path_to_item = kwargs.pop('_path_to_item', ())
_configuration = kwargs.pop('_configuration', None)
_visited_composed_classes = kwargs.pop('_visited_composed_classes', ())
self = super(OpenApiModel, cls).__new__(cls)
if args:
raise ApiTypeError(
"Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % (
args,
self.__class__.__name__,
),
path_to_item=_path_to_item,
valid_classes=(self.__class__,),
)
self._data_store = {}
self._check_type = _check_type
self._spec_property_naming = _spec_property_naming
self._path_to_item = _path_to_item
self._configuration = _configuration
self._visited_composed_classes = _visited_composed_classes + (self.__class__,)
for var_name, var_value in kwargs.items():
if var_name not in self.attribute_map and \
self._configuration is not None and \
self._configuration.discard_unknown_keys and \
self.additional_properties_type is None:
# discard variable.
continue
setattr(self, var_name, var_value)
return self
required_properties = set([
'_data_store',
'_check_type',
'_spec_property_naming',
'_path_to_item',
'_configuration',
'_visited_composed_classes',
])
@convert_js_args_to_python_args
def __init__(self, *args, **kwargs): # noqa: E501
"""FCVolumeSource - a model defined in OpenAPI
Keyword Args:
_check_type (bool): if True, values for parameters in openapi_types
will be type checked and a TypeError will be
raised if the wrong type is input.
Defaults to True
_path_to_item (tuple/list): This is a list of keys or values to
drill down to the model in received_data
when deserializing a response
_spec_property_naming (bool): True if the variable names in the input data
are serialized names, as specified in the OpenAPI document.
False if the variable names in the input data
are pythonic names, e.g. snake case (default)
_configuration (Configuration): the instance to use when
deserializing a file_type parameter.
If passed, type conversion is attempted
If omitted no type conversion is done.
_visited_composed_classes (tuple): This stores a tuple of
classes that we have traveled through so that
if we see that class again we will not use its
discriminator again.
When traveling through a discriminator, the
composed schema that is
is traveled through is added to this set.
For example if Animal has a discriminator
petType and we pass in "Dog", and the class Dog
allOf includes Animal, we move through Animal
once using the discriminator, and pick Dog.
Then in Dog, we will make an instance of the
Animal class but this time we won't travel
through its discriminator because we passed in
_visited_composed_classes = (Animal,)
fs_type (str): Filesystem type to mount. Must be a filesystem type supported by the host operating system. Ex. \"ext4\", \"xfs\", \"ntfs\". Implicitly inferred to be \"ext4\" if unspecified.. [optional] # noqa: E501
lun (int): Optional: FC target lun number. [optional] # noqa: E501
read_only (bool): Optional: Defaults to false (read/write). ReadOnly here will force the ReadOnly setting in VolumeMounts.. [optional] # noqa: E501
target_wwns ([str]): Optional: FC target worldwide names (WWNs). [optional] # noqa: E501
wwids ([str]): Optional: FC volume world wide identifiers (wwids) Either wwids or combination of targetWWNs and lun must be set, but not both simultaneously.. [optional] # noqa: E501
"""
_check_type = kwargs.pop('_check_type', True)
_spec_property_naming = kwargs.pop('_spec_property_naming', False)
_path_to_item = kwargs.pop('_path_to_item', ())
_configuration = kwargs.pop('_configuration', None)
_visited_composed_classes = kwargs.pop('_visited_composed_classes', ())
if args:
raise ApiTypeError(
"Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % (
args,
self.__class__.__name__,
),
path_to_item=_path_to_item,
valid_classes=(self.__class__,),
)
self._data_store = {}
self._check_type = _check_type
self._spec_property_naming = _spec_property_naming
self._path_to_item = _path_to_item
self._configuration = _configuration
self._visited_composed_classes = _visited_composed_classes + (self.__class__,)
for var_name, var_value in kwargs.items():
if var_name not in self.attribute_map and \
self._configuration is not None and \
self._configuration.discard_unknown_keys and \
self.additional_properties_type is None:
# discard variable.
continue
setattr(self, var_name, var_value)
if var_name in self.read_only_vars:
raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate "
f"class with read only attributes.")
| sdks/python/client/openapi_client/model/fc_volume_source.py | 12,886 | NOTE: This class is auto generated by OpenAPI Generator.
Ref: https://openapi-generator.tech
Do not edit the class manually.
Attributes:
allowed_values (dict): The key is the tuple path to the attribute
and the for var_name this is (var_name,). The value is a dict
with a capitalized key describing the allowed value and an allowed
value. These dicts store the allowed enum values.
attribute_map (dict): The key is attribute name
and the value is json key in definition.
discriminator_value_class_map (dict): A dict to go from the discriminator
variable value to the discriminator class name.
validations (dict): The key is the tuple path to the attribute
and the for var_name this is (var_name,). The value is a dict
that stores validations for max_length, min_length, max_items,
min_items, exclusive_maximum, inclusive_maximum, exclusive_minimum,
inclusive_minimum, and regex.
additional_properties_type (tuple): A tuple of classes accepted
as additional properties values.
FCVolumeSource - a model defined in OpenAPI
Keyword Args:
_check_type (bool): if True, values for parameters in openapi_types
will be type checked and a TypeError will be
raised if the wrong type is input.
Defaults to True
_path_to_item (tuple/list): This is a list of keys or values to
drill down to the model in received_data
when deserializing a response
_spec_property_naming (bool): True if the variable names in the input data
are serialized names, as specified in the OpenAPI document.
False if the variable names in the input data
are pythonic names, e.g. snake case (default)
_configuration (Configuration): the instance to use when
deserializing a file_type parameter.
If passed, type conversion is attempted
If omitted no type conversion is done.
_visited_composed_classes (tuple): This stores a tuple of
classes that we have traveled through so that
if we see that class again we will not use its
discriminator again.
When traveling through a discriminator, the
composed schema that is
is traveled through is added to this set.
For example if Animal has a discriminator
petType and we pass in "Dog", and the class Dog
allOf includes Animal, we move through Animal
once using the discriminator, and pick Dog.
Then in Dog, we will make an instance of the
Animal class but this time we won't travel
through its discriminator because we passed in
_visited_composed_classes = (Animal,)
fs_type (str): Filesystem type to mount. Must be a filesystem type supported by the host operating system. Ex. "ext4", "xfs", "ntfs". Implicitly inferred to be "ext4" if unspecified.. [optional] # noqa: E501
lun (int): Optional: FC target lun number. [optional] # noqa: E501
read_only (bool): Optional: Defaults to false (read/write). ReadOnly here will force the ReadOnly setting in VolumeMounts.. [optional] # noqa: E501
target_wwns ([str]): Optional: FC target worldwide names (WWNs). [optional] # noqa: E501
wwids ([str]): Optional: FC volume world wide identifiers (wwids) Either wwids or combination of targetWWNs and lun must be set, but not both simultaneously.. [optional] # noqa: E501
FCVolumeSource - a model defined in OpenAPI
Keyword Args:
_check_type (bool): if True, values for parameters in openapi_types
will be type checked and a TypeError will be
raised if the wrong type is input.
Defaults to True
_path_to_item (tuple/list): This is a list of keys or values to
drill down to the model in received_data
when deserializing a response
_spec_property_naming (bool): True if the variable names in the input data
are serialized names, as specified in the OpenAPI document.
False if the variable names in the input data
are pythonic names, e.g. snake case (default)
_configuration (Configuration): the instance to use when
deserializing a file_type parameter.
If passed, type conversion is attempted
If omitted no type conversion is done.
_visited_composed_classes (tuple): This stores a tuple of
classes that we have traveled through so that
if we see that class again we will not use its
discriminator again.
When traveling through a discriminator, the
composed schema that is
is traveled through is added to this set.
For example if Animal has a discriminator
petType and we pass in "Dog", and the class Dog
allOf includes Animal, we move through Animal
once using the discriminator, and pick Dog.
Then in Dog, we will make an instance of the
Animal class but this time we won't travel
through its discriminator because we passed in
_visited_composed_classes = (Animal,)
fs_type (str): Filesystem type to mount. Must be a filesystem type supported by the host operating system. Ex. "ext4", "xfs", "ntfs". Implicitly inferred to be "ext4" if unspecified.. [optional] # noqa: E501
lun (int): Optional: FC target lun number. [optional] # noqa: E501
read_only (bool): Optional: Defaults to false (read/write). ReadOnly here will force the ReadOnly setting in VolumeMounts.. [optional] # noqa: E501
target_wwns ([str]): Optional: FC target worldwide names (WWNs). [optional] # noqa: E501
wwids ([str]): Optional: FC volume world wide identifiers (wwids) Either wwids or combination of targetWWNs and lun must be set, but not both simultaneously.. [optional] # noqa: E501
This must be a method because a model may have properties that are
of type self, this must run after the class is loaded
This must be a method because a model may have properties that are
of type self, this must run after the class is loaded
Returns
openapi_types (dict): The key is attribute name
and the value is attribute type.
Argo Server API
You can get examples of requests and responses by using the CLI with `--gloglevel=9`, e.g. `argo list --gloglevel=9` # noqa: E501
The version of the OpenAPI document: VERSION
Generated by: https://openapi-generator.tech
noqa: F401 noqa: F401 noqa: F401 noqa: E501 noqa: E501 noqa: E501 noqa: E501 noqa: E501 noqa: E501 noqa: E501 noqa: E501 noqa: E501 noqa: E501 noqa: E501 noqa: E501 discard variable. noqa: E501 discard variable. | 7,312 | en | 0.764473 |
# Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""A module to blocker devices based on device blocklists."""
from __future__ import absolute_import
from __future__ import division
from __future__ import google_type_annotations
from __future__ import print_function
from tradefed_cluster import datastore_entities
def IsLabBlocked(lab_name):
"""Check if the lab is blocked.
Args:
lab_name: lab name
Returns:
true if the lab is blocked, otherwise false.
"""
device_blocklists = (
datastore_entities.DeviceBlocklist.query()
.filter(datastore_entities.DeviceBlocklist.lab_name == lab_name)
.fetch(1))
return bool(device_blocklists)
| tradefed_cluster/device_blocker.py | 1,199 | Check if the lab is blocked.
Args:
lab_name: lab name
Returns:
true if the lab is blocked, otherwise false.
A module to blocker devices based on device blocklists.
Copyright 2020 Google LLC Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. | 719 | en | 0.846369 |
# This code is part of Qiskit.
#
# (C) Copyright IBM 2017, 2020.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""The Grover operator."""
from typing import List, Optional, Union
import numpy
from qiskit.circuit import QuantumCircuit, QuantumRegister, AncillaRegister
# from qiskit.quantum_info import Statevector, Operator, DensityMatrix
from qiskit.quantum_info import Operator
from .standard_gates import MCXGate
class GroverOperator(QuantumCircuit):
r"""The Grover operator.
Grover's search algorithm [1, 2] consists of repeated applications of the so-called
Grover operator used to amplify the amplitudes of the desired output states.
This operator, :math:`\mathcal{Q}`, consists of the phase oracle, :math:`\mathcal{S}_f`,
zero phase-shift or zero reflection, :math:`\mathcal{S}_0`, and an
input state preparation :math:`\mathcal{A}`:
.. math::
\mathcal{Q} = \mathcal{A} \mathcal{S}_0 \mathcal{A}^\dagger \mathcal{S}_f
In the standard Grover search we have :math:`\mathcal{A} = H^{\otimes n}`:
.. math::
\mathcal{Q} = H^{\otimes n} \mathcal{S}_0 H^{\otimes n} \mathcal{S}_f
= D \mathcal{S_f}
The operation :math:`D = H^{\otimes n} \mathcal{S}_0 H^{\otimes n}` is also referred to as
diffusion operator. In this formulation we can see that Grover's operator consists of two
steps: first, the phase oracle multiplies the good states by -1 (with :math:`\mathcal{S}_f`)
and then the whole state is reflected around the mean (with :math:`D`).
This class allows setting a different state preparation, as in quantum amplitude
amplification (a generalization of Grover's algorithm), :math:`\mathcal{A}` might not be
a layer of Hardamard gates [3].
The action of the phase oracle :math:`\mathcal{S}_f` is defined as
.. math::
\mathcal{S}_f: |x\rangle \mapsto (-1)^{f(x)}|x\rangle
where :math:`f(x) = 1` if :math:`x` is a good state and 0 otherwise. To highlight the fact
that this oracle flips the phase of the good states and does not flip the state of a result
qubit, we call :math:`\mathcal{S}_f` a phase oracle.
Note that you can easily construct a phase oracle from a bitflip oracle by sandwiching the
controlled X gate on the result qubit by a X and H gate. For instance
.. parsed-literal::
Bitflip oracle Phaseflip oracle
q_0: ──■── q_0: ────────────■────────────
┌─┴─┐ ┌───┐┌───┐┌─┴─┐┌───┐┌───┐
out: ┤ X ├ out: ┤ X ├┤ H ├┤ X ├┤ H ├┤ X ├
└───┘ └───┘└───┘└───┘└───┘└───┘
There is some flexibility in defining the oracle and :math:`\mathcal{A}` operator. Before the
Grover operator is applied in Grover's algorithm, the qubits are first prepared with one
application of the :math:`\mathcal{A}` operator (or Hadamard gates in the standard formulation).
Thus, we always have operation of the form
:math:`\mathcal{A} \mathcal{S}_f \mathcal{A}^\dagger`. Therefore it is possible to move
bitflip logic into :math:`\mathcal{A}` and leaving the oracle only to do phaseflips via Z gates
based on the bitflips. One possible use-case for this are oracles that do not uncompute the
state qubits.
The zero reflection :math:`\mathcal{S}_0` is usually defined as
.. math::
\mathcal{S}_0 = 2 |0\rangle^{\otimes n} \langle 0|^{\otimes n} - \mathbb{I}_n
where :math:`\mathbb{I}_n` is the identity on :math:`n` qubits.
By default, this class implements the negative version
:math:`2 |0\rangle^{\otimes n} \langle 0|^{\otimes n} - \mathbb{I}_n`, since this can simply
be implemented with a multi-controlled Z sandwiched by X gates on the target qubit and the
introduced global phase does not matter for Grover's algorithm.
Examples:
>>> from qiskit.circuit import QuantumCircuit
>>> from qiskit.circuit.library import GroverOperator
>>> oracle = QuantumCircuit(2)
>>> oracle.z(0) # good state = first qubit is |1>
>>> grover_op = GroverOperator(oracle, insert_barriers=True)
>>> grover_op.draw()
┌───┐ ░ ┌───┐ ░ ┌───┐ ┌───┐ ░ ┌───┐
state_0: ┤ Z ├─░─┤ H ├─░─┤ X ├───────■──┤ X ├──────░─┤ H ├
└───┘ ░ ├───┤ ░ ├───┤┌───┐┌─┴─┐├───┤┌───┐ ░ ├───┤
state_1: ──────░─┤ H ├─░─┤ X ├┤ H ├┤ X ├┤ H ├┤ X ├─░─┤ H ├
░ └───┘ ░ └───┘└───┘└───┘└───┘└───┘ ░ └───┘
>>> oracle = QuantumCircuit(1)
>>> oracle.z(0) # the qubit state |1> is the good state
>>> state_preparation = QuantumCircuit(1)
>>> state_preparation.ry(0.2, 0) # non-uniform state preparation
>>> grover_op = GroverOperator(oracle, state_preparation)
>>> grover_op.draw()
┌───┐┌──────────┐┌───┐┌───┐┌───┐┌─────────┐
state_0: ┤ Z ├┤ RY(-0.2) ├┤ X ├┤ Z ├┤ X ├┤ RY(0.2) ├
└───┘└──────────┘└───┘└───┘└───┘└─────────┘
>>> oracle = QuantumCircuit(4)
>>> oracle.z(3)
>>> reflection_qubits = [0, 3]
>>> state_preparation = QuantumCircuit(4)
>>> state_preparation.cry(0.1, 0, 3)
>>> state_preparation.ry(0.5, 3)
>>> grover_op = GroverOperator(oracle, state_preparation,
... reflection_qubits=reflection_qubits)
>>> grover_op.draw()
┌───┐ ┌───┐
state_0: ──────────────────────■──────┤ X ├───────■──┤ X ├──────────■────────────────
│ └───┘ │ └───┘ │
state_1: ──────────────────────┼──────────────────┼─────────────────┼────────────────
│ │ │
state_2: ──────────────────────┼──────────────────┼─────────────────┼────────────────
┌───┐┌──────────┐┌────┴─────┐┌───┐┌───┐┌─┴─┐┌───┐┌───┐┌────┴────┐┌─────────┐
state_3: ┤ Z ├┤ RY(-0.5) ├┤ RY(-0.1) ├┤ X ├┤ H ├┤ X ├┤ H ├┤ X ├┤ RY(0.1) ├┤ RY(0.5) ├
└───┘└──────────┘└──────────┘└───┘└───┘└───┘└───┘└───┘└─────────┘└─────────┘
>>> mark_state = Statevector.from_label('011')
>>> diffuse_operator = 2 * DensityMatrix.from_label('000') - Operator.from_label('III')
>>> grover_op = GroverOperator(oracle=mark_state, zero_reflection=diffuse_operator)
>>> grover_op.draw(fold=70)
┌─────────────────┐ ┌───┐ »
state_0: ┤0 ├──────┤ H ├──────────────────────────»
│ │┌─────┴───┴─────┐ ┌───┐ »
state_1: ┤1 UCRZ(0,pi,0,0) ├┤0 ├─────┤ H ├──────────»
│ ││ UCRZ(pi/2,0) │┌────┴───┴────┐┌───┐»
state_2: ┤2 ├┤1 ├┤ UCRZ(-pi/4) ├┤ H ├»
└─────────────────┘└───────────────┘└─────────────┘└───┘»
« ┌─────────────────┐ ┌───┐
«state_0: ┤0 ├──────┤ H ├─────────────────────────
« │ │┌─────┴───┴─────┐ ┌───┐
«state_1: ┤1 UCRZ(pi,0,0,0) ├┤0 ├────┤ H ├──────────
« │ ││ UCRZ(pi/2,0) │┌───┴───┴────┐┌───┐
«state_2: ┤2 ├┤1 ├┤ UCRZ(pi/4) ├┤ H ├
« └─────────────────┘└───────────────┘└────────────┘└───┘
References:
[1]: L. K. Grover (1996), A fast quantum mechanical algorithm for database search,
`arXiv:quant-ph/9605043 <https://arxiv.org/abs/quant-ph/9605043>`_.
[2]: I. Chuang & M. Nielsen, Quantum Computation and Quantum Information,
Cambridge: Cambridge University Press, 2000. Chapter 6.1.2.
[3]: Brassard, G., Hoyer, P., Mosca, M., & Tapp, A. (2000).
Quantum Amplitude Amplification and Estimation.
`arXiv:quant-ph/0005055 <http://arxiv.org/abs/quant-ph/0005055>`_.
"""
def __init__(
self,
# oracle: Union[QuantumCircuit, Statevector],
oracle: QuantumCircuit,
state_preparation: Optional[QuantumCircuit] = None,
# zero_reflection: Optional[Union[QuantumCircuit, DensityMatrix, Operator]] = None,
zero_reflection: Optional[Union[QuantumCircuit, Operator]] = None,
reflection_qubits: Optional[List[int]] = None,
insert_barriers: bool = False,
mcx_mode: str = "noancilla",
name: str = "Q",
) -> None:
r"""
Args:
oracle: The phase oracle implementing a reflection about the bad state. Note that this
is not a bitflip oracle, see the docstring for more information.
state_preparation: The operator preparing the good and bad state.
For Grover's algorithm, this is a n-qubit Hadamard gate and for amplitude
amplification or estimation the operator :math:`\mathcal{A}`.
zero_reflection: The reflection about the zero state, :math:`\mathcal{S}_0`.
reflection_qubits: Qubits on which the zero reflection acts on.
insert_barriers: Whether barriers should be inserted between the reflections and A.
mcx_mode: The mode to use for building the default zero reflection.
name: The name of the circuit.
"""
super().__init__(name=name)
# store inputs
# if isinstance(oracle, Statevector):
# from qiskit.circuit.library import Diagonal # pylint: disable=cyclic-import
# oracle = Diagonal((-1) ** oracle.data)
self._oracle = oracle
# if isinstance(zero_reflection, (Operator, DensityMatrix)):
# from qiskit.circuit.library import Diagonal # pylint: disable=cyclic-import
# zero_reflection = Diagonal(zero_reflection.data.diagonal())
self._zero_reflection = zero_reflection
self._reflection_qubits = reflection_qubits
self._state_preparation = state_preparation
self._insert_barriers = insert_barriers
self._mcx_mode = mcx_mode
# build circuit
self._build()
@property
def reflection_qubits(self):
"""Reflection qubits, on which S0 is applied (if S0 is not user-specified)."""
if self._reflection_qubits is not None:
return self._reflection_qubits
num_state_qubits = self.oracle.num_qubits - self.oracle.num_ancillas
return list(range(num_state_qubits))
@property
def zero_reflection(self) -> QuantumCircuit:
"""The subcircuit implementing the reflection about 0."""
if self._zero_reflection is not None:
return self._zero_reflection
num_state_qubits = self.oracle.num_qubits - self.oracle.num_ancillas
return _zero_reflection(num_state_qubits, self.reflection_qubits, self._mcx_mode)
@property
def state_preparation(self) -> QuantumCircuit:
"""The subcircuit implementing the A operator or Hadamards."""
if self._state_preparation is not None:
return self._state_preparation
num_state_qubits = self.oracle.num_qubits - self.oracle.num_ancillas
hadamards = QuantumCircuit(num_state_qubits, name="H")
# apply Hadamards only on reflection qubits, rest will cancel out
hadamards.h(self.reflection_qubits)
return hadamards
@property
def oracle(self):
"""The oracle implementing a reflection about the bad state."""
return self._oracle
def _build(self):
num_state_qubits = self.oracle.num_qubits - self.oracle.num_ancillas
self.add_register(QuantumRegister(num_state_qubits, name="state"))
num_ancillas = numpy.max(
[
self.oracle.num_ancillas,
self.zero_reflection.num_ancillas,
self.state_preparation.num_ancillas,
]
)
if num_ancillas > 0:
self.add_register(AncillaRegister(num_ancillas, name="ancilla"))
self.compose(self.oracle, list(range(self.oracle.num_qubits)), inplace=True)
if self._insert_barriers:
self.barrier()
self.compose(
self.state_preparation.inverse(),
list(range(self.state_preparation.num_qubits)),
inplace=True,
)
if self._insert_barriers:
self.barrier()
self.compose(
self.zero_reflection, list(range(self.zero_reflection.num_qubits)), inplace=True
)
if self._insert_barriers:
self.barrier()
self.compose(
self.state_preparation, list(range(self.state_preparation.num_qubits)), inplace=True
)
# minus sign
self.global_phase = numpy.pi
# TODO use the oracle compiler or the bit string oracle
def _zero_reflection(
num_state_qubits: int, qubits: List[int], mcx_mode: Optional[str] = None
) -> QuantumCircuit:
qr_state = QuantumRegister(num_state_qubits, "state")
reflection = QuantumCircuit(qr_state, name="S_0")
num_ancillas = MCXGate.get_num_ancilla_qubits(len(qubits) - 1, mcx_mode)
if num_ancillas > 0:
qr_ancilla = AncillaRegister(num_ancillas, "ancilla")
reflection.add_register(qr_ancilla)
else:
qr_ancilla = []
reflection.x(qubits)
if len(qubits) == 1:
reflection.z(0) # MCX does not allow 0 control qubits, therefore this is separate
else:
reflection.h(qubits[-1])
reflection.mcx(qubits[:-1], qubits[-1], qr_ancilla[:], mode=mcx_mode)
reflection.h(qubits[-1])
reflection.x(qubits)
return reflection
| qiskit/circuit/library/grover_operator.py | 16,719 | The Grover operator.
Grover's search algorithm [1, 2] consists of repeated applications of the so-called
Grover operator used to amplify the amplitudes of the desired output states.
This operator, :math:`\mathcal{Q}`, consists of the phase oracle, :math:`\mathcal{S}_f`,
zero phase-shift or zero reflection, :math:`\mathcal{S}_0`, and an
input state preparation :math:`\mathcal{A}`:
.. math::
\mathcal{Q} = \mathcal{A} \mathcal{S}_0 \mathcal{A}^\dagger \mathcal{S}_f
In the standard Grover search we have :math:`\mathcal{A} = H^{\otimes n}`:
.. math::
\mathcal{Q} = H^{\otimes n} \mathcal{S}_0 H^{\otimes n} \mathcal{S}_f
= D \mathcal{S_f}
The operation :math:`D = H^{\otimes n} \mathcal{S}_0 H^{\otimes n}` is also referred to as
diffusion operator. In this formulation we can see that Grover's operator consists of two
steps: first, the phase oracle multiplies the good states by -1 (with :math:`\mathcal{S}_f`)
and then the whole state is reflected around the mean (with :math:`D`).
This class allows setting a different state preparation, as in quantum amplitude
amplification (a generalization of Grover's algorithm), :math:`\mathcal{A}` might not be
a layer of Hardamard gates [3].
The action of the phase oracle :math:`\mathcal{S}_f` is defined as
.. math::
\mathcal{S}_f: |x\rangle \mapsto (-1)^{f(x)}|x\rangle
where :math:`f(x) = 1` if :math:`x` is a good state and 0 otherwise. To highlight the fact
that this oracle flips the phase of the good states and does not flip the state of a result
qubit, we call :math:`\mathcal{S}_f` a phase oracle.
Note that you can easily construct a phase oracle from a bitflip oracle by sandwiching the
controlled X gate on the result qubit by a X and H gate. For instance
.. parsed-literal::
Bitflip oracle Phaseflip oracle
q_0: ──■── q_0: ────────────■────────────
┌─┴─┐ ┌───┐┌───┐┌─┴─┐┌───┐┌───┐
out: ┤ X ├ out: ┤ X ├┤ H ├┤ X ├┤ H ├┤ X ├
└───┘ └───┘└───┘└───┘└───┘└───┘
There is some flexibility in defining the oracle and :math:`\mathcal{A}` operator. Before the
Grover operator is applied in Grover's algorithm, the qubits are first prepared with one
application of the :math:`\mathcal{A}` operator (or Hadamard gates in the standard formulation).
Thus, we always have operation of the form
:math:`\mathcal{A} \mathcal{S}_f \mathcal{A}^\dagger`. Therefore it is possible to move
bitflip logic into :math:`\mathcal{A}` and leaving the oracle only to do phaseflips via Z gates
based on the bitflips. One possible use-case for this are oracles that do not uncompute the
state qubits.
The zero reflection :math:`\mathcal{S}_0` is usually defined as
.. math::
\mathcal{S}_0 = 2 |0\rangle^{\otimes n} \langle 0|^{\otimes n} - \mathbb{I}_n
where :math:`\mathbb{I}_n` is the identity on :math:`n` qubits.
By default, this class implements the negative version
:math:`2 |0\rangle^{\otimes n} \langle 0|^{\otimes n} - \mathbb{I}_n`, since this can simply
be implemented with a multi-controlled Z sandwiched by X gates on the target qubit and the
introduced global phase does not matter for Grover's algorithm.
Examples:
>>> from qiskit.circuit import QuantumCircuit
>>> from qiskit.circuit.library import GroverOperator
>>> oracle = QuantumCircuit(2)
>>> oracle.z(0) # good state = first qubit is |1>
>>> grover_op = GroverOperator(oracle, insert_barriers=True)
>>> grover_op.draw()
┌───┐ ░ ┌───┐ ░ ┌───┐ ┌───┐ ░ ┌───┐
state_0: ┤ Z ├─░─┤ H ├─░─┤ X ├───────■──┤ X ├──────░─┤ H ├
└───┘ ░ ├───┤ ░ ├───┤┌───┐┌─┴─┐├───┤┌───┐ ░ ├───┤
state_1: ──────░─┤ H ├─░─┤ X ├┤ H ├┤ X ├┤ H ├┤ X ├─░─┤ H ├
░ └───┘ ░ └───┘└───┘└───┘└───┘└───┘ ░ └───┘
>>> oracle = QuantumCircuit(1)
>>> oracle.z(0) # the qubit state |1> is the good state
>>> state_preparation = QuantumCircuit(1)
>>> state_preparation.ry(0.2, 0) # non-uniform state preparation
>>> grover_op = GroverOperator(oracle, state_preparation)
>>> grover_op.draw()
┌───┐┌──────────┐┌───┐┌───┐┌───┐┌─────────┐
state_0: ┤ Z ├┤ RY(-0.2) ├┤ X ├┤ Z ├┤ X ├┤ RY(0.2) ├
└───┘└──────────┘└───┘└───┘└───┘└─────────┘
>>> oracle = QuantumCircuit(4)
>>> oracle.z(3)
>>> reflection_qubits = [0, 3]
>>> state_preparation = QuantumCircuit(4)
>>> state_preparation.cry(0.1, 0, 3)
>>> state_preparation.ry(0.5, 3)
>>> grover_op = GroverOperator(oracle, state_preparation,
... reflection_qubits=reflection_qubits)
>>> grover_op.draw()
┌───┐ ┌───┐
state_0: ──────────────────────■──────┤ X ├───────■──┤ X ├──────────■────────────────
│ └───┘ │ └───┘ │
state_1: ──────────────────────┼──────────────────┼─────────────────┼────────────────
│ │ │
state_2: ──────────────────────┼──────────────────┼─────────────────┼────────────────
┌───┐┌──────────┐┌────┴─────┐┌───┐┌───┐┌─┴─┐┌───┐┌───┐┌────┴────┐┌─────────┐
state_3: ┤ Z ├┤ RY(-0.5) ├┤ RY(-0.1) ├┤ X ├┤ H ├┤ X ├┤ H ├┤ X ├┤ RY(0.1) ├┤ RY(0.5) ├
└───┘└──────────┘└──────────┘└───┘└───┘└───┘└───┘└───┘└─────────┘└─────────┘
>>> mark_state = Statevector.from_label('011')
>>> diffuse_operator = 2 * DensityMatrix.from_label('000') - Operator.from_label('III')
>>> grover_op = GroverOperator(oracle=mark_state, zero_reflection=diffuse_operator)
>>> grover_op.draw(fold=70)
┌─────────────────┐ ┌───┐ »
state_0: ┤0 ├──────┤ H ├──────────────────────────»
│ │┌─────┴───┴─────┐ ┌───┐ »
state_1: ┤1 UCRZ(0,pi,0,0) ├┤0 ├─────┤ H ├──────────»
│ ││ UCRZ(pi/2,0) │┌────┴───┴────┐┌───┐»
state_2: ┤2 ├┤1 ├┤ UCRZ(-pi/4) ├┤ H ├»
└─────────────────┘└───────────────┘└─────────────┘└───┘»
« ┌─────────────────┐ ┌───┐
«state_0: ┤0 ├──────┤ H ├─────────────────────────
« │ │┌─────┴───┴─────┐ ┌───┐
«state_1: ┤1 UCRZ(pi,0,0,0) ├┤0 ├────┤ H ├──────────
« │ ││ UCRZ(pi/2,0) │┌───┴───┴────┐┌───┐
«state_2: ┤2 ├┤1 ├┤ UCRZ(pi/4) ├┤ H ├
« └─────────────────┘└───────────────┘└────────────┘└───┘
References:
[1]: L. K. Grover (1996), A fast quantum mechanical algorithm for database search,
`arXiv:quant-ph/9605043 <https://arxiv.org/abs/quant-ph/9605043>`_.
[2]: I. Chuang & M. Nielsen, Quantum Computation and Quantum Information,
Cambridge: Cambridge University Press, 2000. Chapter 6.1.2.
[3]: Brassard, G., Hoyer, P., Mosca, M., & Tapp, A. (2000).
Quantum Amplitude Amplification and Estimation.
`arXiv:quant-ph/0005055 <http://arxiv.org/abs/quant-ph/0005055>`_.
Args:
oracle: The phase oracle implementing a reflection about the bad state. Note that this
is not a bitflip oracle, see the docstring for more information.
state_preparation: The operator preparing the good and bad state.
For Grover's algorithm, this is a n-qubit Hadamard gate and for amplitude
amplification or estimation the operator :math:`\mathcal{A}`.
zero_reflection: The reflection about the zero state, :math:`\mathcal{S}_0`.
reflection_qubits: Qubits on which the zero reflection acts on.
insert_barriers: Whether barriers should be inserted between the reflections and A.
mcx_mode: The mode to use for building the default zero reflection.
name: The name of the circuit.
The oracle implementing a reflection about the bad state.
Reflection qubits, on which S0 is applied (if S0 is not user-specified).
The subcircuit implementing the A operator or Hadamards.
The subcircuit implementing the reflection about 0.
The Grover operator.
This code is part of Qiskit. (C) Copyright IBM 2017, 2020. This code is licensed under the Apache License, Version 2.0. You may obtain a copy of this license in the LICENSE.txt file in the root directory of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. Any modifications or derivative works of this code must retain this copyright notice, and modified files need to carry a notice indicating that they have been altered from the originals. from qiskit.quantum_info import Statevector, Operator, DensityMatrix oracle: Union[QuantumCircuit, Statevector], zero_reflection: Optional[Union[QuantumCircuit, DensityMatrix, Operator]] = None, store inputs if isinstance(oracle, Statevector): from qiskit.circuit.library import Diagonal pylint: disable=cyclic-import oracle = Diagonal((-1) ** oracle.data) if isinstance(zero_reflection, (Operator, DensityMatrix)): from qiskit.circuit.library import Diagonal pylint: disable=cyclic-import zero_reflection = Diagonal(zero_reflection.data.diagonal()) build circuit apply Hadamards only on reflection qubits, rest will cancel out minus sign TODO use the oracle compiler or the bit string oracle MCX does not allow 0 control qubits, therefore this is separate | 9,320 | en | 0.52359 |
import numpy as np
import copy, operator
from qtensor.optimisation.Optimizer import OrderingOptimizer
from qtensor import utils
from functools import reduce
import networkx as nx
import qtree
def reducelist(f, lst, x=0):
prev = x
for i in lst:
prev = f(prev, i)
yield prev
class RGreedyOptimizer(OrderingOptimizer):
"""
An orderer that greedy selects vertices
using boltzman probabilities.
"""
def __init__(self, *args, temp=0.002, repeats=10, **kwargs):
super().__init__(*args, **kwargs)
self.temp = temp
self.repeats = repeats
def _get_ordering(self, graph, **kwargs):
node_names = nx.get_node_attributes(graph, 'name')
node_sizes = nx.get_node_attributes(graph, 'size')
peo, path = self._get_ordering_ints(graph)
peo = [qtree.optimizer.Var(var, size=node_sizes[var],
name=node_names[var])
for var in peo]
#print('tw=', max(path))
return peo, path
def _get_ordering_ints(self, old_graph, free_vars=[]):
best_peo = None
best_width = np.inf
best_widths = None
for i in range(self.repeats):
graph = copy.deepcopy(old_graph)
peo = []
widths = []
while graph.number_of_nodes():
ngs = np.array(list(
map(len, map(operator.itemgetter(1), graph.adjacency()))
))
weights = np.exp(-(ngs - np.min(ngs))/self.temp)
#print(ngs)
#print(weights)
# 1, 3, 5, 2, 1
distrib = np.array([0]+list(reducelist(lambda x, y:x+y, weights, 0)))
#print(distrib)
# 0, 1, 4, 9, 11, 12
rnd = np.random.random()*distrib[-1]
# between 0 and 12 = say, 5
# find the smallest value that larger than rnd
bool_map = distrib < rnd
# True, True, True, False, False, False
select_map = bool_map[1:] ^ bool_map[:-1]
selected_elem = np.array(list(graph.nodes))[select_map]
assert len(selected_elem)==1, 'Error in algorithm, please submit an issue'
selected_node = selected_elem[0]
utils.eliminate_node_no_structure(graph, selected_node)
peo.append(int(selected_node))
widths.append(int(ngs[select_map][0]))
if max(widths) < best_width:
best_peo = peo
best_widths = widths
best_width = max(widths)
return best_peo, best_widths
| qtensor/optimisation/RGreedy.py | 2,668 | An orderer that greedy selects vertices
using boltzman probabilities.
print('tw=', max(path))print(ngs)print(weights) 1, 3, 5, 2, 1print(distrib) 0, 1, 4, 9, 11, 12 between 0 and 12 = say, 5 find the smallest value that larger than rnd True, True, True, False, False, False | 275 | en | 0.687733 |
import os
import json
__author__ = 'Manfred Minimair <manfred@minimair.org>'
class JSONStorage:
"""
File storage for a dictionary.
"""
file = '' # file name of storage file
data = None # data dict
indent = ' ' # indent prefix for pretty printing json files
def __init__(self, path, name):
"""
Initizlize.
:param path: path to the storage file;
empty means the current direcory.
:param name: file name, json file; may include a path.
"""
if path:
os.makedirs(path, exist_ok=True)
self.file = os.path.normpath(os.path.join(path, name))
try:
with open(self.file) as data_file:
self.data = json.load(data_file)
except FileNotFoundError:
self.data = dict()
self.dump()
def dump(self):
"""
Dump data into storage file.
"""
with open(self.file, 'w') as out_file:
json.dump(self.data, out_file, indent=self.indent)
def get(self, item):
"""
Get stored item.
:param item: name, string, of item to get.
:return: stored item; raises a KeyError if item does not exist.
"""
return self.data[item]
def set(self, item, value):
"""
Set item's value; causes the data to be dumped into the storage file.
:param item: name, string of item to set.
:param value: value to set.
"""
self.data[item] = value
self.dump()
def __getattr__(self, item):
"""
Get stored item with .-notation if not defined as a class member.
:param item: name, string of item compatible
with Python class member name.
:return value of item.
"""
if item in self.data:
return self.data[item]
else:
raise AttributeError
| netdata/workers/json_storage.py | 1,906 | File storage for a dictionary.
Get stored item with .-notation if not defined as a class member.
:param item: name, string of item compatible
with Python class member name.
:return value of item.
Initizlize.
:param path: path to the storage file;
empty means the current direcory.
:param name: file name, json file; may include a path.
Dump data into storage file.
Get stored item.
:param item: name, string, of item to get.
:return: stored item; raises a KeyError if item does not exist.
Set item's value; causes the data to be dumped into the storage file.
:param item: name, string of item to set.
:param value: value to set.
file name of storage file data dict indent prefix for pretty printing json files | 711 | en | 0.731064 |
from __future__ import annotations
import asyncio
import logging
import uuid
from collections import defaultdict
from collections.abc import Hashable
from dask.utils import parse_timedelta
from distributed.client import Client
from distributed.utils import TimeoutError, log_errors
from distributed.worker import get_worker
logger = logging.getLogger(__name__)
class MultiLockExtension:
"""An extension for the scheduler to manage MultiLocks
This adds the following routes to the scheduler
* multi_lock_acquire
* multi_lock_release
The approach is to maintain `self.locks` that maps a lock (unique name given to
`MultiLock(names=, ...)` at creation) to a list of users (instances of `MultiLock`)
that "requests" the lock. Additionally, `self.requests` maps a user to its requested
locks and `self.requests_left` maps a user to the number of locks still need.
Every time a user `x` gets to the front in `self.locks[name] = [x, ...]` it means
that `x` now holds the lock `name` and when it holds all the requested locks
`acquire()` can return.
Finally, `self.events` contains all the events users are waiting on to finish.
"""
def __init__(self, scheduler):
self.scheduler = scheduler
self.locks = defaultdict(list) # lock -> users
self.requests = {} # user -> locks
self.requests_left = {} # user -> locks still needed
self.events = {}
self.scheduler.handlers.update(
{"multi_lock_acquire": self.acquire, "multi_lock_release": self.release}
)
def _request_locks(self, locks: list[str], id: Hashable, num_locks: int) -> bool:
"""Request locks
Parameters
----------
locks: List[str]
Names of the locks to request.
id: Hashable
Identifier of the `MultiLock` instance requesting the locks.
num_locks: int
Number of locks in `locks` requesting
Return
------
result: bool
Whether `num_locks` requested locks are free immediately or not.
"""
assert id not in self.requests
self.requests[id] = set(locks)
assert len(locks) >= num_locks and num_locks > 0
self.requests_left[id] = num_locks
locks = sorted(locks, key=lambda x: len(self.locks[x]))
for i, lock in enumerate(locks):
self.locks[lock].append(id)
if len(self.locks[lock]) == 1: # The lock was free
self.requests_left[id] -= 1
if self.requests_left[id] == 0: # Got all locks needed
# Since we got all locks need, we can remove the rest of the requests
self.requests[id] -= set(locks[i + 1 :])
return True
return False
def _refain_locks(self, locks, id):
"""Cancel/release previously requested/acquired locks
Parameters
----------
locks: List[str]
Names of the locks to refain.
id: Hashable
Identifier of the `MultiLock` instance refraining the locks.
"""
waiters_ready = set()
for lock in locks:
if self.locks[lock][0] == id:
self.locks[lock].pop(0)
if self.locks[lock]:
new_first = self.locks[lock][0]
self.requests_left[new_first] -= 1
if self.requests_left[new_first] <= 0:
# Notice, `self.requests_left[new_first]` might go below zero
# if more locks are freed than requested.
self.requests_left[new_first] = 0
waiters_ready.add(new_first)
else:
self.locks[lock].remove(id)
assert id not in self.locks[lock]
del self.requests[id]
del self.requests_left[id]
for waiter in waiters_ready:
self.scheduler.loop.add_callback(self.events[waiter].set)
async def acquire(self, locks=None, id=None, timeout=None, num_locks=None):
with log_errors():
if not self._request_locks(locks, id, num_locks):
assert id not in self.events
event = asyncio.Event()
self.events[id] = event
future = event.wait()
if timeout is not None:
future = asyncio.wait_for(future, timeout)
try:
await future
except TimeoutError:
self._refain_locks(locks, id)
return False
finally:
del self.events[id]
# At this point `id` acquired all `locks`
assert self.requests_left[id] == 0
return True
def release(self, id=None):
with log_errors():
self._refain_locks(self.requests[id], id)
class MultiLock:
"""Distributed Centralized Lock
Parameters
----------
names: List[str]
Names of the locks to acquire. Choosing the same name allows two
disconnected processes to coordinate a lock.
client: Client (optional)
Client to use for communication with the scheduler. If not given, the
default global client will be used.
Examples
--------
>>> lock = MultiLock(['x', 'y']) # doctest: +SKIP
>>> lock.acquire(timeout=1) # doctest: +SKIP
>>> # do things with protected resource 'x' and 'y'
>>> lock.release() # doctest: +SKIP
"""
def __init__(self, names=[], client=None):
try:
self.client = client or Client.current()
except ValueError:
# Initialise new client
self.client = get_worker().client
self.names = names
self.id = uuid.uuid4().hex
self._locked = False
def acquire(self, blocking=True, timeout=None, num_locks=None):
"""Acquire the lock
Parameters
----------
blocking : bool, optional
If false, don't wait on the lock in the scheduler at all.
timeout : string or number or timedelta, optional
Seconds to wait on the lock in the scheduler. This does not
include local coroutine time, network transfer time, etc..
It is forbidden to specify a timeout when blocking is false.
Instead of number of seconds, it is also possible to specify
a timedelta in string format, e.g. "200ms".
num_locks : int, optional
Number of locks needed. If None, all locks are needed
Examples
--------
>>> lock = MultiLock(['x', 'y']) # doctest: +SKIP
>>> lock.acquire(timeout="1s") # doctest: +SKIP
Returns
-------
True or False whether or not it successfully acquired the lock
"""
timeout = parse_timedelta(timeout)
if not blocking:
if timeout is not None:
raise ValueError("can't specify a timeout for a non-blocking call")
timeout = 0
result = self.client.sync(
self.client.scheduler.multi_lock_acquire,
locks=self.names,
id=self.id,
timeout=timeout,
num_locks=num_locks or len(self.names),
)
self._locked = True
return result
def release(self):
"""Release the lock if already acquired"""
if not self.locked():
raise ValueError("Lock is not yet acquired")
ret = self.client.sync(self.client.scheduler.multi_lock_release, id=self.id)
self._locked = False
return ret
def locked(self):
return self._locked
def __enter__(self):
self.acquire()
return self
def __exit__(self, *args, **kwargs):
self.release()
async def __aenter__(self):
await self.acquire()
return self
async def __aexit__(self, *args, **kwargs):
await self.release()
def __reduce__(self):
return (type(self), (self.names,))
| distributed/multi_lock.py | 8,091 | Distributed Centralized Lock
Parameters
----------
names: List[str]
Names of the locks to acquire. Choosing the same name allows two
disconnected processes to coordinate a lock.
client: Client (optional)
Client to use for communication with the scheduler. If not given, the
default global client will be used.
Examples
--------
>>> lock = MultiLock(['x', 'y']) # doctest: +SKIP
>>> lock.acquire(timeout=1) # doctest: +SKIP
>>> # do things with protected resource 'x' and 'y'
>>> lock.release() # doctest: +SKIP
An extension for the scheduler to manage MultiLocks
This adds the following routes to the scheduler
* multi_lock_acquire
* multi_lock_release
The approach is to maintain `self.locks` that maps a lock (unique name given to
`MultiLock(names=, ...)` at creation) to a list of users (instances of `MultiLock`)
that "requests" the lock. Additionally, `self.requests` maps a user to its requested
locks and `self.requests_left` maps a user to the number of locks still need.
Every time a user `x` gets to the front in `self.locks[name] = [x, ...]` it means
that `x` now holds the lock `name` and when it holds all the requested locks
`acquire()` can return.
Finally, `self.events` contains all the events users are waiting on to finish.
Cancel/release previously requested/acquired locks
Parameters
----------
locks: List[str]
Names of the locks to refain.
id: Hashable
Identifier of the `MultiLock` instance refraining the locks.
Request locks
Parameters
----------
locks: List[str]
Names of the locks to request.
id: Hashable
Identifier of the `MultiLock` instance requesting the locks.
num_locks: int
Number of locks in `locks` requesting
Return
------
result: bool
Whether `num_locks` requested locks are free immediately or not.
Acquire the lock
Parameters
----------
blocking : bool, optional
If false, don't wait on the lock in the scheduler at all.
timeout : string or number or timedelta, optional
Seconds to wait on the lock in the scheduler. This does not
include local coroutine time, network transfer time, etc..
It is forbidden to specify a timeout when blocking is false.
Instead of number of seconds, it is also possible to specify
a timedelta in string format, e.g. "200ms".
num_locks : int, optional
Number of locks needed. If None, all locks are needed
Examples
--------
>>> lock = MultiLock(['x', 'y']) # doctest: +SKIP
>>> lock.acquire(timeout="1s") # doctest: +SKIP
Returns
-------
True or False whether or not it successfully acquired the lock
Release the lock if already acquired
lock -> users user -> locks user -> locks still needed The lock was free Got all locks needed Since we got all locks need, we can remove the rest of the requests Notice, `self.requests_left[new_first]` might go below zero if more locks are freed than requested. At this point `id` acquired all `locks` Initialise new client | 2,924 | en | 0.785905 |
import torchvision
import numpy as np
import matplotlib
import matplotlib.pyplot as plt
def display_and_save_batch(title, batch, data, save=True, display=True):
"""Display and save batch of image using plt"""
im = torchvision.utils.make_grid(batch, nrow=int(batch.shape[0]**0.5))
plt.title(title)
plt.imshow(np.transpose(im.cpu().numpy(), (1, 2, 0)), cmap='gray')
if save:
plt.savefig('results/' + title + data + '.png', transparent=True, bbox_inches='tight')
if display:
plt.show()
def display_and_save_latent(batch, label, data, save=True, display=True):
"""Display and save batch of 2-D latent variable using plt"""
colors = ['black', 'red', 'green', 'blue', 'yellow', 'cyan', 'magenta', 'pink', 'violet', 'grey']
z = batch.cpu().detach().numpy()
l = label.cpu().numpy()
plt.title('Latent variables')
plt.scatter(z[:,0], z[:,1], c=l, cmap=matplotlib.colors.ListedColormap(colors))
plt.xlim(-3, 3, )
plt.ylim(-3, 3)
if save:
plt.savefig('results/latent-variable' + data + '.png', transparent=True, bbox_inches='tight')
if display:
plt.show() | Implementations/Conditional-Variational-Autoencoder/plot_utils.py | 1,142 | Display and save batch of image using plt
Display and save batch of 2-D latent variable using plt | 97 | en | 0.425743 |
import binascii
from PySide2.QtWidgets import QTableWidget, QTableWidgetItem, QAbstractItemView
from PySide2.QtCore import Qt
class QPatchTableItem:
def __init__(self, patch, old_bytes):
self.patch = patch
self.old_bytes = old_bytes
def widgets(self):
patch = self.patch
widgets = [
QTableWidgetItem("%#x" % patch.addr),
QTableWidgetItem("%d bytes" % len(patch)),
QTableWidgetItem(binascii.hexlify(self.old_bytes).decode("ascii") if self.old_bytes else "<unknown>"),
QTableWidgetItem(binascii.hexlify(patch.new_bytes).decode("ascii")),
]
for w in widgets:
w.setFlags(w.flags() & ~Qt.ItemIsEditable)
return widgets
class QPatchTable(QTableWidget):
HEADER = ['Address', 'Size', 'Old Bytes', 'New Bytes']
def __init__(self, instance, parent):
super(QPatchTable, self).__init__(parent)
self.setColumnCount(len(self.HEADER))
self.setHorizontalHeaderLabels(self.HEADER)
self.setSelectionBehavior(QAbstractItemView.SelectRows)
self.verticalHeader().setVisible(False)
self.items = [ ]
self.instance = instance
self.instance.patches.am_subscribe(self._watch_patches)
def current_patch(self):
selected_index = self.currentRow()
if 0 <= selected_index < len(self.items):
return self.items[selected_index]
else:
return None
def reload(self):
current_row = self.currentRow()
self.clearContents()
self.items = [QPatchTableItem(item,
self._get_bytes(self.instance.project, item.addr, len(item)))
for item in self.instance.project.kb.patches.values()]
items_count = len(self.items)
self.setRowCount(items_count)
for idx, item in enumerate(self.items):
for i, it in enumerate(item.widgets()):
self.setItem(idx, i, it)
#if 0 <= current_row < len(self.items):
# self.setCurrentItem(current_row, 0)
def _on_state_selected(self, *args):
if self._selected is not None:
self._selected(self.current_state_record())
def _watch_patches(self, **kwargs):
if not self.instance.patches.am_none:
self.reload()
@staticmethod
def _get_bytes(proj, addr, size):
try:
return proj.loader.memory.load(addr, size)
except KeyError:
return None
| angrmanagement/ui/widgets/qpatch_table.py | 2,529 | if 0 <= current_row < len(self.items): self.setCurrentItem(current_row, 0) | 77 | en | 0.530122 |
import enum
import SimpleITK as sitk
@enum.unique
class Interpolation(enum.Enum):
"""Interpolation techniques available in ITK.
Example:
>>> import torchio as tio
>>> transform = tio.RandomAffine(image_interpolation='nearest')
"""
#: Interpolates image intensity at a non-integer pixel position by copying the intensity for the nearest neighbor.
NEAREST: str = 'sitkNearestNeighbor'
#: Linearly interpolates image intensity at a non-integer pixel position.
LINEAR: str = 'sitkLinear'
#: Computes the B-spline interpolation weights over the support region of the B-spline.
BSPLINE: str = 'sitkBSpline'
GAUSSIAN: str = 'sitkGaussian'
LABEL_GAUSSIAN: str = 'sitkLabelGaussian'
HAMMING: str = 'sitkHammingWindowedSinc'
COSINE: str = 'sitkCosineWindowedSinc'
WELCH: str = 'sitkWelchWindowedSinc'
LANCZOS: str = 'sitkLanczosWindowedSinc'
BLACKMAN: str = 'sitkBlackmanWindowedSinc'
def get_sitk_interpolator(interpolation: str) -> int:
if not isinstance(interpolation, str):
message = (
f'Interpolation must be a string, not {type(interpolation)}'
)
raise ValueError(message)
string = getattr(Interpolation, interpolation.upper()).value
return getattr(sitk, string)
| torchio/transforms/interpolation.py | 1,296 | Interpolation techniques available in ITK.
Example:
>>> import torchio as tio
>>> transform = tio.RandomAffine(image_interpolation='nearest')
: Interpolates image intensity at a non-integer pixel position by copying the intensity for the nearest neighbor.: Linearly interpolates image intensity at a non-integer pixel position.: Computes the B-spline interpolation weights over the support region of the B-spline. | 423 | en | 0.666017 |
# -*- coding: utf-8 -*- #
# Copyright 2016 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""service-management operations describe command."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.calliope import base
from googlecloudsdk.command_lib.endpoints import common_flags
_ERROR = ('The `service-management operations describe` command has been '
'replaced by `endpoints operations describe` and '
'`services operations describe`.')
@base.Deprecate(is_removed=True, error=_ERROR)
class Describe(base.DescribeCommand):
"""Describes an operation resource for a given operation name."""
@staticmethod
def Args(parser):
"""Args is called by calliope to gather arguments for this command.
Args:
parser: An argparse parser that you can use to add arguments that go
on the command line after this command. Positional arguments are
allowed.
"""
common_flags.operation_flag(suffix='to describe').AddToParser(parser)
parser.display_info.AddFormat(
':(metadata.startTime.date(format="%Y-%m-%d %H:%M:%S %Z", tz=LOCAL)) '
'[transforms] default')
parser.add_argument(
'--full',
action='store_true',
default=False,
help=('Print the entire operation resource, which could be large. '
'By default, a summary will be printed instead.'))
def Run(self, args):
"""Stubs 'service-management operations describe'.
Args:
args: argparse.Namespace, The arguments that this command was invoked
with.
"""
pass
| lib/surface/service_management/operations/describe.py | 2,184 | Describes an operation resource for a given operation name.
Args is called by calliope to gather arguments for this command.
Args:
parser: An argparse parser that you can use to add arguments that go
on the command line after this command. Positional arguments are
allowed.
Stubs 'service-management operations describe'.
Args:
args: argparse.Namespace, The arguments that this command was invoked
with.
service-management operations describe command.
-*- coding: utf-8 -*- Copyright 2016 Google Inc. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. | 1,069 | en | 0.854669 |
"""
Reads the version information from the manifest of the Chrome extension.
Author: Mustafa Emre Acer
"""
import json
import sys
def ReadChromeExtensionVersion(manifest_path):
with open(manifest_path) as manifest_file:
manifest = json.load(manifest_file)
print(manifest['version'])
if __name__ == "__main__":
if len(sys.argv) > 1:
ReadChromeExtensionVersion(sys.argv[1])
else:
print('\nUsage: chrome_extension_version.py <manifest_path>\n')
exit(-1)
| build/chrome_extension_version.py | 486 | Reads the version information from the manifest of the Chrome extension.
Author: Mustafa Emre Acer | 98 | en | 0.81803 |
"""
Backprop NN training on Madelon data (Feature selection complete)
"""
import os
import csv
import time
import sys
sys.path.append("C:/ABAGAIL/ABAGAIL.jar")
from func.nn.backprop import BackPropagationNetworkFactory
from shared import SumOfSquaresError, DataSet, Instance
from opt.example import NeuralNetworkOptimizationProblem
from func.nn.backprop import RPROPUpdateRule, BatchBackPropagationTrainer
import opt.RandomizedHillClimbing as RandomizedHillClimbing
import opt.SimulatedAnnealing as SimulatedAnnealing
import opt.ga.StandardGeneticAlgorithm as StandardGeneticAlgorithm
from func.nn.activation import ActivationFunction
# Network parameters found "optimal" in Assignment 1
INPUT_LAYER = 31
HIDDEN_LAYER1 = 62
HIDDEN_LAYER2 = 62
HIDDEN_LAYER3 = 62
OUTPUT_LAYER = 1
TRAINING_ITERATIONS = 5001
OUTFILE = 'BACKPROP_LOG.txt'
def initialize_instances(infile):
"""Read the m_trg.csv CSV data into a list of instances."""
instances = []
# Read in the CSV file
#with open(infile, "r") as dat:
dat = open(infile,"r")
reader = csv.reader(dat)
dat.close()
for row in reader:
instance = Instance([float(value) for value in row[:-1]])
if float(row[-1]) < 0:
instance.setLabel(Instance(0))
else:
instance.setLabel(Instance(1))
#instance.setLabel(Instance(0 if float(row[-1]) < 0 else 1))
instances.append(instance)
return instances
def errorOnDataSet(network,ds,measure):
N = len(ds)
error = 0.
correct = 0
incorrect = 0
for instance in ds:
network.setInputValues(instance.getData())
network.run()
actual = instance.getLabel().getContinuous()
predicted = network.getOutputValues().get(0)
predicted = max(min(predicted,1),0)
if abs(predicted - actual) < 0.5:
correct += 1
else:
incorrect += 1
output = instance.getLabel()
output_values = network.getOutputValues()
example = Instance(output_values, Instance(output_values.get(0)))
error += measure.value(output, example)
MSE = error/float(N)
acc = correct/float(correct+incorrect)
return MSE,acc
def train(oa, network, oaName, training_ints,validation_ints,testing_ints, measure):
"""Train a given network on a set of instances.
"""
print ("\nError results for {}\n---------------------------".format(oaName))
times = [0]
for iteration in xrange(TRAINING_ITERATIONS):
start = time.clock()
oa.train()
elapsed = time.clock()-start
times.append(times[-1]+elapsed)
if iteration % 10 == 0:
MSE_trg, acc_trg = errorOnDataSet(network,training_ints,measure)
MSE_val, acc_val = errorOnDataSet(network,validation_ints,measure)
MSE_tst, acc_tst = errorOnDataSet(network,testing_ints,measure)
txt = '{},{},{},{},{},{},{},{}\n'.format(iteration,MSE_trg,MSE_val,MSE_tst,acc_trg,acc_val,acc_tst,times[-1]);
print (txt)
#with open(OUTFILE,'a+') as f:
f=open(OUTFILE,'a+')
f.write(txt)
f.close()
def main():
"""Run this experiment"""
training_ints = initialize_instances('m_trg.csv')
testing_ints = initialize_instances('m_test.csv')
validation_ints = initialize_instances('m_val.csv')
factory = BackPropagationNetworkFactory()
measure = SumOfSquaresError()
data_set = DataSet(training_ints)
relu = RELU()
rule = RPROPUpdateRule()
oa_names = ["Backprop"]
classification_network = factory.createClassificationNetwork([INPUT_LAYER, HIDDEN_LAYER1,HIDDEN_LAYER2,HIDDEN_LAYER3, OUTPUT_LAYER],relu)
train(BatchBackPropagationTrainer(data_set,classification_network,measure,rule), classification_network, 'Backprop', training_ints,validation_ints,testing_ints, measure)
if __name__ == "__main__":
#with open(OUTFILE,'w') as f:
f=open(OUTFILE,'a+')
f.write('{},{},{},{},{},{},{},{}\n'.format('iteration','MSE_trg','MSE_val','MSE_tst','acc_trg','acc_val','acc_tst','elapsed'))
f.close()
main() | ABAGAIL_execution/flipflop.py | 4,116 | Read the m_trg.csv CSV data into a list of instances.
Run this experiment
Train a given network on a set of instances.
Backprop NN training on Madelon data (Feature selection complete)
Network parameters found "optimal" in Assignment 1 Read in the CSV filewith open(infile, "r") as dat:instance.setLabel(Instance(0 if float(row[-1]) < 0 else 1))with open(OUTFILE,'a+') as f:with open(OUTFILE,'w') as f: | 409 | en | 0.836118 |
# coding=utf-8
# *** WARNING: this file was generated by the Pulumi SDK Generator. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, Sequence, Union
from ... import _utilities, _tables
from . import outputs
from ._enums import *
from ._inputs import *
__all__ = ['MachineLearningCompute']
class MachineLearningCompute(pulumi.CustomResource):
def __init__(__self__,
resource_name: str,
opts: Optional[pulumi.ResourceOptions] = None,
compute_name: Optional[pulumi.Input[str]] = None,
identity: Optional[pulumi.Input[pulumi.InputType['IdentityArgs']]] = None,
location: Optional[pulumi.Input[str]] = None,
properties: Optional[pulumi.Input[Union[pulumi.InputType['AKSArgs'], pulumi.InputType['AmlComputeArgs'], pulumi.InputType['ComputeInstanceArgs'], pulumi.InputType['DataFactoryArgs'], pulumi.InputType['DataLakeAnalyticsArgs'], pulumi.InputType['DatabricksArgs'], pulumi.InputType['HDInsightArgs'], pulumi.InputType['VirtualMachineArgs']]]] = None,
resource_group_name: Optional[pulumi.Input[str]] = None,
sku: Optional[pulumi.Input[pulumi.InputType['SkuArgs']]] = None,
tags: Optional[pulumi.Input[Mapping[str, pulumi.Input[str]]]] = None,
workspace_name: Optional[pulumi.Input[str]] = None,
__props__=None,
__name__=None,
__opts__=None):
"""
Machine Learning compute object wrapped into ARM resource envelope.
:param str resource_name: The name of the resource.
:param pulumi.ResourceOptions opts: Options for the resource.
:param pulumi.Input[str] compute_name: Name of the Azure Machine Learning compute.
:param pulumi.Input[pulumi.InputType['IdentityArgs']] identity: The identity of the resource.
:param pulumi.Input[str] location: Specifies the location of the resource.
:param pulumi.Input[Union[pulumi.InputType['AKSArgs'], pulumi.InputType['AmlComputeArgs'], pulumi.InputType['ComputeInstanceArgs'], pulumi.InputType['DataFactoryArgs'], pulumi.InputType['DataLakeAnalyticsArgs'], pulumi.InputType['DatabricksArgs'], pulumi.InputType['HDInsightArgs'], pulumi.InputType['VirtualMachineArgs']]] properties: Compute properties
:param pulumi.Input[str] resource_group_name: Name of the resource group in which workspace is located.
:param pulumi.Input[pulumi.InputType['SkuArgs']] sku: The sku of the workspace.
:param pulumi.Input[Mapping[str, pulumi.Input[str]]] tags: Contains resource tags defined as key/value pairs.
:param pulumi.Input[str] workspace_name: Name of Azure Machine Learning workspace.
"""
if __name__ is not None:
warnings.warn("explicit use of __name__ is deprecated", DeprecationWarning)
resource_name = __name__
if __opts__ is not None:
warnings.warn("explicit use of __opts__ is deprecated, use 'opts' instead", DeprecationWarning)
opts = __opts__
if opts is None:
opts = pulumi.ResourceOptions()
if not isinstance(opts, pulumi.ResourceOptions):
raise TypeError('Expected resource options to be a ResourceOptions instance')
if opts.version is None:
opts.version = _utilities.get_version()
if opts.id is None:
if __props__ is not None:
raise TypeError('__props__ is only valid when passed in combination with a valid opts.id to get an existing resource')
__props__ = dict()
__props__['compute_name'] = compute_name
__props__['identity'] = identity
__props__['location'] = location
__props__['properties'] = properties
if resource_group_name is None and not opts.urn:
raise TypeError("Missing required property 'resource_group_name'")
__props__['resource_group_name'] = resource_group_name
__props__['sku'] = sku
__props__['tags'] = tags
if workspace_name is None and not opts.urn:
raise TypeError("Missing required property 'workspace_name'")
__props__['workspace_name'] = workspace_name
__props__['name'] = None
__props__['system_data'] = None
__props__['type'] = None
alias_opts = pulumi.ResourceOptions(aliases=[pulumi.Alias(type_="azure-nextgen:machinelearningservices/v20210101:MachineLearningCompute"), pulumi.Alias(type_="azure-native:machinelearningservices:MachineLearningCompute"), pulumi.Alias(type_="azure-nextgen:machinelearningservices:MachineLearningCompute"), pulumi.Alias(type_="azure-native:machinelearningservices/latest:MachineLearningCompute"), pulumi.Alias(type_="azure-nextgen:machinelearningservices/latest:MachineLearningCompute"), pulumi.Alias(type_="azure-native:machinelearningservices/v20180301preview:MachineLearningCompute"), pulumi.Alias(type_="azure-nextgen:machinelearningservices/v20180301preview:MachineLearningCompute"), pulumi.Alias(type_="azure-native:machinelearningservices/v20181119:MachineLearningCompute"), pulumi.Alias(type_="azure-nextgen:machinelearningservices/v20181119:MachineLearningCompute"), pulumi.Alias(type_="azure-native:machinelearningservices/v20190501:MachineLearningCompute"), pulumi.Alias(type_="azure-nextgen:machinelearningservices/v20190501:MachineLearningCompute"), pulumi.Alias(type_="azure-native:machinelearningservices/v20190601:MachineLearningCompute"), pulumi.Alias(type_="azure-nextgen:machinelearningservices/v20190601:MachineLearningCompute"), pulumi.Alias(type_="azure-native:machinelearningservices/v20191101:MachineLearningCompute"), pulumi.Alias(type_="azure-nextgen:machinelearningservices/v20191101:MachineLearningCompute"), pulumi.Alias(type_="azure-native:machinelearningservices/v20200101:MachineLearningCompute"), pulumi.Alias(type_="azure-nextgen:machinelearningservices/v20200101:MachineLearningCompute"), pulumi.Alias(type_="azure-native:machinelearningservices/v20200218preview:MachineLearningCompute"), pulumi.Alias(type_="azure-nextgen:machinelearningservices/v20200218preview:MachineLearningCompute"), pulumi.Alias(type_="azure-native:machinelearningservices/v20200301:MachineLearningCompute"), pulumi.Alias(type_="azure-nextgen:machinelearningservices/v20200301:MachineLearningCompute"), pulumi.Alias(type_="azure-native:machinelearningservices/v20200401:MachineLearningCompute"), pulumi.Alias(type_="azure-nextgen:machinelearningservices/v20200401:MachineLearningCompute"), pulumi.Alias(type_="azure-native:machinelearningservices/v20200501preview:MachineLearningCompute"), pulumi.Alias(type_="azure-nextgen:machinelearningservices/v20200501preview:MachineLearningCompute"), pulumi.Alias(type_="azure-native:machinelearningservices/v20200515preview:MachineLearningCompute"), pulumi.Alias(type_="azure-nextgen:machinelearningservices/v20200515preview:MachineLearningCompute"), pulumi.Alias(type_="azure-native:machinelearningservices/v20200601:MachineLearningCompute"), pulumi.Alias(type_="azure-nextgen:machinelearningservices/v20200601:MachineLearningCompute"), pulumi.Alias(type_="azure-native:machinelearningservices/v20200801:MachineLearningCompute"), pulumi.Alias(type_="azure-nextgen:machinelearningservices/v20200801:MachineLearningCompute"), pulumi.Alias(type_="azure-native:machinelearningservices/v20200901preview:MachineLearningCompute"), pulumi.Alias(type_="azure-nextgen:machinelearningservices/v20200901preview:MachineLearningCompute")])
opts = pulumi.ResourceOptions.merge(opts, alias_opts)
super(MachineLearningCompute, __self__).__init__(
'azure-native:machinelearningservices/v20210101:MachineLearningCompute',
resource_name,
__props__,
opts)
@staticmethod
def get(resource_name: str,
id: pulumi.Input[str],
opts: Optional[pulumi.ResourceOptions] = None) -> 'MachineLearningCompute':
"""
Get an existing MachineLearningCompute resource's state with the given name, id, and optional extra
properties used to qualify the lookup.
:param str resource_name: The unique name of the resulting resource.
:param pulumi.Input[str] id: The unique provider ID of the resource to lookup.
:param pulumi.ResourceOptions opts: Options for the resource.
"""
opts = pulumi.ResourceOptions.merge(opts, pulumi.ResourceOptions(id=id))
__props__ = dict()
__props__["identity"] = None
__props__["location"] = None
__props__["name"] = None
__props__["properties"] = None
__props__["sku"] = None
__props__["system_data"] = None
__props__["tags"] = None
__props__["type"] = None
return MachineLearningCompute(resource_name, opts=opts, __props__=__props__)
@property
@pulumi.getter
def identity(self) -> pulumi.Output[Optional['outputs.IdentityResponse']]:
"""
The identity of the resource.
"""
return pulumi.get(self, "identity")
@property
@pulumi.getter
def location(self) -> pulumi.Output[Optional[str]]:
"""
Specifies the location of the resource.
"""
return pulumi.get(self, "location")
@property
@pulumi.getter
def name(self) -> pulumi.Output[str]:
"""
Specifies the name of the resource.
"""
return pulumi.get(self, "name")
@property
@pulumi.getter
def properties(self) -> pulumi.Output[Any]:
"""
Compute properties
"""
return pulumi.get(self, "properties")
@property
@pulumi.getter
def sku(self) -> pulumi.Output[Optional['outputs.SkuResponse']]:
"""
The sku of the workspace.
"""
return pulumi.get(self, "sku")
@property
@pulumi.getter(name="systemData")
def system_data(self) -> pulumi.Output['outputs.SystemDataResponse']:
"""
Read only system data
"""
return pulumi.get(self, "system_data")
@property
@pulumi.getter
def tags(self) -> pulumi.Output[Optional[Mapping[str, str]]]:
"""
Contains resource tags defined as key/value pairs.
"""
return pulumi.get(self, "tags")
@property
@pulumi.getter
def type(self) -> pulumi.Output[str]:
"""
Specifies the type of the resource.
"""
return pulumi.get(self, "type")
def translate_output_property(self, prop):
return _tables.CAMEL_TO_SNAKE_CASE_TABLE.get(prop) or prop
def translate_input_property(self, prop):
return _tables.SNAKE_TO_CAMEL_CASE_TABLE.get(prop) or prop
| sdk/python/pulumi_azure_native/machinelearningservices/v20210101/machine_learning_compute.py | 10,901 | Machine Learning compute object wrapped into ARM resource envelope.
:param str resource_name: The name of the resource.
:param pulumi.ResourceOptions opts: Options for the resource.
:param pulumi.Input[str] compute_name: Name of the Azure Machine Learning compute.
:param pulumi.Input[pulumi.InputType['IdentityArgs']] identity: The identity of the resource.
:param pulumi.Input[str] location: Specifies the location of the resource.
:param pulumi.Input[Union[pulumi.InputType['AKSArgs'], pulumi.InputType['AmlComputeArgs'], pulumi.InputType['ComputeInstanceArgs'], pulumi.InputType['DataFactoryArgs'], pulumi.InputType['DataLakeAnalyticsArgs'], pulumi.InputType['DatabricksArgs'], pulumi.InputType['HDInsightArgs'], pulumi.InputType['VirtualMachineArgs']]] properties: Compute properties
:param pulumi.Input[str] resource_group_name: Name of the resource group in which workspace is located.
:param pulumi.Input[pulumi.InputType['SkuArgs']] sku: The sku of the workspace.
:param pulumi.Input[Mapping[str, pulumi.Input[str]]] tags: Contains resource tags defined as key/value pairs.
:param pulumi.Input[str] workspace_name: Name of Azure Machine Learning workspace.
Get an existing MachineLearningCompute resource's state with the given name, id, and optional extra
properties used to qualify the lookup.
:param str resource_name: The unique name of the resulting resource.
:param pulumi.Input[str] id: The unique provider ID of the resource to lookup.
:param pulumi.ResourceOptions opts: Options for the resource.
The identity of the resource.
Specifies the location of the resource.
Specifies the name of the resource.
Compute properties
The sku of the workspace.
Read only system data
Contains resource tags defined as key/value pairs.
Specifies the type of the resource.
coding=utf-8 *** WARNING: this file was generated by the Pulumi SDK Generator. *** *** Do not edit by hand unless you're certain you know what you are doing! *** | 1,940 | en | 0.590042 |
# Copyright Contributors to the Amundsen project.
# SPDX-License-Identifier: Apache-2.0
import unittest
from unittest.mock import ANY
from databuilder.models.graph_serializable import (
RELATION_END_KEY, RELATION_END_LABEL, RELATION_REVERSE_TYPE, RELATION_START_KEY, RELATION_START_LABEL,
RELATION_TYPE,
)
from databuilder.models.table_source import TableSource
from databuilder.serializers import neo4_serializer, neptune_serializer
from databuilder.serializers.neptune_serializer import (
NEPTUNE_CREATION_TYPE_JOB, NEPTUNE_CREATION_TYPE_RELATIONSHIP_PROPERTY_NAME_BULK_LOADER_FORMAT, NEPTUNE_HEADER_ID,
NEPTUNE_HEADER_LABEL, NEPTUNE_LAST_EXTRACTED_AT_RELATIONSHIP_PROPERTY_NAME_BULK_LOADER_FORMAT,
NEPTUNE_RELATIONSHIP_HEADER_FROM, NEPTUNE_RELATIONSHIP_HEADER_TO,
)
DB = 'hive'
SCHEMA = 'base'
TABLE = 'test'
CLUSTER = 'default'
SOURCE = '/etl/sql/file.py'
class TestTableSource(unittest.TestCase):
def setUp(self) -> None:
super(TestTableSource, self).setUp()
self.table_source = TableSource(db_name='hive',
schema=SCHEMA,
table_name=TABLE,
cluster=CLUSTER,
source=SOURCE)
self.start_key = f'{DB}://{CLUSTER}.{SCHEMA}/{TABLE}/_source'
self.end_key = f'{DB}://{CLUSTER}.{SCHEMA}/{TABLE}'
def test_get_source_model_key(self) -> None:
source = self.table_source.get_source_model_key()
self.assertEqual(source, f'{DB}://{CLUSTER}.{SCHEMA}/{TABLE}/_source')
def test_get_metadata_model_key(self) -> None:
metadata = self.table_source.get_metadata_model_key()
self.assertEqual(metadata, 'hive://default.base/test')
def test_create_nodes(self) -> None:
nodes = self.table_source.create_nodes()
self.assertEqual(len(nodes), 1)
def test_create_relation(self) -> None:
relations = self.table_source.create_relation()
self.assertEquals(len(relations), 1)
serialized_relation = neo4_serializer.serialize_relationship(relations[0])
expected_relation = {
RELATION_START_KEY: self.start_key,
RELATION_START_LABEL: TableSource.LABEL,
RELATION_END_KEY: self.end_key,
RELATION_END_LABEL: 'Table',
RELATION_TYPE: TableSource.SOURCE_TABLE_RELATION_TYPE,
RELATION_REVERSE_TYPE: TableSource.TABLE_SOURCE_RELATION_TYPE
}
self.assertDictEqual(expected_relation, serialized_relation)
def test_create_relation_neptune(self) -> None:
relations = self.table_source.create_relation()
serialized_relations = neptune_serializer.convert_relationship(relations[0])
expected = [
{
NEPTUNE_HEADER_ID: "{from_vertex_id}_{to_vertex_id}_{label}".format(
from_vertex_id=self.start_key,
to_vertex_id=self.end_key,
label=TableSource.SOURCE_TABLE_RELATION_TYPE
),
NEPTUNE_RELATIONSHIP_HEADER_FROM: self.start_key,
NEPTUNE_RELATIONSHIP_HEADER_TO: self.end_key,
NEPTUNE_HEADER_LABEL: TableSource.SOURCE_TABLE_RELATION_TYPE,
NEPTUNE_LAST_EXTRACTED_AT_RELATIONSHIP_PROPERTY_NAME_BULK_LOADER_FORMAT: ANY,
NEPTUNE_CREATION_TYPE_RELATIONSHIP_PROPERTY_NAME_BULK_LOADER_FORMAT: NEPTUNE_CREATION_TYPE_JOB
},
{
NEPTUNE_HEADER_ID: "{from_vertex_id}_{to_vertex_id}_{label}".format(
from_vertex_id=self.end_key,
to_vertex_id=self.start_key,
label=TableSource.TABLE_SOURCE_RELATION_TYPE
),
NEPTUNE_RELATIONSHIP_HEADER_FROM: self.end_key,
NEPTUNE_RELATIONSHIP_HEADER_TO: self.start_key,
NEPTUNE_HEADER_LABEL: TableSource.TABLE_SOURCE_RELATION_TYPE,
NEPTUNE_LAST_EXTRACTED_AT_RELATIONSHIP_PROPERTY_NAME_BULK_LOADER_FORMAT: ANY,
NEPTUNE_CREATION_TYPE_RELATIONSHIP_PROPERTY_NAME_BULK_LOADER_FORMAT: NEPTUNE_CREATION_TYPE_JOB
}
]
self.assertListEqual(expected, serialized_relations)
| tests/unit/models/test_table_source.py | 4,277 | Copyright Contributors to the Amundsen project. SPDX-License-Identifier: Apache-2.0 | 83 | en | 0.433107 |
__copyright__ = "Copyright (C) 2009-2013 Andreas Kloeckner"
__license__ = """
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 pymbolic.primitives as prim
import pytest
from pymbolic import parse
from pytools.lex import ParseError
from pymbolic.mapper import IdentityMapper
try:
reduce
except NameError:
from functools import reduce
# {{{ utilities
def assert_parsed_same_as_python(expr_str):
# makes sure that has only one line
expr_str, = expr_str.split("\n")
from pymbolic.interop.ast import ASTToPymbolic
import ast
ast2p = ASTToPymbolic()
try:
expr_parsed_by_python = ast2p(ast.parse(expr_str).body[0].value)
except SyntaxError:
with pytest.raises(ParseError):
parse(expr_str)
else:
expr_parsed_by_pymbolic = parse(expr_str)
assert expr_parsed_by_python == expr_parsed_by_pymbolic
def assert_parse_roundtrip(expr_str):
expr = parse(expr_str)
from pymbolic.mapper.stringifier import StringifyMapper
strified = StringifyMapper()(expr)
assert strified == expr_str, (strified, expr_str)
# }}}
def test_integer_power():
from pymbolic.algorithm import integer_power
for base, expn in [
(17, 5),
(17, 2**10),
(13, 20),
(13, 1343),
]:
assert base**expn == integer_power(base, expn)
def test_expand():
from pymbolic import var, expand
x = var("x")
u = (x+1)**5
expand(u)
def test_substitute():
from pymbolic import parse, substitute, evaluate
u = parse("5+x.min**2")
xmin = parse("x.min")
assert evaluate(substitute(u, {xmin: 25})) == 630
def test_no_comparison():
from pymbolic import parse
x = parse("17+3*x")
y = parse("12-5*y")
def expect_typeerror(f):
try:
f()
except TypeError:
pass
else:
raise AssertionError
expect_typeerror(lambda: x < y)
expect_typeerror(lambda: x <= y)
expect_typeerror(lambda: x > y)
expect_typeerror(lambda: x >= y)
def test_structure_preservation():
x = prim.Sum((5, 7))
from pymbolic.mapper import IdentityMapper
x2 = IdentityMapper()(x)
assert x == x2
def test_sympy_interaction():
pytest.importorskip("sympy")
import sympy as sp
x, y = sp.symbols("x y")
f = sp.Function("f")
s1_expr = 1/f(x/sp.sqrt(x**2+y**2)).diff(x, 5) # pylint:disable=not-callable
from pymbolic.interop.sympy import (
SympyToPymbolicMapper,
PymbolicToSympyMapper)
s2p = SympyToPymbolicMapper()
p2s = PymbolicToSympyMapper()
p1_expr = s2p(s1_expr)
s2_expr = p2s(p1_expr)
assert sp.ratsimp(s1_expr - s2_expr) == 0
p2_expr = s2p(s2_expr)
s3_expr = p2s(p2_expr)
assert sp.ratsimp(s1_expr - s3_expr) == 0
# {{{ fft
def test_fft_with_floats():
numpy = pytest.importorskip("numpy")
import numpy.linalg as la
from pymbolic.algorithm import fft, ifft
for n in [2**i for i in range(4, 10)]+[17, 12, 948]:
a = numpy.random.rand(n) + 1j*numpy.random.rand(n)
f_a = fft(a)
a2 = ifft(f_a)
assert la.norm(a-a2) < 1e-10
f_a_numpy = numpy.fft.fft(a)
assert la.norm(f_a-f_a_numpy) < 1e-10
class NearZeroKiller(IdentityMapper):
def map_constant(self, expr):
if isinstance(expr, complex):
r = expr.real
i = expr.imag
if abs(r) < 1e-15:
r = 0
if abs(i) < 1e-15:
i = 0
return complex(r, i)
else:
return expr
def test_fft():
numpy = pytest.importorskip("numpy")
from pymbolic import var
from pymbolic.algorithm import fft, sym_fft
vars = numpy.array([var(chr(97+i)) for i in range(16)], dtype=object)
print(vars)
print(fft(vars))
traced_fft = sym_fft(vars)
from pymbolic.mapper.stringifier import PREC_NONE
from pymbolic.mapper.c_code import CCodeMapper
ccm = CCodeMapper()
code = [ccm(tfi, PREC_NONE) for tfi in traced_fft]
for cse_name, cse_str in enumerate(ccm.cse_name_list):
print(f"{cse_name} = {cse_str}")
for i, line in enumerate(code):
print("result[%d] = %s" % (i, line))
# }}}
def test_sparse_multiply():
numpy = pytest.importorskip("numpy")
pytest.importorskip("scipy")
import scipy.sparse as ss
la = numpy.linalg
mat = numpy.random.randn(10, 10)
s_mat = ss.csr_matrix(mat)
vec = numpy.random.randn(10)
mat_vec = s_mat*vec
from pymbolic.algorithm import csr_matrix_multiply
mat_vec_2 = csr_matrix_multiply(s_mat, vec)
assert la.norm(mat_vec-mat_vec_2) < 1e-14
# {{{ parser
def test_parser():
from pymbolic import parse
parse("(2*a[1]*b[1]+2*a[0]*b[0])*(hankel_1(-1,sqrt(a[1]**2+a[0]**2)*k) "
"-hankel_1(1,sqrt(a[1]**2+a[0]**2)*k))*k /(4*sqrt(a[1]**2+a[0]**2)) "
"+hankel_1(0,sqrt(a[1]**2+a[0]**2)*k)")
print(repr(parse("d4knl0")))
print(repr(parse("0.")))
print(repr(parse("0.e1")))
assert parse("0.e1") == 0
assert parse("1e-12") == 1e-12
print(repr(parse("a >= 1")))
print(repr(parse("a <= 1")))
print(repr(parse(":")))
print(repr(parse("1:")))
print(repr(parse(":2")))
print(repr(parse("1:2")))
print(repr(parse("::")))
print(repr(parse("1::")))
print(repr(parse(":1:")))
print(repr(parse("::1")))
print(repr(parse("3::1")))
print(repr(parse(":5:1")))
print(repr(parse("3:5:1")))
assert_parse_roundtrip("()")
assert_parse_roundtrip("(3,)")
assert_parse_roundtrip("[x + 3, 3, 5]")
assert_parse_roundtrip("[]")
assert_parse_roundtrip("[x]")
assert_parse_roundtrip("g[i, k] + 2.0*h[i, k]")
parse("g[i,k]+(+2.0)*h[i, k]")
print(repr(parse("a - b - c")))
print(repr(parse("-a - -b - -c")))
print(repr(parse("- - - a - - - - b - - - - - c")))
print(repr(parse("~(a ^ b)")))
print(repr(parse("(a | b) | ~(~a & ~b)")))
print(repr(parse("3 << 1")))
print(repr(parse("1 >> 3")))
print(parse("3::1"))
assert parse("e1") == prim.Variable("e1")
assert parse("d1") == prim.Variable("d1")
from pymbolic import variables
f, x, y, z = variables("f x y z")
assert parse("f((x,y),z)") == f((x, y), z)
assert parse("f((x,),z)") == f((x,), z)
assert parse("f(x,(y,z),z)") == f(x, (y, z), z)
assert parse("f(x,(y,z),z, name=15)") == f(x, (y, z), z, name=15)
assert parse("f(x,(y,z),z, name=15, name2=17)") == f(
x, (y, z), z, name=15, name2=17)
assert_parsed_same_as_python("5+i if i>=0 else (0 if i<-1 else 10)")
assert_parsed_same_as_python("0 if 1 if 2 else 3 else 4")
assert_parsed_same_as_python("0 if (1 if 2 else 3) else 4")
assert_parsed_same_as_python("(2, 3,)")
with pytest.deprecated_call():
parse("1+if(0, 1, 2)")
# }}}
def test_mappers():
from pymbolic import variables
f, x, y, z = variables("f x y z")
for expr in [
f(x, (y, z), name=z**2)
]:
from pymbolic.mapper import WalkMapper
from pymbolic.mapper.dependency import DependencyMapper
str(expr)
IdentityMapper()(expr)
WalkMapper()(expr)
DependencyMapper()(expr)
def test_func_dep_consistency():
from pymbolic import var
from pymbolic.mapper.dependency import DependencyMapper
f = var("f")
x = var("x")
dep_map = DependencyMapper(include_calls="descend_args")
assert dep_map(f(x)) == {x}
assert dep_map(f(x=x)) == {x}
def test_conditions():
from pymbolic import var
x = var("x")
y = var("y")
assert str(x.eq(y).and_(x.le(5))) == "x == y and x <= 5"
def test_graphviz():
from pymbolic import parse
expr = parse("(2*a[1]*b[1]+2*a[0]*b[0])*(hankel_1(-1,sqrt(a[1]**2+a[0]**2)*k) "
"-hankel_1(1,sqrt(a[1]**2+a[0]**2)*k))*k /(4*sqrt(a[1]**2+a[0]**2)) "
"+hankel_1(0,sqrt(a[1]**2+a[0]**2)*k)")
from pymbolic.mapper.graphviz import GraphvizMapper
gvm = GraphvizMapper()
gvm(expr)
print(gvm.get_dot_code())
# {{{ geometric algebra
@pytest.mark.parametrize("dims", [2, 3, 4, 5])
# START_GA_TEST
def test_geometric_algebra(dims):
pytest.importorskip("numpy")
import numpy as np
from pymbolic.geometric_algebra import MultiVector as MV # noqa
vec1 = MV(np.random.randn(dims))
vec2 = MV(np.random.randn(dims))
vec3 = MV(np.random.randn(dims))
vec4 = MV(np.random.randn(dims))
vec5 = MV(np.random.randn(dims))
# Fundamental identity
assert ((vec1 ^ vec2) + (vec1 | vec2)).close_to(vec1*vec2)
# Antisymmetry
assert (vec1 ^ vec2 ^ vec3).close_to(- vec2 ^ vec1 ^ vec3)
vecs = [vec1, vec2, vec3, vec4, vec5]
if len(vecs) > dims:
from operator import xor as outer
assert reduce(outer, vecs).close_to(0)
assert (vec1.inv()*vec1).close_to(1)
assert (vec1*vec1.inv()).close_to(1)
assert ((1/vec1)*vec1).close_to(1)
assert (vec1/vec1).close_to(1)
for a, b, c in [
(vec1, vec2, vec3),
(vec1*vec2, vec3, vec4),
(vec1, vec2*vec3, vec4),
(vec1, vec2, vec3*vec4),
(vec1, vec2, vec3*vec4*vec5),
(vec1, vec2*vec1, vec3*vec4*vec5),
]:
# Associativity
assert ((a*b)*c).close_to(a*(b*c))
assert ((a ^ b) ^ c).close_to(a ^ (b ^ c))
# The inner product is not associative.
# scalar product
assert ((c*b).project(0)) .close_to(b.scalar_product(c))
assert ((c.rev()*b).project(0)) .close_to(b.rev().scalar_product(c))
assert ((b.rev()*b).project(0)) .close_to(b.norm_squared())
assert b.norm_squared() >= 0
assert c.norm_squared() >= 0
# Cauchy's inequality
assert b.scalar_product(c) <= abs(b)*abs(c) + 1e-13
# contractions
# (3.18) in [DFM]
assert abs(b.scalar_product(a ^ c) - (b >> a).scalar_product(c)) < 1e-13
# duality, (3.20) in [DFM]
assert ((a ^ b) << c) .close_to(a << (b << c))
# two definitions of the dual agree: (1.2.26) in [HS]
# and (sec 3.5.3) in [DFW]
assert (c << c.I.rev()).close_to(c | c.I.rev())
# inverse
for div in list(b.gen_blades()) + [vec1, vec1.I]:
assert (div.inv()*div).close_to(1)
assert (div*div.inv()).close_to(1)
assert ((1/div)*div).close_to(1)
assert (div/div).close_to(1)
assert ((c/div)*div).close_to(c)
assert ((c*div)/div).close_to(c)
# reverse properties (Sec 2.9.5 [DFM])
assert c.rev().rev() == c
assert (b ^ c).rev() .close_to(c.rev() ^ b.rev())
# dual properties
# (1.2.26) in [HS]
assert c.dual() .close_to(c | c.I.rev())
assert c.dual() .close_to(c*c.I.rev())
# involution properties (Sec 2.9.5 DFW)
assert c.invol().invol() == c
assert (b ^ c).invol() .close_to(b.invol() ^ c.invol())
# commutator properties
# Jacobi identity (1.1.56c) in [HS] or (8.2) in [DFW]
assert (a.x(b.x(c)) + b.x(c.x(a)) + c.x(a.x(b))).close_to(0)
# (1.57) in [HS]
assert a.x(b*c) .close_to(a.x(b)*c + b*a.x(c))
# END_GA_TEST
# }}}
def test_ast_interop():
src = """
def f():
xx = 3*y + z * (12 if x < 13 else 13)
yy = f(x, y=y)
"""
import ast
mod = ast.parse(src.replace("\n ", "\n"))
print(ast.dump(mod))
from pymbolic.interop.ast import ASTToPymbolic
ast2p = ASTToPymbolic()
for f in mod.body:
if not isinstance(f, ast.FunctionDef):
continue
for stmt in f.body:
if not isinstance(stmt, ast.Assign):
continue
lhs, = stmt.targets
lhs = ast2p(lhs)
rhs = ast2p(stmt.value)
print(lhs, rhs)
def test_compile():
from pymbolic import parse, compile
code = compile(parse("x ** y"), ["x", "y"])
assert code(2, 5) == 32
# Test pickling of compiled code.
import pickle
code = pickle.loads(pickle.dumps(code))
assert code(3, 3) == 27
def test_unifier():
from pymbolic import var
from pymbolic.mapper.unifier import UnidirectionalUnifier
a, b, c, d, e, f = [var(s) for s in "abcdef"]
def match_found(records, eqns):
for record in records:
if eqns <= set(record.equations):
return True
return False
recs = UnidirectionalUnifier("abc")(a+b*c, d+e*f)
assert len(recs) == 2
assert match_found(recs, {(a, d), (b, e), (c, f)})
assert match_found(recs, {(a, d), (b, f), (c, e)})
recs = UnidirectionalUnifier("abc")(a+b, d+e+f)
assert len(recs) == 6
assert match_found(recs, {(a, d), (b, e+f)})
assert match_found(recs, {(a, e), (b, d+f)})
assert match_found(recs, {(a, f), (b, d+e)})
assert match_found(recs, {(b, d), (a, e+f)})
assert match_found(recs, {(b, e), (a, d+f)})
assert match_found(recs, {(b, f), (a, d+e)})
vals = [var("v" + str(i)) for i in range(100)]
recs = UnidirectionalUnifier("a")(sum(vals[1:]) + a, sum(vals))
assert len(recs) == 1
assert match_found(recs, {(a, var("v0"))})
recs = UnidirectionalUnifier("abc")(a+b+c, d+e)
assert len(recs) == 0
recs = UnidirectionalUnifier("abc")(f(a+b, f(a+c)), f(b+c, f(b+d)))
assert len(recs) == 1
assert match_found(recs, {(a, b), (b, c), (c, d)})
def test_long_sympy_mapping():
sp = pytest.importorskip("sympy")
from pymbolic.interop.sympy import SympyToPymbolicMapper
SympyToPymbolicMapper()(sp.sympify(int(10**20)))
SympyToPymbolicMapper()(sp.sympify(int(10)))
def test_stringifier_preserve_shift_order():
for expr in [
parse("(a << b) >> 2"),
parse("a << (b >> 2)")
]:
assert parse(str(expr)) == expr
LATEX_TEMPLATE = r"""\documentclass{article}
\usepackage{amsmath}
\begin{document}
%s
\end{document}"""
def test_latex_mapper():
from pymbolic import parse
from pymbolic.mapper.stringifier import LaTeXMapper, StringifyMapper
tm = LaTeXMapper()
sm = StringifyMapper()
equations = []
def add(expr):
# Add an equation to the list of tests.
equations.append(r"\[{}\] % from: {}".format(tm(expr), sm(expr)))
add(parse("a * b + c"))
add(parse("f(a,b,c)"))
add(parse("a ** b ** c"))
add(parse("(a | b) ^ ~c"))
add(parse("a << b"))
add(parse("a >> b"))
add(parse("a[i,j,k]"))
add(parse("a[1:3]"))
add(parse("a // b"))
add(parse("not (a or b) and c"))
add(parse("(a % b) % c"))
add(parse("(a >= b) or (b <= c)"))
add(prim.Min((1,)) + prim.Max((1, 2)))
add(prim.Substitution(prim.Variable("x") ** 2, ("x",), (2,)))
add(prim.Derivative(parse("x**2"), ("x",)))
# Run LaTeX and ensure the file compiles.
import os
import tempfile
import subprocess
import shutil
latex_dir = tempfile.mkdtemp("pymbolic")
try:
tex_file_path = os.path.join(latex_dir, "input.tex")
with open(tex_file_path, "w") as tex_file:
contents = LATEX_TEMPLATE % "\n".join(equations)
tex_file.write(contents)
try:
subprocess.check_output(
["latex",
"-interaction=nonstopmode",
"-output-directory=%s" % latex_dir,
tex_file_path],
universal_newlines=True)
except OSError: # FIXME: Should be FileNotFoundError on Py3
pytest.skip("latex command not found")
except subprocess.CalledProcessError as err:
raise AssertionError(str(err.output))
finally:
shutil.rmtree(latex_dir)
def test_flop_counter():
x = prim.Variable("x")
y = prim.Variable("y")
z = prim.Variable("z")
subexpr = prim.CommonSubexpression(3 * (x**2 + y + z))
expr = 3*subexpr + subexpr
from pymbolic.mapper.flop_counter import FlopCounter, CSEAwareFlopCounter
assert FlopCounter()(expr) == 4 * 2 + 2
assert CSEAwareFlopCounter()(expr) == 4 + 2
def test_make_sym_vector():
numpy = pytest.importorskip("numpy")
from pymbolic.primitives import make_sym_vector
assert len(make_sym_vector("vec", 2)) == 2
assert len(make_sym_vector("vec", numpy.int32(2))) == 2
assert len(make_sym_vector("vec", [1, 2, 3])) == 3
def test_multiplicative_stringify_preserves_association():
for inner in ["*", " / ", " // ", " % "]:
for outer in ["*", " / ", " // ", " % "]:
if outer == inner:
continue
assert_parse_roundtrip(f"x{outer}(y{inner}z)")
assert_parse_roundtrip(f"(y{inner}z){outer}x")
assert_parse_roundtrip("(-1)*(((-1)*x) / 5)")
def test_differentiator_flags_for_nonsmooth_and_discontinuous():
import pymbolic.functions as pf
from pymbolic.mapper.differentiator import differentiate
x = prim.Variable("x")
with pytest.raises(ValueError):
differentiate(pf.fabs(x), x)
result = differentiate(pf.fabs(x), x, allowed_nonsmoothness="continuous")
assert result == pf.sign(x)
with pytest.raises(ValueError):
differentiate(pf.sign(x), x)
result = differentiate(pf.sign(x), x, allowed_nonsmoothness="discontinuous")
assert result == 0
def test_np_bool_handling():
from pymbolic.mapper.evaluator import evaluate
numpy = pytest.importorskip("numpy")
expr = prim.LogicalNot(numpy.bool_(False))
assert evaluate(expr) is True
if __name__ == "__main__":
import sys
if len(sys.argv) > 1:
exec(sys.argv[1])
else:
from pytest import main
main([__file__])
# vim: fdm=marker
| test/test_pymbolic.py | 18,814 | {{{ utilities makes sure that has only one line }}} pylint:disable=not-callable {{{ fft }}} {{{ parser }}} {{{ geometric algebra START_GA_TEST noqa Fundamental identity Antisymmetry Associativity The inner product is not associative. scalar product Cauchy's inequality contractions (3.18) in [DFM] duality, (3.20) in [DFM] two definitions of the dual agree: (1.2.26) in [HS] and (sec 3.5.3) in [DFW] inverse reverse properties (Sec 2.9.5 [DFM]) dual properties (1.2.26) in [HS] involution properties (Sec 2.9.5 DFW) commutator properties Jacobi identity (1.1.56c) in [HS] or (8.2) in [DFW] (1.57) in [HS] END_GA_TEST }}} Test pickling of compiled code. Add an equation to the list of tests. Run LaTeX and ensure the file compiles. FIXME: Should be FileNotFoundError on Py3 vim: fdm=marker | 788 | en | 0.794382 |
"""Support for the OpenWeatherMap (OWM) service."""
from homeassistant.components.weather import WeatherEntity
from homeassistant.const import TEMP_CELSIUS
from .const import (
ATTR_API_CONDITION,
ATTR_API_FORECAST,
ATTR_API_HUMIDITY,
ATTR_API_PRESSURE,
ATTR_API_TEMPERATURE,
ATTR_API_WIND_BEARING,
ATTR_API_WIND_SPEED,
ATTRIBUTION,
DOMAIN,
ENTRY_NAME,
ENTRY_WEATHER_COORDINATOR,
)
from .weather_update_coordinator import WeatherUpdateCoordinator
async def async_setup_entry(hass, config_entry, async_add_entities):
"""Set up OpenWeatherMap weather entity based on a config entry."""
domain_data = hass.data[DOMAIN][config_entry.entry_id]
name = domain_data[ENTRY_NAME]
weather_coordinator = domain_data[ENTRY_WEATHER_COORDINATOR]
unique_id = f"{config_entry.unique_id}"
owm_weather = OpenWeatherMapWeather(name, unique_id, weather_coordinator)
async_add_entities([owm_weather], False)
class OpenWeatherMapWeather(WeatherEntity):
"""Implementation of an OpenWeatherMap sensor."""
def __init__(
self,
name,
unique_id,
weather_coordinator: WeatherUpdateCoordinator,
):
"""Initialize the sensor."""
self._name = name
self._unique_id = unique_id
self._weather_coordinator = weather_coordinator
@property
def name(self):
"""Return the name of the sensor."""
return self._name
@property
def unique_id(self):
"""Return a unique_id for this entity."""
return self._unique_id
@property
def should_poll(self):
"""Return the polling requirement of the entity."""
return False
@property
def attribution(self):
"""Return the attribution."""
return ATTRIBUTION
@property
def condition(self):
"""Return the current condition."""
return self._weather_coordinator.data[ATTR_API_CONDITION]
@property
def temperature(self):
"""Return the temperature."""
return self._weather_coordinator.data[ATTR_API_TEMPERATURE]
@property
def temperature_unit(self):
"""Return the unit of measurement."""
return TEMP_CELSIUS
@property
def pressure(self):
"""Return the pressure."""
return self._weather_coordinator.data[ATTR_API_PRESSURE]
@property
def humidity(self):
"""Return the humidity."""
return self._weather_coordinator.data[ATTR_API_HUMIDITY]
@property
def wind_speed(self):
"""Return the wind speed."""
wind_speed = self._weather_coordinator.data[ATTR_API_WIND_SPEED]
if self.hass.config.units.name == "imperial":
return round(wind_speed * 2.24, 2)
return round(wind_speed * 3.6, 2)
@property
def wind_bearing(self):
"""Return the wind bearing."""
return self._weather_coordinator.data[ATTR_API_WIND_BEARING]
@property
def forecast(self):
"""Return the forecast array."""
return self._weather_coordinator.data[ATTR_API_FORECAST]
@property
def available(self):
"""Return True if entity is available."""
return self._weather_coordinator.last_update_success
async def async_added_to_hass(self):
"""Connect to dispatcher listening for entity data notifications."""
self.async_on_remove(
self._weather_coordinator.async_add_listener(self.async_write_ha_state)
)
async def async_update(self):
"""Get the latest data from OWM and updates the states."""
await self._weather_coordinator.async_request_refresh()
| homeassistant/components/openweathermap/weather.py | 3,650 | Implementation of an OpenWeatherMap sensor.
Initialize the sensor.
Return the attribution.
Return True if entity is available.
Return the current condition.
Return the forecast array.
Return the humidity.
Return the name of the sensor.
Return the pressure.
Return the polling requirement of the entity.
Return the temperature.
Return the unit of measurement.
Return a unique_id for this entity.
Return the wind bearing.
Return the wind speed.
Support for the OpenWeatherMap (OWM) service. | 488 | en | 0.689007 |
# -*- coding: utf-8 -*-
# nodeandtag's package version information
__version_major__ = "0.2"
__version__ = "{}a1".format(__version_major__)
__version_long__ = "{}a1".format(__version_major__)
__status__ = "Alpha"
__author__ = "Jeremy Morosi"
__author_email__ = "jeremymorosi@hotmail.com"
__url__ = "https://github.com/Nauja/nodeandtag"
| noteandtag/__version__.py | 337 | -*- coding: utf-8 -*- nodeandtag's package version information | 62 | en | 0.360283 |
from __future__ import absolute_import, division, print_function
import os
import subprocess
import sys
from setuptools import find_packages, setup
PROJECT_PATH = os.path.dirname(os.path.abspath(__file__))
VERSION = """
# This file is auto-generated with the version information during setup.py installation.
__version__ = '{}'
"""
# Find pyro version.
for line in open(os.path.join(PROJECT_PATH, 'pyro', '__init__.py')):
if line.startswith('version_prefix = '):
version = line.strip().split()[2][1:-1]
# Append current commit sha to version
commit_sha = ''
try:
commit_sha = subprocess.check_output(['git', 'rev-parse', '--short', 'HEAD'],
cwd=PROJECT_PATH).decode('ascii').strip()
except OSError:
pass
# Write version to _version.py
if commit_sha:
version += '+{}'.format(commit_sha)
with open(os.path.join(PROJECT_PATH, 'pyro', '_version.py'), 'w') as f:
f.write(VERSION.format(version))
# Convert README.md to rst for display at https://pypi.python.org/pypi/pyro-ppl
# When releasing on pypi, make sure pandoc is on your system:
# $ brew install pandoc # OS X
# $ sudo apt-get install pandoc # Ubuntu Linux
try:
import pypandoc
long_description = pypandoc.convert('README.md', 'rst')
except (IOError, ImportError, OSError) as e:
sys.stderr.write('Failed to convert README.md to rst:\n {}\n'.format(e))
sys.stderr.flush()
long_description = open('README.md').read()
# Remove badges since they will always be obsolete.
blacklist = ['Build Status', 'Latest Version', 'Documentation Status',
'travis-ci.org', 'pypi.python.org', 'pyro-ppl.readthedocs.io']
long_description = '\n'.join(
[line for line in long_description.split('\n') if not any(patt in line for patt in blacklist)])
# examples/tutorials
EXTRAS_REQUIRE = [
'jupyter>=1.0.0',
'matplotlib>=1.3',
'observations>=0.1.4',
'pillow',
'torchvision',
'visdom>=0.1.4',
'pandas',
'wget',
]
if sys.version_info[0] == 2:
EXTRAS_REQUIRE.append('functools32')
setup(
name='pyro-ppl',
version=version,
description='A Python library for probabilistic modeling and inference',
long_description=long_description,
packages=find_packages(include=['pyro', 'pyro.*']),
url='http://pyro.ai',
author='Uber AI Labs',
author_email='pyro@uber.com',
install_requires=[
# if you add any additional libraries, please also
# add them to `docs/requirements.txt`
'contextlib2',
'graphviz>=0.8',
'networkx>=2.2',
'numpy>=1.7',
'opt_einsum>=2.2.0',
'six>=1.10.0',
'torch==0.4.0',
'tqdm>=4.25',
],
extras_require={
'extras': EXTRAS_REQUIRE,
'test': EXTRAS_REQUIRE + [
'nbval',
'pytest==3.7',
'pytest-cov',
'scipy>=0.19.0',
'ipython<=6.5.0', # https://github.com/jupyter/jupyter_console/issues/158
],
'profile': ['prettytable', 'pytest-benchmark', 'snakeviz'],
'dev': EXTRAS_REQUIRE + [
'flake8',
'isort',
'nbformat',
'nbsphinx>=0.3.2',
'nbstripout',
'nbval',
'pypandoc',
'pytest==3.7',
'pytest-xdist',
'ipython<=6.5.0', # https://github.com/jupyter/jupyter_console/issues/158
'scipy>=0.19.0',
'sphinx',
'sphinx_rtd_theme',
'yapf',
],
},
tests_require=['flake8', 'pytest==3.7'],
keywords='machine learning statistics probabilistic programming bayesian modeling pytorch',
license='MIT License',
classifiers=[
'Intended Audience :: Developers',
'Intended Audience :: Education',
'Intended Audience :: Science/Research',
'Operating System :: POSIX :: Linux',
'Operating System :: MacOS :: MacOS X',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3.6',
],
# yapf
)
| setup.py | 4,067 | Find pyro version. Append current commit sha to version Write version to _version.py Convert README.md to rst for display at https://pypi.python.org/pypi/pyro-ppl When releasing on pypi, make sure pandoc is on your system: $ brew install pandoc OS X $ sudo apt-get install pandoc Ubuntu Linux Remove badges since they will always be obsolete. examples/tutorials if you add any additional libraries, please also add them to `docs/requirements.txt` https://github.com/jupyter/jupyter_console/issues/158 https://github.com/jupyter/jupyter_console/issues/158 yapf | 571 | en | 0.786415 |
from __future__ import unicode_literals
from django.apps import apps
from django.db import models
from django.urls import reverse
from django.utils.encoding import force_text, python_2_unicode_compatible
from django.utils.translation import ugettext
@python_2_unicode_compatible
class Collection(object):
_registry = []
@classmethod
def get_all(cls):
return sorted(cls._registry, key=lambda entry: entry._order)
def __init__(self, label, icon=None, link=None, queryset=None, model=None, order=None):
self._label = label
self._icon = icon
self._link = link
self._queryset = queryset
self._model = model
self._order = order or 99
self.__class__._registry.append(self)
def __str__(self):
return force_text(self.label)
def resolve(self):
self.children = self._get_children()
self.icon = self._icon
self.label = self._label
self.url = None
if self._link:
self.icon = getattr(self._link, 'icon', self._icon)
self.url = reverse(viewname=self._link.view, args=self._link.args)
return ''
def _get_children(self):
if self._queryset:
return self._queryset
else:
if self._model:
return self._model.objects.all()
class Dashboard(object):
_registry = {}
@classmethod
def get(cls, name):
return cls._registry[name]
def __init__(self, name, label):
self.name = name
self.label = label
self.widgets = {}
self.removed_widgets = []
self.__class__._registry[name] = self
def add_widget(self, widget, order=0):
self.widgets[widget] = {'widget': widget, 'order': order}
def get_widgets(self):
"""
Returns a list of widgets sorted by their 'order'.
If two or more widgets have the same 'order', sort by label.
"""
return map(
lambda x: x['widget'],
filter(
lambda x: x['widget'] not in self.removed_widgets,
sorted(
self.widgets.values(),
key=lambda x: (x['order'], x['widget'].label)
)
)
)
def remove_widget(self, widget):
self.removed_widgets.append(widget)
class DashboardWidget(object):
_registry = []
@classmethod
def get_all(cls):
return cls._registry
def __init__(self, label, func=None, icon=None, link=None, queryset=None, statistic_slug=None):
self.label = label
self.icon = icon
self.link = link
self.queryset = queryset
self.func = func
self.statistic_slug = statistic_slug
self.__class__._registry.append(self)
@python_2_unicode_compatible
class ModelAttribute(object):
__registry = {}
@classmethod
def get_for(cls, model, type_names=None):
result = []
try:
for type_name, attributes in cls.__registry[model].iteritems():
if not type_names or type_name in type_names:
result.extend(attributes)
return result
except IndexError:
# We were passed a model instance, try again using the model of
# the instance
# If we are already in the model class, exit with an error
if model.__class__ == models.base.ModelBase:
raise
return cls.get_for[type(model)]
@classmethod
def get_choices_for(cls, model, type_names=None):
return [
(
attribute.name, attribute
) for attribute in cls.get_for(model, type_names)
]
@classmethod
def help_text_for(cls, model, type_names=None):
result = []
for count, attribute in enumerate(cls.get_for(model, type_names), 1):
result.append(
'{}) {}'.format(
count, force_text(attribute.get_display(show_name=True))
)
)
return ' '.join(
[ugettext('Available attributes: \n'), ', \n'.join(result)]
)
def get_display(self, show_name=False):
if self.description:
return '{} - {}'.format(
self.name if show_name else self.label, self.description
)
else:
return force_text(self.name if show_name else self.label)
def __str__(self):
return self.get_display()
def __init__(self, model, name, label=None, description=None, type_name=None):
self.model = model
self.label = label
self.name = name
self.description = description
for field in model._meta.fields:
if field.name == name:
self.label = field.verbose_name
self.description = field.help_text
self.__registry.setdefault(model, {})
if isinstance(type_name, list):
for single_type in type_name:
self.__registry[model].setdefault(single_type, [])
self.__registry[model][single_type].append(self)
else:
self.__registry[model].setdefault(type_name, [])
self.__registry[model][type_name].append(self)
class MissingItem(object):
_registry = []
@classmethod
def get_all(cls):
return cls._registry
def __init__(self, label, condition, description, view):
self.label = label
self.condition = condition
self.description = description
self.view = view
self.__class__._registry.append(self)
@python_2_unicode_compatible
class Filter(object):
_registry = {}
@classmethod
def get(cls, slug):
return cls._registry[slug]
@classmethod
def all(cls):
return cls._registry
def __init__(self, label, slug, filter_kwargs, model, object_permission=None, hide_links=False):
self.label = label
self.slug = slug
self.filter_kwargs = filter_kwargs
self.model = model
self.object_permission = object_permission
self.hide_links = hide_links
self.__class__._registry[self.slug] = self
def __str__(self):
return force_text(self.label)
def get_queryset(self, user):
AccessControlList = apps.get_model(
app_label='acls', model_name='AccessControlList'
)
queryset = self.model.objects.all()
for kwargs in self.filter_kwargs:
queryset = queryset.filter(**kwargs)
queryset = queryset.distinct()
if self.object_permission:
return AccessControlList.objects.filter_by_access(
self.object_permission, user, queryset=queryset
)
else:
return queryset
class Package(object):
_registry = []
@classmethod
def get_all(cls):
return cls._registry
def __init__(self, label, license_text):
self.label = label
self.license_text = license_text
self.__class__._registry.append(self)
class PropertyHelper(object):
"""
Makes adding fields using __class__.add_to_class easier.
Each subclass must implement the `constructor` and the `get_result`
method.
"""
@staticmethod
@property
def constructor(source_object):
return PropertyHelper(source_object)
def __init__(self, instance):
self.instance = instance
def __getattr__(self, name):
return self.get_result(name=name)
def get_result(self, name):
"""
The method that produces the actual result. Must be implemented
by each subclass.
"""
raise NotImplementedError
| mayan/apps/common/classes.py | 7,733 | Makes adding fields using __class__.add_to_class easier.
Each subclass must implement the `constructor` and the `get_result`
method.
The method that produces the actual result. Must be implemented
by each subclass.
Returns a list of widgets sorted by their 'order'.
If two or more widgets have the same 'order', sort by label.
We were passed a model instance, try again using the model of the instance If we are already in the model class, exit with an error | 460 | en | 0.855159 |
# -*- coding: utf-8 -*-
#
# Copyright 2019 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# DO NOT EDIT! This is a generated sample ("Request", "speech_transcribe_multichannel")
# To install the latest published package dependency, execute the following:
# pip install google-cloud-speech
# sample-metadata
# title: Multi-Channel Audio Transcription (Local File)
# description: Transcribe a short audio file with multiple channels
# usage: python3 samples/v1/speech_transcribe_multichannel.py [--local_file_path "resources/multi.wav"]
# [START speech_transcribe_multichannel]
from google.cloud import speech_v1
import io
def sample_recognize(local_file_path):
"""
Transcribe a short audio file with multiple channels
Args:
local_file_path Path to local audio file, e.g. /path/audio.wav
"""
client = speech_v1.SpeechClient()
# local_file_path = 'resources/multi.wav'
# The number of channels in the input audio file (optional)
audio_channel_count = 2
# When set to true, each audio channel will be recognized separately.
# The recognition result will contain a channel_tag field to state which
# channel that result belongs to
enable_separate_recognition_per_channel = True
# The language of the supplied audio
language_code = "en-US"
config = {
"audio_channel_count": audio_channel_count,
"enable_separate_recognition_per_channel": enable_separate_recognition_per_channel,
"language_code": language_code,
}
with io.open(local_file_path, "rb") as f:
content = f.read()
audio = {"content": content}
response = client.recognize(config, audio)
for result in response.results:
# channel_tag to recognize which audio channel this result is for
print(u"Channel tag: {}".format(result.channel_tag))
# First alternative is the most probable result
alternative = result.alternatives[0]
print(u"Transcript: {}".format(alternative.transcript))
# [END speech_transcribe_multichannel]
def main():
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("--local_file_path", type=str, default="resources/multi.wav")
args = parser.parse_args()
sample_recognize(args.local_file_path)
if __name__ == "__main__":
main()
| speech/samples/v1/speech_transcribe_multichannel.py | 2,839 | Transcribe a short audio file with multiple channels
Args:
local_file_path Path to local audio file, e.g. /path/audio.wav
-*- coding: utf-8 -*- Copyright 2019 Google LLC Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at https://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. DO NOT EDIT! This is a generated sample ("Request", "speech_transcribe_multichannel") To install the latest published package dependency, execute the following: pip install google-cloud-speech sample-metadata title: Multi-Channel Audio Transcription (Local File) description: Transcribe a short audio file with multiple channels usage: python3 samples/v1/speech_transcribe_multichannel.py [--local_file_path "resources/multi.wav"] [START speech_transcribe_multichannel] local_file_path = 'resources/multi.wav' The number of channels in the input audio file (optional) When set to true, each audio channel will be recognized separately. The recognition result will contain a channel_tag field to state which channel that result belongs to The language of the supplied audio channel_tag to recognize which audio channel this result is for First alternative is the most probable result [END speech_transcribe_multichannel] | 1,626 | en | 0.830369 |
from hydroDL import pathSMAP, master
import os
from hydroDL.data import dbCsv
# train for each cont
contLst = [
'Africa',
'Asia',
'Australia',
'Europe',
'NorthAmerica',
'SouthAmerica',
]
subsetLst = ['Globalv4f1_' + x for x in contLst]
subsetLst.append('Globalv4f1')
outLst = [x + '_v4f1_y1' for x in contLst]
outLst.append('Global_v4f1_y1')
caseLst = ['Forcing', 'Soilm']
cid = 0
for k in range(len(subsetLst)):
for case in caseLst:
if case == 'Forcing':
varLst = dbCsv.varForcingGlobal
else:
varLst = dbCsv.varSoilmGlobal
optData = master.default.update(
master.default.optDataSMAP,
rootDB=pathSMAP['DB_L3_Global'],
subset=subsetLst[k],
tRange=[20150401, 20160401],
varT=varLst)
optModel = master.default.optLstm
optLoss = master.default.optLossSigma
optTrain = master.default.optTrainSMAP
out = os.path.join(pathSMAP['Out_L3_Global'], outLst[k] + '_' + case)
masterDict = master.wrapMaster(out, optData, optModel, optLoss,
optTrain)
master.runTrain(masterDict, cudaID=cid % 3, screen=outLst[k])
cid = cid + 1
# master.train(masterDict)
# some of them failed and rerun
# master.runTrain(
# r'/mnt/sdb/rnnSMAP/Model_SMAPgrid/L3_Global/Africa_v4f1_y1_Forcing/',
# cudaID=1,
# screen='Africa_v4f1_y1_Forcing')
# master.runTrain(
# r'/mnt/sdb/rnnSMAP/Model_SMAPgrid/L3_Global/Asia_v4f1_y1_Soilm/',
# cudaID=0,
# screen='Asia_v4f1_y1_Soilm')
# master.runTrain(
# r'/mnt/sdb/rnnSMAP/Model_SMAPgrid/L3_Global/NorthAmerica_v4f1_y1_Soilm/',
# cudaID=1,
# screen='NorthAmerica_v4f1_y1_Soilm')
# master.runTrain(
# r'/mnt/sdb/rnnSMAP/Model_SMAPgrid/L3_Global/Global_v4f1_y1_Forcing/',
# cudaID=2,
# screen='Global_v4f1_y1_Forcing')
| app/global/train_cont.py | 1,915 | train for each cont master.train(masterDict) some of them failed and rerun master.runTrain( r'/mnt/sdb/rnnSMAP/Model_SMAPgrid/L3_Global/Africa_v4f1_y1_Forcing/', cudaID=1, screen='Africa_v4f1_y1_Forcing') master.runTrain( r'/mnt/sdb/rnnSMAP/Model_SMAPgrid/L3_Global/Asia_v4f1_y1_Soilm/', cudaID=0, screen='Asia_v4f1_y1_Soilm') master.runTrain( r'/mnt/sdb/rnnSMAP/Model_SMAPgrid/L3_Global/NorthAmerica_v4f1_y1_Soilm/', cudaID=1, screen='NorthAmerica_v4f1_y1_Soilm') master.runTrain( r'/mnt/sdb/rnnSMAP/Model_SMAPgrid/L3_Global/Global_v4f1_y1_Forcing/', cudaID=2, screen='Global_v4f1_y1_Forcing') | 642 | en | 0.554824 |
# coding: utf-8
import re
import six
from huaweicloudsdkcore.utils.http_utils import sanitize_for_serialization
class ShowSecurityGroupRequest:
"""
Attributes:
openapi_types (dict): The key is attribute name
and the value is attribute type.
attribute_map (dict): The key is attribute name
and the value is json key in definition.
"""
sensitive_list = []
openapi_types = {
'security_group_id': 'str'
}
attribute_map = {
'security_group_id': 'security_group_id'
}
def __init__(self, security_group_id=None):
"""ShowSecurityGroupRequest - a model defined in huaweicloud sdk"""
self._security_group_id = None
self.discriminator = None
self.security_group_id = security_group_id
@property
def security_group_id(self):
"""Gets the security_group_id of this ShowSecurityGroupRequest.
安全组资源ID
:return: The security_group_id of this ShowSecurityGroupRequest.
:rtype: str
"""
return self._security_group_id
@security_group_id.setter
def security_group_id(self, security_group_id):
"""Sets the security_group_id of this ShowSecurityGroupRequest.
安全组资源ID
:param security_group_id: The security_group_id of this ShowSecurityGroupRequest.
:type: str
"""
self._security_group_id = security_group_id
def to_dict(self):
"""Returns the model properties as a dict"""
result = {}
for attr, _ in six.iteritems(self.openapi_types):
value = getattr(self, attr)
if isinstance(value, list):
result[attr] = list(map(
lambda x: x.to_dict() if hasattr(x, "to_dict") else x,
value
))
elif hasattr(value, "to_dict"):
result[attr] = value.to_dict()
elif isinstance(value, dict):
result[attr] = dict(map(
lambda item: (item[0], item[1].to_dict())
if hasattr(item[1], "to_dict") else item,
value.items()
))
else:
if attr in self.sensitive_list:
result[attr] = "****"
else:
result[attr] = value
return result
def to_str(self):
"""Returns the string representation of the model"""
import simplejson as json
if six.PY2:
import sys
reload(sys)
sys.setdefaultencoding("utf-8")
return json.dumps(sanitize_for_serialization(self), ensure_ascii=False)
def __repr__(self):
"""For `print`"""
return self.to_str()
def __eq__(self, other):
"""Returns true if both objects are equal"""
if not isinstance(other, ShowSecurityGroupRequest):
return False
return self.__dict__ == other.__dict__
def __ne__(self, other):
"""Returns true if both objects are not equal"""
return not self == other
| huaweicloud-sdk-vpc/huaweicloudsdkvpc/v3/model/show_security_group_request.py | 3,173 | Attributes:
openapi_types (dict): The key is attribute name
and the value is attribute type.
attribute_map (dict): The key is attribute name
and the value is json key in definition.
Returns true if both objects are equal
ShowSecurityGroupRequest - a model defined in huaweicloud sdk
Returns true if both objects are not equal
For `print`
Gets the security_group_id of this ShowSecurityGroupRequest.
安全组资源ID
:return: The security_group_id of this ShowSecurityGroupRequest.
:rtype: str
Sets the security_group_id of this ShowSecurityGroupRequest.
安全组资源ID
:param security_group_id: The security_group_id of this ShowSecurityGroupRequest.
:type: str
Returns the model properties as a dict
Returns the string representation of the model
coding: utf-8 | 803 | en | 0.669299 |
from lark import Lark, Transformer, v_args
from lark.visitors import Interpreter, visit_children_decor
p = Lark.open("rules.lark", parser="lalr", rel_to=__file__)
code = """
// Firrst win in my book
b = 4;
a = b*2;
print a+1
x = 7;
p = [1, 2, 3, 4]
print p
"""
tree = p.parse(code)
@v_args(inline=True)
class MyEval(Transformer):
from operator import add, mul, neg, sub
from operator import truediv as div
number = float
def __init__(self, ns):
self.ns = ns
def var(self, name):
return self.ns[name]
# def num_list(self, value):
# print(value)
def eval_expr(tree, ns):
return MyEval(ns).transform(tree)
@v_args(inline=True)
class MyInterp(Interpreter):
def __init__(self):
self.namespace = {}
def assign(self, var, expr):
self.namespace[var] = eval_expr(expr, self.namespace)
def print_statement(self, expr):
# print(expr)
res = eval_expr(expr, self.namespace)
print(res)
print(tree.pretty())
# MyInterp().visit(tree)
| tests/cmdexpr/ruler.py | 1,039 | def num_list(self, value): print(value) print(expr) MyInterp().visit(tree) | 78 | en | 0.12512 |
# coding: utf-8
# -----------------------------------------------------------------------------------
# <copyright company="Aspose" file="error_details.py">
# Copyright (c) 2020 Aspose.Words for Cloud
# </copyright>
# <summary>
# 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.
# </summary>
# -----------------------------------------------------------------------------------
import pprint
import re # noqa: F401
import six
import json
class ErrorDetails(object):
"""The error details.
"""
"""
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 = {
'error_date_time': 'datetime',
'request_id': 'str'
}
attribute_map = {
'error_date_time': 'ErrorDateTime',
'request_id': 'RequestId'
}
def __init__(self, error_date_time=None, request_id=None): # noqa: E501
"""ErrorDetails - a model defined in Swagger""" # noqa: E501
self._error_date_time = None
self._request_id = None
self.discriminator = None
if error_date_time is not None:
self.error_date_time = error_date_time
if request_id is not None:
self.request_id = request_id
@property
def error_date_time(self):
"""Gets the error_date_time of this ErrorDetails. # noqa: E501
Error datetime. # noqa: E501
:return: The error_date_time of this ErrorDetails. # noqa: E501
:rtype: datetime
"""
return self._error_date_time
@error_date_time.setter
def error_date_time(self, error_date_time):
"""Sets the error_date_time of this ErrorDetails.
Error datetime. # noqa: E501
:param error_date_time: The error_date_time of this ErrorDetails. # noqa: E501
:type: datetime
"""
self._error_date_time = error_date_time
@property
def request_id(self):
"""Gets the request_id of this ErrorDetails. # noqa: E501
The request id. # noqa: E501
:return: The request_id of this ErrorDetails. # noqa: E501
:rtype: str
"""
return self._request_id
@request_id.setter
def request_id(self, request_id):
"""Sets the request_id of this ErrorDetails.
The request id. # noqa: E501
:param request_id: The request_id of this ErrorDetails. # noqa: E501
:type: str
"""
self._request_id = request_id
def to_dict(self):
"""Returns the model properties as a dict"""
result = {}
for attr, _ in six.iteritems(self.swagger_types):
value = getattr(self, attr)
if isinstance(value, list):
result[attr] = list(map(
lambda x: x.to_dict() if hasattr(x, "to_dict") else x,
value
))
elif hasattr(value, "to_dict"):
result[attr] = value.to_dict()
elif isinstance(value, dict):
result[attr] = dict(map(
lambda item: (item[0], item[1].to_dict())
if hasattr(item[1], "to_dict") else item,
value.items()
))
else:
result[attr] = value
return result
def to_json(self):
"""Returns the model properties as a dict"""
result = {}
for attr, _ in six.iteritems(self.swagger_types):
value = getattr(self, attr)
if isinstance(value, list):
result[self.attribute_map[attr]] = list(map(
lambda x: x.to_dict() if hasattr(x, "to_dict") else x,
value
))
elif hasattr(value, "to_dict"):
result[self.attribute_map[attr]] = value.to_dict()
elif isinstance(value, dict):
result[self.attribute_map[attr]] = dict(map(
lambda item: (item[0], item[1].to_dict())
if hasattr(item[1], "to_dict") else item,
value.items()
))
else:
result[self.attribute_map[attr]] = value
return json.dumps(result)
def to_str(self):
"""Returns the string representation of the model"""
return pprint.pformat(self.to_dict())
def __repr__(self):
"""For `print` and `pprint`"""
return self.to_str()
def __eq__(self, other):
"""Returns true if both objects are equal"""
if not isinstance(other, ErrorDetails):
return False
return self.__dict__ == other.__dict__
def __ne__(self, other):
"""Returns true if both objects are not equal"""
return not self == other | asposewordscloud/models/error_details.py | 5,944 | The error details.
Returns true if both objects are equal
ErrorDetails - a model defined in Swagger
Returns true if both objects are not equal
For `print` and `pprint`
Gets the error_date_time of this ErrorDetails. # noqa: E501
Error datetime. # noqa: E501
:return: The error_date_time of this ErrorDetails. # noqa: E501
:rtype: datetime
Sets the error_date_time of this ErrorDetails.
Error datetime. # noqa: E501
:param error_date_time: The error_date_time of this ErrorDetails. # noqa: E501
:type: datetime
Gets the request_id of this ErrorDetails. # noqa: E501
The request id. # noqa: E501
:return: The request_id of this ErrorDetails. # noqa: E501
:rtype: str
Sets the request_id of this ErrorDetails.
The request id. # noqa: E501
:param request_id: The request_id of this ErrorDetails. # noqa: E501
:type: str
Returns the model properties as a dict
Returns the model properties as a dict
Returns the string representation of the model
coding: utf-8 ----------------------------------------------------------------------------------- <copyright company="Aspose" file="error_details.py"> Copyright (c) 2020 Aspose.Words for Cloud </copyright> <summary> 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. </summary> ----------------------------------------------------------------------------------- noqa: F401 noqa: E501 noqa: E501 | 2,347 | en | 0.701694 |
import datetime
from flask_restplus import Namespace, Resource
from flask_login import login_required, current_user
from flask import request
from ..util import query_util, coco_util, profile
from config import Config
from database import (
ImageModel,
CategoryModel,
AnnotationModel,
SessionEvent
)
api = Namespace('annotator', description='Annotator related operations')
@api.route('/data')
class AnnotatorData(Resource):
@profile
@login_required
def post(self):
"""
Called when saving data from the annotator client
"""
data = request.get_json(force=True)
image = data.get('image')
dataset = data.get('dataset')
image_id = image.get('id')
image_model = ImageModel.objects(id=image_id).first()
if image_model is None:
return {'success': False, 'message': 'Image does not exist'}, 400
# Check if current user can access dataset
db_dataset = current_user.datasets.filter(id=image_model.dataset_id).first()
if dataset is None:
return {'success': False, 'message': 'Could not find associated dataset'}
db_dataset.update(annotate_url=dataset.get('annotate_url', ''))
categories = CategoryModel.objects.all()
annotations = AnnotationModel.objects(image_id=image_id)
current_user.update(preferences=data.get('user', {}))
annotated = False
# Iterate every category passed in the data
for category in data.get('categories', []):
category_id = category.get('id')
# Find corresponding category object in the database
db_category = categories.filter(id=category_id).first()
if db_category is None:
continue
category_update = {'color': category.get('color')}
if current_user.can_edit(db_category):
category_update['keypoint_edges'] = category.get('keypoint_edges', [])
category_update['keypoint_labels'] = category.get('keypoint_labels', [])
db_category.update(**category_update)
# Iterate every annotation from the data annotations
for annotation in category.get('annotations', []):
# Find corresponding annotation object in database
annotation_id = annotation.get('id')
db_annotation = annotations.filter(id=annotation_id).first()
if db_annotation is None:
continue
# Paperjs objects are complex, so they will not always be passed. Therefor we update
# the annotation twice, checking if the paperjs exists.
# Update annotation in database
sessions = []
total_time = 0
for session in annotation.get('sessions', []):
date = datetime.datetime.fromtimestamp(int(session.get('start')) / 1e3)
model = SessionEvent(
user=current_user.username,
created_at=date,
milliseconds=session.get('milliseconds'),
tools_used=session.get('tools')
)
total_time += session.get('milliseconds')
sessions.append(model)
db_annotation.update(
add_to_set__events=sessions,
inc__milliseconds=total_time,
set__isbbox=annotation.get('isbbox', False),
set__keypoints=annotation.get('keypoints', []),
set__metadata=annotation.get('metadata'),
set__color=annotation.get('color')
)
paperjs_object = annotation.get('compoundPath', [])
# Update paperjs if it exists
if len(paperjs_object) == 2:
width = db_annotation.width
height = db_annotation.height
# Generate coco formatted segmentation data
segmentation, area, bbox = coco_util.\
paperjs_to_coco(width, height, paperjs_object)
db_annotation.update(
set__segmentation=segmentation,
set__area=area,
set__isbbox=annotation.get('isbbox', False),
set__bbox=bbox,
set__paper_object=paperjs_object,
)
if area > 0:
annotated = True
image_model.update(
set__metadata=image.get('metadata', {}),
set__annotated=annotated,
set__category_ids=image.get('category_ids', []),
set__regenerate_thumbnail=True,
set__num_annotations=annotations\
.filter(deleted=False, area__gt=0).count()
)
return {"success": True}
@api.route('/data/<int:image_id>')
class AnnotatorId(Resource):
@profile
@login_required
def get(self, image_id):
""" Called when loading from the annotator client """
image = ImageModel.objects(id=image_id)\
.exclude('events').first()
if image is None:
return {'success': False, 'message': 'Could not load image'}, 400
dataset = current_user.datasets.filter(id=image.dataset_id).first()
if dataset is None:
return {'success': False, 'message': 'Could not find associated dataset'}, 400
categories = CategoryModel.objects(deleted=False)\
.in_bulk(dataset.categories).items()
# Get next and previous image
images = ImageModel.objects(dataset_id=dataset.id, deleted=False)
pre = images.filter(file_name__lt=image.file_name).order_by('-file_name').first()
nex = images.filter(file_name__gt=image.file_name).order_by('file_name').first()
preferences = {}
if not Config.LOGIN_DISABLED:
preferences = current_user.preferences
# Generate data about the image to return to client
data = {
'image': query_util.fix_ids(image),
'categories': [],
'dataset': query_util.fix_ids(dataset),
'preferences': preferences,
'permissions': {
'dataset': dataset.permissions(current_user),
'image': image.permissions(current_user)
}
}
data['image']['previous'] = pre.id if pre else None
data['image']['next'] = nex.id if nex else None
for category in categories:
category = query_util.fix_ids(category[1])
category_id = category.get('id')
annotations = AnnotationModel.objects(image_id=image_id, category_id=category_id, deleted=False)\
.exclude('events').all()
category['show'] = True
category['visualize'] = False
category['annotations'] = [] if annotations is None else query_util.fix_ids(annotations)
data.get('categories').append(category)
return data
| coco-annotator/backend/webserver/api/annotator.py | 7,195 | Called when loading from the annotator client
Called when saving data from the annotator client
Check if current user can access dataset Iterate every category passed in the data Find corresponding category object in the database Iterate every annotation from the data annotations Find corresponding annotation object in database Paperjs objects are complex, so they will not always be passed. Therefor we update the annotation twice, checking if the paperjs exists. Update annotation in database Update paperjs if it exists Generate coco formatted segmentation data Get next and previous image Generate data about the image to return to client | 647 | en | 0.74844 |
# coding: utf-8
# Copyright (c) 2016, 2022, Oracle and/or its affiliates. All rights reserved.
# This software is dual-licensed to you under the Universal Permissive License (UPL) 1.0 as shown at https://oss.oracle.com/licenses/upl or Apache License 2.0 as shown at http://www.apache.org/licenses/LICENSE-2.0. You may choose either license.
from .update_connection_details import UpdateConnectionDetails
from oci.util import formatted_flat_dict, NONE_SENTINEL, value_allowed_none_or_none_sentinel # noqa: F401
from oci.decorators import init_model_state_from_kwargs
@init_model_state_from_kwargs
class UpdateConnectionFromAmazonS3(UpdateConnectionDetails):
"""
The details to update an Amazon s3 connection.
"""
def __init__(self, **kwargs):
"""
Initializes a new UpdateConnectionFromAmazonS3 object with values from keyword arguments. The default value of the :py:attr:`~oci.data_integration.models.UpdateConnectionFromAmazonS3.model_type` attribute
of this class is ``AMAZON_S3_CONNECTION`` and it should not be changed.
The following keyword arguments are supported (corresponding to the getters/setters of this class):
:param model_type:
The value to assign to the model_type property of this UpdateConnectionFromAmazonS3.
Allowed values for this property are: "ORACLE_ADWC_CONNECTION", "ORACLE_ATP_CONNECTION", "ORACLE_OBJECT_STORAGE_CONNECTION", "ORACLEDB_CONNECTION", "MYSQL_CONNECTION", "GENERIC_JDBC_CONNECTION", "BICC_CONNECTION", "AMAZON_S3_CONNECTION", "BIP_CONNECTION"
:type model_type: str
:param key:
The value to assign to the key property of this UpdateConnectionFromAmazonS3.
:type key: str
:param model_version:
The value to assign to the model_version property of this UpdateConnectionFromAmazonS3.
:type model_version: str
:param parent_ref:
The value to assign to the parent_ref property of this UpdateConnectionFromAmazonS3.
:type parent_ref: oci.data_integration.models.ParentReference
:param name:
The value to assign to the name property of this UpdateConnectionFromAmazonS3.
:type name: str
:param description:
The value to assign to the description property of this UpdateConnectionFromAmazonS3.
:type description: str
:param object_status:
The value to assign to the object_status property of this UpdateConnectionFromAmazonS3.
:type object_status: int
:param object_version:
The value to assign to the object_version property of this UpdateConnectionFromAmazonS3.
:type object_version: int
:param identifier:
The value to assign to the identifier property of this UpdateConnectionFromAmazonS3.
:type identifier: str
:param connection_properties:
The value to assign to the connection_properties property of this UpdateConnectionFromAmazonS3.
:type connection_properties: list[oci.data_integration.models.ConnectionProperty]
:param registry_metadata:
The value to assign to the registry_metadata property of this UpdateConnectionFromAmazonS3.
:type registry_metadata: oci.data_integration.models.RegistryMetadata
:param access_key:
The value to assign to the access_key property of this UpdateConnectionFromAmazonS3.
:type access_key: oci.data_integration.models.SensitiveAttribute
:param secret_key:
The value to assign to the secret_key property of this UpdateConnectionFromAmazonS3.
:type secret_key: oci.data_integration.models.SensitiveAttribute
"""
self.swagger_types = {
'model_type': 'str',
'key': 'str',
'model_version': 'str',
'parent_ref': 'ParentReference',
'name': 'str',
'description': 'str',
'object_status': 'int',
'object_version': 'int',
'identifier': 'str',
'connection_properties': 'list[ConnectionProperty]',
'registry_metadata': 'RegistryMetadata',
'access_key': 'SensitiveAttribute',
'secret_key': 'SensitiveAttribute'
}
self.attribute_map = {
'model_type': 'modelType',
'key': 'key',
'model_version': 'modelVersion',
'parent_ref': 'parentRef',
'name': 'name',
'description': 'description',
'object_status': 'objectStatus',
'object_version': 'objectVersion',
'identifier': 'identifier',
'connection_properties': 'connectionProperties',
'registry_metadata': 'registryMetadata',
'access_key': 'accessKey',
'secret_key': 'secretKey'
}
self._model_type = None
self._key = None
self._model_version = None
self._parent_ref = None
self._name = None
self._description = None
self._object_status = None
self._object_version = None
self._identifier = None
self._connection_properties = None
self._registry_metadata = None
self._access_key = None
self._secret_key = None
self._model_type = 'AMAZON_S3_CONNECTION'
@property
def access_key(self):
"""
Gets the access_key of this UpdateConnectionFromAmazonS3.
:return: The access_key of this UpdateConnectionFromAmazonS3.
:rtype: oci.data_integration.models.SensitiveAttribute
"""
return self._access_key
@access_key.setter
def access_key(self, access_key):
"""
Sets the access_key of this UpdateConnectionFromAmazonS3.
:param access_key: The access_key of this UpdateConnectionFromAmazonS3.
:type: oci.data_integration.models.SensitiveAttribute
"""
self._access_key = access_key
@property
def secret_key(self):
"""
Gets the secret_key of this UpdateConnectionFromAmazonS3.
:return: The secret_key of this UpdateConnectionFromAmazonS3.
:rtype: oci.data_integration.models.SensitiveAttribute
"""
return self._secret_key
@secret_key.setter
def secret_key(self, secret_key):
"""
Sets the secret_key of this UpdateConnectionFromAmazonS3.
:param secret_key: The secret_key of this UpdateConnectionFromAmazonS3.
:type: oci.data_integration.models.SensitiveAttribute
"""
self._secret_key = secret_key
def __repr__(self):
return formatted_flat_dict(self)
def __eq__(self, other):
if other is None:
return False
return self.__dict__ == other.__dict__
def __ne__(self, other):
return not self == other
| src/oci/data_integration/models/update_connection_from_amazon_s3.py | 6,882 | The details to update an Amazon s3 connection.
Initializes a new UpdateConnectionFromAmazonS3 object with values from keyword arguments. The default value of the :py:attr:`~oci.data_integration.models.UpdateConnectionFromAmazonS3.model_type` attribute
of this class is ``AMAZON_S3_CONNECTION`` and it should not be changed.
The following keyword arguments are supported (corresponding to the getters/setters of this class):
:param model_type:
The value to assign to the model_type property of this UpdateConnectionFromAmazonS3.
Allowed values for this property are: "ORACLE_ADWC_CONNECTION", "ORACLE_ATP_CONNECTION", "ORACLE_OBJECT_STORAGE_CONNECTION", "ORACLEDB_CONNECTION", "MYSQL_CONNECTION", "GENERIC_JDBC_CONNECTION", "BICC_CONNECTION", "AMAZON_S3_CONNECTION", "BIP_CONNECTION"
:type model_type: str
:param key:
The value to assign to the key property of this UpdateConnectionFromAmazonS3.
:type key: str
:param model_version:
The value to assign to the model_version property of this UpdateConnectionFromAmazonS3.
:type model_version: str
:param parent_ref:
The value to assign to the parent_ref property of this UpdateConnectionFromAmazonS3.
:type parent_ref: oci.data_integration.models.ParentReference
:param name:
The value to assign to the name property of this UpdateConnectionFromAmazonS3.
:type name: str
:param description:
The value to assign to the description property of this UpdateConnectionFromAmazonS3.
:type description: str
:param object_status:
The value to assign to the object_status property of this UpdateConnectionFromAmazonS3.
:type object_status: int
:param object_version:
The value to assign to the object_version property of this UpdateConnectionFromAmazonS3.
:type object_version: int
:param identifier:
The value to assign to the identifier property of this UpdateConnectionFromAmazonS3.
:type identifier: str
:param connection_properties:
The value to assign to the connection_properties property of this UpdateConnectionFromAmazonS3.
:type connection_properties: list[oci.data_integration.models.ConnectionProperty]
:param registry_metadata:
The value to assign to the registry_metadata property of this UpdateConnectionFromAmazonS3.
:type registry_metadata: oci.data_integration.models.RegistryMetadata
:param access_key:
The value to assign to the access_key property of this UpdateConnectionFromAmazonS3.
:type access_key: oci.data_integration.models.SensitiveAttribute
:param secret_key:
The value to assign to the secret_key property of this UpdateConnectionFromAmazonS3.
:type secret_key: oci.data_integration.models.SensitiveAttribute
Gets the access_key of this UpdateConnectionFromAmazonS3.
:return: The access_key of this UpdateConnectionFromAmazonS3.
:rtype: oci.data_integration.models.SensitiveAttribute
Sets the access_key of this UpdateConnectionFromAmazonS3.
:param access_key: The access_key of this UpdateConnectionFromAmazonS3.
:type: oci.data_integration.models.SensitiveAttribute
Gets the secret_key of this UpdateConnectionFromAmazonS3.
:return: The secret_key of this UpdateConnectionFromAmazonS3.
:rtype: oci.data_integration.models.SensitiveAttribute
Sets the secret_key of this UpdateConnectionFromAmazonS3.
:param secret_key: The secret_key of this UpdateConnectionFromAmazonS3.
:type: oci.data_integration.models.SensitiveAttribute
coding: utf-8 Copyright (c) 2016, 2022, Oracle and/or its affiliates. All rights reserved. This software is dual-licensed to you under the Universal Permissive License (UPL) 1.0 as shown at https://oss.oracle.com/licenses/upl or Apache License 2.0 as shown at http://www.apache.org/licenses/LICENSE-2.0. You may choose either license. noqa: F401 | 3,720 | en | 0.568154 |
#!/usr/bin/env python
"""
<Program Name>
test_root_versioning_integration.py
<Author>
Evan Cordell.
<Started>
July 21, 2016.
<Copyright>
See LICENSE for licensing information.
<Purpose>
Test root versioning for efficient root key rotation.
"""
from __future__ import print_function
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
import os
import logging
import tempfile
import shutil
import sys
# 'unittest2' required for testing under Python < 2.7.
if sys.version_info >= (2, 7):
import unittest
else:
import unittest2 as unittest
import tuf
import tuf.log
import tuf.formats
import tuf.exceptions
import tuf.roledb
import tuf.keydb
import tuf.repository_tool as repo_tool
import securesystemslib
logger = logging.getLogger('tuf.test_root_versioning')
repo_tool.disable_console_log_messages()
class TestRepository(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.temporary_directory = tempfile.mkdtemp(dir=os.getcwd())
@classmethod
def tearDownClass(cls):
shutil.rmtree(cls.temporary_directory)
def tearDown(self):
tuf.roledb.clear_roledb()
tuf.keydb.clear_keydb()
def test_init(self):
# Test normal case.
repository = repo_tool.Repository('repository_directory/',
'metadata_directory/',
'targets_directory/')
self.assertTrue(isinstance(repository.root, repo_tool.Root))
self.assertTrue(isinstance(repository.snapshot, repo_tool.Snapshot))
self.assertTrue(isinstance(repository.timestamp, repo_tool.Timestamp))
self.assertTrue(isinstance(repository.targets, repo_tool.Targets))
# Test improperly formatted arguments.
self.assertRaises(securesystemslib.exceptions.FormatError, repo_tool.Repository, 3,
'metadata_directory/', 'targets_directory')
self.assertRaises(securesystemslib.exceptions.FormatError, repo_tool.Repository,
'repository_directory', 3, 'targets_directory')
self.assertRaises(securesystemslib.exceptions.FormatError, repo_tool.Repository,
'repository_directory', 'metadata_directory', 3)
def test_root_role_versioning(self):
# Test root role versioning
#
# 1. Import public and private keys.
# 2. Add verification keys.
# 3. Load signing keys.
# 4. Add target files.
# 5. Perform delegation.
# 6. writeall()
#
# Copy the target files from 'tuf/tests/repository_data' so that writeall()
# has target fileinfo to include in metadata.
temporary_directory = tempfile.mkdtemp(dir=self.temporary_directory)
targets_directory = os.path.join(temporary_directory, 'repository',
repo_tool.TARGETS_DIRECTORY_NAME)
original_targets_directory = os.path.join('repository_data',
'repository', 'targets')
shutil.copytree(original_targets_directory, targets_directory)
# In this case, create_new_repository() creates the 'repository/'
# sub-directory in 'temporary_directory' if it does not exist.
repository_directory = os.path.join(temporary_directory, 'repository')
metadata_directory = os.path.join(repository_directory,
repo_tool.METADATA_STAGED_DIRECTORY_NAME)
repository = repo_tool.create_new_repository(repository_directory)
# (1) Load the public and private keys of the top-level roles, and one
# delegated role.
keystore_directory = os.path.join('repository_data', 'keystore')
# Load the public keys.
root_pubkey_path = os.path.join(keystore_directory, 'root_key.pub')
targets_pubkey_path = os.path.join(keystore_directory, 'targets_key.pub')
snapshot_pubkey_path = os.path.join(keystore_directory, 'snapshot_key.pub')
timestamp_pubkey_path = os.path.join(keystore_directory, 'timestamp_key.pub')
role1_pubkey_path = os.path.join(keystore_directory, 'delegation_key.pub')
root_pubkey = repo_tool.import_rsa_publickey_from_file(root_pubkey_path)
targets_pubkey = repo_tool.import_ed25519_publickey_from_file(targets_pubkey_path)
snapshot_pubkey = \
repo_tool.import_ed25519_publickey_from_file(snapshot_pubkey_path)
timestamp_pubkey = \
repo_tool.import_ed25519_publickey_from_file(timestamp_pubkey_path)
role1_pubkey = repo_tool.import_ed25519_publickey_from_file(role1_pubkey_path)
# Load the private keys.
root_privkey_path = os.path.join(keystore_directory, 'root_key')
targets_privkey_path = os.path.join(keystore_directory, 'targets_key')
snapshot_privkey_path = os.path.join(keystore_directory, 'snapshot_key')
timestamp_privkey_path = os.path.join(keystore_directory, 'timestamp_key')
role1_privkey_path = os.path.join(keystore_directory, 'delegation_key')
root_privkey = \
repo_tool.import_rsa_privatekey_from_file(root_privkey_path, 'password')
targets_privkey = \
repo_tool.import_ed25519_privatekey_from_file(targets_privkey_path, 'password')
snapshot_privkey = \
repo_tool.import_ed25519_privatekey_from_file(snapshot_privkey_path,
'password')
timestamp_privkey = \
repo_tool.import_ed25519_privatekey_from_file(timestamp_privkey_path,
'password')
role1_privkey = \
repo_tool.import_ed25519_privatekey_from_file(role1_privkey_path,
'password')
# (2) Add top-level verification keys.
repository.root.add_verification_key(root_pubkey)
repository.targets.add_verification_key(targets_pubkey)
repository.snapshot.add_verification_key(snapshot_pubkey)
repository.timestamp.add_verification_key(timestamp_pubkey)
# (3) Load top-level signing keys.
repository.root.load_signing_key(root_privkey)
repository.targets.load_signing_key(targets_privkey)
repository.snapshot.load_signing_key(snapshot_privkey)
repository.timestamp.load_signing_key(timestamp_privkey)
# (4) Add target files.
target1 = os.path.join(targets_directory, 'file1.txt')
target2 = os.path.join(targets_directory, 'file2.txt')
target3 = os.path.join(targets_directory, 'file3.txt')
repository.targets.add_target(target1)
repository.targets.add_target(target2)
# (5) Perform delegation.
repository.targets.delegate('role1', [role1_pubkey], [target3])
repository.targets('role1').load_signing_key(role1_privkey)
# (6) Write repository.
repository.targets.compressions = ['gz']
repository.writeall()
self.assertTrue(os.path.exists(os.path.join(metadata_directory, 'root.json')))
self.assertTrue(os.path.exists(os.path.join(metadata_directory, '1.root.json')))
# Verify that the expected metadata is written.
root_filepath = os.path.join(metadata_directory, 'root.json')
root_1_filepath = os.path.join(metadata_directory, '1.root.json')
root_2_filepath = os.path.join(metadata_directory, '2.root.json')
old_root_signable = securesystemslib.util.load_json_file(root_filepath)
root_1_signable = securesystemslib.util.load_json_file(root_1_filepath)
# Make a change to the root keys
repository.root.add_verification_key(targets_pubkey)
repository.root.load_signing_key(targets_privkey)
repository.root.threshold = 2
repository.writeall()
new_root_signable = securesystemslib.util.load_json_file(root_filepath)
root_2_signable = securesystemslib.util.load_json_file(root_2_filepath)
for role_signable in [old_root_signable, new_root_signable, root_1_signable, root_2_signable]:
# Raise 'securesystemslib.exceptions.FormatError' if 'role_signable' is an
# invalid signable.
tuf.formats.check_signable_object_format(role_signable)
# Verify contents of versioned roots
self.assertEqual(old_root_signable, root_1_signable)
self.assertEqual(new_root_signable, root_2_signable)
self.assertEqual(root_1_signable['signed']['version'], 1)
self.assertEqual(root_2_signable['signed']['version'], 2)
repository.root.remove_verification_key(root_pubkey)
repository.root.unload_signing_key(root_privkey)
repository.root.threshold = 2
# Errors, not enough signing keys to satisfy old threshold
self.assertRaises(tuf.exceptions.UnsignedMetadataError, repository.writeall)
# No error, write() ignore's root's threshold and allows it to be written
# to disk partially signed.
repository.write('root')
if __name__ == '__main__':
unittest.main()
| tests/test_root_versioning_integration.py | 8,665 | <Program Name>
test_root_versioning_integration.py
<Author>
Evan Cordell.
<Started>
July 21, 2016.
<Copyright>
See LICENSE for licensing information.
<Purpose>
Test root versioning for efficient root key rotation.
!/usr/bin/env python 'unittest2' required for testing under Python < 2.7. Test normal case. Test improperly formatted arguments. Test root role versioning 1. Import public and private keys. 2. Add verification keys. 3. Load signing keys. 4. Add target files. 5. Perform delegation. 6. writeall() Copy the target files from 'tuf/tests/repository_data' so that writeall() has target fileinfo to include in metadata. In this case, create_new_repository() creates the 'repository/' sub-directory in 'temporary_directory' if it does not exist. (1) Load the public and private keys of the top-level roles, and one delegated role. Load the public keys. Load the private keys. (2) Add top-level verification keys. (3) Load top-level signing keys. (4) Add target files. (5) Perform delegation. (6) Write repository. Verify that the expected metadata is written. Make a change to the root keys Raise 'securesystemslib.exceptions.FormatError' if 'role_signable' is an invalid signable. Verify contents of versioned roots Errors, not enough signing keys to satisfy old threshold No error, write() ignore's root's threshold and allows it to be written to disk partially signed. | 1,393 | en | 0.698595 |
from datetime import datetime
from django.db import models
# Create your models here.
class JD(models.Model):
appkey = models.CharField(max_length=100,verbose_name='appkey')
secret = models.CharField(max_length=100,verbose_name='secret')
add_time = models.DateTimeField(default=datetime.now,verbose_name='添加时间')
def __str__(self):
return self.appkey
class Meta:
verbose_name = '配置'
verbose_name_plural = verbose_name
"""
1-好券商品,
2-超级大卖场,
10-9.9专区,
22-热销爆品,
24-数码家电,
25-超市,
26-母婴玩具,
27-家具日用,
28-美妆穿搭,
29-医药保健,
30-图书文具,
31-今日必推,
32-王牌好货
"""
class Category(models.Model):
CHOOSE = (
('1','导航'),
('2','九宫格'),
)
pid = models.CharField(max_length=10,verbose_name='分类id')
name = models.CharField(max_length=20,verbose_name='分类名')
sort = models.IntegerField(verbose_name='排序',default=0)
type = models.CharField(max_length=10,choices=CHOOSE,verbose_name='显示',default='1')
add_time = models.DateTimeField(default=datetime.now,verbose_name='添加时间')
def __str__(self):
return self.name
class Meta:
verbose_name = '类别'
verbose_name_plural = verbose_name
class Banner(models.Model):
title = models.CharField(max_length=100,verbose_name='活动名称')
url = models.TextField(verbose_name='跳转地址')
img = models.URLField(verbose_name='图片地址',default='')
start_time = models.DateField(default=datetime.now,verbose_name='活动开始时间')
end_time = models.DateField(default=datetime.now,verbose_name='活动结束时间')
add_time = models.DateTimeField(default=datetime.now, verbose_name='添加时间')
def __str__(self):
return self.title
class Meta:
verbose_name = '活动'
verbose_name_plural = verbose_name | apps/jd_app/models.py | 1,953 | Create your models here. | 24 | en | 0.920486 |
"""
This file imports `__all__` from the solvers directory, thus populating the solver registry.
"""
from pysperf.solvers import *
from .config import solvers
__all__ = ['solvers']
| pysperf/solver_library.py | 183 | This file imports `__all__` from the solvers directory, thus populating the solver registry. | 92 | en | 0.920715 |
# Copyright 2013-2022 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)
class Volk(CMakePackage):
"""VOLK is the Vector-Optimized Library of Kernels. It is a
library that contains kernels of hand-written SIMD code for
different mathematical operations. Since each SIMD architecture
can be very different and no compiler has yet come along to handle
vectorization properly or highly efficiently, VOLK approaches the
problem differently.
For each architecture or platform that a developer wishes to
vectorize for, a new proto-kernel is added to VOLK. At runtime,
VOLK will select the correct proto-kernel. In this way, the users
of VOLK call a kernel for performing the operation that is
platform/architecture agnostic. This allows us to write portable
SIMD code."""
homepage = "https://github.com/gnuradio/volk"
url = "https://github.com/gnuradio/volk/archive/v2.3.0.tar.gz"
maintainers = ['aweits']
version('2.3.0', sha256='f42c928f561b128acfe4adb21227e4a62a3f6ab8103592fc3233765ff326d5fc')
depends_on('python@3.4:', type=('build', 'run'))
depends_on('py-mako@0.4.2:', type=('build', 'run'))
| var/spack/repos/builtin/packages/volk/package.py | 1,301 | VOLK is the Vector-Optimized Library of Kernels. It is a
library that contains kernels of hand-written SIMD code for
different mathematical operations. Since each SIMD architecture
can be very different and no compiler has yet come along to handle
vectorization properly or highly efficiently, VOLK approaches the
problem differently.
For each architecture or platform that a developer wishes to
vectorize for, a new proto-kernel is added to VOLK. At runtime,
VOLK will select the correct proto-kernel. In this way, the users
of VOLK call a kernel for performing the operation that is
platform/architecture agnostic. This allows us to write portable
SIMD code.
Copyright 2013-2022 Lawrence Livermore National Security, LLC and other Spack Project Developers. See the top-level COPYRIGHT file for details. SPDX-License-Identifier: (Apache-2.0 OR MIT) | 852 | en | 0.903804 |
# -*- coding: utf-8 -*-
#
# 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.
"""This module is deprecated. Please use `airflow.providers.amazon.aws.operators.emr_add_steps`."""
import warnings
# pylint: disable=unused-import
from airflow.providers.amazon.aws.operators.emr_add_steps import EmrAddStepsOperator # noqa
warnings.warn(
"This module is deprecated. Please use `airflow.providers.amazon.aws.operators.emr_add_steps`.",
DeprecationWarning, stacklevel=2
)
| airflow/contrib/operators/emr_add_steps_operator.py | 1,210 | This module is deprecated. Please use `airflow.providers.amazon.aws.operators.emr_add_steps`.
-*- coding: utf-8 -*- 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. pylint: disable=unused-import noqa | 905 | en | 0.847582 |
# coding=utf-8
# Copyright 2018 The Google AI Language Team Authors,
# The HuggingFace Inc. team, and The XTREME Benchmark Authors.
# Copyright (c) 2018, NVIDIA CORPORATION. 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.
"""Fine-tuning models for NER and POS tagging."""
from __future__ import absolute_import, division, print_function
import argparse
import glob
import logging
import os
import random
from dataclasses import dataclass, field
from typing import Optional
import json
import numpy as np
import scipy
import torch
from seqeval.metrics import precision_score, recall_score, f1_score
from tensorboardX import SummaryWriter
from torch.nn import CrossEntropyLoss
from torch.utils.data import DataLoader, TensorDataset
from torch.utils.data import RandomSampler, SequentialSampler
from torch.utils.data.distributed import DistributedSampler
from tqdm import tqdm, trange
from utils_tag import convert_examples_to_features
from utils_tag import get_labels
from utils_tag import read_examples_from_file
# import lang2vec.lang2vec as l2v
from scipy.spatial import distance
from transformers import (
AdamW,
get_linear_schedule_with_warmup,
WEIGHTS_NAME,
AutoConfig,
AutoModelForTokenClassification,
AutoTokenizer,
HfArgumentParser,
MultiLingAdapterArguments,
AdapterConfig,
AdapterType,
)
#from xlm import XLMForTokenClassification
DEFAULT_LANGUAGES = {
'mr': 'hi',
'bn': 'hi',
'ta': 'ta',
'fo': 'fo',
'no': 'da',
'da': 'da',
'be': 'be',
'uk': 'uk',
'bg': 'bg'
}
logger = logging.getLogger(__name__)
def set_seed(args):
random.seed(args.seed)
np.random.seed(args.seed)
torch.manual_seed(args.seed)
logger.info(f'Seed = {args.seed}')
if args.n_gpu > 0:
torch.cuda.manual_seed_all(args.seed)
def train(args, train_dataset, model, tokenizer, labels, pad_token_label_id, lang_adapter_names, task_name, lang2id=None):
"""Train the model."""
if args.local_rank in [-1, 0]:
tb_writer = SummaryWriter()
args.train_batch_size = args.per_gpu_train_batch_size * max(1, args.n_gpu)
print(f'Local Rank = {args.local_rank}')
print(len(train_dataset))
train_sampler = RandomSampler(train_dataset) if args.local_rank == -1 else DistributedSampler(train_dataset)
train_dataloader = DataLoader(train_dataset, sampler=train_sampler, batch_size=args.train_batch_size)
if args.max_steps > 0:
t_total = args.max_steps
args.num_train_epochs = args.max_steps // (len(train_dataloader) // args.gradient_accumulation_steps) + 1
else:
t_total = len(train_dataloader) // args.gradient_accumulation_steps * args.num_train_epochs
# Prepare optimizer and schedule (linear warmup and decay)
no_decay = ["bias", "LayerNorm.weight"]
optimizer_grouped_parameters = [
{"params": [p for n, p in model.named_parameters() if not any(nd in n for nd in no_decay)],
"weight_decay": args.weight_decay},
{"params": [p for n, p in model.named_parameters() if any(nd in n for nd in no_decay)], "weight_decay": 0.0}
]
optimizer = AdamW(optimizer_grouped_parameters, lr=args.learning_rate, eps=args.adam_epsilon)
logging.info([n for (n, p) in model.named_parameters() if p.requires_grad])
scheduler = get_linear_schedule_with_warmup(optimizer, num_warmup_steps=args.warmup_steps, num_training_steps=t_total)
if args.fp16:
try:
from apex import amp
except ImportError:
raise ImportError("Please install apex from https://www.github.com/nvidia/apex to use fp16 training.")
model, optimizer = amp.initialize(model, optimizer, opt_level=args.fp16_opt_level)
# multi-gpu training (should be after apex fp16 initialization)
if args.n_gpu > 1:
model = torch.nn.DataParallel(model)
# Distributed training (should be after apex fp16 initialization)
if args.local_rank != -1:
model = torch.nn.parallel.DistributedDataParallel(model, device_ids=[args.local_rank],
output_device=args.local_rank,
find_unused_parameters=True)
# Train!
logger.info("***** Running training *****")
logger.info(" Num examples = %d", len(train_dataset))
logger.info(" Num Epochs = %d", args.num_train_epochs)
logger.info(" Instantaneous batch size per GPU = %d", args.per_gpu_train_batch_size)
logger.info(" Total train batch size (w. parallel, distributed & accumulation) = %d",
args.train_batch_size * args.gradient_accumulation_steps * (
torch.distributed.get_world_size() if args.local_rank != -1 else 1))
logger.info(" Gradient Accumulation steps = %d", args.gradient_accumulation_steps)
logger.info(" Total optimization steps = %d", t_total)
best_score = 0.0
best_checkpoint = None
patience = 0
global_step = 0
tr_loss, logging_loss = 0.0, 0.0
model.zero_grad()
train_iterator = trange(int(args.num_train_epochs), desc="Epoch", disable=args.local_rank not in [-1, 0])
set_seed(args) # Add here for reproductibility (even between python 2 and 3)
cur_epoch = 0
for _ in train_iterator:
epoch_iterator = tqdm(train_dataloader, desc="Iteration", disable=args.local_rank not in [-1, 0])
cur_epoch += 1
for step, batch in enumerate(epoch_iterator):
batch = tuple(t.to(args.device) for t in batch if t is not None)
inputs = {"input_ids": batch[0],
"attention_mask": batch[1],
"labels": batch[3]}
if args.model_type != "distilbert":
# XLM and RoBERTa don"t use segment_ids
inputs["token_type_ids"] = batch[2] if args.model_type in ["bert", "xlnet"] else None
if args.model_type == "xlm":
inputs["langs"] = batch[4]
outputs = model(**inputs)
loss = outputs[0]
if args.n_gpu > 1:
# mean() to average on multi-gpu parallel training
loss = loss.mean()
if args.gradient_accumulation_steps > 1:
loss = loss / args.gradient_accumulation_steps
if args.fp16:
with amp.scale_loss(loss, optimizer) as scaled_loss:
scaled_loss.backward()
else:
loss.backward()
tr_loss += loss.item()
if (step + 1) % args.gradient_accumulation_steps == 0:
if args.fp16:
torch.nn.utils.clip_grad_norm_(amp.master_params(optimizer), args.max_grad_norm)
else:
torch.nn.utils.clip_grad_norm_(model.parameters(), args.max_grad_norm)
scheduler.step() # Update learning rate schedule
optimizer.step()
model.zero_grad()
global_step += 1
if args.local_rank in [-1, 0] and args.logging_steps > 0 and global_step % args.logging_steps == 0:
# Log metrics
if args.local_rank == -1 and args.evaluate_during_training:
# Only evaluate on single GPU otherwise metrics may not average well
results, _ = evaluate(args, model, tokenizer, labels, pad_token_label_id, mode="dev", lang=args.train_langs, lang2id=lang2id, lang_adapter_names=lang_adapter_names, task_name=task_name)
for key, value in results.items():
tb_writer.add_scalar("eval_{}".format(key), value, global_step)
tb_writer.add_scalar("lr", scheduler.get_lr()[0], global_step)
tb_writer.add_scalar("loss", (tr_loss - logging_loss) / args.logging_steps, global_step)
logging_loss = tr_loss
if args.local_rank in [-1, 0] and args.save_steps > 0 and global_step % args.save_steps == 0:
if args.save_only_best_checkpoint:
result, _ = evaluate(args, model, tokenizer, labels, pad_token_label_id, mode="dev", prefix=global_step, lang=args.train_langs, lang2id=lang2id, lang_adapter_names=lang_adapter_names, task_name=task_name)
if result["f1"] > best_score:
logger.info("result['f1']={} > best_score={}".format(result["f1"], best_score))
best_score = result["f1"]
# Save the best model checkpoint
output_dir = os.path.join(args.output_dir, "checkpoint-best")
best_checkpoint = output_dir
if not os.path.exists(output_dir):
os.makedirs(output_dir)
# Take care of distributed/parallel training
model_to_save = model.module if hasattr(model, "module") else model
if args.do_save_adapters:
model_to_save.save_all_adapters(output_dir)
if args.do_save_adapter_fusions:
model_to_save.save_all_adapter_fusions(output_dir)
if args.do_save_full_model:
model_to_save.save_pretrained(output_dir)
torch.save(args, os.path.join(output_dir, "training_args.bin"))
logger.info("Saving the best model checkpoint to %s", output_dir)
logger.info("Reset patience to 0")
patience = 0
else:
patience += 1
logger.info("Hit patience={}".format(patience))
if args.eval_patience > 0 and patience > args.eval_patience:
logger.info("early stop! patience={}".format(patience))
epoch_iterator.close()
train_iterator.close()
if args.local_rank in [-1, 0]:
tb_writer.close()
return global_step, tr_loss / global_step
else:
# Save model checkpoint
output_dir = os.path.join(args.output_dir, "checkpoint-{}".format(global_step))
if not os.path.exists(output_dir):
os.makedirs(output_dir)
# Take care of distributed/parallel training
model_to_save = model.module if hasattr(model, "module") else model
if args.do_save_adapters:
model_to_save.save_all_adapters(output_dir)
if args.do_save_adapter_fusions:
model_to_save.save_all_adapter_fusions(output_dir)
if args.do_save_full_model:
model_to_save.save_pretrained(output_dir)
torch.save(args, os.path.join(output_dir, "training_args.bin"))
logger.info("Saving model checkpoint to %s", output_dir)
if args.max_steps > 0 and global_step > args.max_steps:
epoch_iterator.close()
break
if args.max_steps > 0 and global_step > args.max_steps:
train_iterator.close()
break
if args.local_rank in [-1, 0]:
tb_writer.close()
return global_step, tr_loss / global_step
def calc_weight_multi(args, model, batch, lang_adapter_names, task_name, adapter_weights, step=10, lang=None):
inputs = {"input_ids": batch[0],
"attention_mask": batch[1],
"return_sequence_out": True,
"labels": batch[3]}
# logger.info(f'Language Adapters are {lang_adapter_names}')
adapter_weights = [torch.FloatTensor([0.5 for _ in range(len(lang_adapter_names))]).to(args.device) for _ in range(13)]
if args.lang_to_vec:
logger.info(lang)
logger.info(lang_adapter_names)
adapter_weights = calc_l2v_weights(lang, lang_adapter_names, args.en_weight)
logger.info(adapter_weights)
for step_no in range(step):
for w in adapter_weights: w.requires_grad = True
if args.lang_to_vec and step_no == 0:
normed_adapter_weights = adapter_weights
else:
normed_adapter_weights = [torch.nn.functional.softmax(w) for w in adapter_weights]
# logger.info(f'Initial Adapter Weights = {normed_adapter_weights}')
model.set_active_adapters([lang_adapter_names, [task_name]])
inputs["adapter_names"] = [lang_adapter_names, [task_name]]
inputs["adapter_weights"] = normed_adapter_weights
outputs = model(**inputs)
loss, logits, orig_sequence_output = outputs[:3]
kept_logits = outputs[-1]
entropy = torch.nn.functional.softmax(kept_logits, dim=1)*torch.nn.functional.log_softmax(kept_logits, dim=1)
entropy = -entropy.sum() / kept_logits.size(0)
grads = torch.autograd.grad(entropy, adapter_weights)
#print(adapter_weights)
#print(grads)
#print(grads)
for i, w in enumerate(adapter_weights):
adapter_weights[i] = adapter_weights[i].data - 10*grads[i].data
normed_adapter_weights = [torch.nn.functional.softmax(w) for w in adapter_weights]
#print(normed_adapter_weights)
# logger.info(f'Final Adapter Weights = {normed_adapter_weights}')
return normed_adapter_weights
def jaccard_sim(vec1, vec2):
intersection = 0
union = 0
for i in range(len(vec1)):
if vec1[i] == '--' or vec2[i] == '--':
continue
if vec1[i] == 1 or vec2[i] == 1:
union += 1
if vec1[i] == 1 and vec2[i] == 1:
intersection += 1
return intersection/union
def get_sim(lang1, lang2):
features = l2v.get_features(f'{DEFAULT_LANGUAGES[lang1]} {lang2}', 'learned')
similarity = 1 - distance.cosine(features[DEFAULT_LANGUAGES[lang1]], features[lang2])
return similarity
def get_syntax_sim(lang1, lang2):
features = l2v.get_features(f'{lang1} {lang2}', "syntax_wals|syntax_sswl|syntax_ethnologue")
similarity = jaccard_sim(features[lang1], features[lang2])
return similarity
def calc_l2v_weights(args, lang, lang_adapter_names):
adapter_weight = []
for adapter_lang in lang_adapter_names:
if args.en_weight is not None and adapter_lang == 'en':
continue
if args.lang_to_vec == 'learned':
adapter_weight.append(get_sim(lang, adapter_lang))
elif args.lang_to_vec == 'syntax':
adapter_weight.append(get_syntax_sim(lang, adapter_lang))
else:
logger.info('INVALID FEATURE TYPE')
exit()
logger.info(adapter_weight)
adapter_weight = torch.FloatTensor(adapter_weight)
adapter_weight = torch.nn.functional.softmax(adapter_weight/args.temperature).tolist()
if args.en_weight is not None:
adapter_weight = [(1 - args.en_weight)*aw for aw in adapter_weight]
en_index = lang_adapter_names.index('en')
adapter_weight.insert(en_index, args.en_weight)
return adapter_weight
def scaled_input(emb, batch_size=16, num_batch=1, baseline=None, start_i=None, end_i=None):
# shape of emb: (num_head, seq_len, seq_len)
if baseline is None:
baseline = torch.zeros_like(emb)
num_points = batch_size * num_batch
scale = 1.0 / num_points
if start_i is None:
step = (emb.unsqueeze(0) - baseline.unsqueeze(0)) * scale
res = torch.cat([torch.add(baseline.unsqueeze(0), step*i) for i in range(num_points)], dim=0)
return res, step[0]
else:
step = (emb - baseline) * scale
start_emb = torch.add(baseline, step*start_i)
end_emb = torch.add(baseline, step*end_i)
step_new = (end_emb.unsqueeze(0) - start_emb.unsqueeze(0)) * scale
res = torch.cat([torch.add(start_emb.unsqueeze(0), step_new*i) for i in range(num_points)], dim=0)
return res, step_new[0]
#Changed the default of calc_weight_step to 0
def evaluate(args, model, tokenizer, labels, pad_token_label_id, mode, prefix="", lang="en", lang2id=None, print_result=True, adapter_weight=None, lang_adapter_names=None, task_name=None, calc_weight_step=0):
eval_dataset = load_and_cache_examples(args, tokenizer, labels, pad_token_label_id, mode=mode, lang=lang, lang2id=lang2id)
args.eval_batch_size = args.per_gpu_eval_batch_size * max(1, args.n_gpu)
# Note that DistributedSampler samples randomly
if args.get_attr:
eval_sampler = RandomSampler(eval_dataset) if args.local_rank == -1 else DistributedSampler(eval_dataset)
else:
eval_sampler = SequentialSampler(eval_dataset) if args.local_rank == -1 else DistributedSampler(eval_dataset)
eval_dataloader = DataLoader(eval_dataset, sampler=eval_sampler, batch_size=args.eval_batch_size)
# multi-gpu evaluate
if args.n_gpu > 1:
model = torch.nn.DataParallel(model)
# Eval!
logger.info("***** Running evaluation %s in %s *****" % (prefix, lang))
logger.info(" Num examples = %d", len(eval_dataset))
logger.info(" Batch size = %d", args.eval_batch_size)
eval_loss = 0.0
nb_eval_steps = 0
preds = None
out_label_ids = None
model.eval()
counter = 0
head_importances = None
all_head_importances = None
for batch in tqdm(eval_dataloader, desc="Evaluating"):
counter += 1
logger.info(f'Batch number = {counter}')
batch = tuple(t.to(args.device) for t in batch)
if calc_weight_step > 0:
adapter_weight = calc_weight_multi(args, model, batch, lang_adapter_names, task_name, adapter_weight, calc_weight_step, lang=lang)
if args.get_attr:
inputs = {"input_ids": batch[0],
"attention_mask": batch[1],
"labels": batch[3],
"adapter_weights": adapter_weight}
if args.model_type != "distilbert":
# XLM and RoBERTa don"t use segment_ids
inputs["token_type_ids"] = batch[2] if args.model_type in ["bert", "xlnet"] else None
if args.model_type == 'xlm':
inputs["langs"] = batch[4]
inputs["output_attentions"] = True
outputs = model(**inputs)
tmp_eval_loss, logits, attentions, kept_labels, kl_logits = outputs
attr_all = []
res_attr = []
input_len = int(inputs["attention_mask"][0].sum())
example_head_importances = None
#Remove the batch_size dim since batch_size=1
logits = logits[0]
for tar_layer in range(12):
att = attentions[tar_layer][0]
pred_labels = torch.argmax(logits, dim=-1)
scale_att, step = scaled_input(att.data)
scale_att.requires_grad_(True)
attr_all = None
prob_all = None
for j_batch in range(1):
one_batch_att = scale_att[j_batch*16:(j_batch+1)*16]
_, grad = model(input_ids=inputs['input_ids'], token_type_ids=inputs['token_type_ids'], attention_mask=inputs['attention_mask'], labels=inputs['labels'], tar_layer=tar_layer, tmp_score=one_batch_att, pred_labels=pred_labels)
grad = grad.sum(dim=0)
attr_all = grad if attr_all is None else torch.add(attr_all, grad)
# prob_all = tar_prob if prob_all is None else torch.cat([prob_all, tar_prob])
attr_all = attr_all[:,0:input_len,0:input_len] * step[:,0:input_len,0:input_len]
if example_head_importances is None:
example_head_importances = torch.amax(attr_all, dim=(1,2)).unsqueeze(0)
else:
tmp = torch.amax(attr_all, dim=(1,2))
tmp = tmp.unsqueeze(0)
example_head_importances = torch.cat((example_head_importances, tmp), dim=0)
# att = att[:,0:input_len,0:input_len]
res_attr.append(attr_all.data)
# logger.info(f'Example Head Importances = {example_head_importances}')
all_head_importances = example_head_importances.unsqueeze(0) if all_head_importances is None else torch.cat((all_head_importances, example_head_importances.unsqueeze(0)), dim=0)
head_importances = example_head_importances if head_importances is None else torch.add(head_importances, example_head_importances)
if counter == 100:
break
continue
with torch.no_grad():
inputs = {"input_ids": batch[0],
"attention_mask": batch[1],
"labels": batch[3],
"adapter_weights": adapter_weight}
# logger.info(f'Labels = {batch[3]}')
if args.model_type != "distilbert":
# XLM and RoBERTa don"t use segment_ids
inputs["token_type_ids"] = batch[2] if args.model_type in ["bert", "xlnet"] else None
if args.model_type == 'xlm':
inputs["langs"] = batch[4]
outputs = model(**inputs)
tmp_eval_loss, logits = outputs[:2]
if args.n_gpu > 1:
# mean() to average on multi-gpu parallel evaluating
tmp_eval_loss = tmp_eval_loss.mean()
eval_loss += tmp_eval_loss.item()
nb_eval_steps += 1
if preds is None:
preds = logits.detach().cpu().numpy()
out_label_ids = inputs["labels"].detach().cpu().numpy()
else:
preds = np.append(preds, logits.detach().cpu().numpy(), axis=0)
out_label_ids = np.append(out_label_ids, inputs["labels"].detach().cpu().numpy(), axis=0)
if args.get_attr:
head_importances = head_importances/counter
logger.info(f'Head Importances = {head_importances}')
torch.save(head_importances, os.path.join(args.output_dir,f'{mode}_{lang}_s{args.seed}_importances_100.pt'))
torch.save(all_head_importances, os.path.join(args.output_dir,f'{mode}_{lang}_s{args.seed}_all_importances_100.pt'))
return None, None
if nb_eval_steps == 0:
results = {k: 0 for k in ["loss", "precision", "recall", "f1"]}
else:
eval_loss = eval_loss / nb_eval_steps
preds = np.argmax(preds, axis=2)
label_map = {i: label for i, label in enumerate(labels)}
out_label_list = [[] for _ in range(out_label_ids.shape[0])]
preds_list = [[] for _ in range(out_label_ids.shape[0])]
for i in range(out_label_ids.shape[0]):
for j in range(out_label_ids.shape[1]):
if out_label_ids[i, j] != pad_token_label_id:
out_label_list[i].append(label_map[out_label_ids[i][j]])
preds_list[i].append(label_map[preds[i][j]])
results = {
"loss": eval_loss,
"precision": precision_score(out_label_list, preds_list),
"recall": recall_score(out_label_list, preds_list),
"f1": f1_score(out_label_list, preds_list)
}
if print_result:
logger.info("***** Evaluation result %s in %s *****" % (prefix, lang))
for key in sorted(results.keys()):
logger.info(" %s = %s", key, str(results[key]))
return results, preds_list
def load_and_cache_examples(args, tokenizer, labels, pad_token_label_id, mode, lang, lang2id=None, few_shot=-1):
# Make sure only the first process in distributed training process
# the dataset, and the others will use the cache
if args.local_rank not in [-1, 0] and not evaluate:
torch.distributed.barrier()
# Load data features from cache or dataset file
bpe_dropout = args.bpe_dropout
if mode != 'train': bpe_dropout = 0
if bpe_dropout > 0:
cached_features_file = os.path.join(args.data_dir, "cached_{}_{}_{}_{}_drop{}".format(mode, lang,
list(filter(None, args.model_name_or_path.split("/"))).pop(),
str(args.max_seq_length), bpe_dropout))
else:
cached_features_file = os.path.join(args.data_dir, "cached_{}_{}_{}_{}".format(mode, lang,
list(filter(None, args.model_name_or_path.split("/"))).pop(),
str(args.max_seq_length)))
if os.path.exists(cached_features_file) and not args.overwrite_cache:
logger.info("Loading features from cached file %s", cached_features_file)
features = torch.load(cached_features_file)
else:
langs = lang.split(',')
logger.info("all languages = {}".format(lang))
features = []
for lg in langs:
data_file = os.path.join(args.data_dir, lg, "{}.{}".format(mode, args.model_name_or_path))
logger.info("Creating features from dataset file at {} in language {}".format(data_file, lg))
examples = read_examples_from_file(data_file, lg, lang2id)
print(examples)
features_lg = convert_examples_to_features(examples, labels, args.max_seq_length, tokenizer,
cls_token_at_end=bool(args.model_type in ["xlnet"]),
cls_token=tokenizer.cls_token,
cls_token_segment_id=2 if args.model_type in ["xlnet"] else 0,
sep_token=tokenizer.sep_token,
sep_token_extra=bool(args.model_type in ["roberta", "xlmr"]),
pad_on_left=bool(args.model_type in ["xlnet"]),
pad_token=tokenizer.convert_tokens_to_ids([tokenizer.pad_token])[0],
pad_token_segment_id=4 if args.model_type in ["xlnet"] else 0,
pad_token_label_id=pad_token_label_id,
lang=lg,
bpe_dropout=bpe_dropout,
)
features.extend(features_lg)
if args.local_rank in [-1, 0]:
logger.info("Saving features into cached file {}, len(features)={}".format(cached_features_file, len(features)))
torch.save(features, cached_features_file)
# Make sure only the first process in distributed training process
# the dataset, and the others will use the cache
if args.local_rank == 0 and not evaluate:
torch.distributed.barrier()
if few_shot > 0 and mode == 'train':
logger.info("Original no. of examples = {}".format(len(features)))
features = features[: few_shot]
logger.info('Using few-shot learning on {} examples'.format(len(features)))
# Convert to Tensors and build dataset
all_input_ids = torch.tensor([f.input_ids for f in features], dtype=torch.long)
all_input_mask = torch.tensor([f.input_mask for f in features], dtype=torch.long)
all_segment_ids = torch.tensor([f.segment_ids for f in features], dtype=torch.long)
all_label_ids = torch.tensor([f.label_ids for f in features], dtype=torch.long)
if args.model_type == 'xlm' and features[0].langs is not None:
all_langs = torch.tensor([f.langs for f in features], dtype=torch.long)
logger.info('all_langs[0] = {}'.format(all_langs[0]))
dataset = TensorDataset(all_input_ids, all_input_mask, all_segment_ids, all_label_ids, all_langs)
else:
dataset = TensorDataset(all_input_ids, all_input_mask, all_segment_ids, all_label_ids)
return dataset
@dataclass
class ModelArguments:
"""
Arguments pertaining to which model/config/tokenizer we are going to fine-tune from.
"""
model_name_or_path: str = field(
metadata={"help": "Path to pretrained model or model identifier from huggingface.co/models"}
)
model_type: Optional[str] = field(
default=None, metadata={"help": "Pretrained config name or path if not the same as model_name"}
)
config_name: Optional[str] = field(
default=None, metadata={"help": "Pretrained config name or path if not the same as model_name"}
)
tokenizer_name: Optional[str] = field(
default=None, metadata={"help": "Pretrained tokenizer name or path if not the same as model_name"}
)
cache_dir: Optional[str] = field(
default=None, metadata={"help": "Where do you want to store the pretrained models downloaded from s3"}
)
labels: str = field(
default=None, metadata={"help": "Where do you want to store the pretrained models downloaded from s3"}
)
data_dir: str = field(
default=None, metadata={"help": "Where do you want to store the pretrained models downloaded from s3"}
)
output_dir: str = field(
default=None, metadata={"help": "Where do you want to store the pretrained models downloaded from s3"}
)
max_seq_length: Optional[int] = field(
default=128, metadata={"help": "Where do you want to store the pretrained models downloaded from s3"}
)
do_train: Optional[bool] = field(default=False )
do_eval: Optional[bool] = field(default=False )
do_predict: Optional[bool] = field(default=False )
do_adapter_predict: Optional[bool] = field(default=False )
do_predict_dev: Optional[bool] = field(default=False )
do_predict_train: Optional[bool] = field(default=False )
init_checkpoint: Optional[str] = field(default=None )
evaluate_during_training: Optional[bool] = field(default=False )
do_lower_case: Optional[bool] = field(default=False )
few_shot: Optional[int] = field(default=-1 )
per_gpu_train_batch_size: Optional[int] = field(default=8)
per_gpu_eval_batch_size: Optional[int] = field(default=8)
gradient_accumulation_steps: Optional[int] = field(default=1)
learning_rate: Optional[float] = field(default=5e-5)
weight_decay: Optional[float] = field(default=0.0)
adam_epsilon: Optional[float] = field(default=1e-8)
max_grad_norm: Optional[float] = field(default=1.0)
num_train_epochs: Optional[float] = field(default=3.0)
max_steps: Optional[int] = field(default=-1)
save_steps: Optional[int] = field(default=-1)
warmup_steps: Optional[int] = field(default=0)
logging_steps: Optional[int] = field(default=50)
save_only_best_checkpoint: Optional[bool] = field(default=False)
eval_all_checkpoints: Optional[bool] = field(default=False)
no_cuda: Optional[bool] = field(default=False)
overwrite_output_dir: Optional[bool] = field(default=False)
overwrite_cache: Optional[bool] = field(default=False)
seed: Optional[int] = field(default=42)
fp16: Optional[bool] = field(default=False)
fp16_opt_level: Optional[str] = field(default="O1")
local_rank: Optional[int] = field(default=-1)
server_ip: Optional[str] = field(default="")
server_port: Optional[str] = field(default="")
predict_langs: Optional[str] = field(default="en")
train_langs: Optional[str] = field(default="en")
log_file: Optional[str] = field(default=None)
eval_patience: Optional[int] = field(default=-1)
bpe_dropout: Optional[float] = field(default=0)
do_save_adapter_fusions: Optional[bool] = field(default=False)
task_name: Optional[str] = field(default="ner")
predict_task_adapter: Optional[str] = field(default=None)
predict_lang_adapter: Optional[str] = field(default=None)
test_adapter: Optional[bool] = field(default=False)
adapter_weight: Optional[str] = field(default=None)
lang_to_vec: Optional[str] = field(default=None)
calc_weight_step: Optional[int] = field(default=0)
predict_save_prefix: Optional[str] = field(default=None)
en_weight: Optional[float] = field(default=None)
temperature: Optional[float] = field(default=1.0)
get_attr: Optional[bool] = field(default=False)
topk: Optional[int] = field(default=1)
task: Optional[str] = field(default='udpos')
def setup_adapter(args, adapter_args, model, train_adapter=True, load_adapter=None, load_lang_adapter=None):
task_name = args.task_name or "ner"
# check if adapter already exists, otherwise add it
if task_name not in model.config.adapters.adapter_list(AdapterType.text_task):
logging.info("Trying to decide if add adapter")
# resolve the adapter config
adapter_config = AdapterConfig.load(
adapter_args.adapter_config,
non_linearity=adapter_args.adapter_non_linearity,
reduction_factor=adapter_args.adapter_reduction_factor,
)
# load a pre-trained from Hub if specified
if adapter_args.load_adapter or load_adapter:
logging.info("loading task adapter")
model.load_adapter(
adapter_args.load_adapter if load_adapter is None else load_adapter,
AdapterType.text_task,
config=adapter_config,
load_as=task_name,
)
# otherwise, add a fresh adapter
else:
logging.info("Adding task adapter")
model.add_adapter(task_name, AdapterType.text_task, config=adapter_config)
# optionally load a pre-trained language adapter
if adapter_args.load_lang_adapter or load_lang_adapter:
if load_lang_adapter is None:
# load a set of language adapters
logging.info("loading lang adpater {}".format(adapter_args.load_lang_adapter))
# resolve the language adapter config
lang_adapter_config = AdapterConfig.load(
adapter_args.lang_adapter_config,
non_linearity=adapter_args.lang_adapter_non_linearity,
reduction_factor=adapter_args.lang_adapter_reduction_factor,
)
# load the language adapter from Hub
# if adapter_args.language == 'topk':
# assert len(args.predict_langs.split(',')) == 1
# filename = f'scripts/{args.task}/en/{args.predict_langs}.json'
# logger.info(f'Loading Adapter Languages from {filename}')
# languages = []
# with open(filename) as f:
# for i,line in enumerate(f):
# if i == args.topk:
# break
# line = json.loads(line)
# languages.append(line['adapter'].strip())
# adapter_names = [f'{lang}/wiki@ukp' for lang in languages]
# else:
# languages = adapter_args.language.split(",")
# adapter_names = adapter_args.load_lang_adapter.split(",")
# logger.info(f'Adapter Languages : {languages}, Length : {len(languages)}')
# logger.info(f'Adapter Names {adapter_names}, Length : {len(adapter_names)}')
# assert len(languages) == len(adapter_names)
# lang_adapter_names = []
# for language, adapter_name in zip(languages, adapter_names):
# logger.info(f'Language = {language}')
# logger.info(f'Adapter Name = {adapter_name}')
# lang_adapter_name = model.load_adapter(
# adapter_name,
# AdapterType.text_lang,
# config=lang_adapter_config,
# load_as=language,
# )
# lang_adapter_names.append(lang_adapter_name)
else:
logging.info("loading lang adpater {}".format(load_lang_adapter))
# resolve the language adapter config
lang_adapter_config = AdapterConfig.load(
adapter_args.lang_adapter_config,
non_linearity=adapter_args.lang_adapter_non_linearity,
reduction_factor=adapter_args.lang_adapter_reduction_factor,
)
# load the language adapter from Hub
# lang_adapter_name = model.load_adapter(
# load_lang_adapter,
# AdapterType.text_lang,
# config=lang_adapter_config,
# load_as="lang",
# )
# lang_adapter_names = [lang_adapter_name]
else:
lang_adapter_name = None
lang_adapter_names = []
# Freeze all model weights except of those of this adapter
model.train_adapter([task_name])
# Set the adapters to be used in every forward pass
if lang_adapter_name:
model.set_active_adapters([lang_adapter_names, [task_name]])
else:
model.set_active_adapters([task_name])
return model, lang_adapter_names, task_name
def load_model(args, num_labels):
logger.info('Loading pretrained model and tokenizer')
config = AutoConfig.from_pretrained(
args.config_name if args.config_name else args.model_name_or_path,
num_labels=num_labels,
cache_dir=args.cache_dir,
)
args.model_type = config.model_type
tokenizer = AutoTokenizer.from_pretrained(
args.tokenizer_name if args.tokenizer_name else args.model_name_or_path,
do_lower_case=args.do_lower_case,
cache_dir=args.cache_dir,
use_fast=False,
)
if args.init_checkpoint:
logger.info("loading from init_checkpoint={}".format(args.init_checkpoint))
model = AutoModelForTokenClassification.from_pretrained(
args.init_checkpoint,
config=config,
cache_dir=args.cache_dir,
)
else:
logger.info("loading from existing model {}".format(args.model_name_or_path))
model = AutoModelForTokenClassification.from_pretrained(
args.model_name_or_path,
from_tf=bool(".ckpt" in args.model_name_or_path),
config=config,
cache_dir=args.cache_dir,
)
lang2id = config.lang2id if args.model_type == "xlm" else None
logger.info("Using lang2id = {}".format(lang2id))
return model, tokenizer, lang2id
def predict_and_save(args, adapter_args, model, tokenizer, labels, lang2id, pad_token_label_id, lang_adapter_names, task_name, split):
output_test_results_file = os.path.join(args.output_dir, f"{split}_results.txt")
with open(output_test_results_file, "a") as result_writer:
for lang in args.predict_langs.split(','):
#Check if language data exists
if not os.path.exists(os.path.join(args.data_dir, lang, '{}.{}'.format(split, args.model_name_or_path))):
logger.info("Language {}, split {} does not exist".format(lang, split))
continue
#Activate the required language adapter
adapter_weight = None
# if not args.adapter_weight and not args.lang_to_vec:
# if (adapter_args.train_adapter or args.test_adapter) and not args.adapter_weight:
# if lang in lang_adapter_names:
# logger.info(f'Language adapter for {lang} found')
# logger.info("Set active language adapter to {}".format(lang))
# model.set_active_adapters([[lang], [task_name]])
# else:
# logger.info(f'Language adapter for {lang} not found, using {lang_adapter_names[0]} instead')
# logger.info("Set active language adapter to {}".format(lang_adapter_names[0]))
# model.set_active_adapters([[lang_adapter_names[0]], [task_name]])
# else:
# if args.adapter_weight == 'equal':
# adapter_weight = [1/len(lang_adapter_names) for _ in lang_adapter_names]
# elif args.adapter_weight == 'equal_en':
# assert 'en' in lang_adapter_names, 'English language adapter not included'
# adapter_weight = [(1-args.en_weight)/(len(lang_adapter_names)-1) for _ in lang_adapter_names]
# en_index = lang_adapter_names.index('en')
# adapter_weight[en_index] = args.en_weight
# elif args.lang_to_vec:
# if args.en_weight is not None:
# logger.info(lang_adapter_names)
# assert 'en' in lang_adapter_names, 'English language adapter not included'
# adapter_weight = calc_l2v_weights(args, lang, lang_adapter_names)
# elif args.adapter_weight == 'load':
# filename = f'weights/{args.task}/{lang}/weights_s{args.seed}'
# logger.info(f'Loading adapter weights from {filename}')
# with open(filename) as f:
# adapter_weight = json.loads(next(f))
# elif args.adapter_weight != "0" and args.adapter_weight is not None:
# adapter_weight = [float(w) for w in args.adapter_weight.split(",")]
logger.info('Args Adapter Weight = {}'.format(args.adapter_weight))
logger.info('Adapter Languages = {}'.format(lang_adapter_names))
if adapter_weight is not None:
logger.info("Adapter Weights = {}".format(adapter_weight))
logger.info('Sum of Adapter Weights = {}'.format(sum(adapter_weight)))
logger.info("Length of Adapter Weights = {}".format(len(adapter_weight)))
# model.set_active_adapters([ lang_adapter_names, [task_name]])
#Evaluate
result, predictions = evaluate(args, model, tokenizer, labels, pad_token_label_id, mode=split, lang=lang, lang2id=lang2id, adapter_weight=adapter_weight, lang_adapter_names=lang_adapter_names, task_name=task_name, calc_weight_step=args.calc_weight_step)
if args.get_attr:
continue
result_json = {}
# Save results
if args.predict_save_prefix is not None and args.predict_save_prefix:
result_json['language'] = f'{args.predict_save_prefix}_{lang}'
else:
result_json['language'] = f'{lang}'
result_json['seed'] = args.seed
result_json['language_adapters'] = lang_adapter_names
if args.adapter_weight:
result_json['adapter_weights'] = args.adapter_weight
for key in sorted(result.keys()):
result_json[key] = result[key]
result_writer.write(json.dumps(result_json) + '\n')
# Save predictions
if args.predict_save_prefix is not None and args.predict_save_prefix:
output_test_predictions_file = os.path.join(args.output_dir, "{}_{}_{}_s{}_predictions.txt".format(split, args.predict_save_prefix, lang, args.seed))
else:
output_test_predictions_file = os.path.join(args.output_dir, "{}_{}_s{}_predictions.txt".format(split, lang, args.seed))
infile = os.path.join(args.data_dir, lang, "{}.{}".format(split, args.model_name_or_path))
idxfile = infile + '.idx'
save_predictions(args, predictions, output_test_predictions_file, infile, idxfile)
def main():
parser = argparse.ArgumentParser()
parser = HfArgumentParser((ModelArguments, MultiLingAdapterArguments))
args, adapter_args = parser.parse_args_into_dataclasses()
if os.path.exists(args.output_dir) and os.listdir(
args.output_dir) and args.do_train and not args.overwrite_output_dir:
raise ValueError(
"Output directory ({}) already exists and is not empty. Use --overwrite_output_dir to overcome.".format(
args.output_dir))
# Setup distant debugging if needed
if args.server_ip and args.server_port:
import ptvsd
print("Waiting for debugger attach")
ptvsd.enable_attach(address=(args.server_ip, args.server_port), redirect_output=True)
ptvsd.wait_for_attach()
# Setup CUDA, GPU & distributed training
if args.local_rank == -1 or args.no_cuda:
device = torch.device("cuda" if torch.cuda.is_available() and not args.no_cuda else "cpu")
args.n_gpu = torch.cuda.device_count()
else:
# Initializes the distributed backend which sychronizes nodes/GPUs
torch.cuda.set_device(args.local_rank)
device = torch.device("cuda", args.local_rank)
torch.distributed.init_process_group(backend="nccl")
args.n_gpu = 1
args.device = device
# Setup logging
logging.basicConfig(handlers = [logging.FileHandler(args.log_file), logging.StreamHandler()],
format = '%(asctime)s - %(levelname)s - %(name)s - %(message)s',
datefmt = '%m/%d/%Y %H:%M:%S',
level = logging.INFO if args.local_rank in [-1, 0] else logging.WARN)
logging.info("Input args: %r" % args)
logger.warning("Process rank: %s, device: %s, n_gpu: %s, distributed training: %s, 16-bits training: %s",
args.local_rank, device, args.n_gpu, bool(args.local_rank != -1), args.fp16)
# Set seed
set_seed(args)
# Prepare NER/POS task
labels = get_labels(args.labels)
num_labels = len(labels)
# Use cross entropy ignore index as padding label id
# so that only real label ids contribute to the loss later
pad_token_label_id = CrossEntropyLoss().ignore_index
# Load pretrained model and tokenizer
# Make sure only the first process in distributed training loads model/vocab
if args.local_rank not in [-1, 0]:
torch.distributed.barrier()
args.do_save_full_model= (not adapter_args.train_adapter)
args.do_save_adapters=adapter_args.train_adapter
if args.do_save_adapters:
logging.info('save adapters')
logging.info(adapter_args.train_adapter)
if args.do_save_full_model:
logging.info('save model')
# Make sure only the first process in distributed training loads model/vocab
if args.local_rank == 0:
torch.distributed.barrier()
logger.info("Training/evaluation parameters %s", args)
# Training
if args.do_train:
model, tokenizer, lang2id = load_model(args, num_labels)
if adapter_args.train_adapter:
model, lang_adapter_names, task_name = setup_adapter(args, adapter_args, model)
logger.info("lang adapter names: {}".format(" ".join(lang_adapter_names)))
else:
lang_adatper_names = []
task_name = None
model.to(args.device)
train_dataset = load_and_cache_examples(args, tokenizer, labels, pad_token_label_id, mode="train", lang=args.train_langs, lang2id=lang2id, few_shot=args.few_shot)
global_step, tr_loss = train(args, train_dataset, model, tokenizer, labels, pad_token_label_id, lang_adapter_names, task_name, lang2id)
logger.info(" global_step = %s, average loss = %s", global_step, tr_loss)
# Saving best-practices: if you use default names for the model,
# you can reload it using from_pretrained()
if args.do_train and (args.local_rank == -1 or torch.distributed.get_rank() == 0):
# Create output directory if needed
if not os.path.exists(args.output_dir) and args.local_rank in [-1, 0]:
os.makedirs(args.output_dir)
# Save model, configuration and tokenizer using `save_pretrained()`.
# They can then be reloaded using `from_pretrained()`
# Take care of distributed/parallel training
logger.info("Saving model checkpoint to %s", args.output_dir)
model_to_save = model.module if hasattr(model, "module") else model
if args.do_save_adapters:
logging.info("Save adapter")
model_to_save.save_all_adapters(args.output_dir)
if args.do_save_adapter_fusions:
logging.info("Save adapter fusion")
model_to_save.save_all_adapter_fusions(args.output_dir)
if args.do_save_full_model:
logging.info("Save full model")
model_to_save.save_pretrained(args.output_dir)
tokenizer.save_pretrained(args.output_dir)
# Good practice: save your training arguments together with the model
torch.save(args, os.path.join(args.output_dir, "training_args.bin"))
# Initialization for evaluation
results = {}
if args.init_checkpoint:
best_checkpoint = args.init_checkpoint
elif os.path.exists(os.path.join(args.output_dir, 'checkpoint-best')):
best_checkpoint = os.path.join(args.output_dir, 'checkpoint-best')
else:
best_checkpoint = args.output_dir
# Evaluation
#This evaluates only if the entire model is saved, something we are not doing
if args.do_eval and args.local_rank in [-1, 0]:
model, tokenizer, lang2id = load_model(args, num_labels)
logger.info('Evaluating the model on dev set of training language(en)')
load_adapter = (best_checkpoint + "/" + args.task_name) if args.predict_task_adapter is None else args.predict_task_adapter
# load_adapter = 'output/panx/bert-base-multilingual-cased-LR1e-4-epoch100-MaxLen128-TrainLangen_en_s0/checkpoint-best/ner/'
logger.info(f'Task Adapter will be loaded from this path {load_adapter}')
model.model_name = args.model_name_or_path
model, lang_adapter_names, task_name = setup_adapter(args, adapter_args, model, load_adapter=load_adapter)
model.to(args.device)
result, _ = evaluate(args, model, tokenizer, labels, pad_token_label_id, mode="dev", prefix='debugging', lang=args.train_langs, lang2id=lang2id, lang_adapter_names=lang_adapter_names, task_name=task_name, calc_weight_step=args.calc_weight_step)
results.update(result)
# for checkpoint in checkpoints:
# global_step = checkpoint.split("-")[-1] if len(checkpoints) > 1 else ""
# model = AutoModelForTokenClassification.from_pretrained(checkpoint)
# if adapter_args.train_adapter:
# load_adapter = checkpoint + "/" + args.task_name
# load_lang_adapter = "{}/{}".format(checkpoint, adapter_args.language)
# model.model_name = args.model_name_or_path
# model, lang_adapter_names, task_name = setup_adapter(args, adapter_args, model, load_adapter=load_adapter)
#
# model.to(args.device)
# result, _ = evaluate(args, model, tokenizer, labels, pad_token_label_id, mode="dev", prefix=global_step, lang=args.train_langs, lang2id=lang2id, lang_adapter_names=lang_adapter_names, task_name=task_name, calc_weight_step=args.calc_weight_step)
# if result["f1"] > best_f1:
# best_checkpoint = checkpoint
# best_f1 = result["f1"]
# if global_step:
# result = {"{}_{}".format(global_step, k): v for k, v in result.items()}
# results.update(result)
output_eval_file = os.path.join(args.output_dir, "eval_results.txt")
with open(output_eval_file, "w") as writer:
for key in sorted(results.keys()):
writer.write("{} = {}\n".format(key, str(results[key])))
# writer.write("best checkpoint = {}, best f1 = {}\n".format(best_checkpoint, best_f1))
if args.do_predict and args.local_rank in [-1, 0]:
model, tokenizer, lang2id = load_model(args, num_labels)
# Prediction
logger.info('Evaluating the model on test set of all the languages specified')
#Set up the task adapter
if adapter_args.train_adapter or args.test_adapter:
load_adapter = (best_checkpoint + "/" + args.task_name) if args.predict_task_adapter is None else args.predict_task_adapter
# load_adapter = 'output/panx/bert-base-multilingual-cased-LR1e-4-epoch100-MaxLen128-TrainLangen_en_s0/checkpoint-best/ner/'
logger.info(f'Task Adapter will be loaded from this path {load_adapter}')
load_lang_adapter = args.predict_lang_adapter
model.model_name = args.model_name_or_path
model, lang_adapter_names, task_name = setup_adapter(args, adapter_args, model, load_adapter=load_adapter, load_lang_adapter=load_lang_adapter)
model.to(args.device)
predict_and_save(args, adapter_args, model, tokenizer, labels, lang2id, pad_token_label_id, lang_adapter_names, task_name, 'test')
if args.do_predict_train and args.local_rank in [-1, 0]:
logger.info('Evaluating on the train set of all specified languages')
model, tokenizer, lang2id = load_model(args, num_labels)
if adapter_args.train_adapter or args.test_adapter:
load_adapter = (best_checkpoint + "/" + args.task_name) if args.predict_task_adapter is None else args.predict_task_adapter
# load_adapter = 'output/panx/bert-base-multilingual-cased-LR1e-4-epoch100-MaxLen128-TrainLangen_en_s0/checkpoint-best/ner/'
logger.info(f'Task Adapter will be loaded from this path {load_adapter}')
load_lang_adapter = args.predict_lang_adapter
model.model_name = args.model_name_or_path
model, lang_adapter_names, task_name = setup_adapter(args, adapter_args, model, load_adapter=load_adapter, load_lang_adapter=load_lang_adapter)
model.to(args.device)
predict_and_save(args, adapter_args, model, tokenizer, labels, lang2id, pad_token_label_id, lang_adapter_names, task_name, 'train')
#Predict dev set
if args.do_predict_dev and args.local_rank in [-1, 0]:
model, tokenizer, lang2id = load_model(args, num_labels)
logger.info('Evaluating on the dev sets of all the specified languages')
#Set up task and language adapters
if adapter_args.train_adapter or args.test_adapter:
load_adapter = (best_checkpoint + "/" + args.task_name) if args.predict_task_adapter is None else args.predict_task_adapter
# load_adapter = 'output/panx/bert-base-multilingual-cased-LR1e-4-epoch100-MaxLen128-TrainLangen_en_s0/checkpoint-best/ner/'
logger.info(f'Task Adapter will be loaded from this path {load_adapter}')
load_lang_adapter = args.predict_lang_adapter
model.model_name = args.model_name_or_path
model, lang_adapter_names, task_name = setup_adapter(args, adapter_args, model, load_adapter=load_adapter, load_lang_adapter=load_lang_adapter)
model.to(args.device)
predict_and_save(args, adapter_args, model, tokenizer, labels, lang2id, pad_token_label_id, lang_adapter_names, task_name, 'dev')
def save_predictions(args, predictions, output_file, text_file, idx_file, output_word_prediction=False):
# Save predictions
with open(text_file, "r") as text_reader, open(idx_file, "r") as idx_reader:
text = text_reader.readlines()
index = idx_reader.readlines()
assert len(text) == len(index)
# Sanity check on the predictions
with open(output_file, "w") as writer:
example_id = 0
prev_id = int(index[0])
for line, idx in zip(text, index):
if line == "" or line == "\n":
example_id += 1
else:
cur_id = int(idx)
output_line = '\n' if cur_id != prev_id else ''
if output_word_prediction:
output_line += line.split()[0] + '\t'
output_line += predictions[example_id].pop(0) + '\n'
writer.write(output_line)
prev_id = cur_id
if __name__ == "__main__":
main()
| third_party/ridayesh_run_tag.py | 52,064 | Arguments pertaining to which model/config/tokenizer we are going to fine-tune from.
Train the model.
Fine-tuning models for NER and POS tagging.
coding=utf-8 Copyright 2018 The Google AI Language Team Authors, The HuggingFace Inc. team, and The XTREME Benchmark Authors. Copyright (c) 2018, NVIDIA CORPORATION. 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 lang2vec.lang2vec as l2vfrom xlm import XLMForTokenClassification Prepare optimizer and schedule (linear warmup and decay) multi-gpu training (should be after apex fp16 initialization) Distributed training (should be after apex fp16 initialization) Train! Add here for reproductibility (even between python 2 and 3) XLM and RoBERTa don"t use segment_ids mean() to average on multi-gpu parallel training Update learning rate schedule Log metrics Only evaluate on single GPU otherwise metrics may not average well Save the best model checkpoint Take care of distributed/parallel training Save model checkpoint Take care of distributed/parallel training logger.info(f'Language Adapters are {lang_adapter_names}') logger.info(f'Initial Adapter Weights = {normed_adapter_weights}')print(adapter_weights)print(grads)print(grads)print(normed_adapter_weights) logger.info(f'Final Adapter Weights = {normed_adapter_weights}') shape of emb: (num_head, seq_len, seq_len)Changed the default of calc_weight_step to 0 Note that DistributedSampler samples randomly multi-gpu evaluate Eval! XLM and RoBERTa don"t use segment_idsRemove the batch_size dim since batch_size=1 prob_all = tar_prob if prob_all is None else torch.cat([prob_all, tar_prob]) att = att[:,0:input_len,0:input_len] logger.info(f'Example Head Importances = {example_head_importances}') logger.info(f'Labels = {batch[3]}') XLM and RoBERTa don"t use segment_ids mean() to average on multi-gpu parallel evaluating Make sure only the first process in distributed training process the dataset, and the others will use the cache Load data features from cache or dataset file Make sure only the first process in distributed training process the dataset, and the others will use the cache Convert to Tensors and build dataset check if adapter already exists, otherwise add it resolve the adapter config load a pre-trained from Hub if specified otherwise, add a fresh adapter optionally load a pre-trained language adapter load a set of language adapters resolve the language adapter config load the language adapter from Hub if adapter_args.language == 'topk': assert len(args.predict_langs.split(',')) == 1 filename = f'scripts/{args.task}/en/{args.predict_langs}.json' logger.info(f'Loading Adapter Languages from {filename}') languages = [] with open(filename) as f: for i,line in enumerate(f): if i == args.topk: break line = json.loads(line) languages.append(line['adapter'].strip()) adapter_names = [f'{lang}/wiki@ukp' for lang in languages] else: languages = adapter_args.language.split(",") adapter_names = adapter_args.load_lang_adapter.split(",") logger.info(f'Adapter Languages : {languages}, Length : {len(languages)}') logger.info(f'Adapter Names {adapter_names}, Length : {len(adapter_names)}') assert len(languages) == len(adapter_names) lang_adapter_names = [] for language, adapter_name in zip(languages, adapter_names): logger.info(f'Language = {language}') logger.info(f'Adapter Name = {adapter_name}') lang_adapter_name = model.load_adapter( adapter_name, AdapterType.text_lang, config=lang_adapter_config, load_as=language, ) lang_adapter_names.append(lang_adapter_name) resolve the language adapter config load the language adapter from Hub lang_adapter_name = model.load_adapter( load_lang_adapter, AdapterType.text_lang, config=lang_adapter_config, load_as="lang", ) lang_adapter_names = [lang_adapter_name] Freeze all model weights except of those of this adapter Set the adapters to be used in every forward passCheck if language data existsActivate the required language adapter if not args.adapter_weight and not args.lang_to_vec: if (adapter_args.train_adapter or args.test_adapter) and not args.adapter_weight: if lang in lang_adapter_names: logger.info(f'Language adapter for {lang} found') logger.info("Set active language adapter to {}".format(lang)) model.set_active_adapters([[lang], [task_name]]) else: logger.info(f'Language adapter for {lang} not found, using {lang_adapter_names[0]} instead') logger.info("Set active language adapter to {}".format(lang_adapter_names[0])) model.set_active_adapters([[lang_adapter_names[0]], [task_name]]) else: if args.adapter_weight == 'equal': adapter_weight = [1/len(lang_adapter_names) for _ in lang_adapter_names] elif args.adapter_weight == 'equal_en': assert 'en' in lang_adapter_names, 'English language adapter not included' adapter_weight = [(1-args.en_weight)/(len(lang_adapter_names)-1) for _ in lang_adapter_names] en_index = lang_adapter_names.index('en') adapter_weight[en_index] = args.en_weight elif args.lang_to_vec: if args.en_weight is not None: logger.info(lang_adapter_names) assert 'en' in lang_adapter_names, 'English language adapter not included' adapter_weight = calc_l2v_weights(args, lang, lang_adapter_names) elif args.adapter_weight == 'load': filename = f'weights/{args.task}/{lang}/weights_s{args.seed}' logger.info(f'Loading adapter weights from {filename}') with open(filename) as f: adapter_weight = json.loads(next(f)) elif args.adapter_weight != "0" and args.adapter_weight is not None: adapter_weight = [float(w) for w in args.adapter_weight.split(",")] model.set_active_adapters([ lang_adapter_names, [task_name]])Evaluate Save results Save predictions Setup distant debugging if needed Setup CUDA, GPU & distributed training Initializes the distributed backend which sychronizes nodes/GPUs Setup logging Set seed Prepare NER/POS task Use cross entropy ignore index as padding label id so that only real label ids contribute to the loss later Load pretrained model and tokenizer Make sure only the first process in distributed training loads model/vocab Make sure only the first process in distributed training loads model/vocab Training Saving best-practices: if you use default names for the model, you can reload it using from_pretrained() Create output directory if needed Save model, configuration and tokenizer using `save_pretrained()`. They can then be reloaded using `from_pretrained()` Take care of distributed/parallel training Good practice: save your training arguments together with the model Initialization for evaluation EvaluationThis evaluates only if the entire model is saved, something we are not doing load_adapter = 'output/panx/bert-base-multilingual-cased-LR1e-4-epoch100-MaxLen128-TrainLangen_en_s0/checkpoint-best/ner/' for checkpoint in checkpoints: global_step = checkpoint.split("-")[-1] if len(checkpoints) > 1 else "" model = AutoModelForTokenClassification.from_pretrained(checkpoint) if adapter_args.train_adapter: load_adapter = checkpoint + "/" + args.task_name load_lang_adapter = "{}/{}".format(checkpoint, adapter_args.language) model.model_name = args.model_name_or_path model, lang_adapter_names, task_name = setup_adapter(args, adapter_args, model, load_adapter=load_adapter) model.to(args.device) result, _ = evaluate(args, model, tokenizer, labels, pad_token_label_id, mode="dev", prefix=global_step, lang=args.train_langs, lang2id=lang2id, lang_adapter_names=lang_adapter_names, task_name=task_name, calc_weight_step=args.calc_weight_step) if result["f1"] > best_f1: best_checkpoint = checkpoint best_f1 = result["f1"] if global_step: result = {"{}_{}".format(global_step, k): v for k, v in result.items()} results.update(result) writer.write("best checkpoint = {}, best f1 = {}\n".format(best_checkpoint, best_f1)) PredictionSet up the task adapter load_adapter = 'output/panx/bert-base-multilingual-cased-LR1e-4-epoch100-MaxLen128-TrainLangen_en_s0/checkpoint-best/ner/' load_adapter = 'output/panx/bert-base-multilingual-cased-LR1e-4-epoch100-MaxLen128-TrainLangen_en_s0/checkpoint-best/ner/'Predict dev setSet up task and language adapters load_adapter = 'output/panx/bert-base-multilingual-cased-LR1e-4-epoch100-MaxLen128-TrainLangen_en_s0/checkpoint-best/ner/' Save predictions Sanity check on the predictions | 8,979 | en | 0.6209 |
# The MIT License (MIT)
#
# Copyright (c) 2016 Oracle
#
# 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.
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~#
__author__ = "Michael Shanley (Oracle A-Team)"
__copyright__ = "Copyright (c) 2016 Oracle and/or its affiliates. All rights reserved."
__version__ = "1.0.0.0"
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~#
from oc_provision_wrappers import commerce_setup_helper
import os
import time
import logging
logger = logging.getLogger(__name__)
json_key = 'ORACLE_11g_clone'
service_name = "Oracle DB clone"
def clone_oracle(configData, full_path):
if json_key in configData:
jsonData = configData[json_key]
else:
logging.error(json_key + " config data missing from json. will not install")
return
logging.info("installing " + service_name)
INSTALL_OWNER = jsonData['installOwner']
ORACLE_HOME = jsonData['oracleHome']
ORIG_HOST = jsonData['originalHost']
NEW_HOST = jsonData['newHost']
ORACLE_SID = jsonData['oracleSID']
UPDATE_DB_CONSOLE = jsonData['updateDBConsole']
db_script = "/etc/init.d/oracleDatabase"
db_console_script = "/etc/init.d/oracleDBconsole"
stop_db_cmd = db_script + " stop"
stop_db_console_cmd = db_console_script + " stop"
start_db_cmd = db_script + " start"
start_db_console_cmd = db_console_script + " start"
tns_path = ORACLE_HOME + "/network/admin/tnsnames.ora"
lsnr_path = ORACLE_HOME + "/network/admin/listener.ora"
if not os.path.exists(tns_path):
logging.error("tnsnames.ora not found at " + tns_path + " - will not proceed")
return False
# stop db
commerce_setup_helper.exec_cmd(stop_db_cmd)
# stop console
commerce_setup_helper.exec_cmd(stop_db_console_cmd)
tns_replacements = {}
lsnr_replacements = {}
if (ORIG_HOST and NEW_HOST):
tns_replacements[ORIG_HOST] = NEW_HOST
lsnr_replacements[ORIG_HOST] = NEW_HOST
# update tnsnames
if tns_replacements:
if not os.path.exists(tns_path):
logging.warn("tnsnames.ora not found at " + tns_path + " - cannot modify")
else:
# backup tnsnames
timestr = time.strftime("%Y%m%d-%H%M%S")
installCommand = "\"" + "cp " + tns_path + " " + tns_path + "." + timestr + "\""
commerce_setup_helper.exec_as_user(INSTALL_OWNER, installCommand)
commerce_setup_helper.substitute_file_fields(tns_path, tns_path, tns_replacements)
# update listener
if lsnr_replacements:
if not os.path.exists(lsnr_path):
logging.warn("listener.ora not found at " + lsnr_path + " - cannot modify")
else:
# backup listener
timestr = time.strftime("%Y%m%d-%H%M%S")
installCommand = "\"" + "cp " + lsnr_path + " " + lsnr_path + "." + timestr + "\""
commerce_setup_helper.exec_as_user(INSTALL_OWNER, installCommand)
commerce_setup_helper.substitute_file_fields(lsnr_path, lsnr_path, tns_replacements)
# update db name
orig_db_name = ORACLE_HOME + "/" + ORIG_HOST + "_" + ORACLE_SID
new_db_name = ORACLE_HOME + "/" + NEW_HOST + "_" + ORACLE_SID
if not os.path.exists(orig_db_name):
logging.error("db path not found at " + orig_db_name + " - cannot modify")
else:
mv_cmd = "\"" + "mv " + orig_db_name + " " + new_db_name + "\""
commerce_setup_helper.exec_as_user(INSTALL_OWNER, mv_cmd)
# update db console
if (UPDATE_DB_CONSOLE == "true") :
PORT = jsonData['lsnrPort']
ORACLE_PW = jsonData['adminPW']
orig_db_console = ORACLE_HOME + "/oc4j/j2ee/OC4J_DBConsole_" + ORIG_HOST + "_" + ORACLE_SID
new_db_console = ORACLE_HOME + "/oc4j/j2ee/OC4J_DBConsole_" + NEW_HOST + "_" + ORACLE_SID
if not os.path.exists(orig_db_console):
logging.warn("db console not found at " + orig_db_console + " - cannot modify")
else:
mv_cmd = "\"" + "mv " + orig_db_console + " " + new_db_console + "\""
commerce_setup_helper.exec_as_user(INSTALL_OWNER, mv_cmd)
# db must be running for emca to exec. make sure
# start db
commerce_setup_helper.exec_cmd(start_db_cmd)
emca_params = "-SID " + ORACLE_SID + " -PORT " + PORT + " -SYS_PWD " + ORACLE_PW + " -SYSMAN_PWD " + ORACLE_PW + " -DBSNMP_PWD " + ORACLE_PW
drop_repo_cmd = "\"" + ORACLE_HOME + "/bin/emca -deconfig dbcontrol db -repos drop -silent " + emca_params + "\""
create_repo_cmd = "\"" + ORACLE_HOME + "/bin/emca -config dbcontrol db -repos create -silent " + emca_params + "\""
commerce_setup_helper.exec_as_user(INSTALL_OWNER, drop_repo_cmd)
commerce_setup_helper.exec_as_user(INSTALL_OWNER, create_repo_cmd)
# stop db
commerce_setup_helper.exec_cmd(stop_db_cmd)
# stop console
commerce_setup_helper.exec_cmd(stop_db_console_cmd)
# start db
commerce_setup_helper.exec_cmd(start_db_cmd)
if (UPDATE_DB_CONSOLE == "true") :
# start dbconsole
commerce_setup_helper.exec_cmd(start_db_console_cmd)
| common-python/oc_provisioning/oc_provision_wrappers/database/v11g/oracle_rdbms_clone.py | 6,399 | The MIT License (MIT) Copyright (c) 2016 Oracle 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. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ stop db stop console update tnsnames backup tnsnames update listener backup listener update db name update db console db must be running for emca to exec. make sure start db stop db stop console start db start dbconsole | 1,465 | en | 0.725242 |
# Copyright 2017 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
"""Define tflite op hints (intrinsic operations).
This essentially allows defining a TensorFlow API for tflite operations in
Python with hints on how they are represented in TensorFlow Lite. This basically
is a form of tflite intrinsic. It wraps a subpart of a TensorFlow execution
graph and is useful for LSTMs and other complicated TensorFlow constructions
that are difficult to pattern match in TOCO, but are represented by a single
accelerated tflite op.
Example:
def tflite_cool_activation(input):
# A cool activation function.
custom = tf.contrib.lite.OpHint("cool_activation")
input = custom.add_inputs(input)
output = tf.sigmoid(input) * input
custom.add_outputs(output)
return output
image = tf.placeholder(tf.float32, (1, 16, 16, 1))
output = tf.identity(tflite_cool_activation(image))
session = tf.Session()
graphdef_to_convert = tf.contrib.lite.convert_op_hints_to_stubs(session)
tflite_graph = tf.contrib.lite.toco_convert(graphdef_to_convert,
[image], [output])
[image], [output])
with open("/tmp/graph.fb", "wb") as fp:
fp.write(tflite_graph)
How does it work?:
OpHint is a helper that you use when defining a vanilla python function.
It allows you to wrap arguments with tf.identities with some custom attributes.
These attributes allow you to find the original block of ops that was created.
For example, if you use cool_activation above you essentially get:
a_input = tf.identity()
result = tf.multiply(tf.sigmoid(a_input), a_input)
output = tf.identity()
a_input, output are identities that have parameters representing
what argument they are, what the name of the function they should turn into
in tf lite as well as a guid that uniquely identifies a particular invocation.
Once you have built your whole tensorflow graph, you can run it and train it
as usual, but after you have done that, you need to convert the graph into
a form that replaces these subgraphs wrapped in identities to stub ops. These
ops don't actually exist in the normal TensorFlow runtime, but will be
understood by toco later.
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import collections as _collections
import itertools as _itertools
import uuid as _uuid
from tensorflow.contrib import framework as _framework
from tensorflow.core.framework import attr_value_pb2 as _attr_value_pb2
from tensorflow.python.framework import ops as _ops
from tensorflow.python.ops import array_ops as _array_ops
from tensorflow.python.util.all_util import remove_undocumented
class OpHint(object):
"""A class that helps build tflite function invocations.
It allows you to take a bunch of TensorFlow ops and annotate the construction
such that toco knows how to convert it to tflite. This embeds a pseudo
function in a TensorFlow graph. This allows embedding high-level API usage
information in a lower level TensorFlow implementation so that an alternative
implementation can be substituted later.
Essentially, any "input" into this pseudo op is fed into an identity, and
attributes are added to that input before being used by the constituent ops
that make up the pseudo op. A similar process is done to any output that
is to be exported from the current op.
TODO(aselle): When TensorFlow functions functionality works for arbitrary
constructs, this mechanism can be retired and changed to use python defun's.
"""
# Attr constants that are used for representation in the GraphDef
FUNCTION_NAME_ATTR = "_tflite_function_name"
FUNCTION_UUID_ATTR = "_tflite_function_uuid"
FUNCTION_INPUT_INDEX_ATTR = "_tflite_function_input_index"
FUNCTION_OUTPUT_INDEX_ATTR = "_tflite_function_output_index"
def __init__(self, function_name, **kwargs):
"""Create a OpHint.
Args:
function_name: Name of the function (the custom op name in tflite)
**kwargs: Keyword arguments of any constant attributes for the function.
"""
self._function_name = function_name
self._unique_function_id = _uuid.uuid1().hex # TODO(aselle): Unique enough?
self._curr_input_index = 0
self._curr_output_index = 0
self._attrs_to_store_later = kwargs
self._stored_attrs = False
def _setattr(self, dest_op, name, value):
tensor_value = _ops.convert_to_tensor(value)
# pylint: disable=protected-access
dest_op.op._set_attr(name, _attr_value_pb2.AttrValue(
tensor=tensor_value.op.node_def.attr["value"].tensor))
# pylint: enable=protected-access
def add_inputs(self, *args):
"""Add a sequence of inputs to the function invocation.
Args:
*args: List of inputs to be converted (should be Tf.Tensor).
Returns:
Wrapped inputs (identity standins that have additional metadata). These
are also are also tf.Tensor's.
"""
def augmented_identity(arg):
identity_op = _array_ops.identity(arg)
# pylint: disable=protected-access
identity_op.op._set_attr(
OpHint.FUNCTION_NAME_ATTR,
_attr_value_pb2.AttrValue(s=self._function_name))
identity_op.op._set_attr(
OpHint.FUNCTION_UUID_ATTR,
_attr_value_pb2.AttrValue(s=self._unique_function_id))
identity_op.op._set_attr(
OpHint.FUNCTION_INPUT_INDEX_ATTR,
_attr_value_pb2.AttrValue(i=self._curr_input_index))
# pylint: enable=protected-access
self._curr_input_index += 1
return identity_op
return [augmented_identity(arg) for arg in args]
def add_outputs(self, *args):
"""Add a sequence of outputs to the function invocation.
Args:
*args: List of outputs to be converted (should be tf.Tensor).
Returns:
Wrapped outputs (identity standins that have additional metadata). These
are also tf.Tensor's.
"""
def augmented_identity(arg):
identity_op = _array_ops.identity(arg)
# pylint: disable=protected-access
identity_op.op._set_attr(
OpHint.FUNCTION_NAME_ATTR,
_attr_value_pb2.AttrValue(s=self._function_name))
identity_op.op._set_attr(
OpHint.FUNCTION_UUID_ATTR,
_attr_value_pb2.AttrValue(s=self._unique_function_id))
identity_op.op._set_attr(
OpHint.FUNCTION_OUTPUT_INDEX_ATTR,
_attr_value_pb2.AttrValue(i=self._curr_output_index))
# pylint: enable=protected-access
self._curr_output_index += 1
return identity_op
wrapped_outputs = [augmented_identity(arg) for arg in args]
if not self._stored_attrs:
for key, value in self._attrs_to_store_later.iteritems():
self._setattr(wrapped_outputs[0], "_tflite_attr_" + key, value)
self._stored_attrs = True
return wrapped_outputs
class _LiteFuncCall(object):
"""Represent a TensorFlow Lite custom function.
This is uses to accumulate found hints in the graphdef into a single
conceptual unit.
Properties:
self.inputs: inputs to the op (hash from index # to argument)
self.outputs: outputs to the op (hash from index # to argument)
self.function_name: the tflite custom op name to use
self.uuid: a unique call id for this particular call (i.e.
multiple function calls would have the same function_name but different
uuids.
self.params: A param name to key value for op constant data. I.e. for
axis on a reduction, strides on a convolution, etc.
"""
def __init__(self):
self.inputs = {}
self.outputs = {}
self.function_name = None
self.uuid = None
self.params = {}
def __str__(self):
return "tflite function %s call %s\n\tinputs: %r\n\toutputs: %r" % (
self.function_name, self.uuid, self.inputs, self.outputs)
def _find_all_hints_in_graph_def(session):
"""Look at the current default graph and return a list of LiteFuncCall objs.
Args:
session: A TensorFlow session that contains the graph to convert.
Returns:
a list of `LifeFuncCall` objects in the form
"""
func_calls = _collections.defaultdict(_LiteFuncCall)
seen_ops = set()
for op in session.graph.get_operations():
for operand in _itertools.chain(op.inputs, op.outputs):
if operand in seen_ops:
continue
seen_ops.add(operand)
attr = operand.op.node_def.attr
uuid = attr[OpHint.FUNCTION_UUID_ATTR].s
if OpHint.FUNCTION_UUID_ATTR not in attr:
continue
call_def = func_calls[uuid]
call_def.uuid = uuid
if OpHint.FUNCTION_UUID_ATTR in attr:
call_def.function_name = attr[OpHint.FUNCTION_NAME_ATTR].s
if OpHint.FUNCTION_INPUT_INDEX_ATTR in attr:
call_def.inputs[attr[OpHint.FUNCTION_INPUT_INDEX_ATTR].i] = operand
if OpHint.FUNCTION_OUTPUT_INDEX_ATTR in attr:
call_def.outputs[attr[OpHint.FUNCTION_OUTPUT_INDEX_ATTR].i] = operand
for a in attr:
if a.startswith("_tflite_attr_"):
# TODO(aselle): Remember the attribute tensors so we can put them
# in collapse.
call_def.params[a.replace("_tflite_attr_,", "")] = attr[a].tensor
return func_calls
def _tensor_name_base(full_tensor_name):
"""Removes the device assignment code from a tensor.
e.g. _tensor_name_base("foo:3") => "foo"
Args:
full_tensor_name: A tensor name that is annotated with a device placement
(this is what tensor flow introspection gives).
Returns:
A name without any device assignment.
"""
return full_tensor_name.name.split(":")[0]
def convert_op_hints_to_stubs(session):
"""Converts a graphdef with LiteOp hints into stub operations.
This is used to prepare for toco conversion of complex intrinsic usages.
Args:
session: A TensorFlow session that contains the graph to convert.
Returns:
A new graphdef with all ops contained in OpHints being replaced by
a single op call with the right parameters.
"""
hints = _find_all_hints_in_graph_def(session)
current_graph_def = session.graph_def
for call in hints.values():
input_names = [None] * len(call.inputs)
output_names = [None] * len(call.outputs)
output_dtypes = [None] * len(call.outputs)
output_quantized = False
for input_index, tensor in call.inputs.items():
input_names[input_index] = _tensor_name_base(tensor)
for output_index, tensor in call.outputs.items():
output_names[output_index] = _tensor_name_base(tensor)
output_dtypes[output_index] = tensor.dtype.as_datatype_enum
# TODO(aselle): Support quantized flag properly
current_graph_def = _framework.fuse_op(
current_graph_def, input_names, output_names, output_dtypes,
output_quantized, call.uuid, call.function_name)
for node in current_graph_def.node:
if node.name == call.uuid:
for param, tensor in call.params.items():
node.attr[param].tensor.CopyFrom(tensor)
return current_graph_def
_allowed_symbols = ["OpHint", "convert_op_hints_to_stubs"]
remove_undocumented(__name__, _allowed_symbols)
| tensorflow/contrib/lite/python/op_hint.py | 11,740 | A class that helps build tflite function invocations.
It allows you to take a bunch of TensorFlow ops and annotate the construction
such that toco knows how to convert it to tflite. This embeds a pseudo
function in a TensorFlow graph. This allows embedding high-level API usage
information in a lower level TensorFlow implementation so that an alternative
implementation can be substituted later.
Essentially, any "input" into this pseudo op is fed into an identity, and
attributes are added to that input before being used by the constituent ops
that make up the pseudo op. A similar process is done to any output that
is to be exported from the current op.
TODO(aselle): When TensorFlow functions functionality works for arbitrary
constructs, this mechanism can be retired and changed to use python defun's.
Represent a TensorFlow Lite custom function.
This is uses to accumulate found hints in the graphdef into a single
conceptual unit.
Properties:
self.inputs: inputs to the op (hash from index # to argument)
self.outputs: outputs to the op (hash from index # to argument)
self.function_name: the tflite custom op name to use
self.uuid: a unique call id for this particular call (i.e.
multiple function calls would have the same function_name but different
uuids.
self.params: A param name to key value for op constant data. I.e. for
axis on a reduction, strides on a convolution, etc.
Create a OpHint.
Args:
function_name: Name of the function (the custom op name in tflite)
**kwargs: Keyword arguments of any constant attributes for the function.
Look at the current default graph and return a list of LiteFuncCall objs.
Args:
session: A TensorFlow session that contains the graph to convert.
Returns:
a list of `LifeFuncCall` objects in the form
Removes the device assignment code from a tensor.
e.g. _tensor_name_base("foo:3") => "foo"
Args:
full_tensor_name: A tensor name that is annotated with a device placement
(this is what tensor flow introspection gives).
Returns:
A name without any device assignment.
Add a sequence of inputs to the function invocation.
Args:
*args: List of inputs to be converted (should be Tf.Tensor).
Returns:
Wrapped inputs (identity standins that have additional metadata). These
are also are also tf.Tensor's.
Add a sequence of outputs to the function invocation.
Args:
*args: List of outputs to be converted (should be tf.Tensor).
Returns:
Wrapped outputs (identity standins that have additional metadata). These
are also tf.Tensor's.
Converts a graphdef with LiteOp hints into stub operations.
This is used to prepare for toco conversion of complex intrinsic usages.
Args:
session: A TensorFlow session that contains the graph to convert.
Returns:
A new graphdef with all ops contained in OpHints being replaced by
a single op call with the right parameters.
Define tflite op hints (intrinsic operations).
This essentially allows defining a TensorFlow API for tflite operations in
Python with hints on how they are represented in TensorFlow Lite. This basically
is a form of tflite intrinsic. It wraps a subpart of a TensorFlow execution
graph and is useful for LSTMs and other complicated TensorFlow constructions
that are difficult to pattern match in TOCO, but are represented by a single
accelerated tflite op.
Example:
def tflite_cool_activation(input):
# A cool activation function.
custom = tf.contrib.lite.OpHint("cool_activation")
input = custom.add_inputs(input)
output = tf.sigmoid(input) * input
custom.add_outputs(output)
return output
image = tf.placeholder(tf.float32, (1, 16, 16, 1))
output = tf.identity(tflite_cool_activation(image))
session = tf.Session()
graphdef_to_convert = tf.contrib.lite.convert_op_hints_to_stubs(session)
tflite_graph = tf.contrib.lite.toco_convert(graphdef_to_convert,
[image], [output])
[image], [output])
with open("/tmp/graph.fb", "wb") as fp:
fp.write(tflite_graph)
How does it work?:
OpHint is a helper that you use when defining a vanilla python function.
It allows you to wrap arguments with tf.identities with some custom attributes.
These attributes allow you to find the original block of ops that was created.
For example, if you use cool_activation above you essentially get:
a_input = tf.identity()
result = tf.multiply(tf.sigmoid(a_input), a_input)
output = tf.identity()
a_input, output are identities that have parameters representing
what argument they are, what the name of the function they should turn into
in tf lite as well as a guid that uniquely identifies a particular invocation.
Once you have built your whole tensorflow graph, you can run it and train it
as usual, but after you have done that, you need to convert the graph into
a form that replaces these subgraphs wrapped in identities to stub ops. These
ops don't actually exist in the normal TensorFlow runtime, but will be
understood by toco later.
Copyright 2017 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ============================================================================== Attr constants that are used for representation in the GraphDef TODO(aselle): Unique enough? pylint: disable=protected-access pylint: enable=protected-access pylint: disable=protected-access pylint: enable=protected-access pylint: disable=protected-access pylint: enable=protected-access TODO(aselle): Remember the attribute tensors so we can put them in collapse. TODO(aselle): Support quantized flag properly | 6,109 | en | 0.806004 |
#!/usr/bin/python
# vim:fileencoding=utf-8
#
# Lookup for MX and NS records
#
import unbound
ctx = unbound.ub_ctx()
ctx.resolvconf("/etc/resolv.conf")
status, result = ctx.resolve("nic.cz", unbound.RR_TYPE_MX, unbound.RR_CLASS_IN)
if status == 0 and result.havedata:
print "Result:"
print " raw data:", result.data
for k in result.data.mx_list:
print " priority:%d address:%s" % k
status, result = ctx.resolve("nic.cz", unbound.RR_TYPE_A, unbound.RR_CLASS_IN)
if status == 0 and result.havedata:
print "Result:"
print " raw data:", result.data
for k in result.data.address_list:
print " address:%s" % k
status, result = ctx.resolve("nic.cz", unbound.RR_TYPE_NS, unbound.RR_CLASS_IN)
if status == 0 and result.havedata:
print "Result:"
print " raw data:", result.data
for k in result.data.domain_list:
print " host: %s" % k
| external/unbound/libunbound/python/doc/examples/example8-1.py | 918 | !/usr/bin/python vim:fileencoding=utf-8 Lookup for MX and NS records | 68 | en | 0.617261 |
#!/usr/bin/python3
import sys
import os
import shutil
import csv
import zipfile
import pandas as pd
import glob
infile = sys.argv[1]
outfile = sys.argv[2]
# remove holding_folder if it exists, and create new folder
# use 'rm -r /holding_folder/* in shell script instead?'
holding_path = '/media/secure_volume/holding_folder'
if os.path.isdir(holding_path):
shutil.rmtree(holding_path)
os.mkdir(holding_path)
def extract(infile):
'''
Merges bioindex.tsv with the infile (balanced data),
finds the volsplit.zip location for each bio file and
extracts the files into secure_volume/holding_folder.
'''
bioindex = pd.read_csv('/media/secure_volume/index/bioindex.tsv', sep='\t')
balanced_bioindex = pd.read_table(infile)
for suffix in balanced_bioindex.filesuffix.unique():
volsplit_file = 'volsplit'+str(suffix)+'.zip'
volsplit_df = balanced_bioindex.loc[balanced_bioindex.filesuffix == suffix,:]
try:
with zipfile.ZipFile('/media/secure_volume/'+volsplit_file, 'r') as myzip:
for idx, row in volsplit_df.iterrows():
filename = row['mainid']+'.zip'
myzip.extract(filename, '/media/secure_volume/holding_folder')
except Exception as e:
print('ERROR:',filename,'not found in',volsplit_file,'!', e)
def slicer(outfile):
idx_file_path = '/media/secure_volume/index/bioindex.tsv'
holding_folder_path = '/media/secure_volume/holding_folder/'
bio_idx_df = pd.read_table(idx_file_path)
bio_idx_df.set_index('mainid', inplace = True)
mainid_list = [vol for vol in os.listdir(holding_folder_path) if vol.endswith('.zip')]
# remove '.zip' from file names
mainid_list_clean = [item[0:-4] for item in mainid_list]
#subset bioindex on holding_folder IDs
htid_series = bio_idx_df.htid[mainid_list_clean]
file_path_list = glob.glob(holding_folder_path+'*.zip')
# print('file path list has: ',len(file_path_list))
# print('htid_list has', len(htid_list))
slice_df = pd.DataFrame(htid_series)
slice_df['path'] = file_path_list
slice_df['c'] = 0
slice_df['d'] = 1001
with open(outfile, 'w') as outf:
slice_df.to_csv(outfile, sep='\t', header=False, index=False)
print("Wrote", len(slice_df), "rows to", outfile)
extract(infile)
slicer(outfile)
| code/extract_balanced.py | 2,383 | Merges bioindex.tsv with the infile (balanced data),
finds the volsplit.zip location for each bio file and
extracts the files into secure_volume/holding_folder.
!/usr/bin/python3 remove holding_folder if it exists, and create new folder use 'rm -r /holding_folder/* in shell script instead?' remove '.zip' from file namessubset bioindex on holding_folder IDs print('file path list has: ',len(file_path_list)) print('htid_list has', len(htid_list)) | 449 | en | 0.572134 |
#Faça um algoritmo utilizando o comando while que mostra uma
#contagem regressiva na tela, iniciando em 10 e terminando
#em O. Mostrar uma mensagem “FIM!" após a contagem.
i=11
while(i!=0):
i-=1
print(i)
print("FIM") | exercicios/Lista3/Q3.py | 228 | Faça um algoritmo utilizando o comando while que mostra umacontagem regressiva na tela, iniciando em 10 e terminandoem O. Mostrar uma mensagem “FIM!" após a contagem. | 166 | pt | 0.991115 |
# Columbus - A Smart Navigation System for the Visually-Impaired
# Ike Kilinc
# This file integrates Columbus' primary start location and destination input
# features with its core pathfinding algorithm. This file also facilitates
# Columbus' speech recognition and audio functionalities.
from speech_to_text import *
from node_mapper import *
from path_finder import *
#####################################################################
#####################################################################
def run():
# Columbus asks what the user would like to do (with help option). directions, popular dests, directions
pathMode = startupModeSelection()
if pathMode == "specificDestination":
# User inputs destination.
destination = destinationInput()
startLocation = startLocationInput()
elif pathMode == "nearestRestroom":
# Columbus asks where user is (TEMP).
startLocation = startLocationInput()
# Columbus finds nearest Restroom and sets as destination
destination = None
elif pathMode == "nearestPrinter":
# Columbus asks where user is (TEMP).
startLocation = startLocationInput()
# Columbus finds nearest Printer and sets as destination
destination = None
elif pathMode == "popularDestinations":
# Columbus gives user choice options of popular destinations.
# Sets user input as the destination.
destination = popularLocationsInput(data)
startLocation = startLocationInput()
elif pathMode == "savedDestinations":
# Columbus gives user choice of previously saved destinations and sets
# user input as the destination.
destination = savedLocationsInput(data)
startLocation = startLocationInput()
elif pathMode == "findGod":
pass
# Columbus searches for and determines path to destination.
nodesPath = pathFinder(startLocation, destination, pathMode)
#####################################################################
#####################################################################
class Segment(object):
def __init__(self, startCoords, endCoords, segNumber, isActive, isFloorChange):
self.segmentBounds = (startCoords[0], startCoords[1], endCoords[0], endCoords[1])
self.floor = startCoords[2]
self.segNumber = segNumber
self.isActive = isActive
self.isFloorChange = isFloorChange
# self.direction = direction
def __repr__(self):
return str(self.segNumber)
def __hash__(self):
return hash(self.segNumber)
def getSegBounds(self):
return self.segmentBounds
def getSegNum(self):
return self.segNumber
def getSegFloor(self):
return self.floor
def getIsActive(self):
return self.isActive
def getIsFloorChange(self):
return self.isFloorChange
def getCenter(self):
centerX = (self.segmentBounds[0] + self.segmentBounds[2])/2
centerY = (self.segmentBounds[1] + self.segmentBounds[3])/2
return (centerX, centerY)
def getSegmentDirection(self):
(x0,y0,x1,y1) = self.segmentBounds
if (x1-x0) > 0: return "E"
elif (x1-x0) < 0: return "W"
elif (y1-y0) > 0: return "S"
elif (y1-y0) < 0: return "N"
else: return None
def createAllSegments(nodesPath):
allSegments = []
isFloorChange = False
intNodesPath = []
for i in range(len(nodesPath)):
node = nodesPath[i]
if (isinstance(node, Intersection) or isinstance(node, Elevator) or
i==0 or i==(len(nodesPath)-1)):
intNodesPath.append(node)
for i in range(len(intNodesPath)-1):
(node, nextNode) = (intNodesPath[i], intNodesPath[i+1])
if (isinstance(node, Elevator) and isinstance(nextNode, Elevator)):
isFloorChange = True
segment = Segment(node.getCoords(), nextNode.getCoords(), i, False, isFloorChange)
isFloorChange = False
allSegments.append(segment)
allSegments.append(Segment(intNodesPath[-1].getCoords(), intNodesPath[-1].getCoords(), i, False, False))
return allSegments
#####################################################################
#####################################################################
def startupModeSelection(repeat=False):
# Used to select mode for operating Columbus. Mode options include:
# Finding directions to a specific destination, directions to the nearest
# restroom, directions to popular destinations, and directions to previously
# saved destinations.
if repeat == True:
play("voiceCommands/sorryPleaseRepeat.wav")
else:
play("voiceCommands/modeSelectionInputPrompt.wav")
userInput = recognizeSpeech("mode")
if userInput == "help":
play("voiceCommands/modeSelectionHelp.wav")
userInput = recognizeSpeech("mode")
if userInput in ["nearestRestroom", "popularDestinations",
"savedDestinations", "nearestPrinter",
"specificDestination", "findGod", "help"]:
return userInput
else:
return startupModeSelection(True)
def destinationInput(repeat=False):
if repeat==True:
play("voiceCommands/sorryPleaseRepeat.wav")
else:
# Columbus asks where user would like to go.
play("voiceCommands/destinationInputPrompt.wav")
# User inputs destination
destination = recognizeSpeech("location")
if isLegalNode(destination):
return destination
else:
return destinationInput(True)
def startLocationInput(repeat=False):
if repeat==True:
play("voiceCommands/sorryPleaseRepeat.wav")
else:
# Columbus asks where user is now.
play("voiceCommands/startLocationInputPrompt.wav")
# User inputs start location.
startLocation = recognizeSpeech("location")
if isLegalNode(startLocation):
return startLocation
else:
return startLocationInput(True)
def popularLocationsInput(data, repeat=False):
print("popLocsInput")
if repeat==True:
play("voiceCommands/sorryPleaseRepeat.wav")
else:
# Columbus asks where user would like to go.
play("voiceCommands/destinationInputPromptWithHelp.wav")
userInput = recognizeSpeech("popularDest")
if userInput == "help":
play("voiceCommands/popularLocationSelectionHelp.wav")
userInput = recognizeSpeech("popularDest")
if userInput in ["5Prima", "4Sorrells"]:
return userInput
else:
return popularLocationsInput(data, True)
def savedLocationsInput(data, repeat=False):
if len(data.savedLocations) == 0:
play("voiceCommands/noSavedDestinations.wav")
else:
if repeat==True:
play("voiceCommands/sorryPleaseRepeat.wav")
else:
# Columbus asks where user would like to go.
play("voiceCommands/destinationInputPromptWithHelp.wav")
userInput = recognizeSpeech("savedDest")
if userInput == "help":
play("voiceCommands/modeSelectionHelp.wav")
userInput = recognizeSpeech("savedDest")
if userInput in data.savedLocations:
return userInput
else:
return savedLocationsInput(data, True)
def isLegalNode(string):
allNodesMap = mapAllNodes()
for floor in allNodesMap:
for roomStr in allNodesMap[floor]:
if string == roomStr:
return True
return False
| main_algo.py | 7,570 | Columbus - A Smart Navigation System for the Visually-Impaired Ike Kilinc This file integrates Columbus' primary start location and destination input features with its core pathfinding algorithm. This file also facilitates Columbus' speech recognition and audio functionalities. Columbus asks what the user would like to do (with help option). directions, popular dests, directions User inputs destination. Columbus asks where user is (TEMP). Columbus finds nearest Restroom and sets as destination Columbus asks where user is (TEMP). Columbus finds nearest Printer and sets as destination Columbus gives user choice options of popular destinations. Sets user input as the destination. Columbus gives user choice of previously saved destinations and sets user input as the destination. Columbus searches for and determines path to destination. self.direction = direction Used to select mode for operating Columbus. Mode options include: Finding directions to a specific destination, directions to the nearest restroom, directions to popular destinations, and directions to previously saved destinations. Columbus asks where user would like to go. User inputs destination Columbus asks where user is now. User inputs start location. Columbus asks where user would like to go. Columbus asks where user would like to go. | 1,317 | en | 0.931265 |
# ----------------------------------------------------------------------------
# Copyright (c) 2016-2018, QIIME 2 development team.
#
# Distributed under the terms of the Modified BSD License.
#
# The full license is in the file LICENSE, distributed with this software.
# ----------------------------------------------------------------------------
import unittest
from q2_emperor.plugin_setup import plugin as emperor_plugin
class PluginSetupTests(unittest.TestCase):
def test_plugin_setup(self):
self.assertEqual(emperor_plugin.name, 'emperor')
| q2_emperor/tests/test_plugin_setup.py | 564 | ---------------------------------------------------------------------------- Copyright (c) 2016-2018, QIIME 2 development team. Distributed under the terms of the Modified BSD License. The full license is in the file LICENSE, distributed with this software. ---------------------------------------------------------------------------- | 334 | en | 0.564752 |
"""
Generate configuration files into :ref:`generated_dir<directories>`.
"""
from fabric.api import task
from gusset.output import status
from gusset.validation import with_validation
from confab.iter import iter_conffiles
@task
@with_validation
def generate(directory=None):
"""
Generate configuration files.
"""
for conffiles in iter_conffiles(directory):
status("Generating templates for '{environment}' and '{role}'",
environment=conffiles.environment,
role=conffiles.role)
conffiles.generate()
| confab/generate.py | 565 | Generate configuration files.
Generate configuration files into :ref:`generated_dir<directories>`. | 98 | en | 0.428521 |
from habit.habit_model import HabitHistory
from habit.complete_habit import complete
def test_overdue_habit(datasett):
"""
please note the 'double tt' for datasett. This stands to differentiate
the functional test data from the data used for unit tests.
habit 1 is the overdue habit since its added first in the func/conftest
module.
:param datasett: from func/conftest
:return:
"""
session = datasett
complete(1, session)
result = session.query(HabitHistory.broken_count).\
filter(HabitHistory.habitid == 1).all()
assert result == [(1,)]
def test_a_habit_due_for_completion(datasett):
"""
habit 2 is the due habit since its added second in the func/conftest
module.
:param datasett: from func/conftest
:return:
"""
session = datasett
complete(2, session)
result = session.query(HabitHistory.streak).\
filter(HabitHistory.habitid == 2).all()
assert result == [(1,)]
| tests/func/test_complete_habit.py | 974 | habit 2 is the due habit since its added second in the func/conftest
module.
:param datasett: from func/conftest
:return:
please note the 'double tt' for datasett. This stands to differentiate
the functional test data from the data used for unit tests.
habit 1 is the overdue habit since its added first in the func/conftest
module.
:param datasett: from func/conftest
:return: | 377 | en | 0.811299 |
#!/usr/bin/python3
"""Alta3 Research - Exploring OpenAPIs with requests"""
# documentation for this API is at
# https://anapioficeandfire.com/Documentation
import requests
AOIF = "https://www.anapioficeandfire.com/api"
def main():
## Send HTTPS GET to the API of ICE and Fire
gotresp = requests.get(AOIF)
## Decode the response
got_dj = gotresp.json()
## print the response
print(got_dj)
if __name__ == "__main__":
main()
| Day 6/iceAndFire01.py | 456 | Alta3 Research - Exploring OpenAPIs with requests
!/usr/bin/python3 documentation for this API is at https://anapioficeandfire.com/Documentation Send HTTPS GET to the API of ICE and Fire Decode the response print the response | 226 | en | 0.778368 |
# coding: utf-8
"""
OpenAPI Petstore
This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501
The version of the OpenAPI document: 1.0.0
Generated by: https://openapi-generator.tech
"""
from __future__ import absolute_import
import re # noqa: F401
import sys # noqa: F401
import six # noqa: F401
import nulltype # noqa: F401
from petstore_api.model_utils import ( # noqa: F401
ApiTypeError,
ModelComposed,
ModelNormal,
ModelSimple,
cached_property,
change_keys_js_to_python,
convert_js_args_to_python_args,
date,
datetime,
file_type,
int,
none_type,
str,
validate_get_composed_info,
)
class (ModelNormal):
"""NOTE: This class is auto generated by OpenAPI Generator.
Ref: https://openapi-generator.tech
Do not edit the class manually.
Attributes:
allowed_values (dict): The key is the tuple path to the attribute
and the for var_name this is (var_name,). The value is a dict
with a capitalized key describing the allowed value and an allowed
value. These dicts store the allowed enum values.
attribute_map (dict): The key is attribute name
and the value is json key in definition.
discriminator_value_class_map (dict): A dict to go from the discriminator
variable value to the discriminator class name.
validations (dict): The key is the tuple path to the attribute
and the for var_name this is (var_name,). The value is a dict
that stores validations for max_length, min_length, max_items,
min_items, exclusive_maximum, inclusive_maximum, exclusive_minimum,
inclusive_minimum, and regex.
additional_properties_type (tuple): A tuple of classes accepted
as additional properties values.
"""
allowed_values = {
}
validations = {
}
additional_properties_type = None
_nullable = False
@cached_property
def openapi_types():
"""
This must be a class method so a model may have properties that are
of type self, this ensures that we don't create a cyclic import
Returns
openapi_types (dict): The key is attribute name
and the value is attribute type.
"""
return {
}
@cached_property
def discriminator():
return None
attribute_map = {
}
_composed_schemas = {}
required_properties = set([
'_data_store',
'_check_type',
'_spec_property_naming',
'_path_to_item',
'_configuration',
'_visited_composed_classes',
])
@convert_js_args_to_python_args
def __init__(self, *args, **kwargs): # noqa: E501
"""OuterEnumIntegerDefaultValue - a model defined in OpenAPI
Keyword Args:
_check_type (bool): if True, values for parameters in openapi_types
will be type checked and a TypeError will be
raised if the wrong type is input.
Defaults to True
_path_to_item (tuple/list): This is a list of keys or values to
drill down to the model in received_data
when deserializing a response
_spec_property_naming (bool): True if the variable names in the input data
are serialized names, as specified in the OpenAPI document.
False if the variable names in the input data
are pythonic names, e.g. snake case (default)
_configuration (Configuration): the instance to use when
deserializing a file_type parameter.
If passed, type conversion is attempted
If omitted no type conversion is done.
_visited_composed_classes (tuple): This stores a tuple of
classes that we have traveled through so that
if we see that class again we will not use its
discriminator again.
When traveling through a discriminator, the
composed schema that is
is traveled through is added to this set.
For example if Animal has a discriminator
petType and we pass in "Dog", and the class Dog
allOf includes Animal, we move through Animal
once using the discriminator, and pick Dog.
Then in Dog, we will make an instance of the
Animal class but this time we won't travel
through its discriminator because we passed in
_visited_composed_classes = (Animal,)
"""
_check_type = kwargs.pop('_check_type', True)
_spec_property_naming = kwargs.pop('_spec_property_naming', False)
_path_to_item = kwargs.pop('_path_to_item', ())
_configuration = kwargs.pop('_configuration', None)
_visited_composed_classes = kwargs.pop('_visited_composed_classes', ())
if args:
raise ApiTypeError(
"Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % (
args,
self.__class__.__name__,
),
path_to_item=_path_to_item,
valid_classes=(self.__class__,),
)
self._data_store = {}
self._check_type = _check_type
self._spec_property_naming = _spec_property_naming
self._path_to_item = _path_to_item
self._configuration = _configuration
self._visited_composed_classes = _visited_composed_classes + (self.__class__,)
for var_name, var_value in six.iteritems(kwargs):
if var_name not in self.attribute_map and \
self._configuration is not None and \
self._configuration.discard_unknown_keys and \
self.additional_properties_type is None:
# discard variable.
continue
setattr(self, var_name, var_value)
| samples/openapi3/client/petstore/python-experimental/petstore_api/model/outer_enum_integer_default_value.py | 6,563 | coding: utf-8 noqa: F401 noqa: F401 noqa: F401 noqa: F401 noqa: F401 noqa: E501 discard variable. | 97 | en | 0.227221 |
from math import pi, sqrt
from typing import List
import numpy as np
import pytest
from src.kinematics.forward_kinematics import get_tform
from src.prechecks.spatial_interpolation import linear_interpolation, circular_interpolation
@pytest.mark.parametrize("start,end,ds,expected_points",
[
(
[[0, 0, 0], [0, 0, 0], [0, 0, 0], [0, 0, 0]],
[[0, 0, 0], [0, 0, 0], [0, 0, 0], [300, 0, 0]],
50,
7
),
(
[[0, 0, 0], [0, 0, 0], [0, 0, 0], [0, 0, 0]],
[[0, 0, 0], [0, 0, 0], [0, 0, 0], [50, 0, 0]],
50,
2
)
]
)
def test_linear_interpolation(start, end, ds, expected_points):
# Create the start and end point matrices
start = get_tform(*start)
end = get_tform(*end)
# Calculate the interpolated tforms
interpolated_tforms = list(linear_interpolation(start, end, ds=ds))
helper_spatial_interpolation_test(interpolated_tforms, start, end, expected_points)
# Check that the points are equidistant
if expected_points > 2:
for i in range(expected_points - 1):
ds_actual = np.linalg.norm(interpolated_tforms[i + 1][0:3, 3] - interpolated_tforms[i][0:3, 3])
assert pytest.approx(ds, rel=0.1) == ds_actual
@pytest.mark.parametrize("start,end,nvec,cw,ds,expected_points",
[
# XY plane half circle (start, intermediate, end)
(
[[1, 0, 0], [0, 1, 0], [0, 0, 1], [-1, 0, 0]],
[[1, 0, 0], [0, 1, 0], [0, 0, 1], [1, 0, 0]],
[0, 0, 1],
True,
pi / 2,
3
),
# XY plane half circle (start, end)
(
[[1, 0, 0], [0, 1, 0], [0, 0, 1], [-1, 0, 0]],
[[1, 0, 0], [0, 1, 0], [0, 0, 1], [1, 0, 0]],
[0, 0, 1],
True,
pi,
2
),
# XY plane half circle (start, end) rounded
(
[[1, 0, 0], [0, 1, 0], [0, 0, 1], [-1, 0, 0]],
[[1, 0, 0], [0, 1, 0], [0, 0, 1], [1, 0, 0]],
[0, 0, 1],
True,
pi / 2 * 1.1,
2
),
# XY plane half circle (start, end) rounded
(
[[1, 0, 0], [0, 1, 0], [0, 0, 1], [-1, 0, 0]],
[[1, 0, 0], [0, 1, 0], [0, 0, 1], [1, 0, 0]],
[0, 0, 1],
False,
pi / 5,
6
),
# XY plane 3/4 circle, five points
(
[[1, 0, 0], [0, 1, 0], [0, 0, 1], [-1, 0, 0]],
[[1, 0, 0], [0, 1, 0], [0, 0, 1], [0, -1, 0]],
[0, 0, 1],
True,
6 / 16 * pi,
5
),
# XY plane full circle, five points
(
[[1, 0, 0], [0, 1, 0], [0, 0, 1], [-1, 0, 0]],
[[1, 0, 0], [0, 1, 0], [0, 0, 1], [-1, 0, 0]],
[0, 0, 1],
False,
2 / 3 * pi,
4
),
# YZ plane 3/4 circle, five points
(
[[1, 0, 0], [0, 1, 0], [0, 0, 1], [0, -1, 0]],
[[1, 0, 0], [0, 1, 0], [0, 0, 1], [0, 0, -1]],
[1, 0, 0],
True,
6 / 16 * pi,
5
),
# XY plane half circle (start, end) rounded
(
[[1, 0, 0], [0, 1, 0], [0, 0, 1], [0, -0.5 * sqrt(2), 0.5 * sqrt(2)]],
[[1, 0, 0], [0, 1, 0], [0, 0, 1], [0, 0.5 * sqrt(2), -0.5 * sqrt(2)]],
[0, 1, 1],
False,
pi / 5,
6
)
]
)
def test_circular_interpolation(start, end, nvec, cw, ds, expected_points):
# Create the start and end point matrices
start = get_tform(*start)
end = get_tform(*end)
# Calculate the interpolated tforms
interpolated_tforms = list(circular_interpolation(start, end, [0, 0, 0], nvec, cw, ds=ds))
print(interpolated_tforms)
helper_spatial_interpolation_test(interpolated_tforms, start, end, expected_points)
# Check that the points all have distance of the radius to the center point
r = np.linalg.norm(start[0:3, 3])
for tform in interpolated_tforms:
assert pytest.approx(r, rel=0.01) == np.linalg.norm(tform[0:3, 3])
# Check that the points are equidistant
if expected_points > 3:
ds_straight_line_ref = np.linalg.norm(interpolated_tforms[1][0:3, 3] - interpolated_tforms[0][0:3, 3])
for i in range(1, expected_points - 1):
ds_actual = np.linalg.norm(interpolated_tforms[i + 1][0:3, 3] - interpolated_tforms[i][0:3, 3])
assert pytest.approx(ds_straight_line_ref, rel=0.1) == ds_actual
def helper_spatial_interpolation_test(interpolated_tforms: List[np.ndarray], start, end, expected_points):
# Test that the number of interpolated points is correct
assert len(interpolated_tforms) == expected_points
# Test that the start and end points are included
np.testing.assert_allclose(interpolated_tforms[0], start)
np.testing.assert_allclose(interpolated_tforms[-1], end)
| test/test_spatial_interpolation.py | 7,146 | Create the start and end point matrices Calculate the interpolated tforms Check that the points are equidistant XY plane half circle (start, intermediate, end) XY plane half circle (start, end) XY plane half circle (start, end) rounded XY plane half circle (start, end) rounded XY plane 3/4 circle, five points XY plane full circle, five points YZ plane 3/4 circle, five points XY plane half circle (start, end) rounded Create the start and end point matrices Calculate the interpolated tforms Check that the points all have distance of the radius to the center point Check that the points are equidistant Test that the number of interpolated points is correct Test that the start and end points are included | 708 | en | 0.852891 |
import csv
import six
import sys
import time
from datetime import (
datetime,
date,
timedelta,
)
from xml.etree import cElementTree as ElementTree
from django.core.management.base import BaseCommand
from corehq.apps.users.util import SYSTEM_USER_ID
from corehq.form_processor.backends.sql.dbaccessors import CaseAccessorSQL, CaseReindexAccessor
from corehq.form_processor.exceptions import CaseNotFound
from corehq.form_processor.interfaces.dbaccessors import CaseAccessors
from corehq.apps.locations.models import SQLLocation
from corehq.apps.hqcase.utils import submit_case_blocks
from corehq.form_processor.backends.sql.dbaccessors import iter_all_rows
from casexml.apps.case.mock import CaseBlock
DOMAIN = "icds-cas"
CASE_TYPE = "person"
CUT_OFF_AGE_IN_YEARS = 6
date_today = date.today()
CUT_OFF_DOB = str(date_today.replace(year=date_today.year - CUT_OFF_AGE_IN_YEARS))
DOB_PROPERTY = "dob"
MOTHER_NAME_PROPERTY = "mother_name"
MOTHER_INDEX_IDENTIFIER = "mother"
CASE_ITERATION_COUNT = 10000
MAX_RESCUE_EXCEPTIONS_ON_UPDATE = 5
CSV_HEADERS = ['Case ID', 'Mother Case ID', 'Mother Name']
class Command(BaseCommand):
help = """
Iterate person cases updated in last 100 days (3 months with buffer) in a single partition,
Find the ones which are
- not deleted
- not belonging to test locations,
- with age less than 6 years using dob case property,
- if there is related mother case, populate mother_name case property with it's name
Returns two lists of case ids, the ones updated and the ones that could not be updated
"""
def __init__(self, *args, **kwargs):
super(Command, self).__init__(*args, **kwargs)
self.db_alias = None
self.log_progress = False
self.test_locations = None
self.case_accessor = CaseAccessors(DOMAIN)
def add_arguments(self, parser):
parser.add_argument('db_alias')
parser.add_argument(
'--log',
action='store_true',
dest='log_progress',
default=False,
help="log progress"
)
def handle(self, db_alias, log_progress, **options):
self.db_alias = db_alias
self.log_progress = log_progress
self.test_locations = find_test_awc_locations()
filename = self._find_case_ids_without_mother_name()
if self.log_progress:
print('starting update now for cases')
self._update_cases(filename)
def _find_case_ids_without_mother_name(self):
start_date = date.today() - timedelta(days=100)
reindex_accessor = CaseReindexAccessor(
domain=DOMAIN,
case_type=CASE_TYPE, limit_db_aliases=[self.db_alias],
start_date=start_date
)
filename = 'cases_without_mother_name_part_%s_%s.csv' % (self.db_alias, datetime.utcnow())
cases_with_no_mother_name_filename = 'cases_with_no_mother_name_part_%s_%s.csv' % (
self.db_alias, datetime.utcnow())
with open(filename, 'w') as output:
with open(cases_with_no_mother_name_filename, 'w') as no_mother_name_file:
cases_iterated = 0
writer = csv.writer(output)
writer.writerow(CSV_HEADERS)
no_mother_name_writer = csv.writer(no_mother_name_file)
no_mother_name_writer.writerow(['Case ID'])
if self.log_progress:
print('iterating now')
for case in iter_all_rows(reindex_accessor):
if self.log_progress and cases_iterated % CASE_ITERATION_COUNT == 0:
print("cases iterated: %s" % cases_iterated)
cases_iterated += 1
if self._case_needs_to_be_updated(case):
mother_case_id, mother_name = self._find_mother_case_id_and_name(case)
if mother_case_id and mother_name:
writer.writerow([case.case_id, mother_case_id, mother_name])
else:
no_mother_name_writer.writerow([case.case_id])
return filename
def _find_mother_case_id_and_name(self, case):
mother_case_ids = [i.referenced_id for i in CaseAccessorSQL.get_indices(DOMAIN, case.case_id)
if i.identifier == MOTHER_INDEX_IDENTIFIER]
if len(mother_case_ids) == 1:
try:
mother_case = self.case_accessor.get_case(mother_case_ids[0])
except CaseNotFound:
pass
else:
return mother_case.case_id, mother_case.name
return None, None
def _case_needs_to_be_updated(self, case):
if case.deleted:
return False
assert case.type == CASE_TYPE
if bool(case.owner_id) and case.owner_id in self.test_locations:
return False
dob = case.get_case_property(DOB_PROPERTY)
if dob and dob > CUT_OFF_DOB and not case.get_case_property(MOTHER_NAME_PROPERTY):
return True
return False
def _update_cases(self, filename):
exceptions_raised = 0
updates = {} # case id: mother name
counter = 0
with open(filename, 'r') as _input:
reader = csv.DictReader(_input)
with open('cases_without_mother_name_part_%s_updated.csv' % self.db_alias, 'w') as output:
writer = csv.writer(output)
writer.writerow(['Case ID', 'Mother Name'])
for row in reader:
updates[row['Case ID']] = row['Mother Name']
counter += 1
if counter > 0 and counter % 100 == 0:
case_ids = self._reassured_case_ids_to_update(list(updates.keys()))
skip_ids = updates.keys() - case_ids
for case_id in skip_ids:
updates.pop(case_id)
for case_id, mother_name in updates.items():
writer.writerow([case_id, mother_name])
exceptions_raised = self._submit_update_form(updates, exceptions_raised)
if self.log_progress:
print("cases updated: %s" % counter)
updates = {}
counter = 0
# update the pending batch
for case_id, mother_name in updates.items():
writer.writerow([case_id, mother_name])
exceptions_raised = self._submit_update_form(updates, exceptions_raised)
def _submit_update_form(self, updates, exceptions_raised):
update_case_blocks = self.create_case_blocks(updates)
if not update_case_blocks:
return exceptions_raised
for attempt in range(MAX_RESCUE_EXCEPTIONS_ON_UPDATE):
try:
submit_case_blocks(update_case_blocks, DOMAIN, user_id=SYSTEM_USER_ID)
except Exception as e:
exc = sys.exc_info()
exceptions_raised += 1
if self.log_progress:
print("rescuing exception %s %s" % (exceptions_raised, str(e)))
if exceptions_raised > MAX_RESCUE_EXCEPTIONS_ON_UPDATE:
six.reraise(*exc)
else:
time.sleep(60) # wait for 1 min before trying again
else:
break
return exceptions_raised
def create_case_blocks(self, updates):
case_blocks = []
for case_id, mother_name in updates.items():
case_block = CaseBlock.deprecated_init(case_id,
update={MOTHER_NAME_PROPERTY: mother_name},
user_id=SYSTEM_USER_ID)
case_block = ElementTree.tostring(case_block.as_xml()).decode('utf-8')
case_blocks.append(case_block)
return case_blocks
def _reassured_case_ids_to_update(self, case_ids):
# reconfirm the cases before updating to avoid removing updates in between
# fetching case ids and updating
invalid_cases = self.case_accessor.get_cases(case_ids)
case_ids_list = set()
for invalid_case in invalid_cases:
if self._case_needs_to_be_updated(invalid_case):
case_ids_list.add(invalid_case.case_id)
return case_ids_list
def find_test_awc_locations():
test_locations = set()
for location in SQLLocation.active_objects.filter(location_type__code='state', domain=DOMAIN):
if location.metadata.get('is_test_location') == 'test':
test_locations.update(
location.get_descendants(include_self=True).
filter(location_type__code='awc').values_list('location_id', flat=True)
)
return test_locations
| custom/icds/management/commands/populate_mother_name.py | 8,913 | case id: mother name update the pending batch wait for 1 min before trying again reconfirm the cases before updating to avoid removing updates in between fetching case ids and updating | 184 | en | 0.813473 |
"""Class to manage the entities for a single platform."""
import asyncio
from homeassistant.const import DEVICE_DEFAULT_NAME
from homeassistant.core import callback, valid_entity_id, split_entity_id
from homeassistant.exceptions import HomeAssistantError, PlatformNotReady
from homeassistant.util.async_ import (
run_callback_threadsafe, run_coroutine_threadsafe)
from .event import async_track_time_interval, async_call_later
SLOW_SETUP_WARNING = 10
SLOW_SETUP_MAX_WAIT = 60
PLATFORM_NOT_READY_RETRIES = 10
class EntityPlatform:
"""Manage the entities for a single platform."""
def __init__(self, *, hass, logger, domain, platform_name, platform,
scan_interval, entity_namespace,
async_entities_added_callback):
"""Initialize the entity platform.
hass: HomeAssistant
logger: Logger
domain: str
platform_name: str
scan_interval: timedelta
entity_namespace: str
async_entities_added_callback: @callback method
"""
self.hass = hass
self.logger = logger
self.domain = domain
self.platform_name = platform_name
self.platform = platform
self.scan_interval = scan_interval
self.entity_namespace = entity_namespace
self.async_entities_added_callback = async_entities_added_callback
self.config_entry = None
self.entities = {}
self._tasks = []
# Method to cancel the state change listener
self._async_unsub_polling = None
# Method to cancel the retry of setup
self._async_cancel_retry_setup = None
self._process_updates = asyncio.Lock()
# Platform is None for the EntityComponent "catch-all" EntityPlatform
# which powers entity_component.add_entities
if platform is None:
self.parallel_updates = None
self.parallel_updates_semaphore = None
return
self.parallel_updates = getattr(platform, 'PARALLEL_UPDATES', None)
# semaphore will be created on demand
self.parallel_updates_semaphore = None
def _get_parallel_updates_semaphore(self):
"""Get or create a semaphore for parallel updates."""
if self.parallel_updates_semaphore is None:
self.parallel_updates_semaphore = asyncio.Semaphore(
self.parallel_updates if self.parallel_updates else 1,
loop=self.hass.loop
)
return self.parallel_updates_semaphore
async def async_setup(self, platform_config, discovery_info=None):
"""Set up the platform from a config file."""
platform = self.platform
hass = self.hass
@callback
def async_create_setup_task():
"""Get task to set up platform."""
if getattr(platform, 'async_setup_platform', None):
return platform.async_setup_platform(
hass, platform_config,
self._async_schedule_add_entities, discovery_info
)
# This should not be replaced with hass.async_add_job because
# we don't want to track this task in case it blocks startup.
return hass.loop.run_in_executor(
None, platform.setup_platform, hass, platform_config,
self._schedule_add_entities, discovery_info
)
await self._async_setup_platform(async_create_setup_task)
async def async_setup_entry(self, config_entry):
"""Set up the platform from a config entry."""
# Store it so that we can save config entry ID in entity registry
self.config_entry = config_entry
platform = self.platform
@callback
def async_create_setup_task():
"""Get task to set up platform."""
return platform.async_setup_entry(
self.hass, config_entry, self._async_schedule_add_entities)
return await self._async_setup_platform(async_create_setup_task)
async def _async_setup_platform(self, async_create_setup_task, tries=0):
"""Set up a platform via config file or config entry.
async_create_setup_task creates a coroutine that sets up platform.
"""
logger = self.logger
hass = self.hass
full_name = '{}.{}'.format(self.domain, self.platform_name)
logger.info("Setting up %s", full_name)
warn_task = hass.loop.call_later(
SLOW_SETUP_WARNING, logger.warning,
"Setup of platform %s is taking over %s seconds.",
self.platform_name, SLOW_SETUP_WARNING)
try:
task = async_create_setup_task()
await asyncio.wait_for(
asyncio.shield(task),
SLOW_SETUP_MAX_WAIT)
# Block till all entities are done
if self._tasks:
pending = [task for task in self._tasks if not task.done()]
self._tasks.clear()
if pending:
await asyncio.wait(
pending)
hass.config.components.add(full_name)
return True
except PlatformNotReady:
tries += 1
wait_time = min(tries, 6) * 30
logger.warning(
'Platform %s not ready yet. Retrying in %d seconds.',
self.platform_name, wait_time)
async def setup_again(now):
"""Run setup again."""
self._async_cancel_retry_setup = None
await self._async_setup_platform(
async_create_setup_task, tries)
self._async_cancel_retry_setup = \
async_call_later(hass, wait_time, setup_again)
return False
except asyncio.TimeoutError:
logger.error(
"Setup of platform %s is taking longer than %s seconds."
" Startup will proceed without waiting any longer.",
self.platform_name, SLOW_SETUP_MAX_WAIT)
return False
except Exception: # pylint: disable=broad-except
logger.exception(
"Error while setting up platform %s", self.platform_name)
return False
finally:
warn_task.cancel()
def _schedule_add_entities(self, new_entities, update_before_add=False):
"""Schedule adding entities for a single platform, synchronously."""
run_callback_threadsafe(
self.hass.loop,
self._async_schedule_add_entities, list(new_entities),
update_before_add
).result()
@callback
def _async_schedule_add_entities(self, new_entities,
update_before_add=False):
"""Schedule adding entities for a single platform async."""
self._tasks.append(self.hass.async_add_job(
self.async_add_entities(
new_entities, update_before_add=update_before_add)
))
def add_entities(self, new_entities, update_before_add=False):
"""Add entities for a single platform."""
# That avoid deadlocks
if update_before_add:
self.logger.warning(
"Call 'add_entities' with update_before_add=True "
"only inside tests or you can run into a deadlock!")
run_coroutine_threadsafe(
self.async_add_entities(list(new_entities), update_before_add),
self.hass.loop).result()
async def async_add_entities(self, new_entities, update_before_add=False):
"""Add entities for a single platform async.
This method must be run in the event loop.
"""
# handle empty list from component/platform
if not new_entities:
return
hass = self.hass
device_registry = await \
hass.helpers.device_registry.async_get_registry()
entity_registry = await \
hass.helpers.entity_registry.async_get_registry()
tasks = [
self._async_add_entity(entity, update_before_add,
entity_registry, device_registry)
for entity in new_entities]
# No entities for processing
if not tasks:
return
await asyncio.wait(tasks)
self.async_entities_added_callback()
if self._async_unsub_polling is not None or \
not any(entity.should_poll for entity
in self.entities.values()):
return
self._async_unsub_polling = async_track_time_interval(
self.hass, self._update_entity_states, self.scan_interval
)
async def _async_add_entity(self, entity, update_before_add,
entity_registry, device_registry):
"""Add an entity to the platform."""
if entity is None:
raise ValueError('Entity cannot be None')
entity.hass = self.hass
entity.platform = self
# Async entity
# PARALLEL_UPDATE == None: entity.parallel_updates = None
# PARALLEL_UPDATE == 0: entity.parallel_updates = None
# PARALLEL_UPDATE > 0: entity.parallel_updates = Semaphore(p)
# Sync entity
# PARALLEL_UPDATE == None: entity.parallel_updates = Semaphore(1)
# PARALLEL_UPDATE == 0: entity.parallel_updates = None
# PARALLEL_UPDATE > 0: entity.parallel_updates = Semaphore(p)
if hasattr(entity, 'async_update') and not self.parallel_updates:
entity.parallel_updates = None
elif (not hasattr(entity, 'async_update')
and self.parallel_updates == 0):
entity.parallel_updates = None
else:
entity.parallel_updates = self._get_parallel_updates_semaphore()
# Update properties before we generate the entity_id
if update_before_add:
try:
await entity.async_device_update(warning=False)
except Exception: # pylint: disable=broad-except
self.logger.exception(
"%s: Error on device update!", self.platform_name)
return
suggested_object_id = None
# Get entity_id from unique ID registration
if entity.unique_id is not None:
if entity.entity_id is not None:
suggested_object_id = split_entity_id(entity.entity_id)[1]
else:
suggested_object_id = entity.name
if self.entity_namespace is not None:
suggested_object_id = '{} {}'.format(
self.entity_namespace, suggested_object_id)
if self.config_entry is not None:
config_entry_id = self.config_entry.entry_id
else:
config_entry_id = None
device_info = entity.device_info
device_id = None
if config_entry_id is not None and device_info is not None:
processed_dev_info = {
'config_entry_id': config_entry_id
}
for key in (
'connections',
'identifiers',
'manufacturer',
'model',
'name',
'sw_version',
'via_hub',
):
if key in device_info:
processed_dev_info[key] = device_info[key]
device = device_registry.async_get_or_create(
**processed_dev_info)
if device:
device_id = device.id
entry = entity_registry.async_get_or_create(
self.domain, self.platform_name, entity.unique_id,
suggested_object_id=suggested_object_id,
config_entry_id=config_entry_id,
device_id=device_id,
known_object_ids=self.entities.keys())
if entry.disabled:
self.logger.info(
"Not adding entity %s because it's disabled",
entry.name or entity.name or
'"{} {}"'.format(self.platform_name, entity.unique_id))
return
entity.entity_id = entry.entity_id
entity.registry_name = entry.name
entity.async_on_remove(entry.add_update_listener(entity))
# We won't generate an entity ID if the platform has already set one
# We will however make sure that platform cannot pick a registered ID
elif (entity.entity_id is not None and
entity_registry.async_is_registered(entity.entity_id)):
# If entity already registered, convert entity id to suggestion
suggested_object_id = split_entity_id(entity.entity_id)[1]
entity.entity_id = None
# Generate entity ID
if entity.entity_id is None:
suggested_object_id = \
suggested_object_id or entity.name or DEVICE_DEFAULT_NAME
if self.entity_namespace is not None:
suggested_object_id = '{} {}'.format(self.entity_namespace,
suggested_object_id)
entity.entity_id = entity_registry.async_generate_entity_id(
self.domain, suggested_object_id, self.entities.keys())
# Make sure it is valid in case an entity set the value themselves
if not valid_entity_id(entity.entity_id):
raise HomeAssistantError(
'Invalid entity id: {}'.format(entity.entity_id))
if (entity.entity_id in self.entities or
entity.entity_id in self.hass.states.async_entity_ids(
self.domain)):
msg = 'Entity id already exists: {}'.format(entity.entity_id)
if entity.unique_id is not None:
msg += '. Platform {} does not generate unique IDs'.format(
self.platform_name)
raise HomeAssistantError(msg)
entity_id = entity.entity_id
self.entities[entity_id] = entity
entity.async_on_remove(lambda: self.entities.pop(entity_id))
await entity.async_added_to_hass()
await entity.async_update_ha_state()
async def async_reset(self):
"""Remove all entities and reset data.
This method must be run in the event loop.
"""
if self._async_cancel_retry_setup is not None:
self._async_cancel_retry_setup()
self._async_cancel_retry_setup = None
if not self.entities:
return
tasks = [self.async_remove_entity(entity_id)
for entity_id in self.entities]
await asyncio.wait(tasks)
if self._async_unsub_polling is not None:
self._async_unsub_polling()
self._async_unsub_polling = None
async def async_remove_entity(self, entity_id):
"""Remove entity id from platform."""
await self.entities[entity_id].async_remove()
# Clean up polling job if no longer needed
if (self._async_unsub_polling is not None and
not any(entity.should_poll for entity
in self.entities.values())):
self._async_unsub_polling()
self._async_unsub_polling = None
async def _update_entity_states(self, now):
"""Update the states of all the polling entities.
To protect from flooding the executor, we will update async entities
in parallel and other entities sequential.
This method must be run in the event loop.
"""
if self._process_updates.locked():
self.logger.warning(
"Updating %s %s took longer than the scheduled update "
"interval %s", self.platform_name, self.domain,
self.scan_interval)
return
async with self._process_updates:
tasks = []
for entity in self.entities.values():
if not entity.should_poll:
continue
tasks.append(entity.async_update_ha_state(True))
if tasks:
await asyncio.wait(tasks)
| homeassistant/helpers/entity_platform.py | 16,282 | Manage the entities for a single platform.
Initialize the entity platform.
hass: HomeAssistant
logger: Logger
domain: str
platform_name: str
scan_interval: timedelta
entity_namespace: str
async_entities_added_callback: @callback method
Schedule adding entities for a single platform async.
Get or create a semaphore for parallel updates.
Schedule adding entities for a single platform, synchronously.
Add entities for a single platform.
Get task to set up platform.
Get task to set up platform.
Class to manage the entities for a single platform.
Method to cancel the state change listener Method to cancel the retry of setup Platform is None for the EntityComponent "catch-all" EntityPlatform which powers entity_component.add_entities semaphore will be created on demand This should not be replaced with hass.async_add_job because we don't want to track this task in case it blocks startup. Store it so that we can save config entry ID in entity registry Block till all entities are done pylint: disable=broad-except That avoid deadlocks handle empty list from component/platform No entities for processing Async entity PARALLEL_UPDATE == None: entity.parallel_updates = None PARALLEL_UPDATE == 0: entity.parallel_updates = None PARALLEL_UPDATE > 0: entity.parallel_updates = Semaphore(p) Sync entity PARALLEL_UPDATE == None: entity.parallel_updates = Semaphore(1) PARALLEL_UPDATE == 0: entity.parallel_updates = None PARALLEL_UPDATE > 0: entity.parallel_updates = Semaphore(p) Update properties before we generate the entity_id pylint: disable=broad-except Get entity_id from unique ID registration We won't generate an entity ID if the platform has already set one We will however make sure that platform cannot pick a registered ID If entity already registered, convert entity id to suggestion Generate entity ID Make sure it is valid in case an entity set the value themselves Clean up polling job if no longer needed | 1,940 | en | 0.715893 |
from __future__ import annotations
import typing
if typing.TYPE_CHECKING:
from typing import Optional, Union, Any, Dict
from pypbbot.driver import AffairDriver
from pypbbot.typing import Event
from pypbbot.utils import Clips
from pypbbot.protocol import GroupMessageEvent, PrivateMessageEvent
from enum import Enum
import asyncio
from pypbbot.logging import logger
from pypbbot.utils import sendBackClipsTo
__all__ = ['HandlerPriority', 'BaseAffair', 'ChatAffair']
class HandlerPriority(Enum):
SYSTEM = 0 # SHOULD NOT USED BY PLUGINS
VERY_HIGH = 1
HIGH = 2
NORMAL = 3
LOW = 4
VERY_LOW = 5
def __lt__(self, other: object) -> bool:
if not isinstance(other, HandlerPriority):
return NotImplemented
return self.value < other.value
class BaseAffair:
def __init__(self, driver: AffairDriver, event: Event) -> None:
logger.debug(
'A new affair has been created for event [{}]'.format(type(event)))
self.event: Optional[Event] = event
self.driver: AffairDriver = driver
self.states: Dict[str, Any] = {}
self.finished: bool = False
return
class ChatAffair(BaseAffair):
def __init__(self, driver: AffairDriver, event: Union[GroupMessageEvent, PrivateMessageEvent], sender_id: int) -> None:
self.event: Union[GroupMessageEvent, PrivateMessageEvent] = event
self.driver: AffairDriver = driver
self.receiver_id: int = event.self_id
self.sender_id: int = sender_id
self.raw_message: str = event.raw_message
return
async def send(self, clips: Union[Clips, str, int, float]) -> Any:
return await sendBackClipsTo(self.event, clips)
def sendAndWait(self, clips: Union[Clips, str, int, float]) -> Any:
return asyncio.run(self.send(clips))
| pypbbot/affairs/builtin.py | 1,849 | SHOULD NOT USED BY PLUGINS | 26 | en | 0.965124 |
# The most basic of settings to get the app to run as an example, should *never* be used in a
# production environment.
import os
import dj_database_url
DATABASES = {}
db_url = os.environ.get('DATABASE_URL', '')
if db_url:
DATABASES['default'] = dj_database_url.parse(db_url, conn_max_age=600, ssl_require=True)
else:
DATABASES['default'] = {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': 'dr.sqlite3',
}
INSTALLED_APPS = (
'django.contrib.auth',
'django.contrib.sites',
'django.contrib.sessions',
'django.contrib.contenttypes',
'django.contrib.admin',
'django.contrib.messages',
'keybase_proofs',
'test_app',
)
DEBUG = True
ALLOWED_HOSTS = ['*']
SECRET_KEY = '_'
SITE_ID = 1
ROOT_URLCONF = 'test_app.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'OPTIONS': {
'context_processors': [
'django.contrib.auth.context_processors.auth',
'django.template.context_processors.debug',
'django.template.context_processors.i18n',
'django.template.context_processors.media',
'django.template.context_processors.static',
'django.template.context_processors.tz',
'django.contrib.messages.context_processors.messages',
],
'loaders': [
'django.template.loaders.app_directories.Loader',
],
},
},
]
MIDDLEWARE = (
'django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
)
EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend'
# Must match the `domain` set in the config.
KEYBASE_PROOFS_DOMAIN = '<your-domain.com>'
| test_app/settings.py | 1,952 | The most basic of settings to get the app to run as an example, should *never* be used in a production environment. Must match the `domain` set in the config. | 158 | en | 0.873556 |
# Copyright (c) 2019-2020, NVIDIA CORPORATION.
#
# 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 cupy as cp
from cuml.dask.common.base import BaseEstimator
from cuml.dask.common.base import DelayedPredictionMixin
from cuml.dask.common.base import DelayedTransformMixin
from cuml.dask.common.base import mnmg_import
from cuml.dask.common.input_utils import concatenate
from cuml.dask.common.input_utils import DistributedDataHandler
from cuml.dask.common.comms import CommsContext
from cuml.dask.common.comms import worker_state
from cuml.dask.common.utils import raise_exception_from_futures
from dask.distributed import wait
from cuml.common.memory_utils import with_cupy_rmm
class KMeans(BaseEstimator, DelayedPredictionMixin, DelayedTransformMixin):
"""
Multi-Node Multi-GPU implementation of KMeans.
This version minimizes data transfer by sharing only
the centroids between workers in each iteration.
Predictions are done embarrassingly parallel, using cuML's
single-GPU version.
For more information on this implementation, refer to the
documentation for single-GPU K-Means.
Parameters
----------
handle : cuml.Handle
If it is None, a new one is created just for this class.
n_clusters : int (default = 8)
The number of centroids or clusters you want.
max_iter : int (default = 300)
The more iterations of EM, the more accurate, but slower.
tol : float (default = 1e-4)
Stopping criterion when centroid means do not change much.
verbose : int or boolean (default = False)
Logging level for printing diagnostic information
random_state : int (default = 1)
If you want results to be the same when you restart Python,
select a state.
init : {'scalable-kmeans++', 'k-means||' , 'random' or an ndarray}
(default = 'scalable-k-means++')
'scalable-k-means++' or 'k-means||': Uses fast and stable scalable
kmeans++ intialization.
'random': Choose 'n_cluster' observations (rows) at random
from data for the initial centroids. If an ndarray is passed,
it should be of shape (n_clusters, n_features) and gives the
initial centers.
oversampling_factor : int (default = 2) The amount of points to sample
in scalable k-means++ initialization for potential centroids.
Increasing this value can lead to better initial centroids at the
cost of memory. The total number of centroids sampled in scalable
k-means++ is oversampling_factor * n_clusters * 8.
max_samples_per_batch : int (default = 32768) The number of data
samples to use for batches of the pairwise distance computation.
This computation is done throughout both fit predict. The default
should suit most cases. The total number of elements in the
batched pairwise distance computation is max_samples_per_batch
* n_clusters. It might become necessary to lower this number when
n_clusters becomes prohibitively large.
Attributes
----------
cluster_centers_ : cuDF DataFrame or CuPy ndarray
The coordinates of the final clusters. This represents of "mean" of
each data cluster.
"""
def __init__(self, client=None, verbose=False, **kwargs):
super(KMeans, self).__init__(client=client,
verbose=verbose,
**kwargs)
@staticmethod
@mnmg_import
def _func_fit(sessionId, objs, datatype, **kwargs):
from cuml.cluster.kmeans_mg import KMeansMG as cumlKMeans
handle = worker_state(sessionId)["handle"]
inp_data = concatenate(objs)
return cumlKMeans(handle=handle, output_type=datatype,
**kwargs).fit(inp_data)
@staticmethod
def _score(model, data):
ret = model.score(data)
return ret
@with_cupy_rmm
def fit(self, X):
"""
Fit a multi-node multi-GPU KMeans model
Parameters
----------
X : Dask cuDF DataFrame or CuPy backed Dask Array
Training data to cluster.
"""
data = DistributedDataHandler.create(X, client=self.client)
self.datatype = data.datatype
comms = CommsContext(comms_p2p=False)
comms.init(workers=data.workers)
kmeans_fit = [self.client.submit(KMeans._func_fit,
comms.sessionId,
wf[1],
self.datatype,
**self.kwargs,
workers=[wf[0]],
pure=False)
for idx, wf in enumerate(data.worker_to_parts.items())]
wait(kmeans_fit)
raise_exception_from_futures(kmeans_fit)
comms.destroy()
self.local_model = kmeans_fit[0].result()
self.cluster_centers_ = self.local_model.cluster_centers_
return self
def fit_predict(self, X, delayed=True):
"""
Compute cluster centers and predict cluster index for each sample.
Parameters
----------
X : Dask cuDF DataFrame or CuPy backed Dask Array
Data to predict
Returns
-------
result: Dask cuDF DataFrame or CuPy backed Dask Array
Distributed object containing predictions
"""
return self.fit(X).predict(X, delayed=delayed)
def predict(self, X, delayed=True):
"""
Predict labels for the input
Parameters
----------
X : Dask cuDF DataFrame or CuPy backed Dask Array
Data to predict
delayed : bool (default = True)
Whether to do a lazy prediction (and return Delayed objects) or an
eagerly executed one.
Returns
-------
result: Dask cuDF DataFrame or CuPy backed Dask Array
Distributed object containing predictions
"""
return self._predict(X, delayed=delayed)
def fit_transform(self, X, delayed=True):
"""
Calls fit followed by transform using a distributed KMeans model
Parameters
----------
X : Dask cuDF DataFrame or CuPy backed Dask Array
Data to predict
delayed : bool (default = True)
Whether to execute as a delayed task or eager.
Returns
-------
result: Dask cuDF DataFrame or CuPy backed Dask Array
Distributed object containing the transformed data
"""
return self.fit(X).transform(X, delayed=delayed)
def transform(self, X, delayed=True):
"""
Transforms the input into the learned centroid space
Parameters
----------
X : Dask cuDF DataFrame or CuPy backed Dask Array
Data to predict
delayed : bool (default = True)
Whether to execute as a delayed task or eager.
Returns
-------
result: Dask cuDF DataFrame or CuPy backed Dask Array
Distributed object containing the transformed data
"""
return self._transform(X, n_dims=2, delayed=delayed)
@with_cupy_rmm
def score(self, X):
"""
Computes the inertia score for the trained KMeans centroids.
Parameters
----------
X : dask_cudf.Dataframe
Dataframe to compute score
Returns
-------
Inertial score
"""
scores = self._run_parallel_func(KMeans._score,
X,
n_dims=1,
delayed=False,
output_futures=True)
return -1 * cp.sum(cp.asarray(
self.client.compute(scores, sync=True))*-1.0)
def get_param_names(self):
return list(self.kwargs.keys())
| python/cuml/dask/cluster/kmeans.py | 8,530 | Multi-Node Multi-GPU implementation of KMeans.
This version minimizes data transfer by sharing only
the centroids between workers in each iteration.
Predictions are done embarrassingly parallel, using cuML's
single-GPU version.
For more information on this implementation, refer to the
documentation for single-GPU K-Means.
Parameters
----------
handle : cuml.Handle
If it is None, a new one is created just for this class.
n_clusters : int (default = 8)
The number of centroids or clusters you want.
max_iter : int (default = 300)
The more iterations of EM, the more accurate, but slower.
tol : float (default = 1e-4)
Stopping criterion when centroid means do not change much.
verbose : int or boolean (default = False)
Logging level for printing diagnostic information
random_state : int (default = 1)
If you want results to be the same when you restart Python,
select a state.
init : {'scalable-kmeans++', 'k-means||' , 'random' or an ndarray}
(default = 'scalable-k-means++')
'scalable-k-means++' or 'k-means||': Uses fast and stable scalable
kmeans++ intialization.
'random': Choose 'n_cluster' observations (rows) at random
from data for the initial centroids. If an ndarray is passed,
it should be of shape (n_clusters, n_features) and gives the
initial centers.
oversampling_factor : int (default = 2) The amount of points to sample
in scalable k-means++ initialization for potential centroids.
Increasing this value can lead to better initial centroids at the
cost of memory. The total number of centroids sampled in scalable
k-means++ is oversampling_factor * n_clusters * 8.
max_samples_per_batch : int (default = 32768) The number of data
samples to use for batches of the pairwise distance computation.
This computation is done throughout both fit predict. The default
should suit most cases. The total number of elements in the
batched pairwise distance computation is max_samples_per_batch
* n_clusters. It might become necessary to lower this number when
n_clusters becomes prohibitively large.
Attributes
----------
cluster_centers_ : cuDF DataFrame or CuPy ndarray
The coordinates of the final clusters. This represents of "mean" of
each data cluster.
Fit a multi-node multi-GPU KMeans model
Parameters
----------
X : Dask cuDF DataFrame or CuPy backed Dask Array
Training data to cluster.
Compute cluster centers and predict cluster index for each sample.
Parameters
----------
X : Dask cuDF DataFrame or CuPy backed Dask Array
Data to predict
Returns
-------
result: Dask cuDF DataFrame or CuPy backed Dask Array
Distributed object containing predictions
Calls fit followed by transform using a distributed KMeans model
Parameters
----------
X : Dask cuDF DataFrame or CuPy backed Dask Array
Data to predict
delayed : bool (default = True)
Whether to execute as a delayed task or eager.
Returns
-------
result: Dask cuDF DataFrame or CuPy backed Dask Array
Distributed object containing the transformed data
Predict labels for the input
Parameters
----------
X : Dask cuDF DataFrame or CuPy backed Dask Array
Data to predict
delayed : bool (default = True)
Whether to do a lazy prediction (and return Delayed objects) or an
eagerly executed one.
Returns
-------
result: Dask cuDF DataFrame or CuPy backed Dask Array
Distributed object containing predictions
Computes the inertia score for the trained KMeans centroids.
Parameters
----------
X : dask_cudf.Dataframe
Dataframe to compute score
Returns
-------
Inertial score
Transforms the input into the learned centroid space
Parameters
----------
X : Dask cuDF DataFrame or CuPy backed Dask Array
Data to predict
delayed : bool (default = True)
Whether to execute as a delayed task or eager.
Returns
-------
result: Dask cuDF DataFrame or CuPy backed Dask Array
Distributed object containing the transformed data
Copyright (c) 2019-2020, NVIDIA CORPORATION. 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. | 4,533 | en | 0.678026 |
# Copyright 2017 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
"""Tests for the key functions in pruning library."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import numpy as np
from tensorflow.contrib.model_pruning.python import pruning
from tensorflow.python.framework import constant_op
from tensorflow.python.ops import math_ops
from tensorflow.python.ops import partitioned_variables
from tensorflow.python.ops import random_ops
from tensorflow.python.ops import state_ops
from tensorflow.python.ops import variable_scope
from tensorflow.python.ops import variables
from tensorflow.python.platform import test
from tensorflow.python.training import training_util
class PruningHParamsTest(test.TestCase):
PARAM_LIST = [
"name=test", "threshold_decay=0.9", "pruning_frequency=10",
"sparsity_function_end_step=100", "target_sparsity=0.9",
"weight_sparsity_map=[conv1:0.8,conv2/kernel:0.8]"
]
TEST_HPARAMS = ",".join(PARAM_LIST)
def setUp(self):
super(PruningHParamsTest, self).setUp()
# Add global step variable to the graph
self.global_step = training_util.get_or_create_global_step()
# Add sparsity
self.sparsity = variables.VariableV1(0.5, name="sparsity")
# Parse hparams
self.pruning_hparams = pruning.get_pruning_hparams().parse(
self.TEST_HPARAMS)
def testInit(self):
p = pruning.Pruning(self.pruning_hparams)
self.assertEqual(p._spec.name, "test")
self.assertAlmostEqual(p._spec.threshold_decay, 0.9)
self.assertEqual(p._spec.pruning_frequency, 10)
self.assertEqual(p._spec.sparsity_function_end_step, 100)
self.assertAlmostEqual(p._spec.target_sparsity, 0.9)
self.assertEqual(p._weight_sparsity_map["conv1"], 0.8)
self.assertEqual(p._weight_sparsity_map["conv2/kernel"], 0.8)
def testInitWithExternalSparsity(self):
with self.cached_session():
p = pruning.Pruning(spec=self.pruning_hparams, sparsity=self.sparsity)
variables.global_variables_initializer().run()
sparsity = p._sparsity.eval()
self.assertAlmostEqual(sparsity, 0.5)
def testInitWithVariableReuse(self):
with self.cached_session():
p = pruning.Pruning(spec=self.pruning_hparams, sparsity=self.sparsity)
p_copy = pruning.Pruning(
spec=self.pruning_hparams, sparsity=self.sparsity)
variables.global_variables_initializer().run()
sparsity = p._sparsity.eval()
self.assertAlmostEqual(sparsity, 0.5)
self.assertEqual(p._sparsity.eval(), p_copy._sparsity.eval())
class PruningTest(test.TestCase):
def setUp(self):
super(PruningTest, self).setUp()
self.global_step = training_util.get_or_create_global_step()
def testCreateMask2D(self):
width = 10
height = 20
with self.cached_session():
weights = variables.VariableV1(
random_ops.random_normal([width, height], stddev=1), name="weights")
masked_weights = pruning.apply_mask(weights,
variable_scope.get_variable_scope())
variables.global_variables_initializer().run()
weights_val = weights.eval()
masked_weights_val = masked_weights.eval()
self.assertAllEqual(weights_val, masked_weights_val)
def testUpdateSingleMask(self):
with self.cached_session() as session:
weights = variables.VariableV1(
math_ops.linspace(1.0, 100.0, 100), name="weights")
masked_weights = pruning.apply_mask(weights)
sparsity = variables.VariableV1(0.95, name="sparsity")
p = pruning.Pruning(sparsity=sparsity)
p._spec.threshold_decay = 0.0
mask_update_op = p.mask_update_op()
variables.global_variables_initializer().run()
masked_weights_val = masked_weights.eval()
self.assertAllEqual(np.count_nonzero(masked_weights_val), 100)
session.run(mask_update_op)
masked_weights_val = masked_weights.eval()
self.assertAllEqual(np.count_nonzero(masked_weights_val), 5)
def _blockMasking(self, hparams, weights, expected_mask):
threshold = variables.VariableV1(0.0, name="threshold")
sparsity = variables.VariableV1(0.5, name="sparsity")
test_spec = ",".join(hparams)
pruning_hparams = pruning.get_pruning_hparams().parse(test_spec)
# Set up pruning
p = pruning.Pruning(pruning_hparams, sparsity=sparsity)
with self.cached_session():
variables.global_variables_initializer().run()
_, new_mask = p._maybe_update_block_mask(weights, threshold)
# Check if the mask is the same size as the weights
self.assertAllEqual(new_mask.get_shape(), weights.get_shape())
mask_val = new_mask.eval()
self.assertAllEqual(mask_val, expected_mask)
def testBlockMasking(self):
param_list = ["block_height=2", "block_width=2", "threshold_decay=0"]
weights_avg = constant_op.constant(
[[0.1, 0.1, 0.2, 0.2], [0.1, 0.1, 0.2, 0.2], [0.3, 0.3, 0.4, 0.4],
[0.3, 0.3, 0.4, 0.4]])
weights_max = constant_op.constant(
[[0.1, 0.0, 0.2, 0.0], [0.0, -0.1, 0.0, -0.2], [0.3, 0.0, 0.4, 0.0],
[0.0, -0.3, 0.0, -0.4]])
expected_mask = [[0.0, 0.0, 0.0, 0.0], [0.0, 0.0, 0.0, 0.0],
[1., 1., 1., 1.], [1., 1., 1., 1.]]
self._blockMasking(param_list + ["block_pooling_function=MAX"], weights_max,
expected_mask)
self._blockMasking(param_list + ["block_pooling_function=AVG"], weights_avg,
expected_mask)
def testBlockMaskingWithHigherDimensions(self):
param_list = ["block_height=2", "block_width=2", "threshold_decay=0"]
# Weights as in testBlockMasking, but with one extra dimension.
weights_avg = constant_op.constant(
[[[0.1, 0.1, 0.2, 0.2], [0.1, 0.1, 0.2, 0.2], [0.3, 0.3, 0.4, 0.4],
[0.3, 0.3, 0.4, 0.4]]])
weights_max = constant_op.constant(
[[[0.1, 0.0, 0.2, 0.0], [0.0, -0.1, 0.0, -0.2], [0.3, 0.0, 0.4, 0.0],
[0.0, -0.3, 0.0, -0.4]]])
expected_mask = [[[0.0, 0.0, 0.0, 0.0], [0.0, 0.0, 0.0, 0.0],
[1., 1., 1., 1.], [1., 1., 1., 1.]]]
self._blockMasking(param_list + ["block_pooling_function=MAX"], weights_max,
expected_mask)
self._blockMasking(param_list + ["block_pooling_function=AVG"],
weights_avg, expected_mask)
def testPartitionedVariableMasking(self):
partitioner = partitioned_variables.variable_axis_size_partitioner(40)
with self.cached_session() as session:
with variable_scope.variable_scope("", partitioner=partitioner):
sparsity = variables.VariableV1(0.5, name="Sparsity")
weights = variable_scope.get_variable(
"weights", initializer=math_ops.linspace(1.0, 100.0, 100))
masked_weights = pruning.apply_mask(
weights, scope=variable_scope.get_variable_scope())
p = pruning.Pruning(sparsity=sparsity)
p._spec.threshold_decay = 0.0
mask_update_op = p.mask_update_op()
variables.global_variables_initializer().run()
masked_weights_val = masked_weights.eval()
session.run(mask_update_op)
masked_weights_val = masked_weights.eval()
self.assertAllEqual(np.count_nonzero(masked_weights_val), 50)
def testConditionalMaskUpdate(self):
param_list = [
"pruning_frequency=2", "begin_pruning_step=1", "end_pruning_step=6",
"nbins=100"
]
test_spec = ",".join(param_list)
pruning_hparams = pruning.get_pruning_hparams().parse(test_spec)
weights = variables.VariableV1(
math_ops.linspace(1.0, 100.0, 100), name="weights")
masked_weights = pruning.apply_mask(weights)
sparsity = variables.VariableV1(0.00, name="sparsity")
# Set up pruning
p = pruning.Pruning(pruning_hparams, sparsity=sparsity)
p._spec.threshold_decay = 0.0
mask_update_op = p.conditional_mask_update_op()
sparsity_val = math_ops.linspace(0.0, 0.9, 10)
increment_global_step = state_ops.assign_add(self.global_step, 1)
non_zero_count = []
with self.cached_session() as session:
variables.global_variables_initializer().run()
for i in range(10):
session.run(state_ops.assign(sparsity, sparsity_val[i]))
session.run(mask_update_op)
session.run(increment_global_step)
non_zero_count.append(np.count_nonzero(masked_weights.eval()))
# Weights pruned at steps 0,2,4,and,6
expected_non_zero_count = [100, 100, 80, 80, 60, 60, 40, 40, 40, 40]
self.assertAllEqual(expected_non_zero_count, non_zero_count)
def testWeightSpecificSparsity(self):
param_list = [
"begin_pruning_step=1", "pruning_frequency=1", "end_pruning_step=100",
"target_sparsity=0.5",
"weight_sparsity_map=[layer1:0.6,layer2/weights:0.75,.*kernel:0.6]",
"threshold_decay=0.0"
]
test_spec = ",".join(param_list)
pruning_hparams = pruning.get_pruning_hparams().parse(test_spec)
with variable_scope.variable_scope("layer1"):
w1 = variables.VariableV1(
math_ops.linspace(1.0, 100.0, 100), name="weights")
_ = pruning.apply_mask(w1)
with variable_scope.variable_scope("layer2"):
w2 = variables.VariableV1(
math_ops.linspace(1.0, 100.0, 100), name="weights")
_ = pruning.apply_mask(w2)
with variable_scope.variable_scope("layer3"):
w3 = variables.VariableV1(
math_ops.linspace(1.0, 100.0, 100), name="kernel")
_ = pruning.apply_mask(w3)
p = pruning.Pruning(pruning_hparams)
mask_update_op = p.conditional_mask_update_op()
increment_global_step = state_ops.assign_add(self.global_step, 1)
with self.cached_session() as session:
variables.global_variables_initializer().run()
for _ in range(110):
session.run(mask_update_op)
session.run(increment_global_step)
self.assertAllClose(
session.run(pruning.get_weight_sparsity()), [0.6, 0.75, 0.6])
if __name__ == "__main__":
test.main()
| tensorflow/contrib/model_pruning/python/pruning_test.py | 10,628 | Tests for the key functions in pruning library.
Copyright 2017 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ============================================================================== Add global step variable to the graph Add sparsity Parse hparams Set up pruning Check if the mask is the same size as the weights Weights as in testBlockMasking, but with one extra dimension. Set up pruning Weights pruned at steps 0,2,4,and,6 | 953 | en | 0.839204 |
"""Adapted from:
@longcw faster_rcnn_pytorch: https://github.com/longcw/faster_rcnn_pytorch
@rbgirshick py-faster-rcnn https://github.com/rbgirshick/py-faster-rcnn
Licensed under The MIT License [see LICENSE for details]
"""
from __future__ import print_function
import torch
import torch.nn as nn
import torch.backends.cudnn as cudnn
from torch.autograd import Variable
from data import VOC_ROOT, VOCAnnotationTransform, VOCDetection, BaseTransform
from data import VOC_CLASSES as labelmap
import torch.utils.data as data
from ssd import build_ssd
import sys
import os
import time
import argparse
import numpy as np
import pickle
import cv2
if sys.version_info[0] == 2:
import xml.etree.cElementTree as ET
else:
import xml.etree.ElementTree as ET
def str2bool(v):
return v.lower() in ("yes", "true", "t", "1")
parser = argparse.ArgumentParser(
description='Single Shot MultiBox Detector Evaluation')
parser.add_argument('--trained_model',
default='weights/ssd300_mAP_77.43_v2.pth', type=str,
help='Trained state_dict file path to open')
parser.add_argument('--save_folder', default='eval/', type=str,
help='File path to save results')
parser.add_argument('--confidence_threshold', default=0.5, type=float,
help='Detection confidence threshold')
parser.add_argument('--top_k', default=5, type=int,
help='Further restrict the number of predictions to parse')
parser.add_argument('--cuda', default=False, type=str2bool,
help='Use cuda to train model')
parser.add_argument('--voc_root', default=VOC_ROOT,
help='Location of VOC root directory')
parser.add_argument('--cleanup', default=True, type=str2bool,
help='Cleanup and remove results files following eval')
args = parser.parse_args()
if not os.path.exists(args.save_folder):
os.mkdir(args.save_folder)
if torch.cuda.is_available():
if args.cuda:
torch.set_default_tensor_type('torch.cuda.FloatTensor')
if not args.cuda:
print("WARNING: It looks like you have a CUDA device, but aren't using \
CUDA. Run with --cuda for optimal eval speed.")
torch.set_default_tensor_type('torch.FloatTensor')
else:
torch.set_default_tensor_type('torch.FloatTensor')
annopath = os.path.join(args.voc_root, 'VOC2007', 'Annotations', '%s.xml')
imgpath = os.path.join(args.voc_root, 'VOC2007', 'JPEGImages', '%s.jpg')
if sys.platform.startswith("linux"):
imgsetpath = os.path.join(args.voc_root, 'VOC2007', 'ImageSets', 'Main', '{:s}.txt') # Linux 系统下
if sys.platform.startswith("win"):
imgsetpath = os.path.join(args.voc_root, 'VOC2007', 'ImageSets', 'Main', '{}.txt') # Linux 系统下
YEAR = '2007'
devkit_path = args.voc_root + 'VOC' + YEAR
dataset_mean = (104, 117, 123)
set_type = 'test'
class Timer(object):
"""A simple timer."""
def __init__(self):
self.total_time = 0.
self.calls = 0
self.start_time = 0.
self.diff = 0.
self.average_time = 0.
def tic(self):
# using time.time instead of time.clock because time time.clock
# does not normalize for multithreading
self.start_time = time.time()
def toc(self, average=True):
self.diff = time.time() - self.start_time
self.total_time += self.diff
self.calls += 1
self.average_time = self.total_time / self.calls
if average:
return self.average_time
else:
return self.diff
def parse_rec(filename):
""" Parse a PASCAL VOC xml file """
tree = ET.parse(filename)
objects = []
for obj in tree.findall('object'):
obj_struct = {}
obj_struct['name'] = obj.find('name').text
obj_struct['pose'] = obj.find('pose').text
obj_struct['truncated'] = int(obj.find('truncated').text)
obj_struct['difficult'] = int(obj.find('difficult').text)
bbox = obj.find('bndbox')
obj_struct['bbox'] = [int(bbox.find('xmin').text) - 1,
int(bbox.find('ymin').text) - 1,
int(bbox.find('xmax').text) - 1,
int(bbox.find('ymax').text) - 1]
objects.append(obj_struct)
return objects
def get_output_dir(name, phase):
"""Return the directory where experimental artifacts are placed.
If the directory does not exist, it is created.
A canonical path is built using the name from an imdb and a network
(if not None).
"""
filedir = os.path.join(name, phase)
if not os.path.exists(filedir):
os.makedirs(filedir)
return filedir
def get_voc_results_file_template(image_set, cls):
# VOCdevkit/VOC2007/results/det_test_aeroplane.txt
filename = 'det_' + image_set + '_%s.txt' % (cls)
filedir = os.path.join(devkit_path, 'results')
if not os.path.exists(filedir):
os.makedirs(filedir)
path = os.path.join(filedir, filename)
return path
def write_voc_results_file(all_boxes, dataset):
for cls_ind, cls in enumerate(labelmap):
print('Writing {:s} VOC results file'.format(cls))
filename = get_voc_results_file_template(set_type, cls)
with open(filename, 'wt') as f:
for im_ind, index in enumerate(dataset.ids):
dets = all_boxes[cls_ind+1][im_ind]
if dets == []:
continue
# the VOCdevkit expects 1-based indices
for k in range(dets.shape[0]):
f.write('{:s} {:.3f} {:.1f} {:.1f} {:.1f} {:.1f}\n'.
format(index[1], dets[k, -1],
dets[k, 0] + 1, dets[k, 1] + 1,
dets[k, 2] + 1, dets[k, 3] + 1))
def do_python_eval(output_dir='output', use_07=True):
cachedir = os.path.join(devkit_path, 'annotations_cache')
aps = []
# The PASCAL VOC metric changed in 2010
use_07_metric = use_07
print('VOC07 metric? ' + ('Yes' if use_07_metric else 'No'))
if not os.path.isdir(output_dir):
os.mkdir(output_dir)
for i, cls in enumerate(labelmap):
filename = get_voc_results_file_template(set_type, cls)
rec, prec, ap = voc_eval(
filename, annopath, imgsetpath.format(set_type), cls, cachedir,
ovthresh=0.5, use_07_metric=use_07_metric)
aps += [ap]
print('AP for {} = {:.4f}'.format(cls, ap))
with open(os.path.join(output_dir, cls + '_pr.pkl'), 'wb') as f:
pickle.dump({'rec': rec, 'prec': prec, 'ap': ap}, f)
print('Mean AP = {:.4f}'.format(np.mean(aps)))
print('~~~~~~~~')
print('Results:')
for ap in aps:
print('{:.3f}'.format(ap))
print('{:.3f}'.format(np.mean(aps)))
print('~~~~~~~~')
print('')
print('--------------------------------------------------------------')
print('Results computed with the **unofficial** Python eval code.')
print('Results should be very close to the official MATLAB eval code.')
print('--------------------------------------------------------------')
def voc_ap(rec, prec, use_07_metric=True):
""" ap = voc_ap(rec, prec, [use_07_metric])
Compute VOC AP given precision and recall.
If use_07_metric is true, uses the
VOC 07 11 point method (default:True).
"""
if use_07_metric:
# 11 point metric
ap = 0.
for t in np.arange(0., 1.1, 0.1):
if np.sum(rec >= t) == 0:
p = 0
else:
p = np.max(prec[rec >= t])
ap = ap + p / 11.
else:
# correct AP calculation
# first append sentinel values at the end
mrec = np.concatenate(([0.], rec, [1.]))
mpre = np.concatenate(([0.], prec, [0.]))
# compute the precision envelope
for i in range(mpre.size - 1, 0, -1):
mpre[i - 1] = np.maximum(mpre[i - 1], mpre[i])
# to calculate area under PR curve, look for points
# where X axis (recall) changes value
i = np.where(mrec[1:] != mrec[:-1])[0]
# and sum (\Delta recall) * prec
ap = np.sum((mrec[i + 1] - mrec[i]) * mpre[i + 1])
return ap
def voc_eval(detpath,
annopath,
imagesetfile,
classname,
cachedir,
ovthresh=0.5,
use_07_metric=True):
"""rec, prec, ap = voc_eval(detpath,
annopath,
imagesetfile,
classname,
[ovthresh],
[use_07_metric])
Top level function that does the PASCAL VOC evaluation.
detpath: Path to detections
detpath.format(classname) should produce the detection results file.
annopath: Path to annotations
annopath.format(imagename) should be the xml annotations file.
imagesetfile: Text file containing the list of images, one image per line.
classname: Category name (duh)
cachedir: Directory for caching the annotations
[ovthresh]: Overlap threshold (default = 0.5)
[use_07_metric]: Whether to use VOC07's 11 point AP computation
(default True)
"""
# assumes detections are in detpath.format(classname)
# assumes annotations are in annopath.format(imagename)
# assumes imagesetfile is a text file with each line an image name
# cachedir caches the annotations in a pickle file
# first load gt
if not os.path.isdir(cachedir):
os.mkdir(cachedir)
cachefile = os.path.join(cachedir, 'annots.pkl')
# read list of images
with open(imagesetfile, 'r') as f:
lines = f.readlines()
imagenames = [x.strip() for x in lines]
if not os.path.isfile(cachefile):
# load annots
recs = {}
for i, imagename in enumerate(imagenames):
recs[imagename] = parse_rec(annopath % (imagename))
if i % 100 == 0:
print('Reading annotation for {:d}/{:d}'.format(
i + 1, len(imagenames)))
# save
print('Saving cached annotations to {:s}'.format(cachefile))
with open(cachefile, 'wb') as f:
pickle.dump(recs, f)
else:
# load
with open(cachefile, 'rb') as f:
recs = pickle.load(f)
# extract gt objects for this class
class_recs = {}
npos = 0
for imagename in imagenames:
R = [obj for obj in recs[imagename] if obj['name'] == classname]
bbox = np.array([x['bbox'] for x in R])
difficult = np.array([x['difficult'] for x in R]).astype(np.bool)
det = [False] * len(R)
npos = npos + sum(~difficult)
class_recs[imagename] = {'bbox': bbox,
'difficult': difficult,
'det': det}
# read dets
detfile = detpath.format(classname)
with open(detfile, 'r') as f:
lines = f.readlines()
if any(lines) == 1:
splitlines = [x.strip().split(' ') for x in lines]
image_ids = [x[0] for x in splitlines]
confidence = np.array([float(x[1]) for x in splitlines])
BB = np.array([[float(z) for z in x[2:]] for x in splitlines])
# sort by confidence
sorted_ind = np.argsort(-confidence)
sorted_scores = np.sort(-confidence)
BB = BB[sorted_ind, :]
image_ids = [image_ids[x] for x in sorted_ind]
# go down dets and mark TPs and FPs
nd = len(image_ids)
tp = np.zeros(nd)
fp = np.zeros(nd)
for d in range(nd):
R = class_recs[image_ids[d]]
bb = BB[d, :].astype(float)
ovmax = -np.inf
BBGT = R['bbox'].astype(float)
if BBGT.size > 0:
# compute overlaps
# intersection
ixmin = np.maximum(BBGT[:, 0], bb[0])
iymin = np.maximum(BBGT[:, 1], bb[1])
ixmax = np.minimum(BBGT[:, 2], bb[2])
iymax = np.minimum(BBGT[:, 3], bb[3])
iw = np.maximum(ixmax - ixmin, 0.)
ih = np.maximum(iymax - iymin, 0.)
inters = iw * ih
uni = ((bb[2] - bb[0]) * (bb[3] - bb[1]) +
(BBGT[:, 2] - BBGT[:, 0]) *
(BBGT[:, 3] - BBGT[:, 1]) - inters)
overlaps = inters / uni
ovmax = np.max(overlaps)
jmax = np.argmax(overlaps)
if ovmax > ovthresh:
if not R['difficult'][jmax]:
if not R['det'][jmax]:
tp[d] = 1.
R['det'][jmax] = 1
else:
fp[d] = 1.
else:
fp[d] = 1.
# compute precision recall
fp = np.cumsum(fp)
tp = np.cumsum(tp)
rec = tp / float(npos)
# avoid divide by zero in case the first detection matches a difficult
# ground truth
prec = tp / np.maximum(tp + fp, np.finfo(np.float64).eps)
ap = voc_ap(rec, prec, use_07_metric)
else:
rec = -1.
prec = -1.
ap = -1.
return rec, prec, ap
def test_net(save_folder, net, cuda, dataset, transform, top_k,
im_size=300, thresh=0.05):
num_images = len(dataset)
# all detections are collected into:
# all_boxes[cls][image] = N x 5 array of detections in
# (x1, y1, x2, y2, score)
all_boxes = [[[] for _ in range(num_images)]
for _ in range(len(labelmap)+1)]
# timers
_t = {'im_detect': Timer(), 'misc': Timer()}
output_dir = get_output_dir('ssd300_120000', set_type)
det_file = os.path.join(output_dir, 'detections.pkl')
for i in range(num_images):
im, gt, h, w = dataset.pull_item(i)
x = Variable(im.unsqueeze(0))
if args.cuda:
x = x.cuda()
_t['im_detect'].tic()
detections = net(x).data
detect_time = _t['im_detect'].toc(average=False)
# skip j = 0, because it's the background class
for j in range(1, detections.size(1)):
dets = detections[0, j, :]
mask = dets[:, 0].gt(0.).expand(5, dets.size(0)).t()
dets = torch.masked_select(dets, mask).view(-1, 5)
if dets.size(0) == 0:
continue
boxes = dets[:, 1:]
boxes[:, 0] *= w
boxes[:, 2] *= w
boxes[:, 1] *= h
boxes[:, 3] *= h
scores = dets[:, 0].cpu().numpy()
cls_dets = np.hstack((boxes.cpu().numpy(),
scores[:, np.newaxis])).astype(np.float32,
copy=False)
all_boxes[j][i] = cls_dets
print('im_detect: {:d}/{:d} {:.3f}s'.format(i + 1,
num_images, detect_time))
with open(det_file, 'wb') as f:
pickle.dump(all_boxes, f, pickle.HIGHEST_PROTOCOL)
print('Evaluating detections')
evaluate_detections(all_boxes, output_dir, dataset)
def evaluate_detections(box_list, output_dir, dataset):
write_voc_results_file(box_list, dataset)
do_python_eval(output_dir)
if __name__ == '__main__':
# load net
num_classes = len(labelmap) + 1 # +1 for background
net = build_ssd('test', 300, num_classes) # initialize SSD
#net.load_state_dict(torch.load(args.trained_model))
net.load_state_dict(torch.load(args.trained_model, map_location='cpu')) # running on a CPU-only machine
net.eval()
print('Finished loading model!')
# load data
dataset = VOCDetection(args.voc_root,
[('2007', set_type)],
BaseTransform(300, dataset_mean),
VOCAnnotationTransform())
if args.cuda:
net = net.cuda()
cudnn.benchmark = True
# evaluation
test_net(args.save_folder, net, args.cuda, dataset,
BaseTransform(net.size, dataset_mean), args.top_k, 300,
thresh=args.confidence_threshold)
| eval.py | 16,187 | A simple timer.
Return the directory where experimental artifacts are placed.
If the directory does not exist, it is created.
A canonical path is built using the name from an imdb and a network
(if not None).
Parse a PASCAL VOC xml file
ap = voc_ap(rec, prec, [use_07_metric])
Compute VOC AP given precision and recall.
If use_07_metric is true, uses the
VOC 07 11 point method (default:True).
rec, prec, ap = voc_eval(detpath,
annopath,
imagesetfile,
classname,
[ovthresh],
[use_07_metric])
Top level function that does the PASCAL VOC evaluation.
detpath: Path to detections
detpath.format(classname) should produce the detection results file.
annopath: Path to annotations
annopath.format(imagename) should be the xml annotations file.
imagesetfile: Text file containing the list of images, one image per line.
classname: Category name (duh)
cachedir: Directory for caching the annotations
[ovthresh]: Overlap threshold (default = 0.5)
[use_07_metric]: Whether to use VOC07's 11 point AP computation
(default True)
Adapted from:
@longcw faster_rcnn_pytorch: https://github.com/longcw/faster_rcnn_pytorch
@rbgirshick py-faster-rcnn https://github.com/rbgirshick/py-faster-rcnn
Licensed under The MIT License [see LICENSE for details]
Linux 系统下 Linux 系统下 using time.time instead of time.clock because time time.clock does not normalize for multithreading VOCdevkit/VOC2007/results/det_test_aeroplane.txt the VOCdevkit expects 1-based indices The PASCAL VOC metric changed in 2010 11 point metric correct AP calculation first append sentinel values at the end compute the precision envelope to calculate area under PR curve, look for points where X axis (recall) changes value and sum (\Delta recall) * prec assumes detections are in detpath.format(classname) assumes annotations are in annopath.format(imagename) assumes imagesetfile is a text file with each line an image name cachedir caches the annotations in a pickle file first load gt read list of images load annots save load extract gt objects for this class read dets sort by confidence go down dets and mark TPs and FPs compute overlaps intersection compute precision recall avoid divide by zero in case the first detection matches a difficult ground truth all detections are collected into: all_boxes[cls][image] = N x 5 array of detections in (x1, y1, x2, y2, score) timers skip j = 0, because it's the background class load net +1 for background initialize SSDnet.load_state_dict(torch.load(args.trained_model)) running on a CPU-only machine load data evaluation | 2,685 | en | 0.703514 |
# Webhooks for external integrations.
from functools import partial
from typing import Any, Callable, Dict, Optional
from django.http import HttpRequest, HttpResponse
from zerver.decorator import api_key_only_webhook_view
from zerver.lib.request import REQ, has_request_variables
from zerver.lib.response import json_success
from zerver.lib.webhooks.common import UnexpectedWebhookEventType, \
check_send_webhook_message, get_http_headers_from_filename, \
validate_extract_webhook_http_header
from zerver.models import UserProfile
TICKET_STARTED_TEMPLATE = """
{customer_name} submitted new ticket [#{number}: {title}]({app_url}):
``` quote
{summary}
```
""".strip()
TICKET_ASSIGNED_TEMPLATE = "[#{number}: {title}]({app_url}) ({state}) assigned to {assignee_info}."
AGENT_REPLIED_TEMPLATE = """
{actor} {action} [ticket #{number}]({app_ticket_url}):
``` quote
{plain_text_body}
```
""".strip()
def ticket_started_body(payload: Dict[str, Any]) -> str:
return TICKET_STARTED_TEMPLATE.format(**payload)
def ticket_assigned_body(payload: Dict[str, Any]) -> Optional[str]:
state = payload['state']
kwargs = {
'state': 'open' if state == 'opened' else state,
'number': payload['number'],
'title': payload['title'],
'app_url': payload['app_url']
}
assignee = payload['assignee']
assigned_group = payload['assigned_group']
if assignee or assigned_group:
if assignee and assigned_group:
kwargs['assignee_info'] = '{assignee} from {assigned_group}'.format(**payload)
elif assignee:
kwargs['assignee_info'] = '{assignee}'.format(**payload)
elif assigned_group:
kwargs['assignee_info'] = '{assigned_group}'.format(**payload)
return TICKET_ASSIGNED_TEMPLATE.format(**kwargs)
else:
return None
def replied_body(payload: Dict[str, Any], actor: str, action: str) -> str:
actor_url = "http://api.groovehq.com/v1/{}/".format(actor + 's')
actor = payload['links']['author']['href'].split(actor_url)[1]
number = payload['links']['ticket']['href'].split("http://api.groovehq.com/v1/tickets/")[1]
body = AGENT_REPLIED_TEMPLATE.format(
actor=actor,
action=action,
number=number,
app_ticket_url=payload['app_ticket_url'],
plain_text_body=payload['plain_text_body']
)
return body
def get_event_handler(event: str) -> Callable[..., str]:
# The main reason for this function existence is because of mypy
handler = EVENTS_FUNCTION_MAPPER.get(event) # type: Any
if handler is None:
raise UnexpectedWebhookEventType("Groove", event)
return handler
@api_key_only_webhook_view('Groove')
@has_request_variables
def api_groove_webhook(request: HttpRequest, user_profile: UserProfile,
payload: Dict[str, Any]=REQ(argument_type='body')) -> HttpResponse:
event = validate_extract_webhook_http_header(request, 'X_GROOVE_EVENT', 'Groove')
assert event is not None
handler = get_event_handler(event)
body = handler(payload)
topic = 'notifications'
if body is not None:
check_send_webhook_message(request, user_profile, topic, body)
return json_success()
EVENTS_FUNCTION_MAPPER = {
'ticket_started': ticket_started_body,
'ticket_assigned': ticket_assigned_body,
'agent_replied': partial(replied_body, actor='agent', action='replied to'),
'customer_replied': partial(replied_body, actor='customer', action='replied to'),
'note_added': partial(replied_body, actor='agent', action='left a note on')
}
fixture_to_headers = get_http_headers_from_filename("HTTP_X_GROOVE_EVENT")
| zerver/webhooks/groove/view.py | 3,671 | Webhooks for external integrations. The main reason for this function existence is because of mypy type: Any | 108 | en | 0.832516 |
import pandas as pd
import tweepy
from textblob import TextBlob
from wordcloud import WordCloud
import plotly.graph_objs as go
import os
import re
import pystan
import numpy as np
import streamlit as st
import matplotlib.pyplot as plt
import yfinance as yf
from fbprophet import Prophet
from fbprophet.plot import plot_plotly
from GoogleNews import GoogleNews
from ta.volatility import BollingerBands
from ta.trend import MACD
from ta.momentum import RSIIndicator
import datetime as datetime
import base64
import pandas as pd
import plotly.express as px
import datetime
import requests
from bs4 import BeautifulSoup
from datetime import date
from plotly import graph_objs
st.set_page_config(
layout="wide",
initial_sidebar_state="auto",
page_title= "Finance-Forcasting-Dashboard",
page_icon= "Images/growth.png",
)
col1, col2, col3 = st.beta_columns([1,2,1])
col1.write("")
col2.image("Images/LL.png", width = 500)
col3.write("")
st.set_option('deprecation.showPyplotGlobalUse', False)
main_bg = "Images/BACK.png"
main_bg_ext = "Images/BACK.png"
st.markdown(
f"""
<style>
.reportview-container {{
background: url(data:image/{main_bg_ext};base64,{base64.b64encode(open(main_bg, "rb").read()).decode()})
}}
</style>
""",
unsafe_allow_html=True
)
###############################Funtions############################
# load data from yahoo finance
def load_data(ticker):
start = "2020-01-01"
today = date.today().strftime("%Y-%m-%d")
data = yf.download(ticker, start, today)
data.reset_index(inplace=True)
return data
# Plot raw data
def plot_raw_data():
fig = graph_objs.Figure()
fig.add_trace(graph_objs.Scatter(x=data['Date'], y=data['Open'], name="stock_open"))
fig.add_trace(graph_objs.Scatter(x=data['Date'], y=data['Close'], name="stock_close"))
fig.layout.update(title_text='Time Series data with Rangeslider', xaxis_rangeslider_visible=True)
st.plotly_chart(fig)
def get_forecast(data):
model = Prophet()
model.fit(data)
future = model.make_future_dataframe(periods=7)
forecast = model.predict(future)
return model, forecast
@st.cache
def read_data():
url = "https://raw.githubusercontent.com/emrecanaltinsoy/forex_data/main/forex_usd_data.csv"
data = pd.read_csv(url)
cols = data.columns
return data, cols[1:]
@st.cache
def get_range(data, date_range):
start_index = data.index[data["date(y-m-d)"] == str(date_range[0])].tolist()[0]
end_index = data.index[data["date(y-m-d)"] == str(date_range[1])].tolist()[0]
data = data.iloc[start_index : end_index + 1]
cols = data.columns
dates = data["date(y-m-d)"]
return data, dates
@st.cache
def scrape_currency():
today = datetime.date.today()
base_url = "https://www.x-rates.com/historical/?from=USD&amount=1&date"
year = today.year
month = today.month if today.month > 9 else f"0{today.month}"
day = today.day if today.day > 9 else f"0{today.day}"
URL = f"{base_url}={year}-{month}-{day}"
page = requests.get(URL)
soup = BeautifulSoup(page.content, "html.parser")
table = soup.find_all("tr")[12:]
currencies = [table[i].text.split("\n")[1:3][0] for i in range(len(table))]
currencies.insert(0, "date(y-m-d)")
currencies.insert(1, "American Dollar")
rates = [table[i].text.split("\n")[1:3][1] for i in range(len(table))]
rates.insert(0, f"{year}-{month}-{day}")
rates.insert(1, "1")
curr_data = {currencies[i]: rates[i] for i in range(len(rates))}
curr_data = pd.DataFrame(curr_data, index=[0])
cols = curr_data.columns
return curr_data, cols[1:]
@st.cache
def train_model(data, currency, period):
df_train = data[["date(y-m-d)", currency]]
df_train = df_train.iloc[-365*2 :]
df_train = df_train.rename(columns={"date(y-m-d)": "ds", currency: "y"})
m = Prophet()
m.fit(df_train)
future = m.make_future_dataframe(periods=period)
forecast = m.predict(future)
return forecast, m
df_all, columns = read_data()
################################################################################
st.sidebar.image("Images/Menu.png", width = 330)
menu = ["Home","STOCKS Live Forcasting", "Crypto-Live Forcasting","View Historical Currency Charts", "Check Live Currency Exchange rates", "Forecast Currency Live Prices"]
choice = st.sidebar.selectbox("Menu", menu)
if choice == "Home":
st.write("")
st.write(""" <p style=" font-size: 15px; font-weight:normal; font-family:verdana"> Finance Dashboard is a special web service that allows you to view Cryptocurrencies,Stocks,and Live Currency Values by many useful methods (technical indicators, graphical patterns, sentimental analysis, and more). Trading and crypto investing requires constant analysis and monitoring. Traders need to track all their trades in order to improve results and find errors. If you don't use additional instruments, then trading will be unsystematic, and the results will be uncertain. Such a service will be useful and even extremely necessary for those who trade and invest in cryptocurrencies and Stocks. Competent selection of cryptocurrencies is at least half of investment success. Finance Dashboard has a simple interface and is great for quick analysis of the Stock market. </p>
""", unsafe_allow_html=True)
st.write("")
st.write("")
st.write("")
st.write("")
st.write("")
st.write(""" <p style=" color:#E75480; font-size: 30px; font-weight:bold"> How does it work? </p>
""", unsafe_allow_html=True)
st.write("")
st.image("Images/How.png", width = 1300)
st.sidebar.write(" ")
st.sidebar.write(" ")
st.sidebar.image("Images/info.png", width = 300)
elif choice == "STOCKS Live Forcasting":
st.title('Stocks Weekly Forecast')
st.subheader('Enter the stock ticker:')
ticker = st.text_input('example: GOOG')
ticket = ticker.upper()
if len(ticker)>0:
data_load_state = st.text('Loading data...')
data = load_data(ticker)
if data.empty:
data_load_state.text(f'No ticker named {ticker}')
ticker = ''
else:
data_load_state.text('Loading data... done!')
st.subheader(f'Company: {yf.Ticker(ticker).info["longName"]}')
st.write(data.head())
plot_raw_data()
# prepare data for forecasting
df_train = data[['Date','Close']]
df_train = df_train.rename(columns={"Date": "ds", "Close": "y"})
# train and forecast
model, forecast = get_forecast(df_train)
st.subheader('Forecast')
# plot forecast
st.write(f'Forecast plot for the next week')
fig = plot_plotly(model, forecast)
st.plotly_chart(fig)
elif choice == "View Historical Currency Charts":
st.write("This app can be used to view historical **currency** charts!")
date_range = st.date_input(
"Choose date range",
value=(
datetime.date(2011, 1, 1),
datetime.date(2011, 1, 1) + datetime.timedelta(df_all.shape[0] - 1),
),
min_value=datetime.date(2011, 1, 1),
max_value=datetime.date(2011, 1, 1) + datetime.timedelta(df_all.shape[0] - 1),
)
df, dates = get_range(df_all, date_range)
selected_curr = st.multiselect("Select currencies", columns)
ok = st.button("View")
if ok:
if selected_curr:
# st.write(df[selected_curr])
for curr in selected_curr:
fig = px.line(
x=dates,
y=df[curr],
)
fig.update_layout(
xaxis_title="Date",
yaxis_title=curr,
)
st.write(fig)
elif choice == "Check Live Currency Exchange rates":
st.write("This app can be used to check current **currency** data!")
daily_df, columns = scrape_currency()
base_curr = st.selectbox("Select the base currency", columns)
selected_curr = st.multiselect("Select currencies", columns)
if selected_curr:
base = daily_df[base_curr].astype(float)
selected = daily_df[selected_curr].astype(float)
converted = selected / float(base)
st.write(converted)
elif choice == "Forecast Currency Live Prices":
currency = st.selectbox("Select the currency for prediction", columns)
n_weeks = st.slider("Weeks of prediction", 4, 20, 8, 1)
ok = st.button("Predict")
if ok:
train_state = st.text("Training the model...")
pred, model = train_model(df_all, currency, period=n_weeks * 7)
train_state.text("Model training completed!!")
st.subheader("Forecast data")
fig1 = plot_plotly(model, pred)
st.plotly_chart(fig1)
elif choice == "Crypto-Live Forcasting":
st.sidebar.header("Please select cryptocurrency")
option = st.sidebar.selectbox("Ticker Symbol",("BTC-USD", "ETH-USD", "XRP-USD", "DOGE-USD", "ADA-USD", "BNB-USD", "LTC-USD",))
today = datetime.date.today()
before = today - datetime.timedelta(days=1400)
start_date = st.sidebar.date_input('Start date', before)
end_date = st.sidebar.date_input('End date', today)
if start_date < end_date:
st.sidebar.success("Start date: `%s`\n\nEnd date: `%s` " % (start_date, end_date))
else:
st.sidebar.error("Error: End date must fall after start date.")
@st.cache(allow_output_mutation = True)
def get_data(option, start_date, end_date):
df = yf.download(option,start= start_date,end = end_date, progress=False)
return df
# Getting API_KEYS
api_key = os.environ.get("Key")
api_secret = os.environ.get("Secret")
# Function for getting tweets
# Create authentication
@st.cache(allow_output_mutation = True)
def get_tweets(key, secret, search_term):
authentication = tweepy.OAuthHandler(api_key, api_secret)
api = tweepy.API(authentication)
term = search_term+"-filter:retweets"
# Create a cursor object
tweets = tweepy.Cursor(api.search, q = term, lang = "en",
since = today, tweet_mode = "extended").items(100)
# Store the tweets
tweets_text = [tweet.full_text for tweet in tweets]
df = pd.DataFrame(tweets_text, columns = ["Tweets"])
return df
# Clean text
@st.cache(allow_output_mutation = True)
def Clean(twt):
twt = re.sub("#cryptocurrency", "cryptocurrency", twt)
twt = re.sub("#Cryptocurrency", "Cryptocurrency", twt)
twt = re.sub("#[A-Za-z0-9]+", "", twt)
twt = re.sub("RT[\s]+", "", twt)
twt = re.sub("\\n", "", twt)
twt = re.sub("https?\://\S+", '', twt)
twt = re.sub("<br />", "", twt)
twt = re.sub("\d","", twt)
twt = re.sub("it\'s", "it is", twt)
twt = re.sub("can\'t", "cannot", twt)
twt = re.sub("<(?:a\b[^>]*>|/a>)", "", twt)
return twt
# Subjectivity and Polarity
@st.cache(allow_output_mutation = True)
def subjectivity(text):
return TextBlob(text).sentiment.subjectivity
@st.cache(allow_output_mutation = True)
def polarity(text):
return TextBlob(text).sentiment.polarity
# Create a function to get sentiment text
@st.cache(allow_output_mutation = True)
def sentiment(score):
if score < 0:
return "Negative"
elif score == 0:
return "Neutral"
else:
return "Positive"
if option == "BTC-USD":
df = get_data(option, start_date, end_date)
st.write(""" <p style=" color:#FFCC00; font-size: 30px; font-weight:bold"> Raw Data </p>
""", unsafe_allow_html=True)
st.write(" ")
st.write(df)
st.write(""" <p style=" color:#FFCC00; font-size: 30px; font-weight:bold"> Close Price </p>
""", unsafe_allow_html=True)
st.write(" ")
st.line_chart(df["Close"])
st.write(" ")
# MACD
st.write(" ")
macd = MACD(df["Close"]).macd()
st.write(""" <p style=" color:#FFCC00; font-size: 30px; font-weight:bold"> Moving Average Convergence Divergence </p>
""", unsafe_allow_html=True)
st.write(" ")
st.area_chart(macd)
# Bollinger Bands
bb_bands = BollingerBands(df["Close"])
bb = df
bb["bb_h"] = bb_bands.bollinger_hband()
bb["bb_l"] = bb_bands.bollinger_lband()
bb = bb[["Close","bb_h","bb_l"]]
st.write(""" <p style=" color:#FFCC00; font-size: 30px; font-weight:bold"> Bollinger Bands </p>
""", unsafe_allow_html=True)
st.line_chart(bb)
st.write(" ")
# Resistence Strength Indicator
rsi = RSIIndicator(df["Close"]).rsi()
st.write(""" <p style=" color:#FFCC00; font-size: 30px; font-weight:bold"> Resistence Strength Indicator </p>
""", unsafe_allow_html=True)
st.write(" ")
st.line_chart(rsi)
st.write(" ")
st.write(""" <p style=" color:#FFCC00; font-size: 30px; font-weight:bold"> BTC-USD Forecast using Facebook Prophet </p>
""", unsafe_allow_html=True)
st.write(" ")
data = df.reset_index()
period = st.slider("Days of prediction:", 1, 365)
# Predict forecast with Prophet.
df_train = data[["Date","Close"]]
df_train = df_train.rename(columns={"Date": "ds", "Close": "y"})
m = Prophet()
m.fit(df_train)
future = m.make_future_dataframe(periods=period)
forecast = m.predict(future)
#Plot
st.write(f'Forecast plot for {period} days')
fig1 = plot_plotly(m, forecast)
st.plotly_chart(fig1)
st.write(" ")
st.write(""" <p style=" color:#FFCC00; font-size: 30px; font-weight:bold"> Latest News </p>
""", unsafe_allow_html=True)
st.write(" ")
news = GoogleNews()
news = GoogleNews("en", "d")
news.search("Bitcoin")
news.get_page(1)
result = news.result()
st.write("1. " + result[1]["title"])
st.info("1. " + result[1]["link"])
st.write("2. " + result[2]["title"])
st.info("2. " + result[2]["link"])
st.write("3. " + result[3]["title"])
st.info("3. " + result[3]["link"])
st.write("4. " + result[4]["title"])
st.info("4. " + result[4]["link"])
st.write("5. " + result[5]["title"])
st.info("5. " + result[5]["link"])
elif option == "ETH-USD":
df = get_data(option, start_date, end_date)
st.write(""" <p style=" color:#FFCC00; font-size: 30px; font-weight:bold"> Raw Data </p>
""", unsafe_allow_html=True)
st.write(" ")
st.write(df)
st.write(" ")
st.write(""" <p style=" color:#FFCC00; font-size: 30px; font-weight:bold"> Close Price </p>
""", unsafe_allow_html=True)
st.write(" ")
st.line_chart(df["Close"])
st.write(" ")
# MACD
st.write(" ")
macd = MACD(df["Close"]).macd()
st.write(""" <p style=" color:#FFCC00; font-size: 30px; font-weight:bold"> Moving Average Convergence Divergence </p>
""", unsafe_allow_html=True)
st.write(" ")
st.area_chart(macd)
# Bollinger Bands
bb_bands = BollingerBands(df["Close"])
bb = df
bb["bb_h"] = bb_bands.bollinger_hband()
bb["bb_l"] = bb_bands.bollinger_lband()
bb = bb[["Close","bb_h","bb_l"]]
st.write(""" <p style=" color:#FFCC00; font-size: 30px; font-weight:bold"> Bollinger Bands </p>
""", unsafe_allow_html=True)
st.line_chart(bb)
st.write(" ")
# Resistence Strength Indicator
rsi = RSIIndicator(df["Close"]).rsi()
st.write(""" <p style=" color:#FFCC00; font-size: 30px; font-weight:bold"> Resistence Strength Indicator </p>
""", unsafe_allow_html=True)
st.write(" ")
st.line_chart(rsi)
st.write(" ")
st.write(""" <p style=" color:#FFCC00; font-size: 30px; font-weight:bold"> ETH-USD Forecast using Facebook Prophet </p>
""", unsafe_allow_html=True)
st.write(" ")
data = df.reset_index()
period = st.slider("Days of prediction:", 1, 365)
# Predict forecast with Prophet.
df_train = data[["Date","Close"]]
df_train = df_train.rename(columns={"Date": "ds", "Close": "y"})
m = Prophet()
m.fit(df_train)
future = m.make_future_dataframe(periods=period)
forecast = m.predict(future)
st.write(f'Forecast plot for {period} days')
fig1 = plot_plotly(m, forecast)
st.plotly_chart(fig1)
st.write(" ")
st.write(""" <p style=" color:#FFCC00; font-size: 30px; font-weight:bold"> Latest News </p>
""", unsafe_allow_html=True)
st.write(" ")
news = GoogleNews()
news = GoogleNews("en", "d")
news.search("Etherium")
news.get_page(1)
result = news.result()
st.write("1. " + result[1]["title"])
st.info("1. " + result[1]["link"])
st.write("2. " + result[2]["title"])
st.info("2. " + result[2]["link"])
st.write("3. " + result[3]["title"])
st.info("3. " + result[3]["link"])
st.write("4. " + result[4]["title"])
st.info("4. " + result[4]["link"])
st.write("5. " + result[5]["title"])
st.info("5. " + result[5]["link"])
elif option == "DOGE-USD":
df = get_data(option, start_date, end_date)
st.write(""" <p style=" color:#FFCC00; font-size: 30px; font-weight:bold"> Raw Data </p>
""", unsafe_allow_html=True)
st.write(" ")
st.write(df)
st.write(" ")
st.write(""" <p style=" color:#FFCC00; font-size: 30px; font-weight:bold"> Close Price </p>
""", unsafe_allow_html=True)
st.write(" ")
st.line_chart(df["Close"])
st.write(" ")
# MACD
st.write(" ")
macd = MACD(df["Close"]).macd()
st.write(""" <p style=" color:#FFCC00; font-size: 30px; font-weight:bold"> Moving Average Convergence Divergence </p>
""", unsafe_allow_html=True)
st.write(" ")
st.area_chart(macd)
# Bollinger Bands
bb_bands = BollingerBands(df["Close"])
bb = df
bb["bb_h"] = bb_bands.bollinger_hband()
bb["bb_l"] = bb_bands.bollinger_lband()
bb = bb[["Close","bb_h","bb_l"]]
st.write(""" <p style=" color:#FFCC00; font-size: 30px; font-weight:bold"> Bollinger Bands </p>
""", unsafe_allow_html=True)
st.line_chart(bb)
st.write(" ")
# Resistence Strength Indicator
rsi = RSIIndicator(df["Close"]).rsi()
st.write(""" <p style=" color:#FFCC00; font-size: 30px; font-weight:bold"> Resistence Strength Indicator </p>
""", unsafe_allow_html=True)
st.write(" ")
st.line_chart(rsi)
st.write(" ")
st.write(""" <p style=" color:#FFCC00; font-size: 30px; font-weight:bold"> DOGE-USD Forecast using Facebook Prophet </p>
""", unsafe_allow_html=True)
st.write(" ")
data = df.reset_index()
period = st.slider("Days of prediction:", 1, 365)
# Predict forecast with Prophet.
df_train = data[["Date","Close"]]
df_train = df_train.rename(columns={"Date": "ds", "Close": "y"})
m = Prophet()
m.fit(df_train)
future = m.make_future_dataframe(periods=period)
forecast = m.predict(future)
st.write(f'Forecast plot for {period} days')
fig1 = plot_plotly(m, forecast)
st.plotly_chart(fig1)
st.write(" ")
st.write(""" <p style=" color:#FFCC00; font-size: 30px; font-weight:bold"> Latest News </p>
""", unsafe_allow_html=True)
st.write(" ")
news = GoogleNews()
news = GoogleNews("en", "d")
news.search("Dogecoin")
news.get_page(1)
result = news.result()
st.write("1. " + result[1]["title"])
st.info("1. " + result[1]["link"])
st.write("2. " + result[2]["title"])
st.info("2. " + result[2]["link"])
st.write("3. " + result[3]["title"])
st.info("3. " + result[3]["link"])
st.write("4. " + result[4]["title"])
st.info("4. " + result[4]["link"])
st.write("5. " + result[5]["title"])
st.info("5. " + result[5]["link"])
st.write(" ")
elif option == "XRP-USD":
df = get_data(option, start_date, end_date)
st.write(""" <p style=" color:#FFCC00; font-size: 30px; font-weight:bold"> Raw Data </p>
""", unsafe_allow_html=True)
st.write(" ")
st.write(df)
st.write(" ")
st.write(""" <p style=" color:#FFCC00; font-size: 30px; font-weight:bold"> Close Price </p>
""", unsafe_allow_html=True)
st.write(" ")
st.line_chart(df["Close"])
st.write(" ")
# MACD
st.write(" ")
macd = MACD(df["Close"]).macd()
st.write(""" <p style=" color:#FFCC00; font-size: 30px; font-weight:bold"> Moving Average Convergence Divergence </p>
""", unsafe_allow_html=True)
st.write(" ")
st.area_chart(macd)
# Bollinger Bands
bb_bands = BollingerBands(df["Close"])
bb = df
bb["bb_h"] = bb_bands.bollinger_hband()
bb["bb_l"] = bb_bands.bollinger_lband()
bb = bb[["Close","bb_h","bb_l"]]
st.write(""" <p style=" color:#FFCC00; font-size: 30px; font-weight:bold"> Bollinger Bands </p>
""", unsafe_allow_html=True)
st.line_chart(bb)
st.write(" ")
# Resistence Strength Indicator
rsi = RSIIndicator(df["Close"]).rsi()
st.write(""" <p style=" color:#FFCC00; font-size: 30px; font-weight:bold"> Resistence Strength Indicator </p>
""", unsafe_allow_html=True)
st.write(" ")
st.line_chart(rsi)
st.write(" ")
st.write(""" <p style=" color:#FFCC00; font-size: 30px; font-weight:bold"> DOGE-USD Forecast using Facebook Prophet </p>
""", unsafe_allow_html=True)
st.write(" ")
data = df.reset_index()
period = st.slider("Days of prediction:", 1, 365)
# Predict forecast with Prophet.
df_train = data[["Date","Close"]]
df_train = df_train.rename(columns={"Date": "ds", "Close": "y"})
m = Prophet()
m.fit(df_train)
future = m.make_future_dataframe(periods=period)
forecast = m.predict(future)
st.write(f'Forecast plot for {period} days')
fig1 = plot_plotly(m, forecast)
st.plotly_chart(fig1)
st.write(" ")
st.write(""" <p style=" color:#FFCC00; font-size: 30px; font-weight:bold"> Latest News </p>
""", unsafe_allow_html=True)
st.write(" ")
news = GoogleNews()
news = GoogleNews("en", "d")
news.search("XRP")
news.get_page(1)
result = news.result()
st.write("1. " + result[1]["title"])
st.info("1. " + result[1]["link"])
st.write("2. " + result[2]["title"])
st.info("2. " + result[2]["link"])
st.write("3. " + result[3]["title"])
st.info("3. " + result[3]["link"])
st.write("4. " + result[4]["title"])
st.info("4. " + result[4]["link"])
st.write("5. " + result[5]["title"])
st.info("5. " + result[5]["link"])
elif option == "ADA-USD":
df = get_data(option, start_date, end_date)
st.write(""" <p style=" color:#FFCC00; font-size: 30px; font-weight:bold"> Raw Data </p>
""", unsafe_allow_html=True)
st.write(" ")
st.write(df)
st.write(" ")
st.write(""" <p style=" color:#FFCC00; font-size: 30px; font-weight:bold"> Close Price </p>
""", unsafe_allow_html=True)
st.write(" ")
st.line_chart(df["Close"])
st.write(" ")
# MACD
st.write(" ")
macd = MACD(df["Close"]).macd()
st.write(""" <p style=" color:#FFCC00; font-size: 30px; font-weight:bold"> Moving Average Convergence Divergence </p>
""", unsafe_allow_html=True)
st.write(" ")
st.area_chart(macd)
# Bollinger Bands
bb_bands = BollingerBands(df["Close"])
bb = df
bb["bb_h"] = bb_bands.bollinger_hband()
bb["bb_l"] = bb_bands.bollinger_lband()
bb = bb[["Close","bb_h","bb_l"]]
st.write(""" <p style=" color:#FFCC00; font-size: 30px; font-weight:bold"> Bollinger Bands </p>
""", unsafe_allow_html=True)
st.line_chart(bb)
st.write(" ")
# Resistence Strength Indicator
rsi = RSIIndicator(df["Close"]).rsi()
st.write(""" <p style=" color:#FFCC00; font-size: 30px; font-weight:bold"> Resistence Strength Indicator </p>
""", unsafe_allow_html=True)
st.write(" ")
st.line_chart(rsi)
st.write(" ")
st.write(""" <p style=" color:#FFCC00; font-size: 30px; font-weight:bold"> ADA-USD Forecast using Facebook Prophet </p>
""", unsafe_allow_html=True)
st.write(" ")
data = df.reset_index()
period = st.slider("Days of prediction:", 1, 365)
# Predict forecast with Prophet.
df_train = data[["Date","Close"]]
df_train = df_train.rename(columns={"Date": "ds", "Close": "y"})
m = Prophet()
m.fit(df_train)
future = m.make_future_dataframe(periods=period)
forecast = m.predict(future)
st.write(f'Forecast plot for {period} days')
fig1 = plot_plotly(m, forecast)
st.plotly_chart(fig1)
st.write(" ")
st.write(""" <p style=" color:#FFCC00; font-size: 30px; font-weight:bold"> Latest News </p>
""", unsafe_allow_html=True)
st.write(" ")
news = GoogleNews()
news = GoogleNews("en", "d")
news.search("cryptocurrency")
news.get_page(1)
result = news.result()
st.write("1. " + result[1]["title"])
st.info("1. " + result[1]["link"])
st.write("2. " + result[2]["title"])
st.info("2. " + result[2]["link"])
st.write("3. " + result[3]["title"])
st.info("3. " + result[3]["link"])
st.write("4. " + result[4]["title"])
st.info("4. " + result[4]["link"])
st.write("5. " + result[5]["title"])
st.info("5. " + result[5]["link"])
elif option == "BNB-USD":
df = get_data(option, start_date, end_date)
st.write(""" <p style=" color:#FFCC00; font-size: 30px; font-weight:bold"> Raw Data </p>
""", unsafe_allow_html=True)
st.write(" ")
st.write(df)
st.write(" ")
st.write(""" <p style=" color:#FFCC00; font-size: 30px; font-weight:bold"> Close Price </p>
""", unsafe_allow_html=True)
st.write(" ")
st.line_chart(df["Close"])
st.write(" ")
# MACD
st.write(" ")
macd = MACD(df["Close"]).macd()
st.write(""" <p style=" color:#FFCC00; font-size: 30px; font-weight:bold"> Moving Average Convergence Divergence </p>
""", unsafe_allow_html=True)
st.write(" ")
st.area_chart(macd)
# Bollinger Bands
bb_bands = BollingerBands(df["Close"])
bb = df
bb["bb_h"] = bb_bands.bollinger_hband()
bb["bb_l"] = bb_bands.bollinger_lband()
bb = bb[["Close","bb_h","bb_l"]]
st.write(""" <p style=" color:#FFCC00; font-size: 30px; font-weight:bold"> Bollinger Bands </p>
""", unsafe_allow_html=True)
st.line_chart(bb)
st.write(" ")
# Resistence Strength Indicator
rsi = RSIIndicator(df["Close"]).rsi()
st.write(""" <p style=" color:#FFCC00; font-size: 30px; font-weight:bold"> Resistence Strength Indicator </p>
""", unsafe_allow_html=True)
st.write(" ")
st.line_chart(rsi)
st.write(" ")
st.write(""" <p style=" color:#FFCC00; font-size: 30px; font-weight:bold"> BNB-USD Forecast using Facebook Prophet </p>
""", unsafe_allow_html=True)
st.write(" ")
data = df.reset_index()
period = st.slider("Days of prediction:", 1, 365)
# Predict forecast with Prophet.
df_train = data[["Date","Close"]]
df_train = df_train.rename(columns={"Date": "ds", "Close": "y"})
m = Prophet()
m.fit(df_train)
future = m.make_future_dataframe(periods=period)
forecast = m.predict(future)
st.write(f'Forecast plot for {period} days')
fig1 = plot_plotly(m, forecast)
st.plotly_chart(fig1)
st.write(" ")
st.write(""" <p style=" color:#FFCC00; font-size: 30px; font-weight:bold"> Latest News </p>
""", unsafe_allow_html=True)
st.write(" ")
news = GoogleNews()
news = GoogleNews("en", "d")
news.search("BNB")
news.get_page(1)
result = news.result()
st.write("1. " + result[1]["title"])
st.info("1. " + result[1]["link"])
st.write("2. " + result[2]["title"])
st.info("2. " + result[2]["link"])
st.write("3. " + result[3]["title"])
st.info("3. " + result[3]["link"])
st.write("4. " + result[4]["title"])
st.info("4. " + result[4]["link"])
st.write("5. " + result[5]["title"])
st.info("5. " + result[5]["link"])
elif option == "LTC-USD":
df = get_data(option, start_date, end_date)
st.write(""" <p style=" color:#FFCC00; font-size: 30px; font-weight:bold"> Raw Data </p>
""", unsafe_allow_html=True)
st.write(" ")
st.write(df)
st.write(" ")
st.write(""" <p style=" color:#FFCC00; font-size: 30px; font-weight:bold"> Close Price </p>
""", unsafe_allow_html=True)
st.write(" ")
st.line_chart(df["Close"])
st.write(" ")
# MACD
st.write(" ")
macd = MACD(df["Close"]).macd()
st.write(""" <p style=" color:#FFCC00; font-size: 30px; font-weight:bold"> Moving Average Convergence Divergence </p>
""", unsafe_allow_html=True)
st.write(" ")
st.area_chart(macd)
# Bollinger Bands
bb_bands = BollingerBands(df["Close"])
bb = df
bb["bb_h"] = bb_bands.bollinger_hband()
bb["bb_l"] = bb_bands.bollinger_lband()
bb = bb[["Close","bb_h","bb_l"]]
st.write(""" <p style=" color:#FFCC00; font-size: 30px; font-weight:bold"> Bollinger Bands </p>
""", unsafe_allow_html=True)
st.line_chart(bb)
st.write(" ")
# Resistence Strength Indicator
rsi = RSIIndicator(df["Close"]).rsi()
st.write(""" <p style=" color:#FFCC00; font-size: 30px; font-weight:bold"> Resistence Strength Indicator </p>
""", unsafe_allow_html=True)
st.write(" ")
st.line_chart(rsi)
st.write(" ")
st.write(""" <p style=" color:#FFCC00; font-size: 30px; font-weight:bold"> LTC-USD Forecast using Facebook Prophet </p>
""", unsafe_allow_html=True)
st.write(" ")
data = df.reset_index()
period = st.slider("Days of prediction:", 1, 365)
# Predict forecast with Prophet.
df_train = data[["Date","Close"]]
df_train = df_train.rename(columns={"Date": "ds", "Close": "y"})
m = Prophet()
m.fit(df_train)
future = m.make_future_dataframe(periods=period)
forecast = m.predict(future)
st.write(f'Forecast plot for {period} days')
fig1 = plot_plotly(m, forecast)
st.plotly_chart(fig1)
st.write(" ")
st.write(""" <p style=" color:#FFCC00; font-size: 30px; font-weight:bold"> Latest News </p>
""", unsafe_allow_html=True)
st.write(" ")
news = GoogleNews()
news = GoogleNews("en", "d")
news.search("Litecoin")
news.get_page(1)
result = news.result()
st.write("1. " + result[1]["title"])
st.info("1. " + result[1]["link"])
st.write("2. " + result[2]["title"])
st.info("2. " + result[2]["link"])
st.write("3. " + result[3]["title"])
st.info("3. " + result[3]["link"])
st.write("4. " + result[4]["title"])
st.info("4. " + result[4]["link"])
st.write("5. " + result[5]["title"])
st.info("5. " + result[5]["link"])
# Sentiment Analysis
st.write(" ")
st.write(""" <p style=" color:#FFCC00; font-size: 30px; font-weight:bold"> How generally users feel about cryptocurrency? </p>
""", unsafe_allow_html=True)
st.write(" ")
df = get_tweets(api_key, api_secret, "#cryptocurrency")
df["Tweets"] = df["Tweets"].apply(Clean)
df["Subjectivity"] = df["Tweets"].apply(subjectivity)
df["Polarity"] = df["Tweets"].apply(polarity)
#WordCloud
words = " ".join([twts for twts in df["Tweets"]])
cloud = WordCloud(random_state = 21, max_font_size = 100).generate(words)
plt.imshow(cloud, interpolation = "bilinear")
plt.axis("off")
st.pyplot()
st.write(" ")
st.write(""" <p style=" color:#FFCC00; font-size: 30px; font-weight:bold"> Sentiment Bar Plot </p>
""", unsafe_allow_html=True)
st.write(" ")
# Get Sentiment tweets
df["Sentiment"] = df["Polarity"].apply(sentiment)
df["Sentiment"].value_counts().plot(kind = "bar", figsize = (10,5))
plt.title("Sentiment Analysis Bar Plot")
plt.xlabel("Sentiment")
plt.ylabel("Number of Tweets")
st.pyplot()
| app.py | 31,779 | Funtions load data from yahoo finance Plot raw data prepare data for forecasting train and forecast plot forecast st.write(df[selected_curr]) Getting API_KEYS Function for getting tweets Create authentication Create a cursor object Store the tweets Clean text Subjectivity and Polarity Create a function to get sentiment text MACD Bollinger Bands Resistence Strength Indicator Predict forecast with Prophet.Plot MACD Bollinger Bands Resistence Strength Indicator Predict forecast with Prophet. MACD Bollinger Bands Resistence Strength Indicator Predict forecast with Prophet. MACD Bollinger Bands Resistence Strength Indicator Predict forecast with Prophet. MACD Bollinger Bands Resistence Strength Indicator Predict forecast with Prophet. MACD Bollinger Bands Resistence Strength Indicator Predict forecast with Prophet. MACD Bollinger Bands Resistence Strength Indicator Predict forecast with Prophet. Sentiment AnalysisWordCloud Get Sentiment tweets | 953 | en | 0.644719 |
"""adding cluster control options on every level
Revision ID: a987c6ce888d
Revises: 00c5cc87408d
Create Date: 2018-08-01 18:34:00.415937
"""
import logging
from alembic import op
import sqlalchemy as sa
revision = 'a987c6ce888d'
down_revision = '8079a1cb5874'
branch_labels = None
depends_on = None
logger = logging.getLogger('alembic.' + revision)
CLUSTER_CONF_OPTIONS = ['cluster_enabled', 'cluster_tfidf_enabled',
'cluster_same_category', 'cluster_same_feed',
'cluster_wake_up']
def upgrade():
op.drop_column('category', 'cluster_on_title')
for table in 'user', 'feed', 'category':
logger.info('adding cluster control options on %s', table)
for option in CLUSTER_CONF_OPTIONS:
op.add_column(table, sa.Column(option, sa.Boolean(),
default=None, nullable=True))
op.add_column(table, sa.Column('cluster_conf', sa.PickleType(),
default={}, nullable=True))
logger.info('setting default options to true for users')
op.execute('UPDATE "user" SET %s;'
% ', '.join(["%s=true" % opt for opt in CLUSTER_CONF_OPTIONS]))
for option in CLUSTER_CONF_OPTIONS:
op.alter_column('user', option, nullable=False)
def downgrade():
for table in 'user', 'feed', 'category':
for option in CLUSTER_CONF_OPTIONS:
op.drop_column(table, option)
op.add_column('category', sa.Column('cluster_on_title',
sa.BOOLEAN(), autoincrement=False, nullable=True))
| python-news_aggregator/migrations/versions/20180830_cluster_control.py | 1,580 | adding cluster control options on every level
Revision ID: a987c6ce888d
Revises: 00c5cc87408d
Create Date: 2018-08-01 18:34:00.415937 | 134 | en | 0.452449 |
import os
import time
import re
from flask import url_for
from . util import set_original_response, set_modified_response, live_server_setup
import logging
from changedetectionio.notification import default_notification_body, default_notification_title
# Hard to just add more live server URLs when one test is already running (I think)
# So we add our test here (was in a different file)
def test_check_notification(client, live_server):
live_server_setup(live_server)
set_original_response()
# Give the endpoint time to spin up
time.sleep(3)
# Re 360 - new install should have defaults set
res = client.get(url_for("settings_page"))
assert default_notification_body.encode() in res.data
assert default_notification_title.encode() in res.data
# When test mode is in BASE_URL env mode, we should see this already configured
env_base_url = os.getenv('BASE_URL', '').strip()
if len(env_base_url):
logging.debug(">>> BASE_URL enabled, looking for %s", env_base_url)
res = client.get(url_for("settings_page"))
assert bytes(env_base_url.encode('utf-8')) in res.data
else:
logging.debug(">>> SKIPPING BASE_URL check")
# re #242 - when you edited an existing new entry, it would not correctly show the notification settings
# Add our URL to the import page
test_url = url_for('test_endpoint', _external=True)
res = client.post(
url_for("api_watch_add"),
data={"url": test_url, "tag": ''},
follow_redirects=True
)
assert b"Watch added" in res.data
# Give the thread time to pick up the first version
time.sleep(3)
# Goto the edit page, add our ignore text
# Add our URL to the import page
url = url_for('test_notification_endpoint', _external=True)
notification_url = url.replace('http', 'json')
print (">>>> Notification URL: "+notification_url)
res = client.post(
url_for("edit_page", uuid="first"),
data={"notification_urls": notification_url,
"notification_title": "New ChangeDetection.io Notification - {watch_url}",
"notification_body": "BASE URL: {base_url}\n"
"Watch URL: {watch_url}\n"
"Watch UUID: {watch_uuid}\n"
"Watch title: {watch_title}\n"
"Watch tag: {watch_tag}\n"
"Preview: {preview_url}\n"
"Diff URL: {diff_url}\n"
"Snapshot: {current_snapshot}\n"
"Diff: {diff}\n"
"Diff Full: {diff_full}\n"
":-)",
"notification_format": "Text",
"url": test_url,
"tag": "my tag",
"title": "my title",
"headers": "",
"fetch_backend": "html_requests",
"trigger_check": "y"},
follow_redirects=True
)
assert b"Updated watch." in res.data
assert b"Test notification queued" in res.data
# Hit the edit page, be sure that we saved it
res = client.get(
url_for("edit_page", uuid="first"))
assert bytes(notification_url.encode('utf-8')) in res.data
# Re #242 - wasnt saving?
assert bytes("New ChangeDetection.io Notification".encode('utf-8')) in res.data
# Because we hit 'send test notification on save'
time.sleep(3)
notification_submission = None
# Verify what was sent as a notification, this file should exist
with open("test-datastore/notification.txt", "r") as f:
notification_submission = f.read()
# Did we see the URL that had a change, in the notification?
assert test_url in notification_submission
os.unlink("test-datastore/notification.txt")
set_modified_response()
# Trigger a check
client.get(url_for("api_watch_checknow"), follow_redirects=True)
# Give the thread time to pick it up
time.sleep(3)
# Did the front end see it?
res = client.get(
url_for("index"))
assert bytes("just now".encode('utf-8')) in res.data
notification_submission=None
# Verify what was sent as a notification
with open("test-datastore/notification.txt", "r") as f:
notification_submission = f.read()
# Did we see the URL that had a change, in the notification?
assert test_url in notification_submission
# Diff was correctly executed
assert "Diff Full: Some initial text" in notification_submission
assert "Diff: (changed) Which is across multiple lines" in notification_submission
assert "(-> into) which has this one new line" in notification_submission
if env_base_url:
# Re #65 - did we see our BASE_URl ?
logging.debug (">>> BASE_URL checking in notification: %s", env_base_url)
assert env_base_url in notification_submission
else:
logging.debug(">>> Skipping BASE_URL check")
## Now configure something clever, we go into custom config (non-default) mode, this is returned by the endpoint
with open("test-datastore/endpoint-content.txt", "w") as f:
f.write(";jasdhflkjadshf kjhsdfkjl ahslkjf haslkjd hfaklsj hf\njl;asdhfkasj stuff we will detect\n")
res = client.post(
url_for("settings_page"),
data={"notification_title": "New ChangeDetection.io Notification - {watch_url}",
"notification_urls": "json://foobar.com", #Re #143 should not see that it sent without [test checkbox]
"minutes_between_check": 180,
"fetch_backend": "html_requests",
},
follow_redirects=True
)
assert b"Settings updated." in res.data
# Re #143 - should not see this if we didnt hit the test box
assert b"Test notification queued" not in res.data
# Trigger a check
client.get(url_for("api_watch_checknow"), follow_redirects=True)
# Give the thread time to pick it up
time.sleep(3)
# Did the front end see it?
res = client.get(
url_for("index"))
assert bytes("just now".encode('utf-8')) in res.data
with open("test-datastore/notification.txt", "r") as f:
notification_submission = f.read()
print ("Notification submission was:", notification_submission)
# Re #342 - check for accidental python byte encoding of non-utf8/string
assert "b'" not in notification_submission
assert re.search('Watch UUID: [0-9a-f]{8}(-[0-9a-f]{4}){3}-[0-9a-f]{12}', notification_submission, re.IGNORECASE)
assert "Watch title: my title" in notification_submission
assert "Watch tag: my tag" in notification_submission
assert "diff/" in notification_submission
assert "preview/" in notification_submission
assert ":-)" in notification_submission
assert "New ChangeDetection.io Notification - {}".format(test_url) in notification_submission
# This should insert the {current_snapshot}
assert "stuff we will detect" in notification_submission
# Prove that "content constantly being marked as Changed with no Updating causes notification" is not a thing
# https://github.com/dgtlmoon/changedetection.io/discussions/192
os.unlink("test-datastore/notification.txt")
# Trigger a check
client.get(url_for("api_watch_checknow"), follow_redirects=True)
time.sleep(3)
client.get(url_for("api_watch_checknow"), follow_redirects=True)
time.sleep(3)
client.get(url_for("api_watch_checknow"), follow_redirects=True)
time.sleep(3)
assert os.path.exists("test-datastore/notification.txt") == False
# Now adding a wrong token should give us an error
res = client.post(
url_for("settings_page"),
data={"notification_title": "New ChangeDetection.io Notification - {watch_url}",
"notification_body": "Rubbish: {rubbish}\n",
"notification_format": "Text",
"notification_urls": "json://foobar.com",
"minutes_between_check": 180,
"fetch_backend": "html_requests"
},
follow_redirects=True
)
assert bytes("is not a valid token".encode('utf-8')) in res.data
# Re #360 some validation
res = client.post(
url_for("edit_page", uuid="first"),
data={"notification_urls": notification_url,
"notification_title": "",
"notification_body": "",
"notification_format": "Text",
"url": test_url,
"tag": "my tag",
"title": "my title",
"headers": "",
"fetch_backend": "html_requests",
"trigger_check": "y"},
follow_redirects=True
)
assert b"Notification Body and Title is required when a Notification URL is used" in res.data
| changedetectionio/tests/test_notification.py | 8,929 | Hard to just add more live server URLs when one test is already running (I think) So we add our test here (was in a different file) Give the endpoint time to spin up Re 360 - new install should have defaults set When test mode is in BASE_URL env mode, we should see this already configured re 242 - when you edited an existing new entry, it would not correctly show the notification settings Add our URL to the import page Give the thread time to pick up the first version Goto the edit page, add our ignore text Add our URL to the import page Hit the edit page, be sure that we saved it Re 242 - wasnt saving? Because we hit 'send test notification on save' Verify what was sent as a notification, this file should exist Did we see the URL that had a change, in the notification? Trigger a check Give the thread time to pick it up Did the front end see it? Verify what was sent as a notification Did we see the URL that had a change, in the notification? Diff was correctly executed Re 65 - did we see our BASE_URl ? Now configure something clever, we go into custom config (non-default) mode, this is returned by the endpointRe 143 should not see that it sent without [test checkbox] Re 143 - should not see this if we didnt hit the test box Trigger a check Give the thread time to pick it up Did the front end see it? Re 342 - check for accidental python byte encoding of non-utf8/string This should insert the {current_snapshot} Prove that "content constantly being marked as Changed with no Updating causes notification" is not a thing https://github.com/dgtlmoon/changedetection.io/discussions/192 Trigger a check Now adding a wrong token should give us an error Re 360 some validation | 1,692 | en | 0.920864 |
"""Connection pooling for psycopg2
This module implements thread-safe (and not) connection pools.
"""
# psycopg/pool.py - pooling code for psycopg
#
# Copyright (C) 2003-2010 Federico Di Gregorio <fog@debian.org>
#
# psycopg2 is free software: you can redistribute it and/or modify it
# under the terms of the GNU Lesser General Public License as published
# by the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# In addition, as a special exception, the copyright holders give
# permission to link this program with the OpenSSL library (or with
# modified versions of OpenSSL that use the same license as OpenSSL),
# and distribute linked combinations including the two.
#
# You must obey the GNU Lesser General Public License in all respects for
# all of the code used other than OpenSSL.
#
# psycopg2 is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
# FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public
# License for more details.
import psycopg2
import psycopg2.extensions as _ext
class PoolError(psycopg2.Error):
pass
class AbstractConnectionPool(object):
"""Generic key-based pooling code."""
def __init__(self, minconn, maxconn, *args, **kwargs):
"""Initialize the connection pool.
New 'minconn' connections are created immediately calling 'connfunc'
with given parameters. The connection pool will support a maximum of
about 'maxconn' connections.
"""
self.minconn = int(minconn)
self.maxconn = int(maxconn)
self.closed = False
self._args = args
self._kwargs = kwargs
self._pool = []
self._used = {}
self._rused = {} # id(conn) -> key map
self._keys = 0
for i in range(self.minconn):
self._connect()
def _connect(self, key=None):
"""Create a new connection and assign it to 'key' if not None."""
conn = psycopg2.connect(*self._args, **self._kwargs)
if key is not None:
self._used[key] = conn
self._rused[id(conn)] = key
else:
self._pool.append(conn)
return conn
def _getkey(self):
"""Return a new unique key."""
self._keys += 1
return self._keys
def _getconn(self, key=None):
"""Get a free connection and assign it to 'key' if not None."""
if self.closed: raise PoolError("connection pool is closed")
if key is None: key = self._getkey()
if key in self._used:
return self._used[key]
if self._pool:
self._used[key] = conn = self._pool.pop()
self._rused[id(conn)] = key
return conn
else:
if len(self._used) == self.maxconn:
raise PoolError("connection pool exhausted")
return self._connect(key)
def _putconn(self, conn, key=None, close=False):
"""Put away a connection."""
if self.closed: raise PoolError("connection pool is closed")
if key is None: key = self._rused.get(id(conn))
if not key:
raise PoolError("trying to put unkeyed connection")
if len(self._pool) < self.minconn and not close:
# Return the connection into a consistent state before putting
# it back into the pool
if not conn.closed:
status = conn.get_transaction_status()
if status == _ext.TRANSACTION_STATUS_UNKNOWN:
# server connection lost
conn.close()
elif status != _ext.TRANSACTION_STATUS_IDLE:
# connection in error or in transaction
conn.rollback()
self._pool.append(conn)
else:
# regular idle connection
self._pool.append(conn)
# If the connection is closed, we just discard it.
else:
conn.close()
# here we check for the presence of key because it can happen that a
# thread tries to put back a connection after a call to close
if not self.closed or key in self._used:
del self._used[key]
del self._rused[id(conn)]
def _closeall(self):
"""Close all connections.
Note that this can lead to some code fail badly when trying to use
an already closed connection. If you call .closeall() make sure
your code can deal with it.
"""
if self.closed: raise PoolError("connection pool is closed")
for conn in self._pool + list(self._used.values()):
try:
conn.close()
except:
pass
self.closed = True
class SimpleConnectionPool(AbstractConnectionPool):
"""A connection pool that can't be shared across different threads."""
getconn = AbstractConnectionPool._getconn
putconn = AbstractConnectionPool._putconn
closeall = AbstractConnectionPool._closeall
class ThreadedConnectionPool(AbstractConnectionPool):
"""A connection pool that works with the threading module."""
def __init__(self, minconn, maxconn, *args, **kwargs):
"""Initialize the threading lock."""
import threading
AbstractConnectionPool.__init__(
self, minconn, maxconn, *args, **kwargs)
self._lock = threading.Lock()
def getconn(self, key=None):
"""Get a free connection and assign it to 'key' if not None."""
self._lock.acquire()
try:
return self._getconn(key)
finally:
self._lock.release()
def putconn(self, conn=None, key=None, close=False):
"""Put away an unused connection."""
self._lock.acquire()
try:
self._putconn(conn, key, close)
finally:
self._lock.release()
def closeall(self):
"""Close all connections (even the one currently in use.)"""
self._lock.acquire()
try:
self._closeall()
finally:
self._lock.release()
class PersistentConnectionPool(AbstractConnectionPool):
"""A pool that assigns persistent connections to different threads.
Note that this connection pool generates by itself the required keys
using the current thread id. This means that until a thread puts away
a connection it will always get the same connection object by successive
`!getconn()` calls. This also means that a thread can't use more than one
single connection from the pool.
"""
def __init__(self, minconn, maxconn, *args, **kwargs):
"""Initialize the threading lock."""
import warnings
warnings.warn("deprecated: use ZPsycopgDA.pool implementation",
DeprecationWarning)
import threading
AbstractConnectionPool.__init__(
self, minconn, maxconn, *args, **kwargs)
self._lock = threading.Lock()
# we we'll need the thread module, to determine thread ids, so we
# import it here and copy it in an instance variable
import _thread as _thread # work around for 2to3 bug - see ticket #348
self.__thread = _thread
def getconn(self):
"""Generate thread id and return a connection."""
key = self.__thread.get_ident()
self._lock.acquire()
try:
return self._getconn(key)
finally:
self._lock.release()
def putconn(self, conn=None, close=False):
"""Put away an unused connection."""
key = self.__thread.get_ident()
self._lock.acquire()
try:
if not conn: conn = self._used[key]
self._putconn(conn, key, close)
finally:
self._lock.release()
def closeall(self):
"""Close all connections (even the one currently in use.)"""
self._lock.acquire()
try:
self._closeall()
finally:
self._lock.release()
| lexis/Lib/site-packages/psycopg2/pool.py | 8,136 | Generic key-based pooling code.
A pool that assigns persistent connections to different threads.
Note that this connection pool generates by itself the required keys
using the current thread id. This means that until a thread puts away
a connection it will always get the same connection object by successive
`!getconn()` calls. This also means that a thread can't use more than one
single connection from the pool.
A connection pool that can't be shared across different threads.
A connection pool that works with the threading module.
Initialize the connection pool.
New 'minconn' connections are created immediately calling 'connfunc'
with given parameters. The connection pool will support a maximum of
about 'maxconn' connections.
Initialize the threading lock.
Initialize the threading lock.
Close all connections.
Note that this can lead to some code fail badly when trying to use
an already closed connection. If you call .closeall() make sure
your code can deal with it.
Create a new connection and assign it to 'key' if not None.
Get a free connection and assign it to 'key' if not None.
Return a new unique key.
Put away a connection.
Close all connections (even the one currently in use.)
Close all connections (even the one currently in use.)
Get a free connection and assign it to 'key' if not None.
Generate thread id and return a connection.
Put away an unused connection.
Put away an unused connection.
Connection pooling for psycopg2
This module implements thread-safe (and not) connection pools.
psycopg/pool.py - pooling code for psycopg Copyright (C) 2003-2010 Federico Di Gregorio <fog@debian.org> psycopg2 is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. In addition, as a special exception, the copyright holders give permission to link this program with the OpenSSL library (or with modified versions of OpenSSL that use the same license as OpenSSL), and distribute linked combinations including the two. You must obey the GNU Lesser General Public License in all respects for all of the code used other than OpenSSL. psycopg2 is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. id(conn) -> key map Return the connection into a consistent state before putting it back into the pool server connection lost connection in error or in transaction regular idle connection If the connection is closed, we just discard it. here we check for the presence of key because it can happen that a thread tries to put back a connection after a call to close we we'll need the thread module, to determine thread ids, so we import it here and copy it in an instance variable work around for 2to3 bug - see ticket 348 | 3,002 | en | 0.893032 |
# -*- coding: utf-8 -*-
# Copyright (c) 2016-2022 by University of Kassel and Fraunhofer Institute for Energy Economics
# and Energy System Technology (IEE), Kassel. All rights reserved.
from math import pi
from numpy import sign, nan, append, zeros, array, sqrt, where
from numpy import max as max_
from pandas import Series, DataFrame, concat
from pandapower.pypower.idx_gen import GEN_BUS, PMIN, PMAX, QMIN, QMAX, GEN_STATUS
from pandapower.pypower.idx_cost import COST, NCOST
from pandapower.pypower.idx_bus import BUS_I, BASE_KV
import pandapower as pp
try:
import pandaplan.core.pplog as logging
except ImportError:
import logging
logger = logging.getLogger(__name__)
try:
from pypower import ppoption, runpf, runopf, rundcpf, rundcopf
ppopt = ppoption.ppoption(VERBOSE=0, OUT_ALL=0)
pypower_import = True
except ImportError:
pypower_import = False
ppc_elms = ["bus", "branch", "gen"]
def _create_costs(net, ppc, gen_lookup, type, idx):
if ppc['gencost'][idx, 0] == 1:
if not len(ppc['gencost'][idx, COST:]) == 2*ppc['gencost'][idx, NCOST]:
logger.error("In gencost line %s, the number n does not fit to the number of values" %
idx)
raise NotImplementedError
pp.create_pwl_cost(net, gen_lookup.element.at[idx],
gen_lookup.element_type.at[idx],
ppc['gencost'][idx, 4:], type)
elif ppc['gencost'][idx, 0] == 2:
ncost = ppc['gencost'][idx, NCOST]
if ncost == 1:
cp2 = 0
cp1 = 0
cp0 = ppc['gencost'][idx, COST]
elif ncost == 2:
cp2 = 0
cp1 = ppc['gencost'][idx, COST]
cp0 = ppc['gencost'][idx, COST + 1]
elif ncost == 3:
cp2 = ppc['gencost'][idx, COST]
cp1 = ppc['gencost'][idx, COST + 1]
cp0 = ppc['gencost'][idx, COST + 2]
elif ncost > 3:
logger.warning("The pandapower poly_cost table only supports up to 2nd order " +
"polynomials. The ppc higher order polynomials cannot be converted.")
cp2 = ppc['gencost'][idx, COST + ncost - 3]
cp1 = ppc['gencost'][idx, COST + ncost - 2]
cp0 = ppc['gencost'][idx, COST + ncost - 1]
else:
raise ValueError("'ncost' must be an positve integer but is " + str(ncost))
pp.create_poly_cost(net, gen_lookup.element.at[idx], gen_lookup.element_type.at[idx],
cp1_eur_per_mw=cp1, cp2_eur_per_mw2=cp2, cp0_eur=cp0)
else:
logger.info("Cost mode of gencost line %s is unknown." % idx)
def _gen_bus_info(ppc, idx_gen):
bus_name = int(ppc["gen"][idx_gen, GEN_BUS])
# assumption: there is only one bus with this bus_name:
idx_bus = int(where(ppc["bus"][:, BUS_I] == bus_name)[0][0])
current_bus_type = int(ppc["bus"][idx_bus, 1])
same_bus_gen_idx = where(ppc["gen"][:, GEN_BUS] == ppc["gen"][idx_gen, GEN_BUS])[0].astype(int)
same_bus_in_service_gen_idx = same_bus_gen_idx[where(ppc["gen"][same_bus_gen_idx, GEN_STATUS] > 0)]
first_same_bus_in_service_gen_idx = same_bus_in_service_gen_idx[0] if len(
same_bus_in_service_gen_idx) else None
last_same_bus_in_service_gen_idx = same_bus_in_service_gen_idx[-1] if len(
same_bus_in_service_gen_idx) else None
return current_bus_type, idx_bus, same_bus_gen_idx, first_same_bus_in_service_gen_idx, \
last_same_bus_in_service_gen_idx
def from_ppc(ppc, f_hz=50, validate_conversion=False, **kwargs):
"""
This function converts pypower case files to pandapower net structure.
INPUT:
**ppc** : The pypower case file.
OPTIONAL:
**f_hz** (float, 50) - The frequency of the network.
**validate_conversion** (bool, False) - If True, validate_from_ppc is run after conversion.
For running the validation, the ppc must already contain the pypower
powerflow results or pypower must be importable.
****kwargs** keyword arguments for validate_from_ppc if validate_conversion is True
OUTPUT:
**net** : pandapower net.
EXAMPLE:
import pandapower.converter as pc
from pypower import case4gs
ppc_net = case4gs.case4gs()
net = pc.from_ppc(ppc_net, f_hz=60)
"""
# --- catch common failures
if Series(ppc['bus'][:, BASE_KV] <= 0).any():
logger.info('There are false baseKV given in the pypower case file.')
# --- general_parameters
baseMVA = ppc['baseMVA'] # MVA
omega = pi * f_hz # 1/s
MAX_VAL = 99999.
net = pp.create_empty_network(f_hz=f_hz, sn_mva=baseMVA)
# --- bus data -> create buses, sgen, load, shunt
for i in range(len(ppc['bus'])):
# create buses
pp.create_bus(net, name=int(ppc['bus'][i, 0]), vn_kv=ppc['bus'][i, 9], type="b",
zone=ppc['bus'][i, 10], in_service=bool(ppc['bus'][i, 1] != 4),
max_vm_pu=ppc['bus'][i, 11], min_vm_pu=ppc['bus'][i, 12])
# create sgen, load
if ppc['bus'][i, 2] > 0:
pp.create_load(net, i, p_mw=ppc['bus'][i, 2], q_mvar=ppc['bus'][i, 3],
controllable=False)
elif ppc['bus'][i, 2] < 0:
pp.create_sgen(net, i, p_mw=-ppc['bus'][i, 2], q_mvar=-ppc['bus'][i, 3],
type="", controllable=False)
elif ppc['bus'][i, 3] != 0:
pp.create_load(net, i, p_mw=ppc['bus'][i, 2], q_mvar=ppc['bus'][i, 3],
controllable=False)
# create shunt
if ppc['bus'][i, 4] != 0 or ppc['bus'][i, 5] != 0:
pp.create_shunt(net, i, p_mw=ppc['bus'][i, 4],
q_mvar=-ppc['bus'][i, 5])
# unused data of ppc: Vm, Va (partwise: in ext_grid), zone
# --- gen data -> create ext_grid, gen, sgen
gen_lookup = DataFrame(nan, columns=['element', 'element_type'],
index=range(len(ppc['gen'][:, 0])))
# if in ppc is only one gen -> numpy initially uses one dim array -> change to two dim array
if len(ppc["gen"].shape) == 1:
ppc["gen"] = array(ppc["gen"], ndmin=2)
for i in range(len(ppc['gen'][:, 0])):
current_bus_type, current_bus_idx, same_bus_gen_idx, first_same_bus_in_service_gen_idx, \
last_same_bus_in_service_gen_idx = _gen_bus_info(ppc, i)
# create ext_grid
if current_bus_type == 3:
if i == first_same_bus_in_service_gen_idx:
gen_lookup.element.loc[i] = pp.create_ext_grid(
net, bus=current_bus_idx, vm_pu=ppc['gen'][last_same_bus_in_service_gen_idx, 5],
va_degree=ppc['bus'][current_bus_idx, 8], in_service=bool(ppc['gen'][i, 7] > 0),
max_p_mw=ppc['gen'][i, PMAX], min_p_mw=ppc['gen'][i, PMIN],
max_q_mvar=ppc['gen'][i, QMAX], min_q_mvar=ppc['gen'][i, QMIN])
gen_lookup.element_type.loc[i] = 'ext_grid'
if ppc['gen'][i, 4] > ppc['gen'][i, 3]:
logger.info('min_q_mvar of gen %d must be less than max_q_mvar but is not.' % i)
if -ppc['gen'][i, 9] < -ppc['gen'][i, 8]:
logger.info('max_p_mw of gen %d must be less than min_p_mw but is not.' % i)
else:
current_bus_type = 1
# create gen
elif current_bus_type == 2:
if i == first_same_bus_in_service_gen_idx:
gen_lookup.element.loc[i] = pp.create_gen(
net, bus=current_bus_idx, vm_pu=ppc['gen'][last_same_bus_in_service_gen_idx, 5],
p_mw=ppc['gen'][i, 1],
in_service=bool(ppc['gen'][i, 7] > 0), controllable=True,
max_p_mw=ppc['gen'][i, PMAX], min_p_mw=ppc['gen'][i, PMIN],
max_q_mvar=ppc['gen'][i, QMAX], min_q_mvar=ppc['gen'][i, QMIN])
gen_lookup.element_type.loc[i] = 'gen'
if ppc['gen'][i, 1] < 0:
logger.info('p_mw of gen %d must be less than zero but is not.' % i)
if ppc['gen'][i, 4] > ppc['gen'][i, 3]:
logger.info('min_q_mvar of gen %d must be less than max_q_mvar but is not.' % i)
if -ppc['gen'][i, 9] < -ppc['gen'][i, 8]:
logger.info('max_p_mw of gen %d must be less than min_p_mw but is not.' % i)
else:
current_bus_type = 1
# create sgen
if current_bus_type == 1:
gen_lookup.element.loc[i] = pp.create_sgen(
net, bus=current_bus_idx, p_mw=ppc['gen'][i, 1],
q_mvar=ppc['gen'][i, 2], type="", in_service=bool(ppc['gen'][i, 7] > 0),
max_p_mw=ppc['gen'][i, PMAX], min_p_mw=ppc['gen'][i, PMIN],
max_q_mvar=ppc['gen'][i, QMAX], min_q_mvar=ppc['gen'][i, QMIN],
controllable=True)
gen_lookup.element_type.loc[i] = 'sgen'
if ppc['gen'][i, 1] < 0:
logger.info('p_mw of sgen %d must be less than zero but is not.' % i)
if ppc['gen'][i, 4] > ppc['gen'][i, 3]:
logger.info('min_q_mvar of gen %d must be less than max_q_mvar but is not.' % i)
if -ppc['gen'][i, 9] < -ppc['gen'][i, 8]:
logger.info('max_p_mw of gen %d must be less than min_p_mw but is not.' % i)
# unused data of ppc: Vg (partwise: in ext_grid and gen), mBase, Pc1, Pc2, Qc1min, Qc1max,
# Qc2min, Qc2max, ramp_agc, ramp_10, ramp_30,ramp_q, apf
# --- branch data -> create line, trafo
for i in range(len(ppc['branch'])):
from_bus = pp.get_element_index(net, 'bus', name=int(ppc['branch'][i, 0]))
to_bus = pp.get_element_index(net, 'bus', name=int(ppc['branch'][i, 1]))
from_vn_kv = ppc['bus'][from_bus, 9]
to_vn_kv = ppc['bus'][to_bus, 9]
if (from_vn_kv == to_vn_kv) & ((ppc['branch'][i, 8] == 0) | (ppc['branch'][i, 8] == 1)) & \
(ppc['branch'][i, 9] == 0): # create line
Zni = ppc['bus'][to_bus, 9]**2/baseMVA # ohm
max_i_ka = ppc['branch'][i, 5]/ppc['bus'][to_bus, 9]/sqrt(3)
if max_i_ka == 0.0:
max_i_ka = MAX_VAL
logger.debug("ppc branch rateA is zero -> Using MAX_VAL instead to calculate " +
"maximum branch flow")
pp.create_line_from_parameters(
net, from_bus=from_bus, to_bus=to_bus, length_km=1,
r_ohm_per_km=ppc['branch'][i, 2]*Zni, x_ohm_per_km=ppc['branch'][i, 3]*Zni,
c_nf_per_km=ppc['branch'][i, 4]/Zni/omega*1e9/2,
max_i_ka=max_i_ka, type='ol', max_loading_percent=100,
in_service=bool(ppc['branch'][i, 10]))
else: # create transformer
if from_vn_kv >= to_vn_kv:
hv_bus = from_bus
vn_hv_kv = from_vn_kv
lv_bus = to_bus
vn_lv_kv = to_vn_kv
tap_side = 'hv'
else:
hv_bus = to_bus
vn_hv_kv = to_vn_kv
lv_bus = from_bus
vn_lv_kv = from_vn_kv
tap_side = 'lv'
if from_vn_kv == to_vn_kv:
logger.warning('The pypower branch %d (from_bus, to_bus)=(%d, %d) is considered'
' as a transformer because of a ratio != 0 | 1 but it connects '
'the same voltage level', i, ppc['branch'][i, 0],
ppc['branch'][i, 1])
rk = ppc['branch'][i, 2]
xk = ppc['branch'][i, 3]
zk = (rk ** 2 + xk ** 2) ** 0.5
sn = ppc['branch'][i, 5]
if sn == 0.0:
sn = MAX_VAL
logger.debug("ppc branch rateA is zero -> Using MAX_VAL instead to calculate " +
"apparent power")
ratio_1 = 0 if ppc['branch'][i, 8] == 0 else (ppc['branch'][i, 8] - 1) * 100
i0_percent = -ppc['branch'][i, 4] * 100 * baseMVA / sn
if i0_percent < 0:
logger.info('A transformer always behaves inductive consumpting but the '
'susceptance of pypower branch %d (from_bus, to_bus)=(%d, %d) is '
'positive.', i, ppc['branch'][i, 0], ppc['branch'][i, 1])
pp.create_transformer_from_parameters(
net, hv_bus=hv_bus, lv_bus=lv_bus, sn_mva=sn, vn_hv_kv=vn_hv_kv,
vn_lv_kv=vn_lv_kv, vk_percent=sign(xk) * zk * sn * 100 / baseMVA,
vkr_percent=rk * sn * 100 / baseMVA, max_loading_percent=100,
pfe_kw=0, i0_percent=i0_percent, shift_degree=ppc['branch'][i, 9],
tap_step_percent=abs(ratio_1), tap_pos=sign(ratio_1),
tap_side=tap_side, tap_neutral=0)
# unused data of ppc: rateB, rateC
# --- gencost -> create polynomial_cost, piecewise_cost
if 'gencost' in ppc:
if len(ppc['gencost'].shape) == 1:
# reshape gencost if only one gencost is given -> no indexError
ppc['gencost'] = ppc['gencost'].reshape((1, -1))
if ppc['gencost'].shape[0] <= gen_lookup.shape[0]:
idx_p = range(ppc['gencost'].shape[0])
idx_q = []
elif ppc['gencost'].shape[0] > gen_lookup.shape[0]:
idx_p = range(gen_lookup.shape[0])
idx_q = range(gen_lookup.shape[0], ppc['gencost'].shape[0])
if ppc['gencost'].shape[0] >= 2*gen_lookup.shape[0]:
idx_p = range(gen_lookup.shape[0])
idx_q = range(gen_lookup.shape[0], 2*gen_lookup.shape[0])
for idx in idx_p:
_create_costs(net, ppc, gen_lookup, 'p', idx)
for idx in idx_q:
_create_costs(net, ppc, gen_lookup, 'q', idx)
# areas are unconverted
if validate_conversion:
logger.setLevel(logging.DEBUG)
if not validate_from_ppc(ppc, net, **kwargs):
logger.error("Validation failed.")
net._options = {}
net._options["gen_lookup"] = gen_lookup
return net
def _validate_diff_res(diff_res, max_diff_values):
to_iterate = set(max_diff_values.keys()) & {'gen_q_mvar', 'branch_p_mw', 'branch_q_mvar',
'gen_p_mw', 'bus_va_degree', 'bus_vm_pu'}
if not len(to_iterate):
logger.warning("There are no keys to validate.")
val = True
for i in to_iterate:
elm = i.split("_")[0]
sought = ["p", "q"] if elm != "bus" else ["vm", "va"]
col = int(array([0, 1])[[j in i for j in sought]][0]) if elm != "branch" else \
list(array([[0, 2], [1, 3]])[[j in i for j in sought]][0])
val &= bool(max_(abs(diff_res[elm][:, col])) < max_diff_values[i])
return val
def validate_from_ppc(ppc_net, net, pf_type="runpp", max_diff_values={
"bus_vm_pu": 1e-6, "bus_va_degree": 1e-5, "branch_p_mw": 1e-6, "branch_q_mvar": 1e-6,
"gen_p_mw": 1e-6, "gen_q_mvar": 1e-6}, run=True):
"""
This function validates the pypower case files to pandapower net structure conversion via a \
comparison of loadflow calculation results. (Hence the opf cost conversion is not validated.)
INPUT:
**ppc_net** - The pypower case file, which must already contain the pypower powerflow
results or pypower must be importable.
**net** - The pandapower network.
OPTIONAL:
**pf_type** ("runpp", string) - Type of validated power flow. Possible are ("runpp",
"rundcpp", "runopp", "rundcopp")
**max_diff_values** - Dict of maximal allowed difference values. The keys must be
'vm_pu', 'va_degree', 'p_branch_mw', 'q_branch_mvar', 'p_gen_mw' and 'q_gen_mvar' and
the values floats.
**run** (True, bool or list of two bools) - changing the value to False avoids trying to run
(optimal) loadflows. Giving a list of two bools addresses first pypower and second
pandapower.
OUTPUT:
**conversion_success** - conversion_success is returned as False if pypower or pandapower
cannot calculate a powerflow or if the maximum difference values (max_diff_values )
cannot be hold.
EXAMPLE:
import pandapower.converter as pc
net = cv.from_ppc(ppc_net, f_hz=50)
conversion_success = cv.validate_from_ppc(ppc_net, net)
NOTE:
The user has to take care that the loadflow results already are included in the provided \
ppc_net or pypower is importable.
"""
# check in case of optimal powerflow comparison whether cost information exist
if "opp" in pf_type:
if not (len(net.polynomial_cost) | len(net.piecewise_linear_cost)):
if "gencost" in ppc_net:
if not len(ppc_net["gencost"]):
logger.debug('ppc and pandapower net do not include cost information.')
return True
else:
logger.error('The pandapower net does not include cost information.')
return False
else:
logger.debug('ppc and pandapower net do not include cost information.')
return True
# guarantee run parameter as list, for pypower and pandapower (optimal) powerflow run
run = [run, run] if isinstance(run, bool) else run
# --- check pypower powerflow success, if possible
if pypower_import and run[0]:
try:
if pf_type == "runpp":
ppc_net = runpf.runpf(ppc_net, ppopt)[0]
elif pf_type == "rundcpp":
ppc_net = rundcpf.rundcpf(ppc_net, ppopt)[0]
elif pf_type == "runopp":
ppc_net = runopf.runopf(ppc_net, ppopt)
elif pf_type == "rundcopp":
ppc_net = rundcopf.rundcopf(ppc_net, ppopt)
else:
raise ValueError("The pf_type %s is unknown" % pf_type)
except:
logger.debug("The pypower run did not work.")
ppc_success = True
if 'success' in ppc_net.keys():
if ppc_net['success'] != 1:
ppc_success = False
logger.error("The given ppc data indicates an unsuccessful pypower powerflow: " +
"'ppc_net['success'] != 1'")
if (ppc_net['branch'].shape[1] < 17):
ppc_success = False
logger.error("The shape of given ppc data indicates missing pypower powerflow results.")
# --- try to run a pandapower powerflow
if run[1]:
if pf_type == "runpp":
try:
pp.runpp(net, init="dc", calculate_voltage_angles=True, trafo_model="pi")
except pp.LoadflowNotConverged:
try:
pp.runpp(net, calculate_voltage_angles=True, init="flat", trafo_model="pi")
except pp.LoadflowNotConverged:
try:
pp.runpp(net, trafo_model="pi", calculate_voltage_angles=False)
if "bus_va_degree" in max_diff_values.keys():
max_diff_values["bus_va_degree"] = 1e2 if max_diff_values[
"bus_va_degree"] < 1e2 else max_diff_values["bus_va_degree"]
logger.info("voltage_angles could be calculated.")
except pp.LoadflowNotConverged:
logger.error('The pandapower powerflow does not converge.')
elif pf_type == "rundcpp":
try:
pp.rundcpp(net, trafo_model="pi")
except pp.LoadflowNotConverged:
logger.error('The pandapower dc powerflow does not converge.')
elif pf_type == "runopp":
try:
pp.runopp(net, init="flat", calculate_voltage_angles=True)
except pp.OPFNotConverged:
try:
pp.runopp(net, init="pf", calculate_voltage_angles=True)
except (pp.OPFNotConverged, pp.LoadflowNotConverged, KeyError):
try:
pp.runopp(net, init="flat", calculate_voltage_angles=False)
logger.info("voltage_angles could be calculated.")
if "bus_va_degree" in max_diff_values.keys():
max_diff_values["bus_va_degree"] = 1e2 if max_diff_values[
"bus_va_degree"] < 1e2 else max_diff_values["bus_va_degree"]
except pp.OPFNotConverged:
try:
pp.runopp(net, init="pf", calculate_voltage_angles=False)
if "bus_va_degree" in max_diff_values.keys():
max_diff_values["bus_va_degree"] = 1e2 if max_diff_values[
"bus_va_degree"] < 1e2 else max_diff_values["bus_va_degree"]
logger.info("voltage_angles could be calculated.")
except (pp.OPFNotConverged, pp.LoadflowNotConverged, KeyError):
logger.error('The pandapower optimal powerflow does not converge.')
elif pf_type == "rundcopp":
try:
pp.rundcopp(net)
except pp.LoadflowNotConverged:
logger.error('The pandapower dc optimal powerflow does not converge.')
else:
raise ValueError("The pf_type %s is unknown" % pf_type)
# --- prepare powerflow result comparison by reordering pp results as they are in ppc results
if not ppc_success:
return False
if "opp" in pf_type:
if not net.OPF_converged:
return
elif not net.converged:
return False
# --- store pypower powerflow results
ppc_res = dict.fromkeys(ppc_elms)
ppc_res["branch"] = ppc_net['branch'][:, 13:17]
ppc_res["bus"] = ppc_net['bus'][:, 7:9]
ppc_res["gen"] = ppc_net['gen'][:, 1:3]
# --- pandapower bus result table
pp_res = dict.fromkeys(ppc_elms)
pp_res["bus"] = array(net.res_bus.sort_index()[['vm_pu', 'va_degree']])
# --- pandapower gen result table
pp_res["gen"] = zeros([1, 2])
# consideration of parallel generators via storing how much generators have been considered
# each node
# if in ppc is only one gen -> numpy initially uses one dim array -> change to two dim array
if len(ppc_net["gen"].shape) == 1:
ppc_net["gen"] = array(ppc_net["gen"], ndmin=2)
GENS = DataFrame(ppc_net['gen'][:, [0]].astype(int))
GEN_uniq = GENS.drop_duplicates()
already_used_gen = Series(zeros(GEN_uniq.shape[0]).astype(int),
index=[int(v) for v in GEN_uniq.values])
change_q_compare = []
for i, j in GENS.iterrows():
current_bus_type, current_bus_idx, same_bus_gen_idx, first_same_bus_in_service_gen_idx, \
last_same_bus_in_service_gen_idx = _gen_bus_info(ppc_net, i)
if current_bus_type == 3 and i == first_same_bus_in_service_gen_idx:
pp_res["gen"] = append(pp_res["gen"], array(net.res_ext_grid[
net.ext_grid.bus == current_bus_idx][['p_mw', 'q_mvar']]).reshape((1, 2)), 0)
elif current_bus_type == 2 and i == first_same_bus_in_service_gen_idx:
pp_res["gen"] = append(pp_res["gen"], array(net.res_gen[
net.gen.bus == current_bus_idx][['p_mw', 'q_mvar']]).reshape((1, 2)), 0)
else:
pp_res["gen"] = append(pp_res["gen"], array(net.res_sgen[
net.sgen.bus == current_bus_idx][['p_mw', 'q_mvar']])[
already_used_gen.at[int(j)]].reshape((1, 2)), 0)
already_used_gen.at[int(j)] += 1
change_q_compare += [int(j)]
pp_res["gen"] = pp_res["gen"][1:, :] # delete initial zero row
# --- pandapower branch result table
pp_res["branch"] = zeros([1, 4])
# consideration of parallel branches via storing how often branches were considered
# each node-to-node-connection
try:
init1 = concat([net.line.from_bus, net.line.to_bus], axis=1,
sort=True).drop_duplicates()
init2 = concat([net.trafo.hv_bus, net.trafo.lv_bus], axis=1,
sort=True).drop_duplicates()
except TypeError:
# legacy pandas < 0.21
init1 = concat([net.line.from_bus, net.line.to_bus], axis=1).drop_duplicates()
init2 = concat([net.trafo.hv_bus, net.trafo.lv_bus], axis=1).drop_duplicates()
init1['hv_bus'] = nan
init1['lv_bus'] = nan
init2['from_bus'] = nan
init2['to_bus'] = nan
try:
already_used_branches = concat([init1, init2], axis=0, sort=True)
except TypeError:
# pandas < 0.21 legacy
already_used_branches = concat([init1, init2], axis=0)
already_used_branches['number'] = zeros([already_used_branches.shape[0], 1]).astype(int)
BRANCHES = DataFrame(ppc_net['branch'][:, [0, 1, 8, 9]])
for i in BRANCHES.index:
from_bus = pp.get_element_index(net, 'bus', name=int(ppc_net['branch'][i, 0]))
to_bus = pp.get_element_index(net, 'bus', name=int(ppc_net['branch'][i, 1]))
from_vn_kv = ppc_net['bus'][from_bus, 9]
to_vn_kv = ppc_net['bus'][to_bus, 9]
ratio = BRANCHES[2].at[i]
angle = BRANCHES[3].at[i]
# from line results
if (from_vn_kv == to_vn_kv) & ((ratio == 0) | (ratio == 1)) & (angle == 0):
pp_res["branch"] = append(pp_res["branch"], array(net.res_line[
(net.line.from_bus == from_bus) &
(net.line.to_bus == to_bus)]
[['p_from_mw', 'q_from_mvar', 'p_to_mw', 'q_to_mvar']])[
int(already_used_branches.number.loc[
(already_used_branches.from_bus == from_bus) &
(already_used_branches.to_bus == to_bus)].values)].reshape(1, 4), 0)
already_used_branches.number.loc[(already_used_branches.from_bus == from_bus) &
(already_used_branches.to_bus == to_bus)] += 1
# from trafo results
else:
if from_vn_kv >= to_vn_kv:
pp_res["branch"] = append(pp_res["branch"], array(net.res_trafo[
(net.trafo.hv_bus == from_bus) &
(net.trafo.lv_bus == to_bus)]
[['p_hv_mw', 'q_hv_mvar', 'p_lv_mw', 'q_lv_mvar']])[
int(already_used_branches.number.loc[
(already_used_branches.hv_bus == from_bus) &
(already_used_branches.lv_bus == to_bus)].values)].reshape(1, 4), 0)
already_used_branches.number.loc[(already_used_branches.hv_bus == from_bus) &
(already_used_branches.lv_bus == to_bus)] += 1
else: # switch hv-lv-connection of pypower connection buses
pp_res["branch"] = append(pp_res["branch"], array(net.res_trafo[
(net.trafo.hv_bus == to_bus) &
(net.trafo.lv_bus == from_bus)]
[['p_lv_mw', 'q_lv_mvar', 'p_hv_mw', 'q_hv_mvar']])[
int(already_used_branches.number.loc[
(already_used_branches.hv_bus == to_bus) &
(already_used_branches.lv_bus == from_bus)].values)].reshape(1, 4), 0)
already_used_branches.number.loc[
(already_used_branches.hv_bus == to_bus) &
(already_used_branches.lv_bus == from_bus)] += 1
pp_res["branch"] = pp_res["branch"][1:, :] # delete initial zero row
# --- do the powerflow result comparison
diff_res = dict.fromkeys(ppc_elms)
diff_res["bus"] = ppc_res["bus"] - pp_res["bus"]
diff_res["bus"][:, 1] -= diff_res["bus"][0, 1] # remove va_degree offset
diff_res["branch"] = ppc_res["branch"] - pp_res["branch"]
diff_res["gen"] = ppc_res["gen"] - pp_res["gen"]
# comparison of buses with several generator units only as q sum
for i in GEN_uniq.loc[GEN_uniq[0].isin(change_q_compare)].index:
next_is = GEN_uniq.index[GEN_uniq.index > i]
if len(next_is) > 0:
next_i = next_is[0]
else:
next_i = GENS.index[-1] + 1
if (next_i - i) > 1:
diff_res["gen"][i:next_i, 1] = sum(diff_res["gen"][i:next_i, 1])
# logger info
logger.debug("Maximum voltage magnitude difference between pypower and pandapower: "
"%.2e pu" % max_(abs(diff_res["bus"][:, 0])))
logger.debug("Maximum voltage angle difference between pypower and pandapower: "
"%.2e degree" % max_(abs(diff_res["bus"][:, 1])))
logger.debug("Maximum branch flow active power difference between pypower and pandapower: "
"%.2e MW" % max_(abs(diff_res["branch"][:, [0, 2]])))
logger.debug("Maximum branch flow reactive power difference between pypower and "
"pandapower: %.2e MVAr" % max_(abs(diff_res["branch"][:, [1, 3]])))
logger.debug("Maximum active power generation difference between pypower and pandapower: "
"%.2e MW" % max_(abs(diff_res["gen"][:, 0])))
logger.debug("Maximum reactive power generation difference between pypower and pandapower: "
"%.2e MVAr" % max_(abs(diff_res["gen"][:, 1])))
if _validate_diff_res(diff_res, {"bus_vm_pu": 1e-3, "bus_va_degree": 1e-3, "branch_p_mw": 1e-6,
"branch_q_mvar": 1e-6}) and \
(max_(abs(diff_res["gen"])) > 1e-1).any():
logger.debug("The active/reactive power generation difference possibly results "
"because of a pypower error. Please validate "
"the results via pypower loadflow.") # this occurs e.g. at ppc case9
# give a return
if isinstance(max_diff_values, dict):
return _validate_diff_res(diff_res, max_diff_values)
else:
logger.debug("'max_diff_values' must be a dict.")
| pandapower/converter/pypower/from_ppc.py | 30,193 | This function converts pypower case files to pandapower net structure.
INPUT:
**ppc** : The pypower case file.
OPTIONAL:
**f_hz** (float, 50) - The frequency of the network.
**validate_conversion** (bool, False) - If True, validate_from_ppc is run after conversion.
For running the validation, the ppc must already contain the pypower
powerflow results or pypower must be importable.
****kwargs** keyword arguments for validate_from_ppc if validate_conversion is True
OUTPUT:
**net** : pandapower net.
EXAMPLE:
import pandapower.converter as pc
from pypower import case4gs
ppc_net = case4gs.case4gs()
net = pc.from_ppc(ppc_net, f_hz=60)
This function validates the pypower case files to pandapower net structure conversion via a comparison of loadflow calculation results. (Hence the opf cost conversion is not validated.)
INPUT:
**ppc_net** - The pypower case file, which must already contain the pypower powerflow
results or pypower must be importable.
**net** - The pandapower network.
OPTIONAL:
**pf_type** ("runpp", string) - Type of validated power flow. Possible are ("runpp",
"rundcpp", "runopp", "rundcopp")
**max_diff_values** - Dict of maximal allowed difference values. The keys must be
'vm_pu', 'va_degree', 'p_branch_mw', 'q_branch_mvar', 'p_gen_mw' and 'q_gen_mvar' and
the values floats.
**run** (True, bool or list of two bools) - changing the value to False avoids trying to run
(optimal) loadflows. Giving a list of two bools addresses first pypower and second
pandapower.
OUTPUT:
**conversion_success** - conversion_success is returned as False if pypower or pandapower
cannot calculate a powerflow or if the maximum difference values (max_diff_values )
cannot be hold.
EXAMPLE:
import pandapower.converter as pc
net = cv.from_ppc(ppc_net, f_hz=50)
conversion_success = cv.validate_from_ppc(ppc_net, net)
NOTE:
The user has to take care that the loadflow results already are included in the provided ppc_net or pypower is importable.
-*- coding: utf-8 -*- Copyright (c) 2016-2022 by University of Kassel and Fraunhofer Institute for Energy Economics and Energy System Technology (IEE), Kassel. All rights reserved. assumption: there is only one bus with this bus_name: --- catch common failures --- general_parameters MVA 1/s --- bus data -> create buses, sgen, load, shunt create buses create sgen, load create shunt unused data of ppc: Vm, Va (partwise: in ext_grid), zone --- gen data -> create ext_grid, gen, sgen if in ppc is only one gen -> numpy initially uses one dim array -> change to two dim array create ext_grid create gen create sgen unused data of ppc: Vg (partwise: in ext_grid and gen), mBase, Pc1, Pc2, Qc1min, Qc1max, Qc2min, Qc2max, ramp_agc, ramp_10, ramp_30,ramp_q, apf --- branch data -> create line, trafo create line ohm create transformer unused data of ppc: rateB, rateC --- gencost -> create polynomial_cost, piecewise_cost reshape gencost if only one gencost is given -> no indexError areas are unconverted check in case of optimal powerflow comparison whether cost information exist guarantee run parameter as list, for pypower and pandapower (optimal) powerflow run --- check pypower powerflow success, if possible --- try to run a pandapower powerflow --- prepare powerflow result comparison by reordering pp results as they are in ppc results --- store pypower powerflow results --- pandapower bus result table --- pandapower gen result table consideration of parallel generators via storing how much generators have been considered each node if in ppc is only one gen -> numpy initially uses one dim array -> change to two dim array delete initial zero row --- pandapower branch result table consideration of parallel branches via storing how often branches were considered each node-to-node-connection legacy pandas < 0.21 pandas < 0.21 legacy from line results from trafo results switch hv-lv-connection of pypower connection buses delete initial zero row --- do the powerflow result comparison remove va_degree offset comparison of buses with several generator units only as q sum logger info this occurs e.g. at ppc case9 give a return | 4,275 | en | 0.720885 |
from setuptools import setup, find_packages
import os
setup(name='avenue',
version=0.1,
description='Element AI car Simulator',
url='https://github.com/cyrilibrahim/Avenue',
author='ElementAI',
author_email='cyril.ibrahim@elementai.com',
license='',
zip_safe=False,
install_requires=[
"gdown",
# "mlagents==0.5.0",
"gym",
# "mlagents_frozen",
"mlagents @ git+https://git@github.com/rmst/ml-agents-frozen@fd10e3544472b365701da2526a8262e0c8a15784#egg=mlagents",
],
extras_require={},
packages=find_packages()
)
| setup.py | 636 | "mlagents==0.5.0", "mlagents_frozen", | 37 | en | 0.642155 |
import collections
Set = set
KEY, PREV, NEXT = range(3)
class OrderedSet(collections.MutableSet):
"""
From: http://code.activestate.com/recipes/576694/
"""
def __init__(self, iterable=None):
self.end = end = []
end += [None, end, end] # sentinel node for doubly linked list
self.map = {} # key --> [key, prev, next]
if iterable is not None:
self |= iterable
def __len__(self):
return len(self.map)
def __contains__(self, key):
return key in self.map
def add(self, key):
if key not in self.map:
end = self.end
curr = end[PREV]
curr[NEXT] = end[PREV] = self.map[key] = [key, curr, end]
def discard(self, key):
if key in self.map:
key, prev, next = self.map.pop(key)
prev[NEXT] = next
next[PREV] = prev
def __iter__(self):
end = self.end
curr = end[NEXT]
while curr is not end:
yield curr[KEY]
curr = curr[NEXT]
def __reversed__(self):
end = self.end
curr = end[PREV]
while curr is not end:
yield curr[KEY]
curr = curr[PREV]
def pop(self, last=True):
if not self:
raise KeyError('set is empty')
key = next(reversed(self)) if last else next(iter(self))
self.discard(key)
return key
def __repr__(self):
if not self:
return '%s()' % (self.__class__.__name__,)
return '%s(%r)' % (self.__class__.__name__, list(self))
def __eq__(self, other):
if isinstance(other, OrderedSet):
return len(self) == len(other) and list(self) == list(other)
return set(self) == set(other)
def __del__(self):
self.clear() # remove circular references
if __name__=="__main__":
a = OrderedSet()
| fastv8/doc/_extensions/backports.py | 1,735 | From: http://code.activestate.com/recipes/576694/
sentinel node for doubly linked list key --> [key, prev, next] remove circular references | 141 | en | 0.640277 |
#!/usr/bin/env python3
import RPi.GPIO as GPIO
import time
import threading
import logging
import pandas as pd
import numpy as np
from tzlocal import get_localzone
from flask import Flask, render_template, url_for, request
logging.basicConfig(level=logging.INFO,
format='%(asctime)s - %(threadName)s - %(name)s - %(levelname)s - %(message)s')
GPIO.setmode(GPIO.BCM)
logger = logging.getLogger(__name__)
from rpiweather import temphumid
from rpiweather import temppressure
from rpiweather import data
from rpiweather import outside_weather
from rpiweather import dust
temppressure.start_recording()
temphumid.start_recording()
outside_weather.start_recording()
dust.start_recording()
app = Flask("rpiweather")
def format_timestamps(series):
local_tz = get_localzone()
return list(
str(dt.tz_localize("UTC").tz_convert(local_tz)) for dt in series
)
@app.route("/")
def index():
lookbehind = int(request.args.get('lookbehind', 24))
bigarray = data.get_recent_datapoints(lookbehind)
logger.info("Total datapoint count: %d" % len(bigarray))
df = pd.DataFrame(bigarray, columns=['time', 'type', 'value'])
df['time'] = pd.to_datetime(df['time'])
df = df.set_index('time')
agg_interval = "15T" if lookbehind < 168 else "1H" if lookbehind < 5040 else "1D"
df2 = df.pivot(columns='type', values='value').resample(agg_interval).mean()
temp_df = df2['temperature'].dropna()
temp_values = {
'x': format_timestamps(temp_df.index),
'y': list(temp_df),
'name': 'Temperature',
'type': 'line',
'line': {
'color': 'rgb(244, 66, 98)'
}
}
outside_temp_df = df2['outside_temperature'].dropna()
ot_values = {
'x': format_timestamps(outside_temp_df.index),
'y': list(outside_temp_df),
'name': 'Temperature Outside',
'type': 'line',
'line': {
'color': 'rgb(244, 66, 98)',
'dash': 'longdash'
}
}
pres_df = df2['pressure'].dropna()
pressure_values = {
'x': format_timestamps(pres_df.index),
'y': list(pres_df),
'name': 'Pressure',
'type': 'line',
'yaxis': 'y2',
'line': {
'dash': 'dot',
'color': 'rgb(151,138,155)'
}
}
hum_df = df2['humidity'].dropna()
humidity_values = {
'x': format_timestamps(hum_df.index),
'y': list(hum_df),
'name': 'Humidity',
'type': 'scatter',
'fill': 'tozeroy',
'yaxis': 'y3',
'marker': {
'color': 'rgb(66,131,244)'
}
}
dust_df = df2['dust'].dropna()
dust_values = {
'x': format_timestamps(dust_df.index),
'y': list(dust_df),
'name': 'Dust level',
'type': 'line',
'yaxis': 'y4',
'line': {
'dash': 'dot',
'color': 'rgb(224, 205, 31)'
}
}
chart_data = [
temp_values, pressure_values, humidity_values, ot_values, dust_values
]
#import pdb; pdb.set_trace()
lookbehind_options = [(24, "1d"),
(24*7, "1w"),
(24*7*30, "30d")]
return render_template("index.html",
weather_data=chart_data,
lookbehind_options=lookbehind_options,
lookbehind=lookbehind)
def make_agg_df(rec):
df = pd.DataFrame.from_records(rec, index="time")
df.index = pd.to_datetime(df.index, unit="s")
return df.resample("T").mean()
def magic():
df_tp = make_agg_df(temppressure.get_records())
df_th = make_agg_df(temphumid.get_records())
df_th = df_th.rename(columns={'temp': 'bad_temp'})
total_view = pd.concat([df_tp, df_th], axis=1)
return total_view
#import IPython
# IPython.embed()
if False:
bigarray = data.get_recent_datapoints()
df = pd.DataFrame(bigarray, columns=['time', 'type', 'value'])
df['time'] = pd.to_datetime(df['time'])
df = df.set_index('time')
df2 = df.pivot(columns='type', values='value').resample("5T").mean()
temp_values = list(zip(
(dt.timestamp() for dt in df2.index),
df2['temperature']
))
pressure_values = list(zip(
(dt.timestamp() for dt in df2.index),
df2['pressure']
))
humidity_values = list(zip(
(dt.timestamp() for dt in df2.index),
df2['humidity']
))
| rpiweather/server.py | 4,434 | !/usr/bin/env python3import pdb; pdb.set_trace()import IPython IPython.embed() | 78 | en | 0.355495 |
# -*- coding:utf-8 -*-
# /usr/bin/env python
"""
Date: 2019/10/30 11:28
Desc: 新浪财经-A股-实时行情数据和历史行情数据(包含前复权和后复权因子)
"""
import re
import demjson
import execjs
import pandas as pd
import requests
from tqdm import tqdm
from akshare.stock.cons import (zh_sina_a_stock_payload,
zh_sina_a_stock_url,
zh_sina_a_stock_count_url,
zh_sina_a_stock_hist_url,
hk_js_decode,
zh_sina_a_stock_hfq_url,
zh_sina_a_stock_qfq_url,
zh_sina_a_stock_amount_url)
def _get_zh_a_page_count() -> int:
"""
所有股票的总页数
http://vip.stock.finance.sina.com.cn/mkt/#hs_a
:return: 需要抓取的股票总页数
:rtype: int
"""
res = requests.get(zh_sina_a_stock_count_url)
page_count = int(re.findall(re.compile(r"\d+"), res.text)[0]) / 80
if isinstance(page_count, int):
return page_count
else:
return int(page_count) + 1
def stock_zh_a_spot() -> pd.DataFrame:
"""
从新浪财经-A股获取所有A股的实时行情数据, 重复运行本函数会被新浪暂时封 IP
http://vip.stock.finance.sina.com.cn/mkt/#qbgg_hk
:return: pandas.DataFrame
symbol code name trade pricechange changepercent buy \
0 sh600000 600000 浦发银行 12.920 -0.030 -0.232 12.920
1 sh600004 600004 白云机场 18.110 -0.370 -2.002 18.110
2 sh600006 600006 东风汽车 4.410 -0.030 -0.676 4.410
3 sh600007 600007 中国国贸 17.240 -0.360 -2.045 17.240
4 sh600008 600008 首创股份 3.320 -0.030 -0.896 3.310
... ... ... ... ... ... ...
3755 sh600096 600096 云天化 5.270 -0.220 -4.007 5.270
3756 sh600097 600097 开创国际 10.180 -0.120 -1.165 10.180
3757 sh600098 600098 广州发展 6.550 -0.040 -0.607 6.540
3758 sh600099 600099 林海股份 6.540 -0.150 -2.242 6.540
3759 sh600100 600100 同方股份 8.200 -0.100 -1.205 8.200
sell settlement open high low volume amount \
0 12.930 12.950 12.950 13.100 12.860 46023920 597016896
1 18.120 18.480 18.510 18.510 17.880 24175071 437419344
2 4.420 4.440 4.490 4.490 4.410 4304900 19130233
3 17.280 17.600 17.670 17.670 17.220 684801 11879731
4 3.320 3.350 3.360 3.360 3.300 8284294 27579688
... ... ... ... ... ... ...
3755 5.280 5.490 5.490 5.500 5.220 16964636 90595172
3756 10.190 10.300 10.220 10.340 10.090 1001676 10231669
3757 6.550 6.590 6.560 6.620 6.500 1996449 13098901
3758 6.580 6.690 6.650 6.680 6.530 1866180 12314997
3759 8.210 8.300 8.300 8.310 8.120 12087236 99281447
ticktime per pb mktcap nmc turnoverratio
0 15:00:00 6.984 0.790 3.792289e+07 3.631006e+07 0.16376
1 15:00:07 32.927 2.365 3.747539e+06 3.747539e+06 1.16826
2 15:00:02 15.926 1.207 8.820000e+05 8.820000e+05 0.21525
3 15:00:02 22.390 2.367 1.736555e+06 1.736555e+06 0.06798
4 15:00:07 22.912 1.730 1.887569e+06 1.600444e+06 0.17185
... ... ... ... ... ...
3755 15:00:00 56.728 1.566 7.523847e+05 6.963668e+05 1.28386
3756 15:00:00 17.552 1.434 2.452734e+05 2.303459e+05 0.44268
3757 15:00:00 25.476 1.059 1.785659e+06 1.785659e+06 0.07323
3758 15:00:00 540.496 3.023 1.433045e+05 1.433045e+05 0.85167
3759 15:00:07 -6.264 1.465 2.430397e+06 2.430397e+06 0.40782
"""
big_df = pd.DataFrame()
page_count = _get_zh_a_page_count()
zh_sina_stock_payload_copy = zh_sina_a_stock_payload.copy()
for page in tqdm(range(1, page_count+1), desc="Please wait for a moment"):
zh_sina_stock_payload_copy.update({"page": page})
r = requests.get(
zh_sina_a_stock_url,
params=zh_sina_stock_payload_copy)
data_json = demjson.decode(r.text)
big_df = big_df.append(pd.DataFrame(data_json), ignore_index=True)
return big_df
def stock_zh_a_daily(symbol: str = "sz000613", adjust: str = "qfq") -> pd.DataFrame:
"""
新浪财经-A股-个股的历史行情数据, 大量抓取容易封IP
:param symbol: sh600000
:type symbol: str
:param adjust: 默认为空: 返回不复权的数据; qfq: 返回前复权后的数据; hfq: 返回后复权后的数据; hfq-factor: 返回后复权因子; hfq-factor: 返回前复权因子
:type adjust: str
:return: specific data
:rtype: pandas.DataFrame
"""
res = requests.get(zh_sina_a_stock_hist_url.format(symbol))
js_code = execjs.compile(hk_js_decode)
dict_list = js_code.call(
'd', res.text.split("=")[1].split(";")[0].replace(
'"', "")) # 执行js解密代码
data_df = pd.DataFrame(dict_list)
data_df["date"] = data_df["date"].str.split("T", expand=True).iloc[:, 0]
data_df.index = pd.to_datetime(data_df["date"])
del data_df["date"]
data_df = data_df.astype("float")
r = requests.get(zh_sina_a_stock_amount_url.format(symbol, symbol))
amount_data_json = demjson.decode(r.text[r.text.find("["): r.text.rfind("]") + 1])
amount_data_df = pd.DataFrame(amount_data_json)
amount_data_df.index = pd.to_datetime(amount_data_df.date)
del amount_data_df["date"]
temp_df = pd.merge(data_df, amount_data_df, left_index=True, right_index=True, how="left")
temp_df.fillna(method="ffill", inplace=True)
temp_df = temp_df.astype(float)
temp_df["amount"] = temp_df["amount"] * 10000
temp_df["turnover"] = temp_df["volume"] / temp_df["amount"]
temp_df.columns = ['open', 'high', 'low', 'close', 'volume', 'outstanding_share', 'turnover']
if adjust == "":
return temp_df
if adjust == "hfq":
res = requests.get(zh_sina_a_stock_hfq_url.format(symbol))
hfq_factor_df = pd.DataFrame(
eval(res.text.split("=")[1].split("\n")[0])['data'])
hfq_factor_df.columns = ["date", "hfq_factor"]
hfq_factor_df.index = pd.to_datetime(hfq_factor_df.date)
del hfq_factor_df["date"]
temp_df = pd.merge(
temp_df, hfq_factor_df, left_index=True, right_index=True, how="left"
)
temp_df.fillna(method="ffill", inplace=True)
temp_df = temp_df.astype(float)
temp_df["open"] = temp_df["open"] * temp_df["hfq_factor"]
temp_df["high"] = temp_df["high"] * temp_df["hfq_factor"]
temp_df["close"] = temp_df["close"] * temp_df["hfq_factor"]
temp_df["low"] = temp_df["low"] * temp_df["hfq_factor"]
return temp_df.iloc[:, :-1]
if adjust == "qfq":
res = requests.get(zh_sina_a_stock_qfq_url.format(symbol))
qfq_factor_df = pd.DataFrame(
eval(res.text.split("=")[1].split("\n")[0])['data'])
qfq_factor_df.columns = ["date", "qfq_factor"]
qfq_factor_df.index = pd.to_datetime(qfq_factor_df.date)
del qfq_factor_df["date"]
temp_df = pd.merge(
temp_df, qfq_factor_df, left_index=True, right_index=True, how="left"
)
temp_df.fillna(method="ffill", inplace=True)
temp_df = temp_df.astype(float)
temp_df["open"] = temp_df["open"] / temp_df["qfq_factor"]
temp_df["high"] = temp_df["high"] / temp_df["qfq_factor"]
temp_df["close"] = temp_df["close"] / temp_df["qfq_factor"]
temp_df["low"] = temp_df["low"] / temp_df["qfq_factor"]
return temp_df.iloc[:, :-1]
if adjust == "hfq-factor":
res = requests.get(zh_sina_a_stock_hfq_url.format(symbol))
hfq_factor_df = pd.DataFrame(
eval(res.text.split("=")[1].split("\n")[0])['data'])
hfq_factor_df.columns = ["date", "hfq_factor"]
hfq_factor_df.index = pd.to_datetime(hfq_factor_df.date)
del hfq_factor_df["date"]
return hfq_factor_df
if adjust == "qfq-factor":
res = requests.get(zh_sina_a_stock_qfq_url.format(symbol))
qfq_factor_df = pd.DataFrame(
eval(res.text.split("=")[1].split("\n")[0])['data'])
qfq_factor_df.columns = ["date", "qfq_factor"]
qfq_factor_df.index = pd.to_datetime(qfq_factor_df.date)
del qfq_factor_df["date"]
return qfq_factor_df
if __name__ == "__main__":
stock_zh_a_daily_hfq_df = stock_zh_a_daily(symbol="sh600582", adjust="qfq-factor")
print(stock_zh_a_daily_hfq_df)
stock_zh_a_daily_df = stock_zh_a_daily(symbol="sz000613", adjust="qfq")
print(stock_zh_a_daily_df)
stock_zh_a_spot_df = stock_zh_a_spot()
print(stock_zh_a_spot_df)
| akshare/stock/zh_stock_a_sina.py | 9,239 | 所有股票的总页数
http://vip.stock.finance.sina.com.cn/mkt/#hs_a
:return: 需要抓取的股票总页数
:rtype: int
新浪财经-A股-个股的历史行情数据, 大量抓取容易封IP
:param symbol: sh600000
:type symbol: str
:param adjust: 默认为空: 返回不复权的数据; qfq: 返回前复权后的数据; hfq: 返回后复权后的数据; hfq-factor: 返回后复权因子; hfq-factor: 返回前复权因子
:type adjust: str
:return: specific data
:rtype: pandas.DataFrame
从新浪财经-A股获取所有A股的实时行情数据, 重复运行本函数会被新浪暂时封 IP
http://vip.stock.finance.sina.com.cn/mkt/#qbgg_hk
:return: pandas.DataFrame
symbol code name trade pricechange changepercent buy 0 sh600000 600000 浦发银行 12.920 -0.030 -0.232 12.920
1 sh600004 600004 白云机场 18.110 -0.370 -2.002 18.110
2 sh600006 600006 东风汽车 4.410 -0.030 -0.676 4.410
3 sh600007 600007 中国国贸 17.240 -0.360 -2.045 17.240
4 sh600008 600008 首创股份 3.320 -0.030 -0.896 3.310
... ... ... ... ... ... ...
3755 sh600096 600096 云天化 5.270 -0.220 -4.007 5.270
3756 sh600097 600097 开创国际 10.180 -0.120 -1.165 10.180
3757 sh600098 600098 广州发展 6.550 -0.040 -0.607 6.540
3758 sh600099 600099 林海股份 6.540 -0.150 -2.242 6.540
3759 sh600100 600100 同方股份 8.200 -0.100 -1.205 8.200
sell settlement open high low volume amount 0 12.930 12.950 12.950 13.100 12.860 46023920 597016896
1 18.120 18.480 18.510 18.510 17.880 24175071 437419344
2 4.420 4.440 4.490 4.490 4.410 4304900 19130233
3 17.280 17.600 17.670 17.670 17.220 684801 11879731
4 3.320 3.350 3.360 3.360 3.300 8284294 27579688
... ... ... ... ... ... ...
3755 5.280 5.490 5.490 5.500 5.220 16964636 90595172
3756 10.190 10.300 10.220 10.340 10.090 1001676 10231669
3757 6.550 6.590 6.560 6.620 6.500 1996449 13098901
3758 6.580 6.690 6.650 6.680 6.530 1866180 12314997
3759 8.210 8.300 8.300 8.310 8.120 12087236 99281447
ticktime per pb mktcap nmc turnoverratio
0 15:00:00 6.984 0.790 3.792289e+07 3.631006e+07 0.16376
1 15:00:07 32.927 2.365 3.747539e+06 3.747539e+06 1.16826
2 15:00:02 15.926 1.207 8.820000e+05 8.820000e+05 0.21525
3 15:00:02 22.390 2.367 1.736555e+06 1.736555e+06 0.06798
4 15:00:07 22.912 1.730 1.887569e+06 1.600444e+06 0.17185
... ... ... ... ... ...
3755 15:00:00 56.728 1.566 7.523847e+05 6.963668e+05 1.28386
3756 15:00:00 17.552 1.434 2.452734e+05 2.303459e+05 0.44268
3757 15:00:00 25.476 1.059 1.785659e+06 1.785659e+06 0.07323
3758 15:00:00 540.496 3.023 1.433045e+05 1.433045e+05 0.85167
3759 15:00:07 -6.264 1.465 2.430397e+06 2.430397e+06 0.40782
Date: 2019/10/30 11:28
Desc: 新浪财经-A股-实时行情数据和历史行情数据(包含前复权和后复权因子)
-*- coding:utf-8 -*- /usr/bin/env python 执行js解密代码 | 3,134 | en | 0.235808 |
"""Support for HomematicIP Cloud lights."""
import logging
from typing import Any, Dict
from homematicip.aio.device import (
AsyncBrandDimmer,
AsyncBrandSwitchMeasuring,
AsyncBrandSwitchNotificationLight,
AsyncDimmer,
AsyncFullFlushDimmer,
AsyncPluggableDimmer,
)
from homematicip.base.enums import RGBColorState
from homematicip.base.functionalChannels import NotificationLightChannel
from homeassistant.components.light import (
ATTR_BRIGHTNESS,
ATTR_COLOR_NAME,
ATTR_HS_COLOR,
ATTR_TRANSITION,
SUPPORT_BRIGHTNESS,
SUPPORT_COLOR,
Light,
)
from homeassistant.config_entries import ConfigEntry
from homeassistant.helpers.typing import HomeAssistantType
from . import DOMAIN as HMIPC_DOMAIN, HMIPC_HAPID, HomematicipGenericDevice
from .hap import HomematicipHAP
_LOGGER = logging.getLogger(__name__)
ATTR_TODAY_ENERGY_KWH = "today_energy_kwh"
ATTR_CURRENT_POWER_W = "current_power_w"
async def async_setup_platform(
hass, config, async_add_entities, discovery_info=None
) -> None:
"""Old way of setting up HomematicIP Cloud lights."""
pass
async def async_setup_entry(
hass: HomeAssistantType, config_entry: ConfigEntry, async_add_entities
) -> None:
"""Set up the HomematicIP Cloud lights from a config entry."""
hap = hass.data[HMIPC_DOMAIN][config_entry.data[HMIPC_HAPID]]
entities = []
for device in hap.home.devices:
if isinstance(device, AsyncBrandSwitchMeasuring):
entities.append(HomematicipLightMeasuring(hap, device))
elif isinstance(device, AsyncBrandSwitchNotificationLight):
entities.append(HomematicipLight(hap, device))
entities.append(
HomematicipNotificationLight(hap, device, device.topLightChannelIndex)
)
entities.append(
HomematicipNotificationLight(
hap, device, device.bottomLightChannelIndex
)
)
elif isinstance(
device,
(AsyncDimmer, AsyncPluggableDimmer, AsyncBrandDimmer, AsyncFullFlushDimmer),
):
entities.append(HomematicipDimmer(hap, device))
if entities:
async_add_entities(entities)
class HomematicipLight(HomematicipGenericDevice, Light):
"""Representation of a HomematicIP Cloud light device."""
def __init__(self, hap: HomematicipHAP, device) -> None:
"""Initialize the light device."""
super().__init__(hap, device)
@property
def is_on(self) -> bool:
"""Return true if device is on."""
return self._device.on
async def async_turn_on(self, **kwargs) -> None:
"""Turn the device on."""
await self._device.turn_on()
async def async_turn_off(self, **kwargs) -> None:
"""Turn the device off."""
await self._device.turn_off()
class HomematicipLightMeasuring(HomematicipLight):
"""Representation of a HomematicIP Cloud measuring light device."""
@property
def device_state_attributes(self) -> Dict[str, Any]:
"""Return the state attributes of the generic device."""
state_attr = super().device_state_attributes
current_power_w = self._device.currentPowerConsumption
if current_power_w > 0.05:
state_attr[ATTR_CURRENT_POWER_W] = round(current_power_w, 2)
state_attr[ATTR_TODAY_ENERGY_KWH] = round(self._device.energyCounter, 2)
return state_attr
class HomematicipDimmer(HomematicipGenericDevice, Light):
"""Representation of HomematicIP Cloud dimmer light device."""
def __init__(self, hap: HomematicipHAP, device) -> None:
"""Initialize the dimmer light device."""
super().__init__(hap, device)
@property
def is_on(self) -> bool:
"""Return true if device is on."""
return self._device.dimLevel is not None and self._device.dimLevel > 0.0
@property
def brightness(self) -> int:
"""Return the brightness of this light between 0..255."""
return int((self._device.dimLevel or 0.0) * 255)
@property
def supported_features(self) -> int:
"""Flag supported features."""
return SUPPORT_BRIGHTNESS
async def async_turn_on(self, **kwargs) -> None:
"""Turn the light on."""
if ATTR_BRIGHTNESS in kwargs:
await self._device.set_dim_level(kwargs[ATTR_BRIGHTNESS] / 255.0)
else:
await self._device.set_dim_level(1)
async def async_turn_off(self, **kwargs) -> None:
"""Turn the light off."""
await self._device.set_dim_level(0)
class HomematicipNotificationLight(HomematicipGenericDevice, Light):
"""Representation of HomematicIP Cloud dimmer light device."""
def __init__(self, hap: HomematicipHAP, device, channel: int) -> None:
"""Initialize the dimmer light device."""
self.channel = channel
if self.channel == 2:
super().__init__(hap, device, "Top")
else:
super().__init__(hap, device, "Bottom")
self._color_switcher = {
RGBColorState.WHITE: [0.0, 0.0],
RGBColorState.RED: [0.0, 100.0],
RGBColorState.YELLOW: [60.0, 100.0],
RGBColorState.GREEN: [120.0, 100.0],
RGBColorState.TURQUOISE: [180.0, 100.0],
RGBColorState.BLUE: [240.0, 100.0],
RGBColorState.PURPLE: [300.0, 100.0],
}
@property
def _func_channel(self) -> NotificationLightChannel:
return self._device.functionalChannels[self.channel]
@property
def is_on(self) -> bool:
"""Return true if device is on."""
return (
self._func_channel.dimLevel is not None
and self._func_channel.dimLevel > 0.0
)
@property
def brightness(self) -> int:
"""Return the brightness of this light between 0..255."""
return int((self._func_channel.dimLevel or 0.0) * 255)
@property
def hs_color(self) -> tuple:
"""Return the hue and saturation color value [float, float]."""
simple_rgb_color = self._func_channel.simpleRGBColorState
return self._color_switcher.get(simple_rgb_color, [0.0, 0.0])
@property
def device_state_attributes(self) -> Dict[str, Any]:
"""Return the state attributes of the generic device."""
state_attr = super().device_state_attributes
if self.is_on:
state_attr[ATTR_COLOR_NAME] = self._func_channel.simpleRGBColorState
return state_attr
@property
def name(self) -> str:
"""Return the name of the generic device."""
return f"{super().name} Notification"
@property
def supported_features(self) -> int:
"""Flag supported features."""
return SUPPORT_BRIGHTNESS | SUPPORT_COLOR
@property
def unique_id(self) -> str:
"""Return a unique ID."""
return f"{self.__class__.__name__}_{self.post}_{self._device.id}"
async def async_turn_on(self, **kwargs) -> None:
"""Turn the light on."""
# Use hs_color from kwargs,
# if not applicable use current hs_color.
hs_color = kwargs.get(ATTR_HS_COLOR, self.hs_color)
simple_rgb_color = _convert_color(hs_color)
# Use brightness from kwargs,
# if not applicable use current brightness.
brightness = kwargs.get(ATTR_BRIGHTNESS, self.brightness)
# If no kwargs, use default value.
if not kwargs:
brightness = 255
# Minimum brightness is 10, otherwise the led is disabled
brightness = max(10, brightness)
dim_level = brightness / 255.0
transition = kwargs.get(ATTR_TRANSITION, 0.5)
await self._device.set_rgb_dim_level_with_time(
channelIndex=self.channel,
rgb=simple_rgb_color,
dimLevel=dim_level,
onTime=0,
rampTime=transition,
)
async def async_turn_off(self, **kwargs) -> None:
"""Turn the light off."""
simple_rgb_color = self._func_channel.simpleRGBColorState
transition = kwargs.get(ATTR_TRANSITION, 0.5)
await self._device.set_rgb_dim_level_with_time(
channelIndex=self.channel,
rgb=simple_rgb_color,
dimLevel=0.0,
onTime=0,
rampTime=transition,
)
def _convert_color(color: tuple) -> RGBColorState:
"""
Convert the given color to the reduced RGBColorState color.
RGBColorStat contains only 8 colors including white and black,
so a conversion is required.
"""
if color is None:
return RGBColorState.WHITE
hue = int(color[0])
saturation = int(color[1])
if saturation < 5:
return RGBColorState.WHITE
if 30 < hue <= 90:
return RGBColorState.YELLOW
if 90 < hue <= 160:
return RGBColorState.GREEN
if 150 < hue <= 210:
return RGBColorState.TURQUOISE
if 210 < hue <= 270:
return RGBColorState.BLUE
if 270 < hue <= 330:
return RGBColorState.PURPLE
return RGBColorState.RED
| homeassistant/components/homematicip_cloud/light.py | 9,102 | Representation of HomematicIP Cloud dimmer light device.
Representation of a HomematicIP Cloud light device.
Representation of a HomematicIP Cloud measuring light device.
Representation of HomematicIP Cloud dimmer light device.
Initialize the light device.
Initialize the dimmer light device.
Initialize the dimmer light device.
Convert the given color to the reduced RGBColorState color.
RGBColorStat contains only 8 colors including white and black,
so a conversion is required.
Return the brightness of this light between 0..255.
Return the brightness of this light between 0..255.
Return the state attributes of the generic device.
Return the state attributes of the generic device.
Return the hue and saturation color value [float, float].
Return true if device is on.
Return true if device is on.
Return true if device is on.
Return the name of the generic device.
Flag supported features.
Flag supported features.
Return a unique ID.
Support for HomematicIP Cloud lights.
Use hs_color from kwargs, if not applicable use current hs_color. Use brightness from kwargs, if not applicable use current brightness. If no kwargs, use default value. Minimum brightness is 10, otherwise the led is disabled | 1,206 | en | 0.75248 |
# region [Imports]
# * Standard Library Imports ---------------------------------------------------------------------------->
import os
import logging
import sqlite3 as sqlite
from pprint import pformat
# * Gid Imports ----------------------------------------------------------------------------------------->
import gidlogger as glog
# endregion[Imports]
__updated__ = '2020-11-26 17:04:37'
# region [AppUserData]
# endregion [AppUserData]
# region [Logging]
log = logging.getLogger('gidsql')
glog.import_notification(log, __name__)
# endregion[Logging]
# region [Constants]
# endregion[Constants]
class GidSqliteActionBase:
def __init__(self, in_db_loc, in_pragmas=None):
self.db_loc = in_db_loc
self.pragmas = in_pragmas
glog.class_init_notification(log, self)
@property
def exists(self):
"""
checks if the db exist and logs it
Returns
-------
bool
bool if the file exist or not
"""
if os.path.isfile(self.db_loc):
log.info("database at %s, does EXIST", self.db_loc)
return True
else:
log.info("databse at %s does NOT EXIST", self.db_loc)
return False
@staticmethod
def _handle_error(error, sql_phrase, variables):
log.critical("%s - with SQL --> %s and args[%s]", str(error), sql_phrase, pformat(variables))
if 'syntax error' in str(error):
raise SyntaxError(error)
raise sqlite.Error(error)
def _execute_pragmas(self, in_cursor):
if self.pragmas is not None and self.pragmas != '':
in_cursor.executescript(self.pragmas)
log.debug("Executed pragmas '%s' successfully", self.pragmas)
def __repr__(self):
return f"{self.__class__.__name__} ('{self.db_loc}')"
def __str__(self):
return self.__class__.__name__
class AioGidSqliteActionBase:
def __init__(self, in_db_loc, in_pragmas=None):
self.db_loc = in_db_loc
self.pragmas = in_pragmas
glog.class_init_notification(log, self)
@property
def exists(self):
"""
checks if the db exist and logs it
Returns
-------
bool
bool if the file exist or not
"""
if os.path.isfile(self.db_loc):
log.info("database at %s, does EXIST", self.db_loc)
return True
else:
log.info("databse at %s does NOT EXIST", self.db_loc)
return False
@staticmethod
async def _handle_error(error, sql_phrase, variables):
log.critical("%s - with SQL --> %s and args[%s]", str(error), sql_phrase, pformat(variables))
if 'syntax error' in str(error):
raise SyntaxError(error)
raise sqlite.Error(error)
async def _execute_pragmas(self, in_connection):
if self.pragmas not in [None, '', []]:
await in_connection.executescript(self.pragmas)
log.debug("Executed pragmas '%s' successfully", self.pragmas)
def __repr__(self):
return f"{self.__class__.__name__} ('{self.db_loc}')"
def __str__(self):
return self.__class__.__name__
# region[Main_Exec]
if __name__ == '__main__':
pass
# endregion[Main_Exec]
| antipetros_discordbot/utility/gidsql/db_action_base.py | 3,328 | checks if the db exist and logs it
Returns
-------
bool
bool if the file exist or not
checks if the db exist and logs it
Returns
-------
bool
bool if the file exist or not
region [Imports] * Standard Library Imports ----------------------------------------------------------------------------> * Gid Imports -----------------------------------------------------------------------------------------> endregion[Imports] region [AppUserData] endregion [AppUserData] region [Logging] endregion[Logging] region [Constants] endregion[Constants] region[Main_Exec] endregion[Main_Exec] | 589 | en | 0.249401 |
# Copyright (c) 2020, Fabio Muratore, Honda Research Institute Europe GmbH, and
# Technical University of Darmstadt.
# 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.
# 3. Neither the name of Fabio Muratore, Honda Research Institute Europe GmbH,
# or Technical University of Darmstadt, 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 FABIO MURATORE, HONDA RESEARCH INSTITUTE EUROPE GMBH,
# OR TECHNICAL UNIVERSITY OF DARMSTADT BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
# PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
# OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER
# IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
import functools
import numpy as np
import operator
import random
import scipy.signal as signal
import torch as to
from collections.abc import Iterable
from copy import deepcopy
from math import ceil
from typing import Sequence, Type, Optional, Union, Callable, Tuple
import pyrado
from pyrado.sampling.data_format import stack_to_format, to_format, cat_to_format, new_tuple
from pyrado.sampling.utils import gen_shuffled_batch_idcs, gen_ordered_batch_idcs
def _index_to_int(idx, n):
# Index conversion
idx = operator.index(idx)
# Check negative index
if idx < 0:
idx += n
# Check bounds
if idx < 0 or idx >= n:
raise IndexError
return idx
class DictIndexProxy:
""" Views a slice through a dict of lists or tensors. """
__slots__ = ("__dict__", "_obj", "_index", "_prefix")
def __init__(self, obj: dict, index: int, path: Optional[str] = None):
super().__init__()
self._obj = obj
self._index = index
if path:
self._prefix = path + "."
else:
self._prefix = ""
def _process_key(self, key: str, index: int, error_type: Type[Exception]):
return key, index
def _get_keyed_value(self, key, error_type: Type[Exception] = RuntimeError):
# Obtain keyed value from obj dict
value = self._obj.get(key, None)
if value is None:
# Try pluralized keys
value = self._obj.get(key + "s", None)
if value is None:
raise error_type(f"No entry named {self._prefix}{key}")
return value
def _index_value(self, key, value, index, error_type: Type[Exception] = RuntimeError):
# Obtain indexed element from value
if isinstance(value, dict):
# Return subdict proxy
return DictIndexProxy(value, index, self._prefix + key)
elif isinstance(value, tuple):
# Return tuple of slices
# Since we can't proxy a tuple, we slice eagerly
# Use type(value) to support named tuples. (the keys is still index though)
return new_tuple(
type(value), (self._index_value(f"{key}[{i}]", v, index, error_type) for i, v in enumerate(value))
)
elif isinstance(value, (to.Tensor, np.ndarray)):
# Return slice of ndarray / tensor
return value[index, ...]
elif isinstance(value, list):
# Return list item
return value[index]
else:
# Unsupported type
raise error_type(f"Entry {self._prefix}{key} has un-gettable type {type(value)}")
def _get_indexed_value(self, key, error_type: Type[Exception] = RuntimeError):
real_key, index = self._process_key(key, self._index, error_type)
# Obtain keyed value list from obj dict
value = self._get_keyed_value(real_key, error_type=error_type)
return self._index_value(key, value, index, error_type)
def _set_indexed_value(self, key, new_value, error_type: Type[Exception] = RuntimeError):
real_key, index = self._process_key(key, self._index, error_type)
# Obtain keyed value list from obj dict
value = self._get_keyed_value(real_key, error_type=error_type)
# Set value to data
if isinstance(value, (to.Tensor, np.ndarray)):
# Set slice of ndarray/tensor
value[index, ...] = new_value
elif isinstance(value, list):
# Set list item
value[index] = new_value
else:
# Don't support setting dict proxies
raise error_type(f"Entry {key} has un-settable type {type(value)}")
def __getattr__(self, key):
if key.startswith("_"):
raise AttributeError
result = self._get_indexed_value(key, error_type=AttributeError)
self.__dict__[key] = result
return result
def __setattr__(self, key, value):
if not key.startswith("_"):
try:
self._set_indexed_value(key, value, error_type=AttributeError)
except AttributeError:
pass
else:
self.__dict__[key] = value
return
object.__setattr__(self, key, value)
def __dir__(self):
# List dict items not starting with _
return [k for k in self._obj if not k.startswith("_")]
# Define getitem and setitem too, helps when return attr is a keyword
def __getitem__(self, key):
result = self._get_indexed_value(key, error_type=KeyError)
self.__dict__[key] = result
return result
def __setitem__(self, key, value):
self._set_indexed_value(key, value, error_type=KeyError)
self.__dict__[key] = value
# Serialize only dict and index
def __getstate__(self):
return {"obj", self._obj, "index", self._index}
def __setstate__(self, state):
self._obj = state["obj"]
self._index = state["index"]
class Step(DictIndexProxy):
"""
A single step in a rollout.
This object is a proxy, referring a specific index in the rollout. When querying an attribute from the step,
it will try to return the corresponding slice from the rollout. Additionally, one can prefix attributes with `next_`
to access the value for the next step, i.e. `next_observations` the observation made at the start of the next step.
"""
__slots__ = "_rollout"
def __init__(self, rollout, index):
"""
Constructor
:param rollout: `StepSequence` object to which this step belongs
:param index: index of this step in the rollout
"""
# Call DictIndexProxy's constructor
super(Step, self).__init__(rollout.__dict__, index)
self._rollout = rollout
def _process_key(self, key: str, index: int, error_type: Type[Exception]):
if key.startswith("next_"):
if not self._rollout.continuous:
raise error_type("Access to next element is not supported for non-continuous rollouts!")
key = key[5:]
index += 1
if key not in self._rollout.data_names and key + "s" not in self._rollout.data_names and key != "done":
raise error_type(f"No such rollout data field: {key}")
return key, index
# Serialize rollout and index
def __getstate__(self):
return {"rollout", self._rollout, "index", self._index}
def __setstate__(self, state):
self._rollout = state["rollout"]
self._obj = self._rollout.__dict__
self._index = state["index"]
class StepSequence(Sequence[Step]):
"""
A sequence of steps.
During the rollout, the values of different variables are recorded. This class provides efficient storage and
access for these values. The constructor accepts a list of step entries for each variable. For every step,
the list should contain a Tensor/ndarray of values for that step. The shape of these tensors must be the same for
all step entries. The passed tensors are then stacked, so that the first dimension is the step count.
Some values, like the observations, can have one more element then there are steps to encode the state after the
last step. Additionally, the step entries may be dicts to support keyed storage. A list of dicts is converted to
a dict of lists, each of which will be regularly stacked. Apart from the variable-based view, the rollout can also
be seen as a sequence of steps. Each Step object is a proxy, it's attributes refer to the respective slice of the
corresponding variable. The only required result variable are `rewards`, observations`, and `actions`.
All other variables are optional. Common optional ones are `states` and `rollout_info`.
.. note::
Storing PyTorch tensors with gradient tracing is NOT supported. The rationale behind this is eager error
avoidance. The only reason you would add them is to profit from the optimized slicing, but using that with
gradient tracking risks lingering incomplete graphs.
"""
rewards: Union[np.ndarray, to.Tensor]
observations: Union[np.ndarray, to.Tensor]
actions: Union[np.ndarray, to.Tensor]
# Set of required rollout fields in addition to rewards, observations, actions. Putting this into a class field
# instead of using the constructor arguments reduces duplicate code and allows to override it during unit tests.
required_fields = {}
def __init__(
self,
*,
complete: Optional[bool] = True,
rollout_info=None,
data_format: Optional[str] = None,
done: Optional[np.ndarray] = None,
continuous: Optional[bool] = True,
rollout_bounds=None,
rewards: Sequence,
observations: Sequence,
actions: Sequence,
**data,
):
# print (data)
"""
Constructor
:param complete: `False` if the rollout is incomplete, i.e. as part of a mini-batch
:param rollout_info: data staying constant through the whole episode
:param data_format: 'torch' to use Tensors, 'numpy' to use ndarrays.
Will use Tensors if any data argument does, else ndarrays
:param done: boolean ndarray, specifying for each step whether it led to termination.
The last step of continuous rollouts, i.e. not mini-batches, is done if `complete` is `True`.
:param continuous: true if the steps form one continuous sequence.
:param rewards: sequence of reward values, determines sequence length
:param observations: sequence of observation values, the length must be `len(rewards) + 1`
:param actions: sequence of action values, the length must be `len(rewards)`
:param data: additional data lists, their length must be `len(rewards)` or `len(rewards) + 1`
"""
# Obtain rollout length from reward list
self.length = len(rewards)
if self.length == 0:
raise pyrado.ShapeErr(msg="StepSequence cannot be empty!")
# Set singular attributes
self.rollout_info = rollout_info
self.continuous = continuous
# Infer if this instance is using numpy arrays or PyTorch tensors
if data_format is None:
# We ignore rewards here since it's probably scalar
for value in data.values():
if isinstance(value, to.Tensor) or (isinstance(value, list) and isinstance(value[0], to.Tensor)):
data_format = "torch"
break
else:
# Use numpy by default
data_format = "numpy"
self._data_format = data_format
# Check for missing extra fields
missing_fields = StepSequence.required_fields - data.keys()
if missing_fields:
raise ValueError(f"Missing required data fields: {missing_fields}")
# Set mandatory data fields
self._data_names = []
self.add_data("rewards", rewards)
self.add_data("observations", observations)
self.add_data("actions", actions)
# Set other data fields and verify their length
for name, value in data.items():
self.add_data(name, value)
# Set done list if any. The done list is always a numpy array since torch doesn't support boolean tensors.
if done is None:
done = np.zeros(self.length, dtype=np.bool)
if complete and continuous:
done[-1] = True
else:
done = np.asarray(done, dtype=np.bool)
assert done.shape[0] == self.length
self.done = done
# Compute rollout bounds from done list (yes this is not exactly safe...)
# The bounds list has one extra entry 0, this simplifies queries greatly.
# bounds[i] = start of rollout i; bounds[i+1]=end of rollout i
if continuous:
if rollout_bounds is None:
rollout_bounds = [0]
rollout_bounds.extend(np.flatnonzero(done) + 1)
if not done[-1]:
rollout_bounds.append(self.length)
else:
# Validate externally passed bounds.
for i in range(len(rollout_bounds) - 1):
assert rollout_bounds[i] < rollout_bounds[i + 1]
assert rollout_bounds[0] == 0
assert rollout_bounds[-1] == self.length
self._rollout_bounds = np.array(rollout_bounds)
else:
self._rollout_bounds = None
@property
def data_format(self) -> str:
""" Get the name of data format ('torch' or 'numpy'). """
return self._data_format
@property
def data_names(self) -> Sequence[str]:
""" Get the list of data attribute names. """
return self._data_names
@property
def rollout_bounds(self) -> np.ndarray:
return self._rollout_bounds
@property
def rollout_count(self):
""" Count the number of sub-rollouts inside this step sequence. """
if not self.continuous:
raise pyrado.ValueErr(msg="Sub-rollouts are only supported on continuous data.")
return len(self._rollout_bounds) - 1
@property
def rollout_lengths(self):
""" Lengths of sub-rollouts. """
if not self.continuous:
raise pyrado.ValueErr(msg="Sub-rollouts are only supported on continuous data.")
bounds = self._rollout_bounds
return bounds[1:] - bounds[:-1]
def __len__(self):
""" Get the step sequence's length. """
return self.length
def __getitem__(self, index):
if isinstance(index, slice) or isinstance(index, Iterable):
# Return a StepSequence object with the subset. Build sliced data dict.
sliced_data = {name: self._slice_entry(self.__dict__[name], index) for name in self._data_names}
sliced_data = {k: v for k, v in sliced_data.items() if v is not None}
# Check if the slice is continuous
continuous = isinstance(index, slice) and (index.step is None or index.step == 1)
rollout_bounds = None
if continuous:
# Slice rollout bounds too.
start, end, _ = index.indices(self.length)
rollout_bounds = [0]
for b in self._rollout_bounds:
if start < b < end:
rollout_bounds.append(b - start)
rollout_bounds.append(end - start)
return StepSequence(
rollout_info=self.rollout_info,
data_format=self._data_format,
done=self.done[index],
continuous=continuous,
rollout_bounds=rollout_bounds,
**sliced_data,
)
# Should be a singular element index. Return step proxy.
return Step(self, _index_to_int(index, self.length))
def __map_tensors(self, mapper, elem):
if isinstance(elem, dict):
# Modify dict in-place
for k in elem.keys():
elem[k] = self.__map_tensors(mapper, elem[k])
return elem
if isinstance(elem, tuple):
# Can't modify in place since it's a tuple
return new_tuple(type(elem), (self.__map_tensors(mapper, part) for part in elem))
# Tensor element
return mapper(elem)
def _validate_data_size(self, name, value):
# In torch case: check that we don't mess with gradients
if isinstance(value, to.Tensor):
assert not value.requires_grad, (
"Do not add gradient-sensitive tensors to SampleCollections. "
"This is a fast road to weird retain_graph errors!"
)
# Check type of data
if isinstance(value, dict):
# Validate dict entries
for k, v in value.items():
self._validate_data_size(f"{name}.{k}", v)
return
if isinstance(value, tuple):
# Validate dict entries
for i, v in enumerate(value):
self._validate_data_size(f"{name}[{i}]", v)
return
if isinstance(value, (np.ndarray, to.Tensor)):
# A single array. The first dimension must match
vlen = value.shape[0]
else:
# Should be a sequence
assert isinstance(value, Sequence)
vlen = len(value)
if self.continuous:
if not (vlen == self.length or vlen == self.length + 1):
raise pyrado.ShapeErr(
msg=f"The data list {name} must have {self.length} or {self.length}+1 elements,"
f"but has {vlen} elements."
)
else:
# Disallow +1 tensors
if not vlen == self.length:
raise pyrado.ShapeErr(
msg=f"The data list {name} must have {self.length} elements," f"but has {vlen} elements."
)
def _slice_entry(self, entry, index: slice):
if isinstance(entry, dict):
return {k: self._slice_entry(v, index) for k, v in entry.items()}
if isinstance(entry, tuple):
return new_tuple(type(entry), (self._slice_entry(e, index) for e in entry))
elif isinstance(entry, (to.Tensor, np.ndarray)):
return entry[index, ...]
elif isinstance(entry, list):
return entry[index]
else:
return None # unsupported
def _truncate_after_last(self, entry):
if isinstance(entry, dict):
return {k: self._truncate_after_last(v) for k, v in entry.items()}
if isinstance(entry, tuple):
return new_tuple(type(entry), (self._truncate_after_last(v) for v in entry))
elif isinstance(entry, (to.Tensor, np.ndarray)):
if entry.shape[0] == self.length + 1:
return entry[:-1, ...]
elif isinstance(entry, list):
if len(entry) == self.length + 1:
return entry[:-1]
# No truncation
return entry
def add_data(self, name: str, value=None, item_shape: tuple = None, with_after_last: Optional[bool] = False):
"""
Add a new data field to the step sequence.
:param name: string for the name
:param value: the data
:param item_shape: shape to store the data in
:param with_after_last: `True` if there is one more element than the length (e.g. last observation)
"""
if name in self._data_names:
raise pyrado.KeyErr(msg=f"Trying to add a duplicate data field for {name}!")
if value is None:
# Compute desired step length
ro_length = self.length
if with_after_last:
ro_length += 1
# Create zero-filled
if self._data_format == "torch":
value = to.zeros(to.Size([ro_length]) + to.Size(item_shape))
else:
value = np.array((ro_length,) + item_shape)
else:
# Check the data
self._validate_data_size(name, value)
if not isinstance(value, (np.ndarray, to.Tensor)):
# Stack into one array/tensor
value = stack_to_format(value, self._data_format)
else:
# Ensure right array format
value = to_format(value, self._data_format)
# Store in dict
self._data_names.append(name)
self.__dict__[name] = value
def get_data_values(self, name: str, truncate_last: Optional[bool] = False):
"""
Return the data tensor stored under the given name.
:param name: data name
:param truncate_last: True to truncate the length+1 entry if present
"""
assert name in self._data_names
entry = self.__dict__[name]
# Truncate if needed
if truncate_last:
# Check length
entry = self._truncate_after_last(entry)
return entry
def numpy(self, data_type=None):
"""
Convert data to numpy ndarrays.
:param data_type: type to return data in. When None is passed, the data type is left unchanged.
"""
self.convert("numpy", data_type)
def torch(self, data_type=None):
"""
Convert data to PyTorch Tensors.
:param data_type: type to return data in. When None is passed, the data type is left unchanged.
"""
self.convert("torch", data_type)
def convert(self, data_format: str, data_type=None):
"""
Convert data to specified format.
:param data_format: torch to use Tensors, numpy to use ndarrays
:param data_type: optional torch/numpy dtype for data. When `None` is passed, the data type is left unchanged.
"""
if data_format not in {"torch", "numpy"}:
raise pyrado.ValueErr(given=data_format, eq_constraint="'torch' or 'numpy'")
if self._data_format == data_format:
return
self._data_format = data_format
for dn in self._data_names:
self.__dict__[dn] = self.__map_tensors(lambda t: to_format(t, data_format, data_type), self.__dict__[dn])
def get_rollout(self, index):
"""
Get an indexed sub-rollout.
:param index: generic index of sub-rollout, negative values, slices and iterables are allowed
:return: selected subset.
"""
if not self.continuous:
raise pyrado.ValueErr(msg="Sub-rollouts are only supported on continuous data.")
if isinstance(index, slice):
# Analyze slice
start, end, step = index.indices(self.rollout_count)
if step == 1:
# A simple, continuous slice
bounds = self._rollout_bounds
start_step = bounds[start]
end_step = bounds[end]
return self[start_step:end_step]
# Convert nonstandard slice to range
index = range(start, end, step)
if isinstance(index, Iterable):
# Nontrivial non-continuous slice, need to slice each element and concat them.
return StepSequence.concat([self.get_rollout(i) for i in index], self.data_format)
# Decode index
index = _index_to_int(index, self.rollout_count)
bounds = self._rollout_bounds
start_step = bounds[index]
end_step = bounds[index + 1]
return self[start_step:end_step]
def iterate_rollouts(self):
""" Iterate over all sub-rollouts of a concatenated rollout. """
if not self.continuous:
raise pyrado.ValueErr(msg="Sub-rollouts are only supported on continuous data.")
bounds = self._rollout_bounds
count = len(bounds) - 1
if count == 1:
# Optimize for single rollout
yield self
else:
for i in range(count):
start_step = bounds[i]
end_step = bounds[i + 1]
yield self[start_step:end_step]
def sample_w_next(self, batch_size: int) -> tuple:
"""
Sample a random batch of steps from a together with the associated next steps.
Similar to `split_shuffled_batches` with `complete_rollouts=False`
:param batch_size: number of steps to sample
:return: randomly sampled batch of steps
"""
if not self.length >= 2:
raise pyrado.ValueErr(given=self.length, ge_constraint="2")
shuffled_idcs = random.sample(range(self.length - 2), batch_size) # - 2 to always have a next step
shuffled_next_idcs = [i + 1 for i in shuffled_idcs]
steps = deepcopy(self[shuffled_idcs])
next_steps = deepcopy(self[shuffled_next_idcs])
return steps, next_steps
def split_ordered_batches(self, batch_size: int = None, num_batches: int = None):
"""
Batch generation. Split the step collection into ordered mini-batches of size batch_size.
:param batch_size: number of steps per batch, i.e. variable number of batches
:param num_batches: number of batches to split the rollout in, i.e. variable batch size
.. note::
Left out the option to return complete rollouts like for `split_shuffled_batches`.
"""
if batch_size is None and num_batches is None or batch_size is not None and num_batches is not None:
raise pyrado.ValueErr(msg="Either batch_size or num_batches must not be None, but not both or none!")
elif batch_size is not None and batch_size < 1:
raise pyrado.ValueErr(given=batch_size, ge_constraint="1 (int)")
elif num_batches is not None and num_batches < 1:
raise pyrado.ValueErr(given=num_batches, ge_constraint="1 (int)")
# Switch the splitting mode
if num_batches is not None:
batch_size = ceil(self.length / num_batches)
if batch_size >= self.length:
# Yield all at once if there are less steps than the batch size
yield self
else:
# Split by steps
for b in gen_ordered_batch_idcs(batch_size, self.length, sorted=True):
yield self[b]
def split_shuffled_batches(self, batch_size: int, complete_rollouts: Optional[bool] = False):
"""
Batch generation. Split the step collection into random mini-batches of size batch_size.
:param batch_size: number of steps per batch
:param complete_rollouts: if `complete_rollouts = True`, the batches will not contain partial rollouts.
However, the size of the returned batches cannot be strictly maintained in this case.
.. note::
This method is also supposed to be called for recurrent networks, which have a different `evaluate()`
method that recognized where the rollouts end within a batch.
"""
if batch_size >= self.length:
# Yield all at once if there are less steps than the batch size
yield self
elif complete_rollouts and self.continuous:
# Our goal here is to randomly shuffle the rollouts, while returning batches of batch_size steps.
# The solution here is to take rollouts in a random order and yield a batch each time it exceeds batch_size.
rollout_lengths = self.rollout_lengths
shuffled_idcs = random.sample(range(len(rollout_lengths)), len(rollout_lengths))
# Now, walk through the rollouts in a random order and split once batch size is full.
batch = []
cur_batch_size = 0
for idx in shuffled_idcs:
batch.append(idx)
cur_batch_size += rollout_lengths[idx]
if cur_batch_size >= batch_size:
# Got a full batch
yield self.get_rollout(batch)
batch.clear()
cur_batch_size = 0
# Yield eventual final one
if batch:
yield self.get_rollout(batch)
else:
# Split by steps
for b in gen_shuffled_batch_idcs(batch_size, self.length):
yield self[b]
def undiscounted_return(self) -> float:
"""
Compute the undiscounted return.
:return: sum of rewards
"""
if not len(self._rollout_bounds) == 2:
raise pyrado.ShapeErr(msg="The StepSequence must be a single continuous rollout.")
return self.rewards.sum()
def discounted_return(self, gamma: float) -> (to.Tensor, np.ndarray):
"""
Compute the discounted return.
:param gamma: temporal discount factor
:return: exponentially weighted sum of rewards
"""
if not len(self._rollout_bounds) == 2:
raise pyrado.ShapeErr(msg="The StepSequence must be a single continuous rollout.")
if not 0 <= gamma <= 1:
raise pyrado.ValueErr(given=gamma, ge_constraint="0", le_constraint="1")
if self.data_format == "torch":
return to.dot(self.rewards, (gamma ** to.arange(self.length)))
else:
return np.dot(self.rewards, (gamma ** np.arange(self.length)))
@classmethod
def concat(
cls, parts: Sequence["StepSequence"], data_format: Optional[str] = None, truncate_last: Optional[bool] = True
):
"""
Concatenate multiple step sequences into one, truncating the last observation.
:param parts: batch of sequences to concatenate
:param data_format: torch to use Tensors, numpy to use ndarrays, `None` to choose automatically
:param truncate_last: remove the last step from each part, highly recommended to be `True`
:return: concatenated sequence of `Steps`
"""
# Obtain data attribute names
data_names = parts[0].data_names
# Deduce data format if is None
if data_format is None:
data_format = parts[0].data_format
# Concat data fields
data = {
name: cat_to_format([ro.get_data_values(name, truncate_last) for ro in parts], data_format)
for name in data_names
}
# Treat done separately since it should stay a ndarray
done = np.concatenate([ro.done for ro in parts])
# Check if parts are continuous
continuous = all(ro.continuous for ro in parts)
rollout_bounds = None
if continuous:
# Concatenate rollout separator indices for continuous rollouts
rollout_bounds = [0]
acc_len = 0
for ro in parts:
rollout_bounds.extend(ro.rollout_bounds[1:] + acc_len)
acc_len += ro.rollout_bounds[-1]
return StepSequence(
data_format=data_format, done=done, continuous=continuous, rollout_bounds=rollout_bounds, **data
)
@classmethod
def process_data(
cls,
rollout: "StepSequence",
fcn: Callable,
fcn_arg_name: str,
fcn_arg_types: Union[type, Tuple[type]] = np.ndarray,
include_fields: Sequence[str] = None,
exclude_fields: Sequence[str] = None,
**process_fcn_kwargs,
):
"""
Process all data fields of a rollouts using an arbitrary function. Optionally, some fields can be excluded.
:param rollout: `StepSequence` holding the data
:param fcn: function (of one remaining input) to used manipulate the data fields, e.g. `scipy.filtfilt()`
:param fcn_arg_name: sting of the remaining input of `process_fcn()`, e.g. `x` for `scipy.filtfilt()`
:param fcn_arg_types: type or tuple thereof which are expected as input to `fcn()`
:param include_fields: list of field names to include for processing, pass `None` to not include everything.
If specified, only fields from this selection will be considered
:param exclude_fields: list of field names to exclude from processing, pass `None` to not exclude anything
:param process_fcn_kwargs: keyword arguments forwarded to `process_fcn()`
:return: new `StepSequence` instance with processed data
"""
@functools.wraps(fcn)
def recursive_wrapper(inp, **kwargs):
""" Wrap the processing function to call it recursivelyy for nested data structures. """
# Add to actual data input to the keyword arguments to make calling the function easier
kwargs.update({fcn_arg_name: inp})
if isinstance(inp, fcn_arg_types):
# Process the data
inp = fcn(**kwargs)
elif isinstance(inp, dict):
# Recursive call
for key, value in inp.items():
if isinstance(value, fcn_arg_types):
inp[key] = recursive_wrapper(value, **kwargs)
else:
inp[key] = value
elif isinstance(inp, list):
# Recursive call
for idx, item in enumerate(inp):
if isinstance(item, fcn_arg_types):
inp[idx] = recursive_wrapper(item, **kwargs)
else:
inp[idx] = item
return inp
# Go through all desired data fields and apply the processing function
data_dict = dict()
include_fields = include_fields or rollout.data_names
exclude_fields = exclude_fields or []
for name in rollout.data_names:
# Extract data field
data = rollout.get_data_values(name)
# Process current data field if included and not explicitly excluded
if name in include_fields and name not in exclude_fields:
data = recursive_wrapper(data, **process_fcn_kwargs)
# Collect the new/old data
data_dict[name] = data
# Create new object
return StepSequence(**data_dict, rollout_info=rollout.rollout_info, continuous=rollout.continuous)
def discounted_reverse_cumsum(data, gamma: float):
"""
Use a linear filter to compute the reverse discounted cumulative sum.
.. note::
`scipy.signal.lfilter` assumes an initialization with 0 by default.
:param data: input data with samples along the 0 axis (e.g. time series)
:param gamma: discount factor
:return: cumulative sums for every step
"""
return signal.lfilter([1], [1, -gamma], data[::-1], axis=0)[::-1]
def discounted_value(rollout: StepSequence, gamma: float):
"""
Compute the discounted state values for one rollout.
:param rollout: input data
:param gamma: temporal discount factor
:return: state values for every time step in the rollout
"""
rewards = [step.reward for step in rollout]
return discounted_reverse_cumsum(rewards, gamma)
def discounted_values(rollouts: Sequence[StepSequence], gamma: float, data_format: Optional[str] = "torch"):
"""
Compute the discounted state values for multiple rollouts.
:param rollouts: input data
:param gamma: temporal discount factor
:param data_format: data format of the given
:return: state values for every time step in the rollouts (concatenated sequence across rollouts)
"""
if data_format == "torch":
# The ndarray.copy() is necessary due to (currently) unsupported negative strides
return to.cat([to.from_numpy(discounted_value(ro, gamma).copy()).to(to.get_default_dtype()) for ro in rollouts])
elif data_format == "numpy":
raise np.array([discounted_value(ro, gamma) for ro in rollouts])
else:
raise pyrado.ValueErr(given=data_format, eq_constraint="'torch' or 'numpy'")
def gae_returns(rollout: StepSequence, gamma: float = 0.99, lamb: float = 0.95):
"""
Compute returns using generalized advantage estimation.
.. seealso::
[1] J. Schulmann, P. Moritz, S. Levine, M. Jordan, P. Abbeel, 'High-Dimensional Continuous Control Using
Generalized Advantage Estimation', ICLR 2016
:param rollout: sequence of steps
:param gamma: temporal discount factor
:param lamb: discount factor
:return: estimated advantage
"""
def _next_value(step: Step) -> float:
""" Helper to return `next_value = 0` for last step """
if step.done:
return 0.0
return step.next_value
deltas = [step.reward + gamma * _next_value(step) - step.value for step in rollout]
cumsum = discounted_reverse_cumsum(deltas, gamma * lamb)
return cumsum
| mushroom_rl/core/parallelization_tools/step_sequence.py | 37,606 | Views a slice through a dict of lists or tensors.
A single step in a rollout.
This object is a proxy, referring a specific index in the rollout. When querying an attribute from the step,
it will try to return the corresponding slice from the rollout. Additionally, one can prefix attributes with `next_`
to access the value for the next step, i.e. `next_observations` the observation made at the start of the next step.
A sequence of steps.
During the rollout, the values of different variables are recorded. This class provides efficient storage and
access for these values. The constructor accepts a list of step entries for each variable. For every step,
the list should contain a Tensor/ndarray of values for that step. The shape of these tensors must be the same for
all step entries. The passed tensors are then stacked, so that the first dimension is the step count.
Some values, like the observations, can have one more element then there are steps to encode the state after the
last step. Additionally, the step entries may be dicts to support keyed storage. A list of dicts is converted to
a dict of lists, each of which will be regularly stacked. Apart from the variable-based view, the rollout can also
be seen as a sequence of steps. Each Step object is a proxy, it's attributes refer to the respective slice of the
corresponding variable. The only required result variable are `rewards`, observations`, and `actions`.
All other variables are optional. Common optional ones are `states` and `rollout_info`.
.. note::
Storing PyTorch tensors with gradient tracing is NOT supported. The rationale behind this is eager error
avoidance. The only reason you would add them is to profit from the optimized slicing, but using that with
gradient tracking risks lingering incomplete graphs.
Constructor
:param rollout: `StepSequence` object to which this step belongs
:param index: index of this step in the rollout
Constructor
:param complete: `False` if the rollout is incomplete, i.e. as part of a mini-batch
:param rollout_info: data staying constant through the whole episode
:param data_format: 'torch' to use Tensors, 'numpy' to use ndarrays.
Will use Tensors if any data argument does, else ndarrays
:param done: boolean ndarray, specifying for each step whether it led to termination.
The last step of continuous rollouts, i.e. not mini-batches, is done if `complete` is `True`.
:param continuous: true if the steps form one continuous sequence.
:param rewards: sequence of reward values, determines sequence length
:param observations: sequence of observation values, the length must be `len(rewards) + 1`
:param actions: sequence of action values, the length must be `len(rewards)`
:param data: additional data lists, their length must be `len(rewards)` or `len(rewards) + 1`
Get the step sequence's length.
Helper to return `next_value = 0` for last step
Add a new data field to the step sequence.
:param name: string for the name
:param value: the data
:param item_shape: shape to store the data in
:param with_after_last: `True` if there is one more element than the length (e.g. last observation)
Concatenate multiple step sequences into one, truncating the last observation.
:param parts: batch of sequences to concatenate
:param data_format: torch to use Tensors, numpy to use ndarrays, `None` to choose automatically
:param truncate_last: remove the last step from each part, highly recommended to be `True`
:return: concatenated sequence of `Steps`
Convert data to specified format.
:param data_format: torch to use Tensors, numpy to use ndarrays
:param data_type: optional torch/numpy dtype for data. When `None` is passed, the data type is left unchanged.
Get the name of data format ('torch' or 'numpy').
Get the list of data attribute names.
Compute the discounted return.
:param gamma: temporal discount factor
:return: exponentially weighted sum of rewards
Use a linear filter to compute the reverse discounted cumulative sum.
.. note::
`scipy.signal.lfilter` assumes an initialization with 0 by default.
:param data: input data with samples along the 0 axis (e.g. time series)
:param gamma: discount factor
:return: cumulative sums for every step
Compute the discounted state values for one rollout.
:param rollout: input data
:param gamma: temporal discount factor
:return: state values for every time step in the rollout
Compute the discounted state values for multiple rollouts.
:param rollouts: input data
:param gamma: temporal discount factor
:param data_format: data format of the given
:return: state values for every time step in the rollouts (concatenated sequence across rollouts)
Compute returns using generalized advantage estimation.
.. seealso::
[1] J. Schulmann, P. Moritz, S. Levine, M. Jordan, P. Abbeel, 'High-Dimensional Continuous Control Using
Generalized Advantage Estimation', ICLR 2016
:param rollout: sequence of steps
:param gamma: temporal discount factor
:param lamb: discount factor
:return: estimated advantage
Return the data tensor stored under the given name.
:param name: data name
:param truncate_last: True to truncate the length+1 entry if present
Get an indexed sub-rollout.
:param index: generic index of sub-rollout, negative values, slices and iterables are allowed
:return: selected subset.
Iterate over all sub-rollouts of a concatenated rollout.
Convert data to numpy ndarrays.
:param data_type: type to return data in. When None is passed, the data type is left unchanged.
Process all data fields of a rollouts using an arbitrary function. Optionally, some fields can be excluded.
:param rollout: `StepSequence` holding the data
:param fcn: function (of one remaining input) to used manipulate the data fields, e.g. `scipy.filtfilt()`
:param fcn_arg_name: sting of the remaining input of `process_fcn()`, e.g. `x` for `scipy.filtfilt()`
:param fcn_arg_types: type or tuple thereof which are expected as input to `fcn()`
:param include_fields: list of field names to include for processing, pass `None` to not include everything.
If specified, only fields from this selection will be considered
:param exclude_fields: list of field names to exclude from processing, pass `None` to not exclude anything
:param process_fcn_kwargs: keyword arguments forwarded to `process_fcn()`
:return: new `StepSequence` instance with processed data
Wrap the processing function to call it recursivelyy for nested data structures.
Count the number of sub-rollouts inside this step sequence.
Lengths of sub-rollouts.
Sample a random batch of steps from a together with the associated next steps.
Similar to `split_shuffled_batches` with `complete_rollouts=False`
:param batch_size: number of steps to sample
:return: randomly sampled batch of steps
Batch generation. Split the step collection into ordered mini-batches of size batch_size.
:param batch_size: number of steps per batch, i.e. variable number of batches
:param num_batches: number of batches to split the rollout in, i.e. variable batch size
.. note::
Left out the option to return complete rollouts like for `split_shuffled_batches`.
Batch generation. Split the step collection into random mini-batches of size batch_size.
:param batch_size: number of steps per batch
:param complete_rollouts: if `complete_rollouts = True`, the batches will not contain partial rollouts.
However, the size of the returned batches cannot be strictly maintained in this case.
.. note::
This method is also supposed to be called for recurrent networks, which have a different `evaluate()`
method that recognized where the rollouts end within a batch.
Convert data to PyTorch Tensors.
:param data_type: type to return data in. When None is passed, the data type is left unchanged.
Compute the undiscounted return.
:return: sum of rewards
Copyright (c) 2020, Fabio Muratore, Honda Research Institute Europe GmbH, and Technical University of Darmstadt. 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. 3. Neither the name of Fabio Muratore, Honda Research Institute Europe GmbH, or Technical University of Darmstadt, 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 FABIO MURATORE, HONDA RESEARCH INSTITUTE EUROPE GMBH, OR TECHNICAL UNIVERSITY OF DARMSTADT 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. Index conversion Check negative index Check bounds Obtain keyed value from obj dict Try pluralized keys Obtain indexed element from value Return subdict proxy Return tuple of slices Since we can't proxy a tuple, we slice eagerly Use type(value) to support named tuples. (the keys is still index though) Return slice of ndarray / tensor Return list item Unsupported type Obtain keyed value list from obj dict Obtain keyed value list from obj dict Set value to data Set slice of ndarray/tensor Set list item Don't support setting dict proxies List dict items not starting with _ Define getitem and setitem too, helps when return attr is a keyword Serialize only dict and index Call DictIndexProxy's constructor Serialize rollout and index Set of required rollout fields in addition to rewards, observations, actions. Putting this into a class field instead of using the constructor arguments reduces duplicate code and allows to override it during unit tests. print (data) Obtain rollout length from reward list Set singular attributes Infer if this instance is using numpy arrays or PyTorch tensors We ignore rewards here since it's probably scalar Use numpy by default Check for missing extra fields Set mandatory data fields Set other data fields and verify their length Set done list if any. The done list is always a numpy array since torch doesn't support boolean tensors. Compute rollout bounds from done list (yes this is not exactly safe...) The bounds list has one extra entry 0, this simplifies queries greatly. bounds[i] = start of rollout i; bounds[i+1]=end of rollout i Validate externally passed bounds. Return a StepSequence object with the subset. Build sliced data dict. Check if the slice is continuous Slice rollout bounds too. Should be a singular element index. Return step proxy. Modify dict in-place Can't modify in place since it's a tuple Tensor element In torch case: check that we don't mess with gradients Check type of data Validate dict entries Validate dict entries A single array. The first dimension must match Should be a sequence Disallow +1 tensors unsupported No truncation Compute desired step length Create zero-filled Check the data Stack into one array/tensor Ensure right array format Store in dict Truncate if needed Check length Analyze slice A simple, continuous slice Convert nonstandard slice to range Nontrivial non-continuous slice, need to slice each element and concat them. Decode index Optimize for single rollout - 2 to always have a next step Switch the splitting mode Yield all at once if there are less steps than the batch size Split by steps Yield all at once if there are less steps than the batch size Our goal here is to randomly shuffle the rollouts, while returning batches of batch_size steps. The solution here is to take rollouts in a random order and yield a batch each time it exceeds batch_size. Now, walk through the rollouts in a random order and split once batch size is full. Got a full batch Yield eventual final one Split by steps Obtain data attribute names Deduce data format if is None Concat data fields Treat done separately since it should stay a ndarray Check if parts are continuous Concatenate rollout separator indices for continuous rollouts Add to actual data input to the keyword arguments to make calling the function easier Process the data Recursive call Recursive call Go through all desired data fields and apply the processing function Extract data field Process current data field if included and not explicitly excluded Collect the new/old data Create new object The ndarray.copy() is necessary due to (currently) unsupported negative strides | 13,235 | en | 0.813468 |
# This file is part of Indico.
# Copyright (C) 2002 - 2021 CERN
#
# Indico is free software; you can redistribute it and/or
# modify it under the terms of the MIT License; see the
# LICENSE file for more details.
from flask_caching import Cache
from flask_caching.backends.rediscache import RedisCache
from flask_caching.backends.simplecache import SimpleCache
from redis import RedisError
from indico.core.logger import Logger
_logger = Logger.get('cache')
class CachedNone:
__slots__ = ()
@classmethod
def wrap(cls, value):
return cls() if value is None else value
@classmethod
def unwrap(cls, value, default=None):
if value is None:
return default
elif isinstance(value, cls):
return None
else:
return value
class IndicoCacheMixin:
def get(self, key, default=None):
return CachedNone.unwrap(super().get(key), default)
def get_many(self, *keys, default=None):
return [CachedNone.unwrap(val, default) for val in super().get_many(*keys)]
def get_dict(self, *keys, default=None):
return dict(zip(keys, self.get_many(*keys, default=default)))
class IndicoRedisCache(IndicoCacheMixin, RedisCache):
"""
This is similar to the original RedisCache from Flask-Caching, but it
allows specifying a default value when retrieving cache data and
distinguishing between a cached ``None`` value and a cache miss.
"""
def dump_object(self, value):
# We are not overriding the `load_object` counterpart to this method o
# purpose because we need to have access to the wrapped value in `get`
# and `get_many`.
return super().dump_object(CachedNone.wrap(value))
class IndicoSimpleCache(IndicoCacheMixin, SimpleCache):
"""
This is similar to the original SimpleCache from Flask-Caching, but it
allows specifying a default value when retrieving cache data and
distinguishing between a cached ``None`` value and a cache miss.
"""
def set(self, key, value, timeout=None):
return super().set(key, CachedNone.wrap(value), timeout=timeout)
def add(self, key, value, timeout=None):
return super().add(key, CachedNone.wrap(value), timeout=timeout)
def make_indico_simple_cache(app, config, args, kwargs):
return IndicoSimpleCache(*args, **kwargs)
def make_indico_redis_cache(app, config, args, kwargs):
from redis import from_url as redis_from_url
key_prefix = config.get('CACHE_KEY_PREFIX')
if key_prefix:
kwargs['key_prefix'] = key_prefix
kwargs['host'] = redis_from_url(config['CACHE_REDIS_URL'], socket_timeout=1)
return IndicoRedisCache(*args, **kwargs)
class ScopedCache:
def __init__(self, cache, scope):
self.cache = cache
self.scope = scope
def _scoped(self, key):
return f'{self.scope}/{key}'
def get(self, key, default=None):
return self.cache.get(self._scoped(key), default=default)
def set(self, key, value, timeout=None):
self.cache.set(self._scoped(key), value, timeout=timeout)
def add(self, key, value, timeout=None):
self.cache.add(self._scoped(key), value, timeout=timeout)
def delete(self, key):
self.cache.delete(self._scoped(key))
def delete_many(self, *keys):
keys = [self._scoped(key) for key in keys]
self.cache.delete_many(*keys)
def clear(self):
raise NotImplementedError('Clearing scoped caches is not supported')
def get_dict(self, *keys, default=None):
return dict(zip(keys, self.get_many(*keys, default=default)))
def get_many(self, *keys, default=None):
keys = [self._scoped(key) for key in keys]
return self.cache.get_many(*keys, default=default)
def set_many(self, mapping, timeout=None):
mapping = {self._scoped(key): value for key, value in mapping.items()}
self.cache.set_many(mapping, timeout=timeout)
def __repr__(self):
return f'<ScopedCache: {self.scope}>'
class IndicoCache(Cache):
"""
This is basicaly the Cache class from Flask-Caching but it silences all
exceptions that happen during a cache operation since cache failures should
not take down the whole page.
While this cache can in principle support many different backends, we only
consider redis and (for unittests) a simple dict-based cache. This allows
us to be more specific in catching exceptions since the Redis cache has
exactly one base exception.
"""
def get(self, key, default=None):
try:
return super().get(key, default)
except RedisError:
_logger.exception('get(%r) failed', key)
return default
def set(self, key, value, timeout=None):
try:
super().set(key, value, timeout=timeout)
except RedisError:
_logger.exception('set(%r) failed', key)
def add(self, key, value, timeout=None):
try:
super().add(key, value, timeout=timeout)
except RedisError:
_logger.exception('add(%r) failed', key)
def delete(self, key):
try:
super().delete(key)
except RedisError:
_logger.exception('delete(%r) failed', key)
def delete_many(self, *keys):
try:
super().delete_many(*keys)
except RedisError:
_logger.exception('delete_many(%s) failed', ', '.join(map(repr, keys)))
def clear(self):
try:
super().clear()
except RedisError:
_logger.exception('clear() failed')
def get_many(self, *keys, default=None):
try:
return super().get_many(*keys, default=default)
except RedisError:
logkeys = ', '.join(map(repr, keys))
_logger.exception('get_many(%s) failed', logkeys)
return [default] * len(keys)
def set_many(self, mapping, timeout=None):
try:
super().set_many(mapping, timeout=timeout)
except RedisError:
_logger.exception('set_many(%r) failed', mapping)
def get_dict(self, *keys, default=None):
try:
return super().get_dict(*keys, default=default)
except RedisError:
logkeys = ', '.join(map(repr, keys))
_logger.exception('get_dict(%s) failed', logkeys)
return dict(zip(keys, [default] * len(keys)))
def make_scoped_cache(scope):
"""Create a new scoped cache.
In most cases the global cache should not be used directly but rather
with a scope depending on the module a cache is used for. This is
especially important when passing user-provided data as the cache key
to prevent reading other unrelated cache keys.
"""
return ScopedCache(cache, scope)
cache = IndicoCache()
| indico/core/cache.py | 6,842 | This is basicaly the Cache class from Flask-Caching but it silences all
exceptions that happen during a cache operation since cache failures should
not take down the whole page.
While this cache can in principle support many different backends, we only
consider redis and (for unittests) a simple dict-based cache. This allows
us to be more specific in catching exceptions since the Redis cache has
exactly one base exception.
This is similar to the original RedisCache from Flask-Caching, but it
allows specifying a default value when retrieving cache data and
distinguishing between a cached ``None`` value and a cache miss.
This is similar to the original SimpleCache from Flask-Caching, but it
allows specifying a default value when retrieving cache data and
distinguishing between a cached ``None`` value and a cache miss.
Create a new scoped cache.
In most cases the global cache should not be used directly but rather
with a scope depending on the module a cache is used for. This is
especially important when passing user-provided data as the cache key
to prevent reading other unrelated cache keys.
This file is part of Indico. Copyright (C) 2002 - 2021 CERN Indico is free software; you can redistribute it and/or modify it under the terms of the MIT License; see the LICENSE file for more details. We are not overriding the `load_object` counterpart to this method o purpose because we need to have access to the wrapped value in `get` and `get_many`. | 1,466 | en | 0.828011 |
import numpy as np # linear algebra
np.random.seed(42)
import pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)
from sklearn.model_selection import train_test_split
from matplotlib import pyplot
import time
import os, glob
import cv2
# parameters
format = "%H%M"
ts = time.strftime(format)
base_name = os.path.splitext(__file__)[0] + "_ts" + ts
input_size = 128
from keras.preprocessing.image import ImageDataGenerator
from keras.models import Sequential
from keras.layers import Conv2D, MaxPooling2D, Dense, Dropout, Input, Flatten, GaussianNoise
from keras.layers import GlobalMaxPooling2D, Reshape, UpSampling3D, Activation
from keras.layers.normalization import BatchNormalization
from keras.layers.merge import Concatenate
from keras.models import Model
from keras.optimizers import Adam
from keras.callbacks import ModelCheckpoint, Callback, EarlyStopping, CSVLogger, ReduceLROnPlateau
from keras import backend as K
def get_callbacks(save_path, lr=0.001, patience=64):
csv_logger = CSVLogger(save_path + '_log.csv', append=True)
# check_path = save_path + '_e{epoch:02d}_vl{val_loss:.5f}.hdf5'
check_path = save_path
save_checkpoint = ModelCheckpoint(filepath=check_path, monitor='val_loss', save_best_only=True)
lerning_rate_schedular = ReduceLROnPlateau(patience=8, min_lr=lr * 0.00001)
early_stopping = EarlyStopping(monitor='val_loss',
patience=16,
verbose=1,
min_delta=1e-4,
mode='min')
Callbacks = [csv_logger,
save_checkpoint,
# lerning_rate_schedular,
early_stopping
]
return Callbacks
def swish(x):
return x * K.sigmoid(x)
from keras.applications.vgg16 import VGG16
from keras.optimizers import SGD
def get_model(num_class):
base_model = VGG16(weights='imagenet', include_top=False,
input_shape=[input_size,input_size,3], classes=1)
x = base_model.get_layer('block5_pool').output
x = GlobalMaxPooling2D()(x)
x = Dense(512, activation='relu', name='fc2')(x)
x = Dropout(0.3)(x)
x = Dense(512, activation='relu', name='fc3')(x)
x = Dropout(0.3)(x)
predictions = Dense(num_class, activation='softmax')(x)
model = Model(inputs=base_model.input, outputs=predictions)
sgd = SGD(lr=1e-3, decay=1e-6, momentum=0.9, nesterov=True)
model.compile(loss='categorical_crossentropy',
optimizer=sgd,
metrics=['accuracy'])
return model
def randomHueSaturationValue(image, hue_shift_limit=(-180, 180),
sat_shift_limit=(-255, 255),
val_shift_limit=(-255, 255), u=0.5):
if np.random.random() < u:
image = cv2.cvtColor(image, cv2.COLOR_BGR2HSV)
h, s, v = cv2.split(image) # sikisou, saido, meido
hue_shift = np.random.uniform(hue_shift_limit[0], hue_shift_limit[1])
h = cv2.add(h, hue_shift)
sat_shift = np.random.uniform(sat_shift_limit[0], sat_shift_limit[1])
s = cv2.add(s, sat_shift)
val_shift = np.random.uniform(val_shift_limit[0], val_shift_limit[1])
v = cv2.add(v, val_shift)
image = cv2.merge((h, s, v))
image = cv2.cvtColor(image, cv2.COLOR_HSV2BGR)
return image
def randomShiftScaleRotate(image,
shift_limit=(-0.0625, 0.0625),
scale_limit=(-0.1, 0.1),
rotate_limit=(-45, 45), aspect_limit=(0, 0),
borderMode=cv2.BORDER_CONSTANT, u=0.5):
if np.random.random() < u:
height, width, channel = image.shape
angle = np.random.uniform(rotate_limit[0], rotate_limit[1]) # degree
scale = np.random.uniform(1 + scale_limit[0], 1 + scale_limit[1])
aspect = np.random.uniform(1 + aspect_limit[0], 1 + aspect_limit[1])
sx = scale * aspect / (aspect ** 0.5)
sy = scale / (aspect ** 0.5)
dx = round(np.random.uniform(shift_limit[0], shift_limit[1]) * width)
dy = round(np.random.uniform(shift_limit[0], shift_limit[1]) * height)
cc = np.math.cos(angle / 180 * np.math.pi) * sx
ss = np.math.sin(angle / 180 * np.math.pi) * sy
rotate_matrix = np.array([[cc, -ss], [ss, cc]])
box0 = np.array([[0, 0], [width, 0], [width, height], [0, height], ])
box1 = box0 - np.array([width / 2, height / 2])
box1 = np.dot(box1, rotate_matrix.T) + np.array([width / 2 + dx, height / 2 + dy])
box0 = box0.astype(np.float32)
box1 = box1.astype(np.float32)
mat = cv2.getPerspectiveTransform(box0, box1)
image = cv2.warpPerspective(image, mat, (width, height), flags=cv2.INTER_LINEAR, borderMode=borderMode,
borderValue=(
0, 0,
0,))
return image
def randomHorizontalFlip(image, u=0.5):
if np.random.random() < u:
image = cv2.flip(image, 1)
return image
def randomVerticalFlip(image, u=0.5):
if np.random.random() < u:
image = cv2.flip(image, 0)
return image
def get_random_eraser(p=0.5, s_l=0.02, s_h=0.4, r_1=0.3, r_2=1/0.3, v_l=0, v_h=255, pixel_level=False):
def eraser(input_img):
img_h, img_w, img_c = input_img.shape
p_1 = np.random.rand()
if p_1 > p:
return input_img
while True:
s = np.random.uniform(s_l, s_h) * img_h * img_w
r = np.random.uniform(r_1, r_2)
w = int(np.sqrt(s / r))
h = int(np.sqrt(s * r))
left = np.random.randint(0, img_w)
top = np.random.randint(0, img_h)
if left + w <= img_w and top + h <= img_h:
break
if pixel_level:
c = np.random.uniform(v_l, v_h, (h, w, img_c))
else:
c = np.random.uniform(v_l, v_h)
input_img[top:top + h, left:left + w, :] = c
return input_img
return eraser
from multiprocessing import Pool
def load_img(args):
img_path = args
img = cv2.imread(img_path)
# print("img shape", img.shape)
img = cv2.resize(img, (input_size, input_size))
img = randomHueSaturationValue(img,
hue_shift_limit=(-5, 5),
sat_shift_limit=(-1, 1),
val_shift_limit=(-2, 2),
u=0.5)
img = randomShiftScaleRotate(img,
shift_limit=(-0.2, 0.2),
scale_limit=(-0.2, 0.5),
rotate_limit=(-30, 30),
aspect_limit=(-0.2, 0.2),
u=0.5)
img = randomHorizontalFlip(img)
img = randomVerticalFlip(img)
return img
def train_generator(x_train, y_train, img_dir, batch_size, shuffle=True):
# x_train = x_train.as_matrix()
# y_train = y_train.as_matrix()
y_train = np.eye(55)[y_train]
batch_index = 0
n = x_train.shape[0]
# print("n", n)
eraser = get_random_eraser(v_h=0.)
pool = Pool()
while 1:
if batch_index == 0:
index_array = np.arange(n)
if shuffle:
index_array = np.random.permutation(n)
current_index = (batch_index * batch_size) % n
if n >= current_index + batch_size:
current_batch_size = batch_size
batch_index += 1
else:
current_batch_size = n - current_index
batch_index = 0
batch_id = index_array[current_index: current_index + current_batch_size]
batch_x = pool.map(load_img,
[img_dir + '/{}'.format(x_train[id])
for id in batch_id])
for id in range(len(batch_x)):
img = batch_x[id]
img =eraser(img)
# img =eraser(img)
# img =eraser(img)
# img =eraser(img)
# img =eraser(img)
batch_x[id] = img
batch_x = np.array(batch_x, np.float32) / 255
batch_y = y_train[index_array[current_index: current_index + current_batch_size]]
# print("batch shape", batch_x.shape, batch_y.shape)
yield (batch_x, batch_y)
def get_mixer(p=0.5, s_l=0.02, s_h=0.4, r_1=0.3, r_2=1/0.3):
def mixer(img1, img2, mask1, mask2):
img_h, img_w, img_c = img1.shape
p_1 = np.random.rand()
if p_1 > p:
return img1, mask1
while True:
s = np.random.uniform(s_l, s_h) * img_h * img_w
r = np.random.uniform(r_1, r_2)
w = int(np.sqrt(s / r))
h = int(np.sqrt(s * r))
left = np.random.randint(0, img_w)
top = np.random.randint(0, img_h)
if left + w <= img_w and top + h <= img_h:
break
img1[top:top + h, left:left + w, :] = img2[top:top + h, left:left + w, :]
mask1[top:top + h, left:left + w, :] = mask2[top:top + h, left:left + w, :]
return img1, mask1
return mixer
def mix_generator(X_train, Y_train, img_dir, batch_size, shuffle=True):
alpha = 0.2
gen1 = train_generator(X_train, Y_train, img_dir, batch_size, shuffle)
gen2 = train_generator(X_train, Y_train, img_dir, batch_size, shuffle)
while True:
batch1 = next(gen1)
batch2 = next(gen2)
current_batch_size = batch1[0].shape[0]
l = np.random.beta(alpha, alpha, current_batch_size)
X_l = l.reshape(current_batch_size, 1, 1, 1)
Y_l = l.reshape(current_batch_size, 1)
batch_x = batch1[0] * X_l + batch2[0] * (1 - X_l)
batch_y = batch1[1] * Y_l + batch2[1] * (1 - Y_l)
yield (batch_x, batch_y)
def test_generator(x_train, img_dir, batch_size, shuffle=True):
# x_train = x_train.as_matrix()
# y_train = y_train.as_matrix()
batch_index = 0
n = x_train.shape[0]
# print("n", n)
eraser = get_random_eraser(v_h=0.)
while 1:
if batch_index == 0:
index_array = np.arange(n)
if shuffle:
index_array = np.random.permutation(n)
current_index = (batch_index * batch_size) % n
if n >= current_index + batch_size:
current_batch_size = batch_size
batch_index += 1
else:
current_batch_size = n - current_index
batch_index = 0
batch_x = []
batch_id = index_array[current_index: current_index + current_batch_size]
# print(batch_x_base)
for id in batch_id:
# print(x_train[0])
# print(x_train[id])
# print(img_dir + '/{}'.format(x_train[id]))
img = cv2.imread(img_dir + '/{}'.format(x_train[id]))
# print("img shape", img.shape)
img = cv2.resize(img, (input_size, input_size))
img = randomHueSaturationValue(img,
hue_shift_limit=(-5, 5),
sat_shift_limit=(-1, 1),
val_shift_limit=(-2, 2),
u=0.5)
img = randomShiftScaleRotate(img,
shift_limit=(-0.2, 0.2),
scale_limit=(-0.2, 0.2),
rotate_limit=(-30, 30),
aspect_limit = (-0.2, 0.2),
u=0.5)
img = randomHorizontalFlip(img)
# img =eraser(img)
batch_x.append(img)
batch_x = np.array(batch_x, np.float32) / 255
# batch_y = y_train[index_array[current_index: current_index + current_batch_size]]
# print("batch shape", batch_x.shape, batch_y.shape)
yield batch_x
def load_data(train_path="input/train_master.tsv", test_path="input/sample_submit.tsv"):
train = pd.read_csv(train_path, delimiter="\t", index_col=False)
test = pd.read_csv(test_path, delimiter="\t", index_col=False, header=None)
print("train shape", train.shape)
print(train.head())
X_train = train['file_name'].as_matrix()
y_train = train['category_id'].as_matrix()
# y_train = np.eye(55)[y_train]
# print(y_train[:5])
# print(y_train.shape)
X_test = test.iloc[:,0]
return X_train, y_train, X_test
from sklearn.model_selection import StratifiedKFold, StratifiedShuffleSplit
from sklearn.metrics import log_loss
def train(epochs, seed):
# parameter
batch_size = 128
num_class = 55
save_path = base_name + "_seed" + str(seed)
model_path = "_"
# Load data
X_train, y_train, X_test = load_data()
# CV
ids_train_split, ids_valid_split = train_test_split(np.arange(X_train.shape[0]),
random_state=42, test_size=0.05,
stratify=y_train)
# data process
X_train_cv = X_train[ids_train_split]
y_train_cv = y_train[ids_train_split]
X_holdout = X_train[ids_valid_split]
Y_holdout = y_train[ids_valid_split]
# print(X_train_cv.head())
# define file path and get callbacks
weight_path = "model/" + save_path + '.hdf5'
callbacks = get_callbacks(weight_path, patience=16)
gen = mix_generator(X_train_cv, y_train_cv, "input/train", batch_size)
gen_val = train_generator(X_holdout, Y_holdout, "input/train", batch_size, shuffle=False)
gen_val_pred = test_generator(X_holdout, "input/train", batch_size, shuffle=False)
gen_tst_pred = test_generator(X_test, "input/test", batch_size, shuffle=False)
model = get_model(num_class)
model.fit_generator(generator=gen,
steps_per_epoch=np.ceil(X_train_cv.shape[0] / batch_size),
epochs=epochs,
verbose=1,
callbacks=callbacks,
validation_data=gen_val,
validation_steps=np.ceil(X_holdout.shape[0] / batch_size),
)
# Getting the Best Model
model.load_weights(filepath=weight_path)
# Getting Training Score
# score = model.evaluate_generator(generator=gen_trn_eval,
# steps=np.ceil(X_train.shape[0]/batch_size))
# print('Train loss:', score[0])
# print('Train accuracy:', score[1])
# Getting Valid Score
score = model.evaluate_generator(generator=gen_val,
steps=np.ceil(X_holdout.shape[0]/batch_size))
print('Valid loss:', score[0])
print('Valid accuracy:', score[1])
# Getting validation prediction
pred_valid = model.predict_generator(generator=gen_val_pred,
steps=np.ceil(X_holdout.shape[0]/batch_size))
# Getting Test prediction
pred_test = model.predict_generator(generator=gen_tst_pred,
steps=np.ceil(X_test.shape[0]/batch_size))
submission = pd.DataFrame({'id': X_test, 'predict': np.argmax(pred_test, axis=1)})
submit_path = "output/submission" + save_path + "_val_loss" + str(score[0]) + "_val_acc" + str(score[1]) + ".tsv"
submission.to_csv(submit_path, index=False, header=False, sep='\t')
np.save("input/" + base_name + "_valid.npy", pred_valid)
np.save("input/" + base_name + "_test.npy", pred_test)
def main():
train(epochs=250, seed=0)
if __name__ == "__main__": main()
| train_180131_2.py | 15,766 | linear algebra data processing, CSV file I/O (e.g. pd.read_csv) parameters check_path = save_path + '_e{epoch:02d}_vl{val_loss:.5f}.hdf5' lerning_rate_schedular, sikisou, saido, meido degree print("img shape", img.shape) x_train = x_train.as_matrix() y_train = y_train.as_matrix() print("n", n) img =eraser(img) img =eraser(img) img =eraser(img) img =eraser(img) print("batch shape", batch_x.shape, batch_y.shape) x_train = x_train.as_matrix() y_train = y_train.as_matrix() print("n", n) print(batch_x_base) print(x_train[0]) print(x_train[id]) print(img_dir + '/{}'.format(x_train[id])) print("img shape", img.shape) img =eraser(img) batch_y = y_train[index_array[current_index: current_index + current_batch_size]] print("batch shape", batch_x.shape, batch_y.shape) y_train = np.eye(55)[y_train] print(y_train[:5]) print(y_train.shape) parameter Load data CV data process print(X_train_cv.head()) define file path and get callbacks Getting the Best Model Getting Training Score score = model.evaluate_generator(generator=gen_trn_eval, steps=np.ceil(X_train.shape[0]/batch_size)) print('Train loss:', score[0]) print('Train accuracy:', score[1]) Getting Valid Score Getting validation prediction Getting Test prediction | 1,253 | en | 0.581472 |
import logging
import numpy as np
from cvlib.object_detection import populate_class_labels, draw_bbox, detect_common_objects
from traffic_monitor.services.detectors.detector_abstract import DetectorAbstract
logger = logging.getLogger('detector')
class DetectorCVlib(DetectorAbstract):
"""
Implementation of DetectorAbstract. This implementation is from the OpenCV
implementation of object instance detection.
https://github.com/arunponnusamy/cvlib
Yolov4 cfg and weights are available at: https://github.com/AlexeyAB/darknet
Supports models:
yolov3-tiny
yolov3
Requires that .cfg file and .weights files are in ~/.cvlib/object_detection/yolo/yolov3
"""
def __init__(self, monitor_config: dict):
DetectorAbstract.__init__(self, monitor_config)
self.detector_name: str = monitor_config.get('detector_name')
self.detector_model: str = monitor_config.get('detector_model')
self.detector_confidence: float = monitor_config.get('detector_confidence')
# note that colors in cvlib uses BGR not RGB colors
self.bgr_colors = np.float64([monitor_config.get('class_colors').get(o)[::-1] for o in populate_class_labels()])
def set_detector_value(self, kwargs_list: list):
""" Only allow changes to confidence or the model """
try:
for kwargs in kwargs_list:
field = kwargs.get('field')
value = kwargs.get('value')
if field in ['detector_confidence', 'detector_model']:
logger.info(f"{self.detector_name}: setting value: {field}: {value}")
self.monitor_config[field] = value
except Exception as e:
logger.error(f"{self.__class__.__name__}: Error setting value: {e}")
def detect(self, frame: np.array) -> (np.array, list):
# colors is a list of BGR values in a list ([[#b,#g,#r],[#b,#g,#r], ... ])
try:
bbox, labels, conf = detect_common_objects(frame, confidence=self.detector_confidence, model=self.detector_model)
frame = draw_bbox(img=frame, bbox=bbox, labels=labels, confidence=conf, write_conf=False, colors=self.bgr_colors)
return frame, labels
except Exception as e:
logger.error(f"{self.__class__.__name__} Exception: {e}")
@classmethod
def get_trained_objects(cls) -> list:
return populate_class_labels()
| traffic_monitor/services/detectors/detector_cvlib.py | 2,446 | Implementation of DetectorAbstract. This implementation is from the OpenCV
implementation of object instance detection.
https://github.com/arunponnusamy/cvlib
Yolov4 cfg and weights are available at: https://github.com/AlexeyAB/darknet
Supports models:
yolov3-tiny
yolov3
Requires that .cfg file and .weights files are in ~/.cvlib/object_detection/yolo/yolov3
Only allow changes to confidence or the model
note that colors in cvlib uses BGR not RGB colors colors is a list of BGR values in a list ([[b,g,r],[b,g,r], ... ]) | 538 | en | 0.712869 |
import torch.nn.functional as F
from torch import nn
from torchvision.ops import MultiScaleRoIAlign
from ..._internally_replaced_utils import load_state_dict_from_url
from ...ops import misc as misc_nn_ops
from ..mobilenetv3 import mobilenet_v3_large
from ..resnet import resnet50
from ._utils import overwrite_eps
from .anchor_utils import AnchorGenerator
from .backbone_utils import _resnet_fpn_extractor, _validate_trainable_layers, _mobilenet_extractor
from .generalized_rcnn import GeneralizedRCNN
from .roi_heads import RoIHeads
from .rpn import RPNHead, RegionProposalNetwork
from .transform import GeneralizedRCNNTransform
__all__ = [
"FasterRCNN",
"fasterrcnn_resnet50_fpn",
"fasterrcnn_mobilenet_v3_large_320_fpn",
"fasterrcnn_mobilenet_v3_large_fpn",
]
class FasterRCNN(GeneralizedRCNN):
"""
Implements Faster R-CNN.
The input to the model is expected to be a list of tensors, each of shape [C, H, W], one for each
image, and should be in 0-1 range. Different images can have different sizes.
The behavior of the model changes depending if it is in training or evaluation mode.
During training, the model expects both the input tensors, as well as a targets (list of dictionary),
containing:
- boxes (``FloatTensor[N, 4]``): the ground-truth boxes in ``[x1, y1, x2, y2]`` format, with
``0 <= x1 < x2 <= W`` and ``0 <= y1 < y2 <= H``.
- labels (Int64Tensor[N]): the class label for each ground-truth box
The model returns a Dict[Tensor] during training, containing the classification and regression
losses for both the RPN and the R-CNN.
During inference, the model requires only the input tensors, and returns the post-processed
predictions as a List[Dict[Tensor]], one for each input image. The fields of the Dict are as
follows:
- boxes (``FloatTensor[N, 4]``): the predicted boxes in ``[x1, y1, x2, y2]`` format, with
``0 <= x1 < x2 <= W`` and ``0 <= y1 < y2 <= H``.
- labels (Int64Tensor[N]): the predicted labels for each image
- scores (Tensor[N]): the scores or each prediction
Args:
backbone (nn.Module): the network used to compute the features for the model.
It should contain a out_channels attribute, which indicates the number of output
channels that each feature map has (and it should be the same for all feature maps).
The backbone should return a single Tensor or and OrderedDict[Tensor].
num_classes (int): number of output classes of the model (including the background).
If box_predictor is specified, num_classes should be None.
min_size (int): minimum size of the image to be rescaled before feeding it to the backbone
max_size (int): maximum size of the image to be rescaled before feeding it to the backbone
image_mean (Tuple[float, float, float]): mean values used for input normalization.
They are generally the mean values of the dataset on which the backbone has been trained
on
image_std (Tuple[float, float, float]): std values used for input normalization.
They are generally the std values of the dataset on which the backbone has been trained on
rpn_anchor_generator (AnchorGenerator): module that generates the anchors for a set of feature
maps.
rpn_head (nn.Module): module that computes the objectness and regression deltas from the RPN
rpn_pre_nms_top_n_train (int): number of proposals to keep before applying NMS during training
rpn_pre_nms_top_n_test (int): number of proposals to keep before applying NMS during testing
rpn_post_nms_top_n_train (int): number of proposals to keep after applying NMS during training
rpn_post_nms_top_n_test (int): number of proposals to keep after applying NMS during testing
rpn_nms_thresh (float): NMS threshold used for postprocessing the RPN proposals
rpn_fg_iou_thresh (float): minimum IoU between the anchor and the GT box so that they can be
considered as positive during training of the RPN.
rpn_bg_iou_thresh (float): maximum IoU between the anchor and the GT box so that they can be
considered as negative during training of the RPN.
rpn_batch_size_per_image (int): number of anchors that are sampled during training of the RPN
for computing the loss
rpn_positive_fraction (float): proportion of positive anchors in a mini-batch during training
of the RPN
rpn_score_thresh (float): during inference, only return proposals with a classification score
greater than rpn_score_thresh
box_roi_pool (MultiScaleRoIAlign): the module which crops and resizes the feature maps in
the locations indicated by the bounding boxes
box_head (nn.Module): module that takes the cropped feature maps as input
box_predictor (nn.Module): module that takes the output of box_head and returns the
classification logits and box regression deltas.
box_score_thresh (float): during inference, only return proposals with a classification score
greater than box_score_thresh
box_nms_thresh (float): NMS threshold for the prediction head. Used during inference
box_detections_per_img (int): maximum number of detections per image, for all classes.
box_fg_iou_thresh (float): minimum IoU between the proposals and the GT box so that they can be
considered as positive during training of the classification head
box_bg_iou_thresh (float): maximum IoU between the proposals and the GT box so that they can be
considered as negative during training of the classification head
box_batch_size_per_image (int): number of proposals that are sampled during training of the
classification head
box_positive_fraction (float): proportion of positive proposals in a mini-batch during training
of the classification head
bbox_reg_weights (Tuple[float, float, float, float]): weights for the encoding/decoding of the
bounding boxes
Example::
>>> import torch
>>> import torchvision
>>> from torchvision.models.detection import FasterRCNN
>>> from torchvision.models.detection.rpn import AnchorGenerator
>>> # load a pre-trained model for classification and return
>>> # only the features
>>> backbone = torchvision.models.mobilenet_v2(pretrained=True).features
>>> # FasterRCNN needs to know the number of
>>> # output channels in a backbone. For mobilenet_v2, it's 1280
>>> # so we need to add it here
>>> backbone.out_channels = 1280
>>>
>>> # let's make the RPN generate 5 x 3 anchors per spatial
>>> # location, with 5 different sizes and 3 different aspect
>>> # ratios. We have a Tuple[Tuple[int]] because each feature
>>> # map could potentially have different sizes and
>>> # aspect ratios
>>> anchor_generator = AnchorGenerator(sizes=((32, 64, 128, 256, 512),),
>>> aspect_ratios=((0.5, 1.0, 2.0),))
>>>
>>> # let's define what are the feature maps that we will
>>> # use to perform the region of interest cropping, as well as
>>> # the size of the crop after rescaling.
>>> # if your backbone returns a Tensor, featmap_names is expected to
>>> # be ['0']. More generally, the backbone should return an
>>> # OrderedDict[Tensor], and in featmap_names you can choose which
>>> # feature maps to use.
>>> roi_pooler = torchvision.ops.MultiScaleRoIAlign(featmap_names=['0'],
>>> output_size=7,
>>> sampling_ratio=2)
>>>
>>> # put the pieces together inside a FasterRCNN model
>>> model = FasterRCNN(backbone,
>>> num_classes=2,
>>> rpn_anchor_generator=anchor_generator,
>>> box_roi_pool=roi_pooler)
>>> model.eval()
>>> x = [torch.rand(3, 300, 400), torch.rand(3, 500, 400)]
>>> predictions = model(x)
"""
def __init__(
self,
backbone,
num_classes=None,
# transform parameters
min_size=800,
max_size=1333,
image_mean=None,
image_std=None,
# RPN parameters
rpn_anchor_generator=None,
rpn_head=None,
rpn_pre_nms_top_n_train=2000,
rpn_pre_nms_top_n_test=1000,
rpn_post_nms_top_n_train=2000,
rpn_post_nms_top_n_test=1000,
rpn_nms_thresh=0.7,
rpn_fg_iou_thresh=0.7,
rpn_bg_iou_thresh=0.3,
rpn_batch_size_per_image=256,
rpn_positive_fraction=0.5,
rpn_score_thresh=0.0,
# Box parameters
box_roi_pool=None,
box_head=None,
box_predictor=None,
box_score_thresh=0.05,
box_nms_thresh=0.5,
box_detections_per_img=100,
box_fg_iou_thresh=0.5,
box_bg_iou_thresh=0.5,
box_batch_size_per_image=512,
box_positive_fraction=0.25,
bbox_reg_weights=None,
):
if not hasattr(backbone, "out_channels"):
raise ValueError(
"backbone should contain an attribute out_channels "
"specifying the number of output channels (assumed to be the "
"same for all the levels)"
)
assert isinstance(rpn_anchor_generator, (AnchorGenerator, type(None)))
assert isinstance(box_roi_pool, (MultiScaleRoIAlign, type(None)))
if num_classes is not None:
if box_predictor is not None:
raise ValueError("num_classes should be None when box_predictor is specified")
else:
if box_predictor is None:
raise ValueError("num_classes should not be None when box_predictor is not specified")
out_channels = backbone.out_channels
if rpn_anchor_generator is None:
anchor_sizes = ((32,), (64,), (128,), (256,), (512,))
aspect_ratios = ((0.5, 1.0, 2.0),) * len(anchor_sizes)
rpn_anchor_generator = AnchorGenerator(anchor_sizes, aspect_ratios)
if rpn_head is None:
rpn_head = RPNHead(out_channels, rpn_anchor_generator.num_anchors_per_location()[0])
rpn_pre_nms_top_n = dict(training=rpn_pre_nms_top_n_train, testing=rpn_pre_nms_top_n_test)
rpn_post_nms_top_n = dict(training=rpn_post_nms_top_n_train, testing=rpn_post_nms_top_n_test)
rpn = RegionProposalNetwork(
rpn_anchor_generator,
rpn_head,
rpn_fg_iou_thresh,
rpn_bg_iou_thresh,
rpn_batch_size_per_image,
rpn_positive_fraction,
rpn_pre_nms_top_n,
rpn_post_nms_top_n,
rpn_nms_thresh,
score_thresh=rpn_score_thresh,
)
if box_roi_pool is None:
box_roi_pool = MultiScaleRoIAlign(featmap_names=["0", "1", "2", "3"], output_size=7, sampling_ratio=2)
if box_head is None:
resolution = box_roi_pool.output_size[0]
representation_size = 1024
box_head = TwoMLPHead(out_channels * resolution ** 2, representation_size)
if box_predictor is None:
representation_size = 1024
box_predictor = FastRCNNPredictor(representation_size, num_classes)
roi_heads = RoIHeads(
# Box
box_roi_pool,
box_head,
box_predictor,
box_fg_iou_thresh,
box_bg_iou_thresh,
box_batch_size_per_image,
box_positive_fraction,
bbox_reg_weights,
box_score_thresh,
box_nms_thresh,
box_detections_per_img,
)
if image_mean is None:
image_mean = [0.485, 0.456, 0.406]
if image_std is None:
image_std = [0.229, 0.224, 0.225]
transform = GeneralizedRCNNTransform(min_size, max_size, image_mean, image_std)
super().__init__(backbone, rpn, roi_heads, transform)
class TwoMLPHead(nn.Module):
"""
Standard heads for FPN-based models
Args:
in_channels (int): number of input channels
representation_size (int): size of the intermediate representation
"""
def __init__(self, in_channels, representation_size):
super().__init__()
self.fc6 = nn.Linear(in_channels, representation_size)
self.fc7 = nn.Linear(representation_size, representation_size)
def forward(self, x):
x = x.flatten(start_dim=1)
x = F.relu(self.fc6(x))
x = F.relu(self.fc7(x))
return x
class FastRCNNPredictor(nn.Module):
"""
Standard classification + bounding box regression layers
for Fast R-CNN.
Args:
in_channels (int): number of input channels
num_classes (int): number of output classes (including background)
"""
def __init__(self, in_channels, num_classes):
super().__init__()
self.cls_score = nn.Linear(in_channels, num_classes)
self.bbox_pred = nn.Linear(in_channels, num_classes * 4)
def forward(self, x):
if x.dim() == 4:
assert list(x.shape[2:]) == [1, 1]
x = x.flatten(start_dim=1)
scores = self.cls_score(x)
bbox_deltas = self.bbox_pred(x)
return scores, bbox_deltas
model_urls = {
"fasterrcnn_resnet50_fpn_coco": "https://download.pytorch.org/models/fasterrcnn_resnet50_fpn_coco-258fb6c6.pth",
"fasterrcnn_mobilenet_v3_large_320_fpn_coco": "https://download.pytorch.org/models/fasterrcnn_mobilenet_v3_large_320_fpn-907ea3f9.pth",
"fasterrcnn_mobilenet_v3_large_fpn_coco": "https://download.pytorch.org/models/fasterrcnn_mobilenet_v3_large_fpn-fb6a3cc7.pth",
}
def fasterrcnn_resnet50_fpn(
pretrained=False, progress=True, num_classes=91, pretrained_backbone=True, trainable_backbone_layers=None, **kwargs
):
"""
Constructs a Faster R-CNN model with a ResNet-50-FPN backbone.
Reference: `"Faster R-CNN: Towards Real-Time Object Detection with
Region Proposal Networks" <https://arxiv.org/abs/1506.01497>`_.
The input to the model is expected to be a list of tensors, each of shape ``[C, H, W]``, one for each
image, and should be in ``0-1`` range. Different images can have different sizes.
The behavior of the model changes depending if it is in training or evaluation mode.
During training, the model expects both the input tensors, as well as a targets (list of dictionary),
containing:
- boxes (``FloatTensor[N, 4]``): the ground-truth boxes in ``[x1, y1, x2, y2]`` format, with
``0 <= x1 < x2 <= W`` and ``0 <= y1 < y2 <= H``.
- labels (``Int64Tensor[N]``): the class label for each ground-truth box
The model returns a ``Dict[Tensor]`` during training, containing the classification and regression
losses for both the RPN and the R-CNN.
During inference, the model requires only the input tensors, and returns the post-processed
predictions as a ``List[Dict[Tensor]]``, one for each input image. The fields of the ``Dict`` are as
follows, where ``N`` is the number of detections:
- boxes (``FloatTensor[N, 4]``): the predicted boxes in ``[x1, y1, x2, y2]`` format, with
``0 <= x1 < x2 <= W`` and ``0 <= y1 < y2 <= H``.
- labels (``Int64Tensor[N]``): the predicted labels for each detection
- scores (``Tensor[N]``): the scores of each detection
For more details on the output, you may refer to :ref:`instance_seg_output`.
Faster R-CNN is exportable to ONNX for a fixed batch size with inputs images of fixed size.
Example::
>>> model = torchvision.models.detection.fasterrcnn_resnet50_fpn(pretrained=True)
>>> # For training
>>> images, boxes = torch.rand(4, 3, 600, 1200), torch.rand(4, 11, 4)
>>> boxes[:, :, 2:4] = boxes[:, :, 0:2] + boxes[:, :, 2:4]
>>> labels = torch.randint(1, 91, (4, 11))
>>> images = list(image for image in images)
>>> targets = []
>>> for i in range(len(images)):
>>> d = {}
>>> d['boxes'] = boxes[i]
>>> d['labels'] = labels[i]
>>> targets.append(d)
>>> output = model(images, targets)
>>> # For inference
>>> model.eval()
>>> x = [torch.rand(3, 300, 400), torch.rand(3, 500, 400)]
>>> predictions = model(x)
>>>
>>> # optionally, if you want to export the model to ONNX:
>>> torch.onnx.export(model, x, "faster_rcnn.onnx", opset_version = 11)
Args:
pretrained (bool): If True, returns a model pre-trained on COCO train2017
progress (bool): If True, displays a progress bar of the download to stderr
num_classes (int): number of output classes of the model (including the background)
pretrained_backbone (bool): If True, returns a model with backbone pre-trained on Imagenet
trainable_backbone_layers (int): number of trainable (not frozen) resnet layers starting from final block.
Valid values are between 0 and 5, with 5 meaning all backbone layers are trainable. If ``None`` is
passed (the default) this value is set to 3.
"""
is_trained = pretrained or pretrained_backbone
trainable_backbone_layers = _validate_trainable_layers(is_trained, trainable_backbone_layers, 5, 3)
norm_layer = misc_nn_ops.FrozenBatchNorm2d if is_trained else nn.BatchNorm2d
if pretrained:
# no need to download the backbone if pretrained is set
pretrained_backbone = False
backbone = resnet50(pretrained=pretrained_backbone, progress=progress, norm_layer=norm_layer)
backbone = _resnet_fpn_extractor(backbone, trainable_backbone_layers)
model = FasterRCNN(backbone, num_classes, **kwargs)
if pretrained:
state_dict = load_state_dict_from_url(model_urls["fasterrcnn_resnet50_fpn_coco"], progress=progress)
model.load_state_dict(state_dict)
overwrite_eps(model, 0.0)
return model
def _fasterrcnn_mobilenet_v3_large_fpn(
weights_name,
pretrained=False,
progress=True,
num_classes=91,
pretrained_backbone=True,
trainable_backbone_layers=None,
**kwargs,
):
is_trained = pretrained or pretrained_backbone
trainable_backbone_layers = _validate_trainable_layers(is_trained, trainable_backbone_layers, 6, 3)
norm_layer = misc_nn_ops.FrozenBatchNorm2d if is_trained else nn.BatchNorm2d
if pretrained:
pretrained_backbone = False
backbone = mobilenet_v3_large(pretrained=pretrained_backbone, progress=progress, norm_layer=norm_layer)
backbone = _mobilenet_extractor(backbone, True, trainable_backbone_layers)
anchor_sizes = (
(
32,
64,
128,
256,
512,
),
) * 3
aspect_ratios = ((0.5, 1.0, 2.0),) * len(anchor_sizes)
model = FasterRCNN(
backbone, num_classes, rpn_anchor_generator=AnchorGenerator(anchor_sizes, aspect_ratios), **kwargs
)
if pretrained:
if model_urls.get(weights_name, None) is None:
raise ValueError(f"No checkpoint is available for model {weights_name}")
state_dict = load_state_dict_from_url(model_urls[weights_name], progress=progress)
model.load_state_dict(state_dict)
return model
def fasterrcnn_mobilenet_v3_large_320_fpn(
pretrained=False, progress=True, num_classes=91, pretrained_backbone=True, trainable_backbone_layers=None, **kwargs
):
"""
Constructs a low resolution Faster R-CNN model with a MobileNetV3-Large FPN backbone tunned for mobile use-cases.
It works similarly to Faster R-CNN with ResNet-50 FPN backbone. See
:func:`~torchvision.models.detection.fasterrcnn_resnet50_fpn` for more
details.
Example::
>>> model = torchvision.models.detection.fasterrcnn_mobilenet_v3_large_320_fpn(pretrained=True)
>>> model.eval()
>>> x = [torch.rand(3, 300, 400), torch.rand(3, 500, 400)]
>>> predictions = model(x)
Args:
pretrained (bool): If True, returns a model pre-trained on COCO train2017
progress (bool): If True, displays a progress bar of the download to stderr
num_classes (int): number of output classes of the model (including the background)
pretrained_backbone (bool): If True, returns a model with backbone pre-trained on Imagenet
trainable_backbone_layers (int): number of trainable (not frozen) resnet layers starting from final block.
Valid values are between 0 and 6, with 6 meaning all backbone layers are trainable. If ``None`` is
passed (the default) this value is set to 3.
"""
weights_name = "fasterrcnn_mobilenet_v3_large_320_fpn_coco"
defaults = {
"min_size": 320,
"max_size": 640,
"rpn_pre_nms_top_n_test": 150,
"rpn_post_nms_top_n_test": 150,
"rpn_score_thresh": 0.05,
}
kwargs = {**defaults, **kwargs}
return _fasterrcnn_mobilenet_v3_large_fpn(
weights_name,
pretrained=pretrained,
progress=progress,
num_classes=num_classes,
pretrained_backbone=pretrained_backbone,
trainable_backbone_layers=trainable_backbone_layers,
**kwargs,
)
def fasterrcnn_mobilenet_v3_large_fpn(
pretrained=False, progress=True, num_classes=91, pretrained_backbone=True, trainable_backbone_layers=None, **kwargs
):
"""
Constructs a high resolution Faster R-CNN model with a MobileNetV3-Large FPN backbone.
It works similarly to Faster R-CNN with ResNet-50 FPN backbone. See
:func:`~torchvision.models.detection.fasterrcnn_resnet50_fpn` for more
details.
Example::
>>> model = torchvision.models.detection.fasterrcnn_mobilenet_v3_large_fpn(pretrained=True)
>>> model.eval()
>>> x = [torch.rand(3, 300, 400), torch.rand(3, 500, 400)]
>>> predictions = model(x)
Args:
pretrained (bool): If True, returns a model pre-trained on COCO train2017
progress (bool): If True, displays a progress bar of the download to stderr
num_classes (int): number of output classes of the model (including the background)
pretrained_backbone (bool): If True, returns a model with backbone pre-trained on Imagenet
trainable_backbone_layers (int): number of trainable (not frozen) resnet layers starting from final block.
Valid values are between 0 and 6, with 6 meaning all backbone layers are trainable. If ``None`` is
passed (the default) this value is set to 3.
"""
weights_name = "fasterrcnn_mobilenet_v3_large_fpn_coco"
defaults = {
"rpn_score_thresh": 0.05,
}
kwargs = {**defaults, **kwargs}
return _fasterrcnn_mobilenet_v3_large_fpn(
weights_name,
pretrained=pretrained,
progress=progress,
num_classes=num_classes,
pretrained_backbone=pretrained_backbone,
trainable_backbone_layers=trainable_backbone_layers,
**kwargs,
)
| torchvision/models/detection/faster_rcnn.py | 23,446 | Standard classification + bounding box regression layers
for Fast R-CNN.
Args:
in_channels (int): number of input channels
num_classes (int): number of output classes (including background)
Implements Faster R-CNN.
The input to the model is expected to be a list of tensors, each of shape [C, H, W], one for each
image, and should be in 0-1 range. Different images can have different sizes.
The behavior of the model changes depending if it is in training or evaluation mode.
During training, the model expects both the input tensors, as well as a targets (list of dictionary),
containing:
- boxes (``FloatTensor[N, 4]``): the ground-truth boxes in ``[x1, y1, x2, y2]`` format, with
``0 <= x1 < x2 <= W`` and ``0 <= y1 < y2 <= H``.
- labels (Int64Tensor[N]): the class label for each ground-truth box
The model returns a Dict[Tensor] during training, containing the classification and regression
losses for both the RPN and the R-CNN.
During inference, the model requires only the input tensors, and returns the post-processed
predictions as a List[Dict[Tensor]], one for each input image. The fields of the Dict are as
follows:
- boxes (``FloatTensor[N, 4]``): the predicted boxes in ``[x1, y1, x2, y2]`` format, with
``0 <= x1 < x2 <= W`` and ``0 <= y1 < y2 <= H``.
- labels (Int64Tensor[N]): the predicted labels for each image
- scores (Tensor[N]): the scores or each prediction
Args:
backbone (nn.Module): the network used to compute the features for the model.
It should contain a out_channels attribute, which indicates the number of output
channels that each feature map has (and it should be the same for all feature maps).
The backbone should return a single Tensor or and OrderedDict[Tensor].
num_classes (int): number of output classes of the model (including the background).
If box_predictor is specified, num_classes should be None.
min_size (int): minimum size of the image to be rescaled before feeding it to the backbone
max_size (int): maximum size of the image to be rescaled before feeding it to the backbone
image_mean (Tuple[float, float, float]): mean values used for input normalization.
They are generally the mean values of the dataset on which the backbone has been trained
on
image_std (Tuple[float, float, float]): std values used for input normalization.
They are generally the std values of the dataset on which the backbone has been trained on
rpn_anchor_generator (AnchorGenerator): module that generates the anchors for a set of feature
maps.
rpn_head (nn.Module): module that computes the objectness and regression deltas from the RPN
rpn_pre_nms_top_n_train (int): number of proposals to keep before applying NMS during training
rpn_pre_nms_top_n_test (int): number of proposals to keep before applying NMS during testing
rpn_post_nms_top_n_train (int): number of proposals to keep after applying NMS during training
rpn_post_nms_top_n_test (int): number of proposals to keep after applying NMS during testing
rpn_nms_thresh (float): NMS threshold used for postprocessing the RPN proposals
rpn_fg_iou_thresh (float): minimum IoU between the anchor and the GT box so that they can be
considered as positive during training of the RPN.
rpn_bg_iou_thresh (float): maximum IoU between the anchor and the GT box so that they can be
considered as negative during training of the RPN.
rpn_batch_size_per_image (int): number of anchors that are sampled during training of the RPN
for computing the loss
rpn_positive_fraction (float): proportion of positive anchors in a mini-batch during training
of the RPN
rpn_score_thresh (float): during inference, only return proposals with a classification score
greater than rpn_score_thresh
box_roi_pool (MultiScaleRoIAlign): the module which crops and resizes the feature maps in
the locations indicated by the bounding boxes
box_head (nn.Module): module that takes the cropped feature maps as input
box_predictor (nn.Module): module that takes the output of box_head and returns the
classification logits and box regression deltas.
box_score_thresh (float): during inference, only return proposals with a classification score
greater than box_score_thresh
box_nms_thresh (float): NMS threshold for the prediction head. Used during inference
box_detections_per_img (int): maximum number of detections per image, for all classes.
box_fg_iou_thresh (float): minimum IoU between the proposals and the GT box so that they can be
considered as positive during training of the classification head
box_bg_iou_thresh (float): maximum IoU between the proposals and the GT box so that they can be
considered as negative during training of the classification head
box_batch_size_per_image (int): number of proposals that are sampled during training of the
classification head
box_positive_fraction (float): proportion of positive proposals in a mini-batch during training
of the classification head
bbox_reg_weights (Tuple[float, float, float, float]): weights for the encoding/decoding of the
bounding boxes
Example::
>>> import torch
>>> import torchvision
>>> from torchvision.models.detection import FasterRCNN
>>> from torchvision.models.detection.rpn import AnchorGenerator
>>> # load a pre-trained model for classification and return
>>> # only the features
>>> backbone = torchvision.models.mobilenet_v2(pretrained=True).features
>>> # FasterRCNN needs to know the number of
>>> # output channels in a backbone. For mobilenet_v2, it's 1280
>>> # so we need to add it here
>>> backbone.out_channels = 1280
>>>
>>> # let's make the RPN generate 5 x 3 anchors per spatial
>>> # location, with 5 different sizes and 3 different aspect
>>> # ratios. We have a Tuple[Tuple[int]] because each feature
>>> # map could potentially have different sizes and
>>> # aspect ratios
>>> anchor_generator = AnchorGenerator(sizes=((32, 64, 128, 256, 512),),
>>> aspect_ratios=((0.5, 1.0, 2.0),))
>>>
>>> # let's define what are the feature maps that we will
>>> # use to perform the region of interest cropping, as well as
>>> # the size of the crop after rescaling.
>>> # if your backbone returns a Tensor, featmap_names is expected to
>>> # be ['0']. More generally, the backbone should return an
>>> # OrderedDict[Tensor], and in featmap_names you can choose which
>>> # feature maps to use.
>>> roi_pooler = torchvision.ops.MultiScaleRoIAlign(featmap_names=['0'],
>>> output_size=7,
>>> sampling_ratio=2)
>>>
>>> # put the pieces together inside a FasterRCNN model
>>> model = FasterRCNN(backbone,
>>> num_classes=2,
>>> rpn_anchor_generator=anchor_generator,
>>> box_roi_pool=roi_pooler)
>>> model.eval()
>>> x = [torch.rand(3, 300, 400), torch.rand(3, 500, 400)]
>>> predictions = model(x)
Standard heads for FPN-based models
Args:
in_channels (int): number of input channels
representation_size (int): size of the intermediate representation
Constructs a low resolution Faster R-CNN model with a MobileNetV3-Large FPN backbone tunned for mobile use-cases.
It works similarly to Faster R-CNN with ResNet-50 FPN backbone. See
:func:`~torchvision.models.detection.fasterrcnn_resnet50_fpn` for more
details.
Example::
>>> model = torchvision.models.detection.fasterrcnn_mobilenet_v3_large_320_fpn(pretrained=True)
>>> model.eval()
>>> x = [torch.rand(3, 300, 400), torch.rand(3, 500, 400)]
>>> predictions = model(x)
Args:
pretrained (bool): If True, returns a model pre-trained on COCO train2017
progress (bool): If True, displays a progress bar of the download to stderr
num_classes (int): number of output classes of the model (including the background)
pretrained_backbone (bool): If True, returns a model with backbone pre-trained on Imagenet
trainable_backbone_layers (int): number of trainable (not frozen) resnet layers starting from final block.
Valid values are between 0 and 6, with 6 meaning all backbone layers are trainable. If ``None`` is
passed (the default) this value is set to 3.
Constructs a high resolution Faster R-CNN model with a MobileNetV3-Large FPN backbone.
It works similarly to Faster R-CNN with ResNet-50 FPN backbone. See
:func:`~torchvision.models.detection.fasterrcnn_resnet50_fpn` for more
details.
Example::
>>> model = torchvision.models.detection.fasterrcnn_mobilenet_v3_large_fpn(pretrained=True)
>>> model.eval()
>>> x = [torch.rand(3, 300, 400), torch.rand(3, 500, 400)]
>>> predictions = model(x)
Args:
pretrained (bool): If True, returns a model pre-trained on COCO train2017
progress (bool): If True, displays a progress bar of the download to stderr
num_classes (int): number of output classes of the model (including the background)
pretrained_backbone (bool): If True, returns a model with backbone pre-trained on Imagenet
trainable_backbone_layers (int): number of trainable (not frozen) resnet layers starting from final block.
Valid values are between 0 and 6, with 6 meaning all backbone layers are trainable. If ``None`` is
passed (the default) this value is set to 3.
Constructs a Faster R-CNN model with a ResNet-50-FPN backbone.
Reference: `"Faster R-CNN: Towards Real-Time Object Detection with
Region Proposal Networks" <https://arxiv.org/abs/1506.01497>`_.
The input to the model is expected to be a list of tensors, each of shape ``[C, H, W]``, one for each
image, and should be in ``0-1`` range. Different images can have different sizes.
The behavior of the model changes depending if it is in training or evaluation mode.
During training, the model expects both the input tensors, as well as a targets (list of dictionary),
containing:
- boxes (``FloatTensor[N, 4]``): the ground-truth boxes in ``[x1, y1, x2, y2]`` format, with
``0 <= x1 < x2 <= W`` and ``0 <= y1 < y2 <= H``.
- labels (``Int64Tensor[N]``): the class label for each ground-truth box
The model returns a ``Dict[Tensor]`` during training, containing the classification and regression
losses for both the RPN and the R-CNN.
During inference, the model requires only the input tensors, and returns the post-processed
predictions as a ``List[Dict[Tensor]]``, one for each input image. The fields of the ``Dict`` are as
follows, where ``N`` is the number of detections:
- boxes (``FloatTensor[N, 4]``): the predicted boxes in ``[x1, y1, x2, y2]`` format, with
``0 <= x1 < x2 <= W`` and ``0 <= y1 < y2 <= H``.
- labels (``Int64Tensor[N]``): the predicted labels for each detection
- scores (``Tensor[N]``): the scores of each detection
For more details on the output, you may refer to :ref:`instance_seg_output`.
Faster R-CNN is exportable to ONNX for a fixed batch size with inputs images of fixed size.
Example::
>>> model = torchvision.models.detection.fasterrcnn_resnet50_fpn(pretrained=True)
>>> # For training
>>> images, boxes = torch.rand(4, 3, 600, 1200), torch.rand(4, 11, 4)
>>> boxes[:, :, 2:4] = boxes[:, :, 0:2] + boxes[:, :, 2:4]
>>> labels = torch.randint(1, 91, (4, 11))
>>> images = list(image for image in images)
>>> targets = []
>>> for i in range(len(images)):
>>> d = {}
>>> d['boxes'] = boxes[i]
>>> d['labels'] = labels[i]
>>> targets.append(d)
>>> output = model(images, targets)
>>> # For inference
>>> model.eval()
>>> x = [torch.rand(3, 300, 400), torch.rand(3, 500, 400)]
>>> predictions = model(x)
>>>
>>> # optionally, if you want to export the model to ONNX:
>>> torch.onnx.export(model, x, "faster_rcnn.onnx", opset_version = 11)
Args:
pretrained (bool): If True, returns a model pre-trained on COCO train2017
progress (bool): If True, displays a progress bar of the download to stderr
num_classes (int): number of output classes of the model (including the background)
pretrained_backbone (bool): If True, returns a model with backbone pre-trained on Imagenet
trainable_backbone_layers (int): number of trainable (not frozen) resnet layers starting from final block.
Valid values are between 0 and 5, with 5 meaning all backbone layers are trainable. If ``None`` is
passed (the default) this value is set to 3.
transform parameters RPN parameters Box parameters Box no need to download the backbone if pretrained is set | 12,905 | en | 0.797593 |
# @Author: Pieter Blok
# @Date: 2021-03-25 15:33:17
# @Last Modified by: Pieter Blok
# @Last Modified time: 2021-03-25 15:36:30
from .uncertainty import * | active_learning/heuristics/__init__.py | 159 | @Author: Pieter Blok @Date: 2021-03-25 15:33:17 @Last Modified by: Pieter Blok @Last Modified time: 2021-03-25 15:36:30 | 123 | en | 0.349088 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.