input stringlengths 2.65k 237k | output stringclasses 1
value |
|---|---|
ParameterMetadataResponse. Access the value via the '{suggest}' property getter instead.")
def __getitem__(self, key: str) -> Any:
ParameterMetadataResponse.__key_warning(key)
return super().__getitem__(key)
def get(self, key: str, default = None) -> Any:
ParameterMetadataResponse.__key_warning(key)
return super().get(key, default)
def __init__(__self__, *,
custom_metadata: Mapping[str, str],
help_text: str,
is_optional: bool,
label: str,
name: str,
param_type: str,
regexes: Sequence[str]):
"""
Metadata for a specific parameter.
:param Mapping[str, str] custom_metadata: Optional. Additional metadata for describing this parameter.
:param str help_text: The help text to display for the parameter.
:param bool is_optional: Optional. Whether the parameter is optional. Defaults to false.
:param str label: The label to display for the parameter.
:param str name: The name of the parameter.
:param str param_type: Optional. The type of the parameter. Used for selecting input picker.
:param Sequence[str] regexes: Optional. Regexes that the parameter must match.
"""
pulumi.set(__self__, "custom_metadata", custom_metadata)
pulumi.set(__self__, "help_text", help_text)
pulumi.set(__self__, "is_optional", is_optional)
pulumi.set(__self__, "label", label)
pulumi.set(__self__, "name", name)
pulumi.set(__self__, "param_type", param_type)
pulumi.set(__self__, "regexes", regexes)
@property
@pulumi.getter(name="customMetadata")
def custom_metadata(self) -> Mapping[str, str]:
"""
Optional. Additional metadata for describing this parameter.
"""
return pulumi.get(self, "custom_metadata")
@property
@pulumi.getter(name="helpText")
def help_text(self) -> str:
"""
The help text to display for the parameter.
"""
return pulumi.get(self, "help_text")
@property
@pulumi.getter(name="isOptional")
def is_optional(self) -> bool:
"""
Optional. Whether the parameter is optional. Defaults to false.
"""
return pulumi.get(self, "is_optional")
@property
@pulumi.getter
def label(self) -> str:
"""
The label to display for the parameter.
"""
return pulumi.get(self, "label")
@property
@pulumi.getter
def name(self) -> str:
"""
The name of the parameter.
"""
return pulumi.get(self, "name")
@property
@pulumi.getter(name="paramType")
def param_type(self) -> str:
"""
Optional. The type of the parameter. Used for selecting input picker.
"""
return pulumi.get(self, "param_type")
@property
@pulumi.getter
def regexes(self) -> Sequence[str]:
"""
Optional. Regexes that the parameter must match.
"""
return pulumi.get(self, "regexes")
@pulumi.output_type
class PipelineDescriptionResponse(dict):
"""
A descriptive representation of submitted pipeline as well as the executed form. This data is provided by the Dataflow service for ease of visualizing the pipeline and interpreting Dataflow provided metrics.
"""
@staticmethod
def __key_warning(key: str):
suggest = None
if key == "displayData":
suggest = "display_data"
elif key == "executionPipelineStage":
suggest = "execution_pipeline_stage"
elif key == "originalPipelineTransform":
suggest = "original_pipeline_transform"
if suggest:
pulumi.log.warn(f"Key '{key}' not found in PipelineDescriptionResponse. Access the value via the '{suggest}' property getter instead.")
def __getitem__(self, key: str) -> Any:
PipelineDescriptionResponse.__key_warning(key)
return super().__getitem__(key)
def get(self, key: str, default = None) -> Any:
PipelineDescriptionResponse.__key_warning(key)
return super().get(key, default)
def __init__(__self__, *,
display_data: Sequence['outputs.DisplayDataResponse'],
execution_pipeline_stage: Sequence['outputs.ExecutionStageSummaryResponse'],
original_pipeline_transform: Sequence['outputs.TransformSummaryResponse']):
"""
A descriptive representation of submitted pipeline as well as the executed form. This data is provided by the Dataflow service for ease of visualizing the pipeline and interpreting Dataflow provided metrics.
:param Sequence['DisplayDataResponse'] display_data: Pipeline level display data.
:param Sequence['ExecutionStageSummaryResponse'] execution_pipeline_stage: Description of each stage of execution of the pipeline.
:param Sequence['TransformSummaryResponse'] original_pipeline_transform: Description of each transform in the pipeline and collections between them.
"""
pulumi.set(__self__, "display_data", display_data)
pulumi.set(__self__, "execution_pipeline_stage", execution_pipeline_stage)
pulumi.set(__self__, "original_pipeline_transform", original_pipeline_transform)
@property
@pulumi.getter(name="displayData")
def display_data(self) -> Sequence['outputs.DisplayDataResponse']:
"""
Pipeline level display data.
"""
return pulumi.get(self, "display_data")
@property
@pulumi.getter(name="executionPipelineStage")
def execution_pipeline_stage(self) -> Sequence['outputs.ExecutionStageSummaryResponse']:
"""
Description of each stage of execution of the pipeline.
"""
return pulumi.get(self, "execution_pipeline_stage")
@property
@pulumi.getter(name="originalPipelineTransform")
def original_pipeline_transform(self) -> Sequence['outputs.TransformSummaryResponse']:
"""
Description of each transform in the pipeline and collections between them.
"""
return pulumi.get(self, "original_pipeline_transform")
@pulumi.output_type
class PubSubIODetailsResponse(dict):
"""
Metadata for a Pub/Sub connector used by the job.
"""
def __init__(__self__, *,
subscription: str,
topic: str):
"""
Metadata for a Pub/Sub connector used by the job.
:param str subscription: Subscription used in the connection.
:param str topic: Topic accessed in the connection.
"""
pulumi.set(__self__, "subscription", subscription)
pulumi.set(__self__, "topic", topic)
@property
@pulumi.getter
def subscription(self) -> str:
"""
Subscription used in the connection.
"""
return pulumi.get(self, "subscription")
@property
@pulumi.getter
def topic(self) -> str:
"""
Topic accessed in the connection.
"""
return pulumi.get(self, "topic")
@pulumi.output_type
class RuntimeMetadataResponse(dict):
"""
RuntimeMetadata describing a runtime environment.
"""
@staticmethod
def __key_warning(key: str):
suggest = None
if key == "sdkInfo":
suggest = "sdk_info"
if suggest:
pulumi.log.warn(f"Key '{key}' not found in RuntimeMetadataResponse. Access the value via the '{suggest}' property getter instead.")
def __getitem__(self, key: str) -> Any:
RuntimeMetadataResponse.__key_warning(key)
return super().__getitem__(key)
def get(self, key: str, default = None) -> Any:
RuntimeMetadataResponse.__key_warning(key)
return super().get(key, default)
def __init__(__self__, *,
parameters: Sequence['outputs.ParameterMetadataResponse'],
sdk_info: 'outputs.SDKInfoResponse'):
"""
RuntimeMetadata describing a runtime environment.
:param Sequence['ParameterMetadataResponse'] parameters: The parameters for the template.
:param 'SDKInfoResponse' sdk_info: SDK Info for the template.
"""
pulumi.set(__self__, "parameters", parameters)
pulumi.set(__self__, "sdk_info", sdk_info)
@property
@pulumi.getter
def parameters(self) -> Sequence['outputs.ParameterMetadataResponse']:
"""
The parameters for the template.
"""
return pulumi.get(self, "parameters")
@property
@pulumi.getter(name="sdkInfo")
def sdk_info(self) -> 'outputs.SDKInfoResponse':
"""
SDK Info for the template.
"""
return pulumi.get(self, "sdk_info")
@pulumi.output_type
class SDKInfoResponse(dict):
"""
SDK Information.
"""
def __init__(__self__, *,
language: str,
version: str):
"""
SDK Information.
:param str language: The SDK Language.
:param str version: Optional. The SDK version.
"""
pulumi.set(__self__, "language", language)
pulumi.set(__self__, "version", version)
@property
@pulumi.getter
def language(self) -> str:
"""
The SDK Language.
"""
return pulumi.get(self, "language")
@property
@pulumi.getter
def version(self) -> str:
"""
Optional. The SDK version.
"""
return pulumi.get(self, "version")
@pulumi.output_type
class SdkHarnessContainerImageResponse(dict):
"""
Defines a SDK harness container for executing Dataflow pipelines.
"""
@staticmethod
def __key_warning(key: str):
suggest = None
if key == "containerImage":
suggest = "container_image"
elif key == "environmentId":
suggest = "environment_id"
elif key == "useSingleCorePerContainer":
suggest = "use_single_core_per_container"
if suggest:
pulumi.log.warn(f"Key '{key}' not found in SdkHarnessContainerImageResponse. Access the value via the '{suggest}' property getter instead.")
def __getitem__(self, key: str) -> Any:
SdkHarnessContainerImageResponse.__key_warning(key)
return super().__getitem__(key)
def get(self, key: str, default = None) -> Any:
SdkHarnessContainerImageResponse.__key_warning(key)
return super().get(key, default)
def __init__(__self__, *,
container_image: str,
environment_id: str,
use_single_core_per_container: bool):
"""
Defines a SDK harness container for executing Dataflow pipelines.
:param str container_image: A docker container image that resides in Google Container Registry.
:param str environment_id: Environment ID for the Beam runner API proto Environment that corresponds to the current SDK Harness.
:param bool use_single_core_per_container: If true, recommends the Dataflow service to use only one core per SDK container instance with this image. If false (or unset) recommends using more than one core per SDK container instance with this image for efficiency. Note that Dataflow service may choose to override this property if needed.
"""
pulumi.set(__self__, "container_image", container_image)
pulumi.set(__self__, "environment_id", environment_id)
pulumi.set(__self__, "use_single_core_per_container", use_single_core_per_container)
@property
@pulumi.getter(name="containerImage")
def container_image(self) -> str:
"""
A docker container image that resides in Google Container Registry.
"""
return pulumi.get(self, "container_image")
@property
@pulumi.getter(name="environmentId")
def environment_id(self) -> str:
"""
Environment ID for the Beam runner API proto Environment that corresponds to the current SDK Harness.
"""
return pulumi.get(self, "environment_id")
@property
@pulumi.getter(name="useSingleCorePerContainer")
def use_single_core_per_container(self) -> bool:
"""
If true, recommends the Dataflow service to use only one core per SDK container instance with this image. If false (or unset) recommends using more than one core per SDK container instance with this image for efficiency. Note that Dataflow service may choose to override this property if needed.
"""
return pulumi.get(self, "use_single_core_per_container")
@pulumi.output_type
class SdkVersionResponse(dict):
"""
The version of the SDK used to run the job.
"""
@staticmethod
def __key_warning(key: str):
suggest = None
if key == "sdkSupportStatus":
suggest = "sdk_support_status"
elif key == "versionDisplayName":
suggest = "version_display_name"
if suggest:
pulumi.log.warn(f"Key '{key}' not found in SdkVersionResponse. Access the value via the '{suggest}' property getter instead.")
def __getitem__(self, key: str) -> Any:
SdkVersionResponse.__key_warning(key)
return super().__getitem__(key)
def get(self, key: str, default = None) -> Any:
SdkVersionResponse.__key_warning(key)
return super().get(key, default)
def __init__(__self__, *,
sdk_support_status: str,
version: str,
version_display_name: str):
"""
The version of the SDK used to run the job.
:param str sdk_support_status: The support status for this SDK version.
:param str version: The version of the SDK used to run the job.
:param str version_display_name: A readable string describing the version of the SDK.
"""
pulumi.set(__self__, "sdk_support_status", sdk_support_status)
pulumi.set(__self__, "version", version)
pulumi.set(__self__, "version_display_name", version_display_name)
@property
@pulumi.getter(name="sdkSupportStatus")
def sdk_support_status(self) -> str:
"""
The support status for this SDK version.
"""
return pulumi.get(self, "sdk_support_status")
@property
@pulumi.getter
def version(self) -> str:
"""
The version of the SDK used to run the job.
"""
return | |
<filename>SCaReM/views_crud.py
from datetime import datetime, timedelta
import json
from copy import deepcopy
from django.http import HttpResponseRedirect
from django.contrib import messages
from django.shortcuts import render, get_object_or_404, redirect
import models
import settings
EASTER_EGG_KEY = 'easter'
LAST_CAMP_KEY = 'last_camp_id'
LAST_OWNER_KEY = 'last_owner'
EASTER_EGGS = {
"Dance!": "dance",
"Dutch Auction!": "dutchauction",
"Hayride!": "hayride",
"Kangaroo Court!": "kangaroocourt",
"Movie Night!": "movienight",
"Pool Party!": "poolparty",
"Scavenger Hunt!": "scavengerhunt",
"Olympics!": "olympics",
"King Ball!": "kingball",
}
def delete_reservation(request, reservation_id=None):
reservation = get_object_or_404(models.Reservation, pk=reservation_id)
# if this is a recurring reservation, make sure we are deleting the
# primary event
if (reservation.recurrence_id
and reservation.recurrence_id != reservation.id):
return HttpResponseRedirect('/reservation/delete/%s'
% reservation.recurrence_id)
if 'confirmed' in request.POST and request.POST['confirmed'] == 'true':
# they've confirmed. actually delete the reservation and go
# back to the index. if it's a recurrence, delete them all
if reservation.recurrence_id:
for recurrence in reservation.recurrences():
recurrence.delete()
reservation.delete()
messages.success(request,
"%s %s has been deleted"
% (reservation.camp.name, reservation.event))
return redirect(request.POST['return_url'])
# show the confirmation page before doing anything
messages.warning(request,
'Are you sure you want to delete this reservation?')
if reservation.recurrence_id:
messages.warning(request, 'This is a recurring reservation. '
'All events will be deleted.')
data = {
'reservation': reservation,
'return_url': '/'
}
if 'HTTP_REFERER' in request.META and request.META['HTTP_REFERER']:
data['return_url'] = request.META['HTTP_REFERER']
return render(request, 'reservations/delete.html', data)
def _assemble_reservation(request, form_values):
reservation = models.Reservation()
error = False
# put together the reservation object
if 'reservation_id' in request.POST and request.POST['reservation_id']:
reservation.id = int(request.POST['reservation_id'])
form_values['reservation_id'] = reservation.id
reservation.event = request.POST['event']
if not reservation.event:
messages.error(request, "You must specify an Event.")
error = True
form_values['event_value'] = reservation.event
reservation.owner = request.POST['owner']
if not reservation.owner:
messages.error(request, "You must specify an Owner.")
error = True
form_values['owner_value'] = reservation.owner
reservation.notes = request.POST['notes']
form_values['notes_value'] = reservation.notes
camp_id = request.POST['camp']
if not camp_id:
messages.error(request, "You must specify a Camp.")
error = True
else:
reservation.camp = get_object_or_404(models.Camp, pk=camp_id)
form_values['camp_value'] = reservation.camp.id
resource_ids = [int(x) for x in request.POST.getlist('resources')]
resources = [get_object_or_404(models.Resource, pk=resource_id)
for resource_id in resource_ids]
if not resources:
messages.error(request, "You must specify at least one Resource.")
error = True
form_values['resource_values'] = [resource.id for resource in resources]
start_date = request.POST['start_date']
if start_date:
try:
datetime.strptime(start_date, settings.DATE_FORMAT)
form_values['start_date_value'] = start_date
except:
messages.error(request,
"Invalid Start Date. Should be formatted as MM/DD/YYYY.")
error = True
start_date = None
else:
messages.error(request, "You must specify a Start Date.")
error = True
end_date = request.POST['end_date']
if end_date:
try:
datetime.strptime(end_date, settings.DATE_FORMAT)
form_values['end_date_value'] = end_date
except:
messages.error(request,
"Invalid End Date. Should be formatted as MM/DD/YYYY.")
error = True
end_date = None
else:
messages.error(request, "You must specify a End Date.")
error = True
start_time = request.POST['start_time']
if start_time:
try:
datetime.strptime(start_time, settings.TIME_FORMAT)
form_values['start_time_value'] = start_time
except:
messages.error(request, "Invalid Start Time. "
"Should be formatted as HH:MM {am/pm}.")
error = True
start_time = None
else:
messages.error(request, "You must specify a Start Time.")
error = True
end_time = request.POST['end_time']
if end_time:
try:
datetime.strptime(end_time, settings.TIME_FORMAT)
form_values['end_time_value'] = end_time
except:
messages.error(request, "Invalid End Time. "
"Should be formatted as HH:MM {am/pm}.")
error = True
end_time = None
else:
messages.error(request, "You must specify a End Time.")
error = True
if start_date and start_time:
reservation.start_time = datetime.strptime(
"%s %s" % (start_date, start_time),
settings.DATETIME_FORMAT)
if end_date and end_time:
reservation.end_time = datetime.strptime(
"%s %s" % (end_date, end_time),
settings.DATETIME_FORMAT)
if (reservation.start_time and reservation.end_time and
reservation.end_time <= reservation.start_time):
messages.error(request, "Reservation must end after it starts.")
error = True
# don't allow reservations less than a week in the future
# (which includes reservations in the past)
if reservation.start_time and reservation.is_frozen():
messages.error(request, "Reservations must be at least one "
"week in the future.")
error = True
# look for conflicts
if start_date and start_time and end_date and end_time:
if _check_for_conflicts(reservation, resources, request):
error = True
return (reservation, resources, error)
def _check_for_conflicts(reservation, resources, request,
ignore_recurrence=None):
conflicts = reservation.check_for_conflicts(resources, ignore_recurrence)
resource_ids = [resource.id for resource in resources]
if not conflicts:
return False
for conflict in conflicts:
message = ("Reservation conflicts with '%s' event for %s."
% (conflict.event, conflict.camp.name))
# figure out which resources conflict
used_resources = [resource for resource in conflict.resources.all()
if resource.id in resource_ids
and not resource.allow_conflicts]
start_time = conflict.start_time.strftime(settings.TIME_FORMAT)
start_date = conflict.start_time.strftime(settings.DATE_FORMAT)
end_time = conflict.end_time.strftime(settings.TIME_FORMAT)
end_date = conflict.end_time.strftime(settings.DATE_FORMAT)
if start_date == end_date:
message += " They are using %s from %s to %s on %s." % (
", ".join([resource.name for resource in used_resources]),
start_time, end_time, start_date)
else:
message += " They are using %s from %s on %s to %s on %s." % (
", ".join([resource.name for resource in used_resources]),
start_time, start_date, end_time, end_date)
messages.error(request, message)
return True
def _assemble_recurrences(request, form_values, reservation, resources):
error = False
recurrences_to_save = []
# if there are existing recurrences, remove them. we'll recreate them
# as needed. this is just easier.
recurrences_to_remove = reservation.recurrences()
reservation.recurrence_id = None
# if this isn't a recurrence, we have nothing to add. if it used
# to be a recurrence, clear out the recurrence_id
if 'repeat_until' not in request.POST or not request.POST['repeat_until']:
if reservation.recurrence_id:
reservation.recurrence_id = None
return (recurrences_to_save, recurrences_to_remove, error)
# parse out the end date for the recurrence
end_time = None
end_date = None
try:
end_date = datetime.strptime(request.POST['repeat_until'],
settings.DATE_FORMAT)
form_values['repeat_until_value'] = request.POST['repeat_until']
end_time = end_date + timedelta(hours=23, minutes=59)
except:
messages.error(request, "Invalid Repeat Daily Until. "
"Should be formatted as MM/DD/YYYY.")
error = True
return (recurrences_to_save, recurrences_to_remove, error)
# end date must be at least 1 day and no more than 90 days after start
num_days = (end_time - reservation.start_time).days
if num_days < 1:
messages.error(request, "Repeat Daily Until must be later than Date.")
error = True
return (recurrences_to_save, recurrences_to_remove, error)
if num_days > 90:
messages.error(request, "Reservations cannot repeat more than 90 days.")
error = True
return (recurrences_to_save, recurrences_to_remove, error)
# assemble the recurrences
next_start = reservation.start_time + timedelta(days=1)
next_end = reservation.end_time + timedelta(days=1)
while next_start < end_time:
# assemble the recurrence
recurrence = deepcopy(reservation)
recurrence.id = None
recurrence.start_time = next_start
recurrence.end_time = next_end
# add it to the list
recurrences_to_save.append(recurrence)
# check for conflicts on this one
ignore_recurrence = None
if 'reservation_id' in form_values:
ignore_recurrence = form_values['reservation_id']
if _check_for_conflicts(recurrence, resources, request,
ignore_recurrence):
error = True
# incrememt for the next one
next_start = next_start + timedelta(days=1)
next_end = next_end + timedelta(days=1)
return (recurrences_to_save, recurrences_to_remove, error)
def _save_reservation(request, form_values):
try:
(reservation, resources, reservation_error) = _assemble_reservation(
request, form_values)
(save_recurrences, remove_recurrences, recurrence_error) = \
_assemble_recurrences(
request, form_values, reservation, resources)
# check for errors before we save
if reservation_error or recurrence_error:
return render(request, 'reservations/addedit.html', form_values)
# save the reservation
is_new = not reservation.id
# if it's a new reservation, check for an easter egg
if is_new and reservation.event in EASTER_EGGS:
request.session[EASTER_EGG_KEY] = EASTER_EGGS[reservation.event]
elif EASTER_EGG_KEY in request.session:
del request.session[EASTER_EGG_KEY]
# save the basic reservation
reservation.save()
# attach the resources and save again
reservation.resources = resources
reservation.save(False)
# if there are recurrences to remove, do that
if remove_recurrences:
for recurrence in remove_recurrences:
recurrence.delete()
# if there are recurrences to add, do a bunch more saving
if save_recurrences:
reservation.recurrence_id = reservation.id
reservation.save()
for recurrence in save_recurrences:
recurrence.recurrence_id = reservation.id
recurrence.save()
recurrence.resources = resources
recurrence.save()
messages.success(request, "%s %s has been %s"
% (reservation.camp.name, reservation.event,
"created" if is_new else "updated"))
# remember this users camp and owner name
request.session[LAST_CAMP_KEY] = reservation.camp.id
request.session[LAST_OWNER_KEY] = reservation.owner
if 'another' in request.POST:
return HttpResponseRedirect('/reservation/create')
return HttpResponseRedirect(request.POST['return_url'])
except Exception as e:
messages.error(request, e.message or e.args[1])
return render(request, 'reservations/addedit.html', form_values)
def _populate_existing_reservation(reservation_id, request, form_values):
# editing an existing reservation. load it from the database
# and fill in form fields
reservation = get_object_or_404(models.Reservation, pk=reservation_id)
# if this is a recurring reservation, make sure we are editing the
# primary event
if (reservation.recurrence_id
and reservation.recurrence_id != reservation.id):
return HttpResponseRedirect('/reservation/edit/%s'
% reservation.recurrence_id)
if reservation.recurrence_id:
messages.warning(request, 'This is a recurring reservation. '
'Any changes will apply to all events.')
last_recurrence = reservation.recurrences().last()
form_values['repeat_until_value'] = last_recurrence.start_time.strftime(
settings.DATE_FORMAT)
form_values['event_value'] = reservation.event
form_values['owner_value'] = reservation.owner
form_values['notes_value'] = reservation.notes
form_values['camp_value'] = reservation.camp.id
form_values['resource_values'] = [
resource.id for resource in reservation.resources.all()]
form_values['date_value'] = reservation.start_time.strftime(
settings.DATE_FORMAT)
form_values['start_time_value'] = reservation.start_time.strftime(
settings.TIME_FORMAT)
form_values['end_time_value'] = reservation.end_time.strftime(
settings.TIME_FORMAT)
form_values['reservation_id'] = reservation_id
return render(request, 'reservations/addedit.html', form_values)
def _populate_blank_reservation(request, form_values):
# if we are starting a fresh reservation, prefill | |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
################################################################################
# import numpy as np
import platform
import os
from UDFManager import UDFManager
##########################################
# UDF の作成
##########################################
class SetUpUDF:
def __init__(self, basic_cond, sim_cond, target_dir):
#
self.ver_cognac = basic_cond[0]
self.blank_udf = basic_cond[1]
self.base_udf = basic_cond[2]
self.core = ' -n ' + str(basic_cond[3])
#
self.sim_type = sim_cond[0]
self.multi_init = sim_cond[1]
self.target_density = sim_cond[2]
self.nv = sim_cond[3]
self.expand = sim_cond[4]
self.step_press = sim_cond[5]
self.rfc = sim_cond[6]
self.equilib_repeat = sim_cond[7]
self.equilib_time = sim_cond[8]
#
self.target_dir = target_dir
self.f_eval_py = 'evaluate_all.py'
# Cognac用の名称設定
self.nw_name = "Network"
self.atom_name = ["JP_A", "End_A", "Strand_A", "Side_A", "Solvent"]
self.bond_name = ["bond_JP-Chn", "bond_Strand", "bond_Side"]
self.angle_name = ["angle_AAA"]
self.site_name = ["site_JP", "site_End", "site_Strand", "site_Solvent"]
self.pair_name = ["site_JP-site_JP", "site_Strand-site_JP", "site_Strand-site_Strand",
"site_JP-site_End", "site_Strand-site_End", "site_End-site_End",
"site_Solvent-site_Solvent", "site_Solvent-site_JP", "site_Solvent-site_End",
"site_Solvent-site_Strand"]
self.site_pair_name = [
["site_JP", "site_JP"],
["site_Strand", "site_JP"],
["site_Strand", "site_Strand"],
["site_JP", "site_End"],
["site_Strand", "site_End"],
["site_End", "site_End"],
["site_Solvent", "site_Solvent"],
["site_Solvent", "site_JP"],
["site_Solvent", "site_End"],
["site_Solvent", "site_Strand"],
]
####################################
# UDFファイルを設定し、バッチ処理を作成
def setup_udf(self):
if platform.system() == "Windows":
batch = ""
elif platform.system() == "Linux":
batch = "#!/bin/bash\n"
###############
# sim_typeに応じて計算条件を選択
if self.sim_type == "homo_KG":
print("making homo KG")
batch = self.homo_kg(batch)
# 評価用のパイソンスクリプトを作成
self.evaluate_setup("chain")
elif self.sim_type == "Entangled" or self.sim_type == "Multi_entangled" or self.sim_type == "Gel_entangled" or self.sim_type == "Gel_concd_entangled":
batch = self.kg_calc(batch)
# 評価用のパイソンスクリプトを作成
self.evaluate_setup("strand")
elif self.sim_type == "NPT" or self.sim_type == "Multi" or self.sim_type == "Gel" or self.sim_type == "Gel_concd":
batch = self.npt_calc(batch)
# 評価用のパイソンスクリプトを作成
self.evaluate_setup("strand")
# elif self.sim_type == "Gel" or self.sim_type == "Gel_concd":
# batch = self.npt_gel(batch)
# # 評価用のパイソンスクリプトを作成
# self.evaluate_setup("strand")
#####################
# バッチファイルを作成
f_batch = os.path.join(self.target_dir, '_Calc_all.bat')
with open(f_batch,'w') as f:
# f.write(batch_all)
f.write(batch)
if platform.system() == "Linux":
os.chmod(f_batch, 0o777)
return
# 評価用のスクリプトを記述したファイルを作成
def evaluate_setup(self, target):
script = '#!/usr/bin/env python \n# -*- coding: utf-8 -*-\n'
script += '################################\n'
script += 'import os \nimport sys \n'
# if target == "chain":
script += 'import EvaluateChain as ec\n'
script += '################################\n'
# script += 'ec = EvaluateChain.EvaluateAll()\n'
script += 'ec.evaluate_all()\n\n'
# elif target == "strand":
# script += 'from evaluation import EvaluateStrand\n'
# script += '################################\n'
# script += 'EvaluateStrand.evaluate_all()\n\n'
#
f_script = os.path.join(self.target_dir, self.f_eval_py)
with open(f_script, 'w') as f:
f.write(script)
return
#####################################################################################
# ターミナルのタイトルを設定
def make_title(self, batch, title):
if platform.system() == "Windows":
batch += "title " + title + "\n"
elif platform.system() == "Linux":
batch += r'echo -ne "\033]0; ' + title + ' \007"' + '\n'
return batch
# ファイル名の処理
def make_step(self, time, fn_ext, batch, f_eval):
present_udf = fn_ext[0] + self.target_dir + fn_ext[1]
out_udf = present_udf.replace("uin", "out")
batch += self.ver_cognac + ' -I ' + present_udf + ' -O ' + out_udf + self.core + ' \n'
if f_eval:
batch += 'python ' + self.f_eval_py + ' ' + out_udf + '\n'
read_udf = out_udf
return present_udf, read_udf, batch
######################
# 各種バッチ条件を設定
######################
######################################################################
# ホモポリマーのKG鎖の計算
def homo_kg(self, batch):
# Force Capped LJ によりステップワイズに初期化
r = 0.9558*2**(1/6)
batch = self.make_title(batch, "Calculating-Init")
fn_ext = ['Init_', '_uin.udf']
time = [0.001, 1000000, 10000]
f_eval = 1
present_udf, read_udf, batch = self.make_step(time, fn_ext, batch, f_eval)
self.step_nonbond_setup(self.base_udf, 'random', present_udf, time, r)
pre = read_udf
template = present_udf
#
for r in [1.0, 0.9, 0.8]:
# 平衡化
batch = self.make_title(batch, "Calculating-Pre_" + str(round(r, 3)).replace('.', '_'))
fn_ext = ['Pre_rfc_' + str(round(r, 3)).replace('.', '_') + "_", "_uin.udf"]
time = [0.01, 5000000, 50000]
f_eval = 1
present_udf, read_udf, batch = self.make_step(time, fn_ext, batch, f_eval)
self.step_nonbond_setup(template, pre, present_udf, time, r)
pre = read_udf
template = present_udf
# KG 鎖に設定
time = [0.01, 10000000, 100000]
batch = self.make_title(batch, "Calculating-KG")
fn_ext = ['KG_', "_uin.udf"]
f_eval = 1
present_udf, read_udf, batch = self.make_step(time, fn_ext, batch, f_eval)
self.kg_setup(template, pre, present_udf, time)
pre = read_udf
template = present_udf
# 平衡化計算
repeat = 4
time = [0.01, 2000000, 5000]
for i in range(repeat):
# 平衡化
batch = self.make_title(batch, "Calculating-Eq_" + str(i))
fn_ext = ['Eq_' + str(i) + "_", "_uin.udf"]
f_eval = 1
present_udf, read_udf, batch = self.make_step(time, fn_ext, batch, f_eval)
self.eq_setup(template, pre, present_udf, time)
pre = read_udf
template = present_udf
# グリーン久保
repeat = 5
time = [0.01, 20000000, 100000]
for i in range(repeat):
# 平衡化
batch = self.make_title(batch, "Calculating-GK_" + str(i))
fn_ext = ['GK_' + str(i) + "_", "_uin.udf"]
f_eval = 1
present_udf, read_udf, batch = self.make_step(time, fn_ext, batch, f_eval)
self.greenkubo_setup(template, pre, present_udf, time)
pre = read_udf
template = present_udf
return batch
######################################################################
# KG鎖の計算
def kg_calc(self, batch):
# Force Capped LJ によりステップワイズに初期化
r = 1.1
batch = self.make_title(batch, "Calculating-Init")
fn_ext = ['Init_', "_uin.udf"]
time = [0.001, 100000, 1000]
f_eval = 1
present_udf, read_udf, batch = self.make_step(time, fn_ext, batch, f_eval)
self.step_nonbond_setup(self.base_udf, '', present_udf, time, r)
pre = read_udf
template = present_udf
#
for r in [0.9558*2**(1/6), 1.0, 0.9, 0.8]:
# 平衡化
batch = self.make_title(batch, "Calculating-Pre_" + str(round(r, 3)).replace('.', '_'))
fn_ext = ['Pre_rfc_' + str(round(r, 3)).replace('.', '_') + "_", "_uin.udf"]
time = [0.01, 1000000, 10000]
f_eval = 1
present_udf, read_udf, batch = self.make_step(time, fn_ext, batch, f_eval)
self.step_nonbond_setup(template, pre, present_udf, time, r)
pre = read_udf
template = present_udf
# KG 鎖に設定
time = [0.01, 1000000, 10000]
batch = self.make_title(batch, "Calculating-KG")
fn_ext = ['KG_', "_uin.udf"]
f_eval = 1
present_udf, read_udf, batch = self.make_step(time, fn_ext, batch, f_eval)
self.kg_setup(template, pre, present_udf, time)
pre = read_udf
template = present_udf
# 平衡化計算
time = [0.01, 500000, 1000]
for i in [1,2]:
# 平衡化
batch = self.make_title(batch, "Calculating-Eq_" + str(i))
fn_ext = ['Eq_' + str(i) + "_", "_uin.udf"]
f_eval = 1
present_udf, read_udf, batch = self.make_step(time, fn_ext, batch, f_eval)
self.eq_setup(template, pre, present_udf, time)
pre = read_udf
template = present_udf
# グリーン久保
# repeat = 5
# time = [0.01, 20000000, 1000000]
# for i in range(repeat):
# # 平衡化
# batch = self.make_title(batch, "Calculating-GK_" + str(i))
# fn_ext = ['GK_' + str(i) + "_", "_uin.udf"]
# f_eval = 1
# present_udf, read_udf, batch = self.make_step(time, fn_ext, batch, f_eval)
# self.greenkubo_setup(template, pre, present_udf, time)
# pre = read_udf
# template = present_udf
return batch
###########################################
# NPT 条件で、設定密度まで圧縮
def npt_calc(self, batch):
# NPTの設定
pres = 0.1
batch = self.make_title(batch, "Calculating-Ini_NPT_" + str(pres).replace('.', '_'))
fn_ext = ['Init_pres_' + str(pres).replace('.', '_') + '_', "_uin.udf"]
time = [0.001, 20000, 200]
f_eval = 0
present_udf, read_udf, batch = self.make_step(time, fn_ext, batch, f_eval)
self.npt_setup(self.base_udf, '', present_udf, time, pres)
pre = read_udf
template = present_udf
# ステップワイズに圧力増加
for pres in self.step_press:
batch = self.make_title(batch, "Calculating-Ini_NPT_" + str(pres).replace('.', '_'))
fn_ext = ['Compress_pres_' + str(pres).replace('.', '_') + '_', "_uin.udf"]
time = [0.01, 100000, 1000]
f_eval = 1
present_udf, read_udf, batch = self.make_step(time, fn_ext, batch, f_eval)
self.npt_setup(template, pre, present_udf, time, pres)
pre = read_udf
template = present_udf
# KG 鎖に設定
time = [0.01, 100000, 1000]
batch = self.make_title(batch, "Calculating-KG")
fn_ext = ['Setup_', "_uin.udf"]
f_eval = 1
present_udf, read_udf, batch = self.make_step(time, fn_ext, batch, f_eval)
self.kg_setup(template, pre, present_udf, time)
pre = read_udf
template = present_udf
# 平衡化計算
time = [0.01, 200000, 1000]
for i in range(5):
# 平衡化
batch = self.make_title(batch, "Calculating-Eq_" + str(i))
fn_ext = ['Eq_' + str(i) + "_", "_uin.udf"]
f_eval = 1
present_udf, read_udf, batch = self.make_step(time, fn_ext, batch, f_eval)
self.eq_setup(template, pre, present_udf, time)
pre = read_udf
template = present_udf
# # グリーン久保
# repeat = 3
# time = [0.01, 2000000, 100000]
# for i in range(repeat):
# # 平衡化
# batch = self.make_title(batch, "Calculating-GK_" + str(i))
# fn_ext = ['GK_' + str(i) + "_", "_uin.udf"]
# f_eval = 1
# present_udf, read_udf, batch = self.make_step(time, fn_ext, batch, f_eval)
# self.greenkubo_setup(template, pre, present_udf, time)
# pre = read_udf
# template = present_udf
return batch
###########################################
# NPT 条件で、設定密度まで圧縮(ゲルの場合は圧縮をきつく)
# def npt_gel(self, batch):
# # NPTの設定
# pres = 0.1
# batch = self.make_title(batch, "Calculating-Ini_NPT_" + str(pres).replace('.', '_'))
# fn_ext = ['Init_pres_' + str(pres).replace('.', '_') + '_', "_uin.udf"]
# time = [0.001, 20000, 200]
# f_eval = 0
# present_udf, read_udf, batch = self.make_step(time, fn_ext, batch, f_eval)
# self.npt_setup(self.base_udf, '', present_udf, time, pres)
# pre = read_udf
# template = present_udf
# # ステップワイズに圧力増加
# for pres in self.step_press:
# batch = self.make_title(batch, "Calculating-Ini_NPT_" + str(pres).replace('.', '_'))
# fn_ext = ['Compress_pres_' + str(pres).replace('.', '_') + '_', "_uin.udf"]
# time = [0.01, 100000, 1000]
# f_eval = 1
# present_udf, read_udf, batch = self.make_step(time, fn_ext, batch, f_eval)
# self.npt_setup(template, pre, present_udf, time, pres)
# pre = read_udf
# template = present_udf
# # KG 鎖に設定
# time = [0.01, 100000, 1000]
# batch = self.make_title(batch, "Calculating-KG")
# fn_ext = ['Setup_', "_uin.udf"]
# f_eval = 1
# present_udf, read_udf, batch = self.make_step(time, fn_ext, batch, f_eval)
# self.kg_setup(template, pre, present_udf, time)
# pre = read_udf
# template = present_udf
# # 平衡化計算
# time = [0.01, 200000, 1000]
# for i in range(5):
# # 平衡化
# batch = self.make_title(batch, "Calculating-Eq_" + str(i))
# fn_ext = ['Eq_' + str(i) + "_", "_uin.udf"]
# f_eval = 1
# present_udf, read_udf, batch = self.make_step(time, fn_ext, batch, f_eval)
# self.eq_setup(template, pre, present_udf, time)
# pre = read_udf
# template = present_udf
# # グリーン久保
# repeat = 3
# time = [0.01, 2000000, 100000]
# for i in range(repeat):
# # 平衡化
# batch = self.make_title(batch, "Calculating-GK_" + str(i))
# fn_ext = ['GK_' + str(i) + "_", "_uin.udf"]
# f_eval = 1
# present_udf, read_udf, batch = self.make_step(time, fn_ext, batch, f_eval)
# self.greenkubo_setup(template, pre, present_udf, time)
# pre = read_udf
# template = present_udf
return batch
###############
# UDF 作成条件
###############
##############################################################################
# ユーザーポテンシャルにより、Force Capped LJ で、ステップワイズにノンボンドを増加
def step_nonbond_setup(self, template, read_udf, present_udf, time, r_fc):
u = UDFManager(os.path.join(self.target_dir, template))
# goto global data
u.jump(-1)
#--- Simulation_Conditions ---
# Dynamics_Conditions
p = 'Simulation_Conditions.Dynamics_Conditions.'
u.put(100000000., p + 'Max_Force')
u.put(time[0], p + 'Time.delta_T')
u.put(time[1], p + 'Time.Total_Steps')
u.put(time[2], p + 'Time.Output_Interval_Steps')
u.put(1.0, p + 'Temperature.Temperature')
u.put(0., p + 'Pressure_Stress.Pressure')
# Calc_Potential_Flags
p = 'Simulation_Conditions.Calc_Potential_Flags.'
u.put(1, p + 'Bond')
u.put(1, p + 'Angle')
if read_udf == 'random':
u.put(0, p + 'Non_Bonding_Interchain')
u.put(0, p + 'Non_Bonding_1_3')
u.put(0, p + 'Non_Bonding_1_4')
u.put(0, p + 'Non_Bonding_Intrachain')
else:
u.put(1, p + 'Non_Bonding_Interchain')
u.put(1, p + 'Non_Bonding_1_3')
u.put(1, p + 'Non_Bonding_1_4')
u.put(1, p + 'Non_Bonding_Intrachain')
#--- Initial_Structure ---
# Initial_Unit_Cell
p = 'Initial_Structure.Initial_Unit_Cell.'
u.put(0.85, p + 'Density')
u.put([0, 0, 0, 90.0, 90.0, 90.0], p + 'Cell_Size')
# Generate_Method
if read_udf == 'random':
# Set atoms
p = 'Initial_Structure.Generate_Method.'
u.put('Random', p + 'Method')
u.put(1, p + 'Random.Fix_Angle')
# Relaxation
p = 'Initial_Structure.Relaxation.'
u.put(1, p + 'Relaxation')
u.put('DYNAMICS', p + 'Method')
u.put(100, p + 'Max_Relax_Force')
u.put(100000, p + 'Max_Relax_Steps')
elif read_udf == '':
p = 'Initial_Structure.Generate_Method.'
u.put('Restart', p+'Method')
u.put(['', -1, 0, 0], p+'Restart')
# Relaxation
p = | |
<reponame>hlasimpk/SIMBAD
"""Module to interact with pyrvapi"""
__author__ = "<NAME> & <NAME>"
__date__ = "06 Oct 2017"
__version__ = "0.2"
import itertools
import json
import logging
import os
import pandas
import pyrvapi
import subprocess
import uuid
import urlparse
from simbad.util import reference_manager
from simbad.util import SIMBAD_PYRVAPI_SHAREDIR
logger = logging.getLogger(__name__)
class RvapiMetadata(object):
"""Storage container for metadata required by JsCoFe"""
def __init__(self):
self.results = []
@property
def n_results(self):
return len(self.results)
def add(self, e):
self.results.append(e)
def to_json(self):
self.__dict__.update({"nResults": self.n_results})
return json.dumps(self.__dict__)
class SimbadOutput(object):
"""Class to display the output of SIMBAD
Attributes
----------
webserver_uri : str
The uri if run on a webserver
display_gui : bool
Option to prevent results being displayed
logfile : str
Path to the log file
work_dir : str
Path to the work directory [default: None]
summary : bool
Option to display summary tab [default: False]
Examples
--------
>>> from simbad.util import pyrvapi_results
>>> gui = pyrvapi_results.SimbadOutput(<'rvapi_file'>, <'webserver_uri'>, <'display__gui'>,
... <'logfile'>, <'work_dir'>)
>>> gui.display_results(<'show_summary'>)
"""
_simbad_tooltips = {
"PDB_code":
"The 4 letter code representing the protein in the protein data bank",
"alt":
"Alternate Niggli Cell",
"a":
"Lattice parameter a",
"b":
"Lattice parameter b",
"c":
"Lattice parameter c",
"alpha":
"Lattice parameter alpha",
"beta":
"Lattice parameter beta",
"gamma":
"Lattice parameter gamma",
"length_penalty":
"The sum of the differences between lattice parameters a, b and c for the "
"model and the target",
"angle_penalty":
"The sum of the differences between lattice parameters alpha, beta and gamma "
"for the model and the target",
"total_penalty":
"The sum of the length penalty and the angle penalty",
"volume_difference":
"The difference in volume between the query and reference unit cells",
"probability_score":
"The probability that the structure corresponding to the total lattice "
"penalty will result in a solution",
"molrep_score":
"MOLREP score for the Molecular Replacement solution",
"molrep_tfscore":
"MOLREP translation function score for the Molecular Replacement solution",
"phaser_llg":
"PHASER Log-likelihood gain for the Molecular Replacement solution",
"phaser_tfz":
"PHASER Translation Function Z-score for the Molecular Replacement solution",
"phaser_rfz":
"PHASER Rotational Function Z-score for the Molecular Replacement solution",
"final_r_fact":
"R-fact score for REFMAC refinement of the Molecular Replacement solution",
"final_r_free":
"R-free score for REFMAC refinement of the Molecular Replacement solution",
"dano_peak_height":
"The Largest Anomalous peak found by ANODE",
"nearest_atom":
"The atom closest to the anomalous peak",
"z_score":
"Z-score calculated from all the anomalous peaks",
"ALPHA":
"Lattice parameter alpha",
"BETA":
"Lattice parameter beta",
"GAMMA":
"Lattice parameter gamma",
"CC_F":
"The correlation coefficient between the observed amplitudes for the crystal and the "
"calculated amplitudes for the model",
"RF_F":
"The classic R factor between the observed amplitudes for the crystal and the "
"calculated amplitudes for the model",
"CC_I":
"The correlation coefficient between the observed intensities for the crystal and the "
"sum of calculated intensities for all symmetry equivalents of the model",
"CC_P":
"The Patterson correlation coefficient between the crystal and the model Pattersons "
"evaluated within the defined sphere centred on the Patterson origin",
"Icp":
"",
"CC_F_Z_score":
"Z-score of CC_F peaks",
"CC_P_Z_score":
"Z-score of CC_P peaks",
"Number_of_rotation_searches_producing_peak":
"Number of rotations searches which produce each peak [out of 5]"
}
def __init__(self, rvapi_document, webserver_uri, display_gui, logfile, work_dir, ccp4i2_xml=None, tab_prefix=""):
self.rvapi_document = rvapi_document
self.webserver_uri = webserver_uri
self.display_gui = display_gui
self.logfile = logfile
self.work_dir = work_dir
self.ccp4i2 = bool(ccp4i2_xml)
self.tab_prefix = tab_prefix
self.jsrview_dir = None
self._webserver_start = None
self.log_tab_id = None
self.lattice_results_tab_id = None
self.lattice_df = None
self.contaminant_results_tab_id = None
self.contaminant_df = None
self.morda_db_results_tab_id = None
self.morda_db_df = None
self.summary_tab_id = None
self.summary_tab_results_sec_id = None
self.citation_tab_id = None
self.lattice_search_results_displayed = False
self.contaminant_results_displayed = False
self.morda_results_displayed = False
self.jscofe_mode = False
self.ccp4online_mode = False
self.rhs_tab_id = None
self.rvapi_meta = RvapiMetadata()
if self.display_gui or self.ccp4i2:
ccp4 = os.environ["CCP4"]
share_jsrview = os.path.join(ccp4, "share", "jsrview")
if self.rvapi_document:
pyrvapi.rvapi_restore_document2(rvapi_document)
self.rhs_tab_id = pyrvapi.rvapi_get_meta()
self.jscofe_mode = True
self.jsrview_dir = os.path.dirname(rvapi_document)
else:
self.jsrview_dir = os.path.join(work_dir, SIMBAD_PYRVAPI_SHAREDIR)
os.mkdir(self.jsrview_dir)
wintitle = "SIMBAD Results"
if ccp4i2_xml:
self.init_from_ccp4i2_xml(ccp4i2_xml, self.jsrview_dir, share_jsrview, wintitle)
else:
pyrvapi.rvapi_init_document("SIMBAD_results", self.jsrview_dir, wintitle, 1, 7, share_jsrview, None,
None, None, None)
self.rvapi_document = os.path.join(self.jsrview_dir, "index.html")
if webserver_uri:
self._webserver_start = len(self.jsrview_dir) - 7
self.ccp4online_mode = True
elif not ccp4i2_xml:
# We start our own browser
jsrview = os.path.join(ccp4, "libexec", "jsrview")
subprocess.Popen([jsrview, os.path.join(self.jsrview_dir, "index.html")])
pyrvapi.rvapi_add_header("SIMBAD Results")
if os.path.isfile(logfile) and not self.ccp4i2:
self.create_log_tab(logfile)
pyrvapi.rvapi_flush()
def init_from_ccp4i2_xml(self, ccp4i2_xml, pyrvapi_dir, share_jsrview, wintitle):
"""This code is largely stolen from <NAME>"""
#// Document modes
#define RVAPI_MODE_Silent 0x00100000
#define RVAPI_MODE_Html 0x00000001
#define RVAPI_MODE_Xmli2 0x00000002
mode = pyrvapi.RVAPI_MODE_Html | bool(ccp4i2_xml) * pyrvapi.RVAPI_MODE_Xmli2
#// Document layouts
#define RVAPI_LAYOUT_Header 0x00000001
#define RVAPI_LAYOUT_Toolbar 0x00000002
#define RVAPI_LAYOUT_Tabs 0x00000004
#define RVAPI_LAYOUT_Full 0x00000007
xml_relpath = os.path.relpath(ccp4i2_xml, pyrvapi_dir) if ccp4i2_xml else None
docid = 'TestRun'
layout = pyrvapi.RVAPI_LAYOUT_Full
html = 'index.html'
pyrvapi.rvapi_init_document(
docid, # const char * docId // mandatory
pyrvapi_dir, # const char * outDir // mandatory
wintitle, # const char * winTitle // mandatory
mode, # const int mode // mandatory
layout, # const int layout // mandatory
share_jsrview, # const char * jsUri // needed
None, # const char * helpFName // may be NULL
html, # const char * htmlFName // may be NULL
None, # const char * taskFName // may be NULL
xml_relpath # const char * xmli2FName // may be NULL
)
return
def _add_tab_to_pyrvapi(self, id, title, opened):
if self.jscofe_mode:
self._insert_tab_to_pyrvapi(id, title, self.rhs_tab_id, opened)
else:
pyrvapi.rvapi_add_tab(id, title, opened)
def _insert_tab_to_pyrvapi(self, id, title, other_tab_id, opened):
pyrvapi.rvapi_insert_tab(id, title, other_tab_id, opened)
def create_log_tab(self, logfile):
"""Function to create log tab
Parameters
----------
logfile : str
Path to the log file
Returns
-------
str
Updating page containing log
"""
if self.jscofe_mode or self.log_tab_id:
return
if not os.path.isfile(logfile):
return False
self.log_tab_id = self.tab_prefix + "log_tab"
logurl = self.fix_path(logfile)
self._add_tab_to_pyrvapi(self.log_tab_id, "Log file", True)
pyrvapi.rvapi_append_content(logurl, True, self.log_tab_id)
return self.log_tab_id
def _create_citation_tab(self):
"""Function to create citation tab"""
if not self.citation_tab_id:
self.citation_tab_id = self.tab_prefix + "citation_tab"
self._add_tab_to_pyrvapi(self.citation_tab_id, "Citations", False)
def _create_lattice_results_tab(self):
"""Function to create lattice results tab"""
if not self.lattice_results_tab_id:
self.lattice_results_tab_id = self.tab_prefix + "lattice_results_tab"
self._add_tab_to_pyrvapi(self.lattice_results_tab_id, "Lattice Parameter Search Results", False)
def _create_contaminant_results_tab(self):
"""Function to create contaminant results tab"""
if not self.contaminant_results_tab_id:
self.contaminant_results_tab_id = self.tab_prefix + "contaminant_results_tab"
self._add_tab_to_pyrvapi(self.contaminant_results_tab_id, "Contaminant Search Results", False)
def _create_morda_db_results_tab(self):
"""Function to create morda db results tab"""
if not self.morda_db_results_tab_id:
self.morda_db_results_tab_id = self.tab_prefix + "morda_db_results_tab"
self._add_tab_to_pyrvapi(self.morda_db_results_tab_id, "MoRDa Database Search Results", False)
def _create_summary_tab(self):
"""Function to create a summary tab
Returns
-------
str
self.summary_tab_id
object
Empty page to append summary to
"""
if self.summary_tab_id:
return
self.summary_tab_id = self.tab_prefix + "summary_tab"
title = "Summary"
opened = True
if self.lattice_results_tab_id:
self._insert_tab_to_pyrvapi(self.summary_tab_id, title, self.lattice_results_tab_id, opened)
elif self.contaminant_results_tab_id:
self._insert_tab_to_pyrvapi(self.summary_tab_id, title, self.contaminant_results_tab_id, opened)
elif self.morda_db_results_tab_id:
self._insert_tab_to_pyrvapi(self.summary_tab_id, title, self.morda_db_results_tab_id, opened)
else:
self._add_tab_to_pyrvapi(self.summary_tab_id, title, opened)
def create_lattice_results_tab(self, lattice_results, lattice_mr_results, results_to_display):
"""Function to create the lattice results tab
Parameters
----------
lattice_results : str
Path to the file containing the lattice results
lattice_mr_results : str
Path to the file containing the lattice MR results
results_to_display : int
Number of results to display
Returns
-------
object
Page containing the results from the lattice parameter search
"""
self._create_lattice_results_tab()
if os.path.isfile(lattice_results):
section_title = 'Lattice Parameter Search Results'
uid = str(uuid.uuid4())
sec = section_title.replace(" ", "_") + uid
tab = self.lattice_results_tab_id
table = "table" + uid
pyrvapi.rvapi_add_section(sec, section_title, tab, 0, 0, 1, 1, True)
table_title = "Lattice Parameter Search Results"
pyrvapi.rvapi_add_table1(sec + "/" + table, table_title, 2, 0, 1, 1, 100)
df = pandas.read_csv(lattice_results)
self.create_table(df, table)
if os.path.isfile(lattice_mr_results):
section_title = 'Molecular Replacement Search Results'
uid = str(uuid.uuid4())
sec = section_title.replace(" ", "_") + uid
tab = self.lattice_results_tab_id
table = "table" + uid
pyrvapi.rvapi_add_section(sec, section_title, tab, 0, 0, 1, 1, True)
table_title = "Molecular Replacement Search Results"
pyrvapi.rvapi_add_table1(sec + "/" + table, table_title, 2, 0, 1, 1, 100)
df = pandas.read_csv(lattice_mr_results)
self.create_table(df, table)
section_title = 'Top {0} Lattice Parameter Search Downloads'.format(results_to_display)
uid = str(uuid.uuid4())
download_sec = section_title.replace(" ", "_") + uid
pyrvapi.rvapi_add_section(download_sec, section_title, tab, 0, 0, 1, 1, True)
section_title = 'Top {0} Lattice Parameter Search Log Files'.format(results_to_display)
uid = str(uuid.uuid4())
logfile_sec = section_title.replace(" ", "_") + uid
pyrvapi.rvapi_add_section(logfile_sec, section_title, tab, 0, 0, 1, 1, False)
self.lattice_df = df
for i in range(0, results_to_display):
try:
pdb_code = df.loc[i][0]
mr_workdir = os.path.join(self.work_dir, 'output_files', pdb_code)
mr_log = os.path.join(mr_workdir, '{0}_mr.log'.format(pdb_code))
ref_pdb = os.path.join(mr_workdir, '{0}_refinement_output.pdb'.format(pdb_code))
ref_mtz = os.path.join(mr_workdir, '{0}_refinement_output.mtz'.format(pdb_code))
| |
dVdi))
gi = trPdV - Py.T.dot(dVdi.dot(Py))
grad.append(gi)
grad = np.concatenate(grad)
grad = _check_shape(np.array(grad))
return grad
def gradient_me(self, theta):
"""
Parameters
----------
theta: array_like
The original parameterization of the components
Returns
-------
gradient: array_like
The gradient of the log likelihood with respect to the covariance
parameterization
Notes
-----
This function avoids forming the (n x n) matrix P, and instead takes
advantage of the fact that yP(dV)Py can be computed using mostly matrix
vector products, while tr(P(dV)) can be computed by accumulating
n vector-vector products where each component of P, P_i, can be formed
only when needed.
"""
Ginv = self.update_gmat(theta, inverse=True)
Rinv = self.R / theta[-1]
X, Z, y = self.X, self.Zs, self.y
W = Rinv.dot(Z)
Omega = cholesky((Z.T.dot(W) + Ginv).tocsc()).inv()
# U = Rinv - W.dot(Omega).dot(W.T)
UX = Rinv.dot(X) - W.dot(Omega).dot(W.T.dot(X))
Uy = Rinv.dot(y) - W.dot(Omega).dot(W.T.dot(y))
self.jac_mats['error'] = [self.jac_mats['error'][0].tocsc()]
S = X.T.dot(UX)
Sinv = np.linalg.inv(S)
Py = Uy - UX.dot(np.linalg.inv(S).dot(UX.T.dot(y)))
UXS = UX.dot(Sinv)
grad = np.zeros_like(theta)
k=0
for key in (self.levels+['error']):
for dVdi in self.jac_mats[key]:
grad[k] += -Py.T.dot(dVdi.dot(Py))[0][0]
k+=1
for i in range(y.shape[0]):
# P_i = np.asarray(U[i] - UXS[i].dot(UX.T))
P_i = np.asarray((Rinv.tocsc()[i].T - W.dot(Omega.dot(W[i].T))).A.T[0] - UXS[i].dot(UX.T))
k=0
for key in (self.levels+['error']):
for dVdi in self.jac_mats[key]:
# grad[k] = grad[k] + dVdi[:, i].T.dot(P_i[0])[0]
grad[k] = grad[k] + dVdi[:, i].T.dot(P_i)[0]
k=k+1
return grad
def hessian(self, theta):
Ginv = self.update_gmat(theta, inverse=True)
Rinv = self.R / theta[-1]
Vinv = sparse_woodbury_inversion(self.Zs, Cinv=Ginv, Ainv=Rinv.tocsc())
W = (Vinv.dot(self.X))
XtW = W.T.dot(self.X)
XtW_inv = np.linalg.inv(XtW)
P = Vinv - np.linalg.multi_dot([W, XtW_inv, W.T])
Py = P.dot(self.y)
H = []
PJ, yPJ = [], []
for key in (self.levels+['error']):
J_list = self.jac_mats[key]
for i in range(len(J_list)):
Ji = J_list[i].T
PJ.append((Ji.dot(P)).T)
yPJ.append((Ji.dot(Py)).T)
t_indices = self.t_indices
for i, j in t_indices:
PJi, PJj = PJ[i], PJ[j]
yPJi, JjPy = yPJ[i], yPJ[j].T
Hij = -(PJi.dot(PJj)).diagonal().sum()\
+ (2 * (yPJi.dot(P)).dot(JjPy))[0]
H.append(np.array(Hij[0]))
H = invech(np.concatenate(H)[:, 0])
return H
def update_chol(self, theta, inverse=False):
"""
Parameters
----------
theta: array_like
array containing the lower triangular components of the cholesky
for each random effect covariance
inverse: bool
Returns
-------
L_dict: dict of array_like
Dictionary whose keys and values correspond to level names
and the corresponding cholesky of the level's random effects
covariance
"""
L_dict = {}
for key in self.levels:
theta_i = theta[self.indices['theta'][key]]
L_i = invech_chol(theta_i)
L_dict[key] = L_i
return L_dict
def dg_dchol(self, L_dict):
"""
Parameters
----------
L_dict: dict of array_like
Dictionary whose keys and values correspond to level names
and the corresponding cholesky of the level's random effects
covariance
Returns
-------
Jf: dict of array_like
For each level contains the derivative of the cholesky parameters
with respect to the covariance
Notes
-----
Function evaluates the derivative of the cholesky parameterization
with respect to the lower triangular components of the covariance
"""
Jf = {}
for key in self.levels:
L = L_dict[key]
E = self.elim_mats[key]
N = self.symm_mats[key]
I = self.iden_mats[key]
Jf[key] = E.dot(N.dot(np.kron(L, I))).dot(E.T)
return Jf
def loglike_c(self, theta_chol, use_sw=False):
"""
Parameters
----------
theta_chol: array_like
The cholesky parameterization of the components
Returns
-------
loglike: scalar
Log likelihood of the model
"""
theta = inverse_transform_theta(theta_chol.copy(), self.dims, self.indices)
theta[-1] = theta_chol[-1]
return self.loglike(theta, use_sw)
def gradient_c(self, theta_chol, use_sw=False):
"""
Parameters
----------
theta_chol: array_like
The cholesky parameterization of the components
Returns
-------
gradient: array_like
The gradient of the log likelihood with respect to the covariance
parameterization
"""
theta = inverse_transform_theta(theta_chol.copy(), self.dims, self.indices)
theta[-1] = theta_chol[-1]
return self.gradient(theta, use_sw)
def gradient_me_c(self, theta_chol):
"""
Parameters
----------
theta_chol: array_like
The cholesky parameterization of the components
Returns
-------
gradient: array_like
The gradient of the log likelihood with respect to the covariance
parameterization
"""
theta = inverse_transform_theta(theta_chol.copy(), self.dims, self.indices)
theta[-1] = theta_chol[-1]
return self.gradient_me(theta)
def hessian_c(self, theta_chol):
"""
Parameters
----------
theta_chol: array_like
The cholesky parameterization of the components
Returns
-------
hessian: array_like
The hessian of the log likelihood with respect to the covariance
parameterization
"""
theta = inverse_transform_theta(theta_chol.copy(), self.dims, self.indices)
theta[-1] = theta_chol[-1]
return self.hessian(theta)
def gradient_chol(self, theta_chol, use_sw=False):
"""
Parameters
----------
theta_chol: array_like
The cholesky parameterization of the components
Returns
-------
gradient: array_like
The gradient of the log likelihood with respect to the cholesky
parameterization
"""
L_dict = self.update_chol(theta_chol)
Jf_dict = self.dg_dchol(L_dict)
Jg = self.gradient_c(theta_chol, use_sw)
Jf = sp.linalg.block_diag(*Jf_dict.values())
Jf = np.pad(Jf, [[0, 1]])
Jf[-1, -1] = 1
return Jg.dot(Jf)
def gradient_me_chol(self, theta_chol):
"""
Parameters
----------
theta_chol: array_like
The cholesky parameterization of the components
Returns
-------
gradient: array_like
The gradient of the log likelihood with respect to the cholesky
parameterization
"""
L_dict = self.update_chol(theta_chol)
Jf_dict = self.dg_dchol(L_dict)
Jg = self.gradient_me_c(theta_chol)
Jf = sp.linalg.block_diag(*Jf_dict.values())
Jf = np.pad(Jf, [[0, 1]])
Jf[-1, -1] = 1
return Jg.dot(Jf)
def hessian_chol(self, theta_chol):
"""
Parameters
----------
theta_chol: array_like
The cholesky parameterization of the components
Returns
-------
hessian: array_like
The hessian of the log likelihood with respect to the cholesky
parameterization
"""
L_dict = self.update_chol(theta_chol)
Jf_dict = self.dg_dchol(L_dict)
Hq = self.hessian_c(theta_chol)
Jg = self.gradient_c(theta_chol)
Hf = self.d2g_dchol
Jf = sp.linalg.block_diag(*Jf_dict.values())
Jf = np.pad(Jf, [[0, 1]])
Jf[-1, -1] = 1
A = Jf.T.dot(Hq).dot(Jf)
B = np.zeros_like(Hq)
for key in self.levels:
ix = self.indices['theta'][key]
Jg_i = Jg[ix]
Hf_i = Hf[key]
C = np.einsum('i,ijk->jk', Jg_i, Hf_i)
B[ix, ix[:, None]] += C
H = A + B
return H
def _compute_effects(self, theta=None):
G = self.update_gmat(theta, inverse=False)
R = self.R * theta[-1]
V = self.Zs.dot(G).dot(self.Zs.T) + R
chol_fac = cholesky(V)
XtVi = (chol_fac.solve_A(self.X)).T
XtViX = XtVi.dot(self.X)
XtViX_inv = np.linalg.inv(XtViX)
beta = _check_shape(XtViX_inv.dot(XtVi.dot(self.y)))
fixed_resids = _check_shape(self.y) - _check_shape(self.X.dot(beta))
#Should be G.dot(Z).T.dot(solve(fixed_resids))
Vinvr = chol_fac.solve_A(fixed_resids)
u = G.dot(self.Zs.T).dot(Vinvr)
return beta, XtViX_inv, u, G, R, V
def _fit(self, use_grad=True, use_hess=False, opt_kws={}):
if use_grad:
default_opt_kws = dict(verbose=0, gtol=1e-6, xtol=1e-6)
if use_hess:
hess = self.hessian_chol
else:
hess = None
for key, value in default_opt_kws.items():
if key not in opt_kws.keys():
opt_kws[key] = value
optimizer = sp.optimize.minimize(self.loglike_c, self.theta,
jac=self.gradient_chol, hess=hess,
options=opt_kws, bounds=self.bounds,
method='trust-constr')
else:
default_opt_kws = dict(disp=True, gtol=1e-14, ftol=1e-14,
finite_diff_rel_step='3-point', eps=1e-7,
iprint=99)
for key, value in default_opt_kws.items():
if key not in opt_kws.keys():
opt_kws[key] = value
optimizer = sp.optimize.minimize(self.loglike_c, self.theta,
bounds=self.bounds_2,
method='L-BFGS-B',
options=opt_kws)
theta_chol = optimizer.x
theta = inverse_transform_theta(theta_chol.copy(), self.dims, self.indices)
beta, XtWX_inv, u, G, R, V = self._compute_effects(theta)
params = np.concatenate([beta, theta])
self.theta, self.beta, self.u, self.params = theta, beta, u, params
self.Hinv_beta = XtWX_inv
self.se_beta = np.sqrt(np.diag(XtWX_inv))
self._G, self._R, self._V = G, R, V
self.optimizer = optimizer
self.theta_chol = theta_chol
self.llconst = (self.X.shape[0] - self.X.shape[1])*np.log(2*np.pi)
self.lltheta = self.optimizer.fun
self.ll = (self.llconst + self.lltheta)
self.llf = self.ll / -2.0
def _post_fit(self, use_grad=True, analytic_se=False):
if analytic_se:
Htheta = self.hessian(self.theta)
elif use_grad:
Htheta = so_gc_cd(self.gradient, self.theta)
else:
Htheta = so_fc_cd(self.loglike, self.theta)
self.Hinv_theta = np.linalg.pinv(Htheta/2.0)
self.se_theta = np.sqrt(np.diag(self.Hinv_theta))
self.se_params = np.concatenate([self.se_beta, self.se_theta])
def predict(self, X=None, Z=None):
if X is None:
X = self.X
if Z is None:
Z = self.Z
return X.dot(self.beta)+Z.dot(self.u)
def fit(self, use_grad=True, use_hess=False, analytic_se=False, opt_kws={}):
self._fit(use_grad, use_hess, opt_kws)
self._post_fit(use_grad, analytic_se)
param_names = list(self.fe_vars)
for level in self.levels:
for i, j in list(zip(*np.triu_indices(self.dims[level]['n_vars']))):
param_names.append(f"{level}:G[{i}][{j}]")
param_names.append("error_cov")
self.param_names = param_names
res = np.vstack((self.params, self.se_params)).T
res = pd.DataFrame(res, index=param_names, columns=['estimate', 'SE'])
res['t'] = res['estimate'] / res['SE']
res['p'] = sp.stats.t(self.X.shape[0]-self.X.shape[1]).sf(np.abs(res['t']))
self.res = res
class WLMEC:
def __init__(self, formula, data, weights=None, fix_error=False):
if weights is None:
weights = np.eye(len(data))
self.weights = sps.csc_matrix(weights)
self.weights_inv = sps.csc_matrix(np.linalg.inv(weights))
indices = {}
X, Z, y, dims, levels = construct_model_matrices(formula, data)
theta, theta_indices = make_theta(dims)
indices['theta'] = theta_indices
G, g_indices = make_gcov(theta, indices, dims)
indices['g'] = g_indices
XZ, Xty, Zty, yty = np.hstack([X, Z]), X.T.dot(y), Z.T.dot(y), y.T.dot(y)
C, m = sps.csc_matrix(XZ.T.dot(XZ)), sps.csc_matrix(np.vstack([Xty, Zty]))
M = sps.bmat([[C, m], [m.T, yty]])
M = M.tocsc()
self.F = | |
import math
import time
import random
from bisect import bisect_left
class SimpleNode(object):
def __init__(self):
self.makeGraph()
pass
def makeNodes(self):
Oberlist={}
for n in self.POSE_INFO:
Oberlist[n] = self.genSimpleNode(n)
return Oberlist
def getAdjacent(self,id):
'''
assumes no cycle.
'''
place= self.ID_LIST.index(id)
a1 = None if place == 0 else self.ID_LIST[place-1]
a2 = None if place == len(self.ID_LIST)-1 else self.ID_LIST[place+1]
return [a1,a2]
def genSimpleNode(self,id):
return {
'name': id,
'holds': self.POSE_INFO[id],
'adj': self.getAdjacent(id)
}
def getNodeFromName(self,name):
return self.GRAPH[name]
def getNodeFromHolds(self,name):
for n in self.GRAPH:
if name in self.GRAPH[n]['holds']:
return self.GRAPH[n]
def traverse(self, origin, destin):
'''
assuming both destin and origin are in graph
'''
path=[]
currN= origin
while currN != destin:
# expand neighbors
n1,n2 = self.getAdjacent(currN['name'])
currN = self.closerNode(self.getNodeFromName(n1),self.getNodeFromName(n2),destin)
path.append(currN)
return path
def closerNode(self,node1, node2, dNode):
'''
uses simple heuristic
'''
closer = node1 if (abs(dNode['name']-node1['name']) < abs(dNode['name']-node2['name'])) else node2
return closer
def makeGraph(self):
'''
POSE_INFO consists of tuples of adjacent rooms.
rooms at index 0 are on one side of the hall, index 1 are the other. (subject to change)
'''
self.GRAPH = self.makeNodes()
def calcNumDoors(self,path,side):
dCount = 0
for n in path:
if n['holds'][side] != None:
dCount +=1
return dCount
def genDirString(self, destination, dSideDist, sideChange):
sc = "Go to the other side of the hallway. " if sideChange else ''
dstr = "{}Proceed {} doors down the hallway and arrive at your destination, room {}.".format(sc, dSideDist, destination)
return dstr
# POSE_INFO holds ids for the room(s) found and the node ID for that spot... maybe gen from pose
POSE_INFO = {
0:('exit',None), # do this for other pose infos
1:('262','263'),
2:('260','261'),
3:('258','259'),
4:('256','257'),
5:('254',None),
6:('252','255'),
7:('exit',None)
}
# sample with four: 7:('intersection')
ID_LIST = list(POSE_INFO.keys())
GRAPH = None
class SecondStateNode(SimpleNode):
'''
(N,S,E,W)
'''
def __init__(self):
self.makeGraph()
self.patchExitNode()
self.distillExits()
self.genDB()
def makeGraph(self):
'''
POSE_INFO consists of tuples of adjacent rooms.
rooms at index 0 are on one side of the hall, index 1 are the other. (subject to change)
'''
id = 0
for n in self.POSE_COLLECTION:
namestr = 'h'+str(id)
self.GRAPH[namestr] = self.makeNodes(n)
id +=1
def makeNodes(self, POSE_INFO):
Oberlist={}
Oberlist['holds'] = list(POSE_INFO.keys())
for n in POSE_INFO:
# Oberlist[n] = self.gen2ndStateNode(n,POSE_INFO) if POSE_INFO[n][-1] != 'exit' else self.genExitNode(n, POSE_INFO)
Oberlist[n] = self.gen2ndStateNode(n,POSE_INFO)
if POSE_INFO[n][-1] == 'exit':
Oberlist[n]['type'] = 'EXIT'
return Oberlist
def gen2ndStateNode(self,id,POSE_INFO):
return {
'name': id,
'type': 'node',
'N': POSE_INFO[id][0],
'S': POSE_INFO[id][1],
'E': POSE_INFO[id][2],
'W': POSE_INFO[id][3]
}
def patchExitNode(self):
# get a list of all exits, a shallow copy that will change the actual node
exits=[]
for h in self.GRAPH:
for n in self.GRAPH[h]:
if n != 'holds' and self.GRAPH[h][n]['type'] == 'EXIT':
self.GRAPH[h][n]['abuts'] = [h]
exits.append(self.GRAPH[h][n])
# now must set the NSEW to correct hallways, instead of just a room node
# first pass, as only item in 'abuts' is the hallway itself
for ex in exits:
for dir in ('N','S','E','W'):
if bool(ex[dir]):
ex[dir] = ex['abuts']
return exits
def getContainingHallways(self, oID,dID,aGraph):
orH = None
dsH = None
for n in aGraph:
if type(n)==int:
if oID in aGraph[n]['holds']:
orH = n
if dID in aGraph[n]['holds']:
dsH = n
return orH, dsH
'''
exits are here manually joined, but must be generated automatically in future.
they are nodes in their own right(???)
'''
H1_POSE_INFO = {
0:(1,None,None,None,'exit'),
1:(2,0,'242','241'),
2:(3,1,'244','243'),
3:(4,2,'246','245'),
4:(5,3,None,'247'),
5:(6,4,'248','249'),
6:(7,5,'250','251'),
7:(None,6,None,None,'exit')
}
H2_POSE_INFO = {
10:(11,None,None,None,'exit'),
11:(2,0,'262','263'),
12:(3,1,'260','261'),
13:(4,2,'258','259'),
14:(5,3,'256','257'),
15:(6,4,'254',None),
16:(7,5,'252','255'),
17:(None,16,None,None,'exit')
}
H3_POSE_INFO = {
20:(21,None,None,None,'exit'),
21:(2,0,'264','265'),
22:(3,1,'266','267'),
23:(4,2,'268',None),
24:(5,3,'270','269'),
25:(None,24,None,None,'exit')
}
POSE_COLLECTION = [H1_POSE_INFO,H2_POSE_INFO,H3_POSE_INFO]
# sample with four: 7:('intersection')
H1_ID_LIST = list(H1_POSE_INFO.keys())
H2_ID_LIST = list(H2_POSE_INFO.keys())
H3_ID_LIST = list(H3_POSE_INFO.keys())
GRAPH = {}
# this sample graph is artificially patched to join exits. THIS MUST BE DONE IN SCRiPT!!!
# this graph acts as a 'floor' and so can be viewed as a node in itself.
# '100001' are placeholders for none-existent hallways that will fail the simple heuristic.
# NH vs N: H stands for hallway. Since these are also regular nodes, they have relationship to other nodes in hallway.
__sampleGraph__= {
1000:{
0: {'EH': None,'E':None,'W':None,'N':1,'S': None,'NH': 1000,'SH': 100001,'WH': None,'name': 0,'type': 'EXIT', 'hall':1000},
1: {'E': '242', 'N': 2, 'S': 0, 'W': '241', 'name': 1, 'type': 'node', 'hall':1000},
2: {'E': '244', 'N': 3, 'S': 1, 'W': '243', 'name': 2, 'type': 'node', 'hall':1000},
3: {'E': '246', 'N': 4, 'S': 2, 'W': '245', 'name': 3, 'type': 'node', 'hall':1000},
4: {'E': None, 'N': 5, 'S': 3, 'W': '247', 'name': 4, 'type': 'node', 'hall':1000},
5: {'E': '248', 'N': 6, 'S': 4, 'W': '249', 'name': 5, 'type': 'node', 'hall':1000},
6: {'E': '250', 'N': 7, 'S': 5, 'W': '251', 'name': 6, 'type': 'node', 'hall':1000},
7: {'EH': None,'E':None,'W':None,'S':6,'N':None, 'NH': 1001, 'SH': 1000, 'WH': None, 'name': 7, 'type': 'EXIT', 'hall':1000},
'holds': [0, 1, 2, 3, 4, 5, 6, 7],
'exits': [0,7],
'adj': [1001,100001]},
1001:{
10: {'EH': None,'E':None,'W':None,'N':11,'S':None,'NH': 1001,'SH': 1002,'WH': None,'name': 10,'type': 'EXIT', 'hall':1001},
11: {'E': '262', 'N': 12, 'S': 10, 'W': '263', 'name': 11, 'type': 'node', 'hall':1001},
12: {'E': '260', 'N': 13, 'S': 11, 'W': '261', 'name': 12, 'type': 'node', 'hall':1001},
13: {'E': '258', 'N': 14, 'S': 12, 'W': '259', 'name': 13, 'type': 'node', 'hall':1001},
14: {'E': '256', 'N': 15, 'S': 13, 'W': '257', 'name': 14, 'type': 'node', 'hall':1001},
15: {'E': '254', 'N': 16, 'S': 14, 'W': None, 'name': 15, 'type': 'node', 'hall':1001},
16: {'E': '252', 'N': 17, 'S': 15, 'W': '255', 'name': 16, 'type': 'node', 'hall':1001},
17: {'EH': None,'E':None,'W':None,'S':16, 'N':None,'NH': 1000, 'SH': 1001, 'WH': None, 'name': 17, 'type': 'EXIT', 'hall':1001},
'holds': [16, 17, 10, 11, 12, 13, 14, 15],
'exits':[10,17],
'adj': [1000,1002]},
1002: {
20: {'EH': None,'E':None,'W':None,'N':21,'S':None,'NH': 1002,'SH': 1001,'WH': None,'name': 20,'type': 'EXIT', 'hall':1002},
21: {'E': '264', 'N': 22, 'S': 20, 'W': '265', 'name': 21, 'type': 'node', 'hall':1002},
22: {'E': '266', 'N': 23, 'S': 21, 'W': '267', 'name': 22, 'type': 'node', 'hall':1002},
23: {'E': '268', 'N': 24, 'S': 22, 'W': None, 'name': 23, 'type': 'node', 'hall':1002},
24: {'E': '270', 'N': 25, 'S': 23, 'W': '269', 'name': 24, 'type': 'node', 'hall':1002},
25: {'EH': None,'E':None,'W':None,'S':24,'N':None, 'NH': 100001, 'SH': 1002, 'WH': None, 'name': 25, 'type': 'EXIT', 'hall':1002},
'holds': [20, 21, 22, 23, 24, 25],
'exits':[20,25],
'adj': [1001,100001]}
}
DB = {}
EXITS_DICT={}
CARDINALS = ('N','S','E','W')
LONG_CARDINALS = {'E': 'East', 'N': 'North', 'S': 'South', 'W': 'West'}
SOUTH_WAY = {'E': 'left', 'N': 'backward', 'S': 'forward', 'W': 'right'}
NORTH_WAY={'W': 'left', 'S': 'backward', 'N': 'forward', 'E': 'right'}
EAST_WAY={'N': 'left', 'W': 'backward', 'E': 'forward', 'S': 'right'}
WEST_WAY={'E': 'left', 'S': 'backward', 'W': 'forward', 'N': 'right'}
def genDB(self):
for h in self.__sampleGraph__:
kl=[x for x in list(self.__sampleGraph__[h].keys()) if type(x) == int]
for n in kl:
for dir in self.CARDINALS:
if dir in self.__sampleGraph__[h][n].keys() and type(self.__sampleGraph__[h][n][dir]) == str:
self.DB[self.__sampleGraph__[h][n][dir]]=self.__sampleGraph__[h][n]['name']
def getIDFromName(self, name):
return self.DB[name] if name in self.DB.keys() else False
def percentWords(self, percentage):
if percentage < .30:
return 'about a quarter of the way'
if percentage < .60:
return 'about halfway'
if percentage < .85:
return 'about three quarters of the way'
else:
return 'most of the way'
def distillExits(self):
'''
grabs all exits in graph. exits are traversed to find path to goal.
'''
for n in self.__sampleGraph__:
if type(n)==int:
for e in self.__sampleGraph__[n]['exits']:
self.EXITS_DICT[e]= self.__sampleGraph__[n][e]
def findClosestExit(self, ID):
exits=list(self.EXITS_DICT.keys())
exits.sort()
return min(exits, key=lambda x: abs(x-ID))
def expandExit(self, exitID):
'''
assuming only 2 exits per hallway. next iteration will feature more.
'''
e1,e2=self.__sampleGraph__[self.EXITS_DICT[exitID]['hall']]['exits']
return e1,e2
def expandExitHalls(self, exitID):
return [self.EXITS_DICT[exitID][n] for n in ('N','S','E','W') if self.EXITS_DICT[exitID][n]]
def performHeuristic(self, dID, ID1, ID2):
return ID1 if abs(dID - ID1) < abs(dID - ID2) else ID2
def getBestOfTwoExits(self, dHall,ex1,ex2):
'''
assuming 2 exits per hallway, and 2 hallways per exit.
'''
e1h1,e1h2=self.expandExitHalls(ex1)
e1h=self.performHeuristic(dHall,e1h1,e1h2)
e2h1,e2h2=self.expandExitHalls(ex2)
e2h=self.performHeuristic(dHall,e2h1,e2h2)
betterHall = self.performHeuristic(dHall,e1h,e2h)
better = ex1 if betterHall is e1h else ex2
return better, betterHall
def traverse(self, oID, dID):
'''
assuming both dID and oID are in graph
in | |
# Copyright (c) 2013 Amazon.com, Inc. or its affiliates. All Rights Reserved
#
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish, dis-
# tribute, sublicense, and/or sell copies of the Software, and to permit
# persons to whom the Software is furnished to do so, subject to the fol-
# lowing 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 MERCHANTABIL-
# ITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
# SHALL THE AUTHOR 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.
#
try:
import json
except ImportError:
import simplejson as json
import boto
from boto.connection import AWSQueryConnection
from boto.regioninfo import RegionInfo
from boto.exception import JSONResponseError
from boto.cloudformation import exceptions
class CloudFormationConnection(AWSQueryConnection):
"""
AWS CloudFormation
AWS CloudFormation enables you to create and manage AWS
infrastructure deployments predictably and repeatedly. AWS
CloudFormation helps you leverage AWS products such as Amazon EC2,
EBS, Amazon SNS, ELB, and Auto Scaling to build highly-reliable,
highly scalable, cost effective applications without worrying
about creating and configuring the underlying AWS infrastructure.
With AWS CloudFormation, you declare all of your resources and
dependencies in a template file. The template defines a collection
of resources as a single unit called a stack. AWS CloudFormation
creates and deletes all member resources of the stack together and
manages all dependencies between the resources for you.
For more information about this product, go to the `CloudFormation
Product Page`_.
Amazon CloudFormation makes use of other AWS products. If you need
additional technical information about a specific AWS product, you
can find the product's technical documentation at
`http://aws.amazon.com/documentation/`_.
"""
APIVersion = "2010-05-15"
DefaultRegionName = "us-east-1"
DefaultRegionEndpoint = "cloudformation.us-east-1.amazonaws.com"
ResponseError = JSONResponseError
_faults = {
"AlreadyExistsException": exceptions.AlreadyExistsException,
"InsufficientCapabilitiesException": exceptions.InsufficientCapabilitiesException,
"LimitExceededException": exceptions.LimitExceededException,
}
def __init__(self, **kwargs):
region = kwargs.pop('region', None)
if not region:
region = RegionInfo(self, self.DefaultRegionName,
self.DefaultRegionEndpoint)
if 'host' not in kwargs:
kwargs['host'] = region.endpoint
super(CloudFormationConnection, self).__init__(**kwargs)
self.region = region
def _required_auth_capability(self):
return ['hmac-v4']
def cancel_update_stack(self, stack_name):
"""
Cancels an update on the specified stack. If the call
completes successfully, the stack will roll back the update
and revert to the previous stack configuration.
Only stacks that are in the UPDATE_IN_PROGRESS state can be
canceled.
:type stack_name: string
:param stack_name: The name or the unique identifier associated with
the stack.
"""
params = {'StackName': stack_name, }
return self._make_request(
action='CancelUpdateStack',
verb='POST',
path='/', params=params)
def create_stack(self, stack_name, template_body=None, template_url=None,
parameters=None, disable_rollback=None,
timeout_in_minutes=None, notification_arns=None,
capabilities=None, on_failure=None,
stack_policy_body=None, stack_policy_url=None,
tags=None):
"""
Creates a stack as specified in the template. After the call
completes successfully, the stack creation starts. You can
check the status of the stack via the DescribeStacks API.
Currently, the limit for stacks is 20 stacks per account per
region.
:type stack_name: string
:param stack_name:
The name associated with the stack. The name must be unique within your
AWS account.
Must contain only alphanumeric characters (case sensitive) and start
with an alpha character. Maximum length of the name is 255
characters.
:type template_body: string
:param template_body: Structure containing the template body. (For more
information, go to `Template Anatomy`_ in the AWS CloudFormation
User Guide.)
Conditional: You must pass `TemplateBody` or `TemplateURL`. If both are
passed, only `TemplateBody` is used.
:type template_url: string
:param template_url: Location of file containing the template body. The
URL must point to a template (max size: 307,200 bytes) located in
an S3 bucket in the same region as the stack. For more information,
go to the `Template Anatomy`_ in the AWS CloudFormation User Guide.
Conditional: You must pass `TemplateURL` or `TemplateBody`. If both are
passed, only `TemplateBody` is used.
:type parameters: list
:param parameters: A list of `Parameter` structures that specify input
parameters for the stack.
:type disable_rollback: boolean
:param disable_rollback: Set to `True` to disable rollback of the stack
if stack creation failed. You can specify either `DisableRollback`
or `OnFailure`, but not both.
Default: `False`
:type timeout_in_minutes: integer
:param timeout_in_minutes: The amount of time that can pass before the
stack status becomes CREATE_FAILED; if `DisableRollback` is not set
or is set to `False`, the stack will be rolled back.
:type notification_arns: list
:param notification_arns: The Simple Notification Service (SNS) topic
ARNs to publish stack related events. You can find your SNS topic
ARNs using the `SNS console`_ or your Command Line Interface (CLI).
:type capabilities: list
:param capabilities: The list of capabilities that you want to allow in
the stack. If your template contains certain resources, you must
specify the CAPABILITY_IAM value for this parameter; otherwise,
this action returns an InsufficientCapabilities error. The
following resources require you to specify the capabilities
parameter: `AWS::CloudFormation::Stack`_, `AWS::IAM::AccessKey`_,
`AWS::IAM::Group`_, `AWS::IAM::InstanceProfile`_,
`AWS::IAM::Policy`_, `AWS::IAM::Role`_, `AWS::IAM::User`_, and
`AWS::IAM::UserToGroupAddition`_.
:type on_failure: string
:param on_failure: Determines what action will be taken if stack
creation fails. This must be one of: DO_NOTHING, ROLLBACK, or
DELETE. You can specify either `OnFailure` or `DisableRollback`,
but not both.
Default: `ROLLBACK`
:type stack_policy_body: string
:param stack_policy_body: Structure containing the stack policy body.
(For more information, go to ` Prevent Updates to Stack Resources`_
in the AWS CloudFormation User Guide.)
If you pass `StackPolicyBody` and `StackPolicyURL`, only
`StackPolicyBody` is used.
:type stack_policy_url: string
:param stack_policy_url: Location of a file containing the stack
policy. The URL must point to a policy (max size: 16KB) located in
an S3 bucket in the same region as the stack. If you pass
`StackPolicyBody` and `StackPolicyURL`, only `StackPolicyBody` is
used.
:type tags: list
:param tags: A set of user-defined `Tags` to associate with this stack,
represented by key/value pairs. Tags defined for the stack are
propagated to EC2 resources that are created as part of the stack.
A maximum number of 10 tags can be specified.
"""
params = {'StackName': stack_name, }
if template_body is not None:
params['TemplateBody'] = template_body
if template_url is not None:
params['TemplateURL'] = template_url
if parameters is not None:
self.build_complex_list_params(
params, parameters,
'Parameters.member',
('ParameterKey', 'ParameterValue'))
if disable_rollback is not None:
params['DisableRollback'] = str(
disable_rollback).lower()
if timeout_in_minutes is not None:
params['TimeoutInMinutes'] = timeout_in_minutes
if notification_arns is not None:
self.build_list_params(params,
notification_arns,
'NotificationARNs.member')
if capabilities is not None:
self.build_list_params(params,
capabilities,
'Capabilities.member')
if on_failure is not None:
params['OnFailure'] = on_failure
if stack_policy_body is not None:
params['StackPolicyBody'] = stack_policy_body
if stack_policy_url is not None:
params['StackPolicyURL'] = stack_policy_url
if tags is not None:
self.build_complex_list_params(
params, tags,
'Tags.member',
('Key', 'Value'))
return self._make_request(
action='CreateStack',
verb='POST',
path='/', params=params)
def delete_stack(self, stack_name):
"""
Deletes a specified stack. Once the call completes
successfully, stack deletion starts. Deleted stacks do not
show up in the DescribeStacks API if the deletion has been
completed successfully.
:type stack_name: string
:param stack_name: The name or the unique identifier associated with
the stack.
"""
params = {'StackName': stack_name, }
return self._make_request(
action='DeleteStack',
verb='POST',
path='/', params=params)
def describe_stack_events(self, stack_name=None, next_token=None):
"""
Returns all stack related events for a specified stack. For
more information about a stack's event history, go to
`Stacks`_ in the AWS CloudFormation User Guide.
Events are returned, even if the stack never existed or has
been successfully deleted.
:type stack_name: string
:param stack_name: The name or the unique identifier associated with
the stack.
Default: There is no default value.
:type next_token: string
:param next_token: String that identifies the start of the next list of
events, if there is one.
Default: There is no default value.
"""
params = {}
if stack_name is not None:
params['StackName'] = stack_name
if next_token is not None:
params['NextToken'] = next_token
return self._make_request(
action='DescribeStackEvents',
| |
update our layout
mpl_active = c.get("matplotlib-mode")
passed_runs = self.all_runs
passed_outputs = raw_outputs
if self.activate_run_selection:
passed_runs = self.all_runs[inputs["run_name"]["value"]]
passed_outputs = raw_outputs[passed_runs.name]
if mpl_active:
outputs = self.load_mpl_outputs(inputs, passed_outputs, passed_runs)
else:
outputs = self.load_outputs(inputs, passed_outputs, passed_runs)
if outputs == PreventUpdate:
raise PreventUpdate()
# Map outputs here because it may be that the outputs are
# differently sorted than the values were registered.
if isinstance(outputs, dict):
outputs = self._dict_to_list(outputs, input=False)
else:
if not isinstance(outputs, list):
outputs = [outputs]
# We have to add no_updates here for the mode we don't want
count_outputs = 0
count_mpl_outputs = 0
for (_, _, mpl_mode) in self.outputs:
if mpl_mode:
count_mpl_outputs += 1
else:
count_outputs += 1
if mpl_active:
outputs = [no_update for _ in range(count_outputs)] + outputs
else:
outputs = outputs + [no_update for _ in range(count_mpl_outputs)]
return outputs
def _list_to_dict(self, values: Iterable[str], input=True) -> Dict[str, Dict[str, str]]:
"""
Maps the given values to a dict, regarding the sorting from
either self.inputs or self.outputs.
Returns:
dict
"""
if input:
order = self.inputs
else:
order = self.outputs
mapping = {}
for value, (id, attribute, *_) in zip(values, order):
if id not in mapping:
mapping[id] = {}
mapping[id][attribute] = value
return mapping
def _dict_to_list(self, d: Dict[str, Dict[str, str]], input=False) -> List[Optional[str]]:
"""
Maps the given dict to a list, regarding the sorting from either
self.inputs or self.outputs.
Returns:
list.
"""
if input:
order = self.inputs
else:
order = self.outputs
result = []
for (id, attribute, instance) in order:
if not input:
# Instance is mlp_mode in case of outputs
# Simply ignore other outputs.
if instance != c.get("matplotlib-mode"):
continue
try:
value = d[id][attribute]
result += [value]
except:
result += [None]
return result
def _dict_as_key(self, d: Dict[str, Any], remove_filters=False) -> Optional[str]:
"""
Converts a dictionary to a key. Only ids from self.inputs are considered.
Parameters:
d (dict): Dictionary to get the key from.
remove_filters (bool): Option wheather the filters should be included or not.
Returns:
key (str): Key as string from the given dictionary.
"""
if not isinstance(d, dict):
return None
new_d = copy.deepcopy(d)
if remove_filters:
for (id, _, filter) in self.inputs:
if filter:
if id in new_d:
del new_d[id]
return string_to_hash(str(new_d))
def __call__(self, render_button: bool = False) -> List[Component]:
"""
Returns the components for the plugin. Basically, all blocks and elements of the plugin
are stacked-up here
Returns
-------
List[Component]
Layout as list of components.
"""
self.previous_inputs = {}
self.raw_outputs = None
self.runs = run_handler.get_runs()
groups = run_handler.get_groups()
self.groups = {
name: GroupedRun(name, [self.runs[run_id] for run_id in run_ids])
for name, run_ids in groups.items()
}
self.all_runs = {}
self.all_runs.update(add_prefix_to_dict(self.runs, "run:"))
self.all_runs.update(add_prefix_to_dict(self.groups, "group:"))
components = [html.H1(self.name)]
if self.description is not None:
components += [html.P(self.description)]
# Register alerts
components += [
dcc.Interval(
id=self.get_internal_id("alert-interval"),
interval=1 * 500,
n_intervals=5,
),
dbc.Alert(
id=self.get_internal_id("alert"),
is_open=False,
dismissable=True,
fade=True,
),
]
try:
self.check_runs_compatibility(list(self.all_runs.values()))
except NotMergeableError as message:
self.update_alert(str(message), color="danger")
return components
if self.activate_run_selection:
run_input_layout = [self.__class__.get_run_input_layout(self.register_input)]
else:
run_input_layout = []
input_layout = self.__class__.get_input_layout(self.register_input)
separator_layout = []
if input_layout and run_input_layout:
separator_layout.append(html.Hr())
input_control_layout = html.Div(
style={} if render_button else {"display": "none"},
className="mt-3 clearfix",
children=[
dbc.Button(
children=self.button_caption,
id=self.get_internal_id("update-button"),
),
html.Span(
html.Em(id=self.get_internal_id("processing-info")),
className="ms-3 align-baseline",
),
],
)
# We always have to render it because of the button.
# Button tells us if the page was just loaded.
components += [
html.Div(
id=f"{self.id}-input",
className="shadow-sm p-3 mb-3 bg-white rounded-lg",
children=run_input_layout
+ separator_layout
+ input_layout
+ [input_control_layout],
style={}
if render_button or input_layout or run_input_layout
else {"display": "none"},
)
]
def register_in(a, b):
return self.register_input(a, b, filter=True)
filter_layout = self.__class__.get_filter_layout(register_in)
if len(filter_layout) > 0:
components += [
html.Div(
id=f"{self.id}-filter",
className="shadow-sm p-3 mb-3 bg-white rounded-lg",
children=filter_layout,
)
]
output_layout = self.__class__.get_output_layout(self.register_output)
if output_layout:
components += [
html.Div(
id=f"{self.id}-output",
className="shadow-sm p-3 bg-white rounded-lg loading-container",
children=output_layout,
style={} if not c.get("matplotlib-mode") else {"display": "none"},
)
]
def register_out(a, b):
return self.register_output(a, b, mpl=True)
output_layout = self.__class__.get_mpl_output_layout(register_out)
if output_layout:
components += [
html.Div(
id=f"{self.id}-mpl-output",
className="shadow-sm p-3 bg-white rounded-lg loading-container",
children=output_layout,
style={} if c.get("matplotlib-mode") else {"display": "none"},
)
]
modal = html.Div(
[
dbc.Button(
"Raw Data",
id=self.get_internal_id("show_raw_data"),
className="mt-3",
n_clicks=0,
),
dbc.Modal(
[
dbc.ModalHeader(
[
dbc.ModalTitle("Raw Data"),
dcc.Clipboard(
target_id=self.get_internal_id("raw_data_content"),
style={
"fontSize": 20,
"marginLeft": "0.5rem",
},
),
]
),
dbc.ModalBody(
[
dbc.Textarea(
id=self.get_internal_id("raw_data_content"),
placeholder="",
readonly=True,
rows=20,
),
]
),
],
id=self.get_internal_id("raw_data"),
size="lg",
scrollable=True,
is_open=False,
),
]
)
components += [modal]
return components
@staticmethod
def get_run_input_layout(register: Callable[[str, Union[str, List[str]]], str]) -> Component:
"""
Generates the run selection input.
This is only the case if `activate_run_selection` is True.
Parameters
----------
register : Callable[[str, Union[str, List[str]]], str]
The register method to register (user) variables.
Returns
-------
Component
The layout of the run selection input.
"""
return html.Div(
[
dbc.Select(
id=register("run_name", ["options", "value"]),
placeholder="Select run ...",
),
]
)
@staticmethod
def load_run_inputs(
runs: Dict[str, AbstractRun],
groups: Dict[str, GroupedRun],
check_run_compatibility: Callable[[AbstractRun], bool],
) -> Dict[str, Any]:
"""
Loads the options for `get_run_input_layout`.
Both runs and groups are displayed.
Parameters
----------
runs : Dict[str, Run]
The runs to display.
groups : Dict[str, GroupedRun]
The groups to display.
check_run_compatibility : Callable[[AbstractRun], bool]
If a single run is compatible. If not, the run is not shown.
Returns
-------
Dict[str, Any]
Both runs and groups, separated by a separator.
"""
labels = []
values = []
disabled = []
for id, run in runs.items():
try:
values.append(f"run:{id}")
labels.append(id)
disabled.append(False)
except:
pass
added_group_label = False
for id, run in groups.items():
if check_run_compatibility(run):
if not added_group_label:
values.append("")
labels.append("Groups")
disabled.append(True)
added_group_label = True
values.append(f"group:{id}")
labels.append(id)
disabled.append(False)
return {
"run_name": {
"options": get_select_options(labels=labels, values=values, disabled=disabled),
"value": None,
}
}
def get_selected_runs(self, inputs: Dict[str, Any]) -> List[AbstractRun]:
"""
Parses selected runs from inputs.
If self.activate_run_selection is set, return only selected run. Otherwise, return all
possible runs.
Parameters
----------
inputs : Dict[str, Any]
The inputs to parse.
Returns
-------
List[AbstractRun]
The selected runs.
Raises
------
PreventUpdate
If `activate_run_selection` is set but `run_name` is not available.
"""
# Special case: If run selection is active
# Don't update anything if the inputs haven't changed
if self.activate_run_selection:
if inputs["run_name"]["value"] is None:
raise PreventUpdate()
# Update runs
run = run_handler.from_run_id(inputs["run_name"]["value"])
# Also:
# Remove `run_name` from inputs_key because
# we don't want the run names included.
_inputs = inputs.copy()
del _inputs["run_name"]
return [run]
else:
return list(self.all_runs.values())
def load_inputs(self) -> Dict[str, Any]:
"""
Load the content for the defined inputs in `get_input_layout` and `get_filter_layout`.
This method is necessary to pre-load contents for the inputs. So, if the plugin is
called for the first time or there are no results in the cache, the plugin gets its
content from this method.
Returns
-------
Dict[str, Any]
Content to be filled.
"""
return {}
def load_dependency_inputs(
self,
previous_inputs: Dict[str, Any],
inputs: Dict[str, Any],
selected_run: Optional[Union[AbstractRun, List[AbstractRun]]] = None,
) -> Dict[str, Any]:
"""
Same as `load_inputs` but called after inputs have changed. Provides a lot of flexibility.
Parameters
----------
previous_inputs : Dict[str, Any]
Previous content of the inputs.
inputs : Dict[str, Any]
Current content of the inputs.
selected_run : Optional[Union[AbstractRun, List[AbstractRun]]], optional
The selected run from the user. In case of `activate_run_selection`, a list of runs
are passed. Defaults to None.
Returns
-------
Dict[str, Any]
Content to be filled.
"""
return inputs
@staticmethod
def get_input_layout(register: Callable[[str, Union[str, List[str]]], str]) -> List[Component]:
"""
Layout for the input block.
Parameters
----------
register : Callable[[str, Union[str, List[str]]], str]
The register method to register (user) variables.
Returns
-------
List[Component]
Layouts for the input block.
"""
return []
@staticmethod
def get_filter_layout(register: Callable[[str, Union[str, List[str]]], str]):
"""
Layout for the filter block.
Parameters
----------
register : Callable[[str, Union[str, List[str]]], str]
The register method to register (user) variables.
Returns
-------
List[Component]
Layouts for the filter block.
"""
return []
@staticmethod
def get_output_layout(register: Callable[[str, Union[str, List[str]]], str]):
"""
Layout for the output block.
Parameters
----------
register : Callable[[str, Union[str, List[str]]], str]
The register method to register outputs.
Returns
-------
List[Component]
Layouts for the output block.
"""
return []
@staticmethod
def get_mpl_output_layout(register: Callable[[str, Union[str, List[str]]], str]):
"""
Layout for the matplotlib output block.
Parameters
----------
| |
+ 0.5*m.b338*m.b350 + 0.5*m.b338*m.b353 +
0.5*m.b338*m.b364 + 0.5*m.b338*m.b370 + 0.5*m.b338*m.b378 + 0.5*m.b338*m.b384 + 0.5*m.b338*m.b401
+ 0.5*m.b338*m.b405 + m.b338*m.b415 + 0.5*m.b338*m.b433 + 0.5*m.b338*m.b437 + 0.5*m.b338*m.b459
+ 0.5*m.b338*m.b495 + 0.5*m.b338*m.b504 + 0.5*m.b338*m.b508 + 0.5*m.b338*m.b517 + m.b338*m.b518
+ 0.5*m.b338*m.b527 + 0.5*m.b338*m.b528 + 0.5*m.b338*m.b535 + m.b338*m.b543 + 0.5*m.b338*m.b548
+ 0.5*m.b338*m.b577 + 0.5*m.b338*m.b579 + 0.5*m.b338*m.b596 + 0.5*m.b338*m.b634 + m.b338*m.b640
+ 0.5*m.b338*m.b649 + 0.5*m.b338*m.b654 + 0.5*m.b338*m.b655 + 0.5*m.b338*m.b665 + 0.5*m.b338*
m.b675 + m.b338*m.x858 + 0.5*m.b339*m.b341 + 0.5*m.b339*m.b345 + 0.5*m.b339*m.b360 + 0.5*m.b339*
m.b366 + 0.5*m.b339*m.b380 + 0.5*m.b339*m.b387 + 0.5*m.b339*m.b401 + 0.5*m.b339*m.b403 + 0.5*
m.b339*m.b405 + 0.5*m.b339*m.b406 + 0.5*m.b339*m.b426 + 0.5*m.b339*m.b431 + 0.5*m.b339*m.b432 +
0.5*m.b339*m.b447 + 0.5*m.b339*m.b452 + m.b339*m.b453 + 0.5*m.b339*m.b475 + 0.5*m.b339*m.b507 +
0.5*m.b339*m.b511 + 0.5*m.b339*m.b519 + 0.5*m.b339*m.b525 + 0.5*m.b339*m.b528 + 0.5*m.b339*m.b533
+ 0.5*m.b339*m.b535 + 0.5*m.b339*m.b545 + m.b339*m.b565 + 0.5*m.b339*m.b575 + 0.5*m.b339*m.b577
+ 0.5*m.b339*m.b579 + 0.5*m.b339*m.b580 + 0.5*m.b339*m.b589 + 0.5*m.b339*m.b592 + m.b339*m.b594
+ 0.5*m.b339*m.b597 + 0.5*m.b339*m.b607 + 0.5*m.b339*m.b642 + 0.5*m.b339*m.b653 + 0.5*m.b339*
m.b659 + 0.5*m.b339*m.b663 + 0.5*m.b339*m.b667 + 0.5*m.b339*m.b680 + 0.5*m.b340*m.b356 + 0.5*
m.b340*m.b378 + 0.5*m.b340*m.b379 + 0.5*m.b340*m.b382 + 0.5*m.b340*m.b384 + 0.5*m.b340*m.b389 +
0.5*m.b340*m.b391 + 0.5*m.b340*m.b392 + 0.5*m.b340*m.b444 + 0.5*m.b340*m.b446 + 0.5*m.b340*m.b448
+ 0.5*m.b340*m.b459 + 0.5*m.b340*m.b462 + m.b340*m.b463 + 0.5*m.b340*m.b469 + 0.5*m.b340*m.b503
+ 0.5*m.b340*m.b514 + 0.5*m.b340*m.b521 + 0.5*m.b340*m.b523 + 0.5*m.b340*m.b524 + m.b340*m.b542
+ 0.5*m.b340*m.b551 + 0.5*m.b340*m.b564 + 0.5*m.b340*m.b573 + 0.5*m.b340*m.b588 + 0.5*m.b340*
m.b609 + 0.5*m.b340*m.b610 + 0.5*m.b340*m.b612 + 0.5*m.b340*m.b618 + 0.5*m.b340*m.b622 + 0.5*
m.b340*m.b630 + 0.5*m.b340*m.b644 + 0.5*m.b340*m.b654 + m.b340*m.b668 + 0.5*m.b340*m.b679 +
m.b340*m.x857 + m.b341*m.b360 + 0.5*m.b341*m.b380 + 0.5*m.b341*m.b387 + 0.5*m.b341*m.b401 + 0.5*
m.b341*m.b403 + 0.5*m.b341*m.b405 + 0.5*m.b341*m.b426 + 0.5*m.b341*m.b429 + m.b341*m.b447 + 0.5*
m.b341*m.b452 + 0.5*m.b341*m.b453 + 0.5*m.b341*m.b511 + 0.5*m.b341*m.b516 + 0.5*m.b341*m.b525 +
0.5*m.b341*m.b528 + 0.5*m.b341*m.b565 + 0.5*m.b341*m.b575 + 0.5*m.b341*m.b577 + 0.5*m.b341*m.b579
+ 0.5*m.b341*m.b580 + 0.5*m.b341*m.b590 + 0.5*m.b341*m.b594 + 0.5*m.b341*m.b607 + 0.5*m.b341*
m.b653 + m.b341*m.b667 + 0.5*m.b341*m.b680 + m.b341*m.x859 + 0.5*m.b342*m.b361 + m.b342*m.b363 +
0.5*m.b342*m.b375 + 0.5*m.b342*m.b377 + 0.5*m.b342*m.b386 + 0.5*m.b342*m.b419 + 0.5*m.b342*m.b440
+ 0.5*m.b342*m.b464 + 0.5*m.b342*m.b485 + 0.5*m.b342*m.b493 + 0.5*m.b342*m.b505 + 0.5*m.b342*
m.b537 + 0.5*m.b342*m.b552 + 0.5*m.b342*m.b556 + 0.5*m.b342*m.b569 + 0.5*m.b342*m.b578 + 0.5*
m.b342*m.b581 + 0.5*m.b342*m.b611 + 0.5*m.b342*m.b627 + 0.5*m.b342*m.b638 + 0.5*m.b342*m.b639 +
0.5*m.b342*m.b646 + 0.5*m.b342*m.b648 + 0.5*m.b342*m.b656 + 0.5*m.b342*m.b666 + m.b342*m.x860 +
m.b343*m.b344 + 0.5*m.b343*m.b346 + 0.5*m.b343*m.b349 + 0.5*m.b343*m.b350 + 0.5*m.b343*m.b364 +
0.5*m.b343*m.b366 + 0.5*m.b343*m.b367 + 0.5*m.b343*m.b368 + 0.5*m.b343*m.b379 + 0.5*m.b343*m.b417
+ 0.5*m.b343*m.b425 + 0.5*m.b343*m.b429 + 0.5*m.b343*m.b432 + 0.5*m.b343*m.b439 + 0.5*m.b343*
m.b441 + m.b343*m.b455 + 0.5*m.b343*m.b460 + 0.5*m.b343*m.b466 + 0.5*m.b343*m.b468 + 0.5*m.b343*
m.b475 + 0.5*m.b343*m.b484 + 0.5*m.b343*m.b494 + 0.5*m.b343*m.b496 + 0.5*m.b343*m.b502 + m.b343*
m.b506 + 0.5*m.b343*m.b514 + 0.5*m.b343*m.b516 + 0.5*m.b343*m.b517 + 0.5*m.b343*m.b521 + 0.5*
m.b343*m.b522 + 0.5*m.b343*m.b523 + 0.5*m.b343*m.b532 + 0.5*m.b343*m.b534 + 0.5*m.b343*m.b548 +
0.5*m.b343*m.b592 + 0.5*m.b343*m.b593 + 0.5*m.b343*m.b596 + 0.5*m.b343*m.b597 + 0.5*m.b343*m.b598
+ 0.5*m.b343*m.b599 + 0.5*m.b343*m.b600 + 0.5*m.b343*m.b612 + 0.5*m.b343*m.b617 + 0.5*m.b343*
m.b637 + 0.5*m.b343*m.b669 + 0.5*m.b344*m.b346 + 0.5*m.b344*m.b349 + 0.5*m.b344*m.b350 + 0.5*
m.b344*m.b364 + 0.5*m.b344*m.b366 + 0.5*m.b344*m.b367 + 0.5*m.b344*m.b368 + 0.5*m.b344*m.b379 +
0.5*m.b344*m.b417 + 0.5*m.b344*m.b425 + 0.5*m.b344*m.b429 + 0.5*m.b344*m.b432 + 0.5*m.b344*m.b439
+ 0.5*m.b344*m.b441 + m.b344*m.b455 + 0.5*m.b344*m.b460 + 0.5*m.b344*m.b466 + 0.5*m.b344*m.b468
+ 0.5*m.b344*m.b475 + 0.5*m.b344*m.b484 + 0.5*m.b344*m.b494 + 0.5*m.b344*m.b496 + 0.5*m.b344*
m.b502 + m.b344*m.b506 + 0.5*m.b344*m.b514 + 0.5*m.b344*m.b516 + 0.5*m.b344*m.b517 + 0.5*m.b344*
m.b521 + 0.5*m.b344*m.b522 + 0.5*m.b344*m.b523 + 0.5*m.b344*m.b532 + 0.5*m.b344*m.b534 + 0.5*
m.b344*m.b548 + 0.5*m.b344*m.b592 + 0.5*m.b344*m.b593 + 0.5*m.b344*m.b596 + 0.5*m.b344*m.b597 +
0.5*m.b344*m.b598 + 0.5*m.b344*m.b599 + 0.5*m.b344*m.b600 + 0.5*m.b344*m.b612 + 0.5*m.b344*m.b617
+ 0.5*m.b344*m.b637 + 0.5*m.b344*m.b669 + 0.5*m.b345*m.b366 + m.b345*m.b406 + 0.5*m.b345*m.b413
+ 0.5*m.b345*m.b431 + 0.5*m.b345*m.b432 + 0.5*m.b345*m.b453 + 0.5*m.b345*m.b475 + 0.5*m.b345*
m.b507 + 0.5*m.b345*m.b519 + 0.5*m.b345*m.b533 + 0.5*m.b345*m.b535 + 0.5*m.b345*m.b545 + 0.5*
m.b345*m.b565 + 0.5*m.b345*m.b589 + 0.5*m.b345*m.b592 + 0.5*m.b345*m.b594 + 0.5*m.b345*m.b597 +
0.5*m.b345*m.b642 + 0.5*m.b345*m.b659 + 0.5*m.b345*m.b663 + 0.5*m.b346*m.b349 + 0.5*m.b346*m.b353
+ 0.5*m.b346*m.b367 + 0.5*m.b346*m.b368 + 0.5*m.b346*m.b379 + 0.5*m.b346*m.b385 + 0.5*m.b346*
m.b409 + 0.5*m.b346*m.b414 + 0.5*m.b346*m.b417 + 0.5*m.b346*m.b420 + 0.5*m.b346*m.b422 + 0.5*
m.b346*m.b441 + 0.5*m.b346*m.b455 + 0.5*m.b346*m.b460 + 0.5*m.b346*m.b466 + 0.5*m.b346*m.b473 +
0.5*m.b346*m.b476 + 0.5*m.b346*m.b486 + 0.5*m.b346*m.b487 + 0.5*m.b346*m.b494 + m.b346*m.b496 +
0.5*m.b346*m.b498 + 0.5*m.b346*m.b506 + 0.5*m.b346*m.b512 + 0.5*m.b346*m.b514 + 0.5*m.b346*m.b521
+ 0.5*m.b346*m.b523 + 0.5*m.b346*m.b527 + 0.5*m.b346*m.b529 + m.b346*m.b532 + m.b346*m.b534 +
0.5*m.b346*m.b539 + 0.5*m.b346*m.b540 + 0.5*m.b346*m.b560 + 0.5*m.b346*m.b584 + 0.5*m.b346*m.b593
+ 0.5*m.b346*m.b598 + 0.5*m.b346*m.b599 + 0.5*m.b346*m.b612 + m.b346*m.b617 + 0.5*m.b346*m.b649
+ 0.5*m.b347*m.b348 + 0.5*m.b347*m.b352 + 0.5*m.b347*m.b354 + 0.5*m.b347*m.b357 + m.b347*m.b362
+ 0.5*m.b347*m.b365 + m.b347*m.b371 + 0.5*m.b347*m.b399 + 0.5*m.b347*m.b410 + 0.5*m.b347*m.b411
+ 0.5*m.b347*m.b419 + 0.5*m.b347*m.b423 + 0.5*m.b347*m.b430 + 0.5*m.b347*m.b436 + 0.5*m.b347*
m.b456 + 0.5*m.b347*m.b461 + 0.5*m.b347*m.b470 + 0.5*m.b347*m.b472 + 0.5*m.b347*m.b474 + 0.5*
m.b347*m.b480 + 0.5*m.b347*m.b485 + 0.5*m.b347*m.b491 + 0.5*m.b347*m.b492 + 0.5*m.b347*m.b515 +
0.5*m.b347*m.b554 + m.b347*m.b555 + 0.5*m.b347*m.b558 + 0.5*m.b347*m.b582 + 0.5*m.b347*m.b587 +
0.5*m.b347*m.b603 + 0.5*m.b347*m.b608 + 0.5*m.b347*m.b614 + 0.5*m.b347*m.b619 + 0.5*m.b347*m.b628
+ 0.5*m.b347*m.b632 + 0.5*m.b347*m.b633 + 0.5*m.b347*m.b638 + 0.5*m.b347*m.b639 + 0.5*m.b347*
m.b645 + 0.5*m.b347*m.b646 + 0.5*m.b347*m.b657 + m.b347*m.b660 + 0.5*m.b347*m.b671 + 0.5*m.b347*
m.b677 + 0.5*m.b347*m.b678 + m.b347*m.x861 + 0.5*m.b348*m.b352 + 0.5*m.b348*m.b354 + 0.5*m.b348*
m.b357 + 0.5*m.b348*m.b362 + 0.5*m.b348*m.b365 + 0.5*m.b348*m.b371 + 0.5*m.b348*m.b410 + 0.5*
m.b348*m.b411 + m.b348*m.b430 + m.b348*m.b436 + 0.5*m.b348*m.b456 + 0.5*m.b348*m.b461 + 0.5*
m.b348*m.b470 + 0.5*m.b348*m.b472 + 0.5*m.b348*m.b474 + m.b348*m.b480 + 0.5*m.b348*m.b492 + 0.5*
m.b348*m.b515 + 0.5*m.b348*m.b555 + 0.5*m.b348*m.b582 + 0.5*m.b348*m.b614 + 0.5*m.b348*m.b619 +
0.5*m.b348*m.b632 + 0.5*m.b348*m.b633 + 0.5*m.b348*m.b645 + 0.5*m.b348*m.b657 + 0.5*m.b348*m.b660
+ 0.5*m.b348*m.b677 + m.b348*m.x855 + 0.5*m.b349*m.b367 + 0.5*m.b349*m.b368 + 0.5*m.b349*m.b379
+ 0.5*m.b349*m.b395 + 0.5*m.b349*m.b398 + 0.5*m.b349*m.b400 + 0.5*m.b349*m.b417 + 0.5*m.b349*
m.b421 + 0.5*m.b349*m.b438 + m.b349*m.b441 + 0.5*m.b349*m.b455 + m.b349*m.b460 + 0.5*m.b349*
m.b466 + 0.5*m.b349*m.b494 + 0.5*m.b349*m.b496 + 0.5*m.b349*m.b501 + 0.5*m.b349*m.b506 + 0.5*
m.b349*m.b514 + 0.5*m.b349*m.b521 + 0.5*m.b349*m.b523 + 0.5*m.b349*m.b532 + 0.5*m.b349*m.b534 +
0.5*m.b349*m.b538 + 0.5*m.b349*m.b541 + 0.5*m.b349*m.b550 + 0.5*m.b349*m.b593 + 0.5*m.b349*m.b598
+ m.b349*m.b599 + 0.5*m.b349*m.b604 + 0.5*m.b349*m.b606 + 0.5*m.b349*m.b612 + 0.5*m.b349*m.b617
+ 0.5*m.b350*m.b353 + m.b350*m.b364 + 0.5*m.b350*m.b366 + 0.5*m.b350*m.b378 + 0.5*m.b350*m.b384
+ 0.5*m.b350*m.b401 + 0.5*m.b350*m.b405 + 0.5*m.b350*m.b415 + 0.5*m.b350*m.b425 + 0.5*m.b350*
m.b429 + 0.5*m.b350*m.b432 + 0.5*m.b350*m.b433 + 0.5*m.b350*m.b439 + 0.5*m.b350*m.b455 + 0.5*
m.b350*m.b459 + 0.5*m.b350*m.b468 + 0.5*m.b350*m.b475 + 0.5*m.b350*m.b484 + 0.5*m.b350*m.b495 +
0.5*m.b350*m.b502 + 0.5*m.b350*m.b504 + 0.5*m.b350*m.b506 + 0.5*m.b350*m.b508 + 0.5*m.b350*m.b516
+ m.b350*m.b517 + 0.5*m.b350*m.b518 + 0.5*m.b350*m.b522 + 0.5*m.b350*m.b527 + 0.5*m.b350*m.b528
+ 0.5*m.b350*m.b543 + m.b350*m.b548 + 0.5*m.b350*m.b577 + 0.5*m.b350*m.b579 + 0.5*m.b350*m.b592
+ m.b350*m.b596 + 0.5*m.b350*m.b597 + 0.5*m.b350*m.b600 + 0.5*m.b350*m.b634 + 0.5*m.b350*m.b637
+ 0.5*m.b350*m.b640 + 0.5*m.b350*m.b649 + 0.5*m.b350*m.b654 + 0.5*m.b350*m.b655 + 0.5*m.b350*
m.b665 + 0.5*m.b350*m.b669 + 0.5*m.b350*m.b675 + 0.5*m.b351*m.b352 + 0.5*m.b351*m.b355 + 0.5*
m.b351*m.b365 + m.b351*m.b372 + 0.5*m.b351*m.b376 + 0.5*m.b351*m.b383 + 0.5*m.b351*m.b390 +
m.b351*m.b394 + 0.5*m.b351*m.b423 + 0.5*m.b351*m.b424 + 0.5*m.b351*m.b428 + 0.5*m.b351*m.b458 +
m.b351*m.b467 + 0.5*m.b351*m.b470 + 0.5*m.b351*m.b477 + 0.5*m.b351*m.b482 + 0.5*m.b351*m.b488 +
0.5*m.b351*m.b490 + 0.5*m.b351*m.b497 + 0.5*m.b351*m.b499 + 0.5*m.b351*m.b500 + 0.5*m.b351*m.b526
+ 0.5*m.b351*m.b530 + 0.5*m.b351*m.b531 + 0.5*m.b351*m.b562 + 0.5*m.b351*m.b566 + 0.5*m.b351*
m.b570 + 0.5*m.b351*m.b572 + 0.5*m.b351*m.b574 + 0.5*m.b351*m.b587 + 0.5*m.b351*m.b603 + 0.5*
m.b351*m.b605 + 0.5*m.b351*m.b608 + 0.5*m.b351*m.b623 + 0.5*m.b351*m.b628 + 0.5*m.b351*m.b664 +
0.5*m.b351*m.b670 + 0.5*m.b351*m.b673 + 0.5*m.b351*m.b674 + 0.5*m.b351*m.b676 + 0.5*m.b351*m.b677
+ 0.5*m.b351*m.b681 + m.b351*m.x854 + 0.5*m.b352*m.b354 + 0.5*m.b352*m.b357 + 0.5*m.b352*m.b362
+ m.b352*m.b365 + 0.5*m.b352*m.b371 + 0.5*m.b352*m.b372 + 0.5*m.b352*m.b394 + 0.5*m.b352*m.b410
+ 0.5*m.b352*m.b411 + 0.5*m.b352*m.b430 + 0.5*m.b352*m.b436 + 0.5*m.b352*m.b456 + 0.5*m.b352*
m.b461 + 0.5*m.b352*m.b467 + m.b352*m.b470 + 0.5*m.b352*m.b472 + 0.5*m.b352*m.b474 + 0.5*m.b352*
m.b480 + 0.5*m.b352*m.b492 + 0.5*m.b352*m.b515 + 0.5*m.b352*m.b555 + 0.5*m.b352*m.b582 + 0.5*
m.b352*m.b614 + 0.5*m.b352*m.b619 + 0.5*m.b352*m.b632 + 0.5*m.b352*m.b633 + 0.5*m.b352*m.b645 +
0.5*m.b352*m.b657 + 0.5*m.b352*m.b660 + m.b352*m.b677 + m.b352*m.x854 + 0.5*m.b353*m.b364 + 0.5*
m.b353*m.b378 + 0.5*m.b353*m.b384 + 0.5*m.b353*m.b385 + 0.5*m.b353*m.b401 + 0.5*m.b353*m.b405 +
0.5*m.b353*m.b409 + 0.5*m.b353*m.b414 + 0.5*m.b353*m.b415 + 0.5*m.b353*m.b420 + 0.5*m.b353*m.b422
+ 0.5*m.b353*m.b433 + 0.5*m.b353*m.b459 + 0.5*m.b353*m.b473 + 0.5*m.b353*m.b476 + 0.5*m.b353*
m.b486 + 0.5*m.b353*m.b487 + 0.5*m.b353*m.b495 + 0.5*m.b353*m.b496 + 0.5*m.b353*m.b498 + 0.5*
m.b353*m.b504 + 0.5*m.b353*m.b508 + 0.5*m.b353*m.b512 + 0.5*m.b353*m.b517 + 0.5*m.b353*m.b518 +
m.b353*m.b527 + 0.5*m.b353*m.b528 + 0.5*m.b353*m.b529 + 0.5*m.b353*m.b532 + 0.5*m.b353*m.b534 +
0.5*m.b353*m.b539 + 0.5*m.b353*m.b540 + 0.5*m.b353*m.b543 + 0.5*m.b353*m.b548 + 0.5*m.b353*m.b560
+ 0.5*m.b353*m.b577 + 0.5*m.b353*m.b579 + 0.5*m.b353*m.b584 + 0.5*m.b353*m.b596 + 0.5*m.b353*
m.b617 + 0.5*m.b353*m.b634 + 0.5*m.b353*m.b640 + m.b353*m.b649 + 0.5*m.b353*m.b654 + 0.5*m.b353*
m.b655 + 0.5*m.b353*m.b665 + 0.5*m.b353*m.b675 + 0.5*m.b354*m.b357 + 0.5*m.b354*m.b361 + 0.5*
m.b354*m.b362 + 0.5*m.b354*m.b365 + 0.5*m.b354*m.b371 + 0.5*m.b354*m.b410 + 0.5*m.b354*m.b411 +
0.5*m.b354*m.b430 + 0.5*m.b354*m.b436 + m.b354*m.b456 + 0.5*m.b354*m.b461 + 0.5*m.b354*m.b470 | |
<reponame>tatigabru/kaggle-lyft<filename>src/datasets/bev_dataset.py
"""
From Lyft Reference_model
"""
import glob
import os
import sys
sys.path.append('/home/user/challenges/lyft/lyft_repo/src')
import cv2
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.utils.data
from configs import DATA_ROOT, IMG_SIZE, NUM_CLASSES, OUTPUT_ROOT
from datasets.transforms import (albu_show_transforms, albu_valid_tansforms,
crop_d4_transforms)
from lyft_dataset_sdk.lyftdataset import LyftDataset
from lyft_dataset_sdk.utils.data_classes import (Box, LidarPointCloud,
Quaternion)
from lyft_dataset_sdk.utils.geometry_utils import transform_matrix, view_points
class BEVImageDataset(torch.utils.data.Dataset):
"""
Bird-eye-view dataset
Args:
fold: integer, number of the fold
df: Dataframe with sample tokens
debug: if True, runs the debugging on few images
img_size: the desired image size to resize to
input_dir: directory with imputs and targets (and maps, optionally)
transforms: augmentations (albumentations composed list))
"""
def __init__(self, fold: int, df: pd.DataFrame,
debug: bool, img_size: int,
input_dir: str, transforms = None):
super(BEVImageDataset, self).__init__() # inherit it from torch Dataset
self.fold = fold
self.df = df
self.debug = debug
self.img_size = img_size
self.input_dir = input_dir
self.transforms = transforms
if self.debug:
self.df = self.df.head(16)
print('Debug mode, samples: ', self.df.samples)
self.sample_tokens = list(self.df.samples)
def __len__(self):
return len(self.sample_tokens)
def __getitem__(self, idx):
sample_token = self.sample_tokens[idx]
input_filepath = '{}/{}_input.png'.format(self.input_dir, sample_token)
target_filepath = '{}/{}_target.png'.format(self.input_dir, sample_token)
im = cv2.imread(input_filepath, cv2.IMREAD_UNCHANGED)
#im = cv2.cvtColor(im, cv2.COLOR_BGR2RGB)
target = cv2.imread(target_filepath, cv2.IMREAD_UNCHANGED)
if self.transforms is not None:
augmented = self.transforms(image=im, mask=target)
im = augmented['image']
target = augmented['mask']
else:
im = cv2.resize(im, (self.img_size, self.img_size))
target = cv2.resize(target, (self.img_size, self.img_size), interpolation=cv2.INTER_NEAREST)
im = im.astype(np.float32)/255
target = target.astype(np.int64)
im = torch.from_numpy(im.transpose(2,0,1)) # channels first
target = torch.from_numpy(target) # single channel
return im, target, sample_token
class BEVLabelsDataset(torch.utils.data.Dataset):
"""
Bird-eye-view dataset with labels
for two headed models
Args:
df: Dataframe with sample tokens
debug: if True, runs the debugging on few images
img_size: the desired image size to resize to
input_dir: directory with imputs and targets (and maps, optionally)
num_classes: numbr of classes in classification head
transforms: augmentations (albumentations composed list))
"""
def __init__(self, df: pd.DataFrame,
debug: bool, img_size: int,
input_dir: str,
num_classes = NUM_CLASSES,
transforms = None):
super(BEVLabelsDataset, self).__init__() # inherit it from torch Dataset
self.df = df
self.debug = debug
self.img_size = img_size
self.input_dir = input_dir
self.num_classes = num_classes
self.transforms = transforms
if self.debug:
self.df = self.df.head(16)
print('Debug mode, samples: ', self.df.samples)
self.sample_tokens = list(self.df.samples)
def __len__(self):
return len(self.sample_tokens)
def __getitem__(self, idx):
sample_token = self.sample_tokens[idx]
input_filepath = '{}/{}_input.png'.format(self.input_dir, sample_token)
target_filepath = '{}/{}_target.png'.format(self.input_dir, sample_token)
im = cv2.imread(input_filepath, cv2.IMREAD_UNCHANGED)
#im = cv2.cvtColor(im, cv2.COLOR_BGR2RGB)
target = cv2.imread(target_filepath, cv2.IMREAD_UNCHANGED)
if self.transforms is not None:
augmented = self.transforms(image=im, mask=target)
im = augmented['image']
target = augmented['mask']
else:
im = cv2.resize(im, (self.img_size, self.img_size))
target = cv2.resize(target, (self.img_size, self.img_size), interpolation=cv2.INTER_NEAREST)
im = im.astype(np.float32)/255
target = target.astype(np.int64)
# get classes
img_classes = np.unique(target)
print(f'img_classes {img_classes}') # sorted unique elements
# make labels one-hot encoding, obey class 0
labels = torch.zeros(self.num_classes)
for cls in img_classes[1:]:
labels[int(cls)] = int(1)
im = torch.from_numpy(im.transpose(2,0,1)) # channels first
target = torch.from_numpy(target) # single channel
return im, target, labels, sample_token
class BEVMapsDataset(torch.utils.data.Dataset):
"""
Bird-eye-view dataset with maps
Args:
df: Dataframe with sample tokens
debug: if True, runs the debugging on few images
img_size: the desired image size to resize to
input_dir: directory with inputs and targets (and maps, optionally)
maps_dir: directory with input maps
num_classes: numbr of classes in classification head
transforms: augmentations (albumentations composed list))
"""
def __init__(self, df: pd.DataFrame,
debug: bool, img_size: int,
input_dir: str, maps_dir: str,
num_classes = NUM_CLASSES, transforms = None):
super(BEVMapsDataset, self).__init__() # inherit it from torch Dataset
self.df = df
self.debug = debug
self.img_size = img_size
self.input_dir = input_dir
self.maps_dir = maps_dir
self.num_classes = num_classes
self.transforms = transforms
if self.debug:
self.df = self.df.head(16)
print('Debug mode, samples: ', self.df.samples)
self.sample_tokens = list(self.df.samples)
def __len__(self):
return len(self.sample_tokens)
def __getitem__(self, idx):
sample_token = self.sample_tokens[idx]
input_filepath = '{}/{}_input.png'.format(self.input_dir, sample_token)
target_filepath = '{}/{}_target.png'.format(self.input_dir, sample_token)
map_filepath = '{}/{}_map.png'.format(self.maps_dir, sample_token)
im = cv2.imread(input_filepath, cv2.IMREAD_UNCHANGED)
#im = cv2.cvtColor(im, cv2.COLOR_BGR2RGB)
target = cv2.imread(target_filepath, cv2.IMREAD_UNCHANGED)
map_im = cv2.imread(map_filepath, cv2.IMREAD_UNCHANGED)
map_im = cv2.resize(map_im, (768, 768))
im = 2*im//3 + map_im//3 # as alternative, we can just add map overlay on image
if self.transforms is not None:
augmented = self.transforms(image=im, mask=target)
im = augmented['image']
target = augmented['mask']
im = cv2.resize(im, (self.img_size, self.img_size))
target = cv2.resize(target, (self.img_size, self.img_size), interpolation=cv2.INTER_NEAREST)
# print(im.shape, map_im.shape)
#im = np.concatenate((im, map_im), axis=2) # second option is concatenate
#im = im.astype(np.float32)/255
target = target.astype(np.int64)
# get classes
img_classes = np.unique(target)
print(f'img_classes {img_classes}')
# make labels one-hot encoding
labels = torch.zeros(num_classes)
for cls in img_classes[1:]:
labels[int(cls)] = int(1)
im = torch.from_numpy(im.transpose(2,0,1)) # channels first
target = torch.from_numpy(target) # single channel
return im, target, labels, sample_token
"""
TEST DATASETS
"""
class BEVTestDataset(torch.utils.data.Dataset):
"""
Bird-eye-view dataset, test
Args:
sample_tokens: list with sample tokens
debug: if True, runs the debugging on few images
img_size: the desired image size to resize to
input_dir: directory with imputs and targets (and maps, optionally)
transforms: augmentations (albumentations composed list))
"""
def __init__(self, sample_tokens: list,
debug: bool, img_size: int,
input_dir: str, transforms = None):
super(BEVTestDataset, self).__init__() # inherit it from torch Dataset
self.sample_tokens = sample_tokens
self.debug = debug
self.img_size = img_size
self.input_dir = input_dir
self.transforms = transforms
if self.debug:
self.sample_tokens = self.sample_tokens[:16]
print('Debug mode, samples: ', self.sample_tokens)
def __len__(self):
return len(self.sample_tokens)
def __getitem__(self, idx):
sample_token = self.sample_tokens[idx]
input_filepath = '{}/{}_input.png'.format(self.input_dir, sample_token)
im = cv2.imread(input_filepath, cv2.IMREAD_UNCHANGED)
#im = cv2.cvtColor(im, cv2.COLOR_BGR2RGB)
if self.transforms is not None:
augmented = self.transforms(image=im, mask=target)
im = augmented['image']
# in initial version we had extra resize and normalisation
im = cv2.resize(im, (self.img_size, self.img_size))
im = im.astype(np.float32)/255
im = torch.from_numpy(im.transpose(2,0,1)) # channels first
return im, sample_token
class BEVMapsTestDataset(torch.utils.data.Dataset):
"""
Bird-eye-view dataset with maps, test data
Args:
df: Dataframe with sample tokens
debug: if True, runs the debugging on few images
img_size: the desired image size to resize to
input_dir: directory with inputs and targets (and maps, optionally)
maps_dir: directory with input maps
num_classes: numbr of classes in classification head
transforms: augmentations (albumentations composed list))
"""
def __init__(self, df: pd.DataFrame,
debug: bool, img_size: int,
input_dir: str, maps_dir: str,
num_classes = NUM_CLASSES, transforms = None):
super(BEVMapsTestDataset, self).__init__() # inherit it from torch Dataset
self.df = df
self.debug = debug
self.img_size = img_size
self.input_dir = input_dir
self.maps_dir = maps_dir
self.num_classes = num_classes
self.transforms = transforms
if self.debug:
self.df = self.df.head(16)
print('Debug mode, samples: ', self.df.samples)
self.sample_tokens = list(self.df.samples)
def __len__(self):
return len(self.sample_tokens)
def __getitem__(self, idx):
sample_token = self.sample_tokens[idx]
input_filepath = '{}/{}_input.png'.format(self.input_dir, sample_token)
map_filepath = '{}/{}_map.png'.format(self.maps_dir, sample_token)
im = cv2.imread(input_filepath, cv2.IMREAD_UNCHANGED)
#im = cv2.cvtColor(im, cv2.COLOR_BGR2RGB)
map_im = cv2.imread(map_filepath, cv2.IMREAD_UNCHANGED)
map_im = cv2.resize(map_im, (768, 768))
im = 2*im//3 + map_im//3 # as alternative, we can just add map overlay on image
if self.transforms is not None:
augmented = self.transforms(image=im, mask=target)
im = augmented['image']
target = augmented['mask']
im = cv2.resize(im, (self.img_size, self.img_size))
# print(im.shape, map_im.shape)
#im = np.concatenate((im, map_im), axis=2) # second option is concatenate
#im = im.astype(np.float32)/255
im = torch.from_numpy(im.transpose(2,0,1)) # channels first
return im, sample_token
def visualize_lidar_of_sample(level5data, sample_token: str, axes_limit=80):
"""Helper to visualize sample lidar data"""
sample = level5data.get("sample", sample_token)
sample_lidar_token = sample["data"]["LIDAR_TOP"]
level5data.render_sample_data(sample_lidar_token, axes_limit=axes_limit)
def plot_img_target(im: torch.Tensor, target: torch.Tensor, sample_token = None, fig_num = 1):
"""Helper to plot imag eand target"""
im = im.numpy()
im =np.rint(im*255)
target = target.numpy()
target_as_rgb = np.repeat(target[...,None], 3, 2) # repeat array for three channels
plt.figure(fig_num, figsize=(16,8))
# Transpose the input volume CXY to XYC order, which is what matplotlib requires.
plt.imshow(np.hstack((im.transpose(1,2,0)[...,:3], target_as_rgb)))
plt.title(sample_token)
plt.show()
def test_dataset_augs(train_df: pd.DataFrame, data_folder: str):
"""Helper to test data augmentations"""
train_dataset = BEVImageDataset(fold=0, df=train_df,
debug=True, img_size=IMG_SIZE, | |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright (C) 2012 <NAME> <<EMAIL>>
# Licensed under the GNU LGPL v2.1 - http://www.gnu.org/licenses/lgpl.html
#
# HDP inference code is adapted from the onlinehdp.py script by
# <NAME> (chongw at cs.princeton.edu).
# http://www.cs.princeton.edu/~chongw/software/onlinehdp.tar.gz
#
"""Module for `online Hierarchical Dirichlet Processing
<http://jmlr.csail.mit.edu/proceedings/papers/v15/wang11a/wang11a.pdf>`_.
The core estimation code is directly adapted from the `blei-lab/online-hdp <https://github.com/blei-lab/online-hdp>`_
from `<NAME>: "Online Variational Inference for the Hierarchical Dirichlet Process", JMLR (2011)
<http://jmlr.csail.mit.edu/proceedings/papers/v15/wang11a/wang11a.pdf>`_.
Examples
--------
Train :class:`~gensim.models.hdpmodel.HdpModel`
.. sourcecode:: pycon
>>> from gensim.test.utils import common_corpus, common_dictionary
>>> from gensim.models import HdpModel
>>>
>>> hdp = HdpModel(common_corpus, common_dictionary)
You can then infer topic distributions on new, unseen documents, with
.. sourcecode:: pycon
>>> unseen_document = [(1, 3.), (2, 4)]
>>> doc_hdp = hdp[unseen_document]
To print 20 topics with top 10 most probable words.
.. sourcecode:: pycon
>>> topic_info = hdp.print_topics(num_topics=20, num_words=10)
The model can be updated (trained) with new documents via
.. sourcecode:: pycon
>>> hdp.update([[(1, 2)], [(1, 1), (4, 5)]])
"""
from __future__ import with_statement
import logging
import time
import warnings
import numpy as np
from scipy.special import gammaln, psi # gamma function utils
from six.moves import zip, range
from gensim import interfaces, utils, matutils
from gensim.matutils import dirichlet_expectation, mean_absolute_difference
from gensim.models import basemodel, ldamodel
from gensim.utils import deprecated
logger = logging.getLogger(__name__)
meanchangethresh = 0.00001
rhot_bound = 0.0
def expect_log_sticks(sticks):
r"""For stick-breaking hdp, get the :math:`\mathbb{E}[log(sticks)]`.
Parameters
----------
sticks : numpy.ndarray
Array of values for stick.
Returns
-------
numpy.ndarray
Computed :math:`\mathbb{E}[log(sticks)]`.
"""
dig_sum = psi(np.sum(sticks, 0))
ElogW = psi(sticks[0]) - dig_sum
Elog1_W = psi(sticks[1]) - dig_sum
n = len(sticks[0]) + 1
Elogsticks = np.zeros(n)
Elogsticks[0: n - 1] = ElogW
Elogsticks[1:] = Elogsticks[1:] + np.cumsum(Elog1_W)
return Elogsticks
def lda_e_step(doc_word_ids, doc_word_counts, alpha, beta, max_iter=100):
r"""Performs EM-iteration on a single document for calculation of likelihood for a maximum iteration of `max_iter`.
Parameters
----------
doc_word_ids : int
Id of corresponding words in a document.
doc_word_counts : int
Count of words in a single document.
alpha : numpy.ndarray
Lda equivalent value of alpha.
beta : numpy.ndarray
Lda equivalent value of beta.
max_iter : int, optional
Maximum number of times the expectation will be maximised.
Returns
-------
(numpy.ndarray, numpy.ndarray)
Computed (:math:`likelihood`, :math:`\gamma`).
"""
gamma = np.ones(len(alpha))
expElogtheta = np.exp(dirichlet_expectation(gamma))
betad = beta[:, doc_word_ids]
phinorm = np.dot(expElogtheta, betad) + 1e-100
counts = np.array(doc_word_counts)
for _ in range(max_iter):
lastgamma = gamma
gamma = alpha + expElogtheta * np.dot(counts / phinorm, betad.T)
Elogtheta = dirichlet_expectation(gamma)
expElogtheta = np.exp(Elogtheta)
phinorm = np.dot(expElogtheta, betad) + 1e-100
meanchange = mean_absolute_difference(gamma, lastgamma)
if meanchange < meanchangethresh:
break
likelihood = np.sum(counts * np.log(phinorm))
likelihood += np.sum((alpha - gamma) * Elogtheta)
likelihood += np.sum(gammaln(gamma) - gammaln(alpha))
likelihood += gammaln(np.sum(alpha)) - gammaln(np.sum(gamma))
return likelihood, gamma
class SuffStats(object):
"""Stores sufficient statistics for the current chunk of document(s) whenever Hdp model is updated with new corpus.
These stats are used when updating lambda and top level sticks. The statistics include number of documents in the
chunk, length of words in the documents and top level truncation level.
"""
def __init__(self, T, Wt, Dt):
"""
Parameters
----------
T : int
Top level truncation level.
Wt : int
Length of words in the documents.
Dt : int
Chunk size.
"""
self.m_chunksize = Dt
self.m_var_sticks_ss = np.zeros(T)
self.m_var_beta_ss = np.zeros((T, Wt))
def set_zero(self):
"""Fill the sticks and beta array with 0 scalar value."""
self.m_var_sticks_ss.fill(0.0)
self.m_var_beta_ss.fill(0.0)
class HdpModel(interfaces.TransformationABC, basemodel.BaseTopicModel):
r"""`Hierarchical Dirichlet Process model <http://jmlr.csail.mit.edu/proceedings/papers/v15/wang11a/wang11a.pdf>`_
Topic models promise to help summarize and organize large archives of texts that cannot be easily analyzed by hand.
Hierarchical Dirichlet process (HDP) is a powerful mixed-membership model for the unsupervised analysis of grouped
data. Unlike its finite counterpart, latent Dirichlet allocation, the HDP topic model infers the number of topics
from the data. Here we have used Online HDP, which provides the speed of online variational Bayes with the modeling
flexibility of the HDP. The idea behind Online variational Bayes in general is to optimize the variational
objective function with stochastic optimization.The challenge we face is that the existing coordinate ascent
variational Bayes algorithms for the HDP require complicated approximation methods or numerical optimization. This
model utilises stick breaking construction of Hdp which enables it to allow for coordinate-ascent variational Bayes
without numerical approximation.
**Stick breaking construction**
To understand the HDP model we need to understand how it is modelled using the stick breaking construction. A very
good analogy to understand the stick breaking construction is `chinese restaurant franchise
<https://www.cs.princeton.edu/courses/archive/fall07/cos597C/scribe/20070921.pdf>`_.
For this assume that there is a restaurant franchise (`corpus`) which has a large number of restaurants
(`documents`, `j`) under it. They have a global menu of dishes (`topics`, :math:`\Phi_{k}`) which they serve.
Also, a single dish (`topic`, :math:`\Phi_{k}`) is only served at a single table `t` for all the customers
(`words`, :math:`\theta_{j,i}`) who sit at that table.
So, when a customer enters the restaurant he/she has the choice to make where he/she wants to sit.
He/she can choose to sit at a table where some customers are already sitting , or he/she can choose to sit
at a new table. Here the probability of choosing each option is not same.
Now, in this the global menu of dishes correspond to the global atoms :math:`\Phi_{k}`, and each restaurant
correspond to a single document `j`. So the number of dishes served in a particular restaurant correspond to the
number of topics in a particular document. And the number of people sitting at each table correspond to the number
of words belonging to each topic inside the document `j`.
Now, coming on to the stick breaking construction, the concept understood from the chinese restaurant franchise is
easily carried over to the stick breaking construction for hdp (`"Figure 1" from "Online Variational Inference
for the Hierarchical Dirichlet Process" <http://proceedings.mlr.press/v15/wang11a/wang11a.pdf>`_).
A two level hierarchical dirichlet process is a collection of dirichlet processes :math:`G_{j}` , one for each
group, which share a base distribution :math:`G_{0}`, which is also a dirichlet process. Also, all :math:`G_{j}`
share the same set of atoms, :math:`\Phi_{k}`, and only the atom weights :math:`\pi _{jt}` differs.
There will be multiple document-level atoms :math:`\psi_{jt}` which map to the same corpus-level atom
:math:`\Phi_{k}`. Here, the :math:`\beta` signify the weights given to each of the topics globally. Also, each
factor :math:`\theta_{j,i}` is distributed according to :math:`G_{j}`, i.e., it takes on the value of
:math:`\Phi_{k}` with probability :math:`\pi _{jt}`. :math:`C_{j,t}` is an indicator variable whose value `k`
signifies the index of :math:`\Phi`. This helps to map :math:`\psi_{jt}` to :math:`\Phi_{k}`.
The top level (`corpus` level) stick proportions correspond the values of :math:`\beta`,
bottom level (`document` level) stick proportions correspond to the values of :math:`\pi`.
The truncation level for the corpus (`K`) and document (`T`) corresponds to the number of :math:`\beta`
and :math:`\pi` which are in existence.
Now, whenever coordinate ascent updates are to be performed, they happen at two level. The document level as well
as corpus level.
At document level, we update the following:
#. The parameters to the document level sticks, i.e, a and b parameters of :math:`\beta` distribution of the
variable :math:`\pi _{jt}`.
#. The parameters to per word topic indicators, :math:`Z_{j,n}`. Here :math:`Z_{j,n}` selects topic parameter
:math:`\psi_{jt}`.
#. The parameters to per document topic indices :math:`\Phi_{jtk}`.
At corpus level, we update the following:
#. The parameters to the top level sticks, i.e., the parameters of the :math:`\beta` distribution for the
corpus level :math:`\beta`, which signify the topic distribution at corpus level.
#. The parameters to the topics :math:`\Phi_{k}`.
Now coming on to the steps involved, procedure for online variational inference for the Hdp model is as follows:
1. We initialise the corpus level parameters, topic parameters randomly and set current time to 1.
2. Fetch a random document j from the corpus.
3. Compute all the parameters required for document level updates.
4. Compute natural gradients of corpus level parameters.
5. Initialise the learning rate as a function of kappa, tau and current time. Also, increment current time by 1
each time it reaches this step.
6. Update corpus level parameters.
Repeat 2 to 6 until stopping condition is not met.
| |
<filename>venv/Lib/site-packages/pyo/lib/mmlmusic.py
"""
Music Macro Language evaluator.
The MML object implements acustom MML evaluator to allow simple and efficient
music composition within pyo. The language's rules are explained below.
The MML object generates triggers on new notes with additional streams to
handle frequency, amplitude, duration and custom parameters. See the object
documentation for more details.
API documentation
=================
- The space separates the tokens in a music sequence (a token can be a note value,
an amplitude control, a tempo statement, etc.).
Pre-Processing on music text
----------------------------
- A comment starts with a semicolon ( ; ) and ends at the end of the line. This
text will be removed before starting to evaluate the sequences.
- A musical voice is represented by a single line of code.
- We can break a long line into multiple short lines with the backslash ( \ ).
- The symbol equal ( = ), preceded by a variable name in UPPER CASE, creates a
macro. The remaining part of the line is the macro body. Anywhere the
pre-processor finds the variable name in the music, it will be replaced by the
macro's body.
Realtime Processing of the music
--------------------------------
- The letters `a` to `g` correspond to the musical pitches and cause the
corresponding note to be played.
- Sharp notes are produced by appending a `+` to the pitch value, and flat notes
by appending a `-` to the pitch value.
- The length of a note is specified by an integer following the note name. If a
note doesn't have a duration, the last specified duration is used. Default
duration is the Sixteenth note. Length values are:
- 0 = Thirty-second note
- 1 = Sixteenth note
- 2 = Dotted sixteenth note
- 3 = Eighth note
- 4 = Dotted eighth note
- 5 = Quarter note
- 6 = Dotted quarter note
- 7 = Half note
- 8 = Dotted half note
- 9 = Whole note
- The letter `r` corresponds to a rest. The length of the rest is specified in
the same manner as the length of a note.
- Notes surrounded by brakets ( `(` and `)` ) act as tuplet. Tuplet length is specified
just after the closing bracket using the same values as for a note duration. Length of
each note in tuplet will evenly be <note length of tuplet> / <count of notes in tuplet>.
If not specified, tuplet duration defaults to 5 (quarter note).
- The letter `o`, followed by a number, selects the octave the instrument will play in.
If the letter `o` is followed by the symbol `+`, the octave steps up by one. If followed
by the symbol `-`, the octave steps down by one. If a number follows the symbol `+` or `-`,
the octave steps up or down by the given amount of octaves.
- The letter `t`, followed by a number, sets the tempo in beats-per-minute.
If the letter `t` is followed by the symbol `+`, the tempo increases by one. If followed
by the symbol `-`, the tempo decreases by one. If a number follows the symbol `+` or `-`,
the tempo increases or decreases by the given amount of BPM.
- The letter `v`, followed by a number between 0 and 100, sets the volume for the following
notes. If the letter `v` is followed by the symbol `+`, the volume increases by one. If
followed by the symbol `-`, the volume decreases by one. If a number follows the symbol
`+` or `-`, the volume increases or decreases by the given amount.
- The symbol #, followed by a number indicates the voice number for the line. This should be
the first token of a line. If missing, the line defaults to voice number 0.
- The letters `x`, `y` an `z`, followed by a real number, are user-defined parameters. They
can be used to control specific parameters of the synthesizer.
If the letter is followed by the symbol `+`, the value increases by 0.01. If followed
by the symbol `-`, the value decreases by 0.01. If a number follows the symbol `+` or `-`,
the value increases or decreases by the given amount.
- Random choice within a set of values can be done with the ? symbol, followed by the
possible values inside square brackets.
Ex. ?[c e g b-] ; the note is a random choice between c e g and b-.
- Random choice between a range can be done with the ? symbol, followed by the range inside
curly brackets. If two values are presents, they are the minimum and maximum of the range.
If there is only one value, the range is 0 to this value and if the brackets are empty, the
range is 0 to 1.
Ex. v?{40 70} ; volume is set randomly between 40 and 70.
- The symbol |: starts a looped segment and the symbol :| ends it. A number right after the
last symbol indicates how many loops to perform. If missing, the number of loops is two (the
first pass + one repetition). It is possible to use loops inside other loops. There is no
limit to the number of levels of loop embedding.
"""
from __future__ import division
from __future__ import print_function
from __future__ import absolute_import
"""
Copyright 2009-2020 <NAME>
This file is part of pyo, a python module to help digital signal
processing script creation.
pyo 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.
pyo 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.
You should have received a copy of the GNU Lesser General Public
License along with pyo. If not, see <http://www.gnu.org/licenses/>.
"""
from ._core import *
from ._maps import *
from ._widgets import createMMLEditorWindow
### MML framework ###
#####################
VALID_NOTES = "abcdefgr?"
VALID_PARAMS = "xyz"
VALID_DIGITS = "0123456789"
VALID_SPACES = " \t\n"
VALID_CHARS = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789?"
MACRO_DELIMITERS = "0123456789abcdefgrxyz?()[]{}.|: \t\n"
class MMLParser:
def __init__(self, text, voices=1):
self.text = text
self.voices = voices
def _remove_comments(self, text):
pos = text.find(";")
while pos != -1:
pos2 = text.find("\n", pos + 1)
if pos2 == -1:
text = text[:pos]
else:
text = text[:pos] + text[pos2 + 1 :]
pos = text.find(";")
return text
def _split_tuplets(self, text):
l = []
text = text.strip()
inside = False
rescan = True
start = 0
for i in range(len(text)):
if text[i] == " " and not inside:
if text[start:i]:
l.append(text[start:i].strip())
start = i
rescan = True
elif text[i] == "[":
inside = True
elif text[i] == "]":
inside = False
if i == len(text) - 1 and text[start:]:
l.append(text[start:].strip())
elif i == len(text) - 1:
if text[start:]:
l.append(text[start:].strip())
elif rescan and text[i] != " ":
rescan = False
start = i
return l
def _expand_tuplets(self, text):
pos = text.find("(")
while pos != -1:
nextpos = text.find("(", pos + 1)
pos2 = text.find(")", pos + 1)
if pos2 == -1:
# missing end brace, just ignore the tuplet.
text = text[:pos] + text[pos + 1 :]
elif nextpos != -1 and nextpos < pos2:
# missing end brace, just ignore the tuplet.
text = text[:pos] + text[pos + 1 :]
else:
durchar = text[pos2 + 1]
if durchar in VALID_DIGITS:
duration = int(durchar)
else:
duration = 5 # default tuplet duration is the quarter note.
tmp_eles = self._split_tuplets(text[pos + 1 : pos2])
elements = []
for ele in tmp_eles:
if ele[0] in VALID_NOTES:
elements.append("%s%i" % (ele, duration))
else:
elements.append(ele)
# count only note elements.
num_eles = len([e for e in elements if e[0] in VALID_NOTES])
ele_text = " ".join(elements)
ele_div = " /%i " % num_eles
text = text[:pos] + ele_div + ele_text + " /1 " + text[pos2 + 2 | |
<gh_stars>1-10
"""Exact distributions covariance tools module.
The functions in the module do small repetitive tasks, that are used along the
whole implementation. These tools improve the way the tasks are standardized
in the modules that use them.
This script requires the following modules:
* os
* pickle
* typing
* matplotlib
* numpy
* scipy
The module contains the following functions:
* save_data - saves computed data.
* save_plot - saves figures.
* function_header_print_data - prints info about the function running.
* function_header_print_plot - prints info about the plot.
* start_folders - creates folders to save data and plots.
* initial_message - prints the initial message with basic information.
* gaussian_distribution - computes gaussian distribution values.
* pdf_gaussian_gaussian - computes the one dimensional Gaussian-Gaussian
PDF.
* pdf_gaussian_algebraic - computes the one dimensional Gaussian-Algebraic
PDF.
* pdf_algebraic_gaussian - computes the one dimensional Algebraic-Gaussian
PDF.
* pdf_algebraic_algebraic - computes the one dimensional
Algebraic-Algebraic PDF.
* main - the main function of the script.
.. moduleauthor:: <NAME> <www.github.com/juanhenao21>
"""
# -----------------------------------------------------------------------------
# Modules
import os
import pickle
from typing import Any, List
from matplotlib import pyplot as plt # type: ignore
import numpy as np # type: ignore
# Gamma function
from scipy.special import gamma # type: ignore
# Modified Bessel function of the second kind of real order v
from scipy.special import kv # type: ignore
# Gauss hypergeometric function 2F1(a, b; c; z)
from scipy.special import hyp2f1 # type: ignore
# Confluent hypergeometric function U
from scipy.special import hyperu # type: ignore
# -----------------------------------------------------------------------------
def save_data(data: Any, function_name: str, dates: List[str], time_step: str) -> None:
"""Saves computed data in pickle files.
Saves the data generated in the functions of the
exact_distributions_covariance_analysis module in pickle files.
:param data: data to be saved. The data can be of different types.
:param function_name: name of the function that generates the plot.
:param dates: List of the interval of dates to be analyzed
(i.e. ['1980-01', '2020-12']).
:param time_step: time step of the data (i.e. '1m', '2m', '5m', ...).
:return: None -- The function saves the data in a file and does not return
a value.
"""
# Saving data
pickle.dump(
data,
open(
f"../data/exact_distributions_covariance/{function_name}_{dates[0]}"
+ f"_{dates[1]}_step_{time_step}.pickle",
"wb",
),
protocol=4,
)
print("Data Saved")
print()
# -----------------------------------------------------------------------------
def save_plot(
figure: plt.Figure, function_name: str, dates: List[str], time_step: str
) -> None:
"""Saves plot in png files.
Saves the plot generated in the functions of the
exact_distributions_covariance_analysis module in png files.
:param figure: figure object that is going to be save.
:param function_name: name of the function that generates the plot.
:param dates: List of the interval of dates to be analyzed
(i.e. ['1980-01', '2020-12']).
:param time_step: time step of the data (i.e. '1m', '2m', '5m', ...).
:return: None -- The function save the plot in a file and does not return
a value.
"""
# Saving plot data
figure.savefig(
f"../plot/exact_distributions_covariance/{function_name}"
+ f"_{dates[0]}_{dates[1]}_step_{time_step}.png"
)
print("Plot Saved")
print()
# -----------------------------------------------------------------------------
def function_header_print_data(
function_name: str, dates: List[str], time_step: str
) -> None:
"""Prints a header of a function that generates data when it is running.
:param function_name: name of the function that generates the data.
:param dates: List of the interval of dates to be analyzed
(i.e. ['1980-01', '2020-12']).
:param time_step: time step of the data (i.e. '1m', '2m', '5m', ...).
:return: None -- The function prints a message and does not return a
value.
"""
print("Exact Distributions")
print(function_name)
print(
"Computing the results of the data in the interval time from the "
+ f"years {dates[0]} to {dates[1]} in time steps of {time_step}"
)
print()
# -----------------------------------------------------------------------------
def function_header_print_plot(
function_name: str, dates: List[str], time_step: str
) -> None:
"""Prints a header of a function that generates a plot when it is running.
:param function_name: name of the function that generates the data.
:param dates: List of the interval of dates to be analyzed
(i.e. ['1980-01', '2020-12']).
:param time_step: time step of the data (i.e. '1m', '2m', '5m', ...).
:return: None -- The function prints a message and does not return a
value.
"""
print("Exact Distributions")
print(function_name)
print(
"Computing the plots of the data in the interval time from the "
+ f"years {dates[0]} to {dates[1]} in time steps of {time_step}"
)
print()
# -----------------------------------------------------------------------------
def start_folders() -> None:
"""Creates the initial folders to save the data and plots.
:return: None -- The function creates folders and does not return a value.
"""
try:
os.mkdir("../data/exact_distributions_covariance")
os.mkdir("../plot/exact_distributions_covariance")
print("Folder to save data created")
print()
except FileExistsError as error:
print("Folder exists. The folder was not created")
print(error)
print()
# -----------------------------------------------------------------------------
def initial_message() -> None:
"""Prints the initial message with basic information.
:return: None -- The function prints a message and does not return a value.
"""
print()
print("###################")
print("Exact Distributions")
print("###################")
print("AG Guhr")
print("Faculty of Physics")
print("University of Duisburg-Essen")
print("Author: <NAME>")
print("More information in:")
print("* https://juanhenao21.github.io/")
print("* https://github.com/juanhenao21/exact_distributions")
# print('* https://forex-response_spread-year.readthedocs.io/en/latest/')
print()
# -----------------------------------------------------------------------------
def gaussian_distribution(
mean: float, variance: float, x_values: np.ndarray
) -> np.ndarray:
"""Computes the Gaussian distribution values.
:param mean: mean of the Gaussian distribution.
:param variance: variance of the Gaussian distribution.
:param x: array of the values to compute the Gaussian
distribution
"""
return (1 / (2 * np.pi * variance) ** 0.5) * np.exp(
-((x_values - mean) ** 2) / (2 * variance)
)
# -----------------------------------------------------------------------------
def pdf_gaussian_gaussian(returns: np.ndarray, N: float, Lambda: float) -> np.ndarray:
"""Computes the one dimensional Gaussian-Gaussian PDF.
:param returns: numpy array with the returns values.
:param N: strength of the fluctuations around the mean.
:param Lambda: variance of the returns.
:return: numpy array with the pdf values.
"""
first_part: np.float = 1 / (
2 ** ((N - 1) / 2) * gamma(N / 2) * np.sqrt((np.pi * Lambda) / N)
)
second_part: np.ndarray = np.sqrt((N * returns ** 2) / Lambda) ** ((N - 1) / 2)
third_part: np.ndarray = kv((1 - N) / 2, np.sqrt(N * returns ** 2) / Lambda)
return first_part * second_part * third_part
# -----------------------------------------------------------------------------
def pdf_gaussian_algebraic(
returns: np.ndarray, K: float, L: float, N: float, Lambda: float
) -> np.ndarray:
"""Computes de one dimensional Gaussian-Algebraic PDF.
:param returns: numpy array with the returns values.
:param K: number of companies.
:param L: shape parameter.
:param N: strength of the fluctuations around the mean.
:param Lambda: variance of the returns.
:return: numpy array with the pdf values.
"""
M: np.float = 2 * L - K - N - 1
numerator: np.float = gamma(L - (K + N) / 2 + 1) * gamma(L - (K - 1) / 2)
denominator: np.float = (
gamma(L - (K + N - 1) / 2) * gamma(N / 2) * np.sqrt(2 * np.pi * Lambda * M / N)
)
frac: np.float = numerator / denominator
function: np.ndarray = hyperu(
L - (K + N) / 2 + 1, (1 - N) / 2 + 1, (N * returns ** 2) / (2 * M * Lambda)
)
return frac * function
# -----------------------------------------------------------------------------
def pdf_algebraic_gaussian(
returns: np.ndarray, K: float, l: float, N: float, Lambda: float
) -> np.ndarray:
"""Computes de one dimensional Algebraic-Gaussian PDF.
:param returns: numpy array with the returns values.
:param K: number of companies.
:param l: shape parameter.
:param N: strength of the fluctuations around the mean.
:param Lambda: variance of the returns.
:return: numpy array with the pdf values.
"""
m: np.float = 2 * l - K - 2
numerator: np.float = gamma(l - (K - 1) / 2) * gamma(l - (K - N) / 2)
denominator: np.float = (
gamma(l - K / 2) * gamma(N / 2) * np.sqrt(2 * np.pi * Lambda * m / N)
)
frac: np.float = numerator / denominator
function: np.ndarray = hyperu(
l - (K - 1) / 2, (1 - N) / 2 + 1, (N * returns ** 2) / (2 * m * Lambda)
)
return frac * function
# -----------------------------------------------------------------------------
def pdf_algebraic_algebraic(
returns: np.ndarray, K: float, L: float, l: float, N: float, Lambda: float
) -> np.ndarray:
"""Computes de one dimensional Algebraic-Algebraic PDF.
:param returns: numpy array with the returns values.
:param K: number of companies.
:param L: shape | |
<gh_stars>0
# ############################################################################
#
# Copyright (c) Microsoft Corporation.
#
# This source code is subject to terms and conditions of the Apache License, Version 2.0. A
# copy of the license can be found in the License.html file at the root of this distribution. If
# you cannot locate the Apache License, Version 2.0, please send an email to
# <EMAIL>. By using this source code in any fashion, you are agreeing to be bound
# by the terms of the Apache License, Version 2.0.
#
# You must not remove this notice, or any other, from this software.
#
# ###########################################################################
import re
import sys
import types
import PythonScraper
try:
import thread
except:
import _thread as thread
try:
import __builtin__ as __builtins__
except ImportError:
import builtins as __builtins__
def safe_dir(obj):
try:
return frozenset(obj.__dict__) | frozenset(dir(obj))
except:
# Some types crash when we access __dict__ and/or dir()
pass
try:
return frozenset(dir(obj))
except:
pass
try:
return frozenset(obj.__dict__)
except:
pass
return frozenset()
def builtins_keys():
if isinstance(__builtins__, dict):
return __builtins__.keys()
return dir(__builtins__)
def get_builtin(name):
if isinstance(__builtins__, dict):
return __builtins__[name]
return getattr(__builtins__, name)
safe_getattr = PythonScraper.safe_getattr
BUILTIN_TYPES = [type_name for type_name in builtins_keys() if type(get_builtin(type_name)) is type]
if sys.version_info[0] >= 3:
BUILTIN = 'builtins'
unicode = str
else:
BUILTIN = '__builtin__'
TYPE_OVERRIDES = {
'string': PythonScraper.type_to_typeref(types.CodeType),
's': PythonScraper.type_to_typeref(str),
'integer': PythonScraper.type_to_typeref(int),
'boolean': PythonScraper.type_to_typeref(bool),
'number': PythonScraper.type_to_typeref(int),
'pid': PythonScraper.type_to_typeref(int),
'ppid': PythonScraper.type_to_typeref(int),
'fd': PythonScraper.type_to_typeref(int),
'handle': PythonScraper.type_to_typeref(int),
'Exit': PythonScraper.type_to_typeref(int),
'fd2': PythonScraper.type_to_typeref(int),
'Integral': PythonScraper.type_to_typeref(int),
'exit_status':PythonScraper.type_to_typeref(int),
'old_mask': PythonScraper.type_to_typeref(int),
'source': PythonScraper.type_to_typeref(str),
'newpos': PythonScraper.type_to_typeref(int),
'key': PythonScraper.type_to_typeref(str),
'dictionary': PythonScraper.type_to_typeref(dict),
'None': PythonScraper.type_to_typeref(type(None)),
'floating': PythonScraper.type_to_typeref(float),
'filename': PythonScraper.type_to_typeref(str),
'path': PythonScraper.type_to_typeref(str),
'byteswritten': PythonScraper.type_to_typeref(int),
'unicode': PythonScraper.type_to_typeref(unicode),
'Unicode': PythonScraper.type_to_typeref(unicode),
'True': PythonScraper.type_to_typeref(bool),
'False': PythonScraper.type_to_typeref(bool),
'lock': PythonScraper.type_to_typeref(thread.LockType),
'code': PythonScraper.type_to_typeref(types.CodeType),
'module': PythonScraper.type_to_typeref(types.ModuleType),
'size': PythonScraper.type_to_typeref(int),
'INT': PythonScraper.type_to_typeref(int),
'STRING': PythonScraper.type_to_typeref(str),
'TUPLE': PythonScraper.type_to_typeref(tuple),
'OBJECT': PythonScraper.type_to_typeref(object),
'LIST': PythonScraper.type_to_typeref(list),
'DICT': PythonScraper.type_to_typeref(dict),
'char *': PythonScraper.type_to_typeref(str),
'wchar_t *': PythonScraper.type_to_typeref(unicode),
'CHAR *': PythonScraper.type_to_typeref(str),
'TCHAR *': PythonScraper.type_to_typeref(str),
'WCHAR *': PythonScraper.type_to_typeref(unicode),
'LPSTR': PythonScraper.type_to_typeref(str),
'LPCSTR': PythonScraper.type_to_typeref(str),
'LPTSTR': PythonScraper.type_to_typeref(str),
'LPCTSTR': PythonScraper.type_to_typeref(str),
'LPWSTR': PythonScraper.type_to_typeref(unicode),
'LPCWSTR': PythonScraper.type_to_typeref(unicode),
}
try:
TYPE_OVERRIDES['file object'] = PythonScraper.type_to_typeref(file)
except NameError:
try:
import _io
TYPE_OVERRIDES['file object'] = PythonScraper.type_to_typeref(_io._IOBase)
except (NameError, ImportError):
pass
RETURN_TYPE_OVERRIDES = dict(TYPE_OVERRIDES)
RETURN_TYPE_OVERRIDES.update({'string': PythonScraper.type_to_typeref(str)})
def type_name_to_typeref(name, mod, type_overrides = TYPE_OVERRIDES):
arg_type = type_overrides.get(name, None)
if arg_type is None:
if name in BUILTIN_TYPES:
arg_type = PythonScraper.type_to_typeref(get_builtin(name))
elif mod is not None and name in mod.__dict__:
arg_type = PythonScraper.typename_to_typeref(mod.__name__, name)
elif name.startswith('list'):
arg_type = PythonScraper.type_to_typeref(list)
else:
# see if we can find it in any module we've imported...
for mod_name, mod in sys.modules.items():
if mod is not None and name in mod.__dict__ and isinstance(mod.__dict__[name], type):
arg_type = PythonScraper.typename_to_typeref(mod_name, name)
break
else:
first_space = name.find(' ')
if first_space != -1:
return type_name_to_typeref(name[:first_space], mod, type_overrides)
arg_type = PythonScraper.typename_to_typeref(name)
return arg_type
OBJECT_TYPE = PythonScraper.type_to_typeref(object)
TOKENS_REGEX = '(' + '|'.join([
r'(?:[a-zA-Z_][0-9a-zA-Z_-]*)', # identifier
r'(?:-?[0-9]+[lL]?(?!\.))', # integer value
r'(?:-?[0-9]*\.[0-9]+)', # floating point value
r'(?:-?[0-9]+\.[0-9]*)', # floating point value
r'(?:\s*\'.*?(?<!\\)\')', # single-quote string
r'(?:\s*".*?(?<!\\)")', # double-quote string
r'(?:\.\.\.)', # ellipsis
r'(?:\.)', # dot
r'(?:\()', # open paren
r'(?:\))', # close paren
r'(?:\:)', # colon
r'(?:-->)', # return value
r'(?:->)', # return value
r'(?:=>)', # return value
r'(?:,)', # comma
r'(?:=)', # assignment (default value)
r'(?:\[)',
r'(?:\])',
r'(?:\*\*)',
r'(?:\*)',
]) + ')'
def get_ret_type(ret_type, obj_class, mod):
if ret_type is not None:
if ret_type == 'copy' and obj_class is not None:
# returns a copy of self
return PythonScraper.type_to_typelist(obj_class)
else:
return [type_name_to_typeref(ret_type, mod, RETURN_TYPE_OVERRIDES)]
RETURNS_REGEX = [r'^\s*returns?[\s\-]*[a-z_]\w*\s*:\s*([a-z_]\w*)']
def update_overload_from_doc_str(overload, doc_str, obj_class, mod):
# see if we can get additional information from the doc string
if 'ret_type' not in overload:
for ret_regex in RETURNS_REGEX:
match = re.search(ret_regex, doc_str, re.MULTILINE | re.IGNORECASE)
if match:
ret_type = match.groups(0)[0]
overload['ret_type'] = get_ret_type(ret_type, obj_class, mod)
break
def parse_doc_str(input_str, module_name, mod, func_name, extra_args = [], obj_class = None):
# we split, so as long as we have all tokens every other item is a token, and the
# rest are empty space. If we have unrecognized tokens (for example during the description
# of the function) those will show up in the even locations. We do join's and bring the
# entire range together in that case.
tokens = re.split(TOKENS_REGEX, input_str)
start_token = 0
last_identifier = None
cur_token = 1
overloads = []
while cur_token < len(tokens):
token = tokens[cur_token]
# see if we have modname.funcname(
if (cur_token + 10 < len(tokens) and
token == module_name and
tokens[cur_token + 2] == '.' and
tokens[cur_token + 4] == func_name and
tokens[cur_token + 6] == '('):
sig_start = cur_token
args, ret_type, cur_token = parse_args(tokens, cur_token + 8, mod)
doc_str = ''.join(tokens[start_token:sig_start])
if doc_str.find(' ') == -1:
doc_str = ''
if (not args or doc_str) and overloads:
# if we already parsed an overload, and are now getting an argless
# overload we're likely just seeing a reference to the function in
# a doc string, let's ignore that. This is betting on the idea that
# people list overloads first, then doc strings, and that people tend
# to list overloads from simplest to more complex. an example of this
# is the future_builtins.ascii doc string
# We also skip it if we have a doc string, this comes up in overloads
# like isinstance which has example calls embedded in the doc string
continue
start_token = cur_token
overload = {'args': tuple(extra_args + args), 'doc': doc_str}
ret_types = get_ret_type(ret_type, obj_class, mod)
if ret_types is not None:
overload['ret_type'] = ret_types
update_overload_from_doc_str(overload, doc_str, obj_class, mod)
overloads.append(overload)
# see if we have funcname(
elif (cur_token + 4 < len(tokens) and
token == func_name and
tokens[cur_token + 2] == '('):
sig_start = cur_token
args, ret_type, cur_token = parse_args(tokens, cur_token + 4, mod)
doc_str = ''.join(tokens[start_token:sig_start])
if doc_str.find(' ') == -1:
doc_str = ''
if (not args or doc_str) and overloads:
# if we already parsed an overload, and are now getting an argless
# overload we're likely just seeing a reference to the function in
# a doc string, let's ignore that. This is betting on the idea that
# people list overloads first, then doc strings, and that people tend
# to list overloads from simplest to more complex. an example of this
# is the future_builtins.ascii doc string
# We also skip it if we have a doc string, this comes up in overloads
# like isinstance which has example calls embedded in the doc string
continue
start_token = cur_token
overload = {'args': tuple(extra_args + args), 'doc': doc_str}
ret_types = get_ret_type(ret_type, obj_class, mod)
if ret_types is not None:
overload['ret_type'] = ret_types
update_overload_from_doc_str(overload, doc_str, obj_class, mod)
overloads.append(overload)
else:
# append to doc string
cur_token += 2
finish_doc = ''.join(tokens[start_token:cur_token])
if finish_doc:
if not overloads:
# This occurs when the docstring does not include a function spec
overloads.append({
'args': ({'name': 'args', 'arg_format': '*'}, {'name': 'kwargs', 'arg_format': '**'}),
'doc': ''
})
for overload in overloads:
overload['doc'] += finish_doc
update_overload_from_doc_str(overload, overload['doc'], obj_class, mod)
return overloads
IDENTIFIER_REGEX = re.compile('^[a-zA-Z_][a-zA-Z_0-9-]*$')
def is_identifier(token):
if IDENTIFIER_REGEX.match(token):
return True
return False
RETURN_TOKENS = set(['-->', '->', '=>', 'return'])
def parse_args(tokens, cur_token, module):
args = []
arg = []
annotation = None
default_value = None
ignore = False
arg_tokens = []
next_is_optional = False
is_optional = False
paren_nesting = 0
while cur_token < len(tokens):
token = tokens[cur_token]
cur_token += 1
if token in (',', ')') and paren_nesting == 0:
arg_tokens.append((arg, annotation, default_value, is_optional))
is_optional = False
arg = []
annotation = None
default_value = None
if token == ')':
cur_token += 1
break
elif ignore:
continue
elif token == '=':
if default_value is None:
default_value = []
else:
ignore = True
elif token == ':':
if annotation is None and default_value is None:
annotation = []
else:
ignore = True
elif default_value is not None:
default_value.append(token)
elif annotation is not None:
annotation.append(token)
elif token == '[':
next_is_optional = True
elif token in (']', ' ', ''):
pass
else:
arg.append(token)
if next_is_optional:
is_optional, next_is_optional = True, False
if token == '(':
paren_nesting += 1
elif token == ')':
paren_nesting -= 1
#from pprint import pprint; pprint(arg_tokens)
for arg, annotation, default_value, is_optional in arg_tokens:
if not arg or arg[0] == '/':
continue
arg_name = None
| |
<gh_stars>1-10
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import os
import sys
root_path = "/".join(os.path.realpath(__file__).split("/")[:-2])
if root_path not in sys.path:
sys.path.insert(0, root_path)
server_root_path = ''
import torch
import time
import itertools
from utils.tokenization import BertTokenizer, CompTokenizer
from utils.multistage_utils import *
from utils.optimization import BertAdam
from utils.config import Config
from dataset_readers.bert_ner import *
from dataset_readers.bert_pos import *
from dataset_readers.bert_cws import *
from models.bert.bert_tagger import BertTagger
from dataset_readers.bert_data_utils import convert_examples_to_features
from bin.eval_model import eval_checkpoint
logging.basicConfig()
logger = logging.getLogger(__name__)
def args_parser():
# start parser
parser = argparse.ArgumentParser()
# required parameters
parser.add_argument("--config_path", default="configs/bert.json", type=str)
parser.add_argument("--bert_model", default=None, type=str, required=True,
help="bert-large-uncased, bert-base-cased, bert-large-cased")
parser.add_argument("--task_name", default=None, type=str)
# # other parameters
parser.add_argument("--cuda", type=bool, default=True)
parser.add_argument("--use_multi_gpu", type=bool, default=False)
parser.add_argument("--device", type=str, default="cpu")
parser.add_argument("--max_seq_length", default=128,
type=int, help="the maximum total input sequence length after ")
parser.add_argument("--do_train", action="store_true",
help="Whether to run training")
parser.add_argument("--do_eval", action="store_true",
help="Whether to run eval")
parser.add_argument("--use_server", action="store_true",
help="Whether to use server")
parser.add_argument("--train_batch_size", default=32, type=int)
parser.add_argument("--dev_batch_size", default=32, type=int)
parser.add_argument("--test_batch_size", default=32, type=int)
parser.add_argument("--checkpoint", default=500, type=int)
parser.add_argument("--learning_rate", default=5e-5, type=float)
parser.add_argument("--num_train_epochs", default=3.0, type=float)
parser.add_argument("--warmup_proportion", default=0.1, type=float)
# parser.add_argument("--bert_frozen", type=bool, default=False)
parser.add_argument("--gradient_accumulation_steps", type=int, default=1)
parser.add_argument("--seed", type=int, default=77777)
parser.add_argument("--export_model", type=bool, default=True)
parser.add_argument("--output_dir", type=str, default="output")
parser.add_argument("--raw_data", type=str, required=True)
parser.add_argument("--book_dir", type=str, required=True)
parser.add_argument("--use_crf", type=bool, default=True)
parser.add_argument("--train_iterator", type=int, default=3)
parser.add_argument("--output_model_name", type=str, default="multi_stage_pytorch.bin")
args = parser.parse_args()
args.train_batch_size = args.train_batch_size // args.gradient_accumulation_steps
random.seed(args.seed)
np.random.seed(args.seed)
torch.manual_seed(args.seed)
if args.cuda:
torch.cuda.manual_seed_all(args.seed)
os.makedirs(args.output_dir, exist_ok=True)
return args
def load_model(config, label_list):
# device = torch.device(torch.cuda.is_available())
if config.use_server and torch.cuda.is_available():
if config.use_multi_gpu:
n_gpu = torch.cuda.device_count()
device = torch.device("cuda")
else:
n_gpu = 1
device = torch.device(config.device)
else:
device = torch.device("cpu")
n_gpu = 0
model = BertTagger(config, num_labels=len(label_list))
# model_path = os.path.join(config.output_dir, config.ckpt_name)
if config.use_server:
model.to(device)
print('using device:' + config.device)
if n_gpu > 1:
model = torch.nn.DataParallel(model)
return model, device, n_gpu
def merge_config(args_config):
if args_config.use_server:
args_config.config_path = server_root_path + args_config.config_path
args_config.bert_model = server_root_path + args_config.bert_model
args_config.output_dir = server_root_path + args_config.output_dir
args_config.raw_data = server_root_path + args_config.raw_data
args_config.book_dir = server_root_path + args_config.book_dir
model_config_path = args_config.config_path
model_config = Config.from_json_file(model_config_path)
model_config.update_args(args_config)
model_config.print_config()
return model_config
def get_optimizer(model, config, num_train_steps):
# get different num_train_steps optimizers
param_optimizer = list(model.named_parameters())
no_decay = ["bias", "LayerNorm.bias", "LayerNorm.weight"]
optimizer_grouped_parameters = [
{"params": [p for n, p in param_optimizer if not any(nd in n for nd in no_decay)], "weight_decay": 0.01},
{"params": [p for n, p in param_optimizer if any(nd in n for nd in no_decay)], "weight_decay": 0.0}]
optimizer = BertAdam(optimizer_grouped_parameters,
lr=config.learning_rate,
warmup=config.warmup_proportion,
t_total=num_train_steps,
max_grad_norm=config.clip_grad)
return optimizer
def one_iter(bert, raw_sents, freqdict, last_time_dataset=None, sample_times=3, is_init=False, thres=75, iters=3):
model, config, device, n_gpu, label_list, tokenizer = bert
if last_time_dataset is None:
sample_sents_lst = produce_sampling_sents(raw_sents, sample_times,
freqdict=freqdict,
thres=thres)
else:
last_time_sents = convert_feature_to_sents(last_time_dataset, tokenizer, label_list)
# with open('data/predict.txt', 'w', encoding='utf-8') as f:
# for s in last_time_sents:
# f.write(s + '\n')
sample_sents_lst = produce_sampling_sents(raw_sents, sample_times - 1,
freqdict=freqdict,
thres=thres,
last_time_sents=last_time_sents)
for sample_sents in sample_sents_lst:
print("sample sentences examples:")
for i in range(min(3, len(sample_sents))):
print(sample_sents[i])
print("-*-" * 7)
train_sents, remain_sents = select_train_sentences(sample_sents_lst, freqdict, is_init=is_init)
print("select sentences examples:")
for i in range(min(10, len(train_sents))):
print(train_sents[i])
print("=&=" * 7)
print("Select %d sentences, remain %d sentences." % (len(train_sents), len(remain_sents)))
train_dataloader, num_train_steps = labeled_txt_to_dataloader(config, label_list, tokenizer, train_sents, iter=iters)
if len(train_sents) < 32:
print("Only select %d sentences, return." % len(train_sents))
return train_sents, remain_sents
auto_train(model, train_dataloader, config, device, n_gpu, label_list, num_train_steps, iters=iters)
return train_sents, remain_sents
def auto_train(model, train_dataloader, config, device, n_gpu, label_list, num_train_steps, iters=5):
iter_cnt = 0
config.num_train_epochs = 3
while iter_cnt < iters:
optimizer = get_optimizer(model, config, num_train_steps)
loss = train(model, optimizer, train_dataloader, config, device, n_gpu, label_list)
if loss < 5.0:
print("Auto train complete, loss is %.4f" % loss)
break
elif loss < 50.0:
continue
else:
iters += 1
iter_cnt += 1
if iter_cnt == iters:
print("%d times of auto_train iteration. Return." % iters)
break
def train(model, optimizer, train_dataloader, config, device, n_gpu, label_list):
global_step = 0
model.train()
train_start = time.time()
tr_loss = 0
for idx in range(int(config.num_train_epochs)):
tr_loss = 0
nb_tr_examples, nb_tr_steps = 0, 0
print("#######" * 7)
print("EPOCH: ", str(idx))
epoch_start = time.time()
print("EPOCH: %d/%d" % (idx, int(config.num_train_epochs)))
for step, batch in enumerate(train_dataloader):
batch = tuple(t.to(device) for t in batch)
input_ids, input_mask, segment_ids, label_ids, label_len = batch
loss = model(input_ids, segment_ids, input_mask, label_ids)
if n_gpu > 1:
loss = loss.mean()
model.zero_grad()
loss.backward()
# nn.utils.clip_grad_norm_(parameters=model.parameters(), max_norm=config.clip_grad)
tr_loss += loss.item()
nb_tr_examples += input_ids.size(0)
nb_tr_steps += 1
if (step + 1) % config.gradient_accumulation_steps == 0:
optimizer.step()
# optimizer.zero_grad()
global_step += 1
if (global_step + 1) % config.checkpoint == 0:
print("-*-" * 15)
print("current batch training loss is : ")
print(loss.item())
print("-*-" * 15)
print("Total training loss is: ", str(tr_loss))
epoch_finish = time.time()
print("EPOCH: %d; TIME: %.2fs" % (idx, epoch_finish - epoch_start), flush=True)
train_finish = time.time()
print("TOTAL_TIME: %.2fs" % (train_finish - train_start))
# export a trained model
model_to_save = model.module if hasattr(model, "module") else model
output_model_file = os.path.join(config.output_dir, config.output_model_name)
if config.export_model:
torch.save(model_to_save.state_dict(), output_model_file)
return tr_loss
def predict(model_object, device, eval_dataloader):
model_object.eval()
input_ids_lst = []
input_mask_lst = []
segment_ids_lst = []
label_ids_lst = []
label_len_lst = []
for input_ids, input_mask, segment_ids, label_ids, label_len in eval_dataloader:
input_ids_lst.append(input_ids)
input_mask_lst.append(input_mask)
segment_ids_lst.append(segment_ids)
# label_ids_lst.append(label_ids)
label_len_lst.append(label_len)
input_ids_cuda = input_ids.to(device)
segment_ids_cuda = segment_ids.to(device)
input_mask_cuda = input_mask.to(device)
with torch.no_grad():
logits = model_object(input_ids_cuda, segment_ids_cuda, input_mask_cuda)
logits = np.array(logits)
logits = torch.tensor(logits, dtype=torch.long)
label_ids_lst.append(logits)
input_ids = torch.cat(input_ids_lst, dim=0)
input_mask = torch.cat(input_mask_lst, dim=0)
segment_ids = torch.cat(segment_ids_lst, dim=0)
label_ids = torch.cat(label_ids_lst, dim=0)
label_len = torch.cat(label_len_lst, dim=0)
data = TensorDataset(input_ids, input_mask, segment_ids, label_ids, label_len)
return data
def test(model, test_dataloader, config, device, n_gpu, label_list):
test_loss, test_acc, test_prec, test_rec, test_f1 = eval_checkpoint(
model_object=model,
eval_dataloader=test_dataloader,
device=device,
label_list=label_list,
task_sign=config.task_name
)
print("TEST: precision, recall, f1, acc, loss ")
print(test_prec, test_rec, test_f1, test_acc, test_loss, '\n')
return
def load_data(config):
# load some data and processor
data_processor = BookCWSProcessor()
label_list = data_processor.get_labels()
if 'wcm' in config.bert_model:
tokenizer = CompTokenizer(config.bert_model)
else:
tokenizer = BertTokenizer.from_pretrained(config.bert_model, do_lower_case=True)
# load data exampels
test_examples_list, book_list = data_processor.get_test_examples(config.book_dir)
cnt_B = 0
cnt = 0
for test_examples in test_examples_list:
for test_line in test_examples:
label = test_line.label
for l in label:
if l == 'B':
cnt_B += 1
cnt += 1
print("Total %d tags, %d tags are [B]. " % (cnt, cnt_B))
def generate_data(examples):
features = convert_examples_to_features(examples, label_list, config.max_seq_length, tokenizer,
task_sign=config.task_name)
input_ids = torch.tensor([f.input_ids for f in features], dtype=torch.long)
input_mask = torch.tensor([f.input_mask for f in features], dtype=torch.long)
segment_ids = torch.tensor([f.segment_ids for f in features], dtype=torch.long)
label_ids = torch.tensor([f.label_id for f in features], dtype=torch.long)
label_len = torch.tensor([f.label_len for f in features], dtype=torch.long)
data = TensorDataset(input_ids, input_mask, segment_ids, label_ids, label_len)
# sampler = DistributedSampler(data)
sampler = RandomSampler(data)
return data, sampler
# convert data example into featrues
test_dataloader_list = []
for test_examples in test_examples_list:
test_data, test_sampler = generate_data(test_examples)
test_dataloader = DataLoader(test_data, sampler=test_sampler, batch_size=config.test_batch_size)
test_dataloader_list.append(test_dataloader)
return test_dataloader_list, label_list, book_list
def main():
args_config = args_parser()
config = merge_config(args_config)
if 'wcm' in config.bert_model:
tokenizer = CompTokenizer(config.bert_model)
else:
tokenizer = BertTokenizer.from_pretrained(config.bert_model, do_lower_case=True)
label_list = WhitespaceCWSPrecessor.get_labels()
bert_model, device, n_gpu = load_model(config, label_list)
fq = FreqDict()
raw_sents = [s.strip() for s in open(config.raw_data, 'r', encoding='utf-8').readlines()]
bert = bert_model, config, device, n_gpu, label_list, tokenizer
# First Part, select sentences, train bert.
train_sents, remain_sents = one_iter(bert, raw_sents, fq,
is_init=True, thres=75)
print("First Part Done.")
print("-*-" * 7)
print("=&=" * 7)
sys.stdout.flush()
# Second Part, use bert to predict remain sentences.
print("\nSecond Part Start.")
eval_dataloader, _ = labeled_txt_to_dataloader(config, label_list, tokenizer, remain_sents)
predicted_data = predict(bert_model, device, eval_dataloader)
gap = 10 / (config.train_iterator - 1)
flag = True
thres = 80
while len(remain_sents) > 10000 and flag:
thres = thres + random.randint(-3, 3)
thres = min(thres, 83)
thres = max(thres, 77)
for i in range(config.train_iterator):
train_sents, remain_sents = one_iter(bert, remain_sents, fq,
last_time_dataset=predicted_data,
thres=thres)
if len(train_sents) < 32:
print("Can only select %d sentences, iteration end." % len(train_sents))
print("Remain %d sentences." % len(remain_sents))
flag = False
break
eval_dataloader, _ = labeled_txt_to_dataloader(config, label_list, tokenizer, remain_sents)
predicted_data = predict(bert_model, device, eval_dataloader)
print("Second Part Done.")
print("-*-" * 7)
print("=&=" * 7)
print("Remain %d sentences." % len(remain_sents))
print("\nTest Part Start.")
test_loader_list, label_list, book_list = load_data(config)
for test_loader, book in zip(test_loader_list, book_list):
print(book)
test(bert_model, test_loader, config, device, n_gpu, label_list)
sys.stdout.flush()
print("Test Part Done.")
# Third part is useless.
'''
# Third part, use bert to predict all the data and fine-tune bert.
eval_dataloader, _ = labeled_txt_to_dataloader(config, label_list, tokenizer, raw_sents)
predicted_data = predict(bert_model, device, eval_dataloader)
sampler = SequentialSampler(predicted_data)
train_dataloader = DataLoader(predicted_data, sampler=sampler, batch_size=config.train_batch_size)
num_train_steps = int(len(train_dataloader.dataset) / config.train_batch_size * config.num_train_epochs)
auto_train(bert_model, train_dataloader, config, device, | |
<filename>sdk/python/pulumi_akamai/app_sec_eval_group.py<gh_stars>1-10
# coding=utf-8
# *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. ***
# *** 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, overload
from . import _utilities
__all__ = ['AppSecEvalGroupArgs', 'AppSecEvalGroup']
@pulumi.input_type
class AppSecEvalGroupArgs:
def __init__(__self__, *,
attack_group: pulumi.Input[str],
attack_group_action: pulumi.Input[str],
config_id: pulumi.Input[int],
security_policy_id: pulumi.Input[str],
condition_exception: Optional[pulumi.Input[str]] = None):
"""
The set of arguments for constructing a AppSecEvalGroup resource.
:param pulumi.Input[str] attack_group: . Unique identifier of the evaluation attack group being modified.
:param pulumi.Input[str] attack_group_action: . Action to be taken any time the attack group is triggered. Allowed values are:
- **alert**. Record the event.
- **deny**. Block the request
- **deny_custom_{custom_deny_id}**. Take the action specified by the custom deny.
- **none**. Take no action.
:param pulumi.Input[int] config_id: . Unique identifier of the security configuration where evaluation is taking place.
:param pulumi.Input[str] security_policy_id: . Unique identifier of the security policy associated with the evaluation process.
:param pulumi.Input[str] condition_exception: . Path to a JSON file containing properties and property values for the attack group. For more information, the [Modify the exceptions of an attack group](https://developer.akamai.com/api/cloud_security/application_security/v1.html#putattackgroupconditionexception) section of the Application Security API documentation.
"""
pulumi.set(__self__, "attack_group", attack_group)
pulumi.set(__self__, "attack_group_action", attack_group_action)
pulumi.set(__self__, "config_id", config_id)
pulumi.set(__self__, "security_policy_id", security_policy_id)
if condition_exception is not None:
pulumi.set(__self__, "condition_exception", condition_exception)
@property
@pulumi.getter(name="attackGroup")
def attack_group(self) -> pulumi.Input[str]:
"""
. Unique identifier of the evaluation attack group being modified.
"""
return pulumi.get(self, "attack_group")
@attack_group.setter
def attack_group(self, value: pulumi.Input[str]):
pulumi.set(self, "attack_group", value)
@property
@pulumi.getter(name="attackGroupAction")
def attack_group_action(self) -> pulumi.Input[str]:
"""
. Action to be taken any time the attack group is triggered. Allowed values are:
- **alert**. Record the event.
- **deny**. Block the request
- **deny_custom_{custom_deny_id}**. Take the action specified by the custom deny.
- **none**. Take no action.
"""
return pulumi.get(self, "attack_group_action")
@attack_group_action.setter
def attack_group_action(self, value: pulumi.Input[str]):
pulumi.set(self, "attack_group_action", value)
@property
@pulumi.getter(name="configId")
def config_id(self) -> pulumi.Input[int]:
"""
. Unique identifier of the security configuration where evaluation is taking place.
"""
return pulumi.get(self, "config_id")
@config_id.setter
def config_id(self, value: pulumi.Input[int]):
pulumi.set(self, "config_id", value)
@property
@pulumi.getter(name="securityPolicyId")
def security_policy_id(self) -> pulumi.Input[str]:
"""
. Unique identifier of the security policy associated with the evaluation process.
"""
return pulumi.get(self, "security_policy_id")
@security_policy_id.setter
def security_policy_id(self, value: pulumi.Input[str]):
pulumi.set(self, "security_policy_id", value)
@property
@pulumi.getter(name="conditionException")
def condition_exception(self) -> Optional[pulumi.Input[str]]:
"""
. Path to a JSON file containing properties and property values for the attack group. For more information, the [Modify the exceptions of an attack group](https://developer.akamai.com/api/cloud_security/application_security/v1.html#putattackgroupconditionexception) section of the Application Security API documentation.
"""
return pulumi.get(self, "condition_exception")
@condition_exception.setter
def condition_exception(self, value: Optional[pulumi.Input[str]]):
pulumi.set(self, "condition_exception", value)
@pulumi.input_type
class _AppSecEvalGroupState:
def __init__(__self__, *,
attack_group: Optional[pulumi.Input[str]] = None,
attack_group_action: Optional[pulumi.Input[str]] = None,
condition_exception: Optional[pulumi.Input[str]] = None,
config_id: Optional[pulumi.Input[int]] = None,
security_policy_id: Optional[pulumi.Input[str]] = None):
"""
Input properties used for looking up and filtering AppSecEvalGroup resources.
:param pulumi.Input[str] attack_group: . Unique identifier of the evaluation attack group being modified.
:param pulumi.Input[str] attack_group_action: . Action to be taken any time the attack group is triggered. Allowed values are:
- **alert**. Record the event.
- **deny**. Block the request
- **deny_custom_{custom_deny_id}**. Take the action specified by the custom deny.
- **none**. Take no action.
:param pulumi.Input[str] condition_exception: . Path to a JSON file containing properties and property values for the attack group. For more information, the [Modify the exceptions of an attack group](https://developer.akamai.com/api/cloud_security/application_security/v1.html#putattackgroupconditionexception) section of the Application Security API documentation.
:param pulumi.Input[int] config_id: . Unique identifier of the security configuration where evaluation is taking place.
:param pulumi.Input[str] security_policy_id: . Unique identifier of the security policy associated with the evaluation process.
"""
if attack_group is not None:
pulumi.set(__self__, "attack_group", attack_group)
if attack_group_action is not None:
pulumi.set(__self__, "attack_group_action", attack_group_action)
if condition_exception is not None:
pulumi.set(__self__, "condition_exception", condition_exception)
if config_id is not None:
pulumi.set(__self__, "config_id", config_id)
if security_policy_id is not None:
pulumi.set(__self__, "security_policy_id", security_policy_id)
@property
@pulumi.getter(name="attackGroup")
def attack_group(self) -> Optional[pulumi.Input[str]]:
"""
. Unique identifier of the evaluation attack group being modified.
"""
return pulumi.get(self, "attack_group")
@attack_group.setter
def attack_group(self, value: Optional[pulumi.Input[str]]):
pulumi.set(self, "attack_group", value)
@property
@pulumi.getter(name="attackGroupAction")
def attack_group_action(self) -> Optional[pulumi.Input[str]]:
"""
. Action to be taken any time the attack group is triggered. Allowed values are:
- **alert**. Record the event.
- **deny**. Block the request
- **deny_custom_{custom_deny_id}**. Take the action specified by the custom deny.
- **none**. Take no action.
"""
return pulumi.get(self, "attack_group_action")
@attack_group_action.setter
def attack_group_action(self, value: Optional[pulumi.Input[str]]):
pulumi.set(self, "attack_group_action", value)
@property
@pulumi.getter(name="conditionException")
def condition_exception(self) -> Optional[pulumi.Input[str]]:
"""
. Path to a JSON file containing properties and property values for the attack group. For more information, the [Modify the exceptions of an attack group](https://developer.akamai.com/api/cloud_security/application_security/v1.html#putattackgroupconditionexception) section of the Application Security API documentation.
"""
return pulumi.get(self, "condition_exception")
@condition_exception.setter
def condition_exception(self, value: Optional[pulumi.Input[str]]):
pulumi.set(self, "condition_exception", value)
@property
@pulumi.getter(name="configId")
def config_id(self) -> Optional[pulumi.Input[int]]:
"""
. Unique identifier of the security configuration where evaluation is taking place.
"""
return pulumi.get(self, "config_id")
@config_id.setter
def config_id(self, value: Optional[pulumi.Input[int]]):
pulumi.set(self, "config_id", value)
@property
@pulumi.getter(name="securityPolicyId")
def security_policy_id(self) -> Optional[pulumi.Input[str]]:
"""
. Unique identifier of the security policy associated with the evaluation process.
"""
return pulumi.get(self, "security_policy_id")
@security_policy_id.setter
def security_policy_id(self, value: Optional[pulumi.Input[str]]):
pulumi.set(self, "security_policy_id", value)
class AppSecEvalGroup(pulumi.CustomResource):
@overload
def __init__(__self__,
resource_name: str,
opts: Optional[pulumi.ResourceOptions] = None,
attack_group: Optional[pulumi.Input[str]] = None,
attack_group_action: Optional[pulumi.Input[str]] = None,
condition_exception: Optional[pulumi.Input[str]] = None,
config_id: Optional[pulumi.Input[int]] = None,
security_policy_id: Optional[pulumi.Input[str]] = None,
__props__=None):
"""
**Scopes**: Evaluation attack group
Modifies the action and the conditions and exceptions for an evaluation mode attack group.
Note that this resource is only available to organizations running the Adaptive Security Engine (ASE) beta. For more information about ASE, please contact your Akamai representative.
## Example Usage
Basic usage:
```python
import pulumi
import pulumi_akamai as akamai
configuration = akamai.get_app_sec_configuration(name="Documentation")
eval_attack_group = akamai.AppSecEvalGroup("evalAttackGroup",
config_id=configuration.config_id,
security_policy_id="gms1_134637",
attack_group="SQL",
attack_group_action="deny",
condition_exception=(lambda path: open(path).read())(f"{path['module']}/condition_exception.json"))
```
:param str resource_name: The name of the resource.
:param pulumi.ResourceOptions opts: Options for the resource.
:param pulumi.Input[str] attack_group: . Unique identifier of the evaluation attack group being modified.
:param pulumi.Input[str] attack_group_action: . Action to be taken any time the attack group is triggered. Allowed values are:
- **alert**. Record the event.
- **deny**. Block the request
- **deny_custom_{custom_deny_id}**. Take the action specified by the custom deny.
- **none**. Take no action.
:param pulumi.Input[str] condition_exception: . Path to a JSON file containing properties and property values for the attack group. For more information, the [Modify the exceptions of an attack group](https://developer.akamai.com/api/cloud_security/application_security/v1.html#putattackgroupconditionexception) section of the Application Security API documentation.
:param pulumi.Input[int] config_id: . Unique identifier of the security configuration where evaluation is taking place.
:param pulumi.Input[str] security_policy_id: . Unique identifier of the security policy associated with the evaluation process.
"""
...
@overload
def __init__(__self__,
resource_name: str,
args: AppSecEvalGroupArgs,
opts: Optional[pulumi.ResourceOptions] = None):
"""
**Scopes**: Evaluation attack group
Modifies the action and the conditions and exceptions for an evaluation mode attack group.
Note that this resource is only available to organizations running the Adaptive Security Engine (ASE) beta. For more information about ASE, please contact your Akamai representative.
## Example Usage
Basic usage:
```python
import pulumi
import pulumi_akamai as akamai
configuration = akamai.get_app_sec_configuration(name="Documentation")
eval_attack_group = akamai.AppSecEvalGroup("evalAttackGroup",
config_id=configuration.config_id,
security_policy_id="gms1_134637",
attack_group="SQL",
attack_group_action="deny",
condition_exception=(lambda path: open(path).read())(f"{path['module']}/condition_exception.json"))
```
:param str resource_name: The name of the resource.
:param AppSecEvalGroupArgs args: The arguments to use to populate this resource's properties.
:param pulumi.ResourceOptions opts: Options for the resource.
"""
...
def __init__(__self__, resource_name: str, *args, **kwargs):
resource_args, opts = _utilities.get_resource_args_opts(AppSecEvalGroupArgs, pulumi.ResourceOptions, *args, **kwargs)
if resource_args is not None:
__self__._internal_init(resource_name, opts, **resource_args.__dict__)
else:
__self__._internal_init(resource_name, *args, **kwargs)
def _internal_init(__self__,
resource_name: str,
opts: Optional[pulumi.ResourceOptions] = None,
attack_group: Optional[pulumi.Input[str]] = None,
attack_group_action: Optional[pulumi.Input[str]] = None,
condition_exception: Optional[pulumi.Input[str]] = None,
config_id: Optional[pulumi.Input[int]] = None,
security_policy_id: Optional[pulumi.Input[str]] = None,
__props__=None):
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')
| |
= cms.int32( 4 ),
extraNumberOfHitsBeforeTheFirstLoop = cms.int32( 4 ),
maxLostHitsFraction = cms.double( 999.0 ),
constantValueForLostHitsFractionFilter = cms.double( 1.0 ),
seedPairPenalty = cms.int32( 0 )
)
HLTPSetCkfTrajectoryFilter = cms.PSet(
minPt = cms.double( 0.9 ),
minHitsMinPt = cms.int32( 3 ),
ComponentType = cms.string( "CkfBaseTrajectoryFilter" ),
maxLostHits = cms.int32( 1 ),
maxNumberOfHits = cms.int32( -1 ),
maxConsecLostHits = cms.int32( 1 ),
minimumNumberOfHits = cms.int32( 5 ),
nSigmaMinPt = cms.double( 5.0 ),
chargeSignificance = cms.double( -1.0 ),
minGoodStripCharge = cms.PSet( refToPSet_ = cms.string( "HLTSiStripClusterChargeCutNone" ) ),
maxCCCLostHits = cms.int32( 9999 ),
seedExtension = cms.int32( 0 ),
strictSeedExtension = cms.bool( False ),
minNumberOfHitsForLoopers = cms.int32( 13 ),
minNumberOfHitsPerLoop = cms.int32( 4 ),
extraNumberOfHitsBeforeTheFirstLoop = cms.int32( 4 ),
maxLostHitsFraction = cms.double( 999.0 ),
constantValueForLostHitsFractionFilter = cms.double( 1.0 ),
seedPairPenalty = cms.int32( 0 )
)
HLTPSetCkf3HitTrajectoryFilter = cms.PSet(
minPt = cms.double( 0.9 ),
minHitsMinPt = cms.int32( 3 ),
ComponentType = cms.string( "CkfBaseTrajectoryFilter" ),
maxLostHits = cms.int32( 1 ),
maxNumberOfHits = cms.int32( -1 ),
maxConsecLostHits = cms.int32( 1 ),
minimumNumberOfHits = cms.int32( 3 ),
nSigmaMinPt = cms.double( 5.0 ),
chargeSignificance = cms.double( -1.0 ),
minGoodStripCharge = cms.PSet( refToPSet_ = cms.string( "HLTSiStripClusterChargeCutNone" ) ),
maxCCCLostHits = cms.int32( 9999 ),
seedExtension = cms.int32( 0 ),
strictSeedExtension = cms.bool( False ),
minNumberOfHitsForLoopers = cms.int32( 13 ),
minNumberOfHitsPerLoop = cms.int32( 4 ),
extraNumberOfHitsBeforeTheFirstLoop = cms.int32( 4 ),
maxLostHitsFraction = cms.double( 999.0 ),
constantValueForLostHitsFractionFilter = cms.double( 1.0 ),
seedPairPenalty = cms.int32( 0 )
)
HLTIter4PSetTrajectoryBuilderIT = cms.PSet(
propagatorAlong = cms.string( "PropagatorWithMaterialParabolicMf" ),
trajectoryFilter = cms.PSet( refToPSet_ = cms.string( "HLTIter4PSetTrajectoryFilterIT" ) ),
maxCand = cms.int32( 1 ),
ComponentType = cms.string( "CkfTrajectoryBuilder" ),
propagatorOpposite = cms.string( "PropagatorWithMaterialParabolicMfOpposite" ),
MeasurementTrackerName = cms.string( "hltIter4ESPMeasurementTracker" ),
estimator = cms.string( "hltESPChi2ChargeLooseMeasurementEstimator16" ),
TTRHBuilder = cms.string( "hltESPTTRHBWithTrackAngle" ),
updator = cms.string( "hltESPKFUpdator" ),
alwaysUseInvalidHits = cms.bool( False ),
intermediateCleaning = cms.bool( True ),
lostHitPenalty = cms.double( 30.0 ),
minNrOfHitsForRebuild = cms.untracked.int32( 4 )
)
HLTIter3PSetTrajectoryBuilderIT = cms.PSet(
propagatorAlong = cms.string( "PropagatorWithMaterialParabolicMf" ),
trajectoryFilter = cms.PSet( refToPSet_ = cms.string( "HLTIter3PSetTrajectoryFilterIT" ) ),
maxCand = cms.int32( 1 ),
ComponentType = cms.string( "CkfTrajectoryBuilder" ),
propagatorOpposite = cms.string( "PropagatorWithMaterialParabolicMfOpposite" ),
MeasurementTrackerName = cms.string( "hltIter3ESPMeasurementTracker" ),
estimator = cms.string( "hltESPChi2ChargeLooseMeasurementEstimator16" ),
TTRHBuilder = cms.string( "hltESPTTRHBWithTrackAngle" ),
updator = cms.string( "hltESPKFUpdator" ),
alwaysUseInvalidHits = cms.bool( False ),
intermediateCleaning = cms.bool( True ),
lostHitPenalty = cms.double( 30.0 )
)
HLTIter2PSetTrajectoryBuilderIT = cms.PSet(
propagatorAlong = cms.string( "PropagatorWithMaterialParabolicMf" ),
trajectoryFilter = cms.PSet( refToPSet_ = cms.string( "HLTIter2PSetTrajectoryFilterIT" ) ),
maxCand = cms.int32( 2 ),
ComponentType = cms.string( "CkfTrajectoryBuilder" ),
propagatorOpposite = cms.string( "PropagatorWithMaterialParabolicMfOpposite" ),
MeasurementTrackerName = cms.string( "hltIter2ESPMeasurementTracker" ),
estimator = cms.string( "hltESPChi2ChargeMeasurementEstimator16" ),
TTRHBuilder = cms.string( "hltESPTTRHBWithTrackAngle" ),
updator = cms.string( "hltESPKFUpdator" ),
alwaysUseInvalidHits = cms.bool( False ),
intermediateCleaning = cms.bool( True ),
lostHitPenalty = cms.double( 30.0 )
)
HLTIter1PSetTrajectoryBuilderIT = cms.PSet(
propagatorAlong = cms.string( "PropagatorWithMaterialParabolicMf" ),
trajectoryFilter = cms.PSet( refToPSet_ = cms.string( "HLTIter1PSetTrajectoryFilterIT" ) ),
maxCand = cms.int32( 2 ),
ComponentType = cms.string( "CkfTrajectoryBuilder" ),
propagatorOpposite = cms.string( "PropagatorWithMaterialParabolicMfOpposite" ),
MeasurementTrackerName = cms.string( "hltIter1ESPMeasurementTracker" ),
estimator = cms.string( "hltESPChi2ChargeMeasurementEstimator16" ),
TTRHBuilder = cms.string( "hltESPTTRHBWithTrackAngle" ),
updator = cms.string( "hltESPKFUpdator" ),
alwaysUseInvalidHits = cms.bool( False ),
intermediateCleaning = cms.bool( True ),
lostHitPenalty = cms.double( 30.0 )
)
HLTPSetTrajectoryBuilderForElectrons = cms.PSet(
propagatorAlong = cms.string( "hltESPFwdElectronPropagator" ),
trajectoryFilter = cms.PSet( refToPSet_ = cms.string( "HLTPSetTrajectoryFilterForElectrons" ) ),
maxCand = cms.int32( 5 ),
ComponentType = cms.string( "CkfTrajectoryBuilder" ),
propagatorOpposite = cms.string( "hltESPBwdElectronPropagator" ),
MeasurementTrackerName = cms.string( "hltESPMeasurementTracker" ),
estimator = cms.string( "hltESPChi2ChargeMeasurementEstimator30" ),
TTRHBuilder = cms.string( "hltESPTTRHBWithTrackAngle" ),
updator = cms.string( "hltESPKFUpdator" ),
alwaysUseInvalidHits = cms.bool( True ),
intermediateCleaning = cms.bool( False ),
lostHitPenalty = cms.double( 90.0 )
)
HLTPSetMuTrackJpsiTrajectoryBuilder = cms.PSet(
propagatorAlong = cms.string( "PropagatorWithMaterial" ),
trajectoryFilter = cms.PSet( refToPSet_ = cms.string( "HLTPSetMuTrackJpsiTrajectoryFilter" ) ),
maxCand = cms.int32( 1 ),
ComponentType = cms.string( "CkfTrajectoryBuilder" ),
propagatorOpposite = cms.string( "PropagatorWithMaterialOpposite" ),
MeasurementTrackerName = cms.string( "hltESPMeasurementTracker" ),
estimator = cms.string( "hltESPChi2ChargeMeasurementEstimator30" ),
TTRHBuilder = cms.string( "hltESPTTRHBWithTrackAngle" ),
updator = cms.string( "hltESPKFUpdator" ),
alwaysUseInvalidHits = cms.bool( False ),
intermediateCleaning = cms.bool( True ),
lostHitPenalty = cms.double( 30.0 )
)
HLTPSetMuTrackJpsiEffTrajectoryBuilder = cms.PSet(
propagatorAlong = cms.string( "PropagatorWithMaterial" ),
trajectoryFilter = cms.PSet( refToPSet_ = cms.string( "HLTPSetMuTrackJpsiEffTrajectoryFilter" ) ),
maxCand = cms.int32( 1 ),
ComponentType = cms.string( "CkfTrajectoryBuilder" ),
propagatorOpposite = cms.string( "PropagatorWithMaterialOpposite" ),
MeasurementTrackerName = cms.string( "hltESPMeasurementTracker" ),
estimator = cms.string( "hltESPChi2ChargeMeasurementEstimator30" ),
TTRHBuilder = cms.string( "hltESPTTRHBWithTrackAngle" ),
updator = cms.string( "hltESPKFUpdator" ),
alwaysUseInvalidHits = cms.bool( False ),
intermediateCleaning = cms.bool( True ),
lostHitPenalty = cms.double( 30.0 )
)
HLTPSetMuonCkfTrajectoryBuilderSeedHit = cms.PSet(
propagatorAlong = cms.string( "PropagatorWithMaterial" ),
trajectoryFilter = cms.PSet( refToPSet_ = cms.string( "HLTPSetMuonCkfTrajectoryFilter" ) ),
maxCand = cms.int32( 5 ),
ComponentType = cms.string( "MuonCkfTrajectoryBuilder" ),
propagatorOpposite = cms.string( "PropagatorWithMaterialOpposite" ),
useSeedLayer = cms.bool( True ),
deltaEta = cms.double( -1.0 ),
deltaPhi = cms.double( -1.0 ),
estimator = cms.string( "hltESPChi2ChargeMeasurementEstimator30" ),
rescaleErrorIfFail = cms.double( 1.0 ),
propagatorProximity = cms.string( "SteppingHelixPropagatorAny" ),
updator = cms.string( "hltESPKFUpdator" ),
alwaysUseInvalidHits = cms.bool( True ),
TTRHBuilder = cms.string( "hltESPTTRHBWithTrackAngle" ),
MeasurementTrackerName = cms.string( "hltESPMeasurementTracker" ),
intermediateCleaning = cms.bool( False ),
lostHitPenalty = cms.double( 30.0 )
)
HLTPSetMuonCkfTrajectoryBuilder = cms.PSet(
propagatorAlong = cms.string( "PropagatorWithMaterial" ),
trajectoryFilter = cms.PSet( refToPSet_ = cms.string( "HLTPSetMuonCkfTrajectoryFilter" ) ),
maxCand = cms.int32( 5 ),
ComponentType = cms.string( "MuonCkfTrajectoryBuilder" ),
propagatorOpposite = cms.string( "PropagatorWithMaterialOpposite" ),
useSeedLayer = cms.bool( False ),
deltaEta = cms.double( -1.0 ),
deltaPhi = cms.double( -1.0 ),
estimator = cms.string( "hltESPChi2ChargeMeasurementEstimator30" ),
rescaleErrorIfFail = cms.double( 1.0 ),
propagatorProximity = cms.string( "SteppingHelixPropagatorAny" ),
updator = cms.string( "hltESPKFUpdator" ),
alwaysUseInvalidHits = cms.bool( True ),
TTRHBuilder = cms.string( "hltESPTTRHBWithTrackAngle" ),
MeasurementTrackerName = cms.string( "hltESPMeasurementTracker" ),
intermediateCleaning = cms.bool( False ),
lostHitPenalty = cms.double( 30.0 )
)
HLTPSetPvClusterComparer = cms.PSet(
track_pt_min = cms.double( 2.5 ),
track_pt_max = cms.double( 10.0 ),
track_chi2_max = cms.double( 9999999.0 ),
track_prob_min = cms.double( -1.0 )
)
HLTIter0PSetTrajectoryBuilderIT = cms.PSet(
propagatorAlong = cms.string( "PropagatorWithMaterialParabolicMf" ),
trajectoryFilter = cms.PSet( refToPSet_ = cms.string( "HLTIter0PSetTrajectoryFilterIT" ) ),
maxCand = cms.int32( 2 ),
ComponentType = cms.string( "CkfTrajectoryBuilder" ),
propagatorOpposite = cms.string( "PropagatorWithMaterialParabolicMfOpposite" ),
estimator = cms.string( "hltESPChi2ChargeMeasurementEstimator9" ),
TTRHBuilder = cms.string( "hltESPTTRHBWithTrackAngle" ),
updator = cms.string( "hltESPKFUpdator" ),
alwaysUseInvalidHits = cms.bool( False ),
intermediateCleaning = cms.bool( True ),
lostHitPenalty = cms.double( 30.0 )
)
HLTIter0PSetTrajectoryFilterIT = cms.PSet(
minPt = cms.double( 0.3 ),
minHitsMinPt = cms.int32( 3 ),
ComponentType = cms.string( "CkfBaseTrajectoryFilter" ),
maxLostHits = cms.int32( 1 ),
maxNumberOfHits = cms.int32( 100 ),
maxConsecLostHits = cms.int32( 1 ),
minimumNumberOfHits = cms.int32( 3 ),
nSigmaMinPt = cms.double( 5.0 ),
chargeSignificance = cms.double( -1.0 ),
minGoodStripCharge = cms.PSet( refToPSet_ = cms.string( "HLTSiStripClusterChargeCutLoose" ) ),
maxCCCLostHits = cms.int32( 1 ),
seedExtension = cms.int32( 0 ),
strictSeedExtension = cms.bool( False ),
minNumberOfHitsForLoopers = cms.int32( 13 ),
minNumberOfHitsPerLoop = cms.int32( 4 ),
extraNumberOfHitsBeforeTheFirstLoop = cms.int32( 4 ),
maxLostHitsFraction = cms.double( 999.0 ),
constantValueForLostHitsFractionFilter = cms.double( 1.0 ),
seedPairPenalty = cms.int32( 0 )
)
HLTPSetPvClusterComparerForBTag = cms.PSet(
track_pt_min = cms.double( 0.1 ),
track_pt_max = cms.double( 20.0 ),
track_chi2_max = cms.double( 20.0 ),
track_prob_min = cms.double( -1.0 )
)
HLTSeedFromConsecutiveHitsTripletOnlyCreator = cms.PSet(
ComponentName = cms.string( "SeedFromConsecutiveHitsTripletOnlyCreator" ),
propagator = cms.string( "PropagatorWithMaterialParabolicMf" ),
SeedMomentumForBOFF = cms.double( 5.0 ),
OriginTransverseErrorMultiplier = cms.double( 1.0 ),
MinOneOverPtError = cms.double( 1.0 ),
magneticField = cms.string( "ParabolicMf" ),
TTRHBuilder = cms.string( "hltESPTTRHBWithTrackAngle" ),
forceKinematicWithRegionDirection = cms.bool( False )
)
HLTSeedFromConsecutiveHitsCreator = cms.PSet(
ComponentName = cms.string( "SeedFromConsecutiveHitsCreator" ),
propagator = cms.string( "PropagatorWithMaterial" ),
SeedMomentumForBOFF = cms.double( 5.0 ),
OriginTransverseErrorMultiplier = cms.double( 1.0 ),
MinOneOverPtError = cms.double( 1.0 ),
TTRHBuilder = cms.string( "hltESPTTRHBWithTrackAngle" ),
forceKinematicWithRegionDirection = cms.bool( False ),
magneticField = cms.string( "" )
)
HLTIter2HighPtTkMuPSetTrajectoryBuilderIT = cms.PSet(
propagatorAlong = cms.string( "PropagatorWithMaterialParabolicMf" ),
trajectoryFilter = cms.PSet( refToPSet_ = cms.string( "HLTIter2HighPtTkMuPSetTrajectoryFilterIT" ) ),
maxCand = cms.int32( 2 ),
ComponentType = cms.string( "CkfTrajectoryBuilder" ),
propagatorOpposite = cms.string( "PropagatorWithMaterialParabolicMfOpposite" ),
estimator = cms.string( "hltESPChi2ChargeMeasurementEstimator30" ),
TTRHBuilder = cms.string( "hltESPTTRHBWithTrackAngle" ),
updator = cms.string( "hltESPKFUpdator" ),
alwaysUseInvalidHits = cms.bool( False ),
intermediateCleaning = cms.bool( True ),
lostHitPenalty = cms.double( 30.0 ),
MeasurementTrackerName = cms.string( "hltIter2HighPtTkMuESPMeasurementTracker" )
)
HLTIter2HighPtTkMuPSetTrajectoryFilterIT = cms.PSet(
minPt = cms.double( 0.3 ),
minHitsMinPt = cms.int32( 3 ),
ComponentType = cms.string( "CkfBaseTrajectoryFilter" ),
maxLostHits = cms.int32( 1 ),
maxNumberOfHits = cms.int32( 100 ),
maxConsecLostHits = cms.int32( | |
<reponame>jatin837/PyBaMM<gh_stars>1-10
#
# Classes for calcuting the effective resistance of current collectors in a pouch cell
#
import pybamm
class EffectiveResistance(pybamm.BaseModel):
"""
A model which calculates the effective Ohmic resistance of the current
collectors in the limit of large electrical conductivity. For details see [1]_.
Note that this formulation assumes uniform *potential* across the tabs. See
:class:`pybamm.AlternativeEffectiveResistance2D` for the formulation that
assumes a uniform *current density* at the tabs (in 1D the two formulations
are equivalent).
Parameters
----------
options: dict
A dictionary of options to be passed to the model. The options that can
be set are listed below.
* "dimensionality" : int, optional
Sets the dimension of the current collector problem. Can be 1
(default) or 2.
name : str, optional
The name of the model.
References
----------
.. [1] <NAME>, <NAME>, <NAME>, CP Please and <NAME>. “Asymptotic
Reduction of a Lithium-ion Pouch Cell Model”. Submitted, 2020.
**Extends:** :class:`pybamm.BaseModel`
"""
def __init__(
self, options=None, name="Effective resistance in current collector model"
):
super().__init__(name)
self.options = options
self.param = pybamm.LithiumIonParameters()
# Set default length scales
self.length_scales = {
"current collector y": self.param.L_z,
"current collector z": self.param.L_z,
}
self.variables = self.get_fundamental_variables()
self.set_algebraic(self.variables)
self.set_boundary_conditions(self.variables)
self.set_initial_conditions(self.variables)
pybamm.citations.register("Timms2021")
def get_fundamental_variables(self):
# Get necessary parameters
param = self.param
l_cn = param.l_cn
l_cp = param.l_cp
sigma_cn_dbl_prime = param.sigma_cn_dbl_prime
sigma_cp_dbl_prime = param.sigma_cp_dbl_prime
delta = param.delta # aspect ratio
# Set model variables: Note: we solve using a scaled version that is
# better conditioned
R_cn_scaled = pybamm.Variable(
"Scaled negative current collector resistance", domain="current collector"
)
R_cp_scaled = pybamm.Variable(
"Scaled positive current collector resistance", domain="current collector"
)
R_cn = delta * R_cn_scaled / (l_cn * sigma_cn_dbl_prime)
R_cp = delta * R_cp_scaled / (l_cp * sigma_cp_dbl_prime)
# Define effective current collector resistance
if self.options["dimensionality"] == 1:
R_cc_n = -pybamm.z_average(R_cn)
R_cc_p = -pybamm.z_average(R_cp)
elif self.options["dimensionality"] == 2:
R_cc_n = -pybamm.yz_average(R_cn)
R_cc_p = -pybamm.yz_average(R_cp)
R_cc = R_cc_n + R_cc_p
R_scale = param.potential_scale / param.I_typ
variables = {
"Scaled negative current collector resistance": R_cn_scaled,
"Negative current collector resistance": R_cn,
"Negative current collector resistance [Ohm]": R_cn * R_scale,
"Scaled positive current collector resistance": R_cp_scaled,
"Positive current collector resistance": R_cp,
"Positive current collector resistance [Ohm]": R_cp * R_scale,
"Effective current collector resistance": R_cc,
"Effective current collector resistance [Ohm]": R_cc * R_scale,
"Effective negative current collector resistance": R_cc_n,
"Effective negative current collector resistance [Ohm]": R_cc_n * R_scale,
"Effective positive current collector resistance": R_cc_p,
"Effective positive current collector resistance [Ohm]": R_cc_p * R_scale,
}
# Add spatial variables
var = pybamm.standard_spatial_vars
L_y = param.L_y
L_z = param.L_z
if self.options["dimensionality"] == 1:
variables.update({"z": var.z, "z [m]": var.z * L_z})
elif self.options["dimensionality"] == 2:
variables.update(
{"y": var.y, "y [m]": var.y * L_y, "z": var.z, "z [m]": var.z * L_z}
)
return variables
def set_algebraic(self, variables):
R_cn_scaled = variables["Scaled negative current collector resistance"]
R_cp_scaled = variables["Scaled positive current collector resistance"]
self.algebraic = {
R_cn_scaled: pybamm.laplacian(R_cn_scaled) - pybamm.source(1, R_cn_scaled),
R_cp_scaled: pybamm.laplacian(R_cp_scaled) - pybamm.source(1, R_cp_scaled),
}
def set_boundary_conditions(self, variables):
R_cn_scaled = variables["Scaled negative current collector resistance"]
R_cp_scaled = variables["Scaled positive current collector resistance"]
if self.options["dimensionality"] == 1:
self.boundary_conditions = {
R_cn_scaled: {
"negative tab": (0, "Dirichlet"),
"no tab": (0, "Neumann"),
},
R_cp_scaled: {
"positive tab": (0, "Dirichlet"),
"no tab": (0, "Neumann"),
},
}
elif self.options["dimensionality"] == 2:
self.boundary_conditions = {
R_cn_scaled: {
"negative tab": (0, "Dirichlet"),
"positive tab": (0, "Neumann"),
},
R_cp_scaled: {
"positive tab": (0, "Dirichlet"),
"negative tab": (0, "Neumann"),
},
}
def set_initial_conditions(self, variables):
R_cn_scaled = variables["Scaled negative current collector resistance"]
R_cp_scaled = variables["Scaled positive current collector resistance"]
self.initial_conditions = {
R_cn_scaled: pybamm.Scalar(0),
R_cp_scaled: pybamm.Scalar(0),
}
def post_process(self, solution, param_values, V_av, I_av):
"""
Calculates the potentials in the current collector and the terminal
voltage given the average voltage and current.
Note: This takes in the *processed* V_av and I_av from a 1D simulation
representing the average cell behaviour and returns a dictionary of
processed potentials.
"""
param = self.param
pot_scale = param_values.evaluate(param.potential_scale)
U_ref = param_values.evaluate(param.U_p_ref - param.U_n_ref)
# Process resistances
R_cn = solution["Negative current collector resistance"]
R_cp = solution["Positive current collector resistance"]
R_cc = solution["Effective current collector resistance"]
# Create callable combination of ProcessedVariable objects for potentials
# and terminal voltage
def V(t):
"Account for effective current collector resistance"
return V_av(t) - I_av(t) * R_cc(t)
def phi_s_cn(t, z, y=None):
return R_cn(y=y, z=z) * I_av(t=t)
def phi_s_cp(t, z, y=None):
return V(t) - R_cp(y=y, z=z) * I_av(t=t)
def V_cc(t, z, y=None):
return phi_s_cp(t, z, y=y) - phi_s_cn(t, z, y=y)
def V_dim(t):
return U_ref + V(t) * pot_scale
def phi_s_cn_dim(t, z, y=None):
return phi_s_cn(t, z, y=y) * pot_scale
def phi_s_cp_dim(t, z, y=None):
return U_ref + phi_s_cp(t, z, y=y) * pot_scale
def V_cc_dim(t, z, y=None):
return U_ref + V_cc(t, z, y=y) * pot_scale
processed_vars = {
"Negative current collector potential": phi_s_cn,
"Negative current collector potential [V]": phi_s_cn_dim,
"Positive current collector potential": phi_s_cp,
"Positive current collector potential [V]": phi_s_cp_dim,
"Local current collector potential difference": V_cc,
"Local current collector potential difference [V]": V_cc_dim,
"Terminal voltage": V,
"Terminal voltage [V]": V_dim,
}
return processed_vars
@property
def default_parameter_values(self):
return pybamm.ParameterValues(chemistry=pybamm.parameter_sets.Marquis2019)
@property
def default_geometry(self):
geometry = {}
param = self.param
var = pybamm.standard_spatial_vars
if self.options["dimensionality"] == 1:
geometry["current collector"] = {
var.z: {"min": 0, "max": 1},
"tabs": {
"negative": {"z_centre": param.centre_z_tab_n},
"positive": {"z_centre": param.centre_z_tab_p},
},
}
elif self.options["dimensionality"] == 2:
geometry["current collector"] = {
var.y: {"min": 0, "max": param.l_y},
var.z: {"min": 0, "max": param.l_z},
"tabs": {
"negative": {
"y_centre": param.centre_y_tab_n,
"z_centre": param.centre_z_tab_n,
"width": param.l_tab_n,
},
"positive": {
"y_centre": param.centre_y_tab_p,
"z_centre": param.centre_z_tab_p,
"width": param.l_tab_p,
},
},
}
return pybamm.Geometry(geometry)
@property
def default_var_pts(self):
var = pybamm.standard_spatial_vars
return {var.y: 32, var.z: 32}
@property
def default_submesh_types(self):
if self.options["dimensionality"] == 1:
return {"current collector": pybamm.MeshGenerator(pybamm.Uniform1DSubMesh)}
elif self.options["dimensionality"] == 2:
return {
"current collector": pybamm.MeshGenerator(pybamm.ScikitUniform2DSubMesh)
}
@property
def default_spatial_methods(self):
if self.options["dimensionality"] == 1:
return {"current collector": pybamm.FiniteVolume()}
elif self.options["dimensionality"] == 2:
return {"current collector": pybamm.ScikitFiniteElement()}
@property
def default_solver(self):
return pybamm.CasadiAlgebraicSolver()
@property
def options(self):
return self._options
@options.setter
def options(self, extra_options):
default_options = {"dimensionality": 1}
extra_options = extra_options or {}
options = pybamm.FuzzyDict(default_options)
# any extra options overwrite the default options
for name, opt in extra_options.items():
if name in default_options:
options[name] = opt
else:
raise pybamm.OptionError(
"Option '{}' not recognised. Best matches are {}".format(
name, options.get_best_matches(name)
)
)
if options["dimensionality"] not in [1, 2]:
raise pybamm.OptionError(
"Dimension of current collectors must be 1 or 2, not {}".format(
options["dimensionality"]
)
)
self._options = options
class AlternativeEffectiveResistance2D(pybamm.BaseModel):
"""
A model which calculates the effective Ohmic resistance of the 2D current
collectors in the limit of large electrical conductivity. This model assumes
a uniform *current density* at the tabs and the solution is computed by first
solving and auxilliary problem which is the related to the resistances.
**Extends:** :class:`pybamm.BaseModel`
"""
def __init__(self):
super().__init__()
self.name = "Effective resistance in current collector model (2D)"
self.param = pybamm.LithiumIonParameters()
# Set default length scales
self.length_scales = {
"current collector y": self.param.L_z,
"current collector z": self.param.L_z,
}
# Get necessary parameters
param = self.param
l_cn = param.l_cn
l_cp = param.l_cp
l_tab_p = param.l_tab_p
A_tab_p = l_cp * l_tab_p
sigma_cn_dbl_prime = param.sigma_cn_dbl_prime
sigma_cp_dbl_prime = param.sigma_cp_dbl_prime
delta = param.delta
# Set model variables -- we solve a auxilliary problem in each current collector
# then relate this to the potentials and resistances later
f_n = pybamm.Variable(
"Unit solution in negative current collector", domain="current collector"
)
f_p = pybamm.Variable(
"Unit solution in positive current collector", domain="current collector"
)
# Governing equations -- we impose that the average of f_p is zero
# by introducing a Lagrange multiplier
c = pybamm.Variable("Lagrange multiplier")
self.algebraic = {
f_n: pybamm.laplacian(f_n) + pybamm.source(1, f_n),
f_p: pybamm.laplacian(f_p)
- pybamm.source(1, f_p)
+ c * pybamm.DefiniteIntegralVector(f_p, vector_type="column"),
c: pybamm.yz_average(f_p),
}
# Boundary conditons
pos_tab_bc = l_cp / A_tab_p
self.boundary_conditions = {
f_n: {"negative tab": (0, "Dirichlet"), "positive tab": (0, "Neumann")},
f_p: {
"negative tab": (0, "Neumann"),
"positive tab": (pos_tab_bc, "Neumann"),
},
}
# "Initial conditions" provides initial guess for solver
self.initial_conditions = {
f_n: pybamm.Scalar(0),
f_p: pybamm.Scalar(0),
c: pybamm.Scalar(0),
}
# Define | |
jump_slices = jump_part_sampler(self.jump_part_params,self.slice_areas_matrix,self.jump_part_name)
if slice_convolution_type == 'fft':
gaussian_slices = np.concatenate([zero_matrix,gaussian_slices],axis=1)
jump_slices = np.concatenate([zero_matrix,jump_slices],axis=1)
#matrix with 1's on and below the secondary diagonal
#flip the filter to agree with np convention
self.gaussian_values[simulation_nr,:] = convolve2d(gaussian_slices,filter_[::-1,::-1],'valid')[0]
self.jump_values[simulation_nr,:] = convolve2d(jump_slices,filter_[::-1,::-1],'valid')[0]
elif slice_convolution_type == 'diagonals':
self.gaussian_values[simulation_nr,:] = cumulative_and_diagonal_sums(gaussian_slices)
self.jump_values[simulation_nr,:] = cumulative_and_diagonal_sums(jump_slices)
def simulate_slice_infinite_decorrelation_time(self,slice_convolution_type):
"""Helper for the `simulate_slice` method."""
zero_matrix = np.zeros([self.nr_trawls,self.nr_trawls-1])
filter_ = np.fliplr(np.tril(np.ones(self.nr_trawls),k=0))
for simulation_nr in range(self.nr_simulations):
gaussian_slices = gaussian_part_sampler(self.gaussian_part_params,self.slice_areas_matrix)
#the lower triangular part of the matrix is made oup of 0's, which can result in an error
#in the scipy.stats sampler (for example, if the levy seed is gamma)
#to prevent this, we extract the upper triangular part of the matrix as a vector
#sample this way, then recast the samples as an upper triangular matrix
slice_areas_row = (np.fliplr(self.slice_areas_matrix))[np.triu_indices(self.slice_areas_matrix.shape[0], k = 0)]
jump_slices_row = jump_part_sampler(self.jump_part_params,slice_areas_row,self.jump_part_name)
jump_slices = np.zeros(gaussian_slices.shape)
jump_slices[np.triu_indices(jump_slices.shape[0], k = 0)] = jump_slices_row
jump_slices = np.fliplr(jump_slices)
if slice_convolution_type == 'fft':
gaussian_slices = np.concatenate([zero_matrix,gaussian_slices],axis=1)
jump_slices = np.concatenate([zero_matrix,jump_slices],axis=1)
self.gaussian_values[simulation_nr,:] = convolve2d(gaussian_slices,filter_[::-1,::-1],'valid')[0]
self.jump_values[simulation_nr,:] = convolve2d(jump_slices,filter_[::-1,::-1],'valid')[0]
elif slice_convolution_type == 'diagonals':
self.gaussian_values[simulation_nr,:] = cumulative_and_diagonal_sums(gaussian_slices)
self.jump_values[simulation_nr,:] = cumulative_and_diagonal_sums(jump_slices)
def simulate_slice(self,slice_convolution_type):
"""implements algorithm [] from [] and simulates teh trawl process at
\(\\tau,\\ldots,\\text{nr_trawls}\ \\tau\). `slice_convolution_type` can be either [to add]"""
if self.decorrelation_time == -np.inf:
self.compute_slice_areas_infinite_decorrelation_time()
self.simulate_slice_infinite_decorrelation_time(slice_convolution_type)
elif self.decorrelation_time > -np.inf:
assert(self.trawl_function(self.decorrelation_time)) == 0,'please check decorrelation time'
self.compute_slice_areas_finite_decorrelation_time()
self.simulate_slice_finite_decorrelation_time(slice_convolution_type)
#self.values = self.gaussian_values + self.jump_values
############################ II Grid ############################
def grid_creation(self,min_t,max_t):
"""Creates a grid on \([0,\phi(0)] \\times [\\text{min_t}, \\text{max_t}]\). Each cell is represented by
the coordinates of its bottom left corner. To each cell we associate a sample from each of the gaussian
and jump parts of the trawl process.
Returns:
gaussian_values: array with the Gaussian of the Levy basis evaluated over the cells
jump_values: array with the jump part of the Levy basis evaluated over the cells
"""
coords = np.mgrid[0:self.trawl_function(0):self.mesh_size,min_t:max_t:self.mesh_size]
x, t = coords[0].flatten(), coords[1].flatten()
areas = self.vol * np.ones([self.nr_simulations,len(t)])
gaussian_values = gaussian_part_sampler(self.gaussian_part_params,areas)
jump_values = jump_part_sampler(self.jump_part_params,areas,self.jump_part_name)
return x,t,gaussian_values,jump_values
def grid_update(self,i,t,gaussian_values,jump_values):
"""Inputs the values of the Levy basis evaluated over the grid cells on \([\\tau_{i-1}+\\text{truncation_grid},\\tau_{i-1}] \\times [0,\\phi(0)]\),
removes the values corresponding to cells with time coordinates less than \(\\tau_{i} + \\text{truncation_grid}\) and adds new samples
for the levy basis evaluated over the grid cells with time coordinates in \([\\tau_{i-1},\\tau_i]\) (see figure).
Assumes that the consecutive ambit sets at times \(\\tau_{i-1},\\tau_i\) are not disjoint, i.e.
\(\\tau_i + \\text{truncation_grid} < \\tau_{i-1}\).
Args:
i: index of the trawl to be simulated
t: time coordinates of the cells of the grid on \([\\tau_{i-1},\\tau_{i-1}+\\text{truncation_grid}] \\times [0,\phi(0)]\)
gaussian_values: gaussian values for the grid on \([\\tau_{i-1},\\tau_{i-1}+\\text{truncation_grid}] \\times [0,\phi(0)]\)
jump_values: jump values for the grid on \([\\tau_{i-1},\\tau_{i-1}+\\text{truncation_grid}] \\times [0,\phi(0)\)
Returns:
gaussian_values: gaussian values for the grid cells on \([\\tau_{i},\\tau_{i}+\\text{truncation_grid}] \\times [0,\phi(0)]\)
jump_values: jump values for the grid cells on \([\\tau_{i},\\tau_{i}+\\text{truncation_grid}] \\times [0,\phi(0)]\)
"""
ind_to_keep = t >= (self.times_grid[i] + self.truncation_grid)
t[~ind_to_keep] += -self.truncation_grid
areas = self.vol * np.ones([self.nr_simulations,sum(~ind_to_keep)])
#print(gaussian_values[:,~ind_to_keep].shape)
#print(self.gaussian_part_sampler(areas).shape)
gaussian_values[:,~ind_to_keep] = gaussian_part_sampler(self.gaussian_part_params,areas)
jump_values[:,~ind_to_keep] = jump_part_sampler(self.jump_part_params,areas,self.jump_part_name)
#print('ind to keep sum is ', ind_to_keep.sum())
#print('gaussian is ',gaussian_values.shape)
#print('non_gaussian_values ',non_gaussian_values[:,ind_to_keep].shape)
#print('new_gaussian_values ',new_gaussian_values.shape)
#print('t new shape is ',t.shape)
#print('x shape is', x.shape)
return t,gaussian_values,jump_values
def simulate_grid(self):
"""Simulate the trawl proces at times `self.times_grid`, which don't have to be
equally distant, via the grid method."""
#If `times_grid` are equidistnant, we do not need to compute `indicators` at each iteration, speeding up the process
for i in range(len(self.times_grid)):
if (i==0) or (self.times_grid[i-1] <= self.times_grid[i] + self.truncation_grid):
#check that we are creating the grid for the first time or that
#trawls at time i-1 and i have empty intersection
x,t,gaussian_values, jump_values = self.grid_creation(self.times_grid[i] + self.truncation_grid, self.times_grid[i])
elif self.times_grid[i-1] > self.times_grid[i] + self.truncation_grid:
#check that we have non empty intersection and update the grid
t,gaussian_values,jump_values = self.grid_update(i,t,gaussian_values,jump_values)
indicators = x < self.trawl_function(t-self.times_grid[i])
#print(gaussian_values.shape,indicators.shape)
self.gaussian_values[:,i] = gaussian_values @ indicators
self.jump_values[:,i] = jump_values @ indicators
#self.values = self.gaussian_values + self.jump_values
########################### III cpp ###########################
# @njit
def simulate_cpp(self):
""" text to be added"""
min_t = min(self.cpp_times) + self.cpp_truncation
max_t = max(self.cpp_times)
min_x = 0
max_x = self.trawl_function(0)
for simulation_nr in range(self.nr_simulations):
points_x, points_t, associated_values = generate_cpp_points(min_x = min_x, max_x = max_x,
min_t = min_t, max_t = max_t, cpp_part_name = self.cpp_part_name,
cpp_part_params = self.cpp_part_params, cpp_intensity = self.cpp_intensity,
custom_sampler = self.custom_sampler)
#(x_i,t_i) in A_t if t < t_i and x_i < phi(t_i-t)
indicator_matrix = np.tile(points_x[:,np.newaxis],(1,self.nr_trawls)) < \
self.trawl_function(np.subtract.outer(points_t, self.cpp_times))
self.cpp_values[simulation_nr,:] = associated_values @ indicator_matrix
####################### simulate meta-method #######################
def simulate(self,method,slice_convolution_type='diagonals'):
"""Function to simulate from the trawl function. Contains sanity checks
for the simulation parameters and uses helper functions for each simulation
method.
Args:
method: one of the strings `cpp`, `grid` or `slice`
slice_convolution_type: if method is set to `slice`, this can be one of the strings `diagonals` or `ftt`, depending on the way we add up the simulated slices. This argument is ignored if method is set to `grid` or `cpp`."""
#general checks
assert isinstance(self.nr_simulations,int) and self.nr_simulations >0
assert method in {'cpp','grid','slice'},'simulation method not supported'
check_trawl_function(self.trawl_function)
check_gaussian_params(self.gaussian_part_params)
#algorithm specific checks and attribute setting
if method == 'grid':
check_jump_part_and_params(self.jump_part_name,self.jump_part_params)
check_grid_params(self.mesh_size,self.truncation_grid,self.times_grid)
self.nr_trawls = len(self.times_grid)
self.vol = self.mesh_size **2
elif method == 'cpp':
check_cpp_params(self.cpp_part_name, self.cpp_part_params,self.cpp_intensity,self.custom_sampler)
self.nr_trawls = len(self.cpp_times)
elif method == 'slice':
assert slice_convolution_type in {'fft','diagonals'}
assert isinstance(self.nr_trawls,int) and self.nr_trawls > 0,'nr_trawls should be a strictly positive integer'
check_jump_part_and_params(self.jump_part_name,self.jump_part_params)
self.gaussian_values = np.zeros(shape = [self.nr_simulations,self.nr_trawls])
self.jump_values = np.zeros(shape = [self.nr_simulations,self.nr_trawls])
self.cpp_values = np.zeros(shape = [self.nr_simulations,self.nr_trawls])
if method == 'grid':
self.simulate_grid()
elif method == 'cpp':
self.simulate_cpp()
elif method == 'slice':
self.simulate_slice(slice_convolution_type)
self.values = self.gaussian_values + self.jump_values + self.cpp_values
def theoretical_acf(self,t_values):
"""Computes the theoretical acf of the trawl process
Args:
t_values: array of time values
Returns:
d_acf: a dictionary of the type \(t: \\text{corr}(X_0,X_t)\), where \(t\) ranges over the input array `t_values`.
"""
total_area = quad(self.trawl_function,a=-np.inf,b= 0)[0]
d_acf=dict()
for t in t_values:
d_acf[t] = quad(self.trawl_function,a=-np.inf,b= -t)[0]/total_area
return d_acf
######################################################################
### Forecasting: determinstic and probabilistic ###
######################################################################
def fit_gmm(self,input_values,envelope,levy_seed,lags,initial_guess=None):
assert len(input_values.shape) == 2
assert isinstance(lags,tuple)
envelope_params = fit_trawl_envelope_gmm(self.tau,input_values,lags,envelope,initial_guess)
levy_seed_params = fit_trawl_marginal(input_values,levy_seed)
# {'envelope: exponential, levy_seed: gamma', lags : (1,2,3), 'params' :
# {'envelope_params': tuple of tuples , levy_seed_params': tuple of tuples}}
params_to_add = {'envelope_params':envelope_params,'levy_seed_params': levy_seed_params}
key_to_add = f'envelope:{envelope},levy_seed:{levy_seed},lags:{lags}'
self.infered_parameters_gmm[key_to_add] = params_to_add
def fit_cl(self,input_values,envelope,levy_seed,max_lag,initial_guess=None):
pass
def predict(self,input_values, steps_ahead, deterministic, fitting_method, envelope, levy_seed, lags, nr_samples = None):
#input_values must be a 2 dimensional array
#key = f'envelope:{envelope},levy_seed:{levy_seed},lags:{lags},params:{params}'
#params_dict = self.infered_parameters_gmm[key]
assert isinstance(input_values,np.ndarray) and len(input_values.shape) == 2
assert fitting_method in ['gmm','cl']
assert deterministic in [True,False]
assert isinstance(lags,tuple)
##get the fitted parameters for teh envelope and for the levy seed from the attribute self.infered_parameters_gmm
key = f'envelope:{envelope},levy_seed:{levy_seed},lags:{lags}'
if fitting_method == 'gmm':
d__ = self.infered_parameters_gmm[key]
elif fitting_method == 'cl':
d__ = self.infered_parameters_cl[key]
envelope_params, levy_seed_params = d__['envelope_params'],d__['levy_seed_params']
nr_simulations, simulation_length = input_values.shape
d={}
for nr_steps_ahead in steps_ahead:
if deterministic == True:
array_to_add = np.zeros([nr_simulations,simulation_length - max(lags) * (levy_seed == 'gaussian')])
elif deterministic == False:
array_to_add = np.zeros([nr_simulations, simulation_length - max(lags) *(levy_seed == 'gaussian'),
nr_samples])
for i in range(nr_simulations):
if deterministic == True:
array_to_add[i] = deterministic_forecasting(tau = self.tau, nr_steps_ahead = nr_steps_ahead ,
values = input_values[i], levy_seed = levy_seed, levy_seed_params = levy_seed_params[i],
envelope = envelope, envelope_params = envelope_params[i],
envelope_function = None, gaussian_lags = max(lags))
elif deterministic == False:
array_to_add[i] = probabilistic_forecasting(tau = self.tau, nr_steps_ahead = nr_steps_ahead, values = input_values[i],
levy_seed = levy_seed, levy_seed_params = levy_seed_params[i],
envelope = envelope, envelope_params = envelope_params[i], nr_samples = nr_samples,
envelope_function = None, gaussian_lags = max(lags))
d[nr_steps_ahead] = array_to_add
return d
#if type_ == 'deterministic':
# deterministic_forecasting(tau_ahead,values,levy_seed,levy_seed_params,envelope,
# | |
#!/usr/bin/env python3
#
# Copyright 2022 Graviti. Licensed under MIT License.
#
"""Template factory releated classes."""
from itertools import groupby
from typing import (
Any,
Callable,
Dict,
Generic,
Iterable,
Iterator,
List,
Optional,
Tuple,
Type,
TypeVar,
Union,
)
import graviti.portex.ptype as PTYPE
from graviti.portex.base import PortexRecordBase, PortexType
from graviti.portex.field import ConnectedFields, Fields, FrozenFields
from graviti.portex.package import Imports
_C = TypeVar("_C", str, float, bool, None)
_CFF = TypeVar("_CFF", bound="ConnectedFieldsFactory")
class Factory:
"""The base class of the template factory."""
is_unpack: bool = False
keys: Dict[str, Any]
def __call__(self, **_: Any) -> Any:
"""Apply the input arguments to the template.
Arguments:
_: The input arguments.
"""
...
class FrozenFieldsFactory(Factory):
"""The factory for FrozenFields.
Arguments:
decl: The decalaration of frozen fields.
imports: The :class:`Imports` instance to specify the import scope of the fields.
"""
def __init__(self, decl: Iterable[Dict[str, Any]], imports: Imports) -> None:
self._factories = [FieldFactory(field, imports) for field in decl]
def __call__(self, **kwargs: Any) -> FrozenFields:
"""Apply the input arguments to the FrozenFields factory.
Arguments:
kwargs: The input arguments.
Returns:
The applied FrozenFields.
"""
return FrozenFields(
filter(
bool,
(factory(**kwargs) for factory in self._factories), # type: ignore[misc]
)
)
class FrozenFieldsFactoryWrapper(Factory):
"""The factory for FrozenFields which needs kwargs transformed.
Arguments:
factory: The factory of frozen fields.
kwargs_transformer: The method to transform the kwargs to the kwargs of base type.
"""
def __init__(
self,
factory: Union[FrozenFieldsFactory, "FrozenFieldsFactoryWrapper"],
kwargs_transformer: Callable[..., Dict[str, Any]],
) -> None:
self._factory = factory
self._kwargs_transformer = kwargs_transformer
def __call__(self, **kwargs: Any) -> FrozenFields:
"""Apply the input arguments to the base FrozenFields factory.
Arguments:
kwargs: The input arguments.
Returns:
The applied FrozenFields.
"""
return self._factory(**self._kwargs_transformer(**kwargs))
UnionFieldsFactory = Union["VariableFactory", FrozenFieldsFactory, FrozenFieldsFactoryWrapper]
class ConnectedFieldsFactory:
"""The factory for ConnectedFields.
Arguments:
decl: A dict which indicates a portex type.
class_: The base type.
imports: The :class:`Imports` instance to specify the import scope of the template.
kwargs_transformer: The method to transform the kwargs to the kwargs of base type.
"""
_factories: List[UnionFieldsFactory]
def __init__(
self,
decl: Dict[str, Any],
class_: Type[PortexRecordBase],
imports: Imports,
kwargs_transformer: Callable[..., Dict[str, Any]],
) -> None:
factories: List[UnionFieldsFactory] = []
for base_factory in class_._fields_factory._factories:
if not isinstance(base_factory, VariableFactory):
factories.append(FrozenFieldsFactoryWrapper(base_factory, kwargs_transformer))
continue
fields_decl = decl[base_factory.key]
if isinstance(fields_decl, str) and fields_decl.startswith("$"):
factories.append(VariableFactory(fields_decl[1:]))
continue
groups = groupby(fields_decl, lambda x: isinstance(x, str) and x.startswith("+$"))
for is_mutable, fields in groups:
if is_mutable:
for unpack_fields in fields:
factories.append(VariableFactory(unpack_fields[2:]))
else:
factories.append(FrozenFieldsFactory(fields, imports))
self._factories = factories
def __call__(self, **kwargs: Any) -> ConnectedFields:
"""Apply the input arguments to the ConnectedFields factory.
Arguments:
kwargs: The input arguments.
Returns:
The applied ConnectedFields.
"""
return ConnectedFields(factory(**kwargs) for factory in self._factories)
@classmethod
def from_parameter_name(cls: Type[_CFF], name: str) -> _CFF:
"""Create ConnectedFieldsFactory for Fields with the given parameter name.
Arguments:
name: The parameter name of the input fields.
Returns:
The created ConnectedFieldsFactory.
"""
obj: _CFF = object.__new__(cls)
obj._factories = [VariableFactory(name)]
return obj
class TypeFactory(Factory):
"""The template factory for portex type.
Arguments:
decl: A dict which indicates a portex type.
"""
def __init__(self, decl: Dict[str, Any], imports: Imports) -> None:
class_ = imports[decl["type"]]
factories = {}
keys = {}
for name, parameter in class_.params.items():
try:
value = decl[name]
except KeyError as error:
if parameter.required:
raise KeyError(f"Parameter '{name}' is required") from error
continue
factory = factory_creator(value, imports, parameter.ptype)
if factory.is_unpack:
raise ValueError("Use array unpack in object value is not allowed")
factories[name] = factory
keys.update(factory.keys)
if "+" in decl:
unpack_factory = mapping_unpack_factory_creator(decl["+"], PTYPE.Mapping)
keys.update(unpack_factory.keys)
self._unpack_factory = unpack_factory
self._factories = factories
self.keys = keys
self.class_ = class_
def __call__(self, **kwargs: Any) -> PortexType:
"""Apply the input arguments to the type template.
Arguments:
kwargs: The input arguments.
Returns:
The applied Portex type.
"""
return self.class_(**self.transform_kwargs(**kwargs)) # type: ignore[call-arg]
def transform_kwargs(self, **kwargs: Any) -> Dict[str, Any]:
"""Transform the keyword arguments to what the base type needs.
Arguments:
kwargs: The input arguments.
Returns:
The transformed keyword arguments.
"""
type_kwargs: Dict[str, Any] = (
self._unpack_factory(**kwargs) if hasattr(self, "_unpack_factory") else {}
)
type_kwargs.update({key: factory(**kwargs) for key, factory in self._factories.items()})
return type_kwargs
class ConstantFactory(Factory, Generic[_C]):
"""The template factory for a constant.
Arguments:
decl: The constant to be created by the factory.
"""
def __init__(self, decl: _C) -> None:
self._constant: _C = decl
self.keys: Dict[str, Any] = {}
def __call__(self, **_: Any) -> _C:
"""Get the constant stored in the factory.
Arguments:
_: The input arguments.
Returns:
The constant stored in the factory.
"""
return self._constant
class VariableFactory(Factory):
"""The template factory for a variable.
Arguments:
decl: The parameter name of the variable.
ptype: The parameter type.
"""
def __init__(self, decl: str, ptype: PTYPE.PType = PTYPE.Any, is_unpack: bool = False) -> None:
self.key = decl
self.keys = {decl: ptype}
self.is_unpack = is_unpack
def __call__(self, **kwargs: Any) -> Any:
"""Apply the input arguments to the variable template.
Arguments:
kwargs: The input arguments.
Returns:
The applied variable.
"""
return kwargs[self.key]
class ListFactory(Factory):
"""The template factory for a list.
Arguments:
decl: A list template.
ptype: The parameter type of the list.
"""
def __init__(self, decl: List[Any], ptype: PTYPE.PType = PTYPE.Any) -> None:
factories = []
keys = {}
for value in decl:
factory = factory_creator(value, None, ptype)
factories.append(factory)
keys.update(factory.keys)
self._factories = factories
self.keys = keys
def __call__(self, **kwargs: Any) -> List[Any]:
"""Apply the input arguments to the list template.
Arguments:
kwargs: The input arguments.
Returns:
The applied list.
"""
return list(_generate_factory_items(self._factories, kwargs))
class DictFactory(Factory):
"""The template factory for a dict.
Arguments:
decl: A dict template.
ptype: The parameter type of the dict.
"""
def __init__(self, decl: Dict[str, Any], ptype: PTYPE.PType = PTYPE.Any) -> None:
factories = {}
keys = {}
for key, value in decl.items():
if key == "+":
unpack_factory = mapping_unpack_factory_creator(value, PTYPE.Mapping)
keys.update(unpack_factory.keys)
self._unpack_factory = unpack_factory
continue
factory = factory_creator(value, None, ptype)
if factory.is_unpack:
raise ValueError("Use array unpack in object value is not allowed")
factories[key] = factory
keys.update(factory.keys)
self._factories = factories
self.keys = keys
def __call__(self, **kwargs: Any) -> Dict[str, Any]:
"""Apply the input arguments to the dict template.
Arguments:
kwargs: The input arguments.
Returns:
The applied dict.
"""
items: Dict[str, Any] = (
self._unpack_factory(**kwargs) if hasattr(self, "_unpack_factory") else {}
)
items.update({key: factory(**kwargs) for key, factory in self._factories.items()})
return items
class FieldFactory(Factory):
"""The template factory for a tuple of name and PortexType.
Arguments:
decl: A dict which indicates a tuple of name and PortexType.
"""
def __init__(self, decl: Dict[str, Any], imports: Imports) -> None:
self.creator: Callable[..., Tuple[str, PortexType]]
item = decl.copy()
keys = {}
condition = string_factory_creator(item.pop("exist_if", True))
keys.update(condition.keys)
name_factory = string_factory_creator(item.pop("name"), PTYPE.String)
type_factory = type_factory_creator(item, imports)
keys.update(name_factory.keys)
keys.update(type_factory.keys)
self._condition = condition
self._name_factory = name_factory
self._type_factory = type_factory
self.keys = keys
def __call__(self, **kwargs: Any) -> Optional[Tuple[str, PortexType]]:
"""Apply the input arguments to the template.
Arguments:
kwargs: The input arguments.
Returns:
The applied tuple of name and PortexType.
"""
if self._condition(**kwargs) is None:
return None
return self._name_factory(**kwargs), self._type_factory(**kwargs)
class FieldsFactory(Factory):
"""The template factory for a ``Fields``.
Arguments:
decl: A list which indicates a ``Fields``.
"""
def __init__(self, decl: List[Union[Dict[str, Any], str]], imports: Imports) -> None:
self._factories = []
keys = {}
for item in decl:
if isinstance(item, dict):
factory: Factory = FieldFactory(item, imports)
elif isinstance(item, str) and item.startswith("+$"):
factory = VariableFactory(item[2:], PTYPE.Fields, True)
else:
raise ValueError("The items of fields can only be object or list unpack parameter")
keys.update(factory.keys)
self._factories.append(factory)
self.keys = keys
def __call__(self, **kwargs: Any) -> Fields:
"""Apply the input arguments to the ``Fields`` template.
Arguments:
kwargs: The input arguments.
Returns:
The applied ``Fields``.
"""
return Fields(
filter(
bool,
_generate_factory_items(self._factories, kwargs, lambda x: x.items()),
)
)
def _generate_factory_items(
factories: Iterable[Factory],
kwargs: Dict[str, Any],
unpack_item_processer: Callable[[Any], Any] = lambda x: x,
) -> Iterator[Any]:
for factory in factories:
item = factory(**kwargs)
if factory.is_unpack:
yield from unpack_item_processer(item)
else:
yield item
def mapping_unpack_factory_creator(decl: str, ptype: PTYPE.PType) -> VariableFactory:
"""Check the object unpack grammar and returns the corresponding factory.
Arguments:
decl: The parameter decalaration.
ptype: The parameter type of the input.
Raises:
ValueError: When the object unpack grammar is incorrect.
Returns:
A ``VariableFactory`` instance according to the input.
"""
if not decl.startswith("$"):
raise ValueError("The decl does not have the correct object unpack grammar")
return VariableFactory(decl[1:], ptype)
def type_factory_creator(
decl: Dict[str, Any], imports: Imports
) -> Union[TypeFactory, VariableFactory]:
"""Check the input and returns the corresponding type factory.
Arguments:
| |
import logging
from datetime import timedelta, datetime
from math import log10
import discord, schedule
from discord.ext import commands
from config import *
from messages.farm import *
from messages.core import MSG_CMD_INVALID
from objects.economy.account import EconomyAccount
from objects.economy.farm.farm import Farm as ORMFarm
from objects.economy.farm.harvest import Harvest
from objects.economy.farm.plant import Plant
from objects.economy.farm.pricelog import PriceLog
class Farm(commands.Cog):
def __init__(self, bot):
self.bot = bot
@commands.command(aliases=["f"])
async def farm(self, ctx, target: discord.Member=None):
"""Show target's farm details."""
if target is None:
target = ctx.author
_farm = ORMFarm.get_farm(target, self.bot.db_session)
farm_name = _farm.get_name(self.bot.db_session)
embed = discord.Embed(
title="{0.name}#{0.discriminator}'s farm, {1}".format(target, farm_name),
color=0xffd700
)
embed.add_field(name="Plots", value="{0} / {1}".format(
len(_farm.plots), FARM_PLOTS_MAX
))
embed.add_field(
name="Storage",
value="{0.current_harvest} / {0.harvest_capacity}".format(_farm)
)
await ctx.send(embed=embed)
@commands.command(aliases=["ftop"])
async def farmtop(self, ctx):
"""Shows top farms in the server."""
top_farms = ORMFarm.get_top_farms(self.bot.db_session)
embed = discord.Embed(title="Top 10 Most Bountiful Farms", color=0xffd700)
rank = 1
for _farm in top_farms:
plot_count = len(_farm.plots)
leaf_count = int(log10(plot_count))+1
user = self.bot.get_user(_farm.user_id)
try:
row_name = "#{1} **{2}** - ({0.name}#{0.discriminator})".format(user, rank, _farm.get_name(self.bot.db_session))
except AttributeError:
row_name = "#{1} **{2}** - ({0})".format("Unknown User", rank, _farm.get_name(self.bot.db_session))
plot_count = "🌱"*leaf_count + " {0} Plots".format(len(_farm.plots))
embed.add_field(name=row_name, value=plot_count, inline=False)
rank += 1
await ctx.send(embed=embed)
@commands.command()
async def setfarmname(self, ctx, name):
"""Show target's farm details."""
if len(name) > 32:
await ctx.send(MSG_FARM_RENAME_NAME_TOO_LONG.format(ctx.author))
_farm = ORMFarm.get_farm(ctx.author, self.bot.db_session)
_farm.name = name
_account = EconomyAccount.get_economy_account(ctx.author, self.bot.db_session)
if not _account.has_balance(FARM_NAME_CHANGE_PRICE, raw=True):
await ctx.send(MSG_INSUFFICIENT_FUNDS_EXTRA.format(
ctx.author, _account.get_balance(), FARM_NAME_CHANGE_PRICE / 10000
))
return
_account.add_debit(
self.bot.db_session, FARM_NAME_CHANGE_PRICE,
name="FARM NAME CHANGE", raw=True
)
self.bot.db_session.add(_farm)
self.bot.db_session.commit()
await ctx.send(MSG_FARM_RENAME_SUCCESS.format(
ctx.author, name, _account.get_balance()
))
@commands.command(aliases=["fp"])
async def farmplots(self, ctx, page_number: int=1):
"""Show the details of your plots."""
_farm = ORMFarm.get_farm(ctx.author, self.bot.db_session)
_plots = _farm.get_all_plots(self.bot.db_session)
plot_count = len(_plots)
paginated_plots = [
_plots[i:i+20] for i in range(0, plot_count, 20)
]
# Make sure page number is in bounds
page_number = min(page_number, len(paginated_plots))
page_number = max(page_number, 1)
plot_str = ""
plot_count = 1 + (20 * (page_number-1))
for _plot in paginated_plots[page_number-1]:
plot_str += "Plot #{0:04d}: {1}\n".format(plot_count, _plot.get_status_str())
plot_count += 1
embed = discord.Embed(
title="{0.name}#{0.discriminator}'s farm, {1}".format(ctx.author, _farm.name),
color=0xffd700
)
embed.add_field(
name=MSG_PLOTS_STATUS.format(page_number, len(paginated_plots)),
value="```{}```".format(plot_str)
)
embed.set_footer(text="Showing 20 plots per page. s!fp [page_number]")
await ctx.send(embed=embed)
# await ctx.send(MSG_PLOTS_STATUS.format(
# ctx.author, _farm.name,
# plot_str,
# page_number, len(paginated_plots)
# ))
@commands.command(aliases=["p$",])
async def plantprices(self, ctx, plant_name=None):
"""Show the current global plant prices."""
try:
page_number = int(plant_name)
plant_name = None
except TypeError:
page_number = 1
except ValueError:
_plant = Plant.get_plant(self.bot.db_session, plant_name)
if plant_name is not None:
if _plant is None:
ctx.send(MSG_PLANT_NOT_FOUND.format(ctx.author))
return
embed = discord.Embed(
title="-=Current {0} Market Prices=-".format(_plant.name),
color=0xffd700
)
bp = _plant.get_buy_price()
sp = _plant.get_sell_price()
embed.add_field(
name="**`{0.tag}` - {0.name}**".format(_plant),
value=MSG_PLANT_PRICES.format(
_plant, bp, sp, get_growing_time_string(_plant.growing_seconds)
),
inline=False
)
else:
all_plants = Plant.get_plants(self.bot.db_session)
plant_count = len(all_plants)
paginated_plants = [
all_plants[i:i+10] for i in range(0, plant_count, 10)
]
# Make sure page number is in bounds
page_number = min(page_number, len(paginated_plants))
page_number = max(page_number, 1)
embed = discord.Embed(
title="-=Current Global Market Prices=-" +
"\nPage {0} of {1}".format(page_number, len(paginated_plants)),
color=0xffd700
)
logging.info(paginated_plants)
final_str = ""
for _plant in paginated_plants[page_number-1]:
bp = _plant.get_buy_price()
sp = _plant.get_sell_price()
embed.add_field(
name="**`{0.tag}` - {0.name}**".format(_plant),
value=MSG_PLANT_PRICES.format(
_plant, bp, sp, get_growing_time_string(_plant.growing_seconds)
),
inline=False
)
embed.set_footer(
text=MSG_PLANT_PRICES_FOOTER.format(
(timedelta(hours=1) + datetime.now().replace(
microsecond=0, second=0, minute=0)).strftime("%I:%M %p UTC+08:00")
)
)
await ctx.send(embed=embed)
@commands.command(aliases=["plot$",])
@commands.cooldown(1, 1, type=commands.BucketType.user)
async def plotprice(self, ctx, up_count: int=1):
"""Show the price of the next N plots. (N <= 1M)"""
up_count = max(1, up_count)
up_count = min(1000000, up_count)
_farm = ORMFarm.get_farm(ctx.author, self.bot.db_session)
plot_count = _farm.get_plot_count()
to_max_plots = FARM_PLOTS_MAX - plot_count
if to_max_plots == 0:
await ctx.send("**{0.mention}, you have reached maximum plot count.**".format(ctx.author))
return
up_count = min(up_count, to_max_plots)
result = _farm.get_next_plot_price(up_count=up_count)
await ctx.send(MSG_PLOT_PRICE_CHECK.format(
ctx.author, result, up_count
))
@commands.command()
@commands.cooldown(1, 5, type=commands.BucketType.user)
async def plotbuy(self, ctx, up_count: int=1):
"""Buy new N plots. (N <= 1M)"""
up_count = max(1, up_count)
up_count = min(1000000, up_count)
_farm = ORMFarm.get_farm(ctx.author, self.bot.db_session)
_account = EconomyAccount.get_economy_account(ctx.author, self.bot.db_session)
plot_count = _farm.get_plot_count()
to_max_plots = FARM_PLOTS_MAX - plot_count
if to_max_plots == 0:
await ctx.send("**{0.mention}, you have reached maximum plot count.**".format(ctx.author))
return
up_count = min(up_count, to_max_plots)
price = _farm.get_next_plot_price(raw=True, up_count=up_count)
if _account.has_balance(price, raw=True):
_farm.add_plot(self.bot.db_session, up_count=up_count)
_account.add_debit(self.bot.db_session, price, name="PLOTBUY", raw=True)
await ctx.send(MSG_PLOT_BUY_SUCCESS.format(
ctx.author, _account.get_balance(), up_count
))
else:
await ctx.send(MSG_INSUFFICIENT_FUNDS_EXTRA.format(
ctx.author, _account.get_balance(), price / 10000
))
@commands.command(aliases=["silo$",])
@commands.cooldown(1, 1, type=commands.BucketType.user)
async def siloprice(self, ctx, up_count: int=1):
"""Show the price of up to the next 1M silos (storage upgrade)."""
up_count = max(1, up_count)
up_count = min(1000000, up_count)
_farm = ORMFarm.get_farm(ctx.author, self.bot.db_session)
result = _farm.get_next_storage_upgrade_price(up_count=up_count)
await ctx.send(MSG_SILO_PRICE_CHECK.format(
ctx.author, result, up_count
))
@commands.command()
@commands.cooldown(1, 5, type=commands.BucketType.user)
async def silobuy(self, ctx, up_count: int=1):
"""Buy new N silos (increases your storage by 100). (N <= 1M)"""
up_count = max(1, up_count)
up_count = min(1000000, up_count)
_farm = ORMFarm.get_farm(ctx.author, self.bot.db_session)
_account = EconomyAccount.get_economy_account(ctx.author, self.bot.db_session)
price = _farm.get_next_storage_upgrade_price(raw=True, up_count=up_count)
if _account.has_balance(price, raw=True):
_farm.upgrade_storage(self.bot.db_session, up_count)
_account.add_debit(self.bot.db_session, price, name="SILOBUY", raw=True)
await ctx.send(MSG_SILO_BUY_SUCCESS.format(
ctx.author, _account.get_balance(), up_count
))
else:
await ctx.send(MSG_INSUFFICIENT_FUNDS_EXTRA.format(
ctx.author, _account.get_balance(), price / 10000
))
@commands.command()
@commands.is_owner()
async def setplanttag(self, ctx, plant_name, tag):
"""(Owner) Set a plant's shorthand tag."""
_plant = Plant.get_plant(self.bot.db_session, plant_name)
if _plant is None:
await ctx.send(MSG_PLANT_NOT_FOUND.format(ctx.author))
return
_plant.tag = tag
self.bot.db_session.add(_plant)
self.bot.db_session.commit()
await ctx.send("**Successfully changed plant tag.**")
@commands.command()
@commands.is_owner()
async def setplantprice(self, ctx, plant_name, base_price: float):
"""(Owner) Set a plant's base unit price."""
_plant = Plant.get_plant(self.bot.db_session, plant_name)
if _plant is None:
await ctx.send(MSG_PLANT_NOT_FOUND.format(ctx.author))
return
_plant.set_base_price(self.bot.db_session, base_price)
@commands.command()
@commands.is_owner()
async def purgeplots(self, ctx, target: discord.Member=None):
"""(Owner) Purge the plants planted in a target's plots."""
if target == None:
target = ctx.author
_farm = ORMFarm.get_farm(ctx.author, self.bot.db_session)
for _plot in _farm.plots:
_plot.plant = None
_plot.planted_at = None
self.bot.db_session.add(_plot)
self.bot.db_session.add(_plot)
await ctx.send("**{0.mention}'s plots have been purged.**".format(target))
@commands.command()
async def trashplots(self, ctx, scrap_range=None):
"""Discard the plants on your plots. No refunds.
Scrap range can be:
- a number, to scrap that single plot
- a range (1-4, 5-7, etc.) with NO SPACES to scrap those plots, the numbers included
You can also choose to leave the scrap_range blank, to scrap ALL your plots.
"""
_farm = ORMFarm.get_farm(ctx.author, self.bot.db_session)
plot_count = len(_farm.plots)
all_plots = False
if scrap_range is not None:
try:
scrap_range = list(map(int, scrap_range.split('-')))
except ValueError:
await ctx.send(MSG_CMD_INVALID.format(ctx.author))
return
else:
all_plots = True
scrap_range = [1, plot_count]
# Command validation:
if len(scrap_range) > 2:
await ctx.send(MSG_CMD_INVALID.format(ctx.author))
return
if len(scrap_range) == 1:
scrap_range.append(scrap_range[0])
if scrap_range[1] < scrap_range[0]:
await ctx.send(MSG_CMD_INVALID.format(ctx.author))
return
if not (0 <= scrap_range[0]-1 < plot_count) or not (0 <= scrap_range[1]-1 < plot_count):
await ctx.send(MSG_DISCARD_OUT_OF_RANGE.format(ctx.author))
return
for i in range(scrap_range[0]-1, scrap_range[1]):
_farm.plots[i].plant = None
_farm.plots[i].planted_at = None
self.bot.db_session.add(_farm.plots[i])
self.bot.db_session.commit()
if all_plots:
await ctx.send(MSG_DISCARD_ALL.format(ctx.author))
elif scrap_range[0] == scrap_range[1]:
await ctx.send(MSG_DISCARD_SINGLE.format(ctx.author, scrap_range))
else:
await ctx.send(MSG_DISCARD_RANGE.format(ctx.author, scrap_range))
@commands.command()
@commands.is_owner()
async def reconsolidatestorage(self, ctx):
"""(Owner) Manually reconsolidate all farm capacities."""
all_farms = ORMFarm.get_all_farms(self.bot.db_session)
for _farm in all_farms:
harvest_count = 0
for _harvest in _farm.harvests:
harvest_count += _harvest.amount
_farm.current_harvest = harvest_count
self.bot.db_session.add(_farm)
self.bot.db_session.commit()
logging.info("Reconsolidated storages of {} farms.".format(len(all_farms)))
await ctx.send("**All farm storages reconsolidated!**")
@commands.command(aliases=["rpp"])
@commands.is_owner()
async def refreshplantprices(self, ctx):
"""(Owner) Manually refresh the global market prices."""
all_plants = Plant.get_plants(self.bot.db_session)
for plant in all_plants:
plant.randomize_price(self.bot.db_session)
final_str = ""
for plant in all_plants:
bp = plant.get_buy_price()
sp = plant.get_sell_price()
_str = "***{0.name}*** `[B: {1:,.2f} gil | S: {2:,.2f} gil]`\n".format(plant, bp, sp)
final_str += _str
await ctx.send("**Prices refreshed!**\n{}".format(final_str))
@commands.command(aliases=["fpa"])
@commands.cooldown(1, 1, type=commands.BucketType.user)
async def farmplant(self, ctx, plant_name, plant_count=1):
"""Plant a crop on a number of your available plots."""
_plant = Plant.get_plant(self.bot.db_session, plant_name)
if _plant is None:
await ctx.send(MSG_PLANT_NOT_FOUND.format(ctx.author))
return
_account = EconomyAccount.get_economy_account(ctx.author, self.bot.db_session)
total_price = _plant.buy_price * plant_count
if not _account.has_balance(total_price, raw=True):
await ctx.send(MSG_INSUFFICIENT_FUNDS.format(ctx.author, _account.get_balance()))
return
_farm = ORMFarm.get_farm(ctx.author, self.bot.db_session)
_plots = _farm.get_available_plots(self.bot.db_session)
if len(_plots) == None:
await ctx.send(MSG_PLOT_NOT_FOUND.format(ctx.author))
return
if len(_plots) < plant_count:
await ctx.send(MSG_PLANT_NO_PLOTS.format(ctx.author, len(_plots), plant_count))
return
_account.add_debit(
self.bot.db_session, total_price,
name="B:{0.id}={0.buy_price}".format(_plant),
raw=True,
)
for _plot in _plots[:plant_count]:
_plot.plant_to_plot(_plant, self.bot.db_session, commit_on_execution=False)
self.bot.db_session.commit()
await ctx.send(
MSG_PLOT_PLANT.format(
ctx.author, _plant,
plant_count, total_price/10000,
_account.get_balance()
)
)
@commands.command(aliases=["sh"])
async def showharvests(self, ctx):
"""Show your harvest inventory."""
_farm = ORMFarm.get_farm(ctx.author, self.bot.db_session)
harvested_plants = set([i.plant for i in _farm.harvests])
print(_farm.harvests)
id_to_plant_name = {_plant.id: _plant.name for _plant in harvested_plants}
total_harvests = {_plant.id: 0 for _plant in harvested_plants}
if len(_farm.harvests) | |
# Initial values of positions and velocity are all fixed.
# The final value of position are fixed, but the final velocity is a free variable.
# The equations of motion are not functions of position, so 'x' and 'y' have no targets.
# The rate source points to the output in the ODE which provides the time derivative of the
# given state.
phase.add_state('x', fix_initial=True, fix_final=True)
phase.add_state('y', fix_initial=True, fix_final=True)
phase.add_state('v', fix_initial=True)
phase.add_state('int_theta', fix_initial=False, rate_source='theta_rate',
targets=['theta'])
# Define theta as a control.
phase.add_polynomial_control(name='theta_rate', order=11, units='rad/s', shape=(1,), targets=None)
# Minimize final time.
phase.add_objective('time', loc='final')
# Set the driver.
p.driver = om.ScipyOptimizeDriver()
# Allow OpenMDAO to automatically determine our sparsity pattern.
# Doing so can significant speed up the execution of Dymos.
p.driver.declare_coloring()
# Setup the problem
p.setup(check=True)
# Now that the OpenMDAO problem is setup, we can set the values of the states.
p.set_val('traj.phase0.t_initial', 0.0, units='s')
p.set_val('traj.phase0.t_duration', 5.0, units='s')
p.set_val('traj.phase0.states:x',
phase.interpolate(ys=[0, 10], nodes='state_input'),
units='m')
p.set_val('traj.phase0.states:y',
phase.interpolate(ys=[10, 5], nodes='state_input'),
units='m')
p.set_val('traj.phase0.states:v',
phase.interpolate(ys=[0, 5], nodes='state_input'),
units='m/s')
p.set_val('traj.phase0.states:int_theta',
phase.interpolate(ys=[0.1, 45], nodes='state_input'),
units='deg')
p.set_val('traj.phase0.polynomial_controls:theta_rate', 10.0, units='deg/s')
# Run the driver to solve the problem
dm.run_problem(p, simulate=True, make_plots=True)
sol = om.CaseReader('dymos_solution.db').get_case('final')
sim = om.CaseReader('dymos_simulation.db').get_case('final')
t_sol = sol.get_val('traj.phase0.timeseries.time')
t_sim = sim.get_val('traj.phase0.timeseries.time')
x_sol = sol.get_val('traj.phase0.timeseries.states:x')
x_sim = sim.get_val('traj.phase0.timeseries.states:x')
y_sol = sol.get_val('traj.phase0.timeseries.states:y')
y_sim = sim.get_val('traj.phase0.timeseries.states:y')
v_sol = sol.get_val('traj.phase0.timeseries.states:v')
v_sim = sim.get_val('traj.phase0.timeseries.states:v')
int_theta_sol = sol.get_val('traj.phase0.timeseries.states:int_theta')
int_theta_sim = sim.get_val('traj.phase0.timeseries.states:int_theta')
theta_rate_sol = sol.get_val('traj.phase0.timeseries.polynomial_controls:theta_rate')
theta_rate_sim = sim.get_val('traj.phase0.timeseries.polynomial_controls:theta_rate')
assert_timeseries_near_equal(t_sol, x_sol, t_sim, x_sim, tolerance=1.0E-3)
assert_timeseries_near_equal(t_sol, y_sol, t_sim, y_sim, tolerance=1.0E-3)
assert_timeseries_near_equal(t_sol, v_sol, t_sim, v_sim, tolerance=1.0E-3)
assert_timeseries_near_equal(t_sol, int_theta_sol, t_sim, int_theta_sim, tolerance=1.0E-2)
assert_timeseries_near_equal(t_sol, theta_rate_sol, t_sim, theta_rate_sim, tolerance=1.0E-2)
def _test_integrate_polynomial_control_rate(self, transcription):
#
# Define the OpenMDAO problem
#
p = om.Problem(model=om.Group())
#
# Define a Trajectory object
#
traj = dm.Trajectory()
p.model.add_subsystem('traj', subsys=traj)
#
# Define a Dymos Phase object with GaussLobatto Transcription
#
phase = dm.Phase(ode_class=BrachistochroneODE,
transcription=transcription(num_segments=10, order=5))
traj.add_phase(name='phase0', phase=phase)
#
# Set the time options
# Time has no targets in our ODE.
# We fix the initial time so that the it is not a design variable in the optimization.
# The duration of the phase is allowed to be optimized, but is bounded on [0.5, 10].
#
phase.set_time_options(fix_initial=True, duration_bounds=(1.0, 10.0), units='s')
#
# Set the time options
# Initial values of positions and velocity are all fixed.
# The final value of position are fixed, but the final velocity is a free variable.
# The equations of motion are not functions of position, so 'x' and 'y' have no targets.
# The rate source points to the output in the ODE which provides the time derivative of the
# given state.
phase.add_state('x', fix_initial=True, fix_final=True)
phase.add_state('y', fix_initial=True, fix_final=True)
phase.add_state('v', fix_initial=True)
phase.add_state('int_theta', fix_initial=False, rate_source='theta_rate',
targets=['theta'])
# Define theta as a control.
phase.add_polynomial_control(name='theta', order=11, units='rad', shape=(1,), targets=None)
# Force the initial value of the theta polynomial control to equal the initial value of the theta state.
traj.add_linkage_constraint(phase_a='phase0', phase_b='phase0',
var_a='theta', var_b='int_theta',
loc_a='initial', loc_b='initial')
# Minimize final time.
phase.add_objective('time', loc='final')
# Set the driver.
p.driver = om.ScipyOptimizeDriver()
# Allow OpenMDAO to automatically determine our sparsity pattern.
# Doing so can significant speed up the execution of Dymos.
p.driver.declare_coloring()
# Setup the problem
p.setup(check=True)
# Now that the OpenMDAO problem is setup, we can set the values of the states.
p.set_val('traj.phase0.t_initial', 0.0, units='s')
p.set_val('traj.phase0.t_duration', 5.0, units='s')
p.set_val('traj.phase0.states:x',
phase.interpolate(ys=[0, 10], nodes='state_input'),
units='m')
p.set_val('traj.phase0.states:y',
phase.interpolate(ys=[10, 5], nodes='state_input'),
units='m')
p.set_val('traj.phase0.states:v',
phase.interpolate(ys=[0, 5], nodes='state_input'),
units='m/s')
p.set_val('traj.phase0.states:int_theta',
phase.interpolate(ys=[0.1, 45], nodes='state_input'),
units='deg')
p.set_val('traj.phase0.polynomial_controls:theta', 45, units='deg')
# Run the driver to solve the problem
dm.run_problem(p, simulate=True, make_plots=False)
sol = om.CaseReader('dymos_solution.db').get_case('final')
sim = om.CaseReader('dymos_simulation.db').get_case('final')
t_sol = sol.get_val('traj.phase0.timeseries.time')
t_sim = sim.get_val('traj.phase0.timeseries.time')
x_sol = sol.get_val('traj.phase0.timeseries.states:x')
x_sim = sim.get_val('traj.phase0.timeseries.states:x')
y_sol = sol.get_val('traj.phase0.timeseries.states:y')
y_sim = sim.get_val('traj.phase0.timeseries.states:y')
v_sol = sol.get_val('traj.phase0.timeseries.states:v')
v_sim = sim.get_val('traj.phase0.timeseries.states:v')
int_theta_sol = sol.get_val('traj.phase0.timeseries.states:int_theta')
int_theta_sim = sim.get_val('traj.phase0.timeseries.states:int_theta')
theta_sol = sol.get_val('traj.phase0.timeseries.polynomial_controls:theta')
theta_sim = sim.get_val('traj.phase0.timeseries.polynomial_controls:theta')
assert_timeseries_near_equal(t_sol, x_sol, t_sim, x_sim, tolerance=1.0E-3)
assert_timeseries_near_equal(t_sol, y_sol, t_sim, y_sim, tolerance=1.0E-3)
assert_timeseries_near_equal(t_sol, v_sol, t_sim, v_sim, tolerance=1.0E-3)
assert_timeseries_near_equal(t_sol, int_theta_sol, t_sim, int_theta_sim,
tolerance=1.0E-3)
assert_timeseries_near_equal(t_sol, int_theta_sol, t_sol, theta_sol, tolerance=1.0E-3)
# assert_timeseries_near_equal(t_sol, int_theta_sim, t_sol, theta_sim, tolerance=1.0E-3)
def _test_integrate_polynomial_control_rate2(self, transcription):
#
# Define the OpenMDAO problem
#
p = om.Problem(model=om.Group())
#
# Define a Trajectory object
#
traj = dm.Trajectory()
p.model.add_subsystem('traj', subsys=traj)
#
# Define a Dymos Phase object with GaussLobatto Transcription
#
phase = dm.Phase(ode_class=BrachistochroneODE,
transcription=transcription(num_segments=20, order=3))
traj.add_phase(name='phase0', phase=phase)
#
# Set the time options
# Time has no targets in our ODE.
# We fix the initial time so that the it is not a design variable in the optimization.
# The duration of the phase is allowed to be optimized, but is bounded on [0.5, 10].
#
phase.set_time_options(fix_initial=True, duration_bounds=(1.0, 10.0), units='s')
#
# Set the time options
# Initial values of positions and velocity are all fixed.
# The final value of position are fixed, but the final velocity is a free variable.
# The equations of motion are not functions of position, so 'x' and 'y' have no targets.
# The rate source points to the output in the ODE which provides the time derivative of the
# given state.
phase.add_state('x', fix_initial=True, fix_final=True)
phase.add_state('y', fix_initial=True, fix_final=True)
phase.add_state('v', fix_initial=True)
phase.add_state('int_theta_dot', fix_initial=False, rate_source='theta_rate2')
phase.add_state('int_theta', fix_initial=False, rate_source='int_theta_dot',
targets=['theta'])
# Define theta as a control.
phase.add_polynomial_control(name='theta', order=11, units='rad', shape=(1,), targets=None)
# Force the initial value of the theta polynomial control to equal the initial value of the theta state.
traj.add_linkage_constraint(phase_a='phase0', phase_b='phase0',
var_a='theta', var_b='int_theta',
loc_a='initial', loc_b='initial')
traj.add_linkage_constraint(phase_a='phase0', phase_b='phase0',
var_a='int_theta_dot', var_b='theta_rate',
loc_a='initial', loc_b='initial',
units='rad/s')
# Minimize final time.
phase.add_objective('time', loc='final')
# Set the driver.
p.driver = om.pyOptSparseDriver(optimizer='SLSQP')
# Allow OpenMDAO to automatically determine our sparsity pattern.
# Doing so can significant speed up the execution of Dymos.
p.driver.declare_coloring()
# Setup the problem
p.setup(check=True)
# Now that the OpenMDAO problem is setup, we can set the values of the states.
p.set_val('traj.phase0.t_initial', 0.0, units='s')
p.set_val('traj.phase0.t_duration', 5.0, units='s')
p.set_val('traj.phase0.states:x',
phase.interpolate(ys=[0, 10], nodes='state_input'),
units='m')
p.set_val('traj.phase0.states:y',
phase.interpolate(ys=[10, 5], nodes='state_input'),
units='m')
p.set_val('traj.phase0.states:v',
phase.interpolate(ys=[0, 5], nodes='state_input'),
units='m/s')
p.set_val('traj.phase0.states:int_theta',
phase.interpolate(ys=[0.1, 45], nodes='state_input'),
units='deg')
p.set_val('traj.phase0.states:int_theta_dot',
phase.interpolate(ys=[0.0, 0.0], nodes='state_input'),
units='deg/s')
p.set_val('traj.phase0.polynomial_controls:theta', 45, units='deg')
# Run the driver to solve the problem
dm.run_problem(p, simulate=True, make_plots=True)
sol = om.CaseReader('dymos_solution.db').get_case('final')
sim = om.CaseReader('dymos_simulation.db').get_case('final')
t_sol = sol.get_val('traj.phase0.timeseries.time')
t_sim = sim.get_val('traj.phase0.timeseries.time')
x_sol = sol.get_val('traj.phase0.timeseries.states:x')
x_sim = sim.get_val('traj.phase0.timeseries.states:x')
y_sol = sol.get_val('traj.phase0.timeseries.states:y')
y_sim = sim.get_val('traj.phase0.timeseries.states:y')
v_sol = sol.get_val('traj.phase0.timeseries.states:v')
v_sim = sim.get_val('traj.phase0.timeseries.states:v')
int_theta_sol = sol.get_val('traj.phase0.timeseries.states:int_theta')
int_theta_sim = sim.get_val('traj.phase0.timeseries.states:int_theta')
theta_sol = sol.get_val('traj.phase0.timeseries.polynomial_controls:theta')
theta_sim = sim.get_val('traj.phase0.timeseries.polynomial_controls:theta')
assert_timeseries_near_equal(t_sol, x_sol, t_sim, x_sim, tolerance=1.0E-2)
assert_timeseries_near_equal(t_sol, y_sol, t_sim, y_sim, tolerance=1.0E-2)
assert_timeseries_near_equal(t_sol, v_sol, t_sim, v_sim, tolerance=1.0E-2)
assert_timeseries_near_equal(t_sol, int_theta_sol, t_sim, int_theta_sim, tolerance=1.0E-2)
def test_integrate_polynomial_control_gl(self):
self._test_integrate_polynomial_control(dm.GaussLobatto)
def test_integrate_polynomial_control_radau(self):
self._test_integrate_polynomial_control(dm.Radau)
def test_integrate_polynomial_control_rate_gl(self):
self._test_integrate_polynomial_control_rate(dm.GaussLobatto)
def test_integrate_polynomial_control_rate_radau(self):
self._test_integrate_polynomial_control_rate(dm.Radau)
def test_integrate_polynomial_control_rate2_gl(self):
self._test_integrate_polynomial_control_rate2(dm.GaussLobatto)
def test_integrate_polynomial_control_rate2_radau(self):
self._test_integrate_polynomial_control_rate2(dm.Radau)
@use_tempdirs
class TestIntegrateTimeParamAndState(unittest.TestCase):
def _test_transcription(self, transcription=dm.GaussLobatto):
#
# Define the OpenMDAO problem
#
p = om.Problem(model=om.Group())
#
# Define a Trajectory object
#
traj = dm.Trajectory()
p.model.add_subsystem('traj', subsys=traj)
#
# Define a Dymos Phase object with GaussLobatto Transcription
#
phase = dm.Phase(ode_class=BrachistochroneODE,
transcription=transcription(num_segments=10, order=3,
solve_segments='forward'))
traj.add_phase(name='phase0', phase=phase)
#
# Set the time options
# Time has no targets in our ODE.
# We fix the initial time so that the it is not a design variable in the optimization.
# The duration of the phase is allowed to be optimized, but is bounded on [0.5, 10].
#
phase.set_time_options(fix_initial=True, fix_duration=True, units='s')
#
# Set the time options
# Initial values of positions and velocity are all fixed.
# The final value of position are fixed, but the final velocity is a free variable.
# The equations of motion are not functions of position, so 'x' and 'y' have no targets.
# The rate source points to the output in the ODE which provides the time derivative of the
# given state.
phase.add_state('x', fix_initial=True)
phase.add_state('y', fix_initial=True)
phase.add_state('v', fix_initial=True)
phase.add_state('int_one', fix_initial=True, rate_source='one')
phase.add_state('int_time', fix_initial=True, rate_source='time')
phase.add_state('int_time_phase', fix_initial=True, rate_source='time_phase')
phase.add_state('int_int_one', fix_initial=True, rate_source='int_one')
# Define theta as a control.
phase.add_control(name='theta', units='rad', lower=0, upper=np.pi)
# With no targets we must explicitly assign units and shape to this parameter.
# Its only purpose is to be integrated as the rate source for a state.
phase.add_parameter(name='one', opt=False, units=None, shape=(1,))
# Minimize final time.
phase.add_objective('time', loc='final')
# Set the driver.
p.driver = om.ScipyOptimizeDriver()
# | |
this
function if there are no corresponding records in other tables e.g. PDBLigand.
I initially added ligands based on IDs extracted from PDBs however this list included ions like FE2 so I wanted
to scrub all existing records and only add ligands with >1 atoms to the Ligand table. Ions are now added to the
Ion table.
'''
tsession = self.get_session()
ligand_ids = [l.ID for l in tsession.query(DBLigand)]
for ligand_id in ligand_ids:
tsession = self.get_session(new_session = True) # do not allow partial deletions
try:
colortext.message('Removing ligand {0}.'.format(ligand_id))
for ltbl in [LigandDescriptor, LigandIdentifier, LigandPrice, LigandReference, LigandSynonym]:
tsession.query(ltbl).filter(ltbl.LigandID == ligand_id).delete()
tsession.query(DBLigand).filter(DBLigand.ID == ligand_id).delete()
tsession.commit()
tsession.close()
print('Success.\n')
except Exception, e:
colortext.error('Failure.')
print(str(e))
print(traceback.format_exc() + '\n')
tsession.rollback()
tsession.close()
print('')
#################################
# #
# Data update API #
# #
#################################
def update_pdbs(self, pdb_ids = [], update_sections = set(), start_at = None, restrict_to_file_source = None, pdb_ligand_params_files = {}):
'''Updates all or selected data for all or selected PDB files in the database, enumerating in alphabetical order.
If start_at is specified, the update begins at the specified PDB identifier.
pdb_ligand_params_files should be a mapping from pdb_id -> ligand_code -> params_file_path
'''
if not pdb_ids:
pdb_ids = [r for r in self.DDG_db.execute_select('SELECT ID, FileSource FROM PDBFile ORDER BY ID')]
counter = 0
num_pdb_ids = len(pdb_ids)
hit_starting_pdb = False
for r in pdb_ids:
counter += 1
pdb_id = r['ID']
if (not restrict_to_file_source) or (r['FileSource'] == restrict_to_file_source):
if (not start_at) or (r['ID'].upper() == start_at):
hit_starting_pdb = True
if hit_starting_pdb:
colortext.message('Updating data for {0} ({1}/{2}).'.format(pdb_id, counter, num_pdb_ids))
tsession = self.get_session(new_session = True)
ligand_params_file_paths = pdb_ligand_params_files.get(pdb_id, {})
self.add_pdb_data(tsession, pdb_id, update_sections = update_sections, ligand_params_file_paths = ligand_params_file_paths)
tsession.commit()
tsession.close()
if not hit_starting_pdb:
raise Exception('We never hit the starting PDB "{0}".'.format(start_at))
#################################
# #
# Ligand entry - public API #
# #
# Missing tables: #
# LigandPrice #
# LigandReference #
# #
#################################
def add_ligand_by_pdb_code(self, pdb_code):
'''This function adds a ligand to the database using the ligand's PDB code. The insertion is handled by a transaction.
The value of the ID field of the Ligand record is returned.
Touched tables:
Ligand
LigandDescriptor
LigandIdentifier
LigandSynonym
'''
colortext.message('Adding ligand {0}'.format(pdb_code))
l = Ligand.retrieve_data_from_rcsb(pdb_code, cached_dir = '/tmp')
colortext.ppurple(l)
tsession = self.get_session(new_session = True) # As this may be called by another function, we want to keep the ligand entry separate from other transactions.
try:
# Create the main ligand record
if l.InChI == None:
# Error handling for the unknown ligands
assert(l.PDBCode == 'UNL' or l.PDBCode == 'UNK' or l.PDBCode == 'UNX')
l.InChI = l.PDBCode
l.InChIKey = l.PDBCode
db_ligand = get_or_create_in_transaction(tsession, DBLigand, l.__dict__, missing_columns = ['ID'])
# Create the ligand descriptor records
descriptor_fieldnames = [c.name for c in list(sqlalchemy_inspect(LigandDescriptor).columns)]
for descriptor in l.descriptors:
descriptor = copy.deepcopy(descriptor)
descriptor['LigandID'] = db_ligand.ID
db_ligand_descriptor = get_or_create_in_transaction(tsession, LigandDescriptor, descriptor, missing_columns = ['ID'])
for identifier in l.identifiers:
identifier = copy.deepcopy(identifier)
identifier['LigandID'] = db_ligand.ID
db_ligand_identifier = get_or_create_in_transaction(tsession, LigandIdentifier, identifier, missing_columns = ['ID'])
for synonym in l.synonyms:
db_ligand_synonym = get_or_create_in_transaction(tsession, LigandSynonym, dict(LigandID = db_ligand.ID, Synonym = synonym.strip()))
db_ligand_id = db_ligand.ID
tsession.commit()
tsession.close()
print('Success.\n')
return db_ligand_id
except:
colortext.error('Failure.')
tsession.rollback()
tsession.close()
raise
###########################################################################################
## File management layer
##
## This part of the API is responsible for file content abstraction
###########################################################################################
@informational_file
def get_file_id(self, content, tsession = None, hexdigest = None):
'''Searches the database to see whether the FileContent already exists. The search uses the digest and filesize as
heuristics to speed up the search. If a file has the same hex digest and file size then we do a straight comparison
of the contents.
If the FileContent exists, the value of the ID field is returned else None is returned.
'''
tsession = tsession or self.get_session()
existing_filecontent_id = None
hexdigest = hexdigest or get_hexdigest(content)
filesize = len(content)
for r in tsession.execute('SELECT ID FROM FileContent WHERE MD5HexDigest=:hd AND Filesize=:fsz', dict(hd = hexdigest, fsz = filesize)):
if self.get_file_content_from_cache(r['ID']) == content:
assert(existing_filecontent_id == None) # content uniqueness check
existing_filecontent_id = r['ID']
return existing_filecontent_id
def _add_file_content(self, file_content, tsession = None, rm_trailing_line_whitespace = False, forced_mime_type = None):
'''Takes file file_content (and an option to remove trailing whitespace from lines e.g. to normalize PDB files), adds
a new record if necessary, and returns the associated FileContent.ID value.'''
tsession = tsession or self.get_session()
if rm_trailing_line_whitespace:
file_content = remove_trailing_line_whitespace(file_content)
# Check to see whether the file has been uploaded before
hexdigest = get_hexdigest(file_content)
existing_filecontent_id = self.get_file_id(file_content, tsession = tsession, hexdigest = hexdigest)
# Create the FileContent record if the file is a new file
if existing_filecontent_id == None:
# Determing the MIME type
mime_type = forced_mime_type
if not mime_type:
# Note: in case the wrong mime-types are being returned, try saving to file first and then calling magic.from_file.
# See commit c62883b58649bd813bf022f7d1193abb06f1676d for the code. This used to be necessary for some odd reason.
mime_type = magic.from_buffer(file_content, mime = True)
# Create the database record
# Note: We have already searched the file cache and database for uniqueness so we do NOT call get_or_create_in_transaction here.
file_content_record = FileContent(**dict(
Content = file_content,
MIMEType = mime_type,
Filesize = len(file_content),
MD5HexDigest = hexdigest
))
tsession.add(file_content_record)
tsession.flush()
existing_filecontent_id = file_content_record.ID
assert(existing_filecontent_id != None)
return existing_filecontent_id
def get_file_content_cache_stats(self):
'''Returns basic statistics on the file content cache access.'''
return dict(
size = self.file_content_buffer_size,
hits = self.file_content_cache_hits,
misses = self.file_content_cache_misses
)
def get_file_content_from_cache(self, file_content_id):
# Sanity check
assert(len(self.file_content_cache) == len(self.file_content_buffer))
assert(sorted(self.file_content_cache.keys()) == sorted(self.file_content_buffer))
if file_content_id not in self.file_content_cache:
self.file_content_cache_misses += 1
file_content = self.get_session().query(FileContent).filter(FileContent.ID == file_content_id).one()
record = row_to_dict(file_content)
# Add the file content to the API cache
self.file_content_buffer.append(file_content_id)
self.file_content_cache[file_content_id] = record['Content']
num_records_to_remove = max(len(self.file_content_buffer) - self.file_content_buffer_size, 0)
if num_records_to_remove > 0:
for stored_file_content_id in self.file_content_buffer[:num_records_to_remove]:
del self.file_content_cache[stored_file_content_id]
self.file_content_buffer = self.file_content_buffer[num_records_to_remove:]
assert(len(self.file_content_buffer) == self.file_content_buffer_size)
assert(len(self.file_content_cache) == len(self.file_content_buffer))
assert(sorted(self.file_content_cache.keys()) == sorted(self.file_content_buffer))
else:
self.file_content_cache_hits += 1
# Promote the most recently active files to the start of the buffer
self.file_content_buffer.remove(file_content_id)
self.file_content_buffer.append(file_content_id)
return self.file_content_cache[file_content_id]
#################################
# #
# PDB data retrieval API #
# #
#################################
def get_pdb_details(self, pdb_ids, cached_pdb_details = None):
'''Returns the details stored in the database about the PDB files associated with pdb_ids e.g. chains, resolution,
technique used to determine the structure etc.'''
pdbs = {}
cached_pdb_ids = []
if cached_pdb_details:
cached_pdb_ids = set(cached_pdb_details.keys())
for pdb_id in pdb_ids:
if pdb_id in cached_pdb_ids:
pdbs[pdb_id] = cached_pdb_details[pdb_id]
else:
record = self.DDG_db.execute_select('SELECT * FROM PDBFile WHERE ID=%s', parameters=(pdb_id,))[0]
p = PDB(record['Content'], parse_ligands = True)
pdb_chain_lengths = {}
for chain_id, s in p.atom_sequences.iteritems():
pdb_chain_lengths[chain_id] = len(s)
# todo: get the list of protein chains and PDB residues from the database and assert that they are the same
# as what were extracted from the PDB file.
# maybe change 'chains' below to 'protein_chains'
pdbs[pdb_id] = dict(
chains = pdb_chain_lengths,
TM = record['Transmembrane'],
Technique = record['Techniques'],
XRay = record['Techniques'].find('X-RAY') != -1,
Resolution = record['Resolution'],
)
return pdbs
def get_rcsb_record(self, pdbfile_db_record, tsession = None):
'''pdbfile_db_record should be a kddg.api.schema.py::PDBFile object.
Winds up the 'derived from' tree to find the RCSB file that this file originated from.
Throws an exception if there are no such files.
This is useful for a number of reasons:
- Looking up the resolution of the original structure, the determination technique, and its b-factors
We do not copy this information into derived structures as it is generally meaningless (e.g. for PDB_REDO
structures or structures minimized or repacked with some force-field).
- Determining the name of the molecules in the derived PDB file.
etc.
'''
if not tsession:
tsession = self.get_session()
try:
c = 0
while (pdbfile_db_record.DerivedFrom) and (pdbfile_db_record.FileSource != 'RCSB') and (c < 40): # the last expression should be unnecessary but just in case...
pdbfile_db_record = tsession.query(PDBFile).filter(PDBFile.ID == pdbfile_db_record.DerivedFrom).one()
c += 1
assert(pdbfile_db_record.FileSource == 'RCSB')
return pdbfile_db_record
except Exception, e:
raise Exception('Failed to retrieve an RCSB record corresponding to "{0}".'.format(pdbfile_db_record.ID))
####################################
# #
# Publication entry - public API #
# #
####################################
# @todo: code debt: write the add_publication function (using the RIS parsing module in klab and | |
import argparse
import tqdm
import os
import pickle as pkl
import scipy as sp
import torch
from pprint import pprint
import utils as ut
from torchvision import datasets, transforms
from model import Classifier, CD_Simu, Cycle_Cons, Encoder, Decoder, Discriminator
from unet_model_cond_warp import Cycle_Cons_3_Improvements, Convnet_SkipConnection
from torch import nn, optim
from torch import nn
from torch.nn import functional as F
import numpy as np
from sklearn.metrics import accuracy_score, f1_score, confusion_matrix, recall_score
import nibabel as nib
parser = argparse.ArgumentParser(formatter_class = argparse.ArgumentDefaultsHelpFormatter)
parser.add_argument('--z', type=int, default=512, help="Number of latent dimensions")
parser.add_argument('--iter_max', type=int, default=7500, help="Number of training iterations")
parser.add_argument('--iter_save', type=int, default=50, help="Save model every n iterations")
parser.add_argument('--run', type=int, default=57, help="Run ID. In case you want to run replicates")
parser.add_argument('--train', type=int, default=15, help="Flag for training")
parser.add_argument('--Type', type=str, default='LAB_CLS', help="Flag for training")
''' Type: Run_cls / ADNI_CLS'''
parser.add_argument('--iter_restart', type=int, default=1400, help="Save model every n iterations")
parser.add_argument('--BATCH_SIZE', type=int, default=40, help="Flag for training")
parser.add_argument('--iter_load', type=int, default=1, help="Flag for loading version of model")
parser.add_argument('--Siamese', type=str, default='SiameseNetAEReg', help="SiameseNetAE\SiameseNet\SiameseNetW\SiamgeseNetAEReg")
args = parser.parse_args()
cyc_con_layout = [
('model={:s}', 'Cyc_con'),
('z={:02d}', args.z),
('run={:04d}', args.run)
]
cyc_con_model_name = '_'.join([t.format(v) for (t, v) in cyc_con_layout])
ctrans_layout = [
('model={:s}', 'ctrans'),
('z={:02d}', args.z),
('run={:04d}', args.run)
]
ctrans_model_name = '_'.join([t.format(v) for (t, v) in ctrans_layout])
dtrans_layout = [
('model={:s}', 'dtrans'),
('z={:02d}', args.z),
('run={:04d}', args.run)
]
dtrans_model_name = '_'.join([t.format(v) for (t, v) in dtrans_layout])
Classifier_layout = [
('model={:s}', 'Classifier'),
('z={:02d}', args.z),
('run={:04d}', args.run)
]
Classifier_model_name = '_'.join([t.format(v) for (t, v) in Classifier_layout])
Discriminator_layout = [
('model={:s}', 'Discriminator'),
('z={:02d}', args.z),
('run={:04d}', args.run)
]
Discriminator_model_name = '_'.join([t.format(v) for (t, v) in Discriminator_layout])
cls_list= [0,1]
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
ut.set_seed(2020)
pathall_saveimg = "/scratch/users/zucks626/ADNI/ADNI_Longitudinal_all/save_image/"
IPMI_save = "/scratch/users/zucks626/ADNI/IPMI/checkpoints/"
LAB_path_group_data = "/home/groups/kpohl/t1_data/lab_data/img_64_longitudinal/"
LAB_data_name_list_txt = "/home/users/zucks626/miccai/lab_list.txt"
IPMI_data_pickle_save_path = "/scratch/users/zucks626/ADNI/IPMI/data_pickle_saved/"
fold_list_4_image_path = IPMI_data_pickle_save_path + 'LAB_CE+HE_fold_list_4_image.txt'
FLAG_Save_data_pickle = False
DEBUG_VERBOSE = True
# if FLAG_Save_data_pickle == True:
# Dataset = ut.get_Longitudinal_dataset_from_raw_image(ADNI_path_group_data)
# f = open(IPMI_data_pickle_save_path + "ADNI_Dataset.pkl","wb")
# pkl.dump(Dataset, f)
# f.close()
# print('Save Dataset success! Len of Dataset is:', len(Dataset))
# else:
# f = open(IPMI_data_pickle_save_path + "ADNI_Dataset.pkl","rb")
# Dataset = pkl.load(f)
# f.close()
# print('Load Dataset success! Len of Dataset is:', len(Dataset))
label_file_path = IPMI_data_pickle_save_path + 'demographics_lab.csv'
if FLAG_Save_data_pickle == True:
ut.get_Id_attr_pkl_from_label_file(Dataset, label_file_path, IPMI_data_pickle_save_path)
else:
f = open(IPMI_data_pickle_save_path + "Id_attr_lab.pkl","rb")
Id_attr = pkl.load(f)
f.close()
print('Load Id_attr.pkl success!')
# if FLAG_Save_data_pickle == True:
# pass
# else:
# f = open(IPMI_data_pickle_save_path + "information_related_to_test_dataset.pkl","rb")
# information_related_to_test_dataset = pkl.load(f)
# f.close()
# print('Load test visualization dataset success!')
# test_dataset = information_related_to_test_dataset[0]
# num_of_test_pair = test_dataset.shape[0]
# print('test visualization dataset shape is:', test_dataset.shape) # shape: (BS, 2, 64, 64, 64)
# test_visualization_loader = ut.split_test_dataset(test_dataset, BATCH_SIZE=10)
# dataset, labels, subject_id, num_image_wrt_subject, label_wrt_subject = ut.get_dataset_from_idx_file_and_label_from_Id_attr(ADNI_data_name_list_txt, ADNI_path_group_data, Id_attr)
# selected_label_list, cls_stats = ut.select_data_given_label_list(labels, label_list=[0, 1])
# selected_label_wrt_subject_list, cls_stats_1 = ut.select_data_given_label_list(label_wrt_subject, label_list=[0, 1])
# if DEBUG_VERBOSE == True:
# print(selected_label_list, cls_stats)
# print(selected_label_wrt_subject_list, cls_stats_1)
# fold_list = ut.get_fold_list_from_dataset_and_label(num_image_wrt_subject, label_wrt_subject, cls_stats, label_list=[0, 1])
# if DEBUG_VERBOSE == True:
# print(list(fold_list))
# np.savetxt(IPMI_data_pickle_save_path + 'ADNI_ADNC_fold_list_wrt_subject.txt', fold_list, fmt='%1.1f')
# fold_list_4_image = ut.get_fold_list_4_image_from_wrt_subject(subject_id, fold_list)
# np.savetxt(IPMI_data_pickle_save_path + 'ADNI_ADNC_fold_list_4_image.txt', fold_list_4_image, fmt='%1.1f')
# sleep(10000)
Type = args.Type
if Type == 'Run_cls' and args.train > 0:
''' Extract data from pickle file'''
# f = open(pathall_saveimg + "augment_pair_cls_AD.pkl", "rb")
# pair = pkl.load(f)
# f.close()
# f = open(pathall_saveimg + "augment_d_cls_AD.pkl", "rb")
f = open(pathall_saveimg + "dataset_pair_realone_adni.pkl", "rb")
dataset = pkl.load(f)
f.close()
print(dataset.shape)
sleep(1000)
f = open(pathall_saveimg + "augment_label_cls_AD.pkl", "rb")
label = pkl.load(f)
f.close()
id_idx, cal_idx = ut.get_idx_label(label)
pair_new, label_new = ut.get_pair_idx_label_new(id_idx, pair, cls_list)
print(pair_new)
print(label_new)
print(len(pair_new))
train_loader_list, train_label_loader_list = ut.split_dataset_folds_new_true_subject(dataset, label_new, pair_new, folds=5, BATCH_SIZE = args.BATCH_SIZE, shuffle=True, seed=2020)
elif Type == 'LAB_CLS':
FLAG_TEST_FOLD = 4
_, labels, _, _, _ = ut.get_dataset_from_idx_file_and_label_from_Id_attr(LAB_data_name_list_txt, LAB_path_group_data, Id_attr, normalize=False, mask_dataset=True, data_source='lab')
f = open(IPMI_data_pickle_save_path + "LAB_CE+HE_orig_data_fold_fp32.pkl", "rb")
data_fold = pkl.load(f)
f.close()
f = open(IPMI_data_pickle_save_path + "LAB_CE+HE_orig_label_fold.pkl", "rb")
label_fold = pkl.load(f)
f.close()
file_idx = np.genfromtxt(LAB_data_name_list_txt, dtype='str')
fold_list_4_image = np.genfromtxt(fold_list_4_image_path, dtype='float')
# f = open(IPMI_data_pickle_save_path + "ADNI_ADNC_augment_data_fold_0_fp32.pkl", "rb")
# augment_data_fold_0 = pkl.load(f)
# f.close()
# f = open(IPMI_data_pickle_save_path + "ADNI_ADNC_augment_label_fold_0.pkl", "rb")
# augment_label_fold_0 = pkl.load(f)
# f.close()
# f = open(IPMI_data_pickle_save_path + "ADNI_ADNC_augment_data_fold_1_fp32.pkl", "rb")
# augment_data_fold_1 = pkl.load(f)
# f.close()
# f = open(IPMI_data_pickle_save_path + "ADNI_ADNC_augment_label_fold_1.pkl", "rb")
# augment_label_fold_1 = pkl.load(f)
# f.close()
print('Load data fold and label success!') # TODO: rich log information
filename_of_data_fold = ut.get_filename_of_data_fold_from_fold_list_4_image(LAB_data_name_list_txt, fold_list_4_image, labels, num_cls=2, fold_num=5)
print(filename_of_data_fold)
if DEBUG_VERBOSE == True:
for i in range(2):
for j in range(5):
print(len(filename_of_data_fold[i][j]))
sleep(10000)
def save_data_to_nii(folder_dir, file_name, data, fold, save_type='both'):
if save_type == 'both':
if not os.path.exists(folder_dir):
os.makedirs(folder_dir)
folder_fold = 'fold_' + str(int(fold)) + '_'
folder_path = folder_dir + folder_fold
name_prefix = ['NC', 'EHE', 'SIMU_EHE', 'SIMU_NC', 'CYC_BACK_NC', 'CYC_BACK_EHE', 'D_Field_SIMU_EHE', 'D_Field_SIMU_NC', 'D_Field_CYC_BACK_NC', 'D_Field_CYC_BACK_EHE']
xp, xn, s1, s3, s2, s4, v1, v3, v2, v4 = data
AD_FILE_NAME = file_name[0]
NC_FILE_NAME = file_name[1]
num_of_AD = len(AD_FILE_NAME)
num_of_NC = len(NC_FILE_NAME)
AD_NAME_TXT = [[] for i in range(len(name_prefix))]
NC_NAME_TXT = [[] for i in range(len(name_prefix))]
NAME_TXT = [[] for i in range(len(name_prefix))]
for name in name_prefix:
subfolder_dir = folder_path + name
if not os.path.exists(subfolder_dir):
os.makedirs(subfolder_dir)
np.savetxt(folder_dir + 'EHE.txt', AD_FILE_NAME, '%s')
np.savetxt(folder_dir + 'NC.txt', NC_FILE_NAME, '%s')
# sleep(1000)
for i in range(num_of_AD):
if DEBUG_VERBOSE == True:
print('EHE:', i)
AD_NAME = str(AD_FILE_NAME[i])
img = xn[i, 0, :, : ,:]
nib_img = nib.Nifti1Image(img, np.diag([1, 1, 1, 1]))
prefix = name_prefix[1]
AD_filename = folder_path + prefix + '/' + prefix + '_' + AD_NAME
NAME_TXT[1].append(prefix + '_' + AD_NAME)
nib.save(nib_img, AD_filename)
img = s3[i, 0, :, : ,:]
nib_img = nib.Nifti1Image(img, np.diag([1, 1, 1, 1]))
prefix = name_prefix[3]
AD_filename = folder_path + prefix + '/' + prefix + '_' + AD_NAME
NAME_TXT[3].append(prefix + '_' + AD_NAME)
nib.save(nib_img, AD_filename)
img = s4[i, 0, :, : ,:]
nib_img = nib.Nifti1Image(img, np.diag([1, 1, 1, 1]))
prefix = name_prefix[5]
AD_filename = folder_path + prefix + '/' + prefix + '_' + AD_NAME
NAME_TXT[5].append(prefix + '_' + AD_NAME)
nib.save(nib_img, AD_filename)
img = v3[i, :, :, : ,:]
nib_img = nib.Nifti1Image(img, np.diag([1, 1, 1, 1]))
prefix = name_prefix[7]
AD_filename = folder_path + prefix + '/' + prefix + '_' + AD_NAME
NAME_TXT[7].append(prefix + '_' + AD_NAME)
nib.save(nib_img, AD_filename)
img = v4[i, :, :, : ,:]
nib_img = nib.Nifti1Image(img, np.diag([1, 1, 1, 1]))
prefix = name_prefix[9]
AD_filename = folder_path + prefix + '/' + prefix + '_' + AD_NAME
NAME_TXT[9].append(prefix + '_' + AD_NAME)
nib.save(nib_img, AD_filename)
for i in range(num_of_NC):
if DEBUG_VERBOSE == True:
print('NC:', i)
NC_NAME = NC_FILE_NAME[i]
img = xp[i, 0, :, : ,:]
nib_img = nib.Nifti1Image(img, np.diag([1, 1, 1, 1]))
prefix = name_prefix[0]
NC_filename = folder_path + prefix + '/' + prefix + '_' + NC_NAME
NAME_TXT[0].append(prefix + '_' + NC_NAME)
nib.save(nib_img, NC_filename)
img = s1[i, 0, :, : ,:]
nib_img = nib.Nifti1Image(img, np.diag([1, 1, 1, 1]))
prefix = name_prefix[2]
NC_filename = folder_path + prefix + '/' + prefix + '_' + NC_NAME
NAME_TXT[2].append(prefix + '_' + NC_NAME)
nib.save(nib_img, NC_filename)
img = s2[i, 0, :, : ,:]
nib_img = nib.Nifti1Image(img, np.diag([1, 1, 1, 1]))
prefix = name_prefix[4]
NC_filename = folder_path + prefix + '/' + prefix + '_' + NC_NAME
NAME_TXT[4].append(prefix + '_' + NC_NAME)
nib.save(nib_img, NC_filename)
img = v1[i, :, :, : ,:]
nib_img = nib.Nifti1Image(img, np.diag([1, 1, 1, 1]))
prefix = name_prefix[6]
NC_filename = folder_path + prefix + '/' + prefix + '_' + NC_NAME
NAME_TXT[6].append(prefix + '_' + NC_NAME)
nib.save(nib_img, NC_filename)
img = v2[i, :, :, : ,:]
nib_img = nib.Nifti1Image(img, np.diag([1, 1, 1, 1]))
prefix = name_prefix[8]
NC_filename = folder_path + prefix + '/' + prefix + '_' + NC_NAME
NAME_TXT[8].append(prefix + '_' + NC_NAME)
nib.save(nib_img, NC_filename)
for i, name in enumerate(name_prefix):
subfolder_dir = folder_path + name + '/'
subtxt_filename = subfolder_dir + name + '_file.txt'
np.savetxt(subtxt_filename, NAME_TXT[i], '%s')
def simulate_img_fold(cyc_con, data_fold, label_fold, filename_of_data_fold, data_save_path, eval_fold_list=[0,1,2,3,4], requires_grad=False, mode='eval', verbose=True):
num_cls = len(data_fold)
num_fold = len(data_fold[0])
if DEBUG_VERBOSE == True:
print(cyc_con.device)
for fold in eval_fold_list:
x_AD = data_fold[0][fold]
x_NC = data_fold[1][fold]
l_AD = label_fold[0][fold]
l_NC = label_fold[1][fold]
f_AD = filename_of_data_fold[0][fold]
f_NC = filename_of_data_fold[1][fold]
f_name = [f_AD, f_NC]
data = []
num_of_AD = len(x_AD)
num_of_NC = len(x_NC)
folder_path = data_save_path
if verbose == True:
print('Fold:',fold, ' EHE:', num_of_AD)
print('Fold:',fold, ' NC:', num_of_NC)
print('data_save_path_fold:', folder_path)
xp = torch.tensor(x_NC).to(cyc_con.device)
xn = torch.tensor(x_AD).to(cyc_con.device)
if verbose == True:
print('NC:', xp.shape)
print('EHE:', xn.shape)
option_simu_AD = torch.ones(num_of_NC, 1).to(cyc_con.device) * -1
option_simu_NC = torch.ones(num_of_AD, 1).to(cyc_con.device) * 1
option_cyc_back_AD = torch.ones(num_of_AD, 1).to(cyc_con.device) * -1
option_cyc_back_NC = torch.ones(num_of_NC, 1).to(cyc_con.device) * 1
v1, s1 = cyc_con.Generate(xp, | |
connected
DriverException: An error occurred that is not described by
one of the more specific ASCOM exceptions.
The device did not *successfully* complete the request.
Notes:
* ReadoutMode is an index into the array :py:attr:`ReadoutModes`, and
selects the desired readout mode for the camera. Defaults to 0 if not set.
* It is strongly recommended, but not required, that cameras make the 0-index
mode suitable for standard imaging operations, since it is the default.
Important:
The :py:attr:`ReadoutMode` may in some cases affect the :py:attr:`Gain`
and/or :py:attr:`Offset` of the camera; if so, the camera must ensure
that the two properties do not conflict if both are used.
"""
return self._get("readoutmode")
@ReadoutMode.setter
def ReadoutMode(self, ReadoutMode: int):
self._put("readoutmode", ReadoutMode=ReadoutMode)
@property
def ReadoutModes(self) -> List[str]:
"""List of ReadoutMode *names* supported by the camera (see notes and :py:attr:`ReadoutMode`)
Raises:
NotImplementedException: If the :py:attr:`ReadoutMode` property is not
implemented.
NotConnectedException: If the device is not connected
DriverException: An error occurred that is not described by
one of the more specific ASCOM exceptions.
The device did not *successfully* complete the request.
Notes:
* Readout modes may be available from the camera, and if so then
:py:attr:`CanFastReadout` will be False. The two camera mode selection
schemes are mutually exclusive.
* This property provides an array of strings, each of which describes an
available readout mode of the camera. At least one string will be present
in the list. Your application may use this list to present to the user a
drop-list of modes. The choice of available modes made available is
entirely at the discretion of the camera. Please note that if the camera
has many different modes of operation, then the most commonly adjusted
settings will probably be in ReadoutModes; additional settings may be
provided using :py:meth:`SetupDialog()`.
* To select a mode, set ReadoutMode to the index of the desired mode.
The index is zero-based.
* It is recommended that this property be retrieved only after a connection is
established with the camera hardware, to ensure that the driver is
aware of the capabilities of the specific camera model.
"""
return self._get("readoutmodes")
@property
def SensorName(self) -> str:
"""The name of the sensor used within the camera.
Raises:
NotConnectedException: If the device is not connected
DriverException: An error occurred that is not described by
one of the more specific ASCOM exceptions.
The device did not *successfully* complete the request.
Notes:
* Returns the name (data sheet part number) of the sensor, e.g. ICX285AL.
The format is to be exactly as shown on manufacturer data sheet,
subject to the following rules:
* All letters will be upper-case.
* Spaces will not be included.
* Any extra suffixes that define region codes, package types, temperature range,
coatings, grading, colour/monochrome, etc. will not be included.
* For colour sensors, if a suffix differentiates different Bayer matrix encodings,
it will be included.
* The property will return an empty string if the sensor name is not known
* Examples:
* ICX285AL-F shall be reported as ICX285
* KAF-8300-AXC-CD-AA shall be reported as KAF-8300
* The most common usage of this property is to select approximate colour balance
parameters to be applied to the Bayer matrix of one-shot colour sensors.
Application authors should assume that an appropriate IR cut-off filter is
in place for colour sensors.
* It is recommended that this property be retrieved only after a connection is
established with the camera hardware, to ensure that the driver is
aware of the capabilities of the specific camera model.
"""
return self._get("sensorname")
@property
def SensorType(self) -> SensorTypes:
"""The type of sensor within the camera.
Raises:
NotConnectedException: If the device is not connected
DriverException: An error occurred that is not described by
one of the more specific ASCOM exceptions.
The device did not *successfully* complete the request.
Notes:
* It is recommended that this property be retrieved only after a connection is
established with the camera hardware, to ensure that the driver is
aware of the capabilities of the specific camera model.
"""
return SensorTypes(self._get("sensortype"))
@property
def SetCCDTemperature(self) -> float:
"""(Read/Write) Get or set the camera's cooler setpoint (degrees Celsius).
Raises:
InvalidValueException: If set to a value outside the camera's valid
temperature setpoint range.
NotConnectedException: If the device is not connected
DriverException: An error occurred that is not described by
one of the more specific ASCOM exceptions.
The device did not *successfully* complete the request.
"""
return self._get("setccdtemperature")
@SetCCDTemperature.setter
def SetCCDTemperature(self, SetCCDTemperature: float):
self._put("setccdtemperature", SetCCDTemperature=SetCCDTemperature)
@property
def StartX(self) -> int:
"""(Read/Write) Set or return the current X-axis subframe start position.
Raises:
NotConnectedException: If the device is not connected
DriverException: An error occurred that is not described by
one of the more specific ASCOM exceptions.
The device did not *successfully* complete the request.
Notes:
* If binning is active, value is in binned pixels.
* Defaults to 0 with :py:attr:`NumX` = :py:attr:`CameraXSize`
(full frame) on initial camera startup.
Attention:
* No error check is performed for incompatibilty with :py:attr:`BinX`,
and :py:attr:`NumX`, If these values are incompatible, you will
receive an **InvalidValueException** from a subsequent call to
:py:meth:`StartExposure()`.
"""
return self._get("startx")
@StartX.setter
def StartX(self, StartX: int):
self._put("startx", StartX=StartX)
@property
def StartY(self) -> int:
"""(Read/Write) Set or return the current Y-axis subframe start position.
Raises:
NotConnectedException: If the device is not connected
DriverException: An error occurred that is not described by
one of the more specific ASCOM exceptions.
The device did not *successfully* complete the request.
Notes:
* If binning is active, value is in binned pixels.
* Defaults to 0 with :py:attr:`NumY` = :py:attr:`CameraYSize`
(full frame) on initial camera startup.
Attention:
* No error check is performed for incompatibilty with :py:attr:`BinY`,
and :py:attr:`NumY`, If these values are incompatible, you will
receive an **InvalidValueException** from a subsequent call to
:py:meth:`StartExposure()`.
"""
return self._get("starty")
@StartY.setter
def StartY(self, StartY):
self._put("starty", StartY=StartY)
@property
def SubExposureDuration(self) -> float:
"""(Read/Write) Set or return the camera's sub-exposure interval (sec)
Raises:
NotImplementedException: The camera does not support
on-board stacking with user-supplied sub-exposure interval.
NotConnectedException: If the device is not connected.
InvalidValueException: The supplied duration is not valid.
DriverException: An error occurred that is not described by
one of the more specific ASCOM exceptions.
The device did not *successfully* complete the request.
"""
return self._get("subexposureduration")
@SubExposureDuration.setter
def SubExposureDuration(self, SubexposureDuration: float):
self._put("subexposureduration", SubexposureDuration=SubexposureDuration)
def AbortExposure(self) -> None:
"""Abort the current exposure, if any, and returns the camera to Idle state.
Raises:
NotConnectedException: If the device is not connected.
InvalidOperationException: If not currently possible (e.g. during image download)
DriverException: An error occurred that is not described by
one of the more specific ASCOM exceptions.
The device did not *successfully* complete the request.
Notes:
* Unlike :py:meth:`StopExposure()` this method simply discards any
partially-acquired image data and returns the camera to idle.
* Will not raise an exception if the camera is already idle.
"""
self._put("abortexposure")
def PulseGuide(self, Direction: GuideDirections, Duration: int) -> None:
"""Pulse guide in the specified direction for the specified time (ms).
**Non-blocking**: See Notes, and :ref:`async_faq`
Args:
Direction: :py:class:`~alpaca.telescope.GuideDirections`
Interval: duration of the guide move, milliseconds
Raises:
NotImplementedException: If the camera does not support pulse guiding
(:py:attr:`CanPulseGuide` property is False)
NotConnectedException: If the device is not connected.
DriverException: An error occurred that is not described by
one of the more specific ASCOM exceptions.
The device did not *successfully* complete the request.
Notes:
* **Asynchronous**: The method returns as soon pulse-guiding operation
has been *successfully* started with :py:attr:`IsPulseGuiding` property True.
However, you may find that :py:attr:`IsPulseGuiding` is False when you get
around to checking it if | |
<filename>blivedm/client.py
# -*- coding: utf-8 -*-
import asyncio
import collections
import enum
import json
import logging
import ssl as ssl_
import struct
from typing import *
import aiohttp
import brotli
from . import handlers
__all__ = (
'BLiveClient',
)
logger = logging.getLogger('blivedm')
ROOM_INIT_URL = 'https://api.live.bilibili.com/xlive/web-room/v1/index/getInfoByRoom'
DANMAKU_SERVER_CONF_URL = 'https://api.live.bilibili.com/xlive/web-room/v1/index/getDanmuInfo'
DEFAULT_DANMAKU_SERVER_LIST = [
{'host': 'broadcastlv.chat.bilibili.com', 'port': 2243, 'wss_port': 443, 'ws_port': 2244}
]
HEADER_STRUCT = struct.Struct('>I2H2I')
HeaderTuple = collections.namedtuple('HeaderTuple', ('pack_len', 'raw_header_size', 'ver', 'operation', 'seq_id'))
# WS_BODY_PROTOCOL_VERSION
class ProtoVer(enum.IntEnum):
NORMAL = 0
HEARTBEAT = 1
DEFLATE = 2
BROTLI = 3
# go-common\app\service\main\broadcast\model\operation.go
class Operation(enum.IntEnum):
HANDSHAKE = 0
HANDSHAKE_REPLY = 1
HEARTBEAT = 2
HEARTBEAT_REPLY = 3
SEND_MSG = 4
SEND_MSG_REPLY = 5
DISCONNECT_REPLY = 6
AUTH = 7
AUTH_REPLY = 8
RAW = 9
PROTO_READY = 10
PROTO_FINISH = 11
CHANGE_ROOM = 12
CHANGE_ROOM_REPLY = 13
REGISTER = 14
REGISTER_REPLY = 15
UNREGISTER = 16
UNREGISTER_REPLY = 17
# B站业务自定义OP
# MinBusinessOp = 1000
# MaxBusinessOp = 10000
# WS_AUTH
class AuthReplyCode(enum.IntEnum):
OK = 0
TOKEN_ERROR = -101
class InitError(Exception):
"""初始化失败"""
class AuthError(Exception):
"""认证失败"""
class BLiveClient:
"""
B站直播弹幕客户端,负责连接房间
:param room_id: URL中的房间ID,可以用短ID
:param uid: B站用户ID,0表示未登录
:param session: cookie、连接池
:param heartbeat_interval: 发送心跳包的间隔时间(秒)
:param ssl: True表示用默认的SSLContext验证,False表示不验证,也可以传入SSLContext
:param loop: 协程事件循环
"""
def __init__(
self,
room_id,
uid=0,
session: Optional[aiohttp.ClientSession] = None,
heartbeat_interval=30,
ssl: Union[bool, ssl_.SSLContext] = True,
loop: Optional[asyncio.BaseEventLoop] = None,
):
# 用来init_room的临时房间ID,可以用短ID
self._tmp_room_id = room_id
self._uid = uid
if loop is not None:
self._loop = loop
elif session is not None:
self._loop = session.loop # noqa
else:
self._loop = asyncio.get_event_loop()
if session is None:
self._session = aiohttp.ClientSession(loop=self._loop, timeout=aiohttp.ClientTimeout(total=10))
self._own_session = True
else:
self._session = session
self._own_session = False
if self._session.loop is not self._loop: # noqa
raise RuntimeError('BLiveClient and session must use the same event loop')
self._heartbeat_interval = heartbeat_interval
self._ssl = ssl if ssl else ssl_._create_unverified_context() # noqa
# 消息处理器,可动态增删
self._handlers: List[handlers.HandlerInterface] = []
# 在调用init_room后初始化的字段
# 真实房间ID
self._room_id = None
# 房间短ID,没有则为0
self._room_short_id = None
# 主播用户ID
self._room_owner_uid = None
# 弹幕服务器列表
# [{host: "tx-bj4-live-comet-04.chat.bilibili.com", port: 2243, wss_port: 443, ws_port: 2244}, ...]
self._host_server_list: Optional[List[dict]] = None
# 连接弹幕服务器用的token
self._host_server_token = None
# 在运行时初始化的字段
# websocket连接
self._websocket: Optional[aiohttp.ClientWebSocketResponse] = None
# 网络协程的future
self._network_future: Optional[asyncio.Future] = None
# 发心跳包定时器的handle
self._heartbeat_timer_handle: Optional[asyncio.TimerHandle] = None
@property
def is_running(self) -> bool:
"""
本客户端正在运行,注意调用stop后还没完全停止也算正在运行
"""
return self._network_future is not None
@property
def room_id(self) -> Optional[int]:
"""
房间ID,调用init_room后初始化
"""
return self._room_id
@property
def room_short_id(self) -> Optional[int]:
"""
房间短ID,没有则为0,调用init_room后初始化
"""
return self._room_short_id
@property
def room_owner_uid(self) -> Optional[int]:
"""
主播用户ID,调用init_room后初始化
"""
return self._room_owner_uid
def add_handler(self, handler: 'handlers.HandlerInterface'):
"""
添加消息处理器
注意多个处理器是并发处理的,不要依赖处理的顺序
消息处理器和接收消息运行在同一协程,如果处理消息耗时太长会阻塞接收消息,这种情况建议将消息推到队列,让另一个协程处理
:param handler: 消息处理器
"""
if handler not in self._handlers:
self._handlers.append(handler)
def remove_handler(self, handler: 'handlers.HandlerInterface'):
"""
移除消息处理器
:param handler: 消息处理器
"""
try:
self._handlers.remove(handler)
except ValueError:
pass
def start(self):
"""
启动本客户端
"""
if self.is_running:
logger.warning('room=%s client is running, cannot start() again', self.room_id)
return
self._network_future = asyncio.ensure_future(self._network_coroutine_wrapper(), loop=self._loop)
def stop(self):
"""
停止本客户端
"""
if not self.is_running:
logger.warning('room=%s client is stopped, cannot stop() again', self.room_id)
return
self._network_future.cancel()
async def stop_and_close(self):
"""
便利函数,停止本客户端并释放本客户端的资源,调用后本客户端将不可用
"""
if self.is_running:
self.stop()
await self.join()
await self.close()
async def join(self):
"""
等待本客户端停止
"""
if not self.is_running:
logger.warning('room=%s client is stopped, cannot join()', self.room_id)
return
await asyncio.shield(self._network_future)
async def close(self):
"""
释放本客户端的资源,调用后本客户端将不可用
"""
if self.is_running:
logger.warning('room=%s is calling close(), but client is running', self.room_id)
# 如果session是自己创建的则关闭session
if self._own_session:
await self._session.close()
async def init_room(self):
"""
初始化连接房间需要的字段
:return: True代表没有降级,如果需要降级后还可用,重载这个函数返回True
"""
res = True
if not await self._init_room_id_and_owner():
res = False
# 失败了则降级
self._room_id = self._room_short_id = self._tmp_room_id
self._room_owner_uid = 0
if not await self._init_host_server():
res = False
# 失败了则降级
self._host_server_list = DEFAULT_DANMAKU_SERVER_LIST
self._host_server_token = None
return res
async def _init_room_id_and_owner(self):
try:
async with self._session.get(ROOM_INIT_URL, params={'room_id': self._tmp_room_id},
ssl=self._ssl) as res:
if res.status != 200:
logger.warning('room=%d _init_room_id_and_owner() failed, status=%d, reason=%s', self._tmp_room_id,
res.status, res.reason)
return False
data = await res.json()
if data['code'] != 0:
logger.warning('room=%d _init_room_id_and_owner() failed, message=%s', self._tmp_room_id,
data['message'])
return False
if not self._parse_room_init(data['data']):
return False
except (aiohttp.ClientConnectionError, asyncio.TimeoutError):
logger.exception('room=%d _init_room_id_and_owner() failed:', self._tmp_room_id)
return False
return True
def _parse_room_init(self, data):
room_info = data['room_info']
self._room_id = room_info['room_id']
self._room_short_id = room_info['short_id']
self._room_owner_uid = room_info['uid']
return True
async def _init_host_server(self):
try:
async with self._session.get(DANMAKU_SERVER_CONF_URL, params={'id': self._room_id, 'type': 0},
ssl=self._ssl) as res:
if res.status != 200:
logger.warning('room=%d _init_host_server() failed, status=%d, reason=%s', self._room_id,
res.status, res.reason)
return False
data = await res.json()
if data['code'] != 0:
logger.warning('room=%d _init_host_server() failed, message=%s', self._room_id, data['message'])
return False
if not self._parse_danmaku_server_conf(data['data']):
return False
except (aiohttp.ClientConnectionError, asyncio.TimeoutError):
logger.exception('room=%d _init_host_server() failed:', self._room_id)
return False
return True
def _parse_danmaku_server_conf(self, data):
self._host_server_list = data['host_list']
self._host_server_token = data['token']
if not self._host_server_list:
logger.warning('room=%d _parse_danmaku_server_conf() failed: host_server_list is empty', self._room_id)
return False
return True
@staticmethod
def _make_packet(data: dict, operation: int) -> bytes:
"""
创建一个要发送给服务器的包
:param data: 包体JSON数据
:param operation: 操作码,见Operation
:return: 整个包的数据
"""
body = json.dumps(data).encode('utf-8')
header = HEADER_STRUCT.pack(*HeaderTuple(
pack_len=HEADER_STRUCT.size + len(body),
raw_header_size=HEADER_STRUCT.size,
ver=1,
operation=operation,
seq_id=1
))
return header + body
async def _network_coroutine_wrapper(self):
"""
负责处理网络协程的异常,网络协程具体逻辑在_network_coroutine里
"""
try:
await self._network_coroutine()
except asyncio.CancelledError:
# 正常停止
pass
except Exception as e: # noqa
logger.exception('room=%s _network_coroutine() finished with exception:', self.room_id)
finally:
logger.debug('room=%s _network_coroutine() finished', self.room_id)
self._network_future = None
async def _network_coroutine(self):
"""
网络协程,负责连接服务器、接收消息、解包
"""
# 如果之前未初始化则初始化
if self._host_server_token is None:
if not await self.init_room():
raise InitError('init_room() failed')
retry_count = 0
while True:
try:
# 连接
host_server = self._host_server_list[retry_count % len(self._host_server_list)]
async with self._session.ws_connect(
f"wss://{host_server['host']}:{host_server['wss_port']}/sub",
receive_timeout=self._heartbeat_interval + 5,
ssl=self._ssl
) as websocket:
self._websocket = websocket
await self._on_ws_connect()
# 处理消息
message: aiohttp.WSMessage
async for message in websocket:
await self._on_ws_message(message)
# 至少成功处理1条消息
retry_count = 0
except (aiohttp.ClientConnectionError, asyncio.TimeoutError):
# 掉线重连
pass
except AuthError:
# 认证失败了,应该重新获取token再重连
logger.exception('room=%d auth failed, trying init_room() again', self.room_id)
if not await self.init_room():
raise InitError('init_room() failed')
except ssl_.SSLError:
logger.error('room=%d a SSLError happened, cannot reconnect', self.room_id)
raise
finally:
self._websocket = None
await self._on_ws_close()
# 准备重连
retry_count += 1
logger.warning('room=%d is reconnecting, retry_count=%d', self.room_id, retry_count)
await asyncio.sleep(1, loop=self._loop)
async def _on_ws_connect(self):
"""
websocket连接成功
"""
await self._send_auth()
self._heartbeat_timer_handle = self._loop.call_later(self._heartbeat_interval, self._on_send_heartbeat)
async def _on_ws_close(self):
"""
websocket连接断开
"""
if self._heartbeat_timer_handle is not None:
self._heartbeat_timer_handle.cancel()
self._heartbeat_timer_handle = None
async def _send_auth(self):
"""
发送认证包
"""
auth_params = {
'uid': self._uid,
'roomid': self._room_id,
'protover': 3,
'platform': 'web',
'type': 2
}
if self._host_server_token is not None:
auth_params['key'] = self._host_server_token
await self._websocket.send_bytes(self._make_packet(auth_params, Operation.AUTH))
def _on_send_heartbeat(self):
"""
定时发送心跳包的回调
"""
if self._websocket is None or self._websocket.closed:
self._heartbeat_timer_handle = None
return
self._heartbeat_timer_handle = self._loop.call_later(self._heartbeat_interval, self._on_send_heartbeat)
asyncio.ensure_future(self._send_heartbeat(), loop=self._loop)
async def _send_heartbeat(self):
"""
发送心跳包
"""
if self._websocket is None or self._websocket.closed:
return
try:
await self._websocket.send_bytes(self._make_packet({}, Operation.HEARTBEAT))
except (ConnectionResetError, aiohttp.ClientConnectionError) as e:
logger.warning('room=%d _send_heartbeat() failed: %r', self.room_id, e)
except Exception: # noqa
logger.exception('room=%d _send_heartbeat() failed:', self.room_id)
async def _on_ws_message(self, message: aiohttp.WSMessage):
"""
收到websocket消息
:param message: websocket消息
"""
if message.type != aiohttp.WSMsgType.BINARY:
logger.warning('room=%d unknown websocket message type=%s, data=%s', self.room_id,
message.type, message.data)
return
try:
await self._parse_ws_message(message.data)
except (asyncio.CancelledError, AuthError):
# 正常停止、认证失败,让外层处理
raise
except Exception: # noqa
logger.exception('room=%d _parse_ws_message() error:', self.room_id)
async def _parse_ws_message(self, data: bytes):
"""
解析websocket消息
:param data: websocket消息数据
"""
offset = 0
try:
header = HeaderTuple(*HEADER_STRUCT.unpack_from(data, offset))
except struct.error:
logger.exception('room=%d parsing header failed, offset=%d, data=%s', self.room_id, offset, data)
return
if header.operation in (Operation.SEND_MSG_REPLY, Operation.AUTH_REPLY):
# 业务消息,可能有多个包一起发,需要分包
while True:
body = data[offset + header.raw_header_size: offset + header.pack_len]
await self._parse_business_message(header, body)
offset += header.pack_len
if offset >= len(data):
break
try:
header = HeaderTuple(*HEADER_STRUCT.unpack_from(data, offset))
except struct.error:
logger.exception('room=%d parsing header failed, offset=%d, data=%s', self.room_id, offset, data)
break
elif header.operation == Operation.HEARTBEAT_REPLY:
# 服务器心跳包,前4字节是人气值,后面是客户端发的心跳包内容
# pack_len不包括客户端发的心跳包内容,不知道是不是服务器BUG
body = data[offset + header.raw_header_size: offset + header.raw_header_size + 4]
popularity = int.from_bytes(body, 'big')
# 自己造个消息当成业务消息处理
body = {
'cmd': '_HEARTBEAT',
'data': {
'popularity': popularity
}
}
await self._handle_command(body)
else:
# 未知消息
body = data[offset + header.raw_header_size: offset + header.pack_len]
logger.warning('room=%d unknown message operation=%d, header=%s, body=%s', self.room_id,
header.operation, header, body)
async def _parse_business_message(self, header: HeaderTuple, body: bytes):
"""
解析业务消息
"""
if header.operation == Operation.SEND_MSG_REPLY:
# 业务消息
if header.ver == ProtoVer.BROTLI:
# 压缩过的先解压,为了避免阻塞网络线程,放在其他线程执行
body = await self._loop.run_in_executor(None, brotli.decompress, body)
await self._parse_ws_message(body)
elif header.ver == ProtoVer.NORMAL:
# 没压缩过的直接反序列化,因为有万恶的GIL,这里不能并行避免阻塞
if len(body) != 0:
try:
body = json.loads(body.decode('utf-8'))
await self._handle_command(body)
except asyncio.CancelledError:
raise
except Exception:
logger.error('room=%d, body=%s', self.room_id, body)
raise
else:
# 未知格式
logger.warning('room=%d unknown protocol version=%d, header=%s, body=%s', self.room_id,
header.ver, header, body)
elif header.operation == Operation.AUTH_REPLY:
# 认证响应
body = json.loads(body.decode('utf-8'))
if body['code'] != AuthReplyCode.OK:
raise AuthError(f"auth reply error, code={body['code']}, body={body}")
await self._websocket.send_bytes(self._make_packet({}, Operation.HEARTBEAT))
else:
# 未知消息
logger.warning('room=%d unknown message operation=%d, header=%s, body=%s', self.room_id,
header.operation, header, | |
from inspect import isawaitable
from typing import Any, NamedTuple, Optional
from pytest import mark
from graphql.execution import execute, execute_sync, ExecutionResult
from graphql.language import parse
from graphql.type import (
GraphQLBoolean,
GraphQLField,
GraphQLInterfaceType,
GraphQLList,
GraphQLObjectType,
GraphQLSchema,
GraphQLString,
GraphQLUnionType,
)
from graphql.utilities import build_schema
def sync_and_async(spec):
"""Decorator for running a test synchronously and asynchronously."""
return mark.asyncio(
mark.parametrize("sync", (True, False), ids=("sync", "async"))(spec)
)
def access_variants(spec):
"""Decorator for tests with dict and object access, including inheritance."""
return mark.asyncio(
mark.parametrize("access", ("dict", "object", "inheritance"))(spec)
)
async def execute_query(
sync: bool, schema: GraphQLSchema, query: str, root_value: Any = None
) -> ExecutionResult:
"""Execute the query against the given schema synchronously or asynchronously."""
assert isinstance(sync, bool)
assert isinstance(schema, GraphQLSchema)
assert isinstance(query, str)
document = parse(query)
result = (execute_sync if sync else execute)(
schema, document, root_value
) # type: ignore
if not sync and isawaitable(result):
result = await result
assert isinstance(result, ExecutionResult)
return result
def get_is_type_of(type_, sync=True):
"""Get a sync or async is_type_of function for the given type."""
if sync:
def is_type_of(obj, _info):
return isinstance(obj, type_)
else:
async def is_type_of(obj, _info):
return isinstance(obj, type_)
return is_type_of
def get_type_resolver(types, sync=True):
"""Get a sync or async type resolver for the given type map."""
if sync:
def resolve(obj, _info, _type):
return resolve_thunk(types)[obj.__class__]
else:
async def resolve(obj, _info, _type):
return resolve_thunk(types)[obj.__class__]
return resolve
def get_type_error(sync=True):
"""Get a sync or async is_type_of or type resolver function that raises an error."""
error = RuntimeError("We are testing this error")
if sync:
def type_error(*_args):
raise error
else:
async def type_error(*_args):
raise error
return type_error
def resolve_thunk(thunk):
return thunk() if callable(thunk) else thunk
class Dog(NamedTuple):
name: str
woofs: bool
class Cat(NamedTuple):
name: str
meows: bool
def describe_execute_handles_synchronous_execution_of_abstract_types():
@sync_and_async
async def is_type_of_used_to_resolve_runtime_type_for_interface(sync):
pet_type = GraphQLInterfaceType("Pet", {"name": GraphQLField(GraphQLString)})
dog_type = GraphQLObjectType(
"Dog",
{
"name": GraphQLField(GraphQLString),
"woofs": GraphQLField(GraphQLBoolean),
},
interfaces=[pet_type],
is_type_of=get_is_type_of(Dog, sync),
)
cat_type = GraphQLObjectType(
"Cat",
{
"name": GraphQLField(GraphQLString),
"meows": GraphQLField(GraphQLBoolean),
},
interfaces=[pet_type],
is_type_of=get_is_type_of(Cat, sync),
)
schema = GraphQLSchema(
GraphQLObjectType(
"Query",
{
"pets": GraphQLField(
GraphQLList(pet_type),
resolve=lambda *_args: [
Dog("Odie", True),
Cat("Garfield", False),
],
)
},
),
types=[cat_type, dog_type],
)
query = """
{
pets {
name
... on Dog {
woofs
}
... on Cat {
meows
}
}
}
"""
assert await execute_query(sync, schema, query) == (
{
"pets": [
{"name": "Odie", "woofs": True},
{"name": "Garfield", "meows": False},
]
},
None,
)
@sync_and_async
async def is_type_of_can_throw(sync):
pet_type = GraphQLInterfaceType("Pet", {"name": GraphQLField(GraphQLString)})
dog_type = GraphQLObjectType(
"Dog",
{
"name": GraphQLField(GraphQLString),
"woofs": GraphQLField(GraphQLBoolean),
},
interfaces=[pet_type],
is_type_of=get_type_error(sync),
)
cat_type = GraphQLObjectType(
"Cat",
{
"name": GraphQLField(GraphQLString),
"meows": GraphQLField(GraphQLBoolean),
},
interfaces=[pet_type],
is_type_of=None,
)
schema = GraphQLSchema(
GraphQLObjectType(
"Query",
{
"pets": GraphQLField(
GraphQLList(pet_type),
resolve=lambda *_args: [
Dog("Odie", True),
Cat("Garfield", False),
],
)
},
),
types=[dog_type, cat_type],
)
query = """
{
pets {
name
... on Dog {
woofs
}
... on Cat {
meows
}
}
}
"""
assert await execute_query(sync, schema, query) == (
{"pets": [None, None]},
[
{
"message": "We are testing this error",
"locations": [(3, 15)],
"path": ["pets", 0],
},
{
"message": "We are testing this error",
"locations": [(3, 15)],
"path": ["pets", 1],
},
],
)
@sync_and_async
async def is_type_of_with_no_suitable_type(sync):
# added in GraphQL-core to improve coverage
pet_type = GraphQLInterfaceType("Pet", {"name": GraphQLField(GraphQLString)})
dog_type = GraphQLObjectType(
"Dog",
{
"name": GraphQLField(GraphQLString),
"woofs": GraphQLField(GraphQLBoolean),
},
interfaces=[pet_type],
is_type_of=get_is_type_of(Cat, sync),
)
schema = GraphQLSchema(
GraphQLObjectType(
"Query",
{
"pets": GraphQLField(
GraphQLList(pet_type),
resolve=lambda *_args: [Dog("Odie", True)],
)
},
),
types=[dog_type],
)
query = """
{
pets {
name
... on Dog {
woofs
}
}
}
"""
message = (
"Abstract type 'Pet' must resolve to an Object type at runtime"
" for field 'Query.pets'."
" Either the 'Pet' type should provide a 'resolve_type' function"
" or each possible type should provide an 'is_type_of' function."
)
assert await execute_query(sync, schema, query) == (
{"pets": [None]},
[{"message": message, "locations": [(3, 15)], "path": ["pets", 0]}],
)
@sync_and_async
async def is_type_of_used_to_resolve_runtime_type_for_union(sync):
dog_type = GraphQLObjectType(
"Dog",
{
"name": GraphQLField(GraphQLString),
"woofs": GraphQLField(GraphQLBoolean),
},
is_type_of=get_is_type_of(Dog, sync),
)
cat_type = GraphQLObjectType(
"Cat",
{
"name": GraphQLField(GraphQLString),
"meows": GraphQLField(GraphQLBoolean),
},
is_type_of=get_is_type_of(Cat, sync),
)
pet_type = GraphQLUnionType("Pet", [cat_type, dog_type])
schema = GraphQLSchema(
GraphQLObjectType(
"Query",
{
"pets": GraphQLField(
GraphQLList(pet_type),
resolve=lambda *_args: [
Dog("Odie", True),
Cat("Garfield", False),
],
)
},
)
)
query = """
{
pets {
... on Dog {
name
woofs
}
... on Cat {
name
meows
}
}
}
"""
assert await execute_query(sync, schema, query) == (
{
"pets": [
{"name": "Odie", "woofs": True},
{"name": "Garfield", "meows": False},
]
},
None,
)
@sync_and_async
async def deprecated_resolve_type_allows_resolving_with_type_object(sync):
cat_type: GraphQLObjectType
dog_type: GraphQLObjectType
pet_type = GraphQLInterfaceType(
"Pet",
{"name": GraphQLField(GraphQLString)},
resolve_type=get_type_resolver(
lambda: {Dog: dog_type, Cat: cat_type}, sync
),
)
dog_type = GraphQLObjectType(
"Dog",
{
"name": GraphQLField(GraphQLString),
"woofs": GraphQLField(GraphQLBoolean),
},
interfaces=[pet_type],
)
cat_type = GraphQLObjectType(
"Cat",
{
"name": GraphQLField(GraphQLString),
"meows": GraphQLField(GraphQLBoolean),
},
interfaces=[pet_type],
)
schema = GraphQLSchema(
GraphQLObjectType(
"Query",
{
"pets": GraphQLField(
GraphQLList(pet_type),
resolve=lambda *_args: [
Dog("Odie", True),
Cat("Garfield", False),
],
)
},
),
types=[cat_type, dog_type],
)
query = """
{
pets {
name
... on Dog {
woofs
}
... on Cat {
meows
}
}
}
"""
assert await execute_query(sync, schema, query) == (
{
"pets": [
{"name": "Odie", "woofs": True},
{"name": "Garfield", "meows": False},
]
},
None,
)
@sync_and_async
async def resolve_type_can_throw(sync):
pet_type = GraphQLInterfaceType(
"Pet",
{"name": GraphQLField(GraphQLString)},
resolve_type=get_type_error(sync),
)
dog_type = GraphQLObjectType(
"Dog",
{
"name": GraphQLField(GraphQLString),
"woofs": GraphQLField(GraphQLBoolean),
},
interfaces=[pet_type],
)
cat_type = GraphQLObjectType(
"Cat",
{
"name": GraphQLField(GraphQLString),
"meows": GraphQLField(GraphQLBoolean),
},
interfaces=[pet_type],
)
schema = GraphQLSchema(
GraphQLObjectType(
"Query",
{
"pets": GraphQLField(
GraphQLList(pet_type),
resolve=lambda *_args: [
Dog("Odie", True),
Cat("Garfield", False),
],
)
},
),
types=[dog_type, cat_type],
)
query = """
{
pets {
name
... on Dog {
woofs
}
... on Cat {
meows
}
}
}
"""
assert await execute_query(sync, schema, query) == (
{"pets": [None, None]},
[
{
"message": "We are testing this error",
"locations": [(3, 15)],
"path": ["pets", 0],
},
{
"message": "We are testing this error",
"locations": [(3, 15)],
"path": ["pets", 1],
},
],
)
def describe_using_typename_on_source_object():
expected = (
{
"pets": [
{"name": "Odie", "woofs": True},
{"name": "Garfield", "meows": False},
]
},
None,
)
# noinspection PyShadowingNames
def _root_value(access: str) -> Any:
if access == "dict":
return {
"pets": [
{"__typename": "Dog", "name": "Odie", "woofs": True},
{"__typename": "Cat", "name": "Garfield", "meows": False},
],
}
if access == "object":
class DogObject:
__typename = "Dog"
name = "Odie"
woofs = True
class CatObject:
__typename = "Cat"
name = "Garfield"
meows = False
class RootValueAsObject:
pets = [DogObject(), CatObject()]
return RootValueAsObject()
if access == "inheritance":
class Pet:
__typename = "Pet"
name: Optional[str] = None
class DogPet(Pet):
__typename = "Dog"
woofs: Optional[bool] = None
class Odie(DogPet):
name = "Odie"
woofs = True
class CatPet(Pet):
__typename = "Cat"
meows: Optional[bool] = None
class Tabby(CatPet):
pass
class Garfield(Tabby):
name = "Garfield"
meows = False
class RootValueWithInheritance:
pets = [Odie(), Garfield()]
return RootValueWithInheritance()
assert False, f"Unknown access variant: {access}" # pragma: no cover
def describe_union_type():
schema = build_schema(
"""
type Query {
pets: [Pet]
}
union Pet = Cat | Dog
type Cat {
name: String
meows: Boolean
}
type Dog {
name: String
woofs: Boolean
}
"""
)
query = """
{
pets {
name
... on Dog {
woofs
}
... on Cat {
meows
}
}
}
"""
@sync_and_async
@access_variants
async def resolve(sync, access):
root_value = _root_value(access)
assert await execute_query(sync, schema, query, root_value) == expected
def describe_interface_type():
schema = build_schema(
"""
type Query {
pets: [Pet]
}
interface Pet {
name: String
}
type Cat implements Pet {
name: String
meows: Boolean
}
type Dog implements Pet {
name: String
woofs: Boolean
}
"""
)
query = """
{
pets {
name
... on Dog {
woofs
}
... on Cat {
meows
}
}
}
"""
@sync_and_async
@access_variants
async def resolve(sync, access):
root_value = _root_value(access)
assert await execute_query(sync, schema, query, root_value) == expected
def resolve_type_on_interface_yields_useful_error():
schema = build_schema(
"""
type Query {
pet: Pet
}
interface Pet {
name: String
}
type Cat implements Pet {
name: String
}
type Dog implements Pet {
name: String
}
"""
)
document = parse(
"""
{
| |
from __future__ import absolute_import
import abc
import os
import uuid
import typing as tp
from datetime import datetime
from ..__version__ import __version__
from ..utils import general_utils, ABC
from . import logger
from .agent_connector import AgentConnector
from .errors import EyesError, NewTestError, DiffsFoundError, TestFailedError
from .match_window_task import MatchWindowTask
from .test_results import TestResults, TestResultsStatus
if tp.TYPE_CHECKING:
from ..utils.custom_types import (ViewPort, UserInputs, AppEnvironment, MatchResult,
RunningSession, SessionStartInfo)
from .capture import EyesScreenshot
from .geometry import Region
__all__ = ('FailureReports', 'MatchLevel', 'ExactMatchSettings', 'ImageMatchSettings', 'EyesBase')
class FailureReports(object):
"""
Failures are either reported immediately when they are detected, or when the test is closed.
"""
IMMEDIATE = "Immediate"
ON_CLOSE = "OnClose"
class MatchLevel(object):
"""
The extent in which two images match (or are expected to match).
"""
NONE = "None"
LEGACY_LAYOUT = "Layout1"
LAYOUT = "Layout2"
LAYOUT2 = "Layout2"
CONTENT = "Content"
STRICT = "Strict"
EXACT = "Exact"
class ExactMatchSettings(object):
"""
Encapsulates settings for the "Exact" match level.
"""
def __init__(self, min_diff_intensity=0, min_diff_width=0, min_diff_height=0, match_threshold=0.0):
# type: (int, int, int, float) -> None
"""
Ctor.
:param min_diff_intensity: Minimal non-ignorable pixel intensity difference.
:param min_diff_width: Minimal non-ignorable diff region width.
:param min_diff_height: Minimal non-ignorable diff region height.
:param match_threshold: The ratio of differing pixels above which images are considered mismatching.
"""
self.min_diff_intensity = min_diff_intensity # type: int
self.min_diff_width = min_diff_width # type: int
self.min_diff_height = min_diff_height # type: int
self.match_threshold = match_threshold # type: float
def __getstate__(self):
return dict(minDiffIntensity=self.min_diff_intensity,
minDiffWidth=self.min_diff_width,
minDiffHeight=self.min_diff_height,
matchThreshold=self.match_threshold)
# This is required in order for jsonpickle to work on this object.
# noinspection PyMethodMayBeStatic
def __setstate__(self, state):
raise EyesError('Cannot create ExactMatchSettings instance from dict!')
def __str__(self):
return "[min diff intensity: %d, min diff width: %d, min diff height: %d, match threshold: %f]" % (
self.min_diff_intensity, self.min_diff_width, self.min_diff_height, self.match_threshold)
class ImageMatchSettings(object):
"""
Encapsulates match settings for the a session.
"""
def __init__(self, match_level=MatchLevel.STRICT, exact_settings=None):
# type: (tp.Text, tp.Optional[ExactMatchSettings]) -> None
"""
:param match_level: The "strictness" level of the match.
:param exact_settings: Parameter for fine tuning the match when "Exact" match level is used.
"""
self.match_level = match_level # type: tp.Text
self.exact_settings = exact_settings # type: tp.Optional[ExactMatchSettings]
def __getstate__(self):
return dict(matchLevel=self.match_level, exact=self.exact_settings)
# This is required in order for jsonpickle to work on this object.
# noinspection PyMethodMayBeStatic
def __setstate__(self, state):
raise EyesError('Cannot create ImageMatchSettings instance from dict!')
def __str__(self):
return "[Match level: %s, Exact match settings: %s]" % (self.match_level, self.exact_settings)
class BatchInfo(object):
"""
A batch of tests.
"""
def __init__(self, name=None, started_at=None):
# type: (tp.Optional[tp.Text], tp.Optional[datetime]) -> None
if started_at is None:
started_at = datetime.now(general_utils.UTC)
self.name = name if name else os.environ.get('APPLITOOLS_BATCH_NAME', None) # type: tp.Optional[tp.Text]
self.started_at = started_at # type: datetime
self.id = os.environ.get('APPLITOOLS_BATCH_ID', str(uuid.uuid4())) # type: tp.Text
@property
def id_(self):
# TODO: Remove in this way of initialization in future
return self.id
@id_.setter
def id_(self, value):
self.id = value
def __getstate__(self):
return dict(name=self.name, startedAt=self.started_at.isoformat(), id=self.id)
# Required is required in order for jsonpickle to work on this object.
# noinspection PyMethodMayBeStatic
def __setstate__(self, state):
raise EyesError('Cannot create BatchInfo instance from dict!')
def __str__(self):
return "%s - %s - %s" % (self.name, self.started_at, self.id)
class EyesBase(ABC):
_DEFAULT_MATCH_TIMEOUT = 2000 # Milliseconds
_DEFAULT_WAIT_BEFORE_SCREENSHOTS = 100 # ms
BASE_AGENT_ID = "eyes.selenium.python/%s" % __version__
DEFAULT_EYES_SERVER = 'https://eyesapi.applitools.com'
def __init__(self, server_url=DEFAULT_EYES_SERVER):
# type: (tp.Text) -> None
"""
Creates a new (possibly disabled) Eyes instance that interacts with the Eyes server.
:param server_url: The URL of the Eyes server
"""
# An optional string identifying the current library using the SDK.
self.agent_id = None # type: tp.Optional[tp.Text]
self._agent_connector = AgentConnector(server_url, self.full_agent_id) # type: AgentConnector
self._should_get_title = False # type: bool
self._is_open = False # type: bool
self._app_name = None # type: tp.Optional[tp.Text]
self._running_session = None # type: tp.Optional[RunningSession]
self._match_timeout = EyesBase._DEFAULT_MATCH_TIMEOUT # type: int
self._last_screenshot = None # type: tp.Optional[EyesScreenshot]
self._should_match_once_on_timeout = False # type: bool
self._start_info = None # type: tp.Optional[SessionStartInfo]
self._test_name = None # type: tp.Optional[tp.Text]
self._user_inputs = [] # type: UserInputs
self._region_to_check = None # type: tp.Optional[Region]
self._viewport_size = None # type: ViewPort
# key-value pairs to be associated with the test. Can be used for filtering later.
self._properties = [] # type: tp.List
# Disables Applitools Eyes and uses the webdriver directly.
self.is_disabled = False # type: bool
# Should the test report mismatches immediately or when it is finished. See FailureReports.
self.failure_reports = FailureReports.ON_CLOSE # type: tp.Text
# The default match settings for the session. See ImageMatchSettings.
self.default_match_settings = ImageMatchSettings() # type: ImageMatchSettings
# The batch to which the tests belong to. See BatchInfo. None means no batch.
self.batch = None # type: tp.Optional[BatchInfo]
# A string identifying the OS running the AUT. Use this to override Eyes automatic inference.
self.host_os = None # type: tp.Optional[tp.Text]
# A string identifying the app running the AUT. Use this to override Eyes automatic inference.
self.host_app = None # type: tp.Optional[tp.Text]
# A string that, if specified, determines the baseline to compare with and disables automatic baseline
# inference.
self.baseline_branch_name = None # type: tp.Optional[tp.Text]
# A boolean denoting whether new tests should be automatically accepted.
self.save_new_tests = True # type: bool
# Whether failed tests should be automatically saved with all new output accepted.
self.save_failed_tests = False # type: bool
# A string identifying the branch in which tests are run.
self.branch_name = None # type: tp.Optional[tp.Text]
# A string identifying the parent branch of the branch set by "branch_name".
self.parent_branch_name = None # type: tp.Optional[tp.Text]
# If true, Eyes will treat new tests the same as failed tests.
self.fail_on_new_test = False # type: bool
# The number of milliseconds to wait before each time a screenshot is taken.
self.wait_before_screenshots = EyesBase._DEFAULT_WAIT_BEFORE_SCREENSHOTS # type: int
# If true, we will send full DOM to the server for analyzing
self.send_dom = False
# If true, use DOM for comparision
self.use_dom = False
self.enable_patterns = False
@property
def baseline_name(self):
logger.warning('DEPRECATED: Use `baseline_branch_name` instead')
return self.baseline_branch_name
@baseline_name.setter
def baseline_name(self, value):
logger.warning('DEPRECATED: Use `baseline_branch_name` instead')
self.baseline_branch_name = value
@property
@abc.abstractmethod
def _title(self):
# type: () -> tp.Text
"""
Returns the title of the window of the AUT, or empty string if the title is not available.
"""
@abc.abstractmethod
def get_screenshot(self):
pass
@abc.abstractmethod
def get_viewport_size(self):
pass
@staticmethod
@abc.abstractmethod
def set_viewport_size(driver, viewport_size):
pass
@abc.abstractmethod
def _ensure_viewport_size(self):
# type: () -> None
"""
Assign the viewport size we need to be in the default content frame.
"""
@property
@abc.abstractmethod
def _environment(self):
# type: () -> AppEnvironment
"""
Application environment is the environment (e.g., the host OS) which runs the application under test.
:return: The current application environment.
"""
@property
@abc.abstractmethod
def _inferred_environment(self):
pass
@property
def _seconds_to_wait_screenshot(self):
return self.wait_before_screenshots / 1000.0
@property
def match_level(self):
# type: () -> tp.Text
"""
Gets the default match level for the entire session. See ImageMatchSettings.
"""
return self.default_match_settings.match_level
@match_level.setter
def match_level(self, match_level):
# type: (tp.Text) -> None
"""
Sets the default match level for the entire session. See ImageMatchSettings.
:param match_level: The match level to set. Should be one of the values defined by MatchLevel
"""
self.default_match_settings.match_level = match_level
@property
def match_timeout(self):
# type: () -> int
"""
Gets the default timeout for check_XXXX operations. (milliseconds)
:return: The match timeout (milliseconds)
"""
return self._match_timeout
@match_timeout.setter
def match_timeout(self, match_timeout):
# type: (int) -> None
"""
Sets the default timeout for check_XXXX operations. (milliseconds)
"""
if 0 < match_timeout < MatchWindowTask.MINIMUM_MATCH_TIMEOUT:
raise ValueError("Match timeout must be at least 60ms.")
self._match_timeout = match_timeout
@property
def api_key(self):
# type: () -> tp.Text
"""
Gets the Api key used for authenticating the user with Eyes.
:return: The Api key used for authenticating the user with Eyes.
"""
return self._agent_connector.api_key
@api_key.setter
def api_key(self, api_key):
# type: (tp.Text) -> None
"""
Sets the api key used for authenticating the user with Eyes.
:param api_key: The api key used for authenticating the user with Eyes.
"""
self._agent_connector.api_key = api_key # type: ignore
@property
def server_url(self):
# type: () -> tp.Text
"""
Gets the URL of the Eyes server.
:return: The URL of the Eyes server, or None to | |
import torch
import sys, math
import numpy as np
import torch.jit as jit
import warnings
import copy
import torch.nn.init as init
import torch.nn as nn
from distutils.util import strtobool
from models.base import Model
from models.utils import *
from models.multi_head_att import MultiHeadedAttention
from models.ssm.inference import RNN_STInf, Attention_STInf
from models.iefs.gated import GatedTransition
from models.iefs.att_iefs import AttentionIEFTransition
from models.iefs.moe import MofE
from pyro.distributions import Normal, Independent, Categorical, LogNormal
from typing import List, Tuple
from torch import Tensor
from collections import namedtuple
from typing import List, Tuple
from torch.autograd import Variable
from argparse import ArgumentParser
class SSM(Model):
def __init__(self, trial, **kwargs):
super(SSM, self).__init__(trial)
self.save_hyperparameters()
def init_model(self):
ttype = self.hparams['ttype']; etype = self.hparams['etype']
dim_hidden = self.hparams['dim_hidden']
num_heads = self.hparams['nheads']
dim_stochastic = self.hparams['dim_stochastic']
#dim_stochastic = self.trial.suggest_int('dim_stochastic',8,256)
dim_data = self.hparams['dim_data']
dim_base = self.hparams['dim_base']
dim_treat = self.hparams['dim_treat']
post_approx = self.hparams['post_approx']
inftype = self.hparams['inftype']; etype = self.hparams['etype']; ttype = self.hparams['ttype']
augmented = self.hparams['augmented']; alpha1_type = self.hparams['alpha1_type']
rank = self.hparams['rank']; combiner_type = self.hparams['combiner_type']; nheads = self.hparams['nheads']
add_stochastic = self.hparams['add_stochastic']
zmatrix = self.hparams['zmatrix']
# Inference Network
self.inf_noise = np.abs(self.hparams['inf_noise'])
if inftype == 'rnn':
self.inf_network = RNN_STInf(dim_base, dim_data, dim_treat, dim_hidden, dim_stochastic, post_approx = post_approx, rank = rank, combiner_type = combiner_type)
elif inftype == 'rnn_bn':
self.inf_network = RNN_STInf(dim_base, dim_data, dim_treat, dim_hidden, dim_stochastic, post_approx = post_approx, rank = rank, use_bn=True, combiner_type = combiner_type)
elif inftype == 'rnn_relu':
self.inf_network = RNN_STInf(dim_base, dim_data, dim_treat, dim_hidden, dim_stochastic, post_approx = post_approx, rank = rank, nl='relu', combiner_type = combiner_type)
elif inftype == 'att':
self.inf_network = Attention_STInf(dim_base, dim_data, dim_treat, dim_hidden, dim_stochastic, nheads = num_heads, post_approx = post_approx, rank = rank)
else:
raise ValueError('Bad inference type')
# Emission Function
if etype == 'lin':
self.e_mu = nn.Linear(dim_stochastic, dim_data)
self.e_sigma = nn.Linear(dim_stochastic, dim_data)
elif etype == 'nl':
dim_hidden = self.trial.suggest_int('dim_hidden',100,500)
emodel = nn.Sequential(nn.Linear(dim_stochastic, dim_hidden), nn.ReLU(True))
self.e_mu = nn.Sequential(emodel, nn.Linear(dim_hidden, dim_data))
self.e_sigma = nn.Sequential(emodel, nn.Linear(dim_hidden, dim_data))
else:
raise ValueError('bad etype')
# Transition Function
if self.hparams['include_baseline'] != 'none':
self.transition_fxn = TransitionFunction(dim_stochastic, dim_data, dim_treat+dim_base, dim_hidden, ttype, \
augmented=augmented, alpha1_type=alpha1_type, add_stochastic=add_stochastic, num_heads=num_heads, zmatrix=zmatrix)
else:
self.transition_fxn = TransitionFunction(dim_stochastic, dim_data, dim_treat, dim_hidden, ttype, \
augmented=augmented, alpha1_type=alpha1_type, add_stochastic=add_stochastic, num_heads=num_heads, zmatrix=zmatrix)
# Prior over Z1
self.prior_W = nn.Linear(dim_treat+dim_data+dim_base, dim_stochastic)
self.prior_sigma = nn.Linear(dim_treat+dim_data+dim_base, dim_stochastic)
def p_Z1(self, B, X0, A0):
inp_cat = torch.cat([B, X0, A0], -1)
mu = self.prior_W(inp_cat)
sigma = torch.nn.functional.softplus(self.prior_sigma(inp_cat))
p_z_bxa = Independent(Normal(mu, sigma), 1)
return p_z_bxa
def p_X_Z(self, Zt, Tval):
if 'spiral' in self.hparams['etype']:
mu = self.e_mu(Zt, Tval)
if 'Spiral' in self.e_sigma.__class__.__name__:
sigma = torch.nn.functional.softplus(self.e_sigma(Zt, Tval))
else:
sigma = torch.nn.functional.softplus(self.e_sigma(Zt))
else:
mu = self.e_mu(Zt)
sigma = torch.nn.functional.softplus(self.e_sigma(Zt))
return mu, sigma
def p_Zt_Ztm1(self, Zt, A, B, X, A0, eps = 0.):
X0 = X[:,0,:]; Xt = X[:,1:,:]
inp_cat = torch.cat([B, X0, A0], -1)
mu1 = self.prior_W(inp_cat)[:,None,:]
sig1 = torch.nn.functional.softplus(self.prior_sigma(inp_cat))[:,None,:]
# mu1 = torch.zeros_like(sig1).to(sig1.device)
Tmax = Zt.shape[1]
if self.hparams['augmented']:
Zinp = torch.cat([Zt[:,:-1,:], Xt[:,:-1,:]], -1)
else:
Zinp = Zt[:,:-1,:]
if self.hparams['include_baseline'] != 'none':
Aval = A[:,1:Tmax,:]
Acat = torch.cat([Aval[...,[0]],B[:,None,:].repeat(1,Aval.shape[1],1), Aval[...,1:]],-1)
mu2T, sig2T = self.transition_fxn(Zinp, Acat, eps = eps)
else:
mu2T, sig2T = self.transition_fxn(Zinp, A[:,1:Tmax,:], eps = eps)
mu, sig = torch.cat([mu1,mu2T],1), torch.cat([sig1,sig2T],1)
return Independent(Normal(mu, sig), 1)
def get_loss(self, B, X, A, M, Y, CE, anneal = 1., return_reconstruction = False, with_pred = False):
_, _, lens = get_masks(M)
B, X, A, M, Y, CE = B[lens>1], X[lens>1], A[lens>1], M[lens>1], Y[lens>1], CE[lens>1]
m_t, m_g_t, _ = get_masks(M[:,1:,:])
Xnew = X + torch.randn(X.shape).to(X.device)*self.inf_noise
Z_t, q_zt = self.inf_network(Xnew, A, M, B)
Tmax = Z_t.shape[1]
p_x_mu, p_x_std = self.p_X_Z(Z_t, A[:,1:Tmax+1,[0]])
p_zt = self.p_Zt_Ztm1(Z_t, A, B, X, A[:,0,:])
masked_nll = masked_gaussian_nll_3d(X[:,1:Tmax+1,:], p_x_mu, p_x_std, M[:,1:Tmax+1,:])
full_masked_nll = masked_nll
masked_nll = masked_nll.sum(-1).sum(-1)
# full_masked_kl_t = m_t[:,:Tmax]*kl_t
# full_nelbo = full_masked_nll + (m_t[:,:Tmax]*kl_t)[...,None]
if with_pred:
p_x_mu_pred, p_x_std_pred = self.p_X_Z(p_zt.mean, A[:,:Z_t.shape[1],[0]])
masked_nll_pred = masked_gaussian_nll_3d(X[:,1:Tmax+1,:], p_x_mu_pred, p_x_std_pred, M[:,1:Tmax+1,:])
masked_nll_pred = masked_nll_pred.sum(-1).sum(-1)
masked_nll = (masked_nll+masked_nll_pred)*0.5
kl_t = q_zt.log_prob(Z_t)-p_zt.log_prob(Z_t)
masked_kl_t= (m_t[:,:Tmax]*kl_t).sum(-1)
neg_elbo = masked_nll + anneal*masked_kl_t
if return_reconstruction:
return (neg_elbo, masked_nll, masked_kl_t, torch.ones_like(masked_kl_t), p_x_mu*M[:,1:,:], p_x_std*M[:,1:,:])
else:
return (neg_elbo, masked_nll, masked_kl_t, torch.ones_like(masked_kl_t))
'''
full_masked_kl_t = m_t[:,:Tmax]*kl_t
full_nelbo = full_masked_nll + (m_t[:,:Tmax]*kl_t)[...,None]
return (neg_elbo, masked_nll, masked_kl_t, torch.ones_like(masked_kl_t), full_masked_nll, full_masked_kl_t)
'''
def imp_sampling(self, B, X, A, M, Y, CE, anneal = 1., imp_samples=100, idx = -1, mask = None):
_, _, lens = get_masks(M)
B, X, A, M, Y, CE = B[lens>1], X[lens>1], A[lens>1], M[lens>1], Y[lens>1], CE[lens>1]
m_t, m_g_t, _ = get_masks(M[:,1:,:])
ll_estimates = torch.zeros((imp_samples,X.shape[0])).to(X.device)
ll_priors = torch.zeros((imp_samples,X.shape[0])).to(X.device)
ll_posteriors = torch.zeros((imp_samples,X.shape[0])).to(X.device)
X0 = X[:,0,:]; Xt = X[:,1:,:]; A0 = A[:,0,:]
inp_cat = torch.cat([B, X0, A0], -1)
mu1 = self.prior_W(inp_cat)[:,None,:]
sig1 = torch.nn.functional.softplus(self.prior_sigma(inp_cat))[:,None,:]
for sample in range(imp_samples):
Z_s, q_zt = self.inf_network(X, A, M, B)
Tmax = Z_s.shape[-2]
p_x_mu, p_x_std = self.p_X_Z(Z_s, A[:,1:Tmax+1,[0]])
masked_nll = masked_gaussian_nll_3d(X[:,1:Tmax+1,:], p_x_mu, p_x_std, M[:,1:Tmax+1,:]) # (bs,T,D)
if idx != -1:
masked_ll = -1*masked_nll[...,[idx]].sum(-1).sum(-1)
elif mask is not None:
mask = mask[...,:Tmax]
masked_ll = -1*(masked_nll.sum(-1)*mask).sum(-1)
else:
masked_ll = -1*masked_nll.sum(-1).sum(-1)
# prior
if self.hparams['augmented']:
Zinp = torch.cat([Z_s[:,:-1,:], Xt[:,:-1,:]], -1)
else:
Zinp = Z_s[:,:-1,:]
if self.hparams['include_baseline']:
Aval = A[:,1:Tmax,:]
Acat = torch.cat([Aval[...,[0]],B[:,None,:].repeat(1,Aval.shape[1],1), Aval[...,1:]],-1)
mu2T, sig2T = self.transition_fxn(Zinp, Acat)
else:
mu2T, sig2T = self.transition_fxn(Zinp, A[:,1:Tmax,:])
mu_prior, std_prior = torch.cat([mu1,mu2T],1), torch.cat([sig1,sig2T],1)
ll_prior = -1*masked_gaussian_nll_3d(Z_s, mu_prior, std_prior, m_t[:,:Tmax,None])
# posterior
ll_posterior = -1*masked_gaussian_nll_3d(Z_s, q_zt.mean, q_zt.stddev, m_t[:,:Tmax,None])
# store values
ll_estimates[sample] = masked_ll
if idx != -1:
ll_priors[sample] = ll_prior[...,[idx]].sum(-1).sum(-1)
ll_posteriors[sample] = ll_posterior[...,[idx]].sum(-1).sum(-1)
elif mask is not None:
mask = mask[...,:Tmax]
ll_priors[sample] = (ll_prior.sum(-1)*mask).sum(-1)
ll_posteriors[sample] = (ll_posterior.sum(-1)*mask).sum(-1)
else:
ll_priors[sample] = ll_prior.sum(-1).sum(-1)
ll_posteriors[sample] = ll_posterior.sum(-1).sum(-1)
nll_estimate = -1*(torch.logsumexp(ll_estimates + ll_priors - ll_posteriors, dim=0) - np.log(imp_samples))
return nll_estimate, torch.mean(nll_estimate)
def forward(self, B, X, A, M, Y, CE, anneal = 1., full_ret_loss=False):
if self.hparams.clock_ablation:
A[...,0] = torch.ones(A.shape[1])
if self.training:
if self.hparams['elbo_samples']>1:
B, X = torch.repeat_interleave(B, repeats=self.elbo_samples, dim=0), torch.repeat_interleave(X, repeats=self.elbo_samples, dim=0)
A, M = torch.repeat_interleave(A, repeats=self.elbo_samples, dim=0), torch.repeat_interleave(M, repeats=self.elbo_samples, dim=0)
Y, CE= torch.repeat_interleave(Y, repeats=self.elbo_samples, dim=0), torch.repeat_interleave(CE, repeats=self.elbo_samples, dim=0)
neg_elbo, masked_nll, kl, _ = self.get_loss(B, X, A, M, Y, CE, anneal = anneal, with_pred = True)
else:
neg_elbo, masked_nll, kl, _ = self.get_loss(B, X, A, M, Y, CE, anneal = anneal, with_pred = False)
reg_loss = torch.mean(neg_elbo)
for name,param in self.named_parameters():
if self.reg_all == 'all':
# reg_loss += self.hparams['C']*apply_reg(param, reg_type=self.hparams['reg_type'])
reg_loss += self.C*apply_reg(param, reg_type=self.reg_type)
elif self.reg_all == 'except_multi_head':
# regularize everything except the multi-headed attention weights?
if 'attn' not in name:
reg_loss += self.C*apply_reg(param, reg_type=self.reg_type)
elif self.reg_all == 'except_multi_head_ief':
if 'attn' not in name and 'logcell' not in name \
and 'treatment_exp' not in name and 'control_layer' not in name:
reg_loss += self.C*apply_reg(param, reg_type=self.reg_type)
loss = torch.mean(reg_loss)
# if full_ret_loss:
# return (full_nelbo, torch.mean(neg_elbo), torch.mean(masked_nll), torch.mean(kl), torch.ones_like(kl)), loss
return (torch.mean(neg_elbo), torch.mean(masked_nll), torch.mean(kl), torch.ones_like(kl)), loss
def forward_sample(self, A, T_forward, Z_start = None, B=None, X0=None, A0=None, eps = 0.):
if Z_start is None:
inp_cat = torch.cat([B, X0, A0], -1)
mu1 = self.prior_W(inp_cat)
sig1 = torch.nn.functional.softplus(self.prior_sigma(inp_cat))
Z_start = torch.squeeze(Independent(Normal(mu1, sig1), 1).sample((1,)))
Zlist = [Z_start]
for t in range(1, T_forward):
Ztm1 = Zlist[t-1]
if self.hparams.include_baseline != 'none':
Aval = A[:,t-1,:]
Acat = torch.cat([Aval[...,[0]], B, Aval[...,1:]], -1)
mut, sigmat= self.transition_fxn(Ztm1, Acat, eps = eps)
else:
mut, sigmat= self.transition_fxn(Ztm1, A[:,t-1,:], eps = eps)
sample = torch.squeeze(Independent(Normal(mut, sigmat), 1).sample((1,)))
if len(sample.shape) == 1:
sample = sample[None,...]
Zlist.append(sample)
Z_t = torch.cat([k[:,None,:] for k in Zlist], 1)
p_x_mu, p_x_sigma = self.p_X_Z(Z_t, A[:,:Z_t.shape[1],[0]])
sample = torch.squeeze(Independent(Normal(p_x_mu, p_x_sigma), 1).sample((1,)))
return sample, (Z_t, p_x_mu, p_x_sigma)
def inspect(self, T_forward, T_condition, B, X, A, M, Y, CE, restrict_lens = False, nsamples = 1, eps = 0.):
self.eval()
m_t, _, lens = get_masks(M)
idx_select = lens>1
B, X, A, M, Y, CE = B[lens>1], X[lens>1], A[lens>1], M[lens>1], Y[lens>1], CE[lens>1]
m_t, m_g_t, lens = get_masks(M[:,1:,:])
Z_t, q_zt = self.inf_network(X, A, M, B)
p_x_mu, p_x_std = self.p_X_Z(Z_t, A[:,:Z_t.shape[1],[0]])
p_zt = self.p_Zt_Ztm1(Z_t, A, B, X, A[:,0,:], eps = eps)
Tmax = Z_t.shape[1]
masked_nll = masked_gaussian_nll_3d(X[:,1:Tmax+1,:], p_x_mu, p_x_std, M[:,1:Tmax+1,:])
kl_t = q_zt.log_prob(Z_t)-p_zt.log_prob(Z_t)
masked_kl_t = (m_t[:,:Tmax]*kl_t).sum(-1)
per_feat_nelbo = (masked_nll.sum(1) + masked_kl_t[...,None]).mean(0)
# calculate MSE instead
mse = (((p_x_mu-X[:,1:Tmax+1])**2)*M[:,1:Tmax+1]).sum(0).sum(0)
vals= M[:,1:Tmax+1].sum(0).sum(0)
per_feat_nelbo = mse/vals
neg_elbo = torch.mean(masked_nll.sum(-1).sum(-1)+masked_kl_t)
if restrict_lens:
_, _, lens = get_masks(M)
idx_select = lens>(T_forward+T_condition)
B, X, A, M, Y, CE = B[idx_select], X[idx_select], A[idx_select], M[idx_select], Y[idx_select], CE[idx_select]
| |
<reponame>jph425/terminal_tattoo<filename>terminal_tattoo.py
#!/usr/bin/env python
#
# terminal_tattoo.py
#
# Renders an image as specified
# (c) Copyright 2021, <NAME>. All rights reserved.
from PIL import Image, ImageDraw, ImageFont
import argparse
import logging
import tempfile
from os import path, get_terminal_size
from sys import exit
import pprint
import re
### SOME REASONABLE DEFAULTS
DEFAULT_FONT = '/System/Library/Fonts/Menlo.ttc'
DEFAULT_SIZE = 45
DEFAULT_POS = 'tR' # top right corner
DEFAULT_FGC = 'fK' # black
DEFAULT_BGC = 'bW' # white
### I USE THESE IN A BUNCH OF PLACES AND I DON'T WANT TO KEEP TYPING IT
POSITION_CODES = ['pT', 'pTL', 'pTR', 'pB', 'pBL', 'pBR', 'pC', 'pL', 'pR']
### EMPIRICAL LINEAR TRANSFORMATION FROM CHARACTER GRID TO PIXELS
RETINA_HCELL_PIXELS = 14
RETINA_VCELL_PIXELS = 28
RETINA_H_OFFSET = 20
RETINA_V_OFFSET = 14
### EXIT CODES
EXIT_INVALID_FG = -1
EXIT_INVALID_BG = -2
EXIT_DOES_NOT_FIT = -3
EXIT_CATASTROPHIC_ERROR = -10
##############################################################################
# logging stuff:
##############################################################################
class ColorizingStreamHandler(logging.StreamHandler):
@property
def is_tty(self):
isatty = getattr(self.stream, 'isatty', None)
return isatty
def emit(self, record):
# noinspection PyBroadException
try:
message = self.format(record)
stream = self.stream
if not self.is_tty:
stream.write(message)
else:
self.output_colorized(message)
stream.write(getattr(self, 'terminator', '\n'))
self.flush()
except (KeyboardInterrupt, SystemExit):
raise
except:
self.handleError(record)
def format(self, record):
message = logging.StreamHandler.format(self, record)
if self.is_tty:
# Don't colorize traceback
parts = message.split('\n', 1)
parts[0] = self.colorize(parts[0], record)
message = '\n'.join(parts)
return message
# color names to partial ANSI code (there'll be math later to make complete codes)
color_map = {
'black': 0,
'red': 1,
'green': 2,
'yellow': 3,
'blue': 4,
'magenta': 5,
'cyan': 6,
'white': 7,
}
# logging levels to (background, foreground, intense)
# NOT multi-platform!
level_map = {
logging.DEBUG: (None, 'blue', False),
logging.INFO: (None, 'black', False),
logging.WARNING: (None, 'yellow', False),
logging.ERROR: (None, 'red', True),
logging.CRITICAL: ('red', 'white', True),
}
csi = '\x1b['
reset = '\x1b[0m'
def colorize(self, message, record):
if record.levelno in self.level_map:
bg, fg, bold = self.level_map[record.levelno]
params = []
if bg in self.color_map:
params.append(str(self.color_map[bg] + 40))
if fg in self.color_map:
params.append(str(self.color_map[fg] + 30))
if bold:
params.append('1')
if params:
message = ''.join((self.csi, ';'.join(params), 'm', message, self.reset))
return message
def output_colorized(self, message):
self.stream.write(message)
# End Class ColorizingStreamHandler
# Initialize logging objects
Logger = logging.getLogger("terminal_tattoo")
formatter = logging.Formatter('%(levelname)-10s: %(message)s')
handler = ColorizingStreamHandler()
handler.setFormatter(formatter)
Logger.addHandler(handler)
pp = pprint.PrettyPrinter(indent=4)
##############################################################################
# main:
##############################################################################
def main():
parser = config_parser()
args = parser.parse_args()
if None == args.verbose:
Logger.setLevel(logging.ERROR)
handler.setLevel(logging.ERROR)
else:
if args.verbose > 0:
Logger.setLevel(logging.WARNING)
handler.setLevel(logging.WARNING)
if args.verbose > 1:
Logger.setLevel(logging.INFO)
handler.setLevel(logging.INFO)
if args.verbose > 2:
Logger.setLevel(logging.DEBUG)
handler.setLevel(logging.DEBUG)
Logger.debug("parsed args:")
pp.pprint(args)
(c, l) = get_terminal_size()
(w, h) = get_terminal_pixel_size(c, l, RETINA_HCELL_PIXELS, RETINA_VCELL_PIXELS, RETINA_H_OFFSET, RETINA_V_OFFSET)
position = check_position(args)
fg_color = check_fg_color(args)
bg_color = check_bg_color(args)
out_path = check_output_file(args)
font = check_font(args)
text = ' '.join(args.text)
size = check_size(args)
alpha = check_alpha(args)
margin = check_margin(args)
render_base_image = create_image(w, h, rgb_to_rgba(html_to_888(bg_color), 255))
render_font = create_font(font, size)
(render_text_width, render_text_height) = get_text_dimensions(render_font, text)
if not fit_check(render_text_width, render_text_height, margin, w, h):
exit(EXIT_DOES_NOT_FIT)
anchor = get_text_anchor_pos(position, render_text_width, render_text_height, render_base_image.size[0], render_base_image.size[1], margin)
render_comp = composite_text(render_base_image, text, render_font, anchor, rgb_to_rgba(html_to_888(fg_color), alpha))
render_comp.save(out_path)
return
##############################################################################
# rendering functions:
##############################################################################
def create_font(font_name, size):
return ImageFont.truetype(font_name, size)
def create_image(w, h, blanking_color):
image = Image.new('RGBA', (w, h), blanking_color)
return image
def composite_text(base_image, text, font_obj, anchor, color_rgba):
text_img = Image.new('RGBA', base_image.size, (255,255,255,0))
drawing = ImageDraw.Draw(text_img)
drawing.text(anchor, text, font=font_obj, fill=color_rgba)
ret = Image.alpha_composite(base_image, text_img)
return ret
##############################################################################
# help, sanitize, re-format, safety:
##############################################################################
def rgb_to_rgba(rgb, a):
return (rgb[0], rgb[1], rgb[2], a)
def fit_check(render_text_width, render_text_height, margin, w, h):
m2 = 2 * margin
if h >= render_text_height + m2 and w >= render_text_width + m2:
return True
if h >= render_text_height + margin and w >= render_text_width + margin:
Logger.warning("this text just barely fits")
return True
return False
def get_terminal_dimensions():
ts = get_terminal_size()
columns = ts.columns
lines = ts.lines
Logger.debug("terminal character cell dimensions measured at ({}, {})".format(columns, lines))
return (columns, lines)
def get_terminal_pixel_size(columns, lines, h_pix, v_pix, h_offset=0, v_offset=0):
height = lines * v_pix + v_offset
width = columns * h_pix + h_offset
Logger.info("terminal dimensions: width: {} height: {}".format(width, height))
return (width, height)
def sanitize_html_color(code):
m = re.match(r'[#]?([0-9a-fA-F]{6})', code)
Logger.debug("santized html code {} to {}".format(code, m.group(1)))
return m.group(1)
def validate_html_color(color):
ret = False
pattern = r'[#]?[0-9a-fA-F]{6}'
m = re.search(pattern, color)
if m.group(0) == color:
ret = True
return ret
def html_to_888(html_str):
pat = r'(?P<red>[0-9a-fA-F]{2})(?P<green>[0-9a-fA-F]{2})(?P<blue>[0-9a-fA-F]{2})'
m = re.match(pat, html_str)
r = hex_byte_to_int(m.group('red'))
g = hex_byte_to_int(m.group('green'))
b = hex_byte_to_int(m.group('blue'))
Logger.debug("converted color #{} to RGB888 ({}, {}, {})".format(html_str, r, g, b))
return (r,g,b)
def hex_byte_to_int(hexbyte_string):
return int(hexbyte_string, 16)
def get_text_dimensions(font_obj, text):
(w, h) = font_obj.getsize(text)
Logger.debug("measured size of text (\'{}\') is ({}, {})".format(text, w, h))
return (w, h)
def get_text_anchor_pos(pos, text_w, text_h, image_w, image_h, margin=0):
"""the text anchor is (by default in ImageFont) the top left corner of the
bounding box. I see no reason to change this. The math is trivial when we
know the desired text location in the image, the image width and height,
and the text width and height."""
anchor_x = 0
anchor_y = 0
(centered_x, centered_y) = center_nested_frames(image_w, image_h, text_w, text_h)
far_x = image_w - (margin + text_w)
far_y = image_h - (margin + text_h)
if pos == 'pTL':
# top left corner: just apply margins
anchor_x = margin
anchor_y = margin
elif pos == 'pT':
# top center: margin in y, centered text in x
anchor_x = centered_x
anchor_y = margin
elif pos == 'pTR':
# top right corner: image_w - (margin + text_w), margin in y
anchor_x = far_x
anchor_y = margin
elif pos == 'pR':
# right center: image_w - (margin + text_w), center in y
anchor_x = far_x
anchor_y = centered_y
elif pos == 'pBR':
# bottom right corner: image_w - (margin + text_w), image_h - (margin + text_h)
anchor_x = far_x
anchor_y = far_y
elif pos == 'pB':
# bottom center: center in x, image_h - (margin + text_h) in y
anchor_x = centered_x
anchor_y = far_y
elif pos == 'pBL':
# bottom left corner: margin in x, image_ - (margin + text_h) in y
anchor_x = margin
anchor_y = far_y
elif pos == 'pL':
# left center: margin in x, center in y
anchor_x = margin
anchor_y = centered_y
elif pos == 'pC':
# centered: center in x, center in y
anchor_x = centered_x
anchor_y = centered_y
else:
raise RuntimeError("Not sure how we got here, but this isn't a valid position {}".format(pos))
exit(EXIT_CATASTROPHIC_ERROR)
return (anchor_x, anchor_y)
def center_nested_frames(outer_w, outer_h, inner_w, inner_h):
# we can ignore the margin since it's symmetric, however other
# checks are still needed to ensure the margin isn't violated.
w = (outer_w / 2) - (inner_w / 2)
h = (outer_h / 2) - (inner_h / 2)
return (w, h)
##############################################################################
# input validation functions:
##############################################################################
def check_position(args):
ret = DEFAULT_POS
position_args = POSITION_CODES
for p in position_args:
if p in args and getattr(args, p) == True:
ret = p
break
Logger.info("position will be {}".format(ret))
return ret
def check_fg_color(args):
ret = DEFAULT_FGC
skip_iter = False
if args.f is not None:
if validate_html_color(args.f):
Logger.debug("the detected bg color is {}".format(args.f))
ret = args.f
else:
Logger.error("invalid bg color format given, a 6-digit hex value is required (HTML format)")
exit(EXIT_INVALID_FG)
color_args = ['f', 'fR', 'fG', 'fB', 'fW', 'fK', 'fC', 'fM', 'fY', 'fg']
color_in_hex = {'fR': 'FF0000', 'fG': '00FF00', 'fB': '0000FF', 'fW': 'FFFFFF', 'fK': '000000', 'fC': '00FFFF', 'fM': 'FF00ff', 'fY': 'FFFF00', 'fg': 'A9A9A9'}
if not skip_iter:
for color in color_args:
if getattr(args, color) == True:
Logger.debug("the detected fg color is: {}".format(color))
ret = color_in_hex[color]
Logger.info("background color will be {}".format(ret))
ret = sanitize_html_color(ret)
return ret
def check_bg_color(args):
ret = DEFAULT_BGC
skip_iter = False
if args.b is not None:
if validate_html_color(args.b):
Logger.debug("the detected bg color is {}".format(args.b))
ret = args.b
else:
Logger.error("invalid bg color format given, a 6-digit hex value is required (HTML format)")
exit(EXIT_INVALID_BG)
color_args = ['bR', 'bG', 'bB', 'bW', 'bK', 'bC', 'bM', 'bY', 'bg']
color_in_hex = {'bR': 'FF0000', 'bG': '00FF00', 'bB': '0000FF', 'bW': 'FFFFFF', 'bK': '000000', 'bC': '00FFFF', 'bM': 'FF00ff', 'bY': 'FFFF00', 'bg': 'A9A9A9'}
if not skip_iter:
for color in color_args:
if getattr(args, color) == True:
Logger.debug("the detected bg color is: {}".format(color))
ret = color_in_hex[color]
Logger.info("background color will be {}".format(ret))
ret = sanitize_html_color(ret)
return ret
def check_alpha(args):
a = args.alpha
if a > 255:
a = 255
Logger.info("clamping alpha to 255")
elif a < 0:
a = 0
Logger.info("clamping alpha to 0 (what are you doing?)")
else:
Logger.info("alpha will be {}".format(a))
return a
def check_margin(args):
ret = args.margin
if ret is None:
return | |
DIR + '/complex/multi-tc-per-file/test_tc.vhd',
]) + '\n')
def test_vhlib_default(self):
"""Test the dependency analyzer with vhlib, default filters"""
#pylint: disable=C0301
self.maxDiff = None #pylint: disable=C0103
code, out, _ = run_vhdeps('dump', '-i', DIR + '/complex/vhlib')
self.assertEqual(code, 0)
self.assertEqual(out, '\n'.join([
'dep work 2008 ' + DIR + '/complex/vhlib/sim/TestCase_pkg.sim.08.vhd',
'dep work 2008 ' + DIR + '/complex/vhlib/sim/SimDataComms_pkg.sim.08.vhd',
'top work 2008 ' + DIR + '/complex/vhlib/sim/SimDataComms_tc.sim.08.vhd',
'dep work 2008 ' + DIR + '/complex/vhlib/stream/model/StreamMonitor_pkg.sim.08.vhd',
'dep work 2008 ' + DIR + '/complex/vhlib/stream/model/StreamSource_pkg.sim.08.vhd',
'dep work 2008 ' + DIR + '/complex/vhlib/stream/model/StreamSink_pkg.sim.08.vhd',
'dep work 2008 ' + DIR + '/complex/vhlib/stream/test/StreamArb/StreamArb_tv.sim.08.vhd',
'dep work 2008 ' + DIR + '/complex/vhlib/stream/Stream_pkg.vhd',
'dep work 2008 ' + DIR + '/complex/vhlib/sim/ClockGen_pkg.sim.08.vhd',
'dep work 2008 ' + DIR + '/complex/vhlib/stream/test/StreamArb/StreamArb_tb.sim.08.vhd',
'top work 2008 ' + DIR + '/complex/vhlib/stream/test/StreamArb/StreamArb_Fixed_tc.sim.08.vhd',
'top work 2008 ' + DIR + '/complex/vhlib/stream/test/StreamArb/StreamArb_RoundRobin_tc.sim.08.vhd',
'top work 2008 ' + DIR + '/complex/vhlib/stream/test/StreamArb/StreamArb_RRSticky_tc.sim.08.vhd',
'dep work 2008 ' + DIR + '/complex/vhlib/stream/StreamArb.vhd',
'dep work 2008 ' + DIR + '/complex/vhlib/stream/test/StreamBuffer/StreamBuffer_tv.sim.08.vhd',
'dep work 2008 ' + DIR + '/complex/vhlib/stream/test/StreamBuffer/StreamBuffer_tb.sim.08.vhd',
'top work 2008 ' + DIR + '/complex/vhlib/stream/test/StreamBuffer/StreamBuffer_0_tc.sim.08.vhd',
'top work 2008 ' + DIR + '/complex/vhlib/stream/test/StreamBuffer/StreamBuffer_200_tc.sim.08.vhd',
'top work 2008 ' + DIR + '/complex/vhlib/stream/test/StreamBuffer/StreamBuffer_2_tc.sim.08.vhd',
'top work 2008 ' + DIR + '/complex/vhlib/stream/test/StreamBuffer/StreamBuffer_4_tc.sim.08.vhd',
'top work 2008 ' + DIR + '/complex/vhlib/stream/test/StreamBuffer/StreamBuffer_6_tc.sim.08.vhd',
'dep work 2008 ' + DIR + '/complex/vhlib/util/UtilInt_pkg.vhd',
'dep work 2008 ' + DIR + '/complex/vhlib/stream/test/StreamElementCounter/StreamElementCounter_tv.sim.08.vhd',
'dep work 2008 ' + DIR + '/complex/vhlib/stream/test/StreamElementCounter/StreamElementCounter_tb.sim.08.vhd',
'top work 2008 ' + DIR + '/complex/vhlib/stream/test/StreamElementCounter/StreamElementCounter_16_5_32_9_tc.sim.08.vhd',
'top work 2008 ' + DIR + '/complex/vhlib/stream/test/StreamElementCounter/StreamElementCounter_8_3_63_6_tc.sim.08.vhd',
'dep work 2008 ' + DIR + '/complex/vhlib/stream/StreamElementCounter.vhd',
'dep work 2008 ' + DIR + '/complex/vhlib/stream/test/StreamFIFO/StreamFIFO_tv.sim.08.vhd',
'dep work 2008 ' + DIR + '/complex/vhlib/stream/test/StreamFIFO/StreamFIFO_tb.sim.08.vhd',
'top work 2008 ' + DIR + '/complex/vhlib/stream/test/StreamFIFO/StreamFIFO_Increase_tc.sim.08.vhd',
'top work 2008 ' + DIR + '/complex/vhlib/stream/test/StreamFIFO/StreamFIFO_Reduce_tc.sim.08.vhd',
'top work 2008 ' + DIR + '/complex/vhlib/stream/test/StreamFIFO/StreamFIFO_Same_tc.sim.08.vhd',
'dep work 2008 ' + DIR + '/complex/vhlib/stream/test/StreamGearbox/StreamGearbox_tv.sim.08.vhd',
'dep work 2008 ' + DIR + '/complex/vhlib/stream/test/StreamGearbox/StreamGearbox_tb.sim.08.vhd',
'top work 2008 ' + DIR + '/complex/vhlib/stream/test/StreamGearbox/StreamGearbox_2_2_8_3_tc.sim.08.vhd',
'top work 2008 ' + DIR + '/complex/vhlib/stream/test/StreamGearbox/StreamGearbox_32_5_16_4_tc.sim.08.vhd',
'top work 2008 ' + DIR + '/complex/vhlib/stream/test/StreamGearbox/StreamGearbox_5_4_3_2_tc.sim.08.vhd',
'top work 2008 ' + DIR + '/complex/vhlib/stream/test/StreamGearbox/StreamGearbox_8_4_8_3_tc.sim.08.vhd',
'dep work 2008 ' + DIR + '/complex/vhlib/stream/StreamGearbox.vhd',
'dep work 2008 ' + DIR + '/complex/vhlib/stream/StreamGearboxParallelizer.vhd',
'dep work 2008 ' + DIR + '/complex/vhlib/stream/StreamGearboxSerializer.vhd',
'dep work 2008 ' + DIR + '/complex/vhlib/stream/StreamNormalizer.vhd',
'dep work 2008 ' + DIR + '/complex/vhlib/stream/test/StreamNormalizer/StreamNormalizer_tb.sim.08.vhd',
'top work 2008 ' + DIR + '/complex/vhlib/stream/test/StreamNormalizer/StreamNormalizer_tc.sim.08.vhd',
'dep work 2008 ' + DIR + '/complex/vhlib/util/UtilMisc_pkg.vhd',
'dep work 2008 ' + DIR + '/complex/vhlib/stream/StreamPipelineBarrel.vhd',
'dep work 2008 ' + DIR + '/complex/vhlib/stream/test/StreamPipelineBarrel/StreamPipelineBarrel_tb.sim.08.vhd',
'top work 2008 ' + DIR + '/complex/vhlib/stream/test/StreamPipelineBarrel/StreamPipelineBarrel_tc.sim.08.vhd',
'dep work 2008 ' + DIR + '/complex/vhlib/stream/test/StreamPipelineControl/StreamPipelineControl_tv.sim.08.vhd',
'dep work 2008 ' + DIR + '/complex/vhlib/stream/test/StreamPipelineControl/StreamPipelineControl_tb.sim.08.vhd',
'top work 2008 ' + DIR + '/complex/vhlib/stream/test/StreamPipelineControl/StreamPipelineControl_20_3_t_tc.sim.08.vhd',
'top work 2008 ' + DIR + '/complex/vhlib/stream/test/StreamPipelineControl/StreamPipelineControl_5_1_f_tc.sim.08.vhd',
'dep work 2008 ' + DIR + '/complex/vhlib/stream/StreamPrefixSum.vhd',
'dep work 2008 ' + DIR + '/complex/vhlib/stream/test/StreamPrefixSum/StreamPrefixSum_tb.sim.08.vhd',
'top work 2008 ' + DIR + '/complex/vhlib/stream/test/StreamPrefixSum/StreamPrefixSum_tc.sim.08.vhd',
'dep work 2008 ' + DIR + '/complex/vhlib/stream/test/StreamPRNG/StreamPRNG_tv.sim.08.vhd',
'dep work 2008 ' + DIR + '/complex/vhlib/stream/test/StreamPRNG/StreamPRNG_tb.sim.08.vhd',
'top work 2008 ' + DIR + '/complex/vhlib/stream/test/StreamPRNG/StreamPRNG_12_tc.sim.08.vhd',
'top work 2008 ' + DIR + '/complex/vhlib/stream/test/StreamPRNG/StreamPRNG_8_tc.sim.08.vhd',
'dep work 2008 ' + DIR + '/complex/vhlib/stream/StreamPRNG.vhd',
'dep work 2008 ' + DIR + '/complex/vhlib/stream/test/StreamReshaper/StreamReshaperCtrl_tv.sim.08.vhd',
'dep work 2008 ' + DIR + '/complex/vhlib/stream/test/StreamReshaper/StreamReshaperCtrl_tb.sim.08.vhd',
'top work 2008 ' + DIR + '/complex/vhlib/stream/test/StreamReshaper/StreamReshaperCtrl_1_1_7_3_tc.sim.08.vhd',
'top work 2008 ' + DIR + '/complex/vhlib/stream/test/StreamReshaper/StreamReshaperCtrl_4_3_4_3_tc.sim.08.vhd',
'top work 2008 ' + DIR + '/complex/vhlib/stream/test/StreamReshaper/StreamReshaperCtrl_8_3_4_2_tc.sim.08.vhd',
'dep work 2008 ' + DIR + '/complex/vhlib/stream/test/StreamReshaper/StreamReshaperLast_tv.sim.08.vhd',
'dep work 2008 ' + DIR + '/complex/vhlib/stream/test/StreamReshaper/StreamReshaperLast_tb.sim.08.vhd',
'top work 2008 ' + DIR + '/complex/vhlib/stream/test/StreamReshaper/StreamReshaperLast_1_1_7_3_tc.sim.08.vhd',
'top work 2008 ' + DIR + '/complex/vhlib/stream/test/StreamReshaper/StreamReshaperLast_4_3_4_3_tc.sim.08.vhd',
'top work 2008 ' + DIR + '/complex/vhlib/stream/test/StreamReshaper/StreamReshaperLast_8_3_4_2_tc.sim.08.vhd',
'dep work 2008 ' + DIR + '/complex/vhlib/stream/StreamPipelineControl.vhd',
'dep work 2008 ' + DIR + '/complex/vhlib/stream/StreamFIFOCounter.vhd',
'dep work 2008 ' + DIR + '/complex/vhlib/util/UtilRam_pkg.vhd',
'dep work 2008 ' + DIR + '/complex/vhlib/stream/StreamFIFO.vhd',
'dep work 2008 ' + DIR + '/complex/vhlib/stream/StreamBuffer.vhd',
'dep work 2008 ' + DIR + '/complex/vhlib/stream/StreamReshaper.vhd',
'top work 2008 ' + DIR + '/complex/vhlib/stream/test/StreamSink/StreamSink_tc.sim.08.vhd',
'dep work 2008 ' + DIR + '/complex/vhlib/stream/StreamSlice.vhd',
'dep work 2008 ' + DIR + '/complex/vhlib/stream/test/StreamSlice/StreamSlice_tb.sim.08.vhd',
'top work 2008 ' + DIR + '/complex/vhlib/stream/test/StreamSlice/StreamSlice_tc.sim.08.vhd',
'top work 2008 ' + DIR + '/complex/vhlib/stream/test/StreamSource/StreamSource_tc.sim.08.vhd',
'dep work 2008 ' + DIR + '/complex/vhlib/stream/model/StreamSource_mdl.sim.08.vhd',
'dep work 2008 ' + DIR + '/complex/vhlib/stream/model/StreamMonitor_mdl.sim.08.vhd',
'dep work 2008 ' + DIR + '/complex/vhlib/stream/model/StreamSink_mdl.sim.08.vhd',
'dep work 2008 ' + DIR + '/complex/vhlib/stream/StreamSync.vhd',
'dep work 2008 ' + DIR + '/complex/vhlib/sim/ClockGen_mdl.sim.08.vhd',
'dep work 2008 ' + DIR + '/complex/vhlib/stream/test/StreamSync/StreamSync_tb.sim.08.vhd',
'top work 2008 ' + DIR + '/complex/vhlib/stream/test/StreamSync/StreamSync_tc.sim.08.vhd',
'dep work 2008 ' + DIR + '/complex/vhlib/util/UtilRam1R1W.vhd',
'dep work 2008 ' + DIR + '/complex/vhlib/util/UtilConv_pkg.vhd',
'dep work 2008 ' + DIR + '/complex/vhlib/util/UtilStr_pkg.vhd',
'dep work 2008 ' + DIR + '/complex/vhlib/util/UtilMem64_pkg.vhd',
]) + '\n')
def test_vhlib_93_desired(self):
"""Test the dependency analyzer with vhlib, preferring v93"""
#pylint: disable=C0301
self.maxDiff = None #pylint: disable=C0103
code, out, _ = run_vhdeps('dump', '-i', DIR + '/complex/vhlib', '-d', '93')
self.assertEqual(code, 0)
self.assertEqual(out, '\n'.join([
'dep work 2008 ' + DIR + '/complex/vhlib/sim/TestCase_pkg.sim.08.vhd',
'dep work 2008 ' + DIR + '/complex/vhlib/sim/SimDataComms_pkg.sim.08.vhd',
'top work 2008 ' + DIR + '/complex/vhlib/sim/SimDataComms_tc.sim.08.vhd',
'dep work 2008 ' + DIR + '/complex/vhlib/stream/model/StreamMonitor_pkg.sim.08.vhd',
'dep work 2008 ' + DIR + '/complex/vhlib/stream/model/StreamSource_pkg.sim.08.vhd',
'dep work 2008 ' + DIR + '/complex/vhlib/stream/model/StreamSink_pkg.sim.08.vhd',
'dep work 2008 ' + DIR + '/complex/vhlib/stream/test/StreamArb/StreamArb_tv.sim.08.vhd',
'dep work 1993 ' + DIR + '/complex/vhlib/stream/Stream_pkg.vhd',
'dep work 2008 ' + DIR + '/complex/vhlib/sim/ClockGen_pkg.sim.08.vhd',
'dep work 2008 ' + DIR + '/complex/vhlib/stream/test/StreamArb/StreamArb_tb.sim.08.vhd',
'top work 2008 ' + DIR + '/complex/vhlib/stream/test/StreamArb/StreamArb_Fixed_tc.sim.08.vhd',
'top work 2008 ' + DIR + '/complex/vhlib/stream/test/StreamArb/StreamArb_RoundRobin_tc.sim.08.vhd',
'top work 2008 ' + DIR + '/complex/vhlib/stream/test/StreamArb/StreamArb_RRSticky_tc.sim.08.vhd',
'dep work 1993 ' + DIR + '/complex/vhlib/stream/StreamArb.vhd',
'dep work 2008 ' + DIR + '/complex/vhlib/stream/test/StreamBuffer/StreamBuffer_tv.sim.08.vhd',
'dep work 2008 ' + DIR + '/complex/vhlib/stream/test/StreamBuffer/StreamBuffer_tb.sim.08.vhd',
'top work 2008 ' + DIR + '/complex/vhlib/stream/test/StreamBuffer/StreamBuffer_0_tc.sim.08.vhd',
'top work 2008 ' + DIR + '/complex/vhlib/stream/test/StreamBuffer/StreamBuffer_200_tc.sim.08.vhd',
'top work 2008 ' + DIR + '/complex/vhlib/stream/test/StreamBuffer/StreamBuffer_2_tc.sim.08.vhd',
'top work 2008 ' + DIR + '/complex/vhlib/stream/test/StreamBuffer/StreamBuffer_4_tc.sim.08.vhd',
'top work 2008 ' + DIR + '/complex/vhlib/stream/test/StreamBuffer/StreamBuffer_6_tc.sim.08.vhd',
'dep work 1993 ' + DIR + '/complex/vhlib/util/UtilInt_pkg.vhd',
'dep work 2008 ' + DIR + '/complex/vhlib/stream/test/StreamElementCounter/StreamElementCounter_tv.sim.08.vhd',
'dep work 2008 ' + DIR + '/complex/vhlib/stream/test/StreamElementCounter/StreamElementCounter_tb.sim.08.vhd',
'top work 2008 ' + DIR + '/complex/vhlib/stream/test/StreamElementCounter/StreamElementCounter_16_5_32_9_tc.sim.08.vhd',
'top work 2008 ' + DIR + '/complex/vhlib/stream/test/StreamElementCounter/StreamElementCounter_8_3_63_6_tc.sim.08.vhd',
'dep work 1993 ' + DIR + '/complex/vhlib/stream/StreamElementCounter.vhd',
'dep work 2008 ' + DIR + '/complex/vhlib/stream/test/StreamFIFO/StreamFIFO_tv.sim.08.vhd',
'dep work 2008 ' + DIR + '/complex/vhlib/stream/test/StreamFIFO/StreamFIFO_tb.sim.08.vhd',
'top work 2008 ' + DIR + '/complex/vhlib/stream/test/StreamFIFO/StreamFIFO_Increase_tc.sim.08.vhd',
'top work 2008 ' + DIR + '/complex/vhlib/stream/test/StreamFIFO/StreamFIFO_Reduce_tc.sim.08.vhd',
'top work 2008 ' + DIR + '/complex/vhlib/stream/test/StreamFIFO/StreamFIFO_Same_tc.sim.08.vhd',
'dep work 2008 ' + DIR + '/complex/vhlib/stream/test/StreamGearbox/StreamGearbox_tv.sim.08.vhd',
'dep work 2008 ' + DIR + '/complex/vhlib/stream/test/StreamGearbox/StreamGearbox_tb.sim.08.vhd',
'top work 2008 ' + DIR + '/complex/vhlib/stream/test/StreamGearbox/StreamGearbox_2_2_8_3_tc.sim.08.vhd',
'top work 2008 ' + DIR + '/complex/vhlib/stream/test/StreamGearbox/StreamGearbox_32_5_16_4_tc.sim.08.vhd',
'top work 2008 ' + DIR + '/complex/vhlib/stream/test/StreamGearbox/StreamGearbox_5_4_3_2_tc.sim.08.vhd',
'top work 2008 ' + DIR + '/complex/vhlib/stream/test/StreamGearbox/StreamGearbox_8_4_8_3_tc.sim.08.vhd',
'dep work 1993 ' + DIR + '/complex/vhlib/stream/StreamGearbox.vhd',
'dep work 1993 ' + DIR + '/complex/vhlib/stream/StreamGearboxParallelizer.vhd',
'dep work 1993 ' + DIR + '/complex/vhlib/stream/StreamGearboxSerializer.vhd',
'dep work 1993 ' + DIR + '/complex/vhlib/stream/StreamNormalizer.vhd',
'dep work 2008 ' + DIR + '/complex/vhlib/stream/test/StreamNormalizer/StreamNormalizer_tb.sim.08.vhd',
'top work 2008 ' + DIR + '/complex/vhlib/stream/test/StreamNormalizer/StreamNormalizer_tc.sim.08.vhd',
'dep work 1993 ' + DIR + '/complex/vhlib/util/UtilMisc_pkg.vhd',
'dep work 1993 ' + DIR + '/complex/vhlib/stream/StreamPipelineBarrel.vhd',
'dep work 2008 ' + DIR + '/complex/vhlib/stream/test/StreamPipelineBarrel/StreamPipelineBarrel_tb.sim.08.vhd',
'top work 2008 ' + DIR + '/complex/vhlib/stream/test/StreamPipelineBarrel/StreamPipelineBarrel_tc.sim.08.vhd',
'dep work 2008 ' + DIR + '/complex/vhlib/stream/test/StreamPipelineControl/StreamPipelineControl_tv.sim.08.vhd',
'dep work 2008 ' + DIR + '/complex/vhlib/stream/test/StreamPipelineControl/StreamPipelineControl_tb.sim.08.vhd',
'top work 2008 ' + DIR + '/complex/vhlib/stream/test/StreamPipelineControl/StreamPipelineControl_20_3_t_tc.sim.08.vhd',
'top work 2008 ' + DIR + '/complex/vhlib/stream/test/StreamPipelineControl/StreamPipelineControl_5_1_f_tc.sim.08.vhd',
'dep work 1993 ' + DIR + '/complex/vhlib/stream/StreamPrefixSum.vhd',
'dep work 2008 ' + DIR + '/complex/vhlib/stream/test/StreamPrefixSum/StreamPrefixSum_tb.sim.08.vhd',
'top work 2008 ' + DIR + '/complex/vhlib/stream/test/StreamPrefixSum/StreamPrefixSum_tc.sim.08.vhd',
'dep work 2008 ' + DIR + '/complex/vhlib/stream/test/StreamPRNG/StreamPRNG_tv.sim.08.vhd',
'dep work 2008 ' + DIR + '/complex/vhlib/stream/test/StreamPRNG/StreamPRNG_tb.sim.08.vhd',
'top work 2008 ' + DIR + '/complex/vhlib/stream/test/StreamPRNG/StreamPRNG_12_tc.sim.08.vhd',
'top work 2008 ' + DIR + '/complex/vhlib/stream/test/StreamPRNG/StreamPRNG_8_tc.sim.08.vhd',
'dep | |
f, m, x):
return (
-Dist(
b * c / (f * (m + S(1)) * (m + S(3))),
Int(
(f * x) ** (m + S(1))
* (d * (m + S(3)) + e * x ** S(2) * (m + S(1)))
/ (sqrt(c * x + S(-1)) * sqrt(c * x + S(1))),
x,
),
x,
)
+ Simp(d * (f * x) ** (m + S(1)) * (a + b * acosh(c * x)) / (f * (m + S(1))), x)
+ Simp(
e
* (f * x) ** (m + S(3))
* (a + b * acosh(c * x))
/ (f ** S(3) * (m + S(3))),
x,
)
)
def replacement6222(a, b, c, d, e, p, x):
return -Dist(
b * c / (S(2) * e * (p + S(1))),
Int((d + e * x ** S(2)) ** (p + S(1)) / sqrt(c ** S(2) * x ** S(2) + S(1)), x),
x,
) + Simp(
(a + b * asinh(c * x))
* (d + e * x ** S(2)) ** (p + S(1))
/ (S(2) * e * (p + S(1))),
x,
)
def replacement6223(a, b, c, d, e, p, x):
return -Dist(
b * c / (S(2) * e * (p + S(1))),
Int(
(d + e * x ** S(2)) ** (p + S(1))
/ (sqrt(c * x + S(-1)) * sqrt(c * x + S(1))),
x,
),
x,
) + Simp(
(a + b * acosh(c * x))
* (d + e * x ** S(2)) ** (p + S(1))
/ (S(2) * e * (p + S(1))),
x,
)
def With6224(a, b, c, d, e, f, m, p, x):
u = IntHide((f * x) ** m * (d + e * x ** S(2)) ** p, x)
return -Dist(
b * c, Int(SimplifyIntegrand(u / sqrt(c ** S(2) * x ** S(2) + S(1)), x), x), x
) + Dist(a + b * asinh(c * x), u, x)
def With6225(a, b, c, d, e, f, m, p, x):
u = IntHide((f * x) ** m * (d + e * x ** S(2)) ** p, x)
return -Dist(
b * c,
Int(SimplifyIntegrand(u / (sqrt(c * x + S(-1)) * sqrt(c * x + S(1))), x), x),
x,
) + Dist(a + b * acosh(c * x), u, x)
def replacement6226(a, b, c, d, e, f, m, n, p, x):
return Int(
ExpandIntegrand(
(a + b * asinh(c * x)) ** n, (f * x) ** m * (d + e * x ** S(2)) ** p, x
),
x,
)
def replacement6227(a, b, c, d, e, f, m, n, p, x):
return Int(
ExpandIntegrand(
(a + b * acosh(c * x)) ** n, (f * x) ** m * (d + e * x ** S(2)) ** p, x
),
x,
)
def replacement6228(a, b, c, d, e, f, m, n, p, x):
return Int((f * x) ** m * (a + b * asinh(c * x)) ** n * (d + e * x ** S(2)) ** p, x)
def replacement6229(a, b, c, d, e, f, m, n, p, x):
return Int((f * x) ** m * (a + b * acosh(c * x)) ** n * (d + e * x ** S(2)) ** p, x)
def replacement6230(a, b, c, d1, d2, e1, e2, f, m, n, p, x):
return Int(
(f * x) ** m
* (a + b * acosh(c * x)) ** n
* (d1 + e1 * x) ** p
* (d2 + e2 * x) ** p,
x,
)
def replacement6231(a, b, c, d, e, f, g, h, m, n, p, x):
return Dist(
(d + e * x) ** FracPart(p)
* (f + g * x) ** FracPart(p)
* (d * f + e * g * x ** S(2)) ** (-FracPart(p)),
Int(
(h * x) ** m
* (a + b * asinh(c * x)) ** n
* (d * f + e * g * x ** S(2)) ** p,
x,
),
x,
)
def replacement6232(a, b, c, d, e, f, m, n, p, x):
return Dist(
(-d) ** IntPart(p)
* (d + e * x ** S(2)) ** FracPart(p)
* (c * x + S(-1)) ** (-FracPart(p))
* (c * x + S(1)) ** (-FracPart(p)),
Int(
(f * x) ** m
* (a + b * acosh(c * x)) ** n
* (c * x + S(-1)) ** p
* (c * x + S(1)) ** p,
x,
),
x,
)
def replacement6233(a, b, c, d, e, n, x):
return Subst(
Int((a + b * x) ** n * cosh(x) / (c * d + e * sinh(x)), x), x, asinh(c * x)
)
def replacement6234(a, b, c, d, e, n, x):
return Subst(
Int((a + b * x) ** n * sinh(x) / (c * d + e * cosh(x)), x), x, acosh(c * x)
)
def replacement6235(a, b, c, d, e, m, n, x):
return -Dist(
b * c * n / (e * (m + S(1))),
Int(
(a + b * asinh(c * x)) ** (n + S(-1))
* (d + e * x) ** (m + S(1))
/ sqrt(c ** S(2) * x ** S(2) + S(1)),
x,
),
x,
) + Simp(
(a + b * asinh(c * x)) ** n * (d + e * x) ** (m + S(1)) / (e * (m + S(1))), x
)
def replacement6236(a, b, c, d, e, m, n, x):
return -Dist(
b * c * n / (e * (m + S(1))),
Int(
(a + b * acosh(c * x)) ** (n + S(-1))
* (d + e * x) ** (m + S(1))
/ (sqrt(c * x + S(-1)) * sqrt(c * x + S(1))),
x,
),
x,
) + Simp(
(a + b * acosh(c * x)) ** n * (d + e * x) ** (m + S(1)) / (e * (m + S(1))), x
)
def replacement6237(a, b, c, d, e, m, n, x):
return Int(ExpandIntegrand((a + b * asinh(c * x)) ** n * (d + e * x) ** m, x), x)
def replacement6238(a, b, c, d, e, m, n, x):
return Int(ExpandIntegrand((a + b * acosh(c * x)) ** n * (d + e * x) ** m, x), x)
def replacement6239(a, b, c, d, e, m, n, x):
return Dist(
c ** (-m + S(-1)),
Subst(
Int((a + b * x) ** n * (c * d + e * sinh(x)) ** m * cosh(x), x),
x,
asinh(c * x),
),
x,
)
def replacement6240(a, b, c, d, e, m, n, x):
return Dist(
c ** (-m + S(-1)),
Subst(
Int((a + b * x) ** n * (c * d + e * cosh(x)) ** m * sinh(x), x),
x,
acosh(c * x),
),
x,
)
def With6241(Px, a, b, c, x):
u = IntHide(Px, x)
return -Dist(
b * c, Int(SimplifyIntegrand(u / sqrt(c ** S(2) * x ** S(2) + S(1)), x), x), x
) + Dist(a + b * asinh(c * x), u, x)
def With6242(Px, a, b, c, x):
u = IntHide(Px, x)
return -Dist(
b
* c
* sqrt(-(c ** S(2)) * x ** S(2) + S(1))
/ (sqrt(c * x + S(-1)) * sqrt(c * x + S(1))),
Int(SimplifyIntegrand(u / sqrt(-(c ** S(2)) * x ** S(2) + S(1)), x), x),
x,
) + Dist(a + b * acosh(c * x), u, x)
def replacement6243(Px, a, b, c, n, x):
return Int(ExpandIntegrand(Px * (a + b * asinh(c * x)) ** n, x), x)
def replacement6244(Px, a, b, c, n, x):
return Int(ExpandIntegrand(Px * (a + b * acosh(c * x)) ** n, x), x)
def With6245(Px, a, b, c, d, e, m, x):
u = IntHide(Px * (d + e * x) ** m, | |
<reponame>jxtxinbing/ops-build
#!/usr/bin/env python
#
# BitBake Graphical GTK User Interface
#
# Copyright (C) 2012 Intel Corporation
#
# Authored by <NAME> <<EMAIL>>
# Authored by <NAME> <<EMAIL>>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License version 2 as
# published by the Free Software Foundation.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License along
# with this program; if not, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
import gobject
import gtk
from bb.ui.crumbs.hobcolor import HobColors
from bb.ui.crumbs.hobwidget import hic, HobViewTable, HobAltButton, HobButton
from bb.ui.crumbs.hobpages import HobPage
import subprocess
from bb.ui.crumbs.hig.crumbsdialog import CrumbsDialog
from bb.ui.crumbs.hig.saveimagedialog import SaveImageDialog
#
# ImageDetailsPage
#
class ImageDetailsPage (HobPage):
class DetailBox (gtk.EventBox):
def __init__(self, widget = None, varlist = None, vallist = None, icon = None, button = None, button2=None, color = HobColors.LIGHT_GRAY):
gtk.EventBox.__init__(self)
# set color
style = self.get_style().copy()
style.bg[gtk.STATE_NORMAL] = self.get_colormap().alloc_color(color, False, False)
self.set_style(style)
self.row = gtk.Table(1, 2, False)
self.row.set_border_width(10)
self.add(self.row)
total_rows = 0
if widget:
total_rows = 10
if varlist and vallist:
# pack the icon and the text on the left
total_rows += len(varlist)
self.table = gtk.Table(total_rows, 20, True)
self.table.set_row_spacings(6)
self.table.set_size_request(100, -1)
self.row.attach(self.table, 0, 1, 0, 1, xoptions=gtk.FILL|gtk.EXPAND, yoptions=gtk.FILL)
colid = 0
rowid = 0
self.line_widgets = {}
if icon:
self.table.attach(icon, colid, colid + 2, 0, 1)
colid = colid + 2
if widget:
self.table.attach(widget, colid, 20, 0, 10)
rowid = 10
if varlist and vallist:
for row in range(rowid, total_rows):
index = row - rowid
self.line_widgets[varlist[index]] = self.text2label(varlist[index], vallist[index])
self.table.attach(self.line_widgets[varlist[index]], colid, 20, row, row + 1)
# pack the button on the right
if button:
self.bbox = gtk.VBox()
self.bbox.pack_start(button, expand=True, fill=False)
if button2:
self.bbox.pack_start(button2, expand=True, fill=False)
self.bbox.set_size_request(150,-1)
self.row.attach(self.bbox, 1, 2, 0, 1, xoptions=gtk.FILL, yoptions=gtk.EXPAND)
def update_line_widgets(self, variable, value):
if len(self.line_widgets) == 0:
return
if not isinstance(self.line_widgets[variable], gtk.Label):
return
self.line_widgets[variable].set_markup(self.format_line(variable, value))
def wrap_line(self, inputs):
# wrap the long text of inputs
wrap_width_chars = 75
outputs = ""
tmps = inputs
less_chars = len(inputs)
while (less_chars - wrap_width_chars) > 0:
less_chars -= wrap_width_chars
outputs += tmps[:wrap_width_chars] + "\n "
tmps = inputs[less_chars:]
outputs += tmps
return outputs
def format_line(self, variable, value):
wraped_value = self.wrap_line(value)
markup = "<span weight=\'bold\'>%s</span>" % variable
markup += "<span weight=\'normal\' foreground=\'#1c1c1c\' font_desc=\'14px\'>%s</span>" % wraped_value
return markup
def text2label(self, variable, value):
# append the name:value to the left box
# such as "Name: hob-core-minimal-variant-2011-12-15-beagleboard"
label = gtk.Label()
label.set_alignment(0.0, 0.5)
label.set_markup(self.format_line(variable, value))
return label
class BuildDetailBox (gtk.EventBox):
def __init__(self, varlist = None, vallist = None, icon = None, color = HobColors.LIGHT_GRAY):
gtk.EventBox.__init__(self)
# set color
style = self.get_style().copy()
style.bg[gtk.STATE_NORMAL] = self.get_colormap().alloc_color(color, False, False)
self.set_style(style)
self.hbox = gtk.HBox()
self.hbox.set_border_width(10)
self.add(self.hbox)
total_rows = 0
if varlist and vallist:
# pack the icon and the text on the left
total_rows += len(varlist)
self.table = gtk.Table(total_rows, 20, True)
self.table.set_row_spacings(6)
self.table.set_size_request(100, -1)
self.hbox.pack_start(self.table, expand=True, fill=True, padding=15)
colid = 0
rowid = 0
self.line_widgets = {}
if icon:
self.table.attach(icon, colid, colid + 2, 0, 1)
colid = colid + 2
if varlist and vallist:
for row in range(rowid, total_rows):
index = row - rowid
self.line_widgets[varlist[index]] = self.text2label(varlist[index], vallist[index])
self.table.attach(self.line_widgets[varlist[index]], colid, 20, row, row + 1)
def update_line_widgets(self, variable, value):
if len(self.line_widgets) == 0:
return
if not isinstance(self.line_widgets[variable], gtk.Label):
return
self.line_widgets[variable].set_markup(self.format_line(variable, value))
def wrap_line(self, inputs):
# wrap the long text of inputs
wrap_width_chars = 75
outputs = ""
tmps = inputs
less_chars = len(inputs)
while (less_chars - wrap_width_chars) > 0:
less_chars -= wrap_width_chars
outputs += tmps[:wrap_width_chars] + "\n "
tmps = inputs[less_chars:]
outputs += tmps
return outputs
def format_line(self, variable, value):
wraped_value = self.wrap_line(value)
markup = "<span weight=\'bold\'>%s</span>" % variable
markup += "<span weight=\'normal\' foreground=\'#1c1c1c\' font_desc=\'14px\'>%s</span>" % wraped_value
return markup
def text2label(self, variable, value):
# append the name:value to the left box
# such as "Name: hob-core-minimal-variant-2011-12-15-beagleboard"
label = gtk.Label()
label.set_alignment(0.0, 0.5)
label.set_markup(self.format_line(variable, value))
return label
def __init__(self, builder):
super(ImageDetailsPage, self).__init__(builder, "Image details")
self.image_store = []
self.button_ids = {}
self.details_bottom_buttons = gtk.HBox(False, 6)
self.image_saved = False
self.create_visual_elements()
self.name_field_template = ""
self.description_field_template = ""
def create_visual_elements(self):
# create visual elements
# create the toolbar
self.toolbar = gtk.Toolbar()
self.toolbar.set_orientation(gtk.ORIENTATION_HORIZONTAL)
self.toolbar.set_style(gtk.TOOLBAR_BOTH)
my_images_button = self.append_toolbar_button(self.toolbar,
"Images",
hic.ICON_IMAGES_DISPLAY_FILE,
hic.ICON_IMAGES_HOVER_FILE,
"Open previously built images",
self.my_images_button_clicked_cb)
settings_button = self.append_toolbar_button(self.toolbar,
"Settings",
hic.ICON_SETTINGS_DISPLAY_FILE,
hic.ICON_SETTINGS_HOVER_FILE,
"View additional build settings",
self.settings_button_clicked_cb)
self.details_top_buttons = self.add_onto_top_bar(self.toolbar)
def _remove_all_widget(self):
children = self.get_children() or []
for child in children:
self.remove(child)
children = self.box_group_area.get_children() or []
for child in children:
self.box_group_area.remove(child)
children = self.details_bottom_buttons.get_children() or []
for child in children:
self.details_bottom_buttons.remove(child)
def show_page(self, step):
self.build_succeeded = (step == self.builder.IMAGE_GENERATED)
image_addr = self.builder.parameters.image_addr
image_names = self.builder.parameters.image_names
if self.build_succeeded:
machine = self.builder.configuration.curr_mach
base_image = self.builder.recipe_model.get_selected_image()
layers = self.builder.configuration.layers
pkg_num = "%s" % len(self.builder.package_model.get_selected_packages())
log_file = self.builder.current_logfile
else:
pkg_num = "N/A"
log_file = None
# remove
for button_id, button in self.button_ids.items():
button.disconnect(button_id)
self._remove_all_widget()
# repack
self.pack_start(self.details_top_buttons, expand=False, fill=False)
self.pack_start(self.group_align, expand=True, fill=True)
self.build_result = None
if self.image_saved or (self.build_succeeded and self.builder.current_step == self.builder.IMAGE_GENERATING):
# building is the previous step
icon = gtk.Image()
pixmap_path = hic.ICON_INDI_CONFIRM_FILE
color = HobColors.RUNNING
pix_buffer = gtk.gdk.pixbuf_new_from_file(pixmap_path)
icon.set_from_pixbuf(pix_buffer)
varlist = [""]
if self.image_saved:
vallist = ["Your image recipe has been saved"]
else:
vallist = ["Your image is ready"]
self.build_result = self.BuildDetailBox(varlist=varlist, vallist=vallist, icon=icon, color=color)
self.box_group_area.pack_start(self.build_result, expand=False, fill=False)
self.buttonlist = ["Build new image", "Save image recipe", "Run image", "Deploy image"]
# Name
self.image_store = []
self.toggled_image = ""
default_image_size = 0
self.num_toggled = 0
i = 0
for image_name in image_names:
image_size = HobPage._size_to_string(os.stat(os.path.join(image_addr, image_name)).st_size)
image_attr = ("run" if (self.test_type_runnable(image_name) and self.test_mach_runnable(image_name)) else \
("deploy" if self.test_deployable(image_name) else ""))
is_toggled = (image_attr != "")
if not self.toggled_image:
if i == (len(image_names) - 1):
is_toggled = True
if is_toggled:
default_image_size = image_size
self.toggled_image = image_name
split_stuff = image_name.split('.')
if "rootfs" in split_stuff:
image_type = image_name[(len(split_stuff[0]) + len(".rootfs") + 1):]
else:
image_type = image_name[(len(split_stuff[0]) + 1):]
self.image_store.append({'name': image_name,
'type': image_type,
'size': image_size,
'is_toggled': is_toggled,
'action_attr': image_attr,})
i = i + 1
self.num_toggled += is_toggled
is_runnable = self.create_bottom_buttons(self.buttonlist, self.toggled_image)
# Generated image files info
varlist = ["Name: ", "Files created: ", "Directory: "]
vallist = []
vallist.append(image_name.split('.')[0])
vallist.append(', '.join(fileitem['type'] for fileitem in self.image_store))
vallist.append(image_addr)
view_files_button = HobAltButton("View files")
view_files_button.connect("clicked", self.view_files_clicked_cb, image_addr)
view_files_button.set_tooltip_text("Open the directory containing the image files")
open_log_button = None
if log_file:
open_log_button = HobAltButton("Open log")
open_log_button.connect("clicked", self.open_log_clicked_cb, log_file)
open_log_button.set_tooltip_text("Open the build's log file")
self.image_detail = self.DetailBox(varlist=varlist, vallist=vallist, button=view_files_button, button2=open_log_button)
self.box_group_area.pack_start(self.image_detail, expand=False, fill=True)
# The default kernel box for the qemu images
self.sel_kernel = ""
self.kernel_detail = None
if 'qemu' in image_name:
self.sel_kernel = self.get_kernel_file_name()
# varlist = ["Kernel: "]
# vallist = []
# vallist.append(self.sel_kernel)
# change_kernel_button = HobAltButton("Change")
# change_kernel_button.connect("clicked", self.change_kernel_cb)
# change_kernel_button.set_tooltip_text("Change qemu kernel file")
# self.kernel_detail = self.DetailBox(varlist=varlist, vallist=vallist, button=change_kernel_button)
# self.box_group_area.pack_start(self.kernel_detail, expand=True, fill=True)
# Machine, Image recipe and Layers
layer_num_limit = 15
varlist = ["Machine: ", "Image recipe: ", "Layers: "]
vallist = []
self.setting_detail = None
if self.build_succeeded:
vallist.append(machine)
if self.builder.recipe_model.is_custom_image():
if self.builder.configuration.initial_selected_image == self.builder.recipe_model.__custom_image__:
base_image ="New image recipe"
else:
base_image = self.builder.configuration.initial_selected_image + " (edited)"
vallist.append(base_image)
i = 0
for layer in layers:
if i > layer_num_limit:
break
varlist.append(" - ")
i += 1
vallist.append("")
i = 0
for layer in layers:
if i > layer_num_limit:
break
elif i == layer_num_limit:
vallist.append("and more...")
else:
vallist.append(layer)
i += 1
edit_config_button = HobAltButton("Edit configuration")
edit_config_button.set_tooltip_text("Edit machine and image recipe")
edit_config_button.connect("clicked", self.edit_config_button_clicked_cb)
self.setting_detail = self.DetailBox(varlist=varlist, vallist=vallist, button=edit_config_button)
self.box_group_area.pack_start(self.setting_detail, expand=True, fill=True)
# Packages included, and Total image size
varlist = ["Packages included: ", "Total image size: "]
vallist = []
vallist.append(pkg_num)
vallist.append(default_image_size)
self.builder.configuration.image_size = default_image_size
self.builder.configuration.image_packages = self.builder.configuration.selected_packages
if self.build_succeeded:
edit_packages_button = HobAltButton("Edit packages")
edit_packages_button.set_tooltip_text("Edit the packages included in your image")
edit_packages_button.connect("clicked", self.edit_packages_button_clicked_cb)
else: # get to this page from "My images"
edit_packages_button = None
self.package_detail = self.DetailBox(varlist=varlist, vallist=vallist, button=edit_packages_button)
self.box_group_area.pack_start(self.package_detail, expand=True, fill=True)
# pack the buttons | |
60,
"BRITISH VIRGIN ISLANDS": 151,
"BRUNEI": 5765,
"BULGARIA": 110879,
"BURKINA FASO": 274200,
"MYANMAR": 676578,
"BURUNDI": 27830,
"<NAME>": 4033,
"CAMBODIA": 181035,
"CAMEROON": 475440,
"CANADA": 9984670,
"CAYMAN ISLANDS": 264,
"CENTRAL AFRICAN REPUBLIC": 622984,
"CHAD": 1284000,
"CHILE": 756102,
"CHINA": 9596960,
"CHRISTMAS ISLAND": 135,
"CLIPPERTON ISLAND": 6,
"COCOS (KEELING) ISLANDS": 14,
"COLOMBIA": 1138910,
"COMOROS": 2235,
"DEMOCRATIC REPUBLIC OF THE CONGO": 2344858,
"CONGO": 342000,
"COOK ISLANDS": 236,
"CORAL SEA ISLANDS": 3,
"COSTA RICA": 51100,
"CÔTE D'IVOIRE": 322463,
"CROATIA": 56594,
"CUBA": 110860,
"CURAÇAO": 444,
"CYPRUS": 9251,
"CZECH REPUBLIC": 78867,
"DENMARK": 43094,
"DHEKELIA": 131,
"DJIBOUTI": 23200,
"DOMINICA": 751,
"DOMINICAN REPUBLIC": 48670,
"ECUADOR": 283561,
"EGYPT": 1001450,
"EL SALVADOR": 21041,
"EQUATORIAL GUINEA": 28051,
"ERITREA": 117600,
"ESTONIA": 45228,
"ETHIOPIA": 1104300,
"FALKLAND ISLANDS (ISLAS MALVINAS)": 12173,
"FAROE ISLANDS": 1393,
"FIJI": 18274,
"FINLAND": 338145,
"FRANCE": 643801,
"FRENCH POLYNESIA": 4167,
"FRENCH SOUTHERN AND ANTARCTIC LANDS": 55,
"GABON": 267667,
"GAMBIA": 11300,
"GAZA STRIP": 360,
"GEORGIA": 69700,
"GERMANY": 357022,
"GHANA": 238533,
"GIBRALTAR": 7,
"GREECE": 131957,
"GREENLAND": 2166086,
"GRENADA": 344,
"GUAM": 544,
"GUATEMALA": 108889,
"GUERNSEY": 78,
"GUINEA": 245857,
"GUINEA-BISSAU": 28120, # 36125, https://en.wikipedia.org/wiki/Geography_of_Guinea-Bissau land area
"GUYANA": 214969,
"HAITI": 27750,
"HEARD ISLAND AND MCDONALD ISLANDS": 412,
"HOLY SEE": 0,
"HONDURAS": 112090,
"HONG KONG": 1108,
"HUNGARY": 93028,
"ICELAND": 103000,
"INDIA": 3287263,
"INDONESIA": 1904569,
"IRAN": 1648195,
"IRAQ": 438317,
"IRELAND": 70273,
"ISLE OF MAN": 572,
"ISRAEL": 20770,
"ITALY": 301340,
"JAMAICA": 10991,
"<NAME>": 377,
"JAPAN": 377915,
"JERSEY": 116,
"JORDAN": 89342,
"KAZAKHSTAN": 2724900,
"KENYA": 580367,
"KIRIBATI": 811,
"DEMOCRATIC PEOPLE'S REPUBLIC OF KOREA": 120538,
"REPUBLIC OF KOREA (SOUTH KOREA)": 99720,
"KOSOVO": 10887,
"KUWAIT": 17818,
"KYRGYZSTAN": 199951,
"LAO PEOPLE'S DEMOCRATIC REPUBLIC": 236800,
"LATVIA": 64589,
"LEBANON": 10400,
"LESOTHO": 30355,
"LIBERIA": 96320, # 111369, https://www.land-links.org/country-profile/liberia/
"LIBYA": 1759540,
"LIECHTENSTEIN": 160,
"LITHUANIA": 65300,
"LUXEMBOURG": 2586,
"MACAU": 28,
"THE FORMER YUGOSLAV REPUBLIC OF MACEDONIA": 25713,
"MADAGASCAR": 587041,
"MALAWI": 118484,
"MALAYSIA": 329847,
"MALDIVES": 298,
"MALI": 1240192,
"MALTA": 316,
"MARSHALL ISLANDS": 181,
"MAURITANIA": 1030700,
"MAURITIUS": 2040,
"MEXICO": 1964375,
"MICRONESIA (FEDERATED STATES OF)": 702,
"MOLDOVA": 33851,
"MONACO": 2,
"MONGOLIA": 1564116,
"MONTENEGRO": 13812,
"MONTSERRAT": 102,
"MOROCCO": 590000, # 446550, disputed territory w/ Western Sahara
"MOZAMBIQUE": 799380,
"NAMIBIA": 824292,
"NAURU": 21,
"NAVASSA ISLAND": 5,
"NEPAL": 147181,
"NETHERLANDS": 41543,
"NEW CALEDONIA": 18575,
"NEW ZEALAND": 268838,
"NICARAGUA": 130370,
"NIGER": 1267000,
"NIGERIA": 923768,
"NIUE": 260,
"NORFOLK ISLAND": 36,
"NORTHERN MARIANA ISLANDS": 464,
"NORWAY": 385203, # 323802, resolved Artic dispute added territory
"OMAN": 309500,
"PAKISTAN": 881913, # 796095, https://en.wikipedia.org/wiki/Pakistan
"PALAU": 459,
"PALESTINE": 6220,
"PANAMA": 75420,
"PAPUA NEW GUINEA": 462840,
"PARACEL ISLANDS": 8,
"PARAGUAY": 406752,
"PERU": 1285216,
"PHILIPPINES": 300000,
"PITCAIRN ISLANDS": 47,
"POLAND": 312685,
"PORTUGAL": 92090,
"<NAME>": 9104,
"QATAR": 11586,
"ROMANIA": 238391,
"RUSSIAN FEDERATION": 17098242,
"RWANDA": 26338,
"SAINT BARTHELEMY": 25,
"SAINT <NAME> AND <NAME>": 394,
"SAINT <NAME>": 261,
"<NAME>": 616,
"SAINT MARTIN": 54,
"SAINT <NAME>": 242,
"SAINT VINCENT AND THE GRENADINES": 389,
"SAMOA": 2831,
"<NAME>": 61,
"<NAME>": 964,
"<NAME>": 2149690,
"SENEGAL": 196722,
"SERBIA": 77474,
"SEYCHELLES": 455,
"<NAME>": 71740,
"SINGAPORE": 697,
"<NAME>": 34,
"SLOVAKIA": 49035,
"SLOVENIA": 20273,
"SOLOMON ISLANDS": 28896,
"SOMALIA": 637657,
"SOUTH AFRICA": 1219090,
"SOUTH GEORGIA AND SOUTH SANDWICH ISLANDS": 3903,
"SOUTH SUDAN": 644329,
"SPAIN": 505370,
"SPRATLY ISLANDS": 5,
"SRI LANKA": 65610,
"SUDAN": 1861484,
"SURINAME": 163820,
"SVALBARD": 62045,
"SWAZILAND": 17364,
"SWEDEN": 450295,
"SWITZERLAND": 41277,
"SYRIAN ARAB REPUBLIC": 185180,
"TAIWAN": 35980,
"TAJIKISTAN": 144100,
"UNITED REPUBLIC OF TANZANIA": 947300,
"THAILAND": 513120,
"TIMOR-LESTE": 14874,
"TOGO": 56785,
"TOKELAU": 12,
"TONGA": 747,
"TRINIDAD AND TOBAGO": 5128,
"TUNISIA": 163610,
"TURKEY": 783562,
"TURKMENISTAN": 488100,
"TURKS AND CAICOS ISLANDS": 948,
"TUVALU": 26,
"UGANDA": 241038,
"UKRAINE": 603550,
"UNITED ARAB EMIRATES": 77700, # 83600, disputed islands in Strait of Hormuz
"UNITED KINGDOM": 243610,
"UNITED STATES PACIFIC ISLAND WILDLIFE REFUGES": 22,
"UNITED STATES OF AMERICA": 9833517,
"URUGUAY": 176215,
"UZBEKISTAN": 447400,
"VANUATU": 12189,
"VENEZUELA": 912050,
"VIETNAM": 331210,
"VIRGIN ISLANDS": 1910,
"WAKE ISLAND": 7,
"WALLIS AND FUTUNA": 142,
"WEST BANK": 5860,
"WESTERN SAHARA": 90000, # 266000, disputed territory w/ Morocco
"YEMEN": 527968,
"ZAMBIA": 752618,
"ZIMBABWE": 390757,
}
gaez_land_areas = [
["Country", "GAEZ SubRegion", "Drawdown Region", "All Classes", "Irrigated Cultivated Land", "Rainfed Cultivated Land", "Forest Land", "Grassland", "Urban Land", "Barren Land", "Water"],
["Afghanistan", "Southern Asia", "Asia (Sans Japan)", 641721, 5.01, 7.58, 1.57, 34.87, 1.02, 49.93, 0.04 ],
["Albania", "Southern Europe", "Eastern Europe", 28429, 11.24, 18.92, 26.79, 37.66, 2.46, 0, 1.63 ],
["Algeria", "Northern Africa", "Middle East and Africa", 2321707, 0.24, 1.43, 0.91, 6.04, 0.36, 90.84, 0.11 ],
["Andorra", "Southern Europe", "OECD90", 475, 0.40, 1.33, 49.02, 46.41, 2.84, 0, 3.30 ],
["Angola", "Central Africa", "Middle East and Africa", 1254626, 0.05, 2.82, 46.94, 46.77, 0.46, 2.43, 0.05 ],
["Antigua and Barbuda", "Caribbean", "Latin America", 448, 0.17, 3.51, 25.39, 15.86, 1.97, 0, 15.37 ],
["Argentina", "South America", "Latin America", 2780530, 0.64, 9.72, 12.46, 63.33, 0.40, 11.60, 1.59 ],
["Armenia", "Central Asia", "Eastern Europe", 29596, 9.66, 8.65, 8.15, 67.51, 2.04, 0.23, 3.76 ],
["Australia", "Australia and New Zealand", "OECD90", 7709156, 0.26, 5.92, 11.59, 64.68, 0.15, 16.46, 0.28 ],
["Austria", "Western Europe", "OECD90", 83618, 1.18, 16.20, 46.63, 32.28, 2.75, 0.67, 0.30 ],
["Azerbaijan", "Central Asia", "Eastern Europe", 164692, 8.76, 4.36, 6.06, 29.83, 1.28, 1.44, 0.53 ],
["Bahamas", "Caribbean", "Latin America", 13376, 2.72, 1.51, 19.85, 24.16, 0.66, 7.06, 15.16 ],
["Bahrain", "Western Asia", "Middle East and Africa", 676, 1.87, 14.80, 0.00, 0.63, 20.23, 30.03, 13.29 ],
["Bangladesh", "Southern Asia", "Asia (Sans Japan)", 139322, 26.51, 33.87, 6.87, 6.37, 16.49, 1.53, 5.30 ],
["Barbados", "Caribbean", "Latin America", 444, 1.06, 14.80, 1.08, 17.18, 10.41, 0, 23.47 ],
["Belarus", "Eastern Europe", "Eastern Europe", 206293, 0.55, 29.72, 38.04, 29.92, 1.51, 0, 0.26 ],
["Belgium", "Western Europe", "OECD90", 30511, 1.32, 25.44, 22.10, 37.58, 12.81, 0.02, 0.02 ],
["Belize", "Central America", "Latin America", 22366, 0.20, 4.43, 59.37, 27.99, 0.33, 1.40, 2.59 ],
["Benin", "Gulf of Guinea", "Middle East and Africa", 116281, 0.11, 28.56, 23.05, 46.01, 1.72, 0, 0.39 ],
["Bhutan", "Southern Asia", "Asia (Sans Japan)", 37761, 0.94, 3.64, 77.98, 11.31, 1.67, 4.24, 0.21 ],
["Bolivia", "South America", "Latin America", 1089820, 0.12, 3.08, 50.45, 34.42, 0.29, 10.48, 1.16 ],
["Bosnia and Herzegovina", "Southern Europe", "Eastern Europe", 50998, 0.10, 21.54, 42.62, 33.59, 2.04, 0, 0.09 ],
["Botswana", "Southern Africa", "Middle East and Africa", 580280, 0.01, 0.77, 5.99, 86.77, 0.18, 6.27, 0.01 ],
["Brazil", "South America", "Latin America", 8532744, 0.36, 7.37, 57.71, 31.81, 0.59, 0.54, 1.44 ],
["Brunei", "South-eastern Asia", "Asia (Sans Japan)", 5902, 0.15, 3.45, 51.31, 35.90, 2.08, 0, 0.86 ],
["Bulgaria", "Eastern Europe", "Eastern Europe", 111018, 5.01, 29.38, 30.40, 32.25, 2.43, 0.00, 0.27 ],
["Burkina Faso", "Sudano-Sahelian Africa", "Middle East and Africa", 274973, 0.09, 18.23, 7.90, 71.58, 1.65, 0.40, 0.15 ],
["Burundi", "Eastern Africa", "Middle East and Africa", 27128, 0.77, 45.05, 8.01, 32.80, 5.53, 0, 7.85 ],
["Cambodia", "South-eastern Asia", "Asia (Sans Japan)", 182498, 1.72, 19.19, 50.95, 23.91, 2.07, 0.00, 1.79 ],
["Cameroon", "Gulf of Guinea", "Middle East and Africa", 469273, 0.05, 15.15, 51.06, 31.68, 1.10, 0.02, 0.61 ],
["Canada", "Northern America", "OECD90", 9806200, 0.08, 5.20, 31.47, 34.22, 0.13, 17.22, 9.22 ],
["Cape Verde", "Sudano-Sahelian Africa", "Middle East and Africa", 4076, 2.72, 14.80, 26.74, 31.46, 3.17, 0, 3.30 ],
["Central African Republic", "Central Africa", "Middle East and Africa", 624200, 0.00, 3.26, 38.48, 57.90, 0.33, 0, 0.04 ],
["Chad", "Sudano-Sahelian Africa", "Middle East and Africa", 1276646, 0.02, 6.55, 1.95, 34.22, 0.30, 56.77, 0.19 ],
["Chile", "South America", "Latin America", 753687, 2.51, 0.80, 19.99, 26.85, 0.53, 41.09, 4.23 ],
["China", "Eastern Asia", "Asia (Sans Japan)", 9378816, 5.75, 9.21, 18.33, 35.25, 2.81, 27.74, 0.65 ],
["Colombia", "South America", "Latin America", 1145383, 0.79, 6.05, 57.21, 34.00, 0.69, 0.28, 0.43 ],
["Comoros", "Eastern Africa", "Middle East and Africa", 1685, 0.03, 9.75, 29.87, 6.99, 2.11, 0.93, 9.71 ],
["Congo", "Central Africa", "Middle East and Africa", 343881, 0.01, 1.84, 68.30, 28.57, 0.40, 0, 0.76 ],
["Cook Islands", "Pacific Islands", None, 249, 2.72, 14.80, 26.74, 31.46, 3.17, 0, 3.30 ],
["Costa Rica", "Central America", "Latin America", 51539, 1.93, 11.23, 45.12, 35.09, 1.59, 0.10, 2.75 ],
["Croatia", "Southern Europe", "Eastern Europe", 56382, 0.11, 27.53, 37.08, 27.03, 2.09, 0.00, 2.24 ],
["Cuba", "Caribbean", "Latin America", 111826, 7.50, 25.98, 20.71, 32.57, 2.46, 0.73, 3.78 ],
["Cyprus", "Western Asia", "Eastern Europe", 9010, 4.28, 10.72, 17.64, 51.56, 1.99, 3.82, 3.71 ],
| |
<reponame>prise-3d/IPFML
"""
Functions which can be used to extract information from image or reduce it
"""
# main imports
import os
import random
import numpy as np
# image processing imports
from numpy.linalg import svd
from scipy import misc
from sklearn import preprocessing
from skimage import io, color
import cv2
from PIL import Image
# ipfml imports
from ipfml.processing import compression
def get_LAB(image):
"""Transforms RGB Image into Lab
Args:
image: image to convert
Returns:
Lab information
Usage:
>>> from PIL import Image
>>> from ipfml.processing import transform
>>> img = Image.open('./images/test_img.png')
>>> Lab = transform.get_LAB(img)
>>> Lab.shape
(200, 200, 3)
"""
return color.rgb2lab(image)
def get_LAB_L(image):
"""Transforms RGB Image into Lab and returns L
Args:
image: image to convert
Returns:
The L chanel from Lab information
>>> from PIL import Image
>>> from ipfml.processing import transform
>>> img = Image.open('./images/test_img.png')
>>> L = transform.get_LAB_L(img)
>>> L.shape
(200, 200)
"""
lab = get_LAB(image)
return lab[:, :, 0]
def get_LAB_a(image):
"""Transforms RGB Image into LAB and returns a
Args:
image: image to convert
Returns:
The a chanel from Lab information
Usage:
>>> from PIL import Image
>>> from ipfml.processing import transform
>>> img = Image.open('./images/test_img.png')
>>> a = transform.get_LAB_a(img)
>>> a.shape
(200, 200)
"""
lab = get_LAB(image)
return lab[:, :, 1]
def get_LAB_b(image):
"""Transforms RGB Image into LAB and returns b
Args:
image: image to convert
Returns:
The b chanel from Lab information
Usage :
>>> from PIL import Image
>>> from ipfml.processing import transform
>>> img = Image.open('./images/test_img.png')
>>> b = transform.get_LAB_b(img)
>>> b.shape
(200, 200)
"""
lab = get_LAB(image)
return lab[:, :, 2]
def get_XYZ(image):
"""Transforms RGB Image into XYZ
Args:
image: image to convert
Returns:
XYZ information obtained from transformation
Usage:
>>> from PIL import Image
>>> from ipfml.processing import transform
>>> img = Image.open('./images/test_img.png')
>>> transform.get_XYZ(img).shape
(200, 200, 3)
"""
return color.rgb2xyz(image)
def get_XYZ_X(image):
"""Transforms RGB Image into XYZ and returns X
Args:
image: image to convert
Returns:
The X chanel from XYZ information
Usage:
>>> from PIL import Image
>>> from ipfml.processing import transform
>>> img = Image.open('./images/test_img.png')
>>> x = transform.get_XYZ_X(img)
>>> x.shape
(200, 200)
"""
xyz = color.rgb2xyz(image)
return xyz[:, :, 0]
def get_XYZ_Y(image):
"""Transforms RGB Image into XYZ and returns Y
Args:
image: image to convert
Returns:
The Y chanel from XYZ information
Usage:
>>> from PIL import Image
>>> from ipfml.processing import transform
>>> img = Image.open('./images/test_img.png')
>>> y = transform.get_XYZ_Y(img)
>>> y.shape
(200, 200)
"""
xyz = color.rgb2xyz(image)
return xyz[:, :, 1]
def get_XYZ_Z(image):
"""Transforms RGB Image into XYZ and returns Z
Args:
image: image to convert
Returns:
The Z chanel from XYZ information
Raises:
ValueError: If `nb_bits` has unexpected value. `nb_bits` needs to be in interval [1, 8].
Usage:
>>> from PIL import Image
>>> from ipfml.processing import transform
>>> img = Image.open('./images/test_img.png')
>>> z = transform.get_XYZ_Z(img)
>>> z.shape
(200, 200)
"""
xyz = color.rgb2xyz(image)
return xyz[:, :, 2]
def get_low_bits_img(image, nb_bits=4):
"""Returns Image or Numpy array with data information reduced using only low bits
Args:
image: image to convert
nb_bits: optional parameter which indicates the number of bits to keep
Returns:
Numpy array with reduced values
Usage:
>>> from PIL import Image
>>> from ipfml.processing import transform
>>> img = Image.open('./images/test_img.png')
>>> low_bits_img = transform.get_low_bits_img(img, 5)
>>> low_bits_img.shape
(200, 200, 3)
"""
if nb_bits <= 0:
raise ValueError(
"unexpected value of number of bits to keep. @nb_bits needs to be positive and greater than 0."
)
if nb_bits > 8:
raise ValueError(
"Unexpected value of number of bits to keep. @nb_bits needs to be in interval [1, 8]."
)
img_arr = np.array(image)
bits_values = sum([pow(2, i - 1) for i in range(1, nb_bits + 1)])
return img_arr & bits_values
def get_bits_img(image, interval):
"""Returns only bits specified into the interval
Args:
image: image to convert using this interval of bits value to keep
interval: (begin, end) of bits values
Returns:
Numpy array with reduced values
Raises:
ValueError: If min value from interval is not >= 1.
ValueError: If max value from interval is not <= 8.
ValueError: If min value from interval >= max value.
Usage:
>>> from PIL import Image
>>> from ipfml.processing import transform
>>> img = Image.open('./images/test_img.png')
>>> bits_img = transform.get_bits_img(img, (2, 5))
>>> bits_img.shape
(200, 200, 3)
"""
img_arr = np.array(image)
begin, end = interval
if begin < 1:
raise ValueError(
"Unexpected value of interval. Interval min value needs to be >= 1."
)
if end > 8:
raise ValueError(
"Unexpected value of interval. Interval min value needs to be <= 8."
)
if begin >= end:
raise ValueError("Unexpected interval values order.")
bits_values = sum([pow(2, i - 1) for i in range(begin, end + 1)])
return img_arr & bits_values
def gray_to_mscn(image):
"""Convert Grayscale Image into Mean Subtracted Contrast Normalized (MSCN)
Args:
image: grayscale image
Returns:
MSCN matrix obtained from transformation
Usage:
>>> from PIL import Image
>>> from ipfml.processing import transform
>>> img = Image.open('./images/test_img.png')
>>> img = transform.get_LAB_L(img)
>>> img_mscn = transform.gray_to_mscn(img)
>>> img_mscn.shape
(200, 200)
"""
s = 7 / 6
blurred = cv2.GaussianBlur(image, (7, 7),
s) # apply gaussian blur to the image
blurred_sq = blurred * blurred
sigma = cv2.GaussianBlur(image * image, (7, 7), s)
sigma = abs(sigma - blurred_sq)**0.5
sigma = sigma + 1.0 / 255 # avoid DivideByZero Exception
mscn = (image - blurred) / sigma # MSCN(i, j) image
return mscn
def rgb_to_mscn(image):
"""Convert RGB Image into Mean Subtracted Contrast Normalized (MSCN)
Args:
image: 3D RGB image Numpy array or PIL RGB image
Returns:
2D Numpy array with MSCN information
Example:
>>> from PIL import Image
>>> from ipfml.processing import transform
>>> img = Image.open('./images/test_img.png')
>>> img_mscn = transform.rgb_to_mscn(img)
>>> img_mscn.shape
(200, 200)
"""
# check if PIL image or not
img_arr = np.array(image)
# convert rgb image to gray
im = np.array(color.rgb2gray(img_arr) * 255, 'uint8')
return gray_to_mscn(im)
def get_mscn_coefficients(image):
"""Compute the Mean Substracted Constrast Normalized coefficients of an image
Args:
image: PIL Image, Numpy array or path of image
Returns:
MSCN coefficients
Raises:
FileNotFoundError: If `image` is set as str path and image was not found
ValueError: If `image` numpy shape are not correct
Example:
>>> from PIL import Image
>>> import numpy as np
>>> from ipfml.processing import transform
>>> image_values = Image.open('./images/test_img.png')
>>> mscn_coefficients = transform.get_mscn_coefficients(image_values)
>>> mscn_coefficients.shape
(200, 200)
"""
if isinstance(image, str):
if os.path.exists(image):
# open image directly as grey level image
imdist = cv2.imread(image, 0)
else:
raise FileNotFoundError('Image not found in your system')
elif isinstance(image, np.ndarray):
# convert if necessary to grey level numpy array
if image.ndim == 2:
imdist = image
if image.ndim == 3:
imdist = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
else:
raise ValueError('Incorrect image shape')
else:
# if PIL Image
image = np.asarray(image)
if image.ndim == 2:
imdist = image
if image.ndim == 3:
imdist = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
else:
raise ValueError('Incorrect image shape')
imdist = imdist.astype(np.float64)
imdist = imdist / 255.0
# calculating MSCN coefficients
mu = cv2.GaussianBlur(imdist, (7, 7),
7 / 6,
borderType=cv2.BORDER_CONSTANT)
mu_sq = mu * mu
sigma = cv2.GaussianBlur(imdist * imdist, (7, 7),
7 / 6,
borderType=cv2.BORDER_CONSTANT)
sigma = np.sqrt(abs((sigma - mu_sq)))
structdis = (imdist - mu) / (sigma + 1)
return structdis
def get_LAB_L_SVD(image):
"""Returns Singular values from LAB L Image information
Args:
image: PIL Image or Numpy array
Returns:
U, s, V information obtained from SVD compression using Lab
Example:
>>> from PIL import Image
>>> from ipfml.processing import transform
>>> img = Image.open('./images/test_img.png')
>>> U, s, V = transform.get_LAB_L_SVD(img)
>>> U.shape
(200, 200)
>>> len(s)
200
>>> V.shape
(200, 200)
"""
L = get_LAB_L(image)
return compression.get_SVD(L)
def get_LAB_L_SVD_s(image):
"""Returns s (Singular values) SVD from L of LAB Image information
Args:
image: PIL Image or Numpy array
Returns:
vector of singular values
Example:
>>> from PIL import Image
>>> from ipfml.processing import transform
>>> img = Image.open('./images/test_img.png')
>>> s = transform.get_LAB_L_SVD_s(img)
>>> len(s)
200
"""
L = get_LAB_L(image)
return compression.get_SVD_s(L)
def get_LAB_L_SVD_U(image):
"""Returns U SVD from L of LAB Image information
Args:
image: PIL Image or Numpy array
Returns:
U matrix of | |
type: str
sample: string
cipher:
description: defines the cipher string or an existing cipher group
type: str
sample: DEFAULT or /Common/f5-default
enableTLS1_3:
description: enables or disables client-side TLSv1.3
type: bool
sample: True
cert:
description: defines the client-facing certificate. For forward proxy this is the template certificate. For reverse proxy this is the server certificate.
type: str
sample: /Common/default.crt
key:
description: defines the client-facing private key. For forward proxy this is the template key. For reverse proxy this is the server private key.
type: str
sample: /Common/default.key
chain:
description: defines the client-facing CA certificate chain. For reverse proxy this is the server certificate's CA chain.
type: str
sample: /Common/local-ca-chain.crt
caCert:
description: defines the issuing CA certificate for a forward proxy.
type: str
sample: /Common/default.crt
caKey:
description: defines the issuing CA private key for a forward proxy.
type: str
sample: /Common/default.key
caChain:
description: defines the CA certificate chain for the issuing CA in a forward proxy.
type: str
sample: /Common/local-ca-chain.crt
alpn:
description: requires 9.0+. Enables or disables ALPN HTTP/2 full proxy through a forward proxy topology.
type: bool
sample: True
logPublisher:
description: requires 9.0+. Defines a specific log publisher for client-side SSL-related events.
type: str
sample: /Common/sys-ssl-publisher
serverSettings:
description: network settings for for-service configuration
type: complex
contains:
cipherType:
description: defines "string" for cipher string, or "group" for cipher group
type: str
sample: string
cipher:
description: defines the cipher string or an existing cipher group
type: str
sample: DEFAULT or /Common/f5-default
enableTLS1_3:
description: enables or disables server-side TLSv1.3
type: bool
sample: True
caBundle:
description: defines a CA bundle used to valdate remote server certificates.
type: str
sample: /Common/ca-bundle.crt
blockExpired:
description: defines the action to take on receiving an expired remote server certificate, True = block, False = ignore.
type: bool
sample: True
blockUntrusted:
description: defines the action to take on receiving an untrusted remote server certificate, True = block, False = ignore.
type: bool
sample: True
ocsp:
description: defines aan existing OCSP configuration to validate revocation of remote server certificates.
type: str
sample: /Common/my-ocsp
crl:
description: defines aan existing CRL configuration to validate revocation of remote server certificates.
type: str
sample: /Common/my-crl
logPublisher:
description: requires 9.0+. Defines a specific log publisher for server-side SSL-related events.
type: str
sample: /Common/sys-ssl-publisher
bypassHandshakeFailure:
description:
- Defines the action to take on receiving a TLS handshake alert from a server. True = bypass decryption and allow through, False = block
type: bool
sample: True
bypassClientCertFailure:
description:
- Defines the action to take on receiving a TLS handshake client certificate request from a server. True = bypass decryption and allow through, False = block
type: bool
sample: True
mode:
description: describes the action to take on the task.
type: str
sample: update
state:
description:
- Changed state.
type: str
sample: present
'''
from datetime import datetime
from ansible.module_utils.basic import (
AnsibleModule, env_fallback
)
from ansible_collections.f5networks.f5_modules.plugins.module_utils.bigip import (
F5RestClient
)
from ansible_collections.f5networks.f5_modules.plugins.module_utils.common import (
F5ModuleError, AnsibleF5Parameters, transform_name, f5_argument_spec
)
from ansible_collections.f5networks.f5_modules.plugins.module_utils.icontrol import (
tmos_version
)
from ipaddress import (
ip_network, ip_interface
)
import json, time, re
global print_output
global json_template
global obj_attempts
global min_version
global max_version
print_output = []
## define object creation attempts count (with 1 seconds pause between each attempt)
obj_attempts = 20
## define minimum supported tmos version - min(SSLO 5.x)
min_version = 5.0
## define maximum supported tmos version - max(SSLO 8.x)
max_version = 9.0
json_template = {
"name":"f5-ssl-orchestrator-gc",
"inputProperties":[
{
"id":"f5-ssl-orchestrator-operation-context",
"type":"JSON",
"value":{
"operationType":"CREATE",
"deploymentType":"SSL_SETTINGS",
"deploymentName":"TEMPLATE_NAME",
"deploymentReference":"",
"partition":"Common",
"strictness":False
}
},
{
"id":"f5-ssl-orchestrator-tls",
"type":"JSON",
"value":{
"sslSettingsReference":"",
"sslSettingsName":"",
"description":"",
"previousVersion":"7.2",
"version":"7.2",
"generalSettings":{
"isForwardProxy":True,
"bypassHandshakeAlert":False,
"bypassClientCertFailure":False
},
"clientSettings":{
"ciphers":{
"isCipherString":True,
"cipherString":"DEFAULT",
"cipherGroup":"/Common/f5-default"
},
"certKeyChain":[
{
"cert":"/Common/default.crt",
"key":"/Common/default.key",
"chain":"",
"passphrase":"",
"name":"CERT_KEY_CHAIN_0"
}
],
"caCertKeyChain":[],
"forwardByPass":True,
"enabledSSLProcessingOptions":[]
},
"serverSettings":{
"ciphers":{
"isCipherString":True,
"cipherString":"DEFAULT",
"cipherGroup":"/Common/f5-default"
},
"caBundle":"/Common/ca-bundle.crt",
"expiredCertificates":False,
"untrustedCertificates":False,
"ocsp":"",
"crl":"",
"enabledSSLProcessingOptions":[]
},
"name":"TEMPLATE_NAME",
"advancedMode":"off",
"strictness":False,
"partition":"Common"
}
},
{
"id":"f5-ssl-orchestrator-topology",
"type":"JSON"
}
],
"configurationProcessorReference":{
"link":"https://localhost/mgmt/shared/iapp/processors/f5-iappslx-ssl-orchestrator-gc"
},
"configProcessorTimeoutSeconds": 120,
"statsProcessorTimeoutSeconds": 60,
"configProcessorAffinity": {
"processorPolicy": "LOCAL",
"affinityProcessorReference": {
"link": "https://localhost/mgmt/shared/iapp/affinity/local"
}
},
"state":"BINDING",
"presentationHtmlReference":{
"link":"https://localhost/iapps/f5-iappslx-ssl-orchestrator/sgc/sgcIndex.html"
},
"operation":"CREATE"
}
json_ca_cert_template = {
"cert":"/Common/default.crt",
"key":"/Common/defaut.key",
"chain":"",
"isCa":True,
"usage":"CA",
"port":"0",
"passphrase":"",
"certKeyChainMismatch":False,
"isDuplicateVal":False,
"name":"CA_CERT_KEY_CHAIN_0"
}
json_enable_tls13 = {
"name":"TLSv1.3",
"value":"TLSv1.3"
}
class Parameters(AnsibleF5Parameters):
api_map = {}
updatables = []
api_attributes = []
returnables = []
class ApiParameters(Parameters):
pass
class ModuleParameters(Parameters):
global print_output
@property
def name(self):
name = self._values['name']
name = "ssloT_" + name
return name
@property
def client_cipher_type(self):
try:
client_cipher_type = self._values['clientSettings']['cipherType']
if client_cipher_type is None:
return "string"
return client_cipher_type
except:
return "string"
@property
def client_cipher(self):
try:
client_cipher = self._values['clientSettings']['cipher']
if client_cipher is None:
return "DEFAULT"
return client_cipher
except:
return "DEFAULT"
@property
def client_enable_tls13(self):
try:
client_enable_tls13 = self._values['clientSettings']['enableTLS1_3']
if client_enable_tls13 is None:
return False
return client_enable_tls13
except:
return False
@property
def client_cert(self):
try:
client_cert = self._values['clientSettings']['cert']
if client_cert is None:
return "/Common/default.crt"
return client_cert
except:
return "/Common/default.crt"
@property
def client_key(self):
try:
client_key = self._values['clientSettings']['key']
if client_key is None:
return "/Common/default.key"
return client_key
except:
return "/Common/default.key"
@property
def client_chain(self):
try:
client_chain = self._values['clientSettings']['chain']
if client_chain is None:
return None
return client_chain
except:
return None
@property
def client_ca_cert(self):
try:
client_ca_cert = self._values['clientSettings']['caCert']
if client_ca_cert is None:
return None
return client_ca_cert
except:
return None
@property
def client_ca_key(self):
try:
client_ca_key = self._values['clientSettings']['caKey']
if client_ca_key is None:
return None
return client_ca_key
except:
return None
@property
def client_ca_chain(self):
try:
client_ca_chain = self._values['clientSettings']['caChain']
if client_ca_chain is None:
return None
return client_ca_chain
except:
return None
@property
def server_cipher_type(self):
try:
server_cipher_type = self._values['serverSettings']['cipherType']
if server_cipher_type is None:
return "string"
return server_cipher_type
except:
return "string"
@property
def server_cipher(self):
try:
server_cipher = self._values['serverSettings']['cipher']
if server_cipher is None:
return "DEFAULT"
return server_cipher
except:
return "DEFAULT"
@property
def server_enable_tls13(self):
try:
server_enable_tls13 = self._values['serverSettings']['enableTLS1_3']
if server_enable_tls13 is None:
return False
return server_enable_tls13
except:
return False
@property
def server_ca_bundle(self):
try:
server_ca_bundle = self._values['serverSettings']['caBundle']
if server_ca_bundle is None:
return "/Common/ca-bundle.crt"
return server_ca_bundle
except:
return "/Common/ca-bundle.crt"
@property
def server_block_expired(self):
try:
server_block_expired = self._values['serverSettings']['blockExpired']
if server_block_expired is None:
return None
return server_block_expired
except:
return None
@property
def server_block_untrusted(self):
try:
server_block_untrusted = self._values['serverSettings']['blockUntrusted']
if server_block_untrusted is None:
return None
return server_block_untrusted
except:
return None
@property
def server_ocsp(self):
try:
server_ocsp = self._values['serverSettings']['ocsp']
if server_ocsp is None:
return None
return server_ocsp
except:
return None
@property
def server_crl(self):
try:
server_crl = self._values['serverSettings']['crl']
if server_crl is None:
return None
return server_crl
except:
return None
@property
def bypass_handshake_failure(self):
bypass_handshake_failure = self._values['bypassHandshakeFailure']
if bypass_handshake_failure is None:
return False
return bypass_handshake_failure
@property
def bypass_clientcert_failure(self):
bypass_clientcert_failure = self._values['bypassClientCertFailure']
if bypass_clientcert_failure is None:
return False
return bypass_clientcert_failure
@property
def mode(self):
mode = self._values['mode']
return mode
@property
def client_alpn(self):
try:
client_alpn = self._values['clientSettings']['alpn']
if client_alpn is None:
return False
return client_alpn
except:
return False
@property
def client_log_publisher(self):
try:
client_log_publisher = self._values['clientSettings']['logPublisher']
if client_log_publisher is None:
return "/Common/sys-ssl-publisher"
return client_log_publisher
except:
return "/Common/sys-ssl-publisher"
@property
def server_log_publisher(self):
try:
server_log_publisher = self._values['clientSettings']['logPublisher']
if server_log_publisher is None:
return "/Common/sys-ssl-publisher"
return server_log_publisher
except:
return "/Common/sys-ssl-publisher"
class ModuleManager(object):
global print_output
global json_template
global obj_attempts
global min_version
global max_version
def __init__(self, *args, **kwargs):
self.module = kwargs.pop('module', None)
self.client = F5RestClient(**self.module.params)
self.want = ModuleParameters(params=self.module.params)
def getSsloVersion(self):
## use this method to get the SSLO version (first two digits (x.y))
uri = "https://{0}:{1}/mgmt/shared/iapp/installed-packages".format(
self.client.provider['server'],
self.client.provider['server_port']
)
try:
resp = self.client.api.get(uri).json()
for x in resp["items"]:
if x["appName"] == "f5-iappslx-ssl-orchestrator":
tmpversion = x["release"].split(".")
version = tmpversion[0] + "." + tmpversion[1]
return float(version)
break
except:
raise F5ModuleError("SSL Orchestrator package does not appear to be installed. Aborting.")
def deleteOperation(self, id):
## use this method to delete an operation that failed
uri = "https://{0}:{1}/mgmt/shared/iapp/blocks/{2}".format(
self.client.provider['server'],
self.client.provider['server_port'],
id
)
resp = self.client.api.delete(uri)
try:
response = resp.json()
except ValueError as ex:
raise F5ModuleError(str(ex))
if resp.status in [200, 201] or 'code' in response and response['code'] in [200, 201]:
return True
else:
return False
def update_json(self, operation):
## use this to method to create and return a modified copy of the JSON template
self.config = json_template
## get base name
self.local_name = re.sub('ssloT_', '', self.want.name)
## perform some input validation
## if TLS1.3 is enabled, the isCipherString value must be "false"
if self.want.client_enable_tls13 == True and self.want.client_cipher_type == "string":
raise F5ModuleError("Enabling client-side TLS 1.3 also requires a cipher group")
if self.want.server_enable_tls13 == True and self.want.server_cipher_type == "string":
raise F5ModuleError("Enabling server-side TLS | |
<filename>src/Sounder.py
import os
import time
import threading
import tkinter.messagebox
import json
from mutagen.mp3 import MP3
from pygame import mixer
from tkinter import *
from tkinter import ttk
from tkinter.filedialog import askdirectory
# dir
sounderdir = os.getcwd()
# sounderdir = os.path.dirname(sys.executable)
userdir = os.path.expanduser('~')
# end
PlayerForm = Tk()
PlayerForm.geometry('800x500')
PlayerForm.title("Sounder!")
PlayerForm.resizable(width=FALSE, height=FALSE)
PlayerForm.iconbitmap(sounderdir + "\\Soundericon.ico")
s = ttk.Style()
s.theme_use('clam')
# variables
PlayLabelText = StringVar()
DirectoryLabelText = StringVar()
GenreLabelText = StringVar()
BitrateLabelText = StringVar()
VolumeValue = StringVar()
YearLabelText = StringVar()
TimeLabelText = StringVar()
SampleLabelText = StringVar()
NowYear = StringVar()
Avtime = StringVar()
TSongs = StringVar()
TVol = StringVar()
ETimeVar = StringVar()
maxsong = 0
playbuttonstate = 0
mode = 0
themeset = "Light"
infoframe = None
threads = 0
totallength = 0.0
directory = ""
version = "2.8.2"
settings = {}
# end
# images
PlayPhotoimg = PhotoImage(file=sounderdir + "\\musicicon.png")
Playimg = PhotoImage(file=sounderdir + "\\play.png")
Pauseimg = PhotoImage(file=sounderdir + "\\pause.png")
Forwardimg = PhotoImage(file=sounderdir + "\\forward.png")
Previousimg = PhotoImage(file=sounderdir + "\\previous.png")
Fileimg = PhotoImage(file=sounderdir + "\\file-directory.png")
RefreshLabelimg = PhotoImage(file=sounderdir + "\\refresh.png")
RepeatNone = PhotoImage(file=sounderdir + "\\repeatnone.png")
RepeatAll = PhotoImage(file=sounderdir + "\\repeatall.png")
RepeatOne = PhotoImage(file=sounderdir + "\\repeatone.png")
Info = PhotoImage(file=sounderdir + "\\info.png")
InfoMusic = PhotoImage(file=sounderdir + "\\musicinfo.png")
Copyright = PhotoImage(file=sounderdir + "\\copyright.png")
Fork = PhotoImage(file=sounderdir + "\\fork.png")
Theme = PhotoImage(file=sounderdir + "\\theme.png")
PlayPhotoimgD = PhotoImage(file=sounderdir + "\\musicicond.png")
PlayimgD = PhotoImage(file=sounderdir + "\\playd.png")
PauseimgD = PhotoImage(file=sounderdir + "\\paused.png")
ForwardimgD = PhotoImage(file=sounderdir + "\\forwardd.png")
PreviousimgD = PhotoImage(file=sounderdir + "\\previousd.png")
FileimgD = PhotoImage(file=sounderdir + "\\file-directoryd.png")
RefreshLabelimgD = PhotoImage(file=sounderdir + "\\refreshd.png")
RepeatNoneD = PhotoImage(file=sounderdir + "\\repeatnoned.png")
RepeatAllD = PhotoImage(file=sounderdir + "\\repeatalld.png")
RepeatOneD = PhotoImage(file=sounderdir + "\\repeatoned.png")
InfoD = PhotoImage(file=sounderdir + "\\infod.png")
InfoMusicD = PhotoImage(file=sounderdir + "\\musicinfod.png")
CopyrightD = PhotoImage(file=sounderdir + "\\copyrightd.png")
ForkD = PhotoImage(file=sounderdir + "\\forkd.png")
ThemeD = PhotoImage(file=sounderdir + "\\themed.png")
# end
# year
NowYear.set("Copyright 2018-{}".format(time.strftime("%Y")))
# end
def musicscan():
global directory, maxsong, listofsongs, state, songnumber
directory = directory.rstrip('\n')
state = 0
songnumber = 0
maxsong = -1
listofsongs = []
try:
os.chdir(directory)
for file in os.listdir(directory):
if file.endswith(".mp3"):
maxsong += 1
state = 1
listofsongs.append(file)
except:
os.chdir(sounderdir)
os.remove('cfg.json')
firststart()
def firststart():
global directory, themeset, settings
if os.path.exists('cfg.json'):
with open('cfg.json', 'r') as file:
try:
settings = json.load(file)
except:
settings["theme"] = "Light"
try:
directory = settings["directory"]
except:
directory = askdirectory()
settings["directory"] = directory
try:
themeset = settings["theme"]
themechange()
themechange()
except:
settings["theme"] = "Light"
themeset = "Light"
themechange()
themechange()
with open('cfg.json', 'w') as file:
json.dump(settings, file)
mixer.pre_init(frequency=44100, size=-16, channels=2, buffer=4096)
mixer.init()
musicscan()
elif not os.path.exists('cfg.json'):
settings["theme"] = "Light"
themechange()
themechange()
directory = askdirectory()
settings["directory"] = directory
with open('cfg.json', 'w') as file:
json.dump(settings, file)
mixer.pre_init(frequency=44100, size=-16, channels=2, buffer=4096)
mixer.init()
musicscan()
def changedirectory():
global directory, sounderdir, state, settings
newdirectory = askdirectory()
if directory != newdirectory and newdirectory != "" or None:
os.chdir(sounderdir)
settings["directory"] = directory
with open('cfg.json', 'w') as file:
json.dump(settings, file)
MusicListBox.delete(0, END)
directory = newdirectory
DirectoryLabelText.set(directory)
musicscan()
update(state)
def update(cstate):
global listofsongs, maxsong, songnumber
try:
if cstate == 1:
if maxsong == 0:
TSongs.set("Song: {}".format(maxsong + 1))
elif maxsong > 0:
TSongs.set("Songs: {}".format(maxsong + 1))
listofsongs.reverse()
for file in listofsongs:
file = file.rstrip('.mp3')
MusicListBox.insert(0, file)
listofsongs.reverse()
if mixer.music.get_busy():
MusicListBox.selection_clear(0, END)
MusicListBox.select_set(songnumber)
elif cstate == 0:
MusicListBox.delete(0, END)
maxsong = -1
listofsongs = []
TSongs.set("Songs: 0")
ETimeVar.set("0:00")
except:
pass
def refreshdirectory():
global directory, maxsong, listofsongs, state
state = 0
maxsong = -1
listofsongs = []
MusicListBox.delete(0, END)
for file in os.listdir(directory):
if file.endswith(".mp3"):
maxsong += 1
state = 1
listofsongs.append(file)
update(state)
time.sleep(0.2)
def playsong():
global playbuttonstate, songnumber, listofsongs, state, themeset
if state == 1:
if playbuttonstate == 1:
mixer.music.pause()
if themeset == "Light":
PlayButton.configure(image=Playimg)
elif themeset == "Dark":
PlayButton.configure(image=PlayimgD)
playbuttonstate = 0
elif playbuttonstate == 0:
if mixer.music.get_busy():
mixer.music.unpause()
if themeset == "Light":
PlayButton.configure(image=Pauseimg)
elif themeset == "Dark":
PlayButton.configure(image=PauseimgD)
playbuttonstate = 1
else:
mixer.music.load(listofsongs[songnumber])
if len(listofsongs[songnumber]) > 60:
PlayLabelText.set(listofsongs[songnumber][0:60])
else:
PlayLabelText.set(str(listofsongs[songnumber]).rstrip('.mp3'))
mixer.music.play()
if themeset == "Light":
PlayButton.configure(image=Pauseimg)
elif themeset == "Dark":
PlayButton.configure(image=PauseimgD)
playbuttonstate = 1
preapir()
elif state == 0:
if playbuttonstate == 1:
mixer.music.stop()
PlayLabelText.set("")
ETimeVar.set("0:00")
if themeset == "Light":
PlayButton.configure(image=Playimg)
elif themeset == "Dark":
PlayButton.configure(image=PlayimgD)
playbuttonstate = 0
def nextsong():
global playbuttonstate, songnumber, state, maxsong, themeset
if state == 1:
if playbuttonstate == 1:
if songnumber < maxsong:
mixer.music.stop()
if themeset == "Light":
PlayButton.configure(image=Pauseimg)
elif themeset == "Dark":
PlayButton.configure(image=PauseimgD)
playbuttonstate = 1
songnumber += 1
mixer.music.load(listofsongs[songnumber])
mixer.music.play()
if len(listofsongs[songnumber]) > 60:
PlayLabelText.set(listofsongs[songnumber][0:60])
else:
PlayLabelText.set(str(listofsongs[songnumber]).rstrip('.mp3'))
preapir()
if playbuttonstate == 0:
if songnumber < maxsong:
mixer.music.stop()
playbuttonstate = 1
if themeset == "Light":
PlayButton.configure(image=Pauseimg)
elif themeset == "Dark":
PlayButton.configure(image=PauseimgD)
songnumber += 1
mixer.music.load(listofsongs[songnumber])
mixer.music.play()
if len(listofsongs[songnumber]) > 60:
PlayLabelText.set(listofsongs[songnumber][0:60])
else:
PlayLabelText.set(str(listofsongs[songnumber]).rstrip('.mp3'))
preapir()
def previoussong():
global playbuttonstate, songnumber, state, themeset
if state == 1:
if playbuttonstate == 1:
if songnumber > 0:
mixer.music.stop()
if themeset == "Light":
PlayButton.configure(image=Pauseimg)
elif themeset == "Dark":
PlayButton.configure(image=PauseimgD)
songnumber -= 1
mixer.music.load(listofsongs[songnumber])
mixer.music.play()
if len(listofsongs[songnumber]) > 50:
PlayLabelText.set(listofsongs[songnumber][0:50])
else:
PlayLabelText.set(str(listofsongs[songnumber]).rstrip('.mp3'))
preapir()
if playbuttonstate == 0:
if songnumber > 0:
mixer.music.stop()
playbuttonstate = 1
if themeset == "Light":
PlayButton.configure(image=Pauseimg)
elif themeset == "Dark":
PlayButton.configure(image=PauseimgD)
songnumber -= 1
mixer.music.load(listofsongs[songnumber])
mixer.music.play()
if len(listofsongs[songnumber]) > 50:
PlayLabelText.set(listofsongs[songnumber][0:50])
else:
PlayLabelText.set(str(listofsongs[songnumber]).rstrip('.mp3'))
preapir()
def musiclistboxpointer(e):
global selected, curent, state, songnumber, playbuttonstate, listofsongs, themeset
if state == 1:
selected = MusicListBox.curselection()
if selected != ():
mixer.music.stop()
for Song in selected:
curent = MusicListBox.get(Song)
for nr, Song in enumerate(listofsongs):
if Song.rstrip('.mp3') == curent:
mixer.music.load(listofsongs[nr])
songnumber = nr
mixer.music.play()
if playbuttonstate == 0:
playbuttonstate = 1
if themeset == "Light":
PlayButton.configure(image=Pauseimg)
elif themeset == "Dark":
PlayButton.configure(image=PauseimgD)
if len(listofsongs[songnumber]) > 50:
PlayLabelText.set(listofsongs[songnumber][0:50].rstrip('.mp3'))
else:
PlayLabelText.set(str(listofsongs[songnumber]).rstrip('.mp3'))
preapir()
def volume(value):
value = float(value)
value = value / 100
if value == 0.99:
TVol.set("Volume: 100%")
else:
TVol.set("Volume: {}%".format(int(value * 100)))
mixer.music.set_volume(value)
def preapir():
global listofsongs, songnumber, playbuttonstate, totallength
MusicListBox.selection_clear(0, END)
MusicListBox.select_set(songnumber)
file = MP3(listofsongs[songnumber])
bitratevar = int(file.info.bitrate / 1000)
samplerate = file.info.sample_rate
BitrateLabelText.set("Bitrate: " + str(bitratevar) + "kbps")
SampleLabelText.set("Sample Rate: " + str(samplerate) + "kHz")
try:
fileinfo = file.tags['TCON']
if len(str(fileinfo)) > 13:
GenreLabelText.set("Genre: " + str(fileinfo)[0:15])
else:
GenreLabelText.set("Genre: " + str(fileinfo))
except:
GenreLabelText.set("Genre: Unknown")
try:
fileyear = file.tags['TDRC']
YearLabelText.set("Year: " + str(fileyear))
except:
YearLabelText.set("Year: Unknown")
mins, secs = divmod(file.info.length, 60)
mins = int(mins)
secs = int(secs)
TimeLabelText.set("Time: " + str(mins) + ":" + str(secs).zfill(2))
totallength = round(file.info.length, 1)
MusicProgressBar["value"] = 0
MusicProgressBar["maximum"] = totallength
if playbuttonstate == 0:
PlayButton.configure(image=Pauseimg)
if not threads > 0:
music_progress = threading.Thread(target=progressbarfill,)
music_progress.daemon = True
music_progress.start()
def progressbarfill():
global playbuttonstate, themeset, threads, totallength
wait = False
threads += 1
activtime = 0
while mixer.music.get_busy() == 1 and activtime <= totallength - 0.11:
# time smoothing
if playbuttonstate == 1 and wait:
time.sleep(0.15)
wait = False
elif playbuttonstate == 1 and not wait:
activtime = mixer.music.get_pos() / 1000
MusicProgressBar["value"] = activtime
emin, esec = divmod(activtime, 60)
ETimeVar.set(str(int(emin)) + ":" + str(int(esec)).zfill(2))
elif playbuttonstate == 0 and not wait:
wait = True
# end
time.sleep(0.2)
threads -= 1
if activtime >= totallength - 0.5:
mixer.music.stop()
if themeset == "Light":
PlayButton.configure(image=Playimg)
elif themeset == "Dark":
PlayButton.configure(image=PlayimgD)
playbuttonstate = 0
playmode()
def playmode():
global mode, songnumber, maxsong, state
if state == 1:
time.sleep(0.5)
if mode == 0:
if songnumber < maxsong:
nextsong()
elif mode == 1:
if songnumber < maxsong:
nextsong()
elif songnumber == maxsong:
songnumber = 0
playsong()
elif mode == 2:
playsong()
def switchmode():
global mode, themeset
if mode == 0:
mode = 1
if themeset == "Light":
ModeButton.configure(image=RepeatAll)
elif themeset == "Dark":
ModeButton.configure(image=RepeatAllD)
elif mode == 1:
mode = 2
if themeset == "Light":
ModeButton.configure(image=RepeatOne)
elif themeset == "Dark":
ModeButton.configure(image=RepeatOneD)
else:
mode = 0
if themeset == "Light":
ModeButton.configure(image=RepeatNone)
elif themeset == "Dark":
ModeButton.configure(image=RepeatNoneD)
def close():
global themeset, playbuttonstate, settings, directory, version
if playbuttonstate == 1:
check = tkinter.messagebox.askquestion('Sounder!', 'Are you sure you want to quit?')
if check == 'yes':
os.chdir(sounderdir)
settings["theme"] = themeset
settings["directory"] = directory
settings["version"] = version
with open('cfg.json', 'w') as file:
json.dump(settings, file)
mixer.music.stop()
PlayerForm.destroy()
else:
pass
else:
os.chdir(sounderdir)
settings["theme"] = themeset
settings["directory"] = directory
settings["version"] = version
with open('cfg.json', 'w') as file:
json.dump(settings, file)
mixer.music.stop()
PlayerForm.destroy()
def info():
global themeset, infoframe, version
infoframe = Toplevel(PlayerForm)
infoframe.geometry("300x220")
infoframe.resizable(width=False, height=False)
infoframe.title("Sounder Info")
infoframe.iconbitmap(sounderdir + "\\Soundericon.ico")
infoframe.grab_set()
verlabel = ttk.Label(infoframe, text="Version {}".format(version), font='Bahnschrift 11', style="W.TLabel")
authorlabel = ttk.Label(infoframe, text="By: <NAME>", font='Bahnschrift 11', style="W.TLabel")
musiclabel = ttk.Label(infoframe, image=InfoMusic, style="W.TLabel")
copylabel = ttk.Label(infoframe, image=Copyright, style="W.TLabel")
infolabel = ttk.Label(infoframe, textvariable=NowYear, font='Bahnschrift 11', style="W.TLabel")
atlabel = ttk.Label(infoframe, textvariable=Avtime, font='Bahnschrift 11', style="W.TLabel")
themebutton = ttk.Button(infoframe, image=Theme, cursor="hand2", takefocus=0, command=themechange)
forknutton = ttk.Button(infoframe, image=Fork, cursor="hand2", takefocus=0, command=lambda: os.system("start \"\" "
"https"
"://github"
".com/losek1"
"/Sounder"))
if themeset == "Dark":
infoframe.configure(background='#000')
musiclabel.configure(image=InfoMusicD)
copylabel.configure(image=CopyrightD)
themebutton.configure(image=ThemeD)
forknutton.configure(image=ForkD)
elif themeset == "Light":
infoframe.configure(background='#fff')
musiclabel.place(x=90, y=15)
verlabel.place(x=110, y=94)
authorlabel.place(x=86, y=120)
copylabel.place(x=2, y=190)
infolabel.place(x=32, | |
self.assertEqual(2, out)
self.assertEqual(1, mc.hits)
self.assertEqual(0, mc.misses)
def test_key_evicts_when_full(self):
sentinel = object()
mc = MQCache(1, 1, 1)
mc.put('key1', 1)
mc.put('key2', 2)
mc.put('key3', 3)
out1 = mc.get('key1', sentinel)
out2 = mc.get('key2', sentinel)
out3 = mc.get('key3', sentinel)
self.assertEqual(sentinel, out1)
self.assertEqual(2, out2)
self.assertEqual(3, out3)
def test_key_evicts_by_expire_time(self):
sentinel = object()
mc = MQCache(2, 1, 1, num_queues=3)
mc.put('key1', 1)
mc.put('key2', 2)
mc.put('key1', 1)
mc.put('key1', 1)
mc.put('key1', 1)
mc.put('key1', 1)
mc.put('key2', 2)
mc.put('key2', 2)
mc.put('key3', 3)
mc.put('key4', 4)
out1 = mc.get('key1', sentinel)
out2 = mc.get('key2', sentinel)
out3 = mc.get('key3', sentinel)
out4 = mc.get('key4', sentinel)
self.assertEqual(out1, sentinel)
self.assertEqual(out2, 2)
self.assertEqual(out3, 3)
self.assertEqual(out4, 4)
def test_key_evicts_correctly(self):
sentinel = object()
mc = MQCache(2, 1, 3, num_queues=1, access_based=False)
mc.put('key1', 1)
mc.put('key2', 2)
mc.put('key3', 3)
out1 = mc.get('key1', sentinel)
out2 = mc.get('key2', sentinel)
out3 = mc.get('key3', sentinel)
mc.put('key1', 1)
# key2 should be evicted
mc.put('key4', 4)
out4 = mc.get('key2', sentinel)
# key3 should be evicted
mc.put('key5', 5)
out5 = mc.get('key1', sentinel)
out6 = mc.get('key2', sentinel)
out7 = mc.get('key3', sentinel)
out8 = mc.get('key4', sentinel)
out9 = mc.get('key5', sentinel)
self.assertEqual(1, out1)
self.assertEqual(2, out2)
self.assertEqual(3, out3)
self.assertEqual(sentinel, out4)
self.assertEqual(1, out5)
self.assertEqual(sentinel, out6)
self.assertEqual(sentinel, out7)
self.assertEqual(4, out8)
self.assertEqual(5, out9)
class TestMRUCache(unittest.TestCase):
def test_invalid_size(self):
with self.assertRaises(ValueError):
MRUCache(0)
def test_current_size_when_empty(self):
mc = MRUCache(1)
self.assertEqual(0, mc.current_size)
def test_current_size_with_items(self):
mc = MRUCache(2)
mc.put('key1', 1)
mc.put('key2', 2)
self.assertEqual(2, mc.current_size)
def test_current_size_with_full_cache(self):
mc = MRUCache(2)
mc.put('key1', 1)
mc.put('key2', 2)
self.assertEqual(2, mc.current_size)
def test_max_size(self):
mc = MRUCache(1)
self.assertEqual(1, mc.max_size)
def test_hits_none(self):
mc = MRUCache(1)
mc.get('key', object())
mc.get('key', object())
self.assertEqual(0, mc.hits)
def test_hits_some(self):
mc = MRUCache(2)
mc.put('key', object())
mc.get('key', object())
mc.get('key', object())
self.assertEqual(2, mc.hits)
def test_misses(self):
mc = MRUCache(1)
mc.get('key', object())
mc.get('key', object())
self.assertEqual(2, mc.misses)
def test_misses_none(self):
mc = MRUCache(2)
mc.put('key', object())
mc.get('key', object())
mc.get('key', object())
self.assertEqual(0, mc.misses)
def test_clear_with_empty_cache(self):
mc = MRUCache(1)
mc.clear()
self.assertEqual({}, mc._map)
self.assertEqual(0, len(mc._queue))
self.assertEqual(0, mc.hits)
self.assertEqual(0, mc.misses)
def test_clear_with_items(self):
mc = MRUCache(1)
mc.put('key1', 1)
mc.put('key2', 2)
mc.clear()
self.assertEqual({}, mc._map)
self.assertEqual(0, len(mc._queue))
self.assertEqual(0, mc.hits)
self.assertEqual(0, mc.misses)
def test_get_key_in_cache(self):
mc = MRUCache(1)
mc.put('key', 1)
out = mc.get('key', object())
self.assertEqual(1, out)
def test_get_key_not_in_cache(self):
mc = MRUCache(1)
sentinel = object()
out = mc.get('key', sentinel)
self.assertEqual(sentinel, out)
def test_put_key_in_cache(self):
mc = MRUCache(1)
mc.put('key', 1)
out = mc.get('key', object())
self.assertEqual(1, out)
self.assertEqual(1, mc.hits)
self.assertEqual(0, mc.misses)
def test_put_existing_key_in_cache(self):
mc = MRUCache(1)
mc.put('key', 1)
mc.put('key', 2)
out = mc.get('key', object())
self.assertEqual(2, out)
self.assertEqual(1, mc.hits)
self.assertEqual(0, mc.misses)
def test_key_evicts_when_full(self):
sentinel = object()
mc = MRUCache(1)
mc.put('key1', 1)
mc.put('key2', 2)
out1 = mc.get('key1', sentinel)
out2 = mc.get('key2', sentinel)
self.assertEqual(sentinel, out1)
self.assertEqual(2, out2)
def test_key_evicts_most_recent(self):
sentinel = object()
mc = MRUCache(2)
mc.put('key1', 1)
mc.put('key2', 2)
out1 = mc.get('key1', sentinel)
out2 = mc.get('key2', sentinel)
out3 = mc.get('key2', sentinel)
# key2 should be evicted
mc.put('key3', 3)
out4 = mc.get('key1', sentinel)
# key1 should be evicted
mc.put('key4', 4)
out5 = mc.get('key2', sentinel)
out6 = mc.get('key3', sentinel)
out7 = mc.get('key4', sentinel)
out8 = mc.get('key1', sentinel)
self.assertEqual(1, out1)
self.assertEqual(2, out2)
self.assertEqual(2, out3)
self.assertEqual(1, out4)
self.assertEqual(sentinel, out5)
self.assertEqual(3, out6)
self.assertEqual(4, out7)
self.assertEqual(sentinel, out8)
class TestNMRUCache(unittest.TestCase):
def test_invalid_size(self):
with self.assertRaises(ValueError):
NMRUCache(0)
def test_current_size_when_empty(self):
nc = NMRUCache(1)
self.assertEqual(0, nc.current_size)
def test_current_size_with_items(self):
nc = NMRUCache(2)
nc.put('key1', 1)
nc.put('key2', 2)
self.assertEqual(2, nc.current_size)
def test_current_size_with_full_cache(self):
nc = NMRUCache(2)
nc.put('key1', 1)
nc.put('key2', 2)
self.assertEqual(2, nc.current_size)
def test_max_size(self):
nc = NMRUCache(1)
self.assertEqual(1, nc.max_size)
def test_hits_none(self):
nc = NMRUCache(1)
nc.get('key', object())
nc.get('key', object())
self.assertEqual(0, nc.hits)
def test_hits_some(self):
nc = NMRUCache(2)
nc.put('key', object())
nc.get('key', object())
nc.get('key', object())
self.assertEqual(2, nc.hits)
def test_misses(self):
nc = NMRUCache(1)
nc.get('key', object())
nc.get('key', object())
self.assertEqual(2, nc.misses)
def test_misses_none(self):
nc = NMRUCache(2)
nc.put('key', object())
nc.get('key', object())
nc.get('key', object())
self.assertEqual(0, nc.misses)
def test_clear_with_empty_cache(self):
nc = NMRUCache(1)
nc.clear()
self.assertEqual({}, nc._store)
self.assertEqual(None, nc._mru_item)
self.assertEqual(0, nc.hits)
self.assertEqual(0, nc.misses)
def test_clear_with_items(self):
nc = NMRUCache(1)
nc.put('key1', 1)
nc.put('key2', 2)
nc.clear()
self.assertEqual({}, nc._store)
self.assertEqual(None, nc._mru_item)
self.assertEqual(0, nc.hits)
self.assertEqual(0, nc.misses)
def test_get_key_in_cache(self):
nc = NMRUCache(1)
nc.put('key', 1)
out = nc.get('key', object())
self.assertEqual(1, out)
def test_get_key_not_in_cache(self):
nc = NMRUCache(1)
sentinel = object()
out = nc.get('key', sentinel)
self.assertEqual(sentinel, out)
def test_put_key_in_cache(self):
nc = NMRUCache(1)
nc.put('key', 1)
out = nc.get('key', object())
self.assertEqual(1, out)
self.assertEqual(1, nc.hits)
self.assertEqual(0, nc.misses)
def test_put_existing_key_in_cache(self):
nc = NMRUCache(1)
nc.put('key', 1)
nc.put('key', 2)
out = nc.get('key', object())
self.assertEqual(2, out)
self.assertEqual(1, nc.hits)
self.assertEqual(0, nc.misses)
def test_key_evicts_when_full(self):
sentinel = object()
nc = NMRUCache(1)
nc.put('key1', 1)
nc.put('key2', 2)
out1 = nc.get('key1', sentinel)
out2 = nc.get('key2', sentinel)
self.assertEqual(sentinel, out1)
self.assertEqual(2, out2)
def test_key_evicts_not_most_recent(self):
sentinel = object()
nc = NMRUCache(3)
nc.put('key1', 1)
nc.put('key2', 2)
nc.put('key3', 3)
out1 = nc.get('key1', sentinel)
out2 = nc.get('key2', sentinel)
out3 = nc.get('key2', sentinel)
# key1 or key3 should be evicted x1
nc.put('key4', 4)
nc.get('key3', sentinel)
nc.put('key4', 4)
out4 = nc.get('key1', sentinel)
out5 = nc.get('key3', sentinel)
out6 = nc.get('key2', sentinel)
# key1 or key3 or key4 should be evicted x2
nc.put('key5', 5)
out7 = nc.get('key1', sentinel)
out8 = nc.get('key2', sentinel)
out9 = nc.get('key3', sentinel)
out10 = nc.get('key4', sentinel)
out11 = nc.get('key5', sentinel)
self.assertEqual(1, out1)
self.assertEqual(2, out2)
self.assertEqual(2, out3)
self.assertEqual(1, len({1, 3}.difference({out4, out5})))
self.assertEqual(2, out6)
self.assertEqual(2, len({1, 3, 4}.difference({out7, out9, out10})))
self.assertEqual(2, out8)
self.assertEqual(5, out11)
class TestRRCache(unittest.TestCase):
def test_invalid_size(self):
with self.assertRaises(ValueError):
RRCache(0)
def test_current_size_when_empty(self):
rc = RRCache(1)
self.assertEqual(0, rc.current_size)
def test_current_size_with_items(self):
rc = RRCache(2)
rc.put('key1', 1)
rc.put('key2', 2)
self.assertEqual(2, rc.current_size)
def test_current_size_with_full_cache(self):
rc = RRCache(2)
rc.put('key1', 1)
rc.put('key2', 2)
self.assertEqual(2, rc.current_size)
def test_max_size(self):
rc = RRCache(1)
self.assertEqual(1, rc.max_size)
def test_hits_none(self):
rc = RRCache(1)
rc.get('key', object())
rc.get('key', object())
self.assertEqual(0, rc.hits)
def test_hits_some(self):
rc = RRCache(2)
rc.put('key', object())
rc.get('key', object())
rc.get('key', object())
self.assertEqual(2, rc.hits)
def test_misses(self):
rc = RRCache(1)
rc.get('key', object())
rc.get('key', object())
self.assertEqual(2, rc.misses)
def test_misses_none(self):
rc = RRCache(2)
rc.put('key', object())
rc.get('key', object())
rc.get('key', object())
self.assertEqual(0, rc.misses)
def test_clear_with_empty_cache(self):
rc = RRCache(1)
rc.clear()
self.assertEqual({}, rc._store)
self.assertEqual(0, rc.hits)
self.assertEqual(0, rc.misses)
def test_clear_with_items(self):
rc = RRCache(1)
rc.put('key1', 1)
rc.put('key2', 2)
rc.clear()
self.assertEqual({}, rc._store)
self.assertEqual(0, rc.hits)
self.assertEqual(0, rc.misses)
def test_get_key_in_cache(self):
rc = RRCache(1)
rc.put('key', 1)
out = rc.get('key', object())
self.assertEqual(1, out)
def test_get_key_not_in_cache(self):
rc = RRCache(1)
sentinel = object()
out = rc.get('key', sentinel)
self.assertEqual(sentinel, out)
def test_put_key_in_cache(self):
rc = RRCache(1)
rc.put('key', 1)
out = rc.get('key', object())
self.assertEqual(1, out)
self.assertEqual(1, rc.hits)
self.assertEqual(0, rc.misses)
def test_put_existing_key_in_cache(self):
rc = RRCache(1)
rc.put('key', 1)
rc.put('key', 2)
out = rc.get('key', object())
self.assertEqual(2, out)
self.assertEqual(1, rc.hits)
self.assertEqual(0, rc.misses)
def test_key_evicts_when_full(self):
sentinel = object()
rc = RRCache(1)
rc.put('key1', 1)
rc.put('key2', 2)
out1 = rc.get('key1', sentinel)
out2 = rc.get('key2', sentinel)
if len({1, 2, sentinel}.difference({out1, out2})) != 1:
self.fail('Unexpected number of keys in cache!')
class TestSLRUCache(unittest.TestCase):
def test_invalid_protected_size(self):
with self.assertRaises(ValueError):
SLRUCache(0, 1)
def test_invalid_probationary_size(self):
with self.assertRaises(ValueError):
SLRUCache(1, 0)
def test_current_size_when_empty(self):
sc = SLRUCache(1, 1)
self.assertEqual(0, sc.current_size)
def test_current_size_with_items(self):
sc = SLRUCache(3, 1)
sc.put('key1', 1)
self.assertEqual(1, sc.current_size)
def test_current_size_with_full_secondary_cache(self):
sc = SLRUCache(1, 1)
sc.put('key1', 1)
sc.put('key2', 2)
self.assertEqual(1, sc.current_size)
def test_current_size_with_full_primary_cache(self):
sc = SLRUCache(1, 1)
sc.put('key1', 1)
sc.get('key1', object())
sc.put('key2', 2)
sc.get('key2', object())
self.assertEqual(2, sc.current_size)
def test_current_size_with_full_secondary_and_primary_cache(self):
sc = SLRUCache(1, 1)
sc.put('key1', 1)
sc.get('key1', object())
sc.put('key2', 2)
self.assertEqual(2, sc.current_size)
def test_max_size(self):
sc = SLRUCache(4, 3)
self.assertEqual(7, sc.max_size)
def test_hits_none(self):
sc = SLRUCache(1, 1)
sc.get('key', object())
sc.get('key', object())
self.assertEqual(0, sc.hits)
def test_hits_some(self):
sc = SLRUCache(1, 1)
sc.put('key', object())
sc.get('key', object())
sc.get('key', object())
self.assertEqual(2, sc.hits)
def test_misses(self):
sc = SLRUCache(1, 1)
sc.get('key', object())
sc.get('key', object())
self.assertEqual(2, sc.misses)
def test_misses_none(self):
sc = SLRUCache(2, 1)
sc.put('key', object())
sc.get('key', object())
sc.get('key', object())
self.assertEqual(0, sc.misses)
def test_clear_with_empty_cache(self):
sc = SLRUCache(1, 1)
sc.clear()
self.assertEqual({}, sc._protected_map)
self.assertEqual({}, sc._probationary_map)
self.assertEqual(0, len(sc._protected_store))
self.assertEqual(0, len(sc._probationary_store))
self.assertEqual(0, sc.hits)
self.assertEqual(0, sc.misses)
def test_clear_with_items(self):
sc = SLRUCache(1, 2)
sc.put('key1', 1)
sc.put('key2', 2)
sc.clear()
self.assertEqual({}, sc._protected_map)
self.assertEqual({}, sc._probationary_map)
self.assertEqual(0, len(sc._protected_store))
self.assertEqual(0, len(sc._probationary_store))
self.assertEqual(0, sc.hits)
self.assertEqual(0, sc.misses)
def test_get_key_in_cache(self):
sc = SLRUCache(1, 1)
sc.put('key', 1)
out = sc.get('key', object())
self.assertEqual(1, out)
def test_get_key_not_in_cache(self):
sc = SLRUCache(1, 1)
sentinel = object()
out = sc.get('key', sentinel)
self.assertEqual(sentinel, out)
def test_put_key_in_cache(self):
sc = SLRUCache(1, 1)
sc.put('key', 1)
out = sc.get('key', object())
self.assertEqual(1, out)
self.assertEqual(1, sc.hits)
self.assertEqual(0, sc.misses)
def test_put_existing_key_in_cache(self):
sc = SLRUCache(1, 1)
sc.put('key', 1)
sc.put('key', 2)
out = sc.get('key', object())
self.assertEqual(2, out)
self.assertEqual(1, sc.hits)
self.assertEqual(0, sc.misses)
def test_key_evicts_when_probationary_full(self):
sentinel = object()
sc = SLRUCache(1, 1)
sc.put('key1', 1)
sc.put('key2', 2)
out1 = sc.get('key1', sentinel)
out2 = sc.get('key2', sentinel)
self.assertEqual(sentinel, out1)
self.assertEqual(2, out2)
def test_key_moves_to_probationary_when_protected_full(self):
sentinel = object()
sc = SLRUCache(1, 1)
sc.put('key1', 1)
out1 = sc.get('key1', sentinel)
sc.put('key2', 2)
out2 | |
# TODO
# - On print extensions, print the reflected internal representation of the object
# - Verify that when mp_obj is given it is indeed the right type (mp_lv_obj_t). Report error if not. can be added to mp_to_lv.
# - Implement inheritance instead of embed base methods (how? seems it's not supported, see https://github.com/micropython/micropython/issues/1159)
from __future__ import print_function
import sys
def eprint(*args, **kwargs):
print(*args, file=sys.stderr, **kwargs)
from sys import argv
from argparse import ArgumentParser
import subprocess, re
from os.path import commonprefix
import os
sys.path.insert(0,'./pycparser')
sys.argv[0] = 'gen_mpy.py'
from pycparser import c_parser, c_ast, c_generator
#
# Argument parsing
#
argParser = ArgumentParser()
argParser.add_argument('-I', '--include', dest='include', help='Preprocesor include path', metavar='<Include Path>', action='append')
argParser.add_argument('-X', '--exclude', dest='exclude', help='Exclude lvgl object', metavar='<Object Name>', action='append')
argParser.add_argument('input', nargs='+')
args = argParser.parse_args()
#
# C proceprocessing
#
pp_cmd = 'gcc -E -std=c99 {include} {input} {first_input}'.format(
input=' '.join('-include %s' % inp for inp in args.input),
first_input= '%s' % args.input[0],
include=' '.join('-I %s' % inc for inc in args.include))
s = subprocess.check_output(pp_cmd.split()).decode()
#
# lv text patterns
# IGNORECASE and "lower" are used to match both function and enum names
#
base_obj_name = 'obj'
lv_ext_pattern = re.compile('^lv_([^_]+)_ext_t')
lv_obj_pattern = re.compile('^lv_([^_]+)', re.IGNORECASE)
lv_func_pattern = re.compile('^lv_(.+)', re.IGNORECASE)
create_obj_pattern = re.compile('^lv_([^_]+)_create')
lv_method_pattern = re.compile('^lv_[^_]+_(.+)', re.IGNORECASE)
lv_base_obj_pattern = re.compile('^(struct _){0,1}lv_%s_t' % (base_obj_name))
lv_callback_return_type_pattern = re.compile('^((void)|(lv_res_t))')
def obj_name_from_ext_name(ext_name):
return re.match(lv_ext_pattern, ext_name).group(1)
def obj_name_from_func_name(func_name):
return re.match(lv_obj_pattern, func_name).group(1)
def ctor_name_from_obj_name(obj_name):
return 'lv_%s_create' % obj_name
def is_method_of(func_name, obj_name):
return func_name.lower().startswith(('lv_%s_' % obj_name).lower())
def method_name_from_func_name(func_name):
return re.match(lv_method_pattern, func_name).group(1)
def get_enum_name(enum):
prefix = 'lv_'
return enum[len(prefix):]
def get_enum_value(obj_name, enum_member):
return '%s_%s' % (obj_name, enum_member)
#
# Initialization, data structures, helper functions
#
parser = c_parser.CParser()
gen = c_generator.CGenerator()
ast = parser.parse(s, filename='<none>')
typedefs = [x.type for x in ast.ext if isinstance(x, c_ast.Typedef)]
func_defs = [x.decl for x in ast.ext if isinstance(x, c_ast.FuncDef)]
func_decls = [x for x in ast.ext if isinstance(x, c_ast.Decl) and isinstance(x.type, c_ast.FuncDecl)]
funcs = func_defs + func_decls
excluded_ctors = [ctor_name_from_obj_name(obj) for obj in args.exclude]
obj_ctors = [func for func in funcs if create_obj_pattern.match(func.name) and not func.name in excluded_ctors]
for obj_ctor in obj_ctors:
funcs.remove(obj_ctor)
obj_names = [re.match(create_obj_pattern, ctor.name).group(1) for ctor in obj_ctors]
def has_ctor(obj_name):
return ctor_name_from_obj_name(obj_name) in [ctor.name for ctor in obj_ctors]
def get_ctor(obj_name):
global obj_ctors
return next(ctor for ctor in obj_ctors if ctor.name == ctor_name_from_obj_name(obj_name))
def get_methods(obj_name):
global funcs
return [func for func in funcs if is_method_of(func.name,obj_name) and (not func.name == ctor_name_from_obj_name(obj_name))]
def get_enum_members(obj_name):
global enums
if not obj_name in enums:
return []
prefix_len = len(obj_name)+1
return [enum_member_name[prefix_len:] for enum_member_name, value in enums[obj_name].items()]
# By default all object (except base_obj) inherit from base_obj. Later we refine this according to hierarchy.
parent_obj_names = {child_name: base_obj_name for child_name in obj_names if child_name != base_obj_name}
parent_obj_names[base_obj_name] = None
# Populate inheritance hierarchy according to lv_ext structures
exts = {obj_name_from_ext_name(ext.name): ext for ext in ast.ext if hasattr(ext, 'name') and ext.name is not None and lv_ext_pattern.match(ext.name)}
for obj_name, ext in exts.items():
try:
parent_ext_name = ext.type.type.decls[0].type.type.names[0]
if lv_ext_pattern.match(parent_ext_name):
parent_obj_names[obj_name] = obj_name_from_ext_name(parent_ext_name)
except AttributeError:
pass
# Parse Enums
enum_defs = [x for x in ast.ext if hasattr(x,'type') and isinstance(x.type, c_ast.Enum)]
enums = {}
for enum_def in enum_defs:
member_names = [member.name for member in enum_def.type.values.enumerators]
enum_name = commonprefix(member_names)
enum_name = "_".join(enum_name.split("_")[:-1]) # remove suffix
enum = {}
next_value = 0
for member in enum_def.type.values.enumerators:
if member.value == None:
value = next_value
else:
value = int(member.value.value, 0)
enum[member.name] = value
next_value = value + 1
enums[enum_name] = enum
# eprint(enums)
# parse function pointers
func_typedefs = [t for t in ast.ext if isinstance(t, c_ast.Typedef) and isinstance(t.type, c_ast.PtrDecl) and isinstance(t.type.type, c_ast.FuncDecl)]
#
# Type convertors
#
#action_index = {}
#
#def handle_lv_action(arg, index, func, obj_name):
# global action_index
# args = func.type.args.params
# if not obj_name in action_index:
# action_index[obj_name] = 0
# prev_arg_type = mp_to_lv[get_arg_type(args[index-1].type)] if index > 0 else None
# eprint("--> %s, %s" % (get_arg_type(args[index-1].type), mp_to_lv[get_arg_type(args[index-1].type)]))
# if prev_arg_type in enums:
# variable_index = "%d + %s" % (action_index[obj_name], args[index-1].name)
# action_index[obj_name] += len(enums[prev_arg_type])
# else:
# variable_index = "{action_index}".format(action_index = action_index[obj_name])
# action_index[obj_name] += 1
# return """mp_lv_obj_t *mp_lb_obj = lv_obj_get_free_ptr(obj);
# {var} = mp_lb_obj.actions[{variable_index}];""".format(
# var = gen.visit(arg), variable_index = variable_index)
class MissingConversionException(ValueError):
pass
mp_to_lv = {
'bool' : 'mp_obj_is_true',
'char*' : '(char*)mp_obj_str_get_str',
'const char*' : 'mp_obj_str_get_str',
'lv_obj_t*' : 'mp_to_lv',
'const lv_obj_t*' : 'mp_to_lv',
'struct _lv_obj_t*' : 'mp_to_lv',
'const struct _lv_obj_t*' : 'mp_to_lv',
'uint8_t' : '(uint8_t)mp_obj_int_get_checked',
'uint16_t' : '(uint16_t)mp_obj_int_get_checked',
'uint32_t' : '(uint32_t)mp_obj_int_get_checked',
'int8_t' : '(int8_t)mp_obj_int_get_checked',
'int16_t' : '(int16_t)mp_obj_int_get_checked',
'int32_t' : '(int32_t)mp_obj_int_get_checked',
# 'lv_action_t' : handle_lv_action
}
lv_to_mp = {
'bool' : 'convert_to_bool',
'char*' : 'convert_to_str',
'const char*' : 'convert_to_str',
'lv_obj_t*' : 'lv_to_mp',
'const lv_obj_t*' : 'lv_to_mp',
'struct _lv_obj_t*' : 'lv_to_mp',
'const struct _lv_obj_t*' : 'lv_to_mp',
'uint8_t' : 'mp_obj_new_int_from_uint',
'uint16_t' : 'mp_obj_new_int_from_uint',
'uint32_t' : 'mp_obj_new_int_from_uint',
'int8_t' : 'mp_obj_new_int',
'int16_t' : 'mp_obj_new_int',
'int32_t' : 'mp_obj_new_int',
}
#
# Emit Header
#
print ("""
/*
* Auto-Generated file, DO NOT EDIT!
*
* Command line:
* {cmd_line}
*
* Preprocessing command:
* {pp_cmd}
*
* Generating Objects: {objs}
*/
/*
* Mpy includes
*/
#include <string.h>
#include "py/obj.h"
#include "py/runtime.h"
/*
* lvgl includes
*/
{lv_headers}
""".format(
cmd_line=' '.join(argv),
pp_cmd=pp_cmd,
objs=", ".join(['%s(%s)' % (objname, parent_obj_names[objname]) for objname in obj_names]),
lv_headers='\n'.join('#include "%s"' % header for header in args.input)))
#
# Emit Mpy helper functions
#
print("""
/*
* Helper functions
*/
typedef lv_obj_t* (*lv_create)(lv_obj_t * par, const lv_obj_t * copy);
typedef struct mp_lv_obj_t {
mp_obj_base_t base;
lv_obj_t *lv_obj;
mp_obj_t *action;
} mp_lv_obj_t;
STATIC inline lv_obj_t *mp_to_lv(mp_obj_t *mp_obj)
{
if (mp_obj == NULL || mp_obj == mp_const_none) return NULL;
mp_lv_obj_t *mp_lv_obj = MP_OBJ_TO_PTR(mp_obj);
return mp_lv_obj->lv_obj;
}
STATIC inline mp_obj_t *mp_to_lv_action(mp_obj_t *mp_obj)
{
if (mp_obj == NULL || mp_obj == mp_const_none) return NULL;
mp_lv_obj_t *mp_lv_obj = MP_OBJ_TO_PTR(mp_obj);
return mp_lv_obj->action;
}
STATIC inline void set_action(mp_obj_t *mp_obj, mp_obj_t *action)
{
if (mp_obj == NULL || mp_obj == mp_const_none) return;
mp_lv_obj_t *mp_lv_obj = MP_OBJ_TO_PTR(mp_obj);
mp_lv_obj->action = action;
}
STATIC inline const mp_obj_type_t *get_BaseObj_type();
STATIC inline mp_obj_t *lv_to_mp(lv_obj_t *lv_obj)
{
mp_lv_obj_t *self = lv_obj_get_free_ptr(lv_obj);
if (!self)
{
self = m_new_obj(mp_lv_obj_t);
*self = (mp_lv_obj_t){
.base = {get_BaseObj_type()},
.lv_obj = lv_obj,
.action = NULL
};
}
return MP_OBJ_FROM_PTR(self);
}
STATIC mp_obj_t make_new(
lv_create create,
const mp_obj_type_t *type,
size_t n_args,
size_t n_kw,
const mp_obj_t *args)
{
mp_arg_check_num(n_args, n_kw, 1, 2, false);
mp_lv_obj_t *self = m_new_obj(mp_lv_obj_t);
lv_obj_t *parent = mp_to_lv(args[0]);
lv_obj_t *copy = n_args > 1? mp_to_lv(args[1]): NULL;
*self = (mp_lv_obj_t){
.base = {type},
.lv_obj = create(parent, copy),
.action = NULL
};
lv_obj_set_free_ptr(self->lv_obj, self);
return MP_OBJ_FROM_PTR(self);
}
STATIC inline mp_obj_t convert_to_bool(bool b)
{
return b? mp_const_true: mp_const_false;
}
STATIC inline mp_obj_t convert_to_str(const char *str)
{
return mp_obj_new_str(str, strlen(str));
}
""")
#
# Generate types from typedefs when needed
#
def get_arg_type(arg):
indirect_level = 0
while isinstance(arg, c_ast.PtrDecl):
indirect_level += 1
arg = arg.type
return '{quals}{type}{indirection}'.format(
quals=''.join('%s ' % qual for qual in arg.quals) if hasattr(arg, 'quals') else '',
type=gen.visit(arg),
indirection='*' * indirect_level)
def get_arg_name(arg):
if isinstance(arg, c_ast.PtrDecl) or isinstance(arg, c_ast.FuncDecl):
return get_arg_name(arg.type)
return arg.declname if hasattr(arg, 'declname') else arg.name
# print "// Typedefs: " + ", ".join(get_arg_name(t) for t in typedefs)
def try_generate_type(type):
global typedefs
global mp_to_lv, lv_to_mp
if type in mp_to_lv:
return True
for new_type in [get_arg_type(x) for x in typedefs if get_arg_name(x) == type]:
if try_generate_type(new_type):
mp_to_lv[type] = mp_to_lv[new_type]
if new_type in lv_to_mp:
lv_to_mp[type] = lv_to_mp[new_type]
# print "// %s = (%s)" % (type, new_type)
return True
return False
#
# Emit C callback functions
#
def build_callback_func_arg(arg, index, func):
arg_type = get_arg_type(arg.type)
if not arg_type in lv_to_mp:
try_generate_type(arg_type)
if not arg_type in lv_to_mp:
raise MissingConversionException("Callback: Missing conversion to %s" % arg_type)
return lv_to_mp[arg_type](arg, index, func, obj_name) if callable(lv_to_mp[arg_type]) else \
'args[{i}] = {convertor}(arg{i});'.format(
convertor = lv_to_mp[arg_type],
i = index)
def gen_callback_func(func):
global mp_to_lv
args = func.args.params
if len(args) < 1 or hasattr(args[0].type.type, 'names') and lv_base_obj_pattern.match(args[0].type.type.names[0]):
raise MissingConversionException("Callback: First argument of callback function must be lv_obj_t")
func_name = get_arg_name(func.type)
return_type = get_arg_type(func.type)
if not lv_callback_return_type_pattern.match(return_type):
raise MissingConversionException("Callback: Can only handle callbaks that return lv_res_t or void")
print("""
/*
* Callback function {func_name}
* {func_prototype}
*/
STATIC {return_type} {func_name}_callback({func_args})
{{
mp_obj_t args[{num_args}];
{build_args}
mp_obj_t action = mp_to_lv_action(args[0]);
mp_obj_t arg_list = mp_obj_new_list({num_args}, args);
bool schedule_result = mp_sched_schedule(action, arg_list);
return{return_value};
}}
""".format(
func_prototype = gen.visit(func),
func_name = func_name,
return_type = return_type,
func_args = ', '.join(["%s arg%s" % (get_arg_type(arg.type), i) for i,arg in enumerate(args)]),
num_args=len(args),
build_args="\n ".join([build_callback_func_arg(arg, i, func) for i,arg in enumerate(args)]),
return_value='' if return_type=='void' else ' schedule_result? LV_RES_OK: LV_RES_INV'))
def register_callback(arg, index, func, obj_name):
return """set_action(args[0], args[{i}]);
{arg} = &{func_name}_callback;""".format(
i = index,
arg = gen.visit(arg),
func_name = func_name)
mp_to_lv[func_name] = register_callback
#
# Emit Mpy function definitions
#
generated_funcs = {}
def build_mp_func_arg(arg, index, func, obj_name):
arg_type = get_arg_type(arg.type)
if not arg_type in mp_to_lv:
try_generate_type(arg_type)
if not arg_type in mp_to_lv:
raise MissingConversionException("Missing conversion to %s" % arg_type)
return mp_to_lv[arg_type](arg, index, func, obj_name) if callable(mp_to_lv[arg_type]) else \
'{var} = {convertor}(args[{i}]);'.format(
var = gen.visit(arg),
convertor = mp_to_lv[arg_type],
i | |
('server_name', self.new_server.name),
]
parsed_args = self.check_parser(self.cmd, arglist, verifylist)
# In base command class ShowOne in cliff, abstract method take_action()
# returns a two-part tuple with a tuple of column names and a tuple of
# data to be shown.
columns, data = self.cmd.take_action(parsed_args)
# Set expected values
kwargs = dict(
meta=None,
files={},
reservation_id=None,
min_count=1,
max_count=1,
security_groups=[],
userdata=None,
key_name=None,
availability_zone=None,
block_device_mapping_v2=[],
nics=[],
scheduler_hints={},
config_drive=None,
)
# ServerManager.create(name, image, flavor, **kwargs)
self.servers_mock.create.assert_called_with(
self.new_server.name,
self.image,
self.flavor,
**kwargs
)
self.assertEqual(self.columns, columns)
self.assertEqual(self.datalist(), data)
self.assertFalse(self.images_mock.called)
self.assertFalse(self.flavors_mock.called)
def test_server_create_with_options(self):
arglist = [
'--image', 'image1',
'--flavor', 'flavor1',
'--key-name', 'keyname',
'--property', 'Beta=b',
'--security-group', 'securitygroup',
'--hint', 'a=b',
'--hint', 'a=c',
self.new_server.name,
]
verifylist = [
('image', 'image1'),
('flavor', 'flavor1'),
('key_name', 'keyname'),
('property', {'Beta': 'b'}),
('security_group', ['securitygroup']),
('hint', ['a=b', 'a=c']),
('config_drive', False),
('server_name', self.new_server.name),
]
parsed_args = self.check_parser(self.cmd, arglist, verifylist)
# In base command class ShowOne in cliff, abstract method take_action()
# returns a two-part tuple with a tuple of column names and a tuple of
# data to be shown.
fake_sg = network_fakes.FakeSecurityGroup.create_security_groups()
mock_find_sg = (
network_fakes.FakeSecurityGroup.get_security_groups(fake_sg)
)
self.app.client_manager.network.find_security_group = mock_find_sg
columns, data = self.cmd.take_action(parsed_args)
mock_find_sg.assert_called_once_with('securitygroup',
ignore_missing=False)
# Set expected values
kwargs = dict(
meta={'Beta': 'b'},
files={},
reservation_id=None,
min_count=1,
max_count=1,
security_groups=[fake_sg[0].id],
userdata=None,
key_name='keyname',
availability_zone=None,
block_device_mapping_v2=[],
nics=[],
scheduler_hints={'a': ['b', 'c']},
config_drive=None,
)
# ServerManager.create(name, image, flavor, **kwargs)
self.servers_mock.create.assert_called_with(
self.new_server.name,
self.image,
self.flavor,
**kwargs
)
self.assertEqual(self.columns, columns)
self.assertEqual(self.datalist(), data)
def test_server_create_with_not_exist_security_group(self):
arglist = [
'--image', 'image1',
'--flavor', 'flavor1',
'--key-name', 'keyname',
'--security-group', 'securitygroup',
'--security-group', 'not_exist_sg',
self.new_server.name,
]
verifylist = [
('image', 'image1'),
('flavor', 'flavor1'),
('key_name', 'keyname'),
('security_group', ['securitygroup', 'not_exist_sg']),
('server_name', self.new_server.name),
]
parsed_args = self.check_parser(self.cmd, arglist, verifylist)
fake_sg = network_fakes.FakeSecurityGroup.create_security_groups(
count=1)
fake_sg.append(exceptions.NotFound(code=404))
mock_find_sg = (
network_fakes.FakeSecurityGroup.get_security_groups(fake_sg)
)
self.app.client_manager.network.find_security_group = mock_find_sg
self.assertRaises(exceptions.NotFound,
self.cmd.take_action,
parsed_args)
mock_find_sg.assert_called_with('not_exist_sg',
ignore_missing=False)
def test_server_create_with_security_group_in_nova_network(self):
arglist = [
'--image', 'image1',
'--flavor', 'flavor1',
'--key-name', 'keyname',
'--security-group', 'securitygroup',
self.new_server.name,
]
verifylist = [
('image', 'image1'),
('flavor', 'flavor1'),
('key_name', 'keyname'),
('security_group', ['securitygroup']),
('server_name', self.new_server.name),
]
parsed_args = self.check_parser(self.cmd, arglist, verifylist)
with mock.patch.object(self.app.client_manager,
'is_network_endpoint_enabled',
return_value=False):
with mock.patch.object(self.app.client_manager.compute.api,
'security_group_find',
return_value={'name': 'fake_sg'}
) as mock_find:
columns, data = self.cmd.take_action(parsed_args)
mock_find.assert_called_once_with('securitygroup')
# Set expected values
kwargs = dict(
meta=None,
files={},
reservation_id=None,
min_count=1,
max_count=1,
security_groups=['fake_sg'],
userdata=None,
key_name='keyname',
availability_zone=None,
block_device_mapping_v2=[],
nics=[],
scheduler_hints={},
config_drive=None,
)
# ServerManager.create(name, image, flavor, **kwargs)
self.servers_mock.create.assert_called_with(
self.new_server.name,
self.image,
self.flavor,
**kwargs
)
self.assertEqual(self.columns, columns)
self.assertEqual(self.datalist(), data)
def test_server_create_with_network(self):
arglist = [
'--image', 'image1',
'--flavor', 'flavor1',
'--network', 'net1',
'--nic', 'net-id=net1,v4-fixed-ip=10.0.0.2',
'--port', 'port1',
'--network', 'net1',
'--nic', 'port-id=port2',
self.new_server.name,
]
verifylist = [
('image', 'image1'),
('flavor', 'flavor1'),
('nic', ['net-id=net1', 'net-id=net1,v4-fixed-ip=10.0.0.2',
'port-id=port1', 'net-id=net1', 'port-id=port2']),
('config_drive', False),
('server_name', self.new_server.name),
]
parsed_args = self.check_parser(self.cmd, arglist, verifylist)
get_endpoints = mock.Mock()
get_endpoints.return_value = {'network': []}
self.app.client_manager.auth_ref = mock.Mock()
self.app.client_manager.auth_ref.service_catalog = mock.Mock()
self.app.client_manager.auth_ref.service_catalog.get_endpoints = (
get_endpoints)
find_network = mock.Mock()
find_port = mock.Mock()
network_client = self.app.client_manager.network
network_client.find_network = find_network
network_client.find_port = find_port
network_resource = mock.Mock(id='net1_uuid')
port1_resource = mock.Mock(id='port1_uuid')
port2_resource = mock.Mock(id='port2_uuid')
find_network.return_value = network_resource
find_port.side_effect = (lambda port_id, ignore_missing:
{"port1": port1_resource,
"port2": port2_resource}[port_id])
# Mock sdk APIs.
_network = mock.Mock(id='net1_uuid')
_port1 = mock.Mock(id='port1_uuid')
_port2 = mock.Mock(id='port2_uuid')
find_network = mock.Mock()
find_port = mock.Mock()
find_network.return_value = _network
find_port.side_effect = (lambda port_id, ignore_missing:
{"port1": _port1,
"port2": _port2}[port_id])
self.app.client_manager.network.find_network = find_network
self.app.client_manager.network.find_port = find_port
# In base command class ShowOne in cliff, abstract method take_action()
# returns a two-part tuple with a tuple of column names and a tuple of
# data to be shown.
columns, data = self.cmd.take_action(parsed_args)
# Set expected values
kwargs = dict(
meta=None,
files={},
reservation_id=None,
min_count=1,
max_count=1,
security_groups=[],
userdata=None,
key_name=None,
availability_zone=None,
block_device_mapping_v2=[],
nics=[{'net-id': 'net1_uuid',
'v4-fixed-ip': '',
'v6-fixed-ip': '',
'port-id': ''},
{'net-id': 'net1_uuid',
'v4-fixed-ip': '10.0.0.2',
'v6-fixed-ip': '',
'port-id': ''},
{'net-id': '',
'v4-fixed-ip': '',
'v6-fixed-ip': '',
'port-id': 'port1_uuid'},
{'net-id': 'net1_uuid',
'v4-fixed-ip': '',
'v6-fixed-ip': '',
'port-id': ''},
{'net-id': '',
'v4-fixed-ip': '',
'v6-fixed-ip': '',
'port-id': 'port2_uuid'}],
scheduler_hints={},
config_drive=None,
)
# ServerManager.create(name, image, flavor, **kwargs)
self.servers_mock.create.assert_called_with(
self.new_server.name,
self.image,
self.flavor,
**kwargs
)
self.assertEqual(self.columns, columns)
self.assertEqual(self.datalist(), data)
def test_server_create_with_auto_network(self):
arglist = [
'--image', 'image1',
'--flavor', 'flavor1',
'--nic', 'auto',
self.new_server.name,
]
verifylist = [
('image', 'image1'),
('flavor', 'flavor1'),
('nic', ['auto']),
('config_drive', False),
('server_name', self.new_server.name),
]
parsed_args = self.check_parser(self.cmd, arglist, verifylist)
columns, data = self.cmd.take_action(parsed_args)
# Set expected values
kwargs = dict(
meta=None,
files={},
reservation_id=None,
min_count=1,
max_count=1,
security_groups=[],
userdata=None,
key_name=None,
availability_zone=None,
block_device_mapping_v2=[],
nics='auto',
scheduler_hints={},
config_drive=None,
)
# ServerManager.create(name, image, flavor, **kwargs)
self.servers_mock.create.assert_called_with(
self.new_server.name,
self.image,
self.flavor,
**kwargs
)
self.assertEqual(self.columns, columns)
self.assertEqual(self.datalist(), data)
def test_server_create_with_auto_network_default_v2_37(self):
"""Tests creating a server without specifying --nic using 2.37."""
arglist = [
'--image', 'image1',
'--flavor', 'flavor1',
self.new_server.name,
]
verifylist = [
('image', 'image1'),
('flavor', 'flavor1'),
('config_drive', False),
('server_name', self.new_server.name),
]
parsed_args = self.check_parser(self.cmd, arglist, verifylist)
# Since check_parser doesn't handle compute global options like
# --os-compute-api-version, we have to mock the construction of
# the novaclient client object with our own APIVersion.
with mock.patch.object(self.app.client_manager.compute, 'api_version',
api_versions.APIVersion('2.37')):
columns, data = self.cmd.take_action(parsed_args)
# Set expected values
kwargs = dict(
meta=None,
files={},
reservation_id=None,
min_count=1,
max_count=1,
security_groups=[],
userdata=None,
key_name=None,
availability_zone=None,
block_device_mapping_v2=[],
nics='auto',
scheduler_hints={},
config_drive=None,
)
# ServerManager.create(name, image, flavor, **kwargs)
self.servers_mock.create.assert_called_with(
self.new_server.name,
self.image,
self.flavor,
**kwargs
)
self.assertEqual(self.columns, columns)
self.assertEqual(self.datalist(), data)
def test_server_create_with_none_network(self):
arglist = [
'--image', 'image1',
'--flavor', 'flavor1',
'--nic', 'none',
self.new_server.name,
]
verifylist = [
('image', 'image1'),
('flavor', 'flavor1'),
('nic', ['none']),
('config_drive', False),
('server_name', self.new_server.name),
]
parsed_args = self.check_parser(self.cmd, arglist, verifylist)
columns, data = self.cmd.take_action(parsed_args)
# Set expected values
kwargs = dict(
meta=None,
files={},
reservation_id=None,
min_count=1,
max_count=1,
security_groups=[],
userdata=None,
key_name=None,
availability_zone=None,
block_device_mapping_v2=[],
nics='none',
scheduler_hints={},
config_drive=None,
)
# ServerManager.create(name, image, flavor, **kwargs)
self.servers_mock.create.assert_called_with(
self.new_server.name,
self.image,
self.flavor,
**kwargs
)
self.assertEqual(self.columns, columns)
self.assertEqual(self.datalist(), data)
def test_server_create_with_conflict_network_options(self):
arglist = [
'--image', 'image1',
'--flavor', 'flavor1',
'--nic', 'none',
'--nic', 'auto',
'--nic', 'port-id=port1',
self.new_server.name,
]
verifylist = [
('image', 'image1'),
('flavor', 'flavor1'),
('nic', ['none', 'auto', 'port-id=port1']),
('config_drive', False),
('server_name', self.new_server.name),
]
parsed_args = self.check_parser(self.cmd, arglist, verifylist)
get_endpoints = mock.Mock()
get_endpoints.return_value = {'network': []}
self.app.client_manager.auth_ref = mock.Mock()
self.app.client_manager.auth_ref.service_catalog = mock.Mock()
self.app.client_manager.auth_ref.service_catalog.get_endpoints = (
get_endpoints)
find_port = mock.Mock()
network_client = self.app.client_manager.network
network_client.find_port = find_port
port_resource = mock.Mock(id='port1_uuid')
find_port.return_value = port_resource
self.assertRaises(exceptions.CommandError,
self.cmd.take_action, parsed_args)
self.assertNotCalled(self.servers_mock.create)
def test_server_create_with_invalid_network_options(self):
arglist = [
'--image', 'image1',
'--flavor', 'flavor1',
'--nic', 'abcdefgh',
self.new_server.name,
]
verifylist = [
('image', 'image1'),
('flavor', 'flavor1'),
('nic', ['abcdefgh']),
('config_drive', False),
('server_name', self.new_server.name),
]
parsed_args = self.check_parser(self.cmd, arglist, verifylist)
self.assertRaises(exceptions.CommandError,
self.cmd.take_action, parsed_args)
self.assertNotCalled(self.servers_mock.create)
def test_server_create_with_invalid_network_key(self):
arglist = [
'--image', 'image1',
'--flavor', 'flavor1',
'--nic', 'abcdefgh=12324',
self.new_server.name,
]
verifylist = [
('image', 'image1'),
('flavor', 'flavor1'),
('nic', ['abcdefgh=12324']),
('config_drive', False),
('server_name', self.new_server.name),
]
parsed_args = self.check_parser(self.cmd, arglist, verifylist)
self.assertRaises(exceptions.CommandError,
self.cmd.take_action, parsed_args)
self.assertNotCalled(self.servers_mock.create)
def test_server_create_with_empty_network_key_value(self):
arglist = [
'--image', 'image1',
'--flavor', 'flavor1',
'--nic', 'net-id=',
self.new_server.name,
]
verifylist = [
('image', 'image1'),
('flavor', 'flavor1'),
('nic', ['net-id=']),
('config_drive', False),
('server_name', self.new_server.name),
]
parsed_args = self.check_parser(self.cmd, arglist, verifylist)
self.assertRaises(exceptions.CommandError,
self.cmd.take_action, parsed_args)
self.assertNotCalled(self.servers_mock.create)
def test_server_create_with_only_network_key(self):
arglist = [
'--image', 'image1',
'--flavor', 'flavor1',
'--nic', 'net-id',
self.new_server.name,
]
verifylist = [
('image', 'image1'),
('flavor', 'flavor1'),
('nic', ['net-id']),
('config_drive', False),
('server_name', self.new_server.name),
]
parsed_args = self.check_parser(self.cmd, arglist, verifylist)
self.assertRaises(exceptions.CommandError,
self.cmd.take_action, parsed_args)
self.assertNotCalled(self.servers_mock.create)
@mock.patch.object(common_utils, 'wait_for_status', return_value=True)
def test_server_create_with_wait_ok(self, mock_wait_for_status):
arglist = [
'--image', 'image1',
'--flavor', 'flavor1',
'--wait',
self.new_server.name,
]
verifylist = [
('image', 'image1'),
('flavor', 'flavor1'),
('config_drive', False),
('wait', True),
('server_name', self.new_server.name),
]
parsed_args = self.check_parser(self.cmd, arglist, verifylist)
columns, data = self.cmd.take_action(parsed_args)
mock_wait_for_status.assert_called_once_with(
self.servers_mock.get,
self.new_server.id,
callback=mock.ANY,
)
kwargs = dict(
meta=None,
files={},
reservation_id=None,
min_count=1,
max_count=1,
security_groups=[],
userdata=None,
key_name=None,
availability_zone=None,
block_device_mapping_v2=[],
nics=[],
scheduler_hints={},
config_drive=None,
)
self.servers_mock.create.assert_called_with(
self.new_server.name,
self.image,
self.flavor,
**kwargs
)
self.assertEqual(self.columns, columns)
self.assertEqual(self.datalist(), data)
@mock.patch.object(common_utils, 'wait_for_status', return_value=False)
def test_server_create_with_wait_fails(self, mock_wait_for_status):
arglist = [
'--image', 'image1',
'--flavor', 'flavor1',
'--wait',
self.new_server.name,
]
verifylist = [
('image', 'image1'),
('flavor', 'flavor1'),
('config_drive', False),
('wait', True),
('server_name', self.new_server.name),
]
parsed_args = self.check_parser(self.cmd, arglist, verifylist)
self.assertRaises(SystemExit, self.cmd.take_action, parsed_args)
mock_wait_for_status.assert_called_once_with(
self.servers_mock.get,
self.new_server.id,
callback=mock.ANY,
)
kwargs = dict(
meta=None,
files={},
reservation_id=None,
min_count=1,
max_count=1,
security_groups=[],
userdata=None,
key_name=None,
availability_zone=None,
block_device_mapping_v2=[],
nics=[],
scheduler_hints={},
config_drive=None,
)
self.servers_mock.create.assert_called_with(
self.new_server.name,
self.image,
self.flavor,
**kwargs
)
@mock.patch('openstackclient.compute.v2.server.io.open')
def test_server_create_userdata(self, mock_open):
mock_file = mock.Mock(name='File')
mock_open.return_value = mock_file
mock_open.read.return_value = '#!/bin/sh'
arglist = [
'--image', 'image1',
'--flavor', 'flavor1',
'--user-data', 'userdata.sh',
self.new_server.name,
]
verifylist = [
('image', 'image1'),
('flavor', 'flavor1'),
('user_data', 'userdata.sh'),
('config_drive', False),
('server_name', self.new_server.name),
]
parsed_args = self.check_parser(self.cmd, arglist, verifylist)
# In base command class ShowOne in cliff, abstract method take_action()
# returns a two-part tuple with a tuple of column names and a tuple of
# data | |
flags['i_e2f_lex']
i_f2e = flags['i_f2e']
i_f2e_lex = flags['i_f2e_lex']
new_weights = weights[:]
if flags['normalize_s_given_t'] == 's':
# set weight to 0 for all models where target phrase is unseen (p(s|t)
new_weights[i_e2f] = list(map(mul,interface.phrase_source[src],weights[i_e2f]))
if flags['normalize-lexical_weights']:
new_weights[i_e2f_lex] = list(map(mul,interface.phrase_source[src],weights[i_e2f_lex]))
elif flags['normalize_s_given_t'] == 't':
# set weight to 0 for all models where target phrase is unseen (p(s|t)
new_weights[i_e2f] = list(map(mul,interface.phrase_target[target],weights[i_e2f]))
if flags['normalize-lexical_weights']:
new_weights[i_e2f_lex] = list(map(mul,interface.phrase_target[target],weights[i_e2f_lex]))
# set weight to 0 for all models where source phrase is unseen (p(t|s)
new_weights[i_f2e] = list(map(mul,interface.phrase_source[src],weights[i_f2e]))
if flags['normalize-lexical_weights']:
new_weights[i_f2e_lex] = list(map(mul,interface.phrase_source[src],weights[i_f2e_lex]))
return normalize_weights(new_weights,mode,flags)
def score_interpolate(weights,src,target,interface,flags,cache=False):
"""linear interpolation of probabilites (and other feature values)
if normalized is True, the probability mass for p(x|y) is redistributed to models with p(y) > 0
"""
model_values = interface.phrase_pairs[src][target][0]
scores = [0]*len(model_values)
if 'normalized' in flags and flags['normalized']:
normalized_weights = redistribute_probability_mass(weights,src,target,interface,flags)
else:
normalized_weights = weights
if 'recompute_lexweights' in flags and flags['recompute_lexweights']:
e2f_alignment,f2e_alignment = interface.get_word_alignments(src,target,cache=cache)
if not e2f_alignment or not f2e_alignment:
sys.stderr.write('Error: no word alignments found, but necessary for lexical weight computation.\n')
lst = 0
lts = 0
else:
scores[flags['i_e2f_lex']] = compute_lexicalweight(normalized_weights[flags['i_e2f_lex']],e2f_alignment,interface.word_pairs_e2f,None,mode='interpolate')
scores[flags['i_f2e_lex']] = compute_lexicalweight(normalized_weights[flags['i_f2e_lex']],f2e_alignment,interface.word_pairs_f2e,None,mode='interpolate')
for idx,prob in enumerate(model_values):
if not ('recompute_lexweights' in flags and flags['recompute_lexweights'] and (idx == flags['i_e2f_lex'] or idx == flags['i_f2e_lex'])):
scores[idx] = dot_product(prob,normalized_weights[idx])
return scores
def score_loglinear(weights,src,target,interface,flags,cache=False):
"""loglinear interpolation of probabilites
warning: if phrase pair does not occur in all models, resulting probability is 0
this is usually not what you want - loglinear scoring is only included for completeness' sake
"""
scores = []
model_values = interface.phrase_pairs[src][target][0]
for idx,prob in enumerate(model_values):
try:
scores.append(exp(dot_product(list(map(log,prob)),weights[idx])))
except ValueError:
scores.append(0)
return scores
def score_counts(weights,src,target,interface,flags,cache=False):
"""count-based re-estimation of probabilites and lexical weights
each count is multiplied by its weight; trivial case is weight 1 for each model, which corresponds to a concatentation
"""
i_e2f = flags['i_e2f']
i_e2f_lex = flags['i_e2f_lex']
i_f2e = flags['i_f2e']
i_f2e_lex = flags['i_f2e_lex']
# if we have non-default number of weights, assume that we might have to do a mix of count-based and interpolated scores.
if len(weights) == 4:
scores = [0]*len(weights)
else:
scores = score_interpolate(weights,src,target,interface,flags,cache=cache)
try:
joined_count = dot_product(interface.phrase_pairs[src][target][0][i_e2f],weights[i_e2f])
target_count = dot_product(interface.phrase_target[target],weights[i_e2f])
scores[i_e2f] = joined_count / target_count
except ZeroDivisionError:
scores[i_e2f] = 0
try:
joined_count = dot_product(interface.phrase_pairs[src][target][0][i_f2e],weights[i_f2e])
source_count = dot_product(interface.phrase_source[src],weights[i_f2e])
scores[i_f2e] = joined_count / source_count
except ZeroDivisionError:
scores[i_f2e] = 0
e2f_alignment,f2e_alignment = interface.get_word_alignments(src,target,cache=cache)
if not e2f_alignment or not f2e_alignment:
sys.stderr.write('Error: no word alignments found, but necessary for lexical weight computation.\n')
scores[i_e2f_lex] = 0
scores[i_f2e_lex] = 0
else:
scores[i_e2f_lex] = compute_lexicalweight(weights[i_e2f_lex],e2f_alignment,interface.word_pairs_e2f,interface.word_target,mode='counts',cache=cache)
scores[i_f2e_lex] = compute_lexicalweight(weights[i_f2e_lex],f2e_alignment,interface.word_pairs_f2e,interface.word_source,mode='counts',cache=cache)
return scores
def score_interpolate_reordering(weights,src,target,interface):
"""linear interpolation of reordering model probabilities
also normalizes model so that
"""
model_values = interface.reordering_pairs[src][target]
scores = [0]*len(model_values)
for idx,prob in enumerate(model_values):
scores[idx] = dot_product(prob,weights[idx])
#normalizes first half and last half probabilities (so that each half sums to one).
#only makes sense for bidirectional configuration in Moses. Remove/change this if you want a different (or no) normalization
scores = normalize_weights(scores[:int(interface.number_of_features/2)],'interpolate') + normalize_weights(scores[int(interface.number_of_features/2):],'interpolate')
return scores
def compute_lexicalweight(weights,alignment,word_pairs,marginal,mode='counts',cache=False,mycache=[0,defaultdict(dict)]):
"""compute the lexical weights as implemented in Moses toolkit"""
lex = 1
# new weights: empty cache
if cache and mycache[0] != weights:
mycache[0] = weights
mycache[1] = defaultdict(dict)
for x,translations in alignment:
# skip nonterminals
if x.startswith(b'['):
continue
if cache and translations in mycache[1][x]:
lex_step = mycache[1][x][translations]
else:
lex_step = 0
for y in translations:
if mode == 'counts':
lex_step += dot_product(word_pairs[x][y],weights) / dot_product(marginal[y],weights)
elif mode == 'interpolate':
lex_step += dot_product(word_pairs[x][y],weights)
lex_step /= len(translations)
if cache:
mycache[1][x][translations] = lex_step
lex *= lex_step
return lex
def normalize_weights(weights,mode,flags=None):
"""make sure that probability mass in linear interpolation is 1
for weighted counts, weight of first model is set to 1
"""
if mode == 'interpolate' or mode == 'loglinear':
if type(weights[0]) == list:
new_weights = []
for weight_list in weights:
total = sum(weight_list)
try:
weight_list = [weight/total for weight in weight_list]
except ZeroDivisionError:
sys.stderr.write('Error: Zero division in weight normalization. Are some of your weights zero? This might lead to undefined behaviour if a phrase pair is only seen in model with weight 0\n')
new_weights.append(weight_list)
else:
total = sum(weights)
try:
new_weights = [weight/total for weight in weights]
except ZeroDivisionError:
sys.stderr.write('Error: Zero division in weight normalization. Are some of your weights zero? This might lead to undefined behaviour if a phrase pair is only seen in model with weight 0\n')
elif mode == 'counts_pure':
if type(weights[0]) == list:
new_weights = []
for weight_list in weights:
ratio = 1/weight_list[0]
new_weights.append([weight * ratio for weight in weight_list])
else:
ratio = 1/weights[0]
new_weights = [weight * ratio for weight in weights]
# make sure that features other than the standard Moses features are always interpolated (since no count-based computation is defined)
elif mode == 'counts':
if type(weights[0]) == list:
norm_counts = normalize_weights(weights,'counts_pure')
new_weights = normalize_weights(weights,'interpolate')
for i in [flags['i_e2f'],flags['i_e2f_lex'],flags['i_f2e'],flags['i_f2e_lex']]:
new_weights[i] = norm_counts[i]
return new_weights
else:
return normalize_weights(weights,'counts_pure')
return new_weights
def handle_file(filename,action,fileobj=None,mode='r'):
"""support reading/writing either from/to file, stdout or gzipped file"""
if action == 'open':
if mode == 'r':
mode = 'rb'
elif mode == 'w':
mode = 'wb'
if mode == 'rb' and not filename == '-' and not os.path.exists(filename):
if os.path.exists(filename+'.gz'):
filename = filename+'.gz'
else:
sys.stderr.write('Error: unable to open file. ' + filename + ' - aborting.\n')
if 'counts' in filename and os.path.exists(os.path.dirname(filename)):
sys.stderr.write('For a weighted counts combination, we need statistics that Moses doesn\'t write to disk by default.\n')
sys.stderr.write('Repeat step 4 of Moses training for all models with the option -write-lexical-counts.\n')
exit(1)
if filename.endswith('.gz'):
fileobj = gzip.open(filename,mode)
elif filename == '-' and mode == 'wb':
fileobj = sys.stdout
else:
fileobj = open(filename,mode)
return fileobj
elif action == 'close' and filename != '-':
fileobj.close()
def sort_file(filename,tempdir=None):
"""Sort a file and return temporary file"""
cmd = ['sort', filename]
env = {}
env['LC_ALL'] = 'C'
if tempdir:
cmd.extend(['-T',tempdir])
outfile = NamedTemporaryFile(delete=False,dir=tempdir)
sys.stderr.write('LC_ALL=C ' + ' '.join(cmd) + ' > ' + outfile.name + '\n')
p = Popen(cmd,env=env,stdout=outfile.file)
p.wait()
outfile.seek(0)
return outfile
class Combine_TMs():
"""This class handles the various options, checks them for sanity and has methods that define what models to load and what functions to call for the different tasks.
Typically, you only need to interact with this class and its attributes.
"""
#some flags that change the behaviour during scoring. See init docstring for more info
flags = {'normalized':False,
'recompute_lexweights':False,
'intersected_cross-entropies':False,
'normalize_s_given_t':None,
'normalize-lexical_weights':True,
'add_origin_features':False,
'write_phrase_penalty':False,
'lowmem': False,
'i_e2f':0,
'i_e2f_lex':1,
'i_f2e':2,
'i_f2e_lex':3
}
# each model needs a priority. See init docstring for more info
_priorities = {'primary':1,
'map':2,
'supplementary':10}
def __init__(self,models,weights=None,
output_file=None,
mode='interpolate',
number_of_features=4,
model_interface=Moses,
reference_interface=Moses_Alignment,
reference_file=None,
lang_src=None,
lang_target=None,
output_lexical=None,
**flags):
"""The whole configuration of the task is done during intialization. Afterwards, you only need to call your intended method(s).
You can change some of the class attributes afterwards (such as the weights, or the output file), but you should never change the models or mode after initialization.
See unit_test function for example configurations
models: list of tuples (path,priority) that defines which models to process. Path is usually the top directory of a Moses model. There are three priorities:
'primary': phrase pairs with this priority will always be included in output model. For most purposes, you'll want to define all models as primary.
'map': for maximum a-posteriori combination (Bacchiani et al. 2004; Foster et al. 2010). for use with mode 'counts'. stores c(t) = 1 and c(s,t) = p(s|t)
'supplementary': phrase pairs are considered for probability computation, but not included in output model (unless they also occur in at least one primary model)
useful for rescoring a model without changing its vocabulary.
weights: accept two types of weight declarations: one weight per model, and one weight per model and feature
type | |
'clf__bootstrap': [True, False],
'clf__max_depth': [int(x) for x in np.linspace(10, 110, num= 11)],
'clf__min_samples_leaf': [1, 2, 4],
'clf__max_features': ['sqrt', 'auto'],
'clf__min_samples_split': [2, 5, 10],
'clf__class_weight': ['balanced', None],
'clf__random_state': [9999]}
clf = RandomizedSearchCV(pipe,
et_grid,
cv = cv,
n_iter = n_iter,
scoring = scoring,
n_jobs = -1,
random_state = 9999)
clf.fit(X_train, y_train)
end = time()
time_elapsed = end - start
print('\nThe best {}-fold cross valdiation score is {:.4f}.'.format(cv, clf.best_score_))
print('The best parameters are:\n', clf.best_estimator_.get_params()['clf'])
print('Training took {:.0f}m {:.0f}s.'.format(time_elapsed//60, time_elapsed % 60))
return clf
elif 'log' in selected_model.get_params().values():
start = time()
pipe = skl_pipeline([('Standardization', FunctionTransformer(standardize)), ('clf', selected_model)])
log_grid = {'clf__loss': ['log'],
'clf__penalty': ['l2', 'l1', 'elasticnet'],
'clf__alpha': [0.01, 0.001, 0.0001],
'clf__max_iter': [1000, 5000],
'clf__class_weight': ['balanced', None],
'clf__random_state': [9999]}
clf = RandomizedSearchCV(pipe,
log_grid,
cv = cv,
n_iter = n_iter,
scoring = scoring,
n_jobs = -1,
random_state = 9999)
clf.fit(X_train, y_train)
end = time()
time_elapsed = end - start
print('\nThe best {}-fold cross valdiation score is {:.4f}.'.format(cv, clf.best_score_))
print('The best parameters are:\n', clf.best_estimator_.get_params()['clf'])
print('Training took {:.0f}m {:.0f}s.'.format(time_elapsed//60, time_elapsed % 60))
return clf
elif resample_method == 'smote_tomek':
if selected_model.__class__.__name__ == 'GradientBoostingClassifier':
start = time()
pipe = imbl_pipeline([('Standardization', FunctionTransformer(standardize)), ('SMOTETOMEK', SMOTETomek()), ('clf', selected_model)])
gb_grid = {'clf__n_estimators': [int(x) for x in np.linspace(start = 100, stop = 1000, num = 10)],
'clf__subsample': [0.7, 0.8],
'clf__learning_rate': [0.001, 0.01, 0.1],
'clf__max_depth': [int(x) for x in np.linspace(10, 110, num = 11)],
'clf__max_features': ['sqrt', 'log2'],
'clf__min_samples_split': [2, 5, 10],
'clf__min_samples_leaf': [1, 2, 4],
'clf__loss': ['deviance'],
'clf__random_state': [9999],
'SMOTETOMEK__random_state': [9999]}
clf = RandomizedSearchCV(pipe,
gb_grid,
cv = cv,
n_iter = n_iter,
scoring = scoring,
n_jobs = -1,
random_state = 9999)
clf.fit(X_train, y_train)
end = time()
time_elapsed = end - start
print('\nThe best {}-fold cross valdiation score is {:.4f}.'.format(cv, clf.best_score_))
print('The best parameters are:\n', clf.best_estimator_.get_params()['clf'])
print('Training took {:.0f}m {:.0f}s.'.format(time_elapsed//60, time_elapsed % 60))
return clf
elif selected_model.__class__.__name__ == 'RandomForestClassifier':
start = time()
pipe = imbl_pipeline([('Standardization', FunctionTransformer(standardize)), ('SMOTETOMEK', SMOTETomek()), ('clf', selected_model)])
rf_grid = {'clf__n_estimators': [int(x) for x in np.linspace(start = 100, stop = 1000, num = 10)],
'clf__max_depth': [int(x) for x in np.linspace(10, 110, num= 11)],
'clf__max_features': ['sqrt', 'auto'],
'clf__min_samples_leaf': [1, 2, 4],
'clf__min_samples_split': [2, 5, 10],
'clf__bootstrap': [True],
'clf__class_weight': ['balanced', None],
'clf__random_state': [9999],
'SMOTETOMEK__random_state': [9999]}
clf = RandomizedSearchCV(pipe,
rf_grid,
cv = cv,
n_iter = n_iter,
scoring = scoring,
n_jobs = -1,
random_state = 9999)
clf.fit(X_train, y_train)
end = time()
time_elapsed = end - start
print('\nThe best {}-fold cross valdiation score is {:.4f}.'.format(cv, clf.best_score_))
print('The best parameters are:\n', clf.best_estimator_.get_params()['clf'])
print('Training took {:.0f}m {:.0f}s.'.format(time_elapsed//60, time_elapsed % 60))
return clf
elif selected_model.__class__.__name__ == 'DecisionTreeClassifier':
start = time()
pipe = imbl_pipeline([('Standardization', FunctionTransformer(standardize)), ('SMOTETOMEK', SMOTETomek()), ('clf', selected_model)])
dt_grid = {'clf__criterion': ['gini'],
'clf__splitter': ['best', 'random'],
'clf__max_depth': [int(x) for x in np.linspace(10, 110, num= 11)],
'clf__min_samples_leaf': [1, 2, 4],
'clf__max_features': ['sqrt', 'auto'],
'clf__min_samples_split': [2, 5, 10],
'clf__class_weight': ['balanced', None],
'clf__random_state': [9999],
'SMOTETOMEK__random_state': [9999]}
clf = RandomizedSearchCV(pipe,
dt_grid,
cv = cv,
n_iter = n_iter,
scoring = scoring,
n_jobs = -1,
random_state = 9999)
clf.fit(X_train, y_train)
end = time()
time_elapsed = end - start
print('\nThe best {}-fold cross valdiation score is {:.4f}.'.format(cv, clf.best_score_))
print('The best parameters are:\n', clf.best_estimator_.get_params()['clf'])
print('Training took {:.0f}m {:.0f}s.'.format(time_elapsed//60, time_elapsed % 60))
return clf
elif selected_model.__class__.__name__ == 'ExtraTreesClassifier':
start = time()
pipe = imbl_pipeline([('Standardization', FunctionTransformer(standardize)), ('SMOTETOMEK', SMOTETomek()), ('clf', selected_model)])
et_grid = {'clf__criterion': ['gini'],
'clf__n_estimators': [int(x) for x in np.linspace(start = 100, stop = 1000, num = 10)],
'clf__bootstrap': [True, False],
'clf__max_depth': [int(x) for x in np.linspace(10, 110, num= 11)],
'clf__min_samples_leaf': [1, 2, 4],
'clf__max_features': ['sqrt', 'auto'],
'clf__min_samples_split': [2, 5, 10],
'clf__class_weight': ['balanced', None],
'clf__random_state': [9999]}
clf = RandomizedSearchCV(pipe,
et_grid,
cv = cv,
n_iter = n_iter,
scoring = scoring,
n_jobs = -1,
random_state = 9999)
clf.fit(X_train, y_train)
end = time()
time_elapsed = end - start
print('\nThe best {}-fold cross valdiation score is {:.4f}.'.format(cv, clf.best_score_))
print('The best parameters are:\n', clf.best_estimator_.get_params()['clf'])
print('Training took {:.0f}m {:.0f}s.'.format(time_elapsed//60, time_elapsed % 60))
return clf
elif 'log' in selected_model.get_params().values():
start = time()
pipe = imbl_pipeline([('Standardization', FunctionTransformer(standardize)), ('SMOTETOMEK', SMOTETomek()), ('clf', selected_model)])
log_grid = {'clf__loss': ['log'],
'clf__penalty': ['l2', 'l1', 'elasticnet'],
'clf__alpha': [0.01, 0.001, 0.0001],
'clf__max_iter': [1000, 5000],
'clf__class_weight': ['balanced', None],
'clf__random_state': [9999],
'SMOTETOMEK__random_state': [9999]}
clf = RandomizedSearchCV(pipe,
log_grid,
cv = cv,
n_iter = n_iter,
scoring = scoring,
n_jobs = -1,
random_state = 9999)
clf.fit(X_train, y_train)
end = time()
time_elapsed = end - start
print('\nThe best {}-fold cross valdiation score is {:.4f}.'.format(cv, clf.best_score_))
print('The best parameters are:\n', clf.best_estimator_.get_params()['clf'])
print('Training took {:.0f}m {:.0f}s.'.format(time_elapsed//60, time_elapsed % 60))
return clf
elif resample_method == 'smote_enn':
if selected_model.__class__.__name__ == 'GradientBoostingClassifier':
start = time()
pipe = imbl_pipeline([('Standardization', FunctionTransformer(standardize)), ('SMOTENN', SMOTEENN()), ('clf', selected_model)])
gb_grid = {'clf__n_estimators': [int(x) for x in np.linspace(start = 100, stop = 1000, num = 10)],
'clf__subsample': [0.7, 0.8],
'clf__learning_rate': [0.001, 0.01, 0.1],
'clf__max_depth': [int(x) for x in np.linspace(10, 110, num = 11)],
'clf__max_features': ['sqrt', 'log2'],
'clf__min_samples_split': [2, 5, 10],
'clf__min_samples_leaf': [1, 2, 4],
'clf__loss': ['deviance'],
'clf__random_state': [9999],
'SMOTENN__random_state': [9999]}
clf = RandomizedSearchCV(pipe,
gb_grid,
cv = cv,
n_iter = n_iter,
scoring = scoring,
n_jobs = -1,
random_state = 9999)
clf.fit(X_train, y_train)
end = time()
time_elapsed = end - start
print('\nThe best {}-fold cross valdiation score is {:.4f}.'.format(cv, clf.best_score_))
print('The best parameters are:\n', clf.best_estimator_.get_params()['clf'])
print('Training took {:.0f}m {:.0f}s.'.format(time_elapsed//60, time_elapsed % 60))
return clf
elif selected_model.__class__.__name__ == 'RandomForestClassifier':
start = time()
pipe = imbl_pipeline([('Standardization', FunctionTransformer(standardize)), ('SMOTENN', SMOTEENN()), ('clf', selected_model)])
rf_grid = {'clf__n_estimators': [int(x) for x in np.linspace(start = 100, stop = 1000, num = 10)],
'clf__max_depth': [int(x) for x in np.linspace(10, 110, num= 11)],
'clf__max_features': ['sqrt', 'auto'],
'clf__min_samples_leaf': [1, 2, 4],
'clf__min_samples_split': [2, 5, 10],
'clf__bootstrap': [True],
'clf__class_weight': ['balanced', None],
'clf__random_state': [9999],
'SMOTENN__random_state': [9999]}
clf = RandomizedSearchCV(pipe,
rf_grid,
cv = cv,
n_iter = n_iter,
scoring = scoring,
n_jobs = -1,
random_state = 9999)
clf.fit(X_train, y_train)
end = time()
time_elapsed = end - start
print('\nThe best {}-fold cross valdiation score is {:.4f}.'.format(cv, clf.best_score_))
print('The best parameters are:\n', clf.best_estimator_.get_params()['clf'])
print('Training took {:.0f}m {:.0f}s.'.format(time_elapsed//60, time_elapsed % 60))
return clf
elif selected_model.__class__.__name__ == 'DecisionTreeClassifier':
start = time()
pipe = imbl_pipeline([('Standardization', FunctionTransformer(standardize)), ('SMOTENN', SMOTEENN()), ('clf', selected_model)])
dt_grid = {'clf__criterion': ['gini'],
'clf__splitter': ['best', 'random'],
'clf__max_depth': [int(x) for x in np.linspace(10, 110, num= 11)],
'clf__min_samples_leaf': [1, 2, 4],
'clf__max_features': ['sqrt', 'auto'],
'clf__min_samples_split': [2, 5, 10],
'clf__class_weight': ['balanced', None],
'clf__random_state': [9999],
'SMOTENN__random_state': [9999]}
clf = RandomizedSearchCV(pipe,
dt_grid,
cv = cv,
n_iter = n_iter,
scoring = scoring,
n_jobs = -1,
random_state = 9999)
clf.fit(X_train, y_train)
end = time()
time_elapsed = end - start
print('\nThe best {}-fold cross valdiation score is {:.4f}.'.format(cv, clf.best_score_))
print('The best parameters are:\n', clf.best_estimator_.get_params()['clf'])
print('Training took {:.0f}m {:.0f}s.'.format(time_elapsed//60, time_elapsed % 60))
return clf
elif selected_model.__class__.__name__ == 'ExtraTreesClassifier':
start = time()
pipe = imbl_pipeline([('Standardization', FunctionTransformer(standardize)), ('SMOTENN', SMOTEENN()), ('clf', selected_model)])
et_grid = {'clf__criterion': ['gini'],
'clf__n_estimators': [int(x) for x in np.linspace(start = 100, stop = 1000, num = 10)],
'clf__bootstrap': [True, False],
'clf__max_depth': [int(x) for x in np.linspace(10, 110, num= 11)],
'clf__min_samples_leaf': [1, 2, 4],
'clf__max_features': ['sqrt', 'auto'],
'clf__min_samples_split': [2, 5, 10],
'clf__class_weight': ['balanced', None],
'clf__random_state': [9999]}
clf = RandomizedSearchCV(pipe,
et_grid,
cv = cv,
n_iter = n_iter,
scoring = scoring,
n_jobs = -1,
random_state = 9999)
clf.fit(X_train, y_train)
end = time()
time_elapsed = end - start
print('\nThe best {}-fold cross valdiation score is {:.4f}.'.format(cv, clf.best_score_))
print('The best parameters are:\n', clf.best_estimator_.get_params()['clf'])
print('Training took {:.0f}m {:.0f}s.'.format(time_elapsed//60, time_elapsed % 60))
return clf
elif 'log' in selected_model.get_params().values():
start = time()
pipe = imbl_pipeline([('Standardization', FunctionTransformer(standardize)), ('SMOTENN', SMOTEENN()), ('clf', selected_model)])
log_grid = {'clf__loss': ['log'],
'clf__penalty': ['l2', 'l1', 'elasticnet'],
'clf__alpha': [0.01, 0.001, 0.0001],
'clf__max_iter': [1000, 5000],
'clf__class_weight': ['balanced', None],
'clf__random_state': [9999],
'SMOTENN__random_state': [9999]}
clf = RandomizedSearchCV(pipe,
log_grid,
cv = cv,
n_iter = n_iter,
scoring = scoring,
n_jobs = -1,
random_state = 9999)
clf.fit(X_train, y_train)
end = time()
time_elapsed = end - start
print('\nThe best {}-fold cross valdiation score is {:.4f}.'.format(cv, clf.best_score_))
print('The | |
<filename>d2lzh_pytorch/train.py<gh_stars>0
from d2lzh_pytorch import linear_reg, data_process, rnn,plot
import time
import torch
import torch.nn as nn
import numpy as np
import math
def train_ch3(net, train_iter, test_iter, loss, num_epochs, batch_size,
params=None, lr=None, optimizer=None):
"""
The training function of chapter3, it is a more useful function.
In Chapter3_6, it is used to train the softmax regconition.
Parameters
----------
net : [function]
input X and get y_hat, the main learning program
train_iter : [producer]
the train dataset
test_iter : [producer]
the test dataset
loss : [function]
input y and y_hat, get loss value
num_epochs : [int]
how many times do you want to learn through the whole training dataset?
batch_size : [int]
size of the batch
params : [tensor], optional
the weight and bias combine to be the params tensor, by default None
lr : [float], optional
learning rate, by default None
optimizer : [function], optional
the function to decrease the gradient, if you have a optimizer, you
don't need to input the params and lr before but input them directly
to the optimizer, by default None
"""
for e in range(num_epochs):
# init
train_loss_sum, train_acc_sum, n = 0.0, 0.0, 0
for X, y in train_iter:
y_hat = net(X)
l = loss(y_hat, y).sum()
# depend on whether you have a optimizer
# clean the grad of params
if optimizer is not None:
optimizer.zero_grad()
elif params is not None and params[0].grad is not None:
for p in params:
p.grad.data.zero_()
l.backward()
# the function to decrease the gradient
if optimizer is None:
linear_reg.sgd(params, lr, batch_size)
else:
optimizer.step()
# gain the loss and acc value of each iter
train_loss_sum += l.item()
train_acc_sum += (y_hat.argmax(dim=1) == y).float().sum().item()
n += y.shape[0]
# use those value stored in iter to gain the final value of every epochs
test_acc = data_process.evaluate_accuracy(test_iter, net)
print('epoch %d, loss %.3f, train acc %.3f, test acc %.3f' %
(e+1, train_loss_sum/n, train_acc_sum/n, test_acc))
def train_ch5(net, train_iter, test_iter, batch_size, optimizer,
device, num_epochs):
"""
The new version of training function, it contain the device selection and
became a fully module function, better than train_ch3.
Parameters
----------
net : [module]
the net that want to apply
train_iter : [producer]
the train dataset
test_iter : [producer]
the test dataset
batch_size : [int]
size of the batch
optimizer : [function]
the function to decrease the gradient
device : [device]
the device want to run on
num_epochs : [int]
how many times do you want to learn through the whole training dataset?
"""
# apply the net on target device
net = net.to(device)
print('training on:', device)
loss = torch.nn.CrossEntropyLoss()
for e in range(num_epochs):
batch_count = 0
train_l_sum, train_acc_sum, n, start = 0.0, 0.0, 0, time.time()
for X, y in train_iter:
# apply datas to target device
X = X.to(device)
y = y.to(device)
y_hat = net(X)
l = loss(y_hat, y)
optimizer.zero_grad()
l.backward()
optimizer.step()
# for some elements not on GPU should move to CPU for calculation
train_l_sum += l.cpu().item()
train_acc_sum += ((y_hat.argmax(dim=1) == y).sum().cpu().item())
n += y.shape[0]
batch_count += 1
# use those value stored in iter to gain the final value of every epochs
test_acc = data_process.evaluate_accuracy(test_iter, net)
print('epoch %d, loss %.3f, train acc %.3f, test acc %.3f,time %.1f sec' %
(e+1, train_l_sum/batch_count, train_acc_sum/n, test_acc, time.time()-start))
def train_and_predict_rnn(RNN, get_params, init_rnn_state, num_hiddens,
vocab_size, device, corpus_indices, idx_to_char,
char_to_idx, is_random_iter, num_epochs, num_steps,
lr, clipping_theta, batch_size, pred_period,
pred_len, prefixes):
"""
Train and predict a sequence with a function building step by step called RNN
Parameters
----------
RNN : [function]
the recycle neural network
get_params : [function]
the function that can return network's init params
init_rnn_state : [tuple]
network's start time state
num_hiddens : [int]
how many hidden parameters you want to add
vocab_size : [int]
the number of non-repeating character in this vocab
device : [device]
device you want to run on
corpus_indices : [tensor]
the index formation of input data
idx_to_char : [tensor]
index to character map
char_to_idx : [tet]
how many epoch would print a prediction
pred_len : [int]
the number of characters you want to predict
prefixes : [string]
the start characters of these character sequencesnsor]
character to index map
is_random_iter : [bool]
choose the iter's type
num_epochs : [int]
number of epochs
num_steps : [int]
number of time steps
lr : [float]
learning rate
clipping_theta : [float]
use to be a threshold of gradients division
batch_size : [int]
how many times a batch would contain
pred_period : [int]
how many epoch would print a prediction
pred_len : [int]
the number of characters you want to predict
prefixes : [string]
the start characters of these character sequences
"""
# choose which function to load data
if is_random_iter:
data_iter_fn = data_process.data_iter_random
else:
data_iter_fn = data_process.data_iter_consecutive
# get init params of network
params = get_params()
# use CrossEntropyLoss's exponent to be the perplexity
loss = nn.CrossEntropyLoss()
# repeat epoch times, to ensure a better result
for e in range(num_epochs):
# if it is not using random iter, init at the start of an epoch
if not is_random_iter:
state = init_rnn_state(batch_size, num_hiddens, device)
l_sum, n, start = 0.0, 0, time.time()
data_iter = data_iter_fn(corpus_indices, batch_size, num_steps, device)
# load a batch of pair of data at a time from data_iter
# this loop will loading data by time-step, one loop one step
for X, Y in data_iter:
if is_random_iter:
# random_iter should re-init in every step calls
state = init_rnn_state(batch_size, num_hiddens, device)
else:
# else we just need to detach it's state, in case the gradient
# compution cost too much time
for s in state:
s.detach_()
# pretreat our datas, get (batch_size ,vocab_size)
inputs = rnn.to_onehot(X, vocab_size)
# put it into RNN and get its output and new state
# outputs will has num_steps (batch_size, vocal_size) matrixes
# here you can see that inputs is totally new, state may be old
outputs, state = RNN(inputs, state, params)
# cat outputs to be (num_steps*batch_size, vocal_size)
outputs = torch.cat(outputs, dim=0)
# make y be (batch*num_steps), y is the gt answer
y = torch.transpose(Y, 0, 1).contiguous().view(-1)
# compute the loss
l = loss(outputs, y.long())
# set gradient to be zero
if params[0].grad is not None:
for p in params:
p.grad.data.zero_()
# then backpropagate the gradient
l.backward()
# clip gradient
rnn.grad_clipping(params, clipping_theta, device)
# decent it
linear_reg.sgd(params, lr, 1)
# cal the whole loss
l_sum += l.item()*y.shape[0]
n += y.shape[0]
# print some result
if (e+1) % pred_period == 0:
# use exp to cal perplexity here
print('epoch %d, perplexity %f, time %.2f sec' %
(e + 1, math.exp(l_sum / n), time.time() - start))
# print some prediction here
for prefix in prefixes:
print(' -', rnn.predict_rnn(prefix, pred_len, RNN, params,
init_rnn_state, num_hiddens,
vocab_size, device, idx_to_char,
char_to_idx))
def train_and_predict_rnn_pytorch(model, num_hiddens, vocab_size, device,
corpus_indices, idx_to_char, char_to_idx,
num_epochs, num_steps, lr, clipping_theta,
batch_size, pred_period, pred_len, prefixes):
"""
Train the net which is constructed by pytorch module and predict strings
Parameters
----------
model : [function]
the recycle neural network
num_hiddens : [function]
the recycle neural network
vocab_size : [int]
the number of non-repeating character in this vocab
device : [device]
device you want to run on
corpus_indices : [tensor]
the index formation of input data
idx_to_char : [tensor]
index to character map
char_to_idx : [tet]
how many epoch would print a prediction
num_epochs : [int]
number of epochs
num_steps : [int]
number of time steps
lr : [float]
learning rate
clipping_theta : [float]
use to be a threshold of gradients division
batch_size : [int]
how many times a batch would contain
pred_period : [int]
how many epoch would print a prediction
pred_len : [int]
the number of characters you want to predict
prefixes : [string]
the start characters of these character sequences
"""
# init
loss = nn.CrossEntropyLoss()
optimizer=torch.optim.Adam(model.parameters(),lr=lr)
model.to(device)
state=None
# repeat epoch times, to ensure a better result
for e in range(num_epochs):
l_sum, n, start = 0.0, 0, time.time()
# here only use the consecutive version
data_iter = data_process.data_iter_consecutive(
corpus_indices, | |
:, 2 * nr_mix:3 * nr_mix])
# here and below: getting the means and adjusting them based on preceding
# sub-pixels
x = tf.reshape(x, xs + [1]) + tf.zeros(xs + [nr_mix])
m2 = tf.reshape(means[:, :, :, 1, :] + coeffs[:, :, :, 0, :]
* x[:, :, :, 0, :], [xs[0], xs[1], xs[2], 1, nr_mix])
m3 = tf.reshape(means[:, :, :, 2, :] + coeffs[:, :, :, 1, :] * x[:, :, :, 0, :] +
coeffs[:, :, :, 2, :] * x[:, :, :, 1, :], [xs[0], xs[1], xs[2], 1, nr_mix])
means = tf.concat([tf.reshape(means[:, :, :, 0, :], [
xs[0], xs[1], xs[2], 1, nr_mix]), m2, m3], 3)
centered_x = x - means
inv_stdv = tf.exp(-log_scales)
plus_in = inv_stdv * (centered_x + 0.5)#1. / buckets)
cdf_plus = tf.nn.sigmoid(plus_in)
min_in = inv_stdv * (centered_x - 0.5)#1. / buckets)
cdf_min = tf.nn.sigmoid(min_in)
# log probability for edge case of 0 (before scaling)
log_cdf_plus = plus_in - tf.nn.softplus(plus_in)
# log probability for edge case of 255 (before scaling)
log_one_minus_cdf_min = -tf.nn.softplus(min_in)
cdf_delta = cdf_plus - cdf_min # probability for all other cases
mid_in = inv_stdv * centered_x
# log probability in the center of the bin, to be used in extreme cases
# (not actually used in our code)
log_pdf_mid = mid_in - log_scales - 2. * tf.nn.softplus(mid_in)
# now select the right output: left edge case, right edge case, normal
# case, extremely low prob case (doesn't actually happen for us)
# this is what we are really doing, but using the robust version below for extreme cases in other applications and to avoid NaN issue with tf.select()
# log_probs = tf.select(x < -0.999, log_cdf_plus, tf.select(x > 0.999, log_one_minus_cdf_min, tf.log(cdf_delta)))
# robust version, that still works if probabilities are below 1e-5 (which never happens in our code)
# tensorflow backpropagates through tf.select() by multiplying with zero instead of selecting: this requires use to use some ugly tricks to avoid potential NaNs
# the 1e-12 in tf.maximum(cdf_delta, 1e-12) is never actually used as output, it's purely there to get around the tf.select() gradient issue
# if the probability on a sub-pixel is below 1e-5, we use an approximation
# based on the assumption that the log-density is constant in the bin of
# the observed sub-pixel value
#log_probs = tf.where(x < -0.999, log_cdf_plus, tf.where(x > 0.999, log_one_minus_cdf_min, tf.where(cdf_delta > 1e-5, tf.log(tf.maximum(cdf_delta, 1e-12)), log_pdf_mid - np.log(buckets / 2))))
log_probs = tf.log(tf.maximum(cdf_delta, 1e-12))
log_probs = tf.reduce_sum(log_probs, 3) + log_prob_from_logits(logit_probs)
if sum_all:
return [-tf.reduce_mean(log_sum_exp(log_probs))]
else:
return [-tf.reduce_mean(log_sum_exp(log_probs), [1, 2])]
def flex_2loss_normed(outputs, gpu_id, min_particle_distance, alpha=0.5, **kwargs):
# norm loss ranges
value_ranges = 27.60602188 / np.array([
18.73734856, 4.05035114, 27.60602188, 0.7037037,
7.97082663, 3.00816584, 9.01172256]).astype(np.float32) / 10
# next state loss
gt_next_state = outputs['full_grids'][:,1,:,:,:,0:outputs['n_states']]
pred_next_state = outputs['pred_grid']
next_state_mask = tf.not_equal(outputs['full_grids'][:,1,:,:,:,14], 0)
next_state_loss = (tf.boolean_mask(
(pred_next_state - gt_next_state) / tf.reshape(value_ranges, [1,1,1,1,7]),
next_state_mask) ** 2) / 2
# next vel loss
gt_next_vel = outputs['next_velocity']
pred_next_vel = outputs['pred_velocity']
mask = tf.not_equal(outputs['full_grids'][:,0,:,:,:,14], 0)
next_vel_loss = (tf.boolean_mask(
(pred_next_vel - gt_next_vel) / tf.reshape(value_ranges[4:7], [1,1,1,1,3]),
mask) ** 2) / 2
# total loss
total_loss = alpha * tf.reduce_mean(next_vel_loss) + \
(1 - alpha) * tf.reduce_mean(next_state_loss)
# predict mask loss
if outputs['predict_mask']:
pred_mask = outputs['pred_mask']
mask_loss = tf.nn.sparse_softmax_cross_entropy_with_logits(
labels=tf.cast(next_state_mask, tf.int32), logits=pred_mask)
total_loss = total_loss + (1 - alpha) * tf.reduce_mean(mask_loss)
return[total_loss]
def flex_2loss(outputs, gpu_id, min_particle_distance, alpha=0.5, **kwargs):
gt_next_state = outputs['full_grids'][:,1,:,:,:,0:outputs['n_states']]
pred_next_state = outputs['pred_grid']
next_state_mask = tf.not_equal(outputs['full_grids'][:,1,:,:,:,14], 0)
next_state_loss = (tf.boolean_mask(pred_next_state - gt_next_state, next_state_mask) ** 2) / 2
gt_next_vel = outputs['next_velocity']
pred_next_vel = outputs['pred_velocity']
mask = tf.not_equal(outputs['full_grids'][:,0,:,:,:,14], 0)
next_vel_loss = (tf.boolean_mask(pred_next_vel - gt_next_vel, mask) ** 2) / 2
total_loss = alpha * tf.reduce_mean(next_vel_loss) + \
(1 - alpha) * tf.reduce_mean(next_state_loss)
return[total_loss]
def flex_next_state_loss(outputs, gpu_id, min_particle_distance,
use_dialation=False, **kwargs):
rot_states = tf.split(outputs['full_grids'], outputs['num_rotations'], axis=len(outputs['full_grids'].get_shape().as_list())-1)
gt_next_states = [gt[:,outputs['time_steps'],:,:,:,0:outputs['n_states']] for gt in rot_states]
pred_next_states = tf.split(outputs['pred_grid'], outputs['num_rotations'], axis=len(outputs['pred_grid'].get_shape().as_list())-1)
masks = [tf.not_equal(m[:,outputs['time_steps'],:,:,:,14], 0) for m in rot_states]
if use_dialation:
# dialate masks
dialation_radius = 3
dialation_kernel = tf.ones(
[dialation_radius,dialation_radius,dialation_radius,1,1],
dtype=tf.float32)
masks = [tf.squeeze(tf.cast(tf.minimum(tf.nn.conv3d(
tf.expand_dims(tf.cast(mask, tf.float32), axis=-1), dialation_kernel,
strides=[1,1,1,1,1], padding='SAME'), 1), tf.bool)) for mask in masks]
losses = []
for (pred_next_state, gt_next_state, mask) in zip(pred_next_states, gt_next_states, masks):
loss = (tf.boolean_mask(pred_next_state - gt_next_state, mask) ** 2) / 2
losses.append(tf.reduce_mean(loss))
losses = tf.stack(losses, axis=-1)
#loss = tf.reduce_sum(loss, axis=-1)
return [tf.reduce_mean(losses)]
def flex_loss(outputs, gpu_id, min_particle_distance, **kwargs):
gt_next_vel = outputs['next_velocity']
pred_next_vel = outputs['pred_velocity']
mask = tf.not_equal(outputs['full_grids'][:,0,:,:,:,14], 0)
#loss = tf.nn.l2_loss(pred_next_vel - gt_next_vel)
loss = (tf.boolean_mask(pred_next_vel - gt_next_vel, mask) ** 2) / 2
#loss = tf.reduce_sum(loss, axis=-1)
return [tf.reduce_mean(loss)]
def particle_loss(outputs, gpu_id, min_particle_distance, **kwargs):
state = outputs['state']
positions = state[:,:,:,:,0:3]
next_vel = outputs['next_vel'][:,:,:,:,0:3]
pred_vel = outputs['pred_vel'][:,:,:,:,0:3]
relation_same = outputs['relation_same']
relation_solid = outputs['relation_solid']
# PRESERVE DISTANCE LOSS
# construct the pairwise distance calculation kernels
# pairwise distance kernel:
# depth height, width, in (x,y,z), out (right, bottom, front) distance
ks = 5
dim = 3
km = ks / 2
k3d = np.zeros([ks,ks,ks,dim,(ks*ks*ks-1)*dim])
# set x,y,z center to 1 and boundary -1
m = 0
for i in range(ks):
for j in range(ks):
for k in range(ks):
for l in range(dim):
if not(i == j == k == km):
k3d[i,j,k,l,m] = -1
k3d[km,km,km,l,m] = 1
m += 1
# determine distance between neighboring particles at time t
positions = [positions, positions + pred_vel]
distances = []
for i, pos in enumerate(positions):
distance = tf.nn.conv3d(pos, k3d, [1,1,1,1,1], "SAME")
distance *= distance
distance = tf.stack([tf.sqrt(tf.reduce_sum(dim, axis=-1)) for dim in \
tf.split(distance, (ks*ks*ks-1), axis=4)], axis=4)
distances.append(distance)
preserve_distance_loss = tf.reduce_sum((distances[1] - distances[0]) ** 2 \
* relation_same) / 2
# CONSERVATION OF MASS = MINIMUM DISTANCE BETWEEN PARTICLES HAS TO BE KEPT
# with mask to enforce only between solid particles and not between empty particles
mass_conservation_loss = tf.reduce_sum( \
tf.nn.relu(-distances[1]+min_particle_distance) * relation_solid)
# MSE VELOCITY LOSS
mse_velocity_loss = tf.nn.l2_loss(pred_vel - next_vel)
# MEAN OF BOTH LOSSES
loss = tf.reduce_mean(tf.stack([
mse_velocity_loss,
preserve_distance_loss,
mass_conservation_loss]))
return [loss]
def softmax_cross_entropy_loss_binary_jerk(outputs, gpu_id, **kwargs):
with tf.device('/gpu:%d' % gpu_id):
labels = tf.cast(tf.not_equal(
tf.norm(outputs['jerk_map'], ord='euclidean', axis=3), 0), tf.int32)
shape = outputs['pred'].get_shape().as_list()
assert shape[3] == 2
logits = outputs['pred']
undersample = False
if undersample:
thres = 0.5412
mask = tf.norm(outputs['jerk_all'], ord='euclidean', axis=2)
mask = tf.cast(tf.logical_or(tf.greater(mask[:,0], thres),
tf.greater(mask[:,1], thres)), tf.float32)
mask = tf.reshape(mask, [mask.get_shape().as_list()[0], 1, 1, 1])
else:
mask = 1
loss = tf.reduce_mean(tf.nn.sparse_softmax_cross_entropy_with_logits(
labels=labels, logits=logits) * mask)
return [loss]
def softmax_cross_entropy_loss_depth(outputs, gpu_id = 0, eps = 0.0,
min_value = -1.0, max_value = 1.0, num_classes=256,
segmented_jerk=True, **kwargs):
with tf.device('/gpu:%d' % gpu_id):
undersample = False
if undersample:
thres = 0.5412
mask = tf.norm(outputs['jerk_all'], ord='euclidean', axis=2)
mask = tf.cast(tf.logical_or(tf.greater(mask[:,0], thres),
tf.greater(mask[:,1], thres)), tf.float32)
mask = tf.reshape(mask, [mask.get_shape().as_list()[0], 1, 1, 1])
else:
mask = 1
shape = outputs['pred_next_vel_1'].get_shape().as_list()
assert shape[3] / 3 == num_classes
losses = []
# next depth losses
logits = outputs['next_moments'][0][0]
logits = tf.reshape(logits, shape[0:3] + [3, shape[3] / 3])
labels = tf.cast(outputs['depths_raw'][:,2], tf.int32)
loss = tf.reduce_mean(tf.nn.sparse_softmax_cross_entropy_with_logits(
labels=labels, logits=logits) * mask)
losses.append(loss)
assert len(losses) == 1, ('loss length: %d' % len(losses))
losses = tf.stack(losses)
return [tf.reduce_mean(losses)]
def softmax_cross_entropy_loss_vel_one(outputs, gpu_id = 0, eps = 0.0,
min_value = -1.0, max_value = 1.0, num_classes=256, use_relations_in_loss=False,
segmented_jerk=True, **kwargs):
with tf.device('/gpu:%d' % gpu_id):
undersample = False
if undersample:
thres = 0.5412
mask = tf.norm(outputs['jerk_all'], ord='euclidean', axis=2)
mask = tf.cast(tf.logical_or(tf.greater(mask[:,0], thres),
tf.greater(mask[:,1], thres)), tf.float32)
mask = tf.reshape(mask, [mask.get_shape().as_list()[0], 1, 1, 1])
else:
mask = 1
shape = outputs['pred_next_vel_1'].get_shape().as_list()
assert shape[3] / 3 == num_classes
losses = []
# next image losses
logits = outputs['next_images'][1][0]
logits = tf.reshape(logits, shape[0:3] + [3, shape[3] / 3])
labels = tf.cast(outputs['depths_raw'][:,2], tf.int32)
loss = tf.reduce_mean(tf.nn.sparse_softmax_cross_entropy_with_logits(
labels=labels, logits=logits) * mask)
losses.append(loss)
assert len(losses) == 1, ('loss length: %d' % len(losses))
losses = tf.stack(losses)
return [tf.reduce_mean(losses)]
def softmax_cross_entropy_loss_vel_all(outputs, gpu_id = 0, eps = 0.0,
min_value = -1.0, max_value = 1.0, num_classes=256, use_relations_in_loss=False, use_next_depth=True,
segmented_jerk=True, **kwargs):
debug = True
with tf.device('/gpu:%d' % gpu_id):
undersample = False
if undersample:
thres = 0.5412
mask = tf.norm(outputs['jerk_all'], ord='euclidean', axis=2)
mask = tf.cast(tf.logical_or(tf.greater(mask[:,0], thres),
tf.greater(mask[:,1], thres)), tf.float32)
mask = tf.reshape(mask, [mask.get_shape().as_list()[0], 1, 1, 1])
else:
mask = 1
shape = outputs['pred_next_vel_1'].get_shape().as_list()
assert shape[3] / 3 | |
<filename>mephisto/operations/supervisor.py
#!/usr/bin/env python3
# Copyright (c) Facebook, Inc. and its affiliates.
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
import threading
from queue import PriorityQueue, Empty
import time
from mephisto.data_model.packet import (
Packet,
PACKET_TYPE_ALIVE,
PACKET_TYPE_AGENT_ACTION,
PACKET_TYPE_NEW_AGENT,
PACKET_TYPE_NEW_WORKER,
PACKET_TYPE_REQUEST_AGENT_STATUS,
PACKET_TYPE_RETURN_AGENT_STATUS,
PACKET_TYPE_INIT_DATA,
PACKET_TYPE_GET_INIT_DATA,
PACKET_TYPE_PROVIDER_DETAILS,
PACKET_TYPE_SUBMIT_ONBOARDING,
PACKET_TYPE_REQUEST_ACTION,
PACKET_TYPE_UPDATE_AGENT_STATUS,
PACKET_TYPE_ERROR_LOG,
)
from mephisto.data_model.worker import Worker
from mephisto.data_model.qualification import worker_is_qualified
from mephisto.data_model.agent import Agent, OnboardingAgent
from mephisto.abstractions.blueprint import OnboardingRequired, AgentState
from mephisto.operations.registry import get_crowd_provider_from_type
from mephisto.abstractions.channel import Channel, STATUS_CHECK_TIME
from dataclasses import dataclass
from typing import Dict, Set, Optional, List, Any, Union, TYPE_CHECKING
if TYPE_CHECKING:
from mephisto.data_model.assignment import Assignment
from mephisto.data_model.unit import Unit
from mephisto.abstractions.database import MephistoDB
from mephisto.data_model.task_run import TaskRun
from mephisto.abstractions.blueprint import TaskRunner
from mephisto.abstractions.crowd_provider import CrowdProvider
from mephisto.abstractions.architect import Architect
from mephisto.operations.logger_core import get_logger
logger = get_logger(name=__name__, verbose=True, level="info")
# This class manages communications between the server
# and workers, ensures that their status is properly tracked,
# and also provides some helping utility functions for
# groups of workers or worker/agent compatibility.
# Mostly, the supervisor oversees the communications
# between jobs and workers over the channels
STATUS_TO_TEXT_MAP = {
AgentState.STATUS_EXPIRED: "This task is no longer available to be completed. "
"Please return it and try a different task",
AgentState.STATUS_TIMEOUT: "You took to long to respond to this task, and have timed out. "
"The task is no longer available, please return it.",
AgentState.STATUS_DISCONNECT: "You have disconnected from our server during the duration of the task. "
"If you have done substantial work, please reach out to see if we can recover it. ",
AgentState.STATUS_PARTNER_DISCONNECT: "One of your partners has disconnected while working on this task. We won't penalize "
"you for them leaving, so please submit this task as is.",
}
SYSTEM_CHANNEL_ID = "mephisto" # TODO pull from somewhere
START_DEATH_TIME = 10
# State storage
@dataclass
class Job:
architect: "Architect"
task_runner: "TaskRunner"
provider: "CrowdProvider"
qualifications: List[Dict[str, Any]]
registered_channel_ids: List[str]
@dataclass
class ChannelInfo:
channel_id: str
job: "Job"
channel: Channel
@dataclass
class AgentInfo:
agent: Union["Agent", "OnboardingAgent"]
used_channel_id: str
assignment_thread: Optional[threading.Thread] = None
class Supervisor:
def __init__(self, db: "MephistoDB"):
self.db = db
# Tracked state
self.agents: Dict[str, AgentInfo] = {}
self.agents_by_registration_id: Dict[str, AgentInfo] = {}
self.channels: Dict[str, ChannelInfo] = {}
# Map from onboarding id to agent request packet
self.onboarding_packets: Dict[str, Packet] = {}
# Agent status handling
self.last_status_check = time.time()
# Message handling
self.message_queue: List[Packet] = []
self.sending_thread: Optional[threading.Thread] = None
def _on_channel_open(self, channel_id: str):
"""Handler for what to do when a socket opens, we send an alive"""
channel_info = self.channels[channel_id]
self._send_alive(channel_info)
def _on_catastrophic_disconnect(self, channel_id):
# TODO(#102) Catastrophic disconnect needs to trigger cleanup
logger.error(f"Channel {channel_id} called on_catastrophic_disconnect")
def _on_channel_message(self, channel_id: str, packet: Packet):
"""Incoming message handler defers to the internal handler"""
try:
channel_info = self.channels[channel_id]
self._on_message(packet, channel_info)
except Exception as e:
# TODO(#93) better error handling about failed messages
logger.exception(
f"Channel {channel_id} encountered error on packet {packet}",
exc_info=True,
)
raise
def register_job(
self,
architect: "Architect",
task_runner: "TaskRunner",
provider: "CrowdProvider",
qualifications: Optional[List[Dict[str, Any]]] = None,
):
if qualifications is None:
qualifications = []
task_run = task_runner.task_run
channels = architect.get_channels(
self._on_channel_open,
self._on_catastrophic_disconnect,
self._on_channel_message,
)
job = Job(
architect=architect,
task_runner=task_runner,
provider=provider,
qualifications=qualifications,
registered_channel_ids=[],
)
for channel in channels:
channel_id = self.register_channel(channel, job)
job.registered_channel_ids.append(channel_id)
return job
def register_channel(self, channel: Channel, job: "Job") -> str:
"""Register the channel to the specific job"""
channel_id = channel.channel_id
channel_info = ChannelInfo(channel_id=channel_id, channel=channel, job=job)
self.channels[channel_id] = channel_info
channel.open()
self._send_alive(channel_info)
start_time = time.time()
while not channel.is_alive():
if time.time() - start_time > START_DEATH_TIME:
# TODO(OWN) Ask channel why it might have failed to connect?
self.channels[channel_id].channel.close()
raise ConnectionRefusedError( # noqa F821 we only support py3
"Was not able to establish a connection with the server, "
"please try to run again. If that fails,"
"please ensure that your local device has the correct SSL "
"certs installed."
)
try:
self._send_alive(channel_info)
except Exception:
pass
time.sleep(0.3)
return channel_id
def close_channel(self, channel_id: str):
"""Close the given channel by id"""
self.channels[channel_id].channel.close()
del self.channels[channel_id]
def shutdown_job(self, job: Job):
"""Close any channels related to a job"""
job_channels = job.registered_channel_ids
for channel_id in job_channels:
self.close_channel(channel_id)
def shutdown(self):
"""Close all of the channels, join threads"""
channels_to_close = list(self.channels.keys())
for channel_id in channels_to_close:
channel_info = self.channels[channel_id]
channel_info.job.task_runner.shutdown()
self.close_channel(channel_id)
if self.sending_thread is not None:
self.sending_thread.join()
for agent_info in self.agents.values():
assign_thread = agent_info.assignment_thread
if assign_thread is not None:
assign_thread.join()
def _send_alive(self, channel_info: ChannelInfo) -> bool:
logger.info("Sending alive")
return channel_info.channel.send(
Packet(
packet_type=PACKET_TYPE_ALIVE,
sender_id=SYSTEM_CHANNEL_ID,
receiver_id=channel_info.channel_id,
)
)
def _on_act(self, packet: Packet, channel_info: ChannelInfo):
"""Handle an action as sent from an agent"""
agent = self.agents[packet.sender_id].agent
# If the packet is_submit, and has files, we need to
# process downloading those files first
if packet.data.get("MEPHISTO_is_submit") is True:
data_files = packet.data.get("files")
if data_files is not None:
save_dir = agent.get_data_dir()
architect = channel_info.job.architect
for f_obj in data_files:
architect.download_file(f_obj["filename"], save_dir)
# TODO(OWN) Packets stored as info from workers can also be
# saved somewhere locally just in case the world dies, and
# then cleaned up once the world completes successfully
agent.pending_actions.append(packet)
agent.has_action.set()
def _on_submit_onboarding(self, packet: Packet, channel_info: ChannelInfo):
"""Handle the submission of onboarding data"""
onboarding_id = packet.sender_id
if onboarding_id not in self.agents:
logger.warning(
f"Onboarding agent {onboarding_id} already submitted or disconnected, "
f"but is calling _on_submit_onboarding again"
)
return
agent_info = self.agents[onboarding_id]
agent = agent_info.agent
# Update the request id for the original packet (which has the required
# registration data) to be the new submission packet (so that we answer
# back properly under the new request)
self.onboarding_packets[onboarding_id].data["request_id"] = packet.data[
"request_id"
]
del packet.data["request_id"]
assert isinstance(
agent, OnboardingAgent
), "Only onboarding agents should submit onboarding"
agent.pending_actions.append(packet)
agent.has_action.set()
self._register_agent_from_onboarding(agent_info)
logger.info(f"Onboarding agent {onboarding_id} registered out from onboarding")
del self.agents[onboarding_id]
del self.onboarding_packets[onboarding_id]
def _register_worker(self, packet: Packet, channel_info: ChannelInfo):
"""Process a worker registration packet to register a worker"""
crowd_data = packet.data["provider_data"]
crowd_provider = channel_info.job.provider
worker_name = crowd_data["worker_name"]
workers = self.db.find_workers(worker_name=worker_name)
if len(workers) == 0:
# TODO(WISH) get rid of sandbox designation
workers = self.db.find_workers(worker_name=worker_name + "_sandbox")
if len(workers) == 0:
worker = crowd_provider.WorkerClass.new_from_provider_data(
self.db, crowd_data
)
else:
worker = workers[0]
if not worker_is_qualified(worker, channel_info.job.qualifications):
self.message_queue.append(
Packet(
packet_type=PACKET_TYPE_PROVIDER_DETAILS,
sender_id=SYSTEM_CHANNEL_ID,
receiver_id=channel_info.channel_id,
data={"request_id": packet.data["request_id"], "worker_id": None},
)
)
else:
self.message_queue.append(
Packet(
packet_type=PACKET_TYPE_PROVIDER_DETAILS,
sender_id=SYSTEM_CHANNEL_ID,
receiver_id=channel_info.channel_id,
data={
"request_id": packet.data["request_id"],
"worker_id": worker.db_id,
},
)
)
def _launch_and_run_onboarding(
self, agent_info: "AgentInfo", task_runner: "TaskRunner"
):
"""Launch a thread to supervise the completion of onboarding for a task"""
tracked_agent = agent_info.agent
assert isinstance(tracked_agent, OnboardingAgent), (
"Can launch onboarding for OnboardingAgents, not Agents"
f", got {tracked_agent}"
)
try:
task_runner.launch_onboarding(tracked_agent)
except Exception as e:
import traceback
traceback.print_exc()
task_runner.cleanup_onboarding(tracked_agent)
finally:
if tracked_agent.get_status() not in [
AgentState.STATUS_WAITING,
AgentState.STATUS_APPROVED,
AgentState.STATUS_REJECTED,
]:
onboarding_id = tracked_agent.get_agent_id()
logger.info(
f"Onboarding agent {onboarding_id} disconnected or errored, "
f"final status {tracked_agent.get_status()}."
)
del self.agents[onboarding_id]
del self.onboarding_packets[onboarding_id]
def _launch_and_run_assignment(
self,
assignment: "Assignment",
agent_infos: List["AgentInfo"],
task_runner: "TaskRunner",
):
"""Launch a thread to supervise the completion of an assignment"""
try:
tracked_agents: List["Agent"] = []
for a in agent_infos:
assert isinstance(
a.agent, Agent
), f"Can launch assignments for Agents, not OnboardingAgents, got {a.agent}"
tracked_agents.append(a.agent)
task_runner.launch_assignment(assignment, tracked_agents)
for agent_info in agent_infos:
self._mark_agent_done(agent_info)
# Wait for agents to be complete
for agent_info in agent_infos:
agent = agent_info.agent
if agent.get_status() not in AgentState.complete():
if not agent.did_submit.is_set():
# Wait for a submit to occur
# TODO(#94) make submit timeout configurable
agent.has_action.wait(timeout=300)
agent.act()
agent.mark_done()
except Exception as e:
logger.exception(f"Cleaning up assignment: {e}", exc_info=True)
task_runner.cleanup_assignment(assignment)
finally:
task_run = task_runner.task_run
for unit in assignment.get_units():
task_run.clear_reservation(unit)
def _launch_and_run_unit(
self, unit: "Unit", agent_info: "AgentInfo", task_runner: "TaskRunner"
):
"""Launch a thread to supervise the completion of an assignment"""
try:
agent = agent_info.agent
assert isinstance(
agent, Agent
), f"Can launch units for Agents, not OnboardingAgents, got {agent}"
task_runner.launch_unit(unit, agent)
if agent.get_status() not in AgentState.complete():
self._mark_agent_done(agent_info)
if not agent.did_submit.is_set():
# Wait for a submit to occur
# TODO(#94) make submit timeout configurable
agent.has_action.wait(timeout=300)
agent.act()
agent.mark_done()
except Exception as e:
logger.exception(f"Cleaning up unit: {e}", exc_info=True)
task_runner.cleanup_unit(unit)
finally:
task_runner.task_run.clear_reservation(unit)
def _assign_unit_to_agent(
self, packet: Packet, channel_info: ChannelInfo, units: List["Unit"]
):
"""Handle creating an agent for the specific worker to register an agent"""
crowd_data = packet.data["provider_data"]
task_run = channel_info.job.task_runner.task_run
crowd_provider = channel_info.job.provider
worker_id = crowd_data["worker_id"]
worker = Worker(self.db, worker_id)
logger.debug(
f"Worker {worker_id} is being assigned one of | |
#!/usr/bin/env python3
"""Supporting utilities.
Classes
-------
.. autosummary::
ProgressBar
OptionReader
Routines
--------
.. autosummary::
read_param
round_up
evaluate_ratio
humansize
humantime
----
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
try:
import configparser
except ImportError:
import ConfigParser as configparser
import math
import os
import re
import sys
import time
def read_param(params, key, default):
"""Read and return a parameter from a dict.
If the key `key` is absent from the dict `params`, return the
default value `default` instead.
Parameters
----------
params : dict
A dict containing parameters.
key : str
Name of the parameter, i.e., its corresponding key in `params`.
default
Default value for the parameter, if `key` is absent from `params`.
Returns
-------
value
If `key` in `params`, return ``params[key]``; otherwise, return
`default` instead.
"""
if not isinstance(key, str):
raise ValueError('invalid parameter name %s' % str(key))
return params[key] if key in params else default
def round_up(number, ndigits=0):
"""Round a floating point number *upward* to a given precision.
Unlike the builtin `round`, the return value `round_up` is always
the smallest float *greater than or equal to* the given number
matching the specified precision.
Parameters
----------
number : float
Number to be rounded up.
ndigits : int, optional
Number of decimal digits in the result. Default is 0.
Returns
-------
float
Examples
--------
>>> round_up(math.pi)
4.0
>>> round_up(math.pi, ndigits=1)
3.2
>>> round_up(math.pi, ndigits=2)
3.15
>>> round_up(-math.pi, ndigits=4)
-3.1415
"""
multiplier = 10 ** ndigits
return math.ceil(number * multiplier) / multiplier
# patterns numerator:denominator and numerator/denominator
_NUM_COLON_DEN = re.compile(r'^([1-9][0-9]*):([1-9][0-9]*)$')
_NUM_SLASH_DEN = re.compile(r'^([1-9][0-9]*)/([1-9][0-9]*)$')
def evaluate_ratio(ratio_str):
"""Evaluate ratio in the form num:den or num/den.
Note that numerator and denominator should both be positive
integers.
Parameters
----------
ratio_str : str
The ratio as a string (either ``'num:den'`` or ``'num/den'``
where ``num`` and ``den``, the numerator and denominator, are
positive integers.
Returns
-------
ratio : float
The ratio as a float, or ``None`` if `ratio_str` is malformed.
Examples
--------
>>> evaluate_ratio('16:9')
1.7777777777777777
>>> evaluate_ratio('16/9')
1.7777777777777777
>>> print(evaluate_ratio('0/9'))
None
"""
match = _NUM_COLON_DEN.match(ratio_str)
if match:
numerator = int(match.group(1))
denominator = int(match.group(2))
return numerator / denominator
match = _NUM_SLASH_DEN.match(ratio_str)
if match:
numerator = int(match.group(1))
denominator = int(match.group(2))
return numerator / denominator
return None
def humansize(size):
"""Return a human readable string of the given size in bytes."""
multiplier = 1024.0
if size < multiplier:
return "%dB" % size
for unit in ['Ki', 'Mi', 'Gi', 'Ti', 'Pi', 'Ei', 'Zi']:
size /= multiplier
if size < multiplier:
if size < 10:
return "%.2f%sB" % (round_up(size, 2), unit)
elif size < 100:
return "%.1f%sB" % (round_up(size, 1), unit)
else:
return "%.0f%sB" % (round_up(size, 0), unit)
break
else:
return "%.1f%sB" % (round_up(size, 1), unit)
def humantime(seconds, ndigits=2, one_hour_digit=False):
"""Format a duration as a human readable string.
The duration in seconds (a nonnegative float) is formatted as
``HH:MM:SS.frac``, where the number of fractional digits is
controlled by `ndigits`; if `ndigits` is 0, the decimal point is not
printed. The number of hour digits (``HH``) can be reduced to one
with the `one_hour_digits` option.
Parameters
----------
seconds : float
Duration in seconds, must be nonnegative.
ndigits : int, optional
Number of digits after the decimal point for the seconds part.
Default is 2. If 0, the decimal point is suppressed.
one_hour_digit : bool, optional
If ``True``, only print one hour digit (e.g., nine hours is
printed as 9:00:00.00). Default is ``False``, i.e., two hour
digits (nine hours is printed as 09:00:00.00).
Returns
-------
human_readable_duration : str
Raises
------
ValueError:
If `seconds` is negative.
Examples
--------
>>> humantime(10.55)
'00:00:10.55'
>>> humantime(10.55, ndigits=1)
'00:00:10.6'
>>> humantime(10.55, ndigits=0)
'00:00:11'
>>> humantime(10.55, one_hour_digit=True)
'0:00:10.55'
>>> # two hours digits for >= 10 hours, even if one_hour_digit is
>>> # set to True
>>> humantime(86400, one_hour_digit=True)
'24:00:00.00'
>>> humantime(-1)
Traceback (most recent call last):
...
ValueError: seconds=-1.000000 is negative, expected nonnegative value
"""
# pylint: disable=invalid-name
if seconds < 0:
raise ValueError("seconds=%f is negative, "
"expected nonnegative value" % seconds)
hh = int(seconds) // 3600 # hours
mm = (int(seconds) // 60) % 60 # minutes
ss = seconds - (int(seconds) // 60) * 60 # seconds
hh_str = "%01d" % hh if one_hour_digit else "%02d" % hh
mm_str = "%02d" % mm
if ndigits == 0:
ss_str = "%02d" % round(ss)
else:
ss_format = "%0{0}.{1}f".format(ndigits + 3, ndigits)
ss_str = ss_format % ss
return "%s:%s:%s" % (hh_str, mm_str, ss_str)
# default progress bar update interval
_PROGRESS_UPDATE_INTERVAL = 1.0
# the format string for a progress bar line
#
# 0: processed size, e.g., 2.02GiB
# 1: elapsed time (7 chars), e.g., 0:00:04
# 2: current processing speed, e.g., 424MiB (/s is already hardcoded)
# 3: the bar, in the form "=====> "
# 4: number of percent done, e.g., 99
# 5: estimated time remaining (11 chars), in the form "ETA H:MM:SS"; if
# finished, fill with space
_FORMAT_STRING = '\r{0:>7s} {1} [{2:>7s}/s] [{3}] {4:>3s}% {5}'
class ProgressBar(object):
"""Progress bar for file processing.
To generate a progress bar, init a ProgressBar instance, then update
frequently with the `update` method, passing in the size of newly
processed chunk. The `force_update` method should only be called if
you want to overwrite the processed size, which is automatically
calculated incrementally. After you finish processing the
file/stream, you must call the `finish` method to wrap it up. Any
further calls after the `finish` method has been called lead to
a ``RuntimeError``.
Each ProgressBar instance defines several public attributes listed
below. Some are available during processing, and some after
processing. These attributes are meant for informational purposes,
and you should not manually tamper with them (which mostly likely
leads to undefined behavior).
The progress bar format is inspired by ``pv(1)`` (pipe viewer).
Parameters
----------
totalsize : int
Total size, in bytes, of the file/stream to be processed.
interval : float, optional
Update (refresh) interval of the progress bar, in
seconds. Default is 1.0.
Attributes
----------
totalsize : int
Total size of file/stream, in bytes. Available throughout.
processed : int
Process size. Available only during processing (deleted after
the `finish` call).
start : float
Starting time (an absolute time returned by
``time.time()``). Available throughout.
interval : float
Update (refresh) interval of the progress bar, in
seconds. Available only during processing (deleted after the
`finish` call).
elapsed : float
Total elapsed time, in seconds. Only available after the
`finish` call.
Notes
-----
For developers: ProgressBar also defines three private attributes,
`_last`, `_last_processed` and `_barlen`, during processing (deleted
after the `finish` call). `_last` stores the absolute time of last
update (refresh), `_last_processed` stores the processed size at the
time of the last update (refresh), and `_barlen` stores the length
of the progress bar (only the bar portion).
There is another private attribute `__finished` (bool) keeping track
of whether `finish` has been called. (Protected with double leading
underscores since no one should ever tamper with this.)
"""
# pylint: disable=too-many-instance-attributes
def __init__(self, totalsize, interval=_PROGRESS_UPDATE_INTERVAL):
"""Initialize the ProgressBar class.
See class docstring for parameters of the constructor.
"""
self.totalsize = totalsize
self.processed = 0
self.start = time.time()
self.interval = interval
self._last = self.start
self._last_processed = 0
self.__finished = False
# calculate bar length
try:
ncol, _ = os.get_terminal_size()
except (AttributeError, OSError):
# Python2 do not have os.get_terminal_size. Also,
# os.get_terminal_size fails if stdout is redirected to a
# pipe (pretty stupid -- should check stderr; relevant
# Python bug: https://bugs.python.org/issue14841). In either
# case, Assume a minimum of 80 columns.
ncol = 80
self._barlen = (ncol - 48) if ncol >= 58 else 10
def update(self, chunk_size):
"""Update the progress bar for a newly processed chunk.
The size of the processed chunk is registered. Whether the
progress bar is refreshed depends on whether we have reached the
refresh interval since the last refresh (handled automatically).
Parameters
----------
chunk_size : int
The size of the newly processed chunk (since last update),
in bytes. This size will be added to the `processed`
attribute.
Raises
------
RuntimeError:
If `finish` has been called on the ProgressBar instance.
"""
if self.__finished:
raise RuntimeError('operation on finished progress bar')
self.processed += chunk_size
if self.processed | |
<filename>pyxel/__init__.py
import inspect
import os
import signal
import sys
import traceback
from collections import MutableSequence
from ctypes import CFUNCTYPE, c_char_p, c_int32, cast, create_string_buffer
from typing import Any, Callable, Dict, List, Optional
from . import core # type: ignore
if sys.version_info < (3, 6, 8):
print("pyxel error: Python version must be 3.6.8 or higher")
sys.exit(1)
#
# constants
#
def _get_constant_number(name: str) -> int:
return core._get_constant_number(name.encode("utf-8")) # type: ignore
def _get_constant_string(name: str) -> str:
buf = create_string_buffer(256)
core._get_constant_string(buf, len(buf), name.encode("utf-8"))
return buf.value.decode()
VERSION: str = _get_constant_string("VERSION")
COLOR_COUNT: int = _get_constant_number("COLOR_COUNT")
COLOR_BLACK: int = _get_constant_number("COLOR_BLACK")
COLOR_NAVY: int = _get_constant_number("COLOR_NAVY")
COLOR_PURPLE: int = _get_constant_number("COLOR_PURPLE")
COLOR_GREEN: int = _get_constant_number("COLOR_GREEN")
COLOR_BROWN: int = _get_constant_number("COLOR_BROWN")
COLOR_DARKBLUE: int = _get_constant_number("COLOR_DARKBLUE")
COLOR_LIGHTBLUE: int = _get_constant_number("COLOR_LIGHTBLUE")
COLOR_WHITE: int = _get_constant_number("COLOR_WHITE")
COLOR_RED: int = _get_constant_number("COLOR_RED")
COLOR_ORANGE: int = _get_constant_number("COLOR_ORANGE")
COLOR_YELLOW: int = _get_constant_number("COLOR_YELLOW")
COLOR_LIME: int = _get_constant_number("COLOR_LIME")
COLOR_CYAN: int = _get_constant_number("COLOR_CYAN")
COLOR_GRAY: int = _get_constant_number("COLOR_GRAY")
COLOR_PINK: int = _get_constant_number("COLOR_PINK")
COLOR_PEACH: int = _get_constant_number("COLOR_PEACH")
FONT_WIDTH: int = _get_constant_number("FONT_WIDTH")
FONT_HEIGHT: int = _get_constant_number("FONT_HEIGHT")
USER_IMAGE_BANK_COUNT: int = _get_constant_number("USER_IMAGE_BANK_COUNT")
IMAGE_BANK_FOR_SYSTEM: int = _get_constant_number("IMAGE_BANK_FOR_SYSTEM")
TILEMAP_BANK_COUNT: int = _get_constant_number("TILEMAP_BANK_COUNT")
USER_SOUND_BANK_COUNT: int = _get_constant_number("USER_SOUND_BANK_COUNT")
SOUND_BANK_FOR_SYSTEM: int = _get_constant_number("SOUND_BANK_FOR_SYSTEM")
MUSIC_BANK_COUNT: int = _get_constant_number("MUSIC_BANK_COUNT")
MUSIC_CHANNEL_COUNT: int = _get_constant_number("MUSIC_CHANNEL_COUNT")
RESOURCE_FILE_EXTENSION: str = _get_constant_string("RESOURCE_FILE_EXTENSION")
DEFAULT_CAPTION: str = _get_constant_string("DEFAULT_CAPTION")
DEFAULT_SCALE: int = _get_constant_number("DEFAULT_SCALE")
DEFAULT_PALETTE: List[int] = [
_get_constant_number("DEFAULT_PALETTE_00"),
_get_constant_number("DEFAULT_PALETTE_01"),
_get_constant_number("DEFAULT_PALETTE_02"),
_get_constant_number("DEFAULT_PALETTE_03"),
_get_constant_number("DEFAULT_PALETTE_04"),
_get_constant_number("DEFAULT_PALETTE_05"),
_get_constant_number("DEFAULT_PALETTE_06"),
_get_constant_number("DEFAULT_PALETTE_07"),
_get_constant_number("DEFAULT_PALETTE_08"),
_get_constant_number("DEFAULT_PALETTE_09"),
_get_constant_number("DEFAULT_PALETTE_10"),
_get_constant_number("DEFAULT_PALETTE_11"),
_get_constant_number("DEFAULT_PALETTE_12"),
_get_constant_number("DEFAULT_PALETTE_13"),
_get_constant_number("DEFAULT_PALETTE_14"),
_get_constant_number("DEFAULT_PALETTE_15"),
]
DEFAULT_FPS: int = _get_constant_number("DEFAULT_FPS")
DEFAULT_QUIT_KEY: int = _get_constant_number("DEFAULT_QUIT_KEY")
KEY_SPACE: int = _get_constant_number("KEY_SPACE")
KEY_QUOTE: int = _get_constant_number("KEY_QUOTE")
KEY_COMMA: int = _get_constant_number("KEY_COMMA")
KEY_MINUS: int = _get_constant_number("KEY_MINUS")
KEY_PERIOD: int = _get_constant_number("KEY_PERIOD")
KEY_SLASH: int = _get_constant_number("KEY_SLASH")
KEY_0: int = _get_constant_number("KEY_0")
KEY_1: int = _get_constant_number("KEY_1")
KEY_2: int = _get_constant_number("KEY_2")
KEY_3: int = _get_constant_number("KEY_3")
KEY_4: int = _get_constant_number("KEY_4")
KEY_5: int = _get_constant_number("KEY_5")
KEY_6: int = _get_constant_number("KEY_6")
KEY_7: int = _get_constant_number("KEY_7")
KEY_8: int = _get_constant_number("KEY_8")
KEY_9: int = _get_constant_number("KEY_9")
KEY_SEMICOLON: int = _get_constant_number("KEY_SEMICOLON")
KEY_EQUAL: int = _get_constant_number("KEY_EQUAL")
KEY_A: int = _get_constant_number("KEY_A")
KEY_B: int = _get_constant_number("KEY_B")
KEY_C: int = _get_constant_number("KEY_C")
KEY_D: int = _get_constant_number("KEY_D")
KEY_E: int = _get_constant_number("KEY_E")
KEY_F: int = _get_constant_number("KEY_F")
KEY_G: int = _get_constant_number("KEY_G")
KEY_H: int = _get_constant_number("KEY_H")
KEY_I: int = _get_constant_number("KEY_I")
KEY_J: int = _get_constant_number("KEY_J")
KEY_K: int = _get_constant_number("KEY_K")
KEY_L: int = _get_constant_number("KEY_L")
KEY_M: int = _get_constant_number("KEY_M")
KEY_N: int = _get_constant_number("KEY_N")
KEY_O: int = _get_constant_number("KEY_O")
KEY_P: int = _get_constant_number("KEY_P")
KEY_Q: int = _get_constant_number("KEY_Q")
KEY_R: int = _get_constant_number("KEY_R")
KEY_S: int = _get_constant_number("KEY_S")
KEY_T: int = _get_constant_number("KEY_T")
KEY_U: int = _get_constant_number("KEY_U")
KEY_V: int = _get_constant_number("KEY_V")
KEY_W: int = _get_constant_number("KEY_W")
KEY_X: int = _get_constant_number("KEY_X")
KEY_Y: int = _get_constant_number("KEY_Y")
KEY_Z: int = _get_constant_number("KEY_Z")
KEY_LEFT_BRACKET: int = _get_constant_number("KEY_LEFT_BRACKET")
KEY_BACKSLASH: int = _get_constant_number("KEY_BACKSLASH")
KEY_RIGHT_BRACKET: int = _get_constant_number("KEY_RIGHT_BRACKET")
KEY_BACKQUOTE: int = _get_constant_number("KEY_BACKQUOTE")
KEY_ESCAPE: int = _get_constant_number("KEY_ESCAPE")
KEY_ENTER: int = _get_constant_number("KEY_ENTER")
KEY_TAB: int = _get_constant_number("KEY_TAB")
KEY_BACKSPACE: int = _get_constant_number("KEY_BACKSPACE")
KEY_INSERT: int = _get_constant_number("KEY_INSERT")
KEY_DELETE: int = _get_constant_number("KEY_DELETE")
KEY_RIGHT: int = _get_constant_number("KEY_RIGHT")
KEY_LEFT: int = _get_constant_number("KEY_LEFT")
KEY_DOWN: int = _get_constant_number("KEY_DOWN")
KEY_UP: int = _get_constant_number("KEY_UP")
KEY_PAGE_UP: int = _get_constant_number("KEY_PAGE_UP")
KEY_PAGE_DOWN: int = _get_constant_number("KEY_PAGE_DOWN")
KEY_HOME: int = _get_constant_number("KEY_HOME")
KEY_END: int = _get_constant_number("KEY_END")
KEY_CAPS_LOCK: int = _get_constant_number("KEY_CAPS_LOCK")
KEY_SCROLL_LOCK: int = _get_constant_number("KEY_SCROLL_LOCK")
KEY_NUM_LOCK: int = _get_constant_number("KEY_NUM_LOCK")
KEY_PRINT_SCREEN: int = _get_constant_number("KEY_PRINT_SCREEN")
KEY_PAUSE: int = _get_constant_number("KEY_PAUSE")
KEY_F1: int = _get_constant_number("KEY_F1")
KEY_F2: int = _get_constant_number("KEY_F2")
KEY_F3: int = _get_constant_number("KEY_F3")
KEY_F4: int = _get_constant_number("KEY_F4")
KEY_F5: int = _get_constant_number("KEY_F5")
KEY_F6: int = _get_constant_number("KEY_F6")
KEY_F7: int = _get_constant_number("KEY_F7")
KEY_F8: int = _get_constant_number("KEY_F8")
KEY_F9: int = _get_constant_number("KEY_F9")
KEY_F10: int = _get_constant_number("KEY_F10")
KEY_F11: int = _get_constant_number("KEY_F11")
KEY_F12: int = _get_constant_number("KEY_F12")
KEY_KP_0: int = _get_constant_number("KEY_KP_0")
KEY_KP_1: int = _get_constant_number("KEY_KP_1")
KEY_KP_2: int = _get_constant_number("KEY_KP_2")
KEY_KP_3: int = _get_constant_number("KEY_KP_3")
KEY_KP_4: int = _get_constant_number("KEY_KP_4")
KEY_KP_5: int = _get_constant_number("KEY_KP_5")
KEY_KP_6: int = _get_constant_number("KEY_KP_6")
KEY_KP_7: int = _get_constant_number("KEY_KP_7")
KEY_KP_8: int = _get_constant_number("KEY_KP_8")
KEY_KP_9: int = _get_constant_number("KEY_KP_9")
KEY_KP_DECIMAL: int = _get_constant_number("KEY_KP_DECIMAL")
KEY_KP_DIVIDE: int = _get_constant_number("KEY_KP_DIVIDE")
KEY_KP_MULTIPLY: int = _get_constant_number("KEY_KP_MULTIPLY")
KEY_KP_SUBTRACT: int = _get_constant_number("KEY_KP_SUBTRACT")
KEY_KP_ADD: int = _get_constant_number("KEY_KP_ADD")
KEY_KP_ENTER: int = _get_constant_number("KEY_KP_ENTER")
KEY_KP_EQUAL: int = _get_constant_number("KEY_KP_EQUAL")
KEY_LEFT_SHIFT: int = _get_constant_number("KEY_LEFT_SHIFT")
KEY_LEFT_CONTROL: int = _get_constant_number("KEY_LEFT_CONTROL")
KEY_LEFT_ALT: int = _get_constant_number("KEY_LEFT_ALT")
KEY_LEFT_SUPER: int = _get_constant_number("KEY_LEFT_SUPER")
KEY_RIGHT_SHIFT: int = _get_constant_number("KEY_RIGHT_SHIFT")
KEY_RIGHT_CONTROL: int = _get_constant_number("KEY_RIGHT_CONTROL")
KEY_RIGHT_ALT: int = _get_constant_number("KEY_RIGHT_ALT")
KEY_RIGHT_SUPER: int = _get_constant_number("KEY_RIGHT_SUPER")
KEY_MENU: int = _get_constant_number("KEY_MENU")
KEY_SHIFT: int = _get_constant_number("KEY_SHIFT")
KEY_CONTROL: int = _get_constant_number("KEY_CONTROL")
KEY_ALT: int = _get_constant_number("KEY_ALT")
KEY_SUPER: int = _get_constant_number("KEY_SUPER")
KEY_NONE: int = _get_constant_number("KEY_NONE")
MOUSE_LEFT_BUTTON: int = _get_constant_number("MOUSE_LEFT_BUTTON")
MOUSE_MIDDLE_BUTTON: int = _get_constant_number("MOUSE_MIDDLE_BUTTON")
MOUSE_RIGHT_BUTTON: int = _get_constant_number("MOUSE_RIGHT_BUTTON")
GAMEPAD_1_A: int = _get_constant_number("GAMEPAD_1_A")
GAMEPAD_1_B: int = _get_constant_number("GAMEPAD_1_B")
GAMEPAD_1_X: int = _get_constant_number("GAMEPAD_1_X")
GAMEPAD_1_Y: int = _get_constant_number("GAMEPAD_1_Y")
GAMEPAD_1_LEFT_SHOULDER: int = _get_constant_number("GAMEPAD_1_LEFT_SHOULDER")
GAMEPAD_1_RIGHT_SHOULDER: int = _get_constant_number("GAMEPAD_1_RIGHT_SHOULDER")
GAMEPAD_1_SELECT: int = _get_constant_number("GAMEPAD_1_SELECT")
GAMEPAD_1_START: int = _get_constant_number("GAMEPAD_1_START")
GAMEPAD_1_UP: int = _get_constant_number("GAMEPAD_1_UP")
GAMEPAD_1_RIGHT: int = _get_constant_number("GAMEPAD_1_RIGHT")
GAMEPAD_1_DOWN: int = _get_constant_number("GAMEPAD_1_DOWN")
GAMEPAD_1_LEFT: int = _get_constant_number("GAMEPAD_1_LEFT")
GAMEPAD_2_A: int = _get_constant_number("GAMEPAD_2_A")
GAMEPAD_2_B: int = _get_constant_number("GAMEPAD_2_B")
GAMEPAD_2_X: int = _get_constant_number("GAMEPAD_2_X")
GAMEPAD_2_Y: int = _get_constant_number("GAMEPAD_2_Y")
GAMEPAD_2_LEFT_SHOULDER: int = _get_constant_number("GAMEPAD_2_LEFT_SHOULDER")
GAMEPAD_2_RIGHT_SHOULDER: int = _get_constant_number("GAMEPAD_2_RIGHT_SHOULDER")
GAMEPAD_2_SELECT: int = _get_constant_number("GAMEPAD_2_SELECT")
GAMEPAD_2_START: int = _get_constant_number("GAMEPAD_2_START")
GAMEPAD_2_UP: int = _get_constant_number("GAMEPAD_2_UP")
GAMEPAD_2_RIGHT: int = _get_constant_number("GAMEPAD_2_RIGHT")
GAMEPAD_2_DOWN: int = _get_constant_number("GAMEPAD_2_DOWN")
GAMEPAD_2_LEFT: int = _get_constant_number("GAMEPAD_2_LEFT")
#
# Image class
#
class Image:
def __init__(self, obj: Any):
self._obj = obj
self._data = core.image_data_getter(self._obj)
@property
def width(self) -> int:
return core.image_width_getter(self._obj) # type: ignore
@property
def height(self) -> int:
return core.image_height_getter(self._obj) # type: ignore
@property
def data(self) -> Any:
return self._data
def get(self, x: int, y: int) -> int:
return core.image_get(self._obj, int(x), int(y)) # type: ignore
def set(self, x: int, y: int, data: Any) -> None:
if type(data) is int:
core.image_set1(self._obj, int(x), int(y), int(data))
else:
data_count = len(data)
c_data = (c_char_p * data_count)()
for i in range(data_count):
c_str = create_string_buffer(data[i].encode("utf-8"))
c_data[i] = cast(c_str, c_char_p)
core.image_set(self._obj, int(x), int(y), c_data, data_count)
def load(self, x: int, y: int, filename: str) -> None:
caller = inspect.currentframe().f_back.f_code.co_filename # type: ignore
dirname = (
getattr(sys, "_MEIPASS", os.path.abspath(os.path.dirname(caller)))
if hasattr(sys, "_MEIPASS")
else os.path.dirname(caller)
)
filename = os.path.abspath(os.path.join(dirname, filename))
core.image_load(self._obj, int(x), int(y), filename.encode("utf-8"))
def copy(self, x: int, y: int, img: int, u: int, v: int, w: int, h: int) -> None:
core.image_copy(
self._obj, int(x), int(y), int(img), int(u), int(v), int(w), int(h)
)
#
# Tilemap class
#
class Tilemap:
def __init__(self, obj: Any):
self._obj = obj
self._data = core.image_data_getter(self._obj)
@property
def width(self) -> int:
return core.tilemap_width_getter(self._obj) # type: ignore
@property
def height(self) -> int:
return core.tilemap_height_getter(self._obj) # type: ignore
@property
def data(self) -> Any:
return self._data
@property
def refimg(self) -> int:
return core.tilemap_refimg_getter(self._obj) # type: ignore
@refimg.setter
def refimg(self, img: int) -> int:
return core.tilemap_refimg_setter(self._obj, int(img)) # type: ignore
def get(self, x: int, y: int) -> int:
return core.tilemap_get(self._obj, int(x), int(y)) # type: ignore
def set(self, x: int, y: int, data: Any) -> None:
if type(data) is int:
core.tilemap_set1(self._obj, int(x), int(y), int(data))
else:
data_count = len(data)
c_data = (c_char_p * data_count)()
for i in range(data_count):
c_str = create_string_buffer(data[i].encode("utf-8"))
c_data[i] = cast(c_str, c_char_p)
core.tilemap_set(self._obj, int(x), int(y), c_data, data_count)
def copy(self, x: int, y: int, tm: int, u: int, v: int, w: int, h: int) -> None:
core.tilemap_copy(
self._obj, int(x), int(y), int(tm), int(u), int(v), int(w), int(h)
)
#
# Sound class
#
class Sound:
def __init__(self, c_obj: Any):
self._c_obj = c_obj
self._note = _CListInterface( # type: ignore
c_obj,
core.sound_note_getter,
core.sound_note_length_getter,
core.sound_note_length_setter,
)
self._tone = _CListInterface( # type: ignore
c_obj,
core.sound_tone_getter,
core.sound_tone_length_getter,
core.sound_tone_length_setter,
)
self._volume = _CListInterface( # type: ignore
c_obj,
core.sound_volume_getter,
core.sound_volume_length_getter,
core.sound_volume_length_setter,
)
self._effect = _CListInterface( # type: ignore
c_obj,
core.sound_effect_getter,
core.sound_effect_length_getter,
core.sound_effect_length_setter,
)
@property
def note(self) -> List[int]:
return self._note # type: ignore
@property
def tone(self) -> List[int]:
return self._tone # type: ignore
@property
def volume(self) -> List[int]:
return self._volume # type: ignore
@property
def effect(self) -> List[int]:
return self._effect # type: ignore
@property
def speed(self) -> int:
return core.sound_speed_getter(self._c_obj) # type: ignore
@speed.setter
def speed(self, speed: int) -> None:
core.sound_speed_setter(self._c_obj, speed)
def set(self, note: str, tone: str, volume: str, effect: str, speed: int) -> None:
core.sound_set(
self._c_obj,
note.encode("utf-8"),
tone.encode("utf-8"),
volume.encode("utf-8"),
effect.encode("utf-8"),
speed,
)
def set_note(self, note: str) -> None:
core.sound_set_note(note.encode("utf-8"))
def set_tone(self, tone: str) -> None:
core.sound_set_tone(tone.encode("utf-8"))
def set_volume(self, volume: str) -> None:
core.sound_set_volume(volume.encode("utf-8"))
def set_effect(self, effect: str) -> None:
core.sound_set_effect(effect.encode("utf-8"))
#
# Music class
#
class Music:
def __init__(self, c_obj: Any):
self._c_obj = c_obj
self._ch0 = _CListInterface( # type: ignore
c_obj,
core.music_ch0_getter,
core.music_ch0_length_getter,
core.music_ch0_length_setter,
)
self._ch1 = _CListInterface( # type: ignore
c_obj,
core.music_ch1_getter,
core.music_ch1_length_getter,
core.music_ch1_length_setter,
)
self._ch2 = _CListInterface( # type: ignore
c_obj,
core.music_ch2_getter,
core.music_ch2_length_getter,
core.music_ch2_length_setter,
)
self._ch3 = _CListInterface( # type: ignore
c_obj,
core.music_ch3_getter,
core.music_ch3_length_getter,
core.music_ch3_length_setter,
)
@property
def ch0(self) -> List[int]:
return self._ch0 # type: ignore
@property
def ch1(self) -> List[int]:
return self._ch1 # type: ignore
@property
def ch2(self) -> List[int]:
return self._ch2 # type: ignore
@property
def ch3(self) -> List[int]:
return self._ch3 # type: ignore
def set(
self, ch0: List[int], ch1: List[int], ch2: List[int], ch3: List[int]
) -> None:
length0 = len(ch0)
length1 = len(ch1)
length2 = len(ch2)
length3 = len(ch3)
core.music_set(
self._c_obj,
(c_int32 * length0)(*ch0),
length0,
(c_int32 * length1)(*ch1),
length1,
(c_int32 * length2)(*ch2),
length2,
(c_int32 * length3)(*ch3),
length3,
)
def set_ch0(self, ch0: List[int]) -> None:
length = len(ch0)
core.music_set(self._c_obj, (c_int32 * length)(*ch0), length)
def set_ch1(self, ch1: List[int]) -> None:
length = len(ch1)
core.music_set(self._c_obj, (c_int32 * length)(*ch1), length)
def set_ch2(self, ch2: List[int]) -> None:
length = len(ch2)
core.music_set(self._c_obj, (c_int32 * length)(*ch2), length)
def set_ch3(self, ch3: List[int]) -> None:
length = len(ch3)
core.music_set(self._c_obj, (c_int32 * length)(*ch3), length)
#
# System
#
width: int = 0
height: int = 0
frame_count: int = 0
caption: str = DEFAULT_CAPTION
scale: int = DEFAULT_SCALE
palette: List[int] = DEFAULT_PALETTE
fps: | |
<filename>gpMgmt/bin/gppylib/operations/backup_utils.py
import fnmatch
import glob
import os
import re
import tempfile
from datetime import datetime
from gppylib import gplog
from gppylib.commands.base import WorkerPool, Command, REMOTE
from gppylib.commands.unix import Scp
from gppylib.db import dbconn
from gppylib.db.dbconn import execSQL
from gppylib.gparray import GpArray
from gppylib.mainUtils import gp
from gppylib import pgconf
from optparse import Values
from pygresql import pg
import gzip
logger = gplog.get_default_logger()
class Context(Values, object):
filename_dict = {
"ao": ("dump", "_ao_state_file"), "cdatabase": ("cdatabase_1_1", ""), "co": ("dump", "_co_state_file"), "dirty_table": ("dump", "_dirty_list"),
"dump": ("dump_%d_%d", ""), "files": ("dump", "_regular_files"), "filter": ("dump", "_filter"), "global": ("global_1_1", ""),
"increments": ("dump", "_increments"), "last_operation": ("dump", "_last_operation"), "master_config": ("master_config_files", ".tar"),
"metadata": ("dump_1_1", ""), "partition_list": ("dump", "_table_list"), "pipes": ("dump", "_pipes"), "plan": ("restore", "_plan"),
"postdata": ("dump_1_1", "_post_data"), "report": ("dump", ".rpt"), "schema": ("dump", "_schema"), "segment_config": ("segment_config_files_%d_%d", ".tar"),
"stats": ("statistics_1_1", ""), "status": ("dump_status_%d_%d", ""),
}
defaults = {
"backup_dir": None, "batch_default": 64, "change_schema": None, "cleanup_date": None, "cleanup_total": None, "clear_catalog_dumps": False,
"clear_dumps": False, "clear_dumps_only": False, "compress": True, "db_host_path": None, "ddboost": False, "ddboost_backupdir": None, "ddboost_config_remove": False,
"ddboost_hosts": None, "ddboost_ping": True, "ddboost_remote": False, "ddboost_show_config": False, "ddboost_storage_unit": None, "ddboost_user": None,
"ddboost_verify": False, "drop_db": False, "dump_config": False, "dump_databases": [], "dump_dir": "db_dumps", "dump_global": False, "dump_prefix": "",
"dump_schema": "", "dump_stats": False, "encoding": None, "exclude_dump_schema": "", "exclude_dump_tables": "", "exclude_dump_tables_file": "",
"exclude_schema_file": "", "free_space_percent": None, "history": True, "include_dump_tables": "", "include_dump_tables_file": "",
"include_schema_file": "", "incremental": False, "list_filter_tables": False, "local_dump_prefix": None, "masterDataDirectory": None,
"master_port": 0, "max_streams": None, "netbackup_block_size": None, "netbackup_keyword": None, "netbackup_policy": None, "netbackup_schedule": None,
"netbackup_service_host": None, "metadata_only": False, "no_analyze": False, "no_ao_stats": False, "no_plan": False, "no_validate_table_name": False,
"output_options": [], "post_script": "", "redirected_restore_db": None, "report_dir": "", "report_status_dir": "", "restore_db": None,
"restore_global": False, "restore_schemas": None, "restore_stats": None, "restore_tables": [], "timestamp": None, "timestamp_key": None,
"full_dump_timestamp": None,
}
def __init__(self, values=None):
if values:
self.defaults.update(values.__dict__) # Ensure that context has default values for all unset variables
super(self.__class__, self).__init__(vars(Values(self.defaults)))
if self.masterDataDirectory:
self.master_datadir = self.masterDataDirectory
else:
self.master_datadir = gp.get_masterdatadir()
self.master_port = self.get_master_port()
if self.local_dump_prefix:
self.dump_prefix = self.local_dump_prefix + "_"
else:
self.dump_prefix = ""
if not self.include_dump_tables: self.include_dump_tables = []
if not self.exclude_dump_tables: self.exclude_dump_tables = []
if not self.output_options: self.output_options = []
if not self.dump_schema: self.dump_schema = []
if not self.exclude_dump_schema: self.exclude_dump_schema = []
def get_master_port(self):
pgconf_dict = pgconf.readfile(self.master_datadir + "/postgresql.conf")
return pgconf_dict.int('port')
def generate_filename(self, filetype, dbid=1, timestamp=None, directory=None):
if timestamp is None:
timestamp = self.timestamp
if directory:
use_dir = directory
else:
use_dir = self.get_backup_dir(timestamp)
format_str = "%s/%sgp_%s_%s%s" % (use_dir, self.dump_prefix, "%s", timestamp, "%s")
filename = format_str % (self.filename_dict[filetype][0], self.filename_dict[filetype][1])
if "%d" in filename:
if dbid == 1:
filename = filename % (1, 1)
else:
filename = filename % (0, dbid)
if self.compress and filetype in ["metadata", "dump", "postdata"]:
filename += ".gz"
return filename
def generate_prefix(self, filetype, dbid=1, timestamp=None):
if timestamp is None:
timestamp = self.timestamp
format_str = "%sgp_%s_" % (self.dump_prefix, "%s")
filename = format_str % (self.filename_dict[filetype][0])
if "%d" in filename:
if dbid == 1:
filename = filename % (1, 1)
else:
filename = filename % (0, dbid)
return filename
def get_backup_dir(self, timestamp=None, directory=None):
if directory is not None:
use_dir = directory
elif self.backup_dir and not self.ddboost:
use_dir = self.backup_dir
elif self.master_datadir:
use_dir = self.master_datadir
else:
raise Exception("Cannot locate backup directory with existing parameters")
if timestamp:
use_timestamp = timestamp
else:
use_timestamp = self.timestamp
if not use_timestamp:
raise Exception("Cannot locate backup directory without timestamp")
if not validate_timestamp(use_timestamp):
raise Exception('Invalid timestamp: "%s"' % use_timestamp)
return "%s/%s/%s" % (use_dir, self.dump_dir, use_timestamp[0:8])
def get_backup_root(self):
if self.backup_dir and not self.ddboost:
return self.backup_dir
else:
return self.master_datadir
def get_gpd_path(self):
gpd_path = os.path.join(self.dump_dir, self.timestamp[0:8])
if self.backup_dir:
gpd_path = os.path.join(self.backup_dir, gpd_path)
return gpd_path
def get_date_dir(self):
return os.path.join(self.get_backup_root(), self.dump_dir, self.db_date_dir)
def backup_dir_is_writable(self):
if self.backup_dir and not self.report_status_dir:
try:
check_dir_writable(self.get_backup_dir())
except Exception as e:
logger.warning('Backup directory %s is not writable. Error %s' % (self.get_backup_dir(), str(e)))
logger.warning('Since --report-status-dir option is not specified, report and status file will be written in segment data directory.')
return False
return True
def generate_dump_timestamp(self):
if self.timestamp_key:
timestamp_key = self.timestamp_key
else:
timestamp_key = datetime.now().strftime("%Y%m%d%H%M%S")
if not validate_timestamp(timestamp_key):
raise Exception('Invalid timestamp key')
year = int(timestamp_key[:4])
month = int(timestamp_key[4:6])
day = int(timestamp_key[6:8])
hours = int(timestamp_key[8:10])
minutes = int(timestamp_key[10:12])
seconds = int(timestamp_key[12:14])
self.timestamp = timestamp_key
self.db_date_dir = "%4d%02d%02d" % (year, month, day)
self.timestamp_object = datetime(year, month, day, hours, minutes, seconds)
def expand_partitions_and_populate_filter_file(dbname, partition_list, file_prefix):
expanded_partitions = expand_partition_tables(dbname, partition_list)
dump_partition_list = list(set(expanded_partitions + partition_list))
return create_temp_file_from_list(dump_partition_list, file_prefix)
def populate_filter_tables(table, rows, non_partition_tables, partition_leaves):
if not rows:
non_partition_tables.append(table)
else:
for (schema_name, partition_leaf_name) in rows:
partition_leaf = schema_name.strip() + '.' + partition_leaf_name.strip()
partition_leaves.append(partition_leaf)
return (non_partition_tables, partition_leaves)
def get_all_parent_tables(dbname):
SQL = "SELECT DISTINCT (schemaname || '.' || tablename) FROM pg_partitions"
data = []
with dbconn.connect(dbconn.DbURL(dbname=dbname)) as conn:
curs = dbconn.execSQL(conn, SQL)
data = curs.fetchall()
return set([d[0] for d in data])
def list_to_quoted_string(filter_tables):
filter_string = "'" + "', '".join([pg.escape_string(t) for t in filter_tables]) + "'"
return filter_string
def convert_parents_to_leafs(dbname, parents):
partition_leaves_sql = """
SELECT x.partitionschemaname || '.' || x.partitiontablename
FROM (
SELECT distinct schemaname, tablename, partitionschemaname, partitiontablename, partitionlevel
FROM pg_partitions
WHERE schemaname || '.' || tablename in (%s)
) as X,
(SELECT schemaname, tablename maxtable, max(partitionlevel) maxlevel
FROM pg_partitions
group by (tablename, schemaname)
) as Y
WHERE x.schemaname = y.schemaname and x.tablename = Y.maxtable and x.partitionlevel = Y.maxlevel;
"""
if not parents:
return []
conn = dbconn.connect(dbconn.DbURL(dbname=dbname))
partition_sql = partition_leaves_sql % list_to_quoted_string(parents)
curs = dbconn.execSQL(conn, partition_sql)
rows = curs.fetchall()
return [r[0] for r in rows]
#input: list of tables to be filtered
#output: same list but parent tables converted to leafs
def expand_partition_tables(dbname, filter_tables):
if not filter_tables or len(filter_tables) == 0:
return filter_tables
parent_tables = list()
non_parent_tables = list()
expanded_list = list()
all_parent_tables = get_all_parent_tables(dbname)
for table in filter_tables:
if table in all_parent_tables:
parent_tables.append(table)
else:
non_parent_tables.append(table)
expanded_list += non_parent_tables
local_batch_size = 1000
for (s, e) in get_batch_from_list(len(parent_tables), local_batch_size):
tmp = convert_parents_to_leafs(dbname, parent_tables[s:e])
expanded_list += tmp
return expanded_list
def get_batch_from_list(length, batch_size):
indices = []
for i in range(0, length, batch_size):
indices.append((i, i+batch_size))
return indices
def create_temp_file_from_list(entries, prefix):
"""
When writing the entries into temp file, don't do any strip as there might be
white space in schema name and table name.
"""
if len(entries) == 0:
return None
fd = tempfile.NamedTemporaryFile(mode='w', prefix=prefix, delete=False)
for entry in entries:
fd.write(entry + '\n')
tmp_file_name = fd.name
fd.close()
return tmp_file_name
def create_temp_file_with_tables(table_list):
return create_temp_file_from_list(table_list, 'table_list_')
def create_temp_file_with_schemas(schema_list):
return create_temp_file_from_list(schema_list, 'schema_file_')
def validate_timestamp(timestamp):
if not timestamp:
return False
if len(timestamp) != 14:
return False
if timestamp.isdigit():
return True
else:
return False
def check_successful_dump(report_file_contents):
for line in report_file_contents:
if line.strip() == 'gp_dump utility finished successfully.':
return True
return False
# raise exception for bad data
def convert_report_filename_to_cdatabase_filename(context, report_file):
(dirname, fname) = os.path.split(report_file)
timestamp = fname[-18:-4]
ddboost_parent_dir = None
if context.ddboost:
ddboost_parent_dir = context.get_backup_dir(timestamp=timestamp, directory='')
return context.generate_filename("cdatabase", timestamp=timestamp, directory=ddboost_parent_dir)
def get_lines_from_dd_file(filename, ddboost_storage_unit):
cmdStr = 'gpddboost --readFile --from-file=%s' % filename
if ddboost_storage_unit:
cmdStr += ' --ddboost-storage-unit=%s' % ddboost_storage_unit
cmd = Command('DDBoost copy of master dump file', cmdStr)
cmd.run(validateAfter=True)
contents = cmd.get_results().stdout.splitlines()
return contents
def check_cdatabase_exists(context, report_file):
try:
filename = convert_report_filename_to_cdatabase_filename(context, report_file)
except Exception, err:
return False
if context.ddboost:
cdatabase_contents = get_lines_from_dd_file(filename, context.ddboost_storage_unit)
elif context.netbackup_service_host:
restore_file_with_nbu(context, path=filename)
cdatabase_contents = get_lines_from_file(filename)
else:
cdatabase_contents = get_lines_from_file(filename, context)
dbname = escapeDoubleQuoteInSQLString(context.dump_database, forceDoubleQuote=False)
for line in cdatabase_contents:
if 'CREATE DATABASE' in line:
dump_dbname = get_dbname_from_cdatabaseline(line)
if dump_dbname is None:
continue
else:
if dbname == checkAndRemoveEnclosingDoubleQuote(dump_dbname):
return True
return False
def get_dbname_from_cdatabaseline(line):
"""
Line format: CREATE DATABASE "DBNAME" WITH TEMPLATE = template0 ENCODING = 'UTF8' OWNER = gpadmin;
To get the dbname:
substring between the ending index of the first statement: CREATE DATABASE and the starting index
of WITH TEMPLATE whichever is not inside any double quotes, based on the fact that double quote
inside any name will be escaped by extra double quote, so there's always only one WITH TEMPLATE not
inside any doubles, means its previous and post string should have only even number of double
quotes.
Note: OWER name can also have special characters with double quote.
"""
cdatabase = "CREATE DATABASE "
try:
start = line.index(cdatabase)
except Exception as e:
logger.error('Failed to find substring %s in line %s, error: %s' % (cdatabase, line, str(e)))
return None
keyword = " WITH TEMPLATE = "
pos = get_nonquoted_keyword_index(line, keyword, '"', len(keyword))
if pos != -1:
dbname = line[start+len(cdatabase) : pos]
return dbname
return None
def get_nonquoted_keyword_index(line, keyword, quote, keyword_len):
# quote can | |
# ==================================================================================
#
# Copyright (c) 2019, <NAME>
#
# 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.
#
# ==================================================================================
# TODO:
# > Implement exact Legendre polynomials
# > Add references for the used polynomials
# > Apply (multiply) a gaussian function in the polynomial in order to
# give a localized nature (similar to Gabor wavelet).
import numpy as _np
# from abc import ABC as _ABC
# from abc import abstractmethod as _abstractmethod
# ===== POLYNOMIAL INTERFACE ========================================================
# # it would be useful to have some interface for enforcing specific
# # polynomial functionality and design. Currently, the following
# # code runs, but don't work (does not enforce the interface design).
#
# class _iPolynomial(_ABC):
# @staticmethod
# @_abstractmethod
# def WeightScheme(upToDegree, *argv):
# """Calculates polynomials weights.
# Parameters
# ----------
# upToDegree: int
# The maximum degree for which we desire to calculate the polynomial values.
# *argv: additional arguments
# Represents whatever parameter may be of need for specific weighting schemes.
# Returns
# -------
# ndarray
# The resulted array is an 1d ndarray, where its rows represent a weight for
# the corresponding polynomial values.
# """
# pass
# @staticmethod
# @_abstractmethod
# def Poly(upToDegree, x):
# """Calculates the n-th degree polynomial.
# Parameters
# ----------
# upToDegree: int
# The maximum degree for which we desire to calculate the polynomial values.
# x: ndarray
# The variable of the polynomial. It must be a 1D ndarray of the disired length.
# Returns
# -------
# ndarray
# The resulted array is a 2d ndarray, where the rows represent the degree
# and the columns the polynomial values.
# """
# pass
# -----------------------------------------------------------------------------------
def GetKernel(family, krnLen):
"""It is responsible for returning the selected kernel's calculation function along with the coresponding weights and some other stuff.
Parameters
----------
family: str
The 'family' parameter determines the kind of desired kernel that will be used in a moment transform.
Currently, the supported kernel families are:
* 'chebyshev1': the Chebyshev polynomials of the first kind,
* 'chebyshevD': the Discrete Chebyshev (or else Tchebichef) polynomials,
* 'geometric' : the geometric monomials (Pn(x) = x**n),
* 'central' : the central monomials (Pn(x; xm) = (x-xm)**n)
krnLen: int
It represents the kernel's length. Each kernel is a vector of values, which are
calculated by the selected 'family' of functions.
Returns
-------
tuple: (kernel, weights, xi, isOrthogonal)
The first element of the resulted tuple is the kernel's function, the second the the coresponding
weight function, the third is the variables values that are used as input in the kernel function
and finally the fourth element is a flag (boolean) which infroms whether or not the kernel is orthogonal.
Examples
--------
from pymoms import Kernel
import matplotlib.pyplot as plt
import numpy as np
def myplot(x, y, title, ylabel):
plt.figure(figsize=(15,5))
plt.plot(x, y)
plt.grid('on')
plt.title(title)
plt.xlabel('x')
plt.ylabel(ylabel)
plt.show()
upToOrder = 5
krnLen = 100
# Get the Chebyshev Polynomial of the first kind as Kernel.
# Actually, for the particular polynomial family, the resulted xi is given by:
# xi = np.cos(np.pi*(np.arange(0, krnLen)+0.5)/float(krnLen))
kernel, weights, xi, isOrthogonal = Kernel.GetKernel('chebyshev1', krnLen)
# Currently, the supported kernel families are:
# * 'chebyshev1': the Chebyshev polynomials of the first kind,
# * 'chebyshevD': the Discrete Chebyshev (or else Tchebichef) polynomials,
# * 'geometric' : the geometric monomials (Pn(x) = x**n),
# * 'central' : the central monomials (Pn(x; xm) = (x-xm)**n)
# Calculate the polynomial values and the corresponding weights
P = kernel(upToOrder, xi)
Wp = weights(upToOrder, krnLen)
P_norm = np.zeros(P.shape)
# normalized the polynomial values using the weights
for idx, p in enumerate(P):
P_norm[idx,:] = P[idx,:] * Wp[idx]
myplot(xi, P.T, 'Chebyshef Polynomial of first kind', '$P_{n}(x)$')
myplot(xi, P_norm.T, 'Norm. Chebyshef Polynomial of first kind', '$\overline{P}_{n}(x)$')
# let us define a different xi:
xi = np.linspace(-1, 1, krnLen)
myplot(xi, P.T, 'Chebyshef Polynomial of first kind', '$P_{n}(x)$')
"""
kernels = {
'chebyshev1': { # continuous Chebychev of 1st kind
'poly' : ConOrthoPoly.Chebyshev1st.Poly,
'weights' : ConOrthoPoly.Chebyshev1st.WeightScheme,
'x' : _np.cos(_np.pi*(_np.arange(0, krnLen)+0.5)/float(krnLen)),
'isOrthogonal': True,
},
'chebyshevD': { # discrete Chebyshef (or else Tchebichef)
'poly' : DisOrthoPoly.Chebyshev.Poly,
'weights' : DisOrthoPoly.Chebyshev.WeightScheme,
'x' : _np.arange(0, krnLen),
'isOrthogonal': True,
},
'geometric': {
'poly' : NonOrthoFunc.Geometric.Calc,
'weights' : NonOrthoFunc.Geometric.WeightScheme,
'x' : _np.arange(0, krnLen) / krnLen, # normalize for improve instability issues
'isOrthogonal': False,
},
'central': {
'poly' : NonOrthoFunc.Central.Calc,
'weights' : NonOrthoFunc.Central.WeightScheme,
'x' : (_np.arange(0, krnLen) - (krnLen-1)/2.) / krnLen, # normalize for improve instability issues
'isOrthogonal': False,
},
}
kernel = kernels[family]['poly']
weights = kernels[family]['weights']
xi = kernels[family]['x']
isOrthogonal = kernels[family]['isOrthogonal']
return kernel, weights, xi, isOrthogonal
# ===== DISCRETE ORTHOGONAL POLYNOMIALS =============================================
class DisOrthoPoly: # Orthogonal Discrete Polynomials
class Chebyshev: # also known as Tchebichef !
@staticmethod
def WeightScheme(upToDegree, *argv):
"""Calculates weights for the Discrete Chebyshev polynomials.
Parameters
----------
upToDegree: int
The maximum degree for which we desire to calculate the polynomial values.
*argv: additional arguments
It exists for sake of uniformity of similar functions. Here we don't need any
additional argument in order to calculate the weights.
Returns
-------
ndarray
The resulted array is an 1d ndarray of shape (upToDegree, 1), where its rows
represent the weight for the corresponding polynomial values.
Examples
--------
upToDegree = 5
W = OrthoDisPoly.Chebyshev.WeightScheme(upToDegree)
"""
return _np.ones((int(upToDegree+1), 1))
@staticmethod
def Poly(upToDegree, x):
"""Calculates up to n-th degree Discrete Chebyshev polynomial.
The discrete Chebyshev polynomials are orthogonal in the interval [0, N-1].
Parameters
----------
upToDegree: int
The maximum degree for which we desire to calculate the polynomial values.
x: ndarray
The variable of the polynomial. The elements of x must belong to [0, N-1],
where N determines the discrete domain in which the discrete Chebychef (or Tchebichef)
polynomials are defined.
Returns
-------
ndarray
The resulted array is a 2d ndarray of shape (upToDegree+1, N).
"""
N = _np.max(x)+1
P = _np.zeros((int(upToDegree+1), int(N)))
plnml = DisOrthoPoly.Chebyshev._Poly
for degree in range(0, int(upToDegree+1)):
P[degree, :] = plnml(degree, N)[0,:]
return P
@staticmethod
def _Poly(degree, N):
"""Calculates the n-th degree Discrete Chebyshev polynomial.
The discrete Chebyshev polynomials are orthogonal in the interval [0, N-1].
Parameters
----------
degree: int
The degree for which we desire to calculate the polynomial values.
N: int
Determines the discrete domain in which the discrete Chebychef (or Tchebichef)
polynomials are defined. The variable X of the polynomial must belong in the
interval [0, N-1].
Returns
-------
ndarray
The resulted array is a 1d ndarray of shape (1, N).
"""
X = N-1
P = _np.zeros((1, N))
T00 = 1.0 / _np.sqrt(N)
Tn0 = T00
for n in _np.arange(1, degree+1):
Tn0 = - _np.sqrt( (N - n) / float(N + n) ) * _np.sqrt( (2.0 * n + 1.0) / (2.0 * n - 1.0) ) * Tn0
if X == 0:
P[0, 0] = Tn0
elif X == 1:
P[0, | |
<gh_stars>0
import numpy as np
import pydart2 as pydart
import math
import dart_ik
import time
from fltk import *
from PyCommon.modules.GUI import hpSimpleViewer as hsv
from PyCommon.modules.Renderer import ysRenderer as yr
from PyCommon.modules.Simulator import yulQpSimulator_penalty as yulqp
# from PyCommon.modules.Simulator import yulQpSimulator_inequality_blade as yulqp
# from PyCommon.modules.Simulator import yulQpSimulator as yulqp
# from PyCommon.modules.Simulator import yulQpSimulator_noknifecon as yulqp
from PyCommon.modules.Motion import ysMotionLoader as yf
from PyCommon.modules.Math import mmMath as mm
render_vector = []
render_vector_origin = []
push_force = []
push_force_origin = []
push_force1 = []
push_force1_origin = []
blade_force = []
blade_force_origin = []
COM = []
l_blade_dir_vec = []
l_blade_dir_vec_origin = []
r_blade_dir_vec = []
r_blade_dir_vec_origin = []
ref_l_blade_dir_vec = []
ref_l_blade_dir_vec_origin = []
ref_r_blade_dir_vec = []
ref_r_blade_dir_vec_origin = []
r1_point = []
r2_point = []
new_bvh_load = False
# new_bvh_load = True
def TicTocGenerator():
ti = 0 # initial time
tf = time.time() # final time
while True:
ti = tf
ti = time.time()
yield ti - tf # returns the time difference
TicToc = TicTocGenerator() #create an instance of the TicToc generator
def toc(tempBool = True):
#Prints the time difference yielded by generator instance TicToc
tempTimeInterval = next(TicToc)
if tempBool:
print("Elapsed time: %f seconds.\n" %tempTimeInterval)
def tic():
#Records a time in TicToc, marks the beginning
toc(False)
class MyWorld(pydart.World):
def __init__(self, ):
pydart.World.__init__(self, 1.0 / 1000.0, './data/skel/blade2_3dof.skel')
self.force = None
self.force1 = None
self.my_tau = None
self.my_tau2 = None
self.my_force = None
self.my_force2 = None
# ---------------------------------- bvh -----------------------------------
bvh = yf.readBvhFileAsBvh('./data/mocap/walk_normal.bvh')
motion = yf.readBvhFile('./data/mocap/walk_normal.bvh', 0.0029, True)
self.bvh = bvh
self.motion = motion
self.duration = bvh.frameTime
fn = bvh.frameNum
self.fn = fn
if new_bvh_load:
tic()
self.ik = dart_ik.DartIk(self.skeletons[1])
self.q_list = []
# hips_index = motion[0].skeleton.getJointIndex('Hips')
left_elbow_index = motion[0].skeleton.getJointIndex('LeftArm')
left_wrist_index = motion[0].skeleton.getJointIndex('LeftForeArm')
left_knee_index = motion[0].skeleton.getJointIndex('LeftLeg')
left_ankle_index = motion[0].skeleton.getJointIndex('LeftFoot')
right_elbow_index = motion[0].skeleton.getJointIndex('RightArm')
right_wrist_index = motion[0].skeleton.getJointIndex('RightForeArm')
right_knee_index = motion[0].skeleton.getJointIndex('RightLeg')
right_ankle_index = motion[0].skeleton.getJointIndex('RightFoot')
# head_index = motion[0].skeleton.getJointIndex('Head')
neck_index = motion[0].skeleton.getJointIndex('Spine1')
chest_index = motion[0].skeleton.getJointIndex('Spine')
left_hip_index = motion[0].skeleton.getJointIndex('LeftUpLeg')
right_hip_index = motion[0].skeleton.getJointIndex('RightUpLeg')
# left_toe_index = motion[0].skeleton.getJointIndex('LeftToe')
# right_toe_index = motion[0].skeleton.getJointIndex('RightToe')
# left_shoulder_index = motion[0].skeleton.getJointIndex('LeftShoulder')
# right_shoulder_index = motion[0].skeleton.getJointIndex('RightShoulder')
for f in range(fn):
# motion.getJointPositionGlobal(left_knee_index)
q = self.skeletons[1].q
q[3:6] = motion.getJointPositionGlobal(0, f)
# q[3:6] = motion[f].local_ts[0]
self.skeletons[1].set_positions(q)
chest_pos = motion.getJointPositionGlobal(chest_index, f)
left_hip_vec = motion.getJointPositionGlobal(left_hip_index, f) - chest_pos
right_hip_vec = motion.getJointPositionGlobal(right_hip_index, f) - chest_pos
hip_unit_x = np.asarray(mm.normalize(mm.cross(right_hip_vec, left_hip_vec)))
hip_unit_y = -np.asarray(mm.normalize(left_hip_vec + right_hip_vec))
hip_unit_z = np.asarray(mm.normalize(mm.cross(hip_unit_x, hip_unit_y)))
hip_ori = mm.I_SO3()
hip_ori[:3, 0] = hip_unit_x
hip_ori[:3, 1] = hip_unit_y
hip_ori[:3, 2] = hip_unit_z
# left_blade_vec = motion.getJointPositionGlobal(left_toe_index, f) - motion.getJointPositionGlobal(
# left_ankle_index, f)
# right_blade_vec = motion.getJointPositionGlobal(right_toe_index, f) - motion.getJointPositionGlobal(
# right_ankle_index, f)
# head_vec = motion.getJointPositionGlobal(head_index, f) - motion.getJointPositionGlobal(neck_index, f)
self.ik.clean_constraints()
self.ik.add_orientation_const('h_pelvis', np.asarray(hip_ori))
# self.ik.add_joint_pos_const('j_abdomen', np.asarray(motion.getJointPositionGlobal(chest_index, f)))
# self.ik.add_vector_const('h_head', mm.unitY(), np.asarray(head_vec))
# self.ik.add_joint_pos_const('j_scapula_left', np.asarray(motion.getJointPositionGlobal(left_shoulder_index, f)))
self.ik.add_joint_pos_const('j_forearm_left', np.asarray(motion.getJointPositionGlobal(left_elbow_index, f)))
self.ik.add_joint_pos_const('j_hand_left', np.asarray(motion.getJointPositionGlobal(left_wrist_index, f)))
self.ik.add_joint_pos_const('j_shin_left', np.asarray(motion.getJointPositionGlobal(left_knee_index, f)))
self.ik.add_joint_pos_const('j_heel_left', np.asarray(motion.getJointPositionGlobal(left_ankle_index, f)))
# self.ik.add_joint_pos_const('j_scapula_right', np.asarray(motion.getJointPositionGlobal(right_shoulder_index, f)))
self.ik.add_joint_pos_const('j_forearm_right', np.asarray(motion.getJointPositionGlobal(right_elbow_index, f)))
self.ik.add_joint_pos_const('j_hand_right', np.asarray(motion.getJointPositionGlobal(right_wrist_index, f)))
self.ik.add_joint_pos_const('j_shin_right', np.asarray(motion.getJointPositionGlobal(right_knee_index, f)))
self.ik.add_joint_pos_const('j_heel_right', np.asarray(motion.getJointPositionGlobal(right_ankle_index, f)))
# self.ik.add_vector_const('h_heel_left', np.array([1., -0.8, 0.]), np.asarray(left_blade_vec))
# self.ik.add_vector_const('h_heel_right', np.array([1., -0.8, 0.]), np.asarray(right_blade_vec))
# left_toe_pos = motion.getJointPositionGlobal(left_toe_index, f)
# # print("lt: ", left_toe_pos)
# # left_toe_pos[1] = 0.0
# self.ik.add_position_const('h_blade_left', left_toe_pos, [-0.1040 + 0.0216, +0.80354016 - 0.85354016, 0.0])
# self.ik.add_position_const('h_blade_left', left_toe_pos, [0.1040 + 0.0216, +0.80354016 - 0.85354016, 0.0])
# right_toe_pos = motion.getJointPositionGlobal(right_toe_index, f)
# # right_toe_pos[1] = 0.0
# self.ik.add_position_const('h_blade_right', right_toe_pos, [-0.1040 + 0.0216, +0.80354016 - 0.85354016, 0.0])
# self.ik.add_position_const('h_blade_right', right_toe_pos, [0.1040 + 0.0216, +0.80354016 - 0.85354016, 0.0])
self.ik.solve()
self.q_list.append(self.skeletons[1].q)
#store q_list to txt file
with open('data/mocap/walk_normal.txt', 'w') as f:
for pose in self.q_list:
for a in pose:
f.write('%s ' % a)
f.write('\n')
# print(len(self.q_list[0]))
# print(self.q_list)
toc()
# read q_list from txt file
self.read_q_list = []
with open('data/mocap/walk_normal.txt') as f:
# lines = f.read().splitlines()
for line in f:
q_temp = []
line = line.replace(' \n', '')
values = line.split(" ")
for a in values:
q_temp.append(float(a))
self.read_q_list.append(q_temp)
#
# print(self.read_q_list)
# print(len(self.read_q_list))
#---------------------------------- bvh -----------------------------------
skel = self.skeletons[0]
# print("mass: ", skel.m, "kg")
# print('[Joint]')
# for joint in skel.joints:
# print("\t" + str(joint))
# print("\t\tparent = " + str(joint.parent_bodynode))
# print("\t\tchild = " + str(joint.child_bodynode))
# print("\t\tdofs = " + str(joint.dofs))
#
# skel.joint("j_abdomen").set_position_upper_limit(10, 0.0)
self.skeletons[1].set_positions(self.read_q_list[0])
self.elapsedTime = 0
self.fn_bvh = 0
self.flag = 0
self.l_dir = np.array([0., 0., 0.])
self.r_dir = np.array([0., 0., 0.])
self.l_blade_dir = np.array([0., 0., 0.])
self.r_blade_dir = np.array([0., 0., 0.])
self.r1 = np.array([0., 0., 0.])
self.r2 = np.array([0., 0., 0.])
self.contact_force = []
self.contactPositionLocals = []
self.bodyIDs = []
# print("dof: ", skel.ndofs)
def step(self):
# if self.fn_bvh == 0 and self.flag < 200:
# print("here? : ", self.fn_bvh, self.flag)
# self.skeletons[1].set_positions(self.read_q_list[self.fn_bvh])
# self.flag += 1
# else:
# if self.fn_bvh < 10:
# self.force = np.array([0.0, 0.0, 50.0])
# else:
# self.force = None
#
# if self.flag < 10:
# self.skeletons[1].set_positions(self.read_q_list[self.fn_bvh])
# self.flag += 1
# else:
# self.flag = 0
# self.fn_bvh += 1
# if self.fn_bvh < 10:
# self.force = np.array([0.0, 0.0, 50.0])
# else:
# self.force = None
ref_skel = self.skeletons[1]
# q_temp = np.asarray(ref_skel.q)
# cur_com_pos = ref_skel.com()
#
# ref_skel.set_positions(self.read_q_list[self.fn_bvh + 1])
# future_com_pos = ref_skel.com()
# ref_skel.set_positions(q_temp)
#
# ref_com_vel = future_com_pos - cur_com_pos
# # print("COM_VEL", ref_com_vel)
# self.force = 1000.* ref_com_vel
if self.flag < 10:
self.skeletons[1].set_positions(self.read_q_list[self.fn_bvh])
self.flag += 1
else:
self.flag = 0
self.fn_bvh += 1
ndofs = skel.num_dofs()
h = self.time_step()
# PD CONTROL
q_revised = np.asarray(self.read_q_list[self.fn_bvh])
q_revised[0:1] = 0.001
# gain_value = 25.0
gain_value = 50.0
Kp = np.diagflat([0.0] * 6 + [gain_value] * (ndofs - 6))
Kd = np.diagflat([0.0] * 6 + [2. * (gain_value ** .5)] * (ndofs - 6))
invM = np.linalg.inv(skel.M + Kd * h)
p = -Kp.dot(skel.q - q_revised + skel.dq * h)
d = -Kd.dot(skel.dq)
qddot = invM.dot(-skel.c + p + d + skel.constraint_forces())
des_accel = p + d + qddot
ddc = np.zeros(6)
if self.fn_bvh < self.fn:
q_temp = np.asarray(ref_skel.q)
cur_blade_left_pos = ref_skel.body('h_blade_left').to_world([0., 0., 0.])
cur_blade_right_pos = ref_skel.body('h_blade_right').to_world([0., 0., 0.])
cur_v1 = ref_skel.body('h_blade_left').to_world([-0.1040 + 0.0216, 0.0, 0.0])
cur_v2 = ref_skel.body('h_blade_left').to_world([0.1040 + 0.0216, 0.0, 0.0])
blade_direction_vec_l = cur_v2 - cur_v1
cur_blade_direction_vec_l = np.array([1, 0, 1]) * blade_direction_vec_l
cur_v1 = ref_skel.body('h_blade_right').to_world([-0.1040 + 0.0216, 0.0, 0.0])
cur_v2 = ref_skel.body('h_blade_right').to_world([0.1040 + 0.0216, 0.0, 0.0])
blade_direction_vec_r = cur_v2 - cur_v1
cur_blade_direction_vec_r = np.array([1, 0, 1]) * blade_direction_vec_r
if np.linalg.norm(cur_blade_direction_vec_l) != 0:
cur_blade_direction_vec_l = cur_blade_direction_vec_l / np.linalg.norm(cur_blade_direction_vec_l)
if np.linalg.norm(cur_blade_direction_vec_r) != 0:
cur_blade_direction_vec_r = cur_blade_direction_vec_r / np.linalg.norm(cur_blade_direction_vec_r)
ref_skel.set_positions(self.read_q_list[self.fn_bvh+1])
future_blade_left_pos = ref_skel.body('h_blade_left').to_world([0., 0., 0.])
future_blade_right_pos = ref_skel.body('h_blade_right').to_world([0., 0., 0.])
slidingAxisLeft = future_blade_left_pos - cur_blade_left_pos
slidingAxisRight = future_blade_right_pos - cur_blade_right_pos
slidingAxisLeft = np.array([1, 0, 1]) * slidingAxisLeft
slidingAxisRight = np.array([1, 0, 1]) * slidingAxisRight
if np.linalg.norm(slidingAxisLeft) != 0:
slidingAxisLeft = slidingAxisLeft / np.linalg.norm(slidingAxisLeft)
if np.linalg.norm(slidingAxisRight) != 0:
slidingAxisRight = slidingAxisRight / np.linalg.norm(slidingAxisRight)
r_vec_l = skel.body('h_blade_left').to_local([0., 0., 0.])
r_vec_l = np.array([1, 0, 1]) * r_vec_l
r_vec_r = skel.body('h_blade_right').to_local([0., 0., 0.])
r_vec_r = np.array([1, 0, 1]) * r_vec_r
r_vec_ref_l = ref_skel.body('h_blade_left').to_local([0., 0., 0.])
r_vec_ref_l = np.array([1, 0, 1]) * r_vec_ref_l
r_vec_ref_r = ref_skel.body('h_blade_right').to_local([0., 0., 0.])
r_vec_ref_r = np.array([1, 0, 1]) * r_vec_ref_r
zero_term = np.linalg.norm(r_vec_l - r_vec_ref_l) + np.linalg.norm(r_vec_r - r_vec_ref_r)
ddc[0:3] = 1/(2*1.5)*zero_term + 0.1*(skel.com_velocity())
ref_skel.set_positions(q_temp)
self.l_dir = slidingAxisLeft
self.r_dir = slidingAxisRight
self.l_blade_dir = cur_blade_direction_vec_l
self.r_blade_dir = cur_blade_direction_vec_r
# YUL QP solve
_ddq, _tau, _bodyIDs, _contactPositions, _contactPositionLocals, _contactForces = yulqp.calc_QP(
skel, des_accel, ddc, slidingAxisLeft, slidingAxisRight, cur_blade_direction_vec_l, cur_blade_direction_vec_r, 1. / self.time_step())
del self.contact_force[:]
del self.bodyIDs[:]
del self.contactPositionLocals[:]
self.bodyIDs = _bodyIDs
for i in range(len(_bodyIDs)):
skel.body(_bodyIDs[i]).add_ext_force(_contactForces[i], _contactPositionLocals[i])
self.contact_force.append(_contactForces[i])
self.contactPositionLocals.append(_contactPositionLocals[i])
# dartModel.applyPenaltyForce(_bodyIDs, _contactPositionLocals, _contactForces)
# External force
# if self.fn_bvh < 10:
# self.force = 15.*np.array([0.0, -1.0, 100.0])
# # self.force1 = 1.*np.array([-20.0, 0.0, -100.0])
#
# # self.force = 1. * np.array([-1.0, -1.0, 100.0])
# # self.force1 = 1. * np.array([.0, -0.0, -100.0])
# else:
# self.force = None
# self.force1 = None
if self.force is not None:
self.skeletons[0].body('h_pelvis').add_ext_force(self.force, [0., 0., -0.1088])
if self.force1 is not None:
self.skeletons[0].body('h_pelvis').add_ext_force(self.force1, [0., 0., 0.1088])
# Jacobian transpose control
if self.fn_bvh < 20:
my_jaco = skel.body("h_blade_right").linear_jacobian()
my_jaco_t = my_jaco.transpose()
self.my_force2 = 30. * np.array([-5.0, 0., -5.0])
# self.my_force2 = 10. * slidingAxisRight
self.my_tau2 = np.dot(my_jaco_t, self.my_force2)
p1 = skel.body("h_blade_left").to_world([-0.1040 + 0.0216, 0.0, 0.0])
p2 = skel.body("h_blade_left").to_world([0.1040 + 0.0216, 0.0, 0.0])
blade_direction_vec = p2 - p1
blade_direction_vec[1] = -0.
if np.linalg.norm(blade_direction_vec) != 0:
blade_direction_vec = blade_direction_vec | |
<filename>modules/plugin_managed_html.py<gh_stars>1-10
# -*- coding: utf-8 -*-
# This plugins is licensed under the MIT license: http://www.opensource.org/licenses/mit-license.php
# Authors: <NAME> <<EMAIL>>
from gluon import *
from gluon.storage import Storage
from gluon.validators import Validator
import gluon.contrib.simplejson as json
# from plugin_uploadify_widget import IS_UPLOADIFY_IMAGE as IS_IMAGE
# from plugin_uploadify_widget import IS_UPLOADIFY_LENGTH as IS_LENGTH
# For referencing static and views from other application
import os
APP = os.path.basename(os.path.dirname(os.path.dirname(__file__)))
LIVE_MODE = '_managed_html_live'
EDIT_MODE = '_managed_html_edit'
PREVIEW_MODE = '_managed_html_preview'
REFERENCE_MODE = '_managed_html_reference'
IMAGE_EXTENSIONS = ('png', 'jpg', 'jpeg', 'gif', 'bmp')
MOVIE_EXTENSIONS = ('flv', 'mp4', 'm4v', 'avi', 'wmv')
FILE_EXTENSIONS = None
class IS_HTML(Validator):
def _strip(self, value):
if value in ('<p> </p>', ' '):
value = ''
if value:
value = value.strip(' ')
while True:
if value.startswith('\n'):
value = value[1:]
if value.startswith('<div><br /></div>'):
value = value[17:]
elif value.startswith('<br />'):
value = value[6:]
else:
break
return value
def __call__(self, value):
try:
from BeautifulSoup import BeautifulSoup
_soup = BeautifulSoup
except ImportError:
_soup = lambda v: v
return (self._strip(str(_soup(value))), None)
class ManagedHTML(object):
def __init__(self, db, keyword='_managed_html'):
self.db, self.keyword = db, keyword
self.file_grid_keyword = '_managed_html_%s_grid'
self.page_grid_keyword = '_managed_html_page_grid'
self.history_grid_keyword = '_managed_html_history_grid'
self.contents_cache = {}
settings = self.settings = Storage()
settings.URL = URL
settings.home_url = '/'
settings.home_label = 'Home'
settings.table_content_name = 'managed_html_content'
settings.table_content = None
settings.table_file_name = 'managed_html_file'
settings.table_file = None
settings.extra_fields = {}
settings.text_widget_cssfiles = [] # ex) [URL('static', 'css/base.css')]
settings.uploadfolder = os.path.join(self.db._adapter.folder, '..', 'uploads')
settings.upload = lambda filename: URL('download', args=[filename]) # TODO
settings.page_grid = None
# settings.page_original_url = ''
settings.editable = True
settings.publishable = True
def _html(name, parent=None):
@self.content_block(name, Field('html', 'text'), parent=parent)
def _(content):
current.response.write(XML(content.html or '').xml(), escape=False)
_()
return ''
settings.content_types = Storage(html=_html)
self.view_mode = LIVE_MODE
settings.devices = [{'name':'pc', 'label':'PC', 'show_side_view':False},
{'name':'mobile', 'label':'Smart-Phone', 'request_updator':{'is_mobile':True}, 'show_side_view':True, 'view_width':'320'}]
def url(self, a=None, c=None, f=None, r=None, args=None, vars=None, **kwds):
if not r:
if a and not c and not f:
(f, a, c) = (a, c, f)
elif a and c and not f:
(c, f, a) = (a, c, f)
if c != 'static':
_arg0 = current.request.args(0)
if _arg0 and (EDIT_MODE in _arg0 or PREVIEW_MODE in _arg0 or REFERENCE_MODE in _arg0):
return self._mode_url(_arg0, a, c, f, r, args, vars, **kwds)
return self.settings.URL(a, c, f, r, args, vars, **kwds)
def _mode_url(self, mode, a=None, c=None, f=None, r=None, args=None, vars=None, **kwds):
if args in (None, []):
args = [mode]
elif not isinstance(args, (list, tuple)):
args = [mode, args]
else:
args = [mode] + args
return self.settings.URL(a, c, f, r, args=args, vars=vars, **kwds)
def define_tables(self, migrate=True, fake_migrate=False):
db, settings, T = self.db, self.settings, current.T
if not settings.table_content_name in db.tables:
db.define_table(settings.table_content_name,
Field('name', readable=False, writable=False),
Field('publish_on', 'datetime', readable=False, writable=False),
Field('data', 'text', default=''),
migrate=migrate, fake_migrate=fake_migrate,
*settings.extra_fields.get(settings.table_content_name, []))
settings.table_content = db[settings.table_content_name]
if not settings.table_file_name in db.tables:
db.define_table(settings.table_file_name,
Field('name', 'upload', unique=True,
label=T('File'), autodelete=True),
# Field('original_name'),
Field('keyword', label=T('Keyword')),
Field('description', 'text', label=T('Description')),
Field('extension', label=T('Extension'), length=16, readable=False, writable=False),
Field('thumbnail', 'upload', autodelete=True, readable=False, writable=False),
migrate=migrate, fake_migrate=fake_migrate,
*settings.extra_fields.get(settings.table_file_name, []))
settings.table_file = db[settings.table_file_name]
def _get_content(self, name, cache=None, id=None):
if self.view_mode == LIVE_MODE:
loaded_record = self.contents_cache.get(name)
if loaded_record:
return loaded_record
table_content = self.settings.table_content
return self.db(table_content.name == name)(table_content.publish_on <= current.request.now
).select(orderby=~table_content.id, cache=cache).first()
else:
table_content = self.settings.table_content
query = (table_content.name == name)
if id:
query &= (table_content.id == id)
record = self.db(query).select(orderby=~table_content.id).first()
self.contents_cache[name] = record
return record
def _is_published(self, content):
return (content is None) or bool(content.publish_on and
content.publish_on <= current.request.now)
def load_contents(self, content_names):
if not content_names:
return
table_content = self.settings.table_content
# records = self.db(
# table_content.name.belongs(content_names))(
# table_content.publish_on!=None
# ).select(table_content.ALL,
# table_content.publish_on.max(),
# groupby=table_content.name)
max_id = table_content.id.max()
_ids = [r[max_id] for r in self.db(
table_content.name.belongs(content_names))(
table_content.publish_on <= current.request.now
).select(max_id, groupby=table_content.name)]
if _ids:
records = self.db(table_content.id.belongs(_ids)).select(table_content.ALL)
for r in records:
self.contents_cache[r.name] = r
def switch_mode(self):
settings, request, response, T = self.settings, current.request, current.response, current.T
_arg0 = request.args(0)
if not (_arg0 and (EDIT_MODE in _arg0 or PREVIEW_MODE in _arg0 or REFERENCE_MODE in _arg0)):
self.view_mode = LIVE_MODE
return
else:
self.view_mode = _arg0
current_device = None
for device in self.settings.devices:
suffix = '_managed_html_%s'%device['name']
if suffix in _arg0:
request.update(**device.get('request_updator', {}))
current_device = device
break
if request.args and request.args[-1] == 'managed_html.js':
# Return javascript
from globals import Response, Storage
_response = Response()
_response._view_environment = current.globalenv.copy()
_response._view_environment.update(
request=Storage(folder=os.path.join(os.path.dirname(os.path.dirname(request.folder)), APP)),
response=_response,
)
_device_url_base = self.view_mode
for device in self.settings.devices:
_device_url_base = _device_url_base.replace('_managed_html_%s'%device['name'], '')
for device in self.settings.devices:
device.update({'url':self.settings.URL(args=[_device_url_base+'_managed_html_%s'%device['name']]+request.args[1:-1], vars=request.vars)})
_response.headers['Content-Type'] = 'text/javascript; charset=utf-8;'
raise HTTP(200, _response.render('plugin_managed_html/managed_html_ajax.js',
dict(
home_url=settings.home_url,
home_label=settings.home_label,
edit_url=settings.URL(args=[self.view_mode.replace(PREVIEW_MODE, EDIT_MODE).replace(REFERENCE_MODE, EDIT_MODE)] +
request.args[1:-1], vars=request.vars)
if PREVIEW_MODE in self.view_mode or REFERENCE_MODE in self.view_mode else '',
preview_url=settings.URL(args=[self.view_mode.replace(EDIT_MODE, PREVIEW_MODE).replace(REFERENCE_MODE, PREVIEW_MODE)] +
request.args[1:-1], vars=request.vars)
if EDIT_MODE in self.view_mode or REFERENCE_MODE in self.view_mode else '',
reference_url=settings.URL(args=[self.view_mode.replace(EDIT_MODE, REFERENCE_MODE).replace(PREVIEW_MODE, REFERENCE_MODE).replace('_managed_html_%s'%current_device['name'] if current_device else '', '')] +
request.args[1:-1], vars=request.vars)
if EDIT_MODE in self.view_mode or PREVIEW_MODE in self.view_mode else '',
live_url=self.settings.URL(args=request.args[1:-1], vars=request.vars, scheme='http'),
show_page_grid=self._show_page_grid_js() if settings.page_grid else '',
devices=self.settings.devices,
current_device=current_device,
is_edit_mode=EDIT_MODE in self.view_mode,
is_preview_mode=PREVIEW_MODE in self.view_mode,
)),
**_response.headers)
response.files.append(URL(args=((request.args or []) + ['managed_html.js'])))
self.use_grid(args=request.args[:2])
def use_grid(self, args):
settings, request, response, T = self.settings, current.request, current.response, current.T
from plugin_solidgrid import SolidGrid
self.solidgrid = SolidGrid(renderstyle=True)
for file_type in ('image', 'movie', 'file'):
_grid_keyword = self.file_grid_keyword % file_type
if (_grid_keyword in request.vars or
(_grid_keyword in request.args)):
if not self.settings.editable:
raise HTTP(400)
raise HTTP(200, self._file_grid(file_type=file_type, args=args))
if ((self.history_grid_keyword in request.vars) or
(self.history_grid_keyword in request.args)):
if not self.settings.editable:
raise HTTP(400)
raise HTTP(200, self._history_grid(args=args))
_files = [
URL(APP, 'static', 'plugin_managed_html/managed_html.css'),
URL(APP, 'static', 'plugin_managed_html/jquery.spinner.js'),
URL(APP, 'static', 'plugin_elrte_widget/js/jquery-ui-1.8.16.custom.min.js'),
URL(APP, 'static', 'plugin_managed_html/bootstrap-dropdown.js'),
]
response.files[:0] = [f for f in _files if f not in response.files]
def _show_page_grid_js(self):
from plugin_dialog import DIALOG
T = current.T
return DIALOG(title=T('+ Page'), close_button=T('close'),
content=self.settings.page_grid,
_class='managed_html_dialog').show(reload=True)
def _show_history_grid_js(self, content_name, collection=False):
from plugin_dialog import DIALOG
T = current.T
request = current.request
_post_js = self._post_content_js if not collection else self._post_collection_js
return """
jQuery(document.body).one('managed_html_history_selected', function(e, content_id) {
eval('%(post)s'.replace("__placeholder__", content_id));
jQuery('.managed_html_dialog').hide();
}); %(show)s; return false;""" % dict(
post=_post_js(content_name, 'revert', content_id='__placeholder__'),
show=DIALOG(title=T('History'), close_button=T('close'),
content=LOAD(url=URL(args=(request.args or []) + ['history'],
vars={self.history_grid_keyword: content_name}), ajax=True),
_class='managed_html_dialog'
).show(reload=True))
def _history_grid(self, args):
T = current.T
request = current.request
table_content = self.settings.table_content
table_content.publish_on.label = T('Publish on')
table_content.publish_on.represent = lambda v: v and v or '---'
def _represent(v):
if not v:
return '---'
data = json.loads(v)
if type(data) == dict:
return DIV([DIV(DIV(k), TEXTAREA(v, _rows=3, _cols=50, _style='width:90%;'))
for k, v in data.items()])
elif type(data) == list:
return DIV([DIV(k, ':', v) for k, v in data])
table_content.data.represent = _represent
extracolumns = [
{'label': '', 'width': '150px;',
'content':lambda row, rc:
SPAN(self.solidgrid.settings.recordbutton('ui-icon-circle-arrow-w', T('Revert'),
'#', _onclick="""
jQuery(document.body).trigger('managed_html_history_selected', ['%s']);return false;
""" % (row.id), _class='ui-btn'))},
]
content_name = request.vars.get(self.history_grid_keyword, request.args(2))
query = (table_content.name == content_name)
grid = self.solidgrid(
query,
columns=[extracolumns[0], table_content.publish_on, table_content.data],
extracolumns=extracolumns,
create=False,
editable=False,
details=False,
showid=False,
searchable=False,
sortable=[~table_content.id],
csv=False,
args=args + [self.history_grid_keyword, content_name],
)
return DIV(DIV(grid.gridbuttons), DIV(_style='clear:both;'), BR(), HR(),
DIV(DIV(_style='clear:both;'), grid),
_class='history_grid')
def _file_grid(self, file_type, args):
T = current.T
table_file = self.settings.table_file
request = current.request
if request.vars._hmac_key:
hmac_key = request.vars._hmac_key
user_signature = False
request.get_vars._signature = request.post_vars._signature
else:
hmac_key = None
user_signature = True
from plugin_uploadify_widget import uploadify_widget
def _uploadify_widget(field, value, download_url=None, **attributes):
if current.session.auth:
attributes['extra_vars'] = {'_signature': request.get_vars._signature,
'_hmac_key': current.session.auth.hmac_key}
return uploadify_widget(field, value, download_url, **attributes)
table_file.name.widget = _uploadify_widget
table_file.name.uploadfolder = self.settings.uploadfolder
table_file.name.comment = self.settings.get('%s_comment' % file_type)
table_file.name.requires = self.settings.get('%s_requires' % file_type)
def _oncreate(form):
if 'filename' in request.vars.name:
filename = request.vars.name.filename
if filename:
extension = filename.split('.')[-1].lower()
thumbnail = ''
if extension in (IMAGE_EXTENSIONS + MOVIE_EXTENSIONS):
if extension in IMAGE_EXTENSIONS:
# TODO
# (nx, ny) = 80, 80
# from PIL import Image
# img = Image.open(os.path.join(self.settings.uploadfolder, filename))
# # print img.size # TODO
# img.thumbnail((nx, ny), Image.ANTIALIAS)
# root, ext = os.path.splitext(filename)
# thumbnail = '%s_thumbnail%s' % (root, ext)
# img.save(os.path.join(self.settings.uploadfolder, thumbnail))
thumbnail = filename
self.db(self.settings.table_file.id == form.vars.id).update(
name=filename, extension=extension, thumbnail=thumbnail,
)
_grid_keyword = self.file_grid_keyword % file_type
_extensions = {'image': IMAGE_EXTENSIONS,
'movie': MOVIE_EXTENSIONS,
'file': FILE_EXTENSIONS,
}.get(file_type)
extracolumns = [
{'label': '', 'width': '150px;',
'content':lambda row, rc:
SPAN(self.solidgrid.settings.recordbutton('ui-icon-seek-next', T('Select'),
'#', _onclick="""
jQuery(document.body).trigger('managed_html_file_selected', ['%s', '%s']);return false;
""" % (row.name, row.thumbnail), _class='ui-btn'))},
{'label': T('File'), 'width': '150px;',
'content':lambda row, rc: DIV(
DIV(self._file_represent(row.name, row.thumbnail)),
TEXTAREA(self.settings.upload(row.name), _rows=1),
_style='word-break:break-all;')}
]
main_table = table_file
grid | |
0), parent=view.scene)
view.add(line)
# -------------------------------
# Zeichnen der Koordinatenachsen
# -------------------------------
def _axes_mayavi(**kwargs):
x_bez = kwargs.get('x_bez')
y_bez = kwargs.get('y_bez')
z_bez = kwargs.get('z_bez')
xl, xr, yl, yr, zl, zr = UMG._sicht_box
_mass = UMG._mass()
f = (0.85, 0.85, 0.85)
f1 = (0.1, 0.1, 0.1)
h = min(100., _mass)
x_achse = _arrow(xl, 0, 0, xr+0.5*_mass, 0, 0, size=2, cone_height=h,
color=f, tube_radius=None)
y_achse = _arrow(0, yl, 0, 0, yr+0.5*_mass, 0, size=2, cone_height=h,
color=f, tube_radius=None)
z_achse = _arrow(0, 0, zl, 0, 0, zr+0.5*_mass, size=2, cone_height=h,
color=f, tube_radius=None)
mlab.text3d(xr*0.9, 0, -1.5*_mass, x_bez, scale=0.5*_mass, color=f1,
opacity=0.8)
mlab.text3d(0, yr*0.9, -1.5*_mass, y_bez, scale=0.5*_mass, color=f1,
opacity=0.8)
mlab.text3d(0, -1.5*_mass, zr*0.9, z_bez, scale=0.5*_mass,
color=f1, opacity=0.8)
def _axes_vispy(view, **kwargs):
x_bez = kwargs.get('x_bez')
y_bez = kwargs.get('y_bez')
z_bez = kwargs.get('z_bez')
xl, xr, yl, yr, zl, zr = UMG._sicht_box
x_achse = scene.visuals.Line(pos=np.array([[xl, 0, 0], [xr, 0, 0]]),
color=(1,0,0,1), parent=view.scene)
view.add(x_achse)
y_achse = scene.visuals.Line(pos=np.array([[0, yl, 0], [0, yr, 0]]),
color=(0,1,0,1), parent=view.scene)
view.add(y_achse)
z_achse = scene.visuals.Line(pos=np.array([[0, 0, zl], [0, 0, zr]]),
color=(0,0,1,1), parent=view.scene)
view.add(z_achse)
# --------------------
# Zeichnen der Skalen
# --------------------
def _x_skala_mayavi(pos):
# pos = 0: entlang der x-Achse
# pos <> 0: entlang der unteren Box-Kante
xl, xr, yl, yr, zl, zr = UMG._sicht_box
if max(abs(xl), xr) < 1.8:
teiler = [0.25, 0.5]
elif max(abs(xl), xr) < 3.9:
teiler = [0.5, 1.]
elif max(abs(xl), xr) < 10:
teiler = [1., 2.]
else:
schritt = [1., 2., 5., 10., 20., 50., 100., 200., 500., 1000., 5000.]
ra = np.ceil(xr)+1 - np.ceil(xl)
for i in list(range(len(schritt))):
if np.ceil(ra/4) < schritt[i]:
teiler = [schritt[i-1]/2, schritt[i-1]]
break
schritt0, schritt1 = teiler
txt = lambda x: str(int(x)) if int(x) == x else format(x, '.1f')
f = (0.1, 0.1, 0.1)
xi = 0
if pos is None:
return
elif pos:
yy, zz = yr, zl
else:
yy, zz = 0, 0
_mass = UMG._mass()
op = 0.7
while xi <= xr:
x, y, z = [xi, xi], [yy, yy+0.25*_mass], [zz, zz]
mlab.plot3d(x, y, z, tube_radius=None, color=f, line_width=0.01,
opacity=op)
mlab.text3d(xi, yy+0.6*_mass, zz-0.3*_mass, txt(xi), \
scale=0.3*_mass, color=f, opacity=op)
xi += schritt1
xi = 0
while xi <= xr:
x, y, z = [xi, xi], [yy, yy+0.25*_mass], [zz, zz]
mlab.plot3d(x, y, z, tube_radius=None, color=f, line_width=0.01,
opacity=op)
xi += schritt0
xi = schritt1
while xi >= xl:
x, y, z = [xi, xi], [yy, yy+0.25*_mass], [zz, zz]
mlab.plot3d(x, y, z, tube_radius=None, color=f, line_width=0.01,
opacity=op)
mlab.text3d(xi, yy+0.6*_mass, zz-0.3*_mass, txt(xi),
scale=0.3*_mass, color=f, opacity=op)
xi -= schritt1
xi = schritt0
while xi >= xl:
x, y, z = [xi, xi], [yy, yy+0.25*_mass], [zz, zz]
mlab.plot3d(x, y, z, tube_radius=None, color=f, line_width=0.01,
opacity=op)
xi -= schritt0
def _x_skala_vispy(view, pos):
# pos = 0: entlang der x-Achse
# pos <> 0: entlang der unteren Box-Kante
xl, xr, yl, yr, zl, zr = UMG._sicht_box
if max(abs(xl), xr) < 1.8:
teiler = [0.25, 0.5]
elif max(abs(xl), xr) < 3.9:
teiler = [0.5, 1.]
elif max(abs(xl), xr) < 10:
teiler = [1., 2.]
else:
schritt = [1., 2., 5., 10., 20., 50., 100., 200., 500., 1000., 5000.]
ra = np.ceil(xr)+1 - np.ceil(xl)
for i in list(range(len(schritt))):
if np.ceil(ra/4) < schritt[i]:
teiler = [schritt[i-1]/2, schritt[i-1]]
break
schritt0, schritt1 = teiler
txt = lambda x: str(int(x)) if int(x) == x else format(x, '.1f')
xi = 0
if pos is None:
return
elif pos:
yy, zz = yr, zl
else:
yy, zz = 0, 0
_mass = UMG._mass()
while xi <= xr:
pos = np.array([[xi, yy, zz], [xi, yy+0.25*_mass, zz]])
line = scene.visuals.Line(pos=pos, color=(0,0,0,1), parent=view.scene)
view.add(line)
xi += schritt1
xi = 0
while xi <= xr:
pos = np.array([[xi, yy, zz], [xi, yy+0.25*_mass, zz]])
line = scene.visuals.Line(pos=pos, color=(0,0,0,1), parent=view.scene)
view.add(line)
xi += schritt0
xi = schritt1
while xi >= xl:
pos = np.array([[xi, yy, zz], [xi, yy+0.25*_mass, zz]])
line = scene.visuals.Line(pos=pos, color=(0,0,0,1), parent=view.scene)
view.add(line)
xi -= schritt1
xi = schritt0
while xi >= xl:
pos = np.array([[xi, yy, zz], [xi, yy+0.25*_mass, zz]])
line = scene.visuals.Line(pos=pos, color=(0,0,0,1), parent=view.scene)
view.add(line)
xi -= schritt0
text1 = scene.visuals.Text(txt(0), pos=[0, yy+0.6*_mass, zz-0.3*_mass],
color=(0,0,0,1), font_size=12, parent=view.scene)
text2 = scene.visuals.Text(txt(xl), pos=[xl, yy+0.6*_mass, zz-0.3*_mass],
color=(0,0,0,1), font_size=12, parent=view.scene)
text3 = scene.visuals.Text(txt(xr), pos=[xr, yy+0.6*_mass, zz-0.3*_mass],
color=(0,0,0,1), font_size=12, parent=view.scene)
view.add(text1)
view.add(text2)
view.add(text3)
def _y_skala_mayavi(pos):
# pos = 0: entlang der y-Achse
# pos <> 0: entlang der unteren Box-Kante
xl, xr, yl, yr, zl, zr = UMG._sicht_box
if max(abs(yl), yr) < 1.8:
teiler = [0.25, 0.5]
elif max(abs(yl), yr) < 3.9:
teiler = [0.5, 1.]
elif max(abs(yl), yr) < 10:
teiler = [1., 2.]
else:
schritt = [1., 2., 5., 10., 20., 50., 100., 200., 500., 1000., 5000.]
ra = np.ceil(yr)+1 - np.ceil(yl)
for i in list(range(len(schritt))):
if np.ceil(ra/4) < schritt[i]:
teiler = [schritt[i-1]/2, schritt[i-1]]
break
schritt0, schritt1 = teiler
txt = lambda x: str(int(x)) if int(x) == x else format(x, '.1f')
f = (0.1, 0.1, 0.1)
yi = 0
if pos is None:
return
elif pos:
xx, zz = xr, zl
else:
xx, zz = 0, 0
_mass = UMG._mass()
op = 0.7
mlab.text3d(xx+0.6*_mass, 0, zz-0.8*_mass,
txt(0), scale=0.3*_mass, color=f, opacity=op)
while yi <= yr:
x, y, z = [xx, xx+0.25*_mass], [yi, yi], [zz, zz]
mlab.plot3d(x, y, z, tube_radius=None, color=f, line_width=0.01,
opacity=op)
if yi != 0:
mlab.text3d(xx+0.6*_mass, yi-0.3*_mass, zz-0.8*_mass,
txt(yi), scale=0.3*_mass, color=f, opacity=op)
yi += schritt1
yi = 0
while yi <= yr:
x, y, z = [xx, xx+0.25*_mass], [yi, yi], [zz, zz]
mlab.plot3d(x, y, z, tube_radius=None, color=f, line_width=0.01,
opacity=op)
yi += schritt0
yi = schritt1
while yi >= yl:
x, y, z = [xx, xx+0.25*_mass], [yi, yi], [zz, zz]
mlab.plot3d(x, y, z, tube_radius=None, color=f, line_width=0.01,
opacity=op)
if yi != 0:
mlab.text3d(xx+0.6*_mass, yi-0.3*_mass, zz-0.8*_mass,
txt(yi), scale=0.3*_mass, color=f, opacity=op)
yi -= schritt1
yi = schritt0
while yi >= yl:
x, y, z = [xx, xx+0.25*_mass], [yi, yi], [zz, zz]
mlab.plot3d(x, y, z, tube_radius=None, color=f, line_width=0.01,
opacity=op)
yi -= schritt0
def _y_skala_vispy(view, pos):
# pos = 0: entlang der y-Achse
# pos <> 0: entlang der unteren Box-Kante
xl, xr, yl, yr, zl, zr = UMG._sicht_box
if max(abs(yl), yr) < 1.8:
teiler = [0.25, 0.5]
elif max(abs(yl), yr) < 3.9:
teiler = [0.5, 1.]
elif max(abs(yl), yr) < 10:
teiler = [1., 2.]
else:
schritt = [1., 2., 5., 10., 20., 50., 100., 200., 500., 1000., 5000.]
ra = np.ceil(yr)+1 - np.ceil(yl)
for i in list(range(len(schritt))):
if np.ceil(ra/4) < schritt[i]:
teiler = [schritt[i-1]/2, schritt[i-1]]
break
schritt0, schritt1 = teiler
txt = lambda x: str(int(x)) if int(x) == x else format(x, '.1f')
f = (0.1, 0.1, 0.1)
yi = 0
if pos is None:
return
elif pos:
xx, zz = xr, zl
else:
xx, zz = 0, 0
_mass = UMG._mass()
while yi <= yr:
pos = np.array([[xx, yi, zz], [xx+.25*_mass, yi, zz]])
line = scene.visuals.Line(pos=pos, color=(0,0,0,1), parent=view.scene)
view.add(line)
yi += schritt1
yi = 0
while yi <= yr:
x, y, z = [xx, xx+0.25*_mass], [yi, yi], [zz, zz]
pos = np.array([[xx, yi, zz], [xx+.25*_mass, yi, zz]])
line = scene.visuals.Line(pos=pos, color=(0,0,0,1), parent=view.scene)
view.add(line)
yi += schritt0
yi = schritt1
while yi >= yl:
pos = np.array([[xx, yi, zz], [xx+.25*_mass, yi, zz]])
line = scene.visuals.Line(pos=pos, color=(0,0,0,1), parent=view.scene)
view.add(line)
yi -= schritt1
yi = schritt0
while yi >= yl:
pos = np.array([[xx, yi, zz], [xx+.25*_mass, yi, zz]])
line = scene.visuals.Line(pos=pos, color=(0,0,0,1), parent=view.scene)
view.add(line)
yi -= schritt0
text1 = scene.visuals.Text(txt(0), pos=[xx+0.6*_mass, 0, zz-0.8*_mass],
color=(0,0,0,1), font_size=12, parent=view.scene)
text2 = scene.visuals.Text(txt(yl), pos=[xx+0.6*_mass, yl, zz-0.8*_mass],
color=(0,0,0,1), font_size=12, parent=view.scene)
text3 = scene.visuals.Text(txt(yr), pos=[xx+0.6*_mass, yr, zz-0.8*_mass],
color=(0,0,0,1), font_size=12, parent=view.scene)
view.add(text1)
view.add(text2)
view.add(text3)
def _z_skala_mayavi(pos):
# pos = 0: entlang der z-Achse
# pos <> 0: entlang der linken Box-Kante
xl, xr, yl, yr, zl, zr = UMG._sicht_box
| |
import pandas as pd
import numpy as np
import matplotlib
matplotlib.use('agg')
import matplotlib.pyplot as plt
from matplotlib import cm, colors
from astropy.modeling import models, fitting
# Reading in all data files at once
import glob
path_normal ='/projects/p30137/ageller/testing/EBLSST/add_m5/output_files'
allFiles_normal = glob.glob(path_normal + "/*.csv")
path_fast = '/projects/p30137/ageller/testing/EBLSST/add_m5/fast/old/output_files'
allFiles_fast = glob.glob(path_fast + "/*.csv")
path_obsDist = '/projects/p30137/ageller/testing/EBLSST/add_m5/fast/old/obsDist/output_files'
allFiles_obsDist = glob.glob(path_obsDist + "/*.csv")
N_totalnormal_array = []
N_totalobservablenormal_array = []
N_totalrecoverablenormal_array = []
N_totalnormal_array_03 = []
N_totalobservablenormal_array_03 = []
N_totalrecoverablenormal_array_03 = []
N_totalnormal_array_1 = []
N_totalobservablenormal_array_1 = []
N_totalrecoverablenormal_array_1 = []
N_totalnormal_array_10 = []
N_totalobservablenormal_array_10 = []
N_totalrecoverablenormal_array_10 = []
N_totalnormal_array_30 = []
N_totalobservablenormal_array_30 = []
N_totalrecoverablenormal_array_30 = []
N_totalnormal_array_100 = []
N_totalobservablenormal_array_100 = []
N_totalrecoverablenormal_array_100 = []
N_totalnormal_array_1000 = []
N_totalobservablenormal_array_1000 = []
N_totalrecoverablenormal_array_1000 = []
N_totalnormal22_array = []
N_totalobservablenormal22_array = []
N_totalrecoverablenormal22_array = []
N_totalnormal22_array_03 = []
N_totalobservablenormal22_array_03 = []
N_totalrecoverablenormal22_array_03 = []
N_totalnormal22_array_1 = []
N_totalobservablenormal22_array_1 = []
N_totalrecoverablenormal22_array_1 = []
N_totalnormal22_array_10 = []
N_totalobservablenormal22_array_10 = []
N_totalrecoverablenormal22_array_10 = []
N_totalnormal22_array_30 = []
N_totalobservablenormal22_array_30 = []
N_totalrecoverablenormal22_array_30 = []
N_totalnormal22_array_100 = []
N_totalobservablenormal22_array_100 = []
N_totalrecoverablenormal22_array_100 = []
N_totalnormal22_array_1000 = []
N_totalobservablenormal22_array_1000 = []
N_totalrecoverablenormal22_array_1000 = []
N_totalnormal195_array = []
N_totalobservablenormal195_array = []
N_totalrecoverablenormal195_array = []
N_totalnormal195_array_03 = []
N_totalobservablenormal195_array_03 = []
N_totalrecoverablenormal195_array_03 = []
N_totalnormal195_array_1 = []
N_totalobservablenormal195_array_1 = []
N_totalrecoverablenormal195_array_1 = []
N_totalnormal195_array_10 = []
N_totalobservablenormal195_array_10 = []
N_totalrecoverablenormal195_array_10 = []
N_totalnormal195_array_30 = []
N_totalobservablenormal195_array_30 = []
N_totalrecoverablenormal195_array_30 = []
N_totalnormal195_array_100 = []
N_totalobservablenormal195_array_100 = []
N_totalrecoverablenormal195_array_100 = []
N_totalnormal195_array_1000 = []
N_totalobservablenormal195_array_1000 = []
N_totalrecoverablenormal195_array_1000 = []
N_totalfast_array = []
N_totalobservablefast_array = []
N_totalrecoverablefast_array = []
N_totalfast_array_03 = []
N_totalobservablefast_array_03 = []
N_totalrecoverablefast_array_03 = []
N_totalfast_array_1 = []
N_totalobservablefast_array_1 = []
N_totalrecoverablefast_array_1 = []
N_totalfast_array_10 = []
N_totalobservablefast_array_10 = []
N_totalrecoverablefast_array_10 = []
N_totalfast_array_30 = []
N_totalobservablefast_array_30 = []
N_totalrecoverablefast_array_30 = []
N_totalfast_array_100 = []
N_totalobservablefast_array_100 = []
N_totalrecoverablefast_array_100 = []
N_totalfast_array_1000 = []
N_totalobservablefast_array_1000 = []
N_totalrecoverablefast_array_1000 = []
N_totalfast22_array = []
N_totalobservablefast22_array = []
N_totalrecoverablefast22_array = []
N_totalfast22_array_03 = []
N_totalobservablefast22_array_03 = []
N_totalrecoverablefast22_array_03 = []
N_totalfast22_array_1 = []
N_totalobservablefast22_array_1 = []
N_totalrecoverablefast22_array_1 = []
N_totalfast22_array_10 = []
N_totalobservablefast22_array_10 = []
N_totalrecoverablefast22_array_10 = []
N_totalfast22_array_30 = []
N_totalobservablefast22_array_30 = []
N_totalrecoverablefast22_array_30 = []
N_totalfast22_array_100 = []
N_totalobservablefast22_array_100 = []
N_totalrecoverablefast22_array_100 = []
N_totalfast22_array_1000 = []
N_totalobservablefast22_array_1000 = []
N_totalrecoverablefast22_array_1000 = []
N_totalfast195_array = []
N_totalobservablefast195_array = []
N_totalrecoverablefast195_array = []
N_totalfast195_array_03 = []
N_totalobservablefast195_array_03 = []
N_totalrecoverablefast195_array_03 = []
N_totalfast195_array_1 = []
N_totalobservablefast195_array_1 = []
N_totalrecoverablefast195_array_1 = []
N_totalfast195_array_10 = []
N_totalobservablefast195_array_10 = []
N_totalrecoverablefast195_array_10 = []
N_totalfast195_array_30 = []
N_totalobservablefast195_array_30 = []
N_totalrecoverablefast195_array_30 = []
N_totalfast195_array_100 = []
N_totalobservablefast195_array_100 = []
N_totalrecoverablefast195_array_100 = []
N_totalfast195_array_1000 = []
N_totalobservablefast195_array_1000 = []
N_totalrecoverablefast195_array_1000 = []
N_totalobsDist_array = []
N_totalobservableobsDist_array = []
N_totalrecoverableobsDist_array = []
N_totalobsDist_array_03 = []
N_totalobservableobsDist_array_03 = []
N_totalrecoverableobsDist_array_03 = []
N_totalobsDist_array_1 = []
N_totalobservableobsDist_array_1 = []
N_totalrecoverableobsDist_array_1 = []
N_totalobsDist_array_10 = []
N_totalobservableobsDist_array_10 = []
N_totalrecoverableobsDist_array_10 = []
N_totalobsDist_array_30 = []
N_totalobservableobsDist_array_30 = []
N_totalrecoverableobsDist_array_30 = []
N_totalobsDist_array_100 = []
N_totalobservableobsDist_array_100 = []
N_totalrecoverableobsDist_array_100 = []
N_totalobsDist_array_1000 = []
N_totalobservableobsDist_array_1000 = []
N_totalrecoverableobsDist_array_1000 = []
N_totalobsDist22_array = []
N_totalobservableobsDist22_array = []
N_totalrecoverableobsDist22_array = []
N_totalobsDist22_array_03 = []
N_totalobservableobsDist22_array_03 = []
N_totalrecoverableobsDist22_array_03 = []
N_totalobsDist22_array_1 = []
N_totalobservableobsDist22_array_1 = []
N_totalrecoverableobsDist22_array_1 = []
N_totalobsDist22_array_10 = []
N_totalobservableobsDist22_array_10 = []
N_totalrecoverableobsDist22_array_10 = []
N_totalobsDist22_array_30 = []
N_totalobservableobsDist22_array_30 = []
N_totalrecoverableobsDist22_array_30 = []
N_totalobsDist22_array_100 = []
N_totalobservableobsDist22_array_100 = []
N_totalrecoverableobsDist22_array_100 = []
N_totalobsDist22_array_1000 = []
N_totalobservableobsDist22_array_1000 = []
N_totalrecoverableobsDist22_array_1000 = []
N_totalobsDist195_array = []
N_totalobservableobsDist195_array = []
N_totalrecoverableobsDist195_array = []
N_totalobsDist195_array_03 = []
N_totalobservableobsDist195_array_03 = []
N_totalrecoverableobsDist195_array_03 = []
N_totalobsDist195_array_1 = []
N_totalobservableobsDist195_array_1 = []
N_totalrecoverableobsDist195_array_1 = []
N_totalobsDist195_array_10 = []
N_totalobservableobsDist195_array_10 = []
N_totalrecoverableobsDist195_array_10 = []
N_totalobsDist195_array_30 = []
N_totalobservableobsDist195_array_30 = []
N_totalrecoverableobsDist195_array_30 = []
N_totalobsDist195_array_100 = []
N_totalobservableobsDist195_array_100 = []
N_totalrecoverableobsDist195_array_100 = []
N_totalobsDist195_array_1000 = []
N_totalobservableobsDist195_array_1000 = []
N_totalrecoverableobsDist195_array_1000 = []
def fitRagfb():
x = [0.05, 0.1, 1, 8, 15] #estimates of midpoints in bins, and using this: https:/sites.uni.edu/morgans/astro/course/Notes/section2/spectralmasses.html
y = [0.20, 0.35, 0.50, 0.70, 0.75]
init = models.PowerLaw1D(amplitude=0.5, x_0=1, alpha=-1.)
fitter = fitting.LevMarLSQFitter()
fit = fitter(init, x, y)
return fit
fbFit= fitRagfb()
mbins = np.arange(0,10, 0.1, dtype='float')
cutP = 0.10 #condition on recoverability/tolerance
for filenormal_ in sorted(allFiles_normal):
filename = filenormal_[60:]
fileid = filename.strip('output_file.csv')
print ("I'm starting " + fileid)
datnormal = pd.read_csv(filenormal_, sep = ',', header=2)
PeriodIn = datnormal['p'] # input period -- 'p' in data file
##########################################################
datnormal1 = pd.read_csv(filenormal_, sep = ',', header=0, nrows=1)
N_tri = datnormal1["NstarsTRILEGAL"][0]
#print("N_tri = ", N_tri)
Nall = len(PeriodIn)
m1hAll0, m1b = np.histogram(datnormal["m1"], bins=mbins)
dm1 = np.diff(m1b)
m1val = m1b[:-1] + dm1/2.
fb = np.sum(m1hAll0/Nall*fbFit(m1val))
N_mult = N_tri*fb
##########################################################
if len(PeriodIn) == 0.:
continue
if N_tri == 0:
continue
else:
PeriodOut = datnormal['LSM_PERIOD'] #LSM_PERIOD in data file
appMagMean = datnormal['appMagMean'] #apparent magnitude, will use to make cuts for 24 (default), 22, and then Kepler's range (?? -- brighter than LSST can manage-- to 19) OR 19.5 (SNR = 10)
observable = datnormal.loc[PeriodOut != -999].index
observable_03 = datnormal.loc[(PeriodIn <= 0.3) & (PeriodOut != -999)].index
observable_1 = datnormal.loc[(PeriodIn <= 1) & (PeriodOut != -999)].index
observable_10 = datnormal.loc[(PeriodIn <= 10) & (PeriodOut != -999)].index
observable_30 = datnormal.loc[(PeriodIn <= 30) & (PeriodOut != -999)].index
observable_100 = datnormal.loc[(PeriodIn <= 100) & (PeriodOut != -999)].index
observable_1000 = datnormal.loc[(PeriodIn <= 1000) & (PeriodOut != -999)].index
observable_22 = datnormal.loc[(PeriodOut != -999) & (appMagMean <= 22.)].index
observable_03_22 = datnormal.loc[(PeriodIn <= 0.3) & (PeriodOut != -999) & (appMagMean <= 22.)].index
observable_1_22 = datnormal.loc[(PeriodIn <= 1) & (PeriodOut != -999) & (appMagMean <= 22.)].index
observable_10_22 = datnormal.loc[(PeriodIn <= 10) & (PeriodOut != -999) & (appMagMean <= 22.)].index
observable_30_22 = datnormal.loc[(PeriodIn <= 30) & (PeriodOut != -999) & (appMagMean <= 22.)].index
observable_100_22 = datnormal.loc[(PeriodIn <= 100) & (PeriodOut != -999) & (appMagMean <= 22.)].index
observable_1000_22 = datnormal.loc[(PeriodIn <= 1000) & (PeriodOut != -999) & (appMagMean <= 22.)].index
observable_195 = datnormal.loc[(PeriodOut != -999) & (appMagMean <= 19.5)].index
observable_03_195 = datnormal.loc[(PeriodIn <= 0.3) & (PeriodOut != -999) & (appMagMean <= 19.5)].index
observable_1_195 = datnormal.loc[(PeriodIn <= 1) & (PeriodOut != -999) & (appMagMean <= 19.5)].index
observable_10_195 = datnormal.loc[(PeriodIn <= 10) & (PeriodOut != -999) & (appMagMean <= 19.5)].index
observable_30_195 = datnormal.loc[(PeriodIn <= 30) & (PeriodOut != -999) & (appMagMean <= 19.5)].index
observable_100_195 = datnormal.loc[(PeriodIn <= 100) & (PeriodOut != -999) & (appMagMean <= 19.5)].index
observable_1000_195 = datnormal.loc[(PeriodIn <= 1000) & (PeriodOut != -999) & (appMagMean <= 19.5)].index
fullP = abs(PeriodOut - PeriodIn)/PeriodIn
halfP = abs(PeriodOut - 0.5*PeriodIn)/(0.5*PeriodIn)
twiceP = abs(PeriodOut - 2*PeriodIn)/(2*PeriodIn)
recoverable = datnormal.loc[(PeriodOut != -999) & ((fullP < cutP) | (halfP < cutP) | (twiceP < cutP))].index
recoverable_03 = datnormal.loc[(PeriodIn <= 0.3) & (PeriodOut != -999) & ((fullP < cutP) | (halfP < cutP) | (twiceP < cutP))].index
recoverable_1 = datnormal.loc[(PeriodIn <= 1) & (PeriodOut != -999) & ((fullP < cutP) | (halfP < cutP) | (twiceP < cutP))].index
recoverable_10 = datnormal.loc[(PeriodIn <= 10) & (PeriodOut != -999) & ((fullP < cutP) | (halfP < cutP) | (twiceP < cutP))].index
recoverable_30 = datnormal.loc[(PeriodIn <= 30) & (PeriodOut != -999) & ((fullP < cutP) | (halfP < cutP) | (twiceP < cutP))].index
recoverable_100 = datnormal.loc[(PeriodIn <= 100) & (PeriodOut != -999) & ((fullP < cutP) | (halfP < cutP) | (twiceP < cutP))].index
recoverable_1000 = datnormal.loc[(PeriodIn <= 1000) & (PeriodOut != -999) & ((fullP < cutP) | (halfP < cutP) | (twiceP < cutP))].index
recoverable_22 = datnormal.loc[(PeriodOut != -999) & ((fullP < cutP) | (halfP < cutP) | (twiceP < cutP)) & (appMagMean <= 22.)].index
recoverable_03_22 = datnormal.loc[(PeriodIn <= 0.3) & (PeriodOut != -999) & ((fullP < cutP) | (halfP < cutP) | (twiceP < cutP)) & (appMagMean <= 22.)].index
recoverable_1_22 = datnormal.loc[(PeriodIn <= 1) & (PeriodOut != -999) & ((fullP < cutP) | (halfP < cutP) | (twiceP < cutP)) & (appMagMean <= 22.)].index
recoverable_10_22 = datnormal.loc[(PeriodIn <= 10) & (PeriodOut != -999) & ((fullP < cutP) | (halfP < cutP) | (twiceP < cutP)) & (appMagMean <= 22.)].index
recoverable_30_22 = datnormal.loc[(PeriodIn <= 30) & (PeriodOut != -999) & ((fullP < cutP) | (halfP < cutP) | (twiceP < cutP)) & (appMagMean <= 22.)].index
recoverable_100_22 = datnormal.loc[(PeriodIn <= 100) & (PeriodOut != -999) & ((fullP < cutP) | (halfP < cutP) | (twiceP < cutP)) & (appMagMean <= 22.)].index
recoverable_1000_22 = datnormal.loc[(PeriodIn <= 1000) & (PeriodOut != -999) & ((fullP < cutP) | (halfP < cutP) | (twiceP < cutP)) & (appMagMean <= 22.)].index
recoverable_195 = datnormal.loc[(PeriodOut != -999) & ((fullP < cutP) | (halfP < cutP) | (twiceP < cutP)) & (appMagMean <= 19.5)].index
recoverable_03_195 = datnormal.loc[(PeriodIn <= 0.3) & (PeriodOut != -999) & ((fullP < cutP) | (halfP < cutP) | (twiceP < cutP)) & (appMagMean <= 19.5)].index
recoverable_1_195 = datnormal.loc[(PeriodIn <= 1) & (PeriodOut != -999) & ((fullP < cutP) | (halfP < cutP) | (twiceP < cutP)) & (appMagMean <= 19.5)].index
recoverable_10_195 = datnormal.loc[(PeriodIn <= 10) & (PeriodOut != -999) & ((fullP < cutP) | (halfP < cutP) | (twiceP < cutP)) & (appMagMean <= 19.5)].index
recoverable_30_195 = datnormal.loc[(PeriodIn <= 30) & (PeriodOut != -999) & ((fullP < cutP) | (halfP < cutP) | (twiceP < cutP)) & (appMagMean <= 19.5)].index
recoverable_100_195 = datnormal.loc[(PeriodIn <= 100) & (PeriodOut != -999) & ((fullP < cutP) | (halfP < cutP) | (twiceP < cutP)) & (appMagMean <= 19.5)].index
recoverable_1000_195 = datnormal.loc[(PeriodIn <= 1000) & (PeriodOut != -999) & ((fullP < cutP) | (halfP < cutP) | (twiceP < cutP)) & (appMagMean <= 19.5)].index
P03 = datnormal.loc[PeriodIn <= 0.3].index
P1 = datnormal.loc[PeriodIn <= 1].index
P10 = datnormal.loc[PeriodIn <= 10].index
P30 = datnormal.loc[PeriodIn <= 30].index
P100 = datnormal.loc[PeriodIn <= 100].index
P1000 = datnormal.loc[PeriodIn <= 1000].index
P_22 = datnormal.loc[appMagMean <= 22.].index
P03_22 | |
if value.attrib['type']=="Free Capacity" :
free_capacity=round(int(value.text)/2/1024/1024/1024,2)
#print('pool_free:',free_capacity,'TB')
if value.attrib['type']=="Allocated Snap Space" :
snaps_capacity=round(int(value.text)/2/1024/1024/1024,2)
#print('pool_snaps:',snaps_capacity,'TB')
free_cap_prcn=int(round(free_capacity/max_capacity*100,0))
used_cap_prcn=int(round(used_capacity/max_capacity*100,0))
snaps_cap_prcn=int(round(snaps_capacity/max_capacity*100,0))
if used_capacity/max_capacity>0.85: warning=True
if value.attrib['type']=="FAST Cache state":
if value.text.lower()=='enabled': fcache_on=True
else: fcache_on=False
#print('FCache Enabled:',fcache_on)
cur.execute('''INSERT INTO POOLS
(name, max_capacity, used_capacity, used_cap_prcn, snaps_capacity,snaps_cap_prcn,free_capacity,free_cap_prcn, fcache_on, warning)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ? )''',
(name, max_capacity, used_capacity, used_cap_prcn, snaps_capacity,snaps_cap_prcn,free_capacity,free_cap_prcn, fcache_on, warning ) )
return
def scan_rgrp(conn, obj):
cur = conn.cursor()
for details in obj:
name=obj.attrib['name']
#print('Name:',name)
for value in obj.iter('value'):
if value.attrib['type']=='Group ID':
id=value.text
#print('RG ID:',id)
if value.attrib['type']=="Total Capacity" :
max_capacity=round(int(value.text)/2/1024/1024/1024,2)
#print('RG Total Capacity:',max_capacity,'TB')
if value.attrib['type']=='Free Space':
free_capacity=round(int(value.text)/2/1024/1024/1024,2)
#print('RG Free Capacity:',free_capacity,'TB')
free_cap_prcn=int(round(free_capacity/max_capacity*100,0))
if value.attrib['type']=='RAID Type':
RAID=value.text
cur.execute('''INSERT INTO RAID_GROUPS
(id, name, max_capacity, free_capacity, free_cap_prcn, RAID)
VALUES (?, ?, ?, ?, ?, ? )''',
(id, name, max_capacity, free_capacity, free_cap_prcn, RAID) )
return
def update_object_value(conn,tname,obj,objname,field,value):
# print('Updating',field,'for',objname,'with',value,'in table',tname)
# value='"'+value+'"'
# print(value)
# c.execute("SELECT * FROM {tn} WHERE {idf}=?".\
# format(tn=table_name, cn=column_2, idf=id_column), (123456,))
cur=conn.cursor()
cur.execute('UPDATE '+tname+' SET '+field+' = ? WHERE '+obj+' = ? ', [value,objname] )
return
def set_fast_cache_drives(conn):
cur=conn.cursor()
print('Searching for FAST Cache drives.')
# input()
cur.execute('UPDATE DRIVES SET pool_name = "FAST_Cache" WHERE pool_name IS NULL AND (drive_type="SAS Flash" OR drive_type="SATA Flash")')
conn.commit()
# cur.execute('UPDATE DRIVES SET pool_name = "FAST_Cache" WHERE pool_name IS NULL AND drive_type="SATA Flash"')
return
def nar_get_config_data(SN):
fname='config.xml'
conn = sqlite3.connect('narvision.db')
cur = conn.cursor()
init_db(conn)
tree = xml.etree.ElementTree.parse(fname)
root = tree.getroot()
for child in root:
print(child.tag, child.attrib)
for obj in root.iter('object'):
if obj.attrib['type']=='Pool':
scan_pool(conn,obj)
if obj.attrib['type']=='RAID Group':
scan_rgrp(conn,obj)
if ('LUN' in obj.attrib['type']) and ('Public' in obj.attrib['type']):
scan_lun(conn,obj)
if ('Snapshot Mount Point' in obj.attrib['type']):
scan_snap(conn,obj)
if obj.attrib['type']=='Disk':
scan_disk(conn,obj)
conn.commit()
#input('config_L5.xml')
fname='config_L5.xml'
tree = xml.etree.ElementTree.parse(fname)
root = tree.getroot()
for child_l1 in root:
#print('L1', child_l1.attrib) #Universe
for child_l2 in child_l1:
#print('L2', child_l2.attrib) #Storage Subsystems
for child_l3 in child_l2:
#print('L3', child_l3.attrib) #SP, RAID Groups, Pools, Consistency Groups
if child_l3.attrib['type']=='RAID Group' or child_l3.attrib['type']=='Pool':
pool_name=child_l3.attrib['name']
#print(pool_name)
for child_l4 in child_l3:
if child_l4.attrib['type']=='Disk': #Disks, LUNs
#print('L4', child_l4.attrib)
disk_name=child_l4.attrib['name']
update_object_value(conn,'DRIVES','name',disk_name,'pool_name',pool_name)
if child_l4.attrib['type']=='Public RaidGroup LUN':
lun_name=child_l4.attrib['name'].split('[')[0]
update_object_value(conn,'RG_LUNS','lun_name',lun_name,'rg_name',pool_name)
if child_l4.attrib['type']=='Pool Public LUN' or child_l4.attrib['type']=='Thin LUN':
lun_name=child_l4.attrib['name'].split('[')[0]
update_object_value(conn,'POOL_LUNS','lun_name',lun_name,'pool_name',pool_name)
if child_l4.attrib['type']=='Snapshot Mount Point':
lun_name=child_l4.attrib['name'].split('[')[0]
update_object_value(conn,'SNAPSHOTS','lun_name',lun_name,'pool_name',pool_name)
conn.commit()
return
def nar_display_system_summary(SN):
conn = sqlite3.connect('narvision.db')
cur = conn.cursor()
# get_config(SN)
for file in os.listdir("."):
if file.startswith('CK') and file.endswith('.nar') :
SN=file.split('_')[0]
break
directory=SN+'_csv/'
fnames=['dump_norm_disk_iops.csv', 'dump_norm_disk_response.csv', 'dump_norm_disk_queues.csv', 'dump_norm_disk_mbps.csv']
for fname in fnames:
f=open(directory+fname)
data=f.read()
data=data.splitlines()
for line in data[1:]:
words=line.split(',')
name=words[0].split('[')[0]
# print(name)
counter=words[0].split('[')[1][:-1]
# print(counter)
p95=float(words[2])
avg=float(words[3])
if 'iops' in fname:
update_object_value(conn,'DRIVES','name',name,'iops_avg',avg)
update_object_value(conn,'DRIVES','name',name,'iops_p95',p95)
if 'response' in fname:
update_object_value(conn,'DRIVES','name',name,'lat_avg',avg)
update_object_value(conn,'DRIVES','name',name,'lat_p95',p95)
if 'queues' in fname:
update_object_value(conn,'DRIVES','name',name,'abql_avg',avg)
update_object_value(conn,'DRIVES','name',name,'abql_p95',p95)
if 'mbps' in fname:
update_object_value(conn,'DRIVES','name',name,'mbps_avg',avg)
update_object_value(conn,'DRIVES','name',name,'mbps_p95',p95)
fnames=['dump_norm_luns_iops_tot.csv', 'dump_norm_luns_response.csv', 'dump_norm_luns_queues.csv']
for fname in fnames:
f=open(directory+fname)
data=f.read()
data=data.splitlines()
for line in data[1:]:
words=line.split(',')
name=words[0].split('[')[0]
counter=words[0].split('[')[1][:-1]
p95=float(words[2])
avg=float(words[3])
#print(name,counter,avg,p95)
#input()
if 'iops' in fname:
update_object_value(conn,'RG_LUNS','lun_name',name,'iops_avg',avg)
update_object_value(conn,'RG_LUNS','lun_name',name,'iops_p95',p95)
update_object_value(conn,'POOL_LUNS','lun_name',name,'iops_avg',avg)
update_object_value(conn,'POOL_LUNS','lun_name',name,'iops_p95',p95)
update_object_value(conn,'SNAPSHOTS','lun_name',name,'iops_avg',avg)
update_object_value(conn,'SNAPSHOTS','lun_name',name,'iops_p95',p95)
if 'response' in fname:
update_object_value(conn,'RG_LUNS','lun_name',name,'lat_avg',avg)
update_object_value(conn,'RG_LUNS','lun_name',name,'lat_p95',p95)
update_object_value(conn,'POOL_LUNS','lun_name',name,'lat_avg',avg)
update_object_value(conn,'POOL_LUNS','lun_name',name,'lat_p95',p95)
update_object_value(conn,'SNAPSHOTS','lun_name',name,'lat_avg',avg)
update_object_value(conn,'SNAPSHOTS','lun_name',name,'lat_p95',p95)
if 'queues' in fname:
update_object_value(conn,'RG_LUNS','lun_name',name,'lat_avg',avg)
update_object_value(conn,'RG_LUNS','lun_name',name,'lat_p95',p95)
update_object_value(conn,'POOL_LUNS','lun_name',name,'abql_avg',avg)
update_object_value(conn,'POOL_LUNS','lun_name',name,'abql_p95',p95)
update_object_value(conn,'SNAPSHOTS','lun_name',name,'abql_avg',avg)
update_object_value(conn,'SNAPSHOTS','lun_name',name,'abql_p95',p95)
conn.commit()
set_fast_cache_drives(conn)
cur.execute('SELECT drive_cap,drive_type, bus, dae, slot, iops_p95,lat_p95,abql_p95,pool_name FROM DRIVES ORDER BY iops_p95 DESC')
data=cur.fetchmany(20)
print(" ------------------------------------------------------------------------------------------------------------------------------------------",file=report)
print('| Top DRIVES by IOPS |',file=report)
print(" ------------------------------------------------------------------------------------------------------------------------------------------",file=report)
print("|drive_cap type bus enc slot iops_p95 lat_p95 abql_p95 pool_name |",file=report)
print(" ------------------------------------------------------------------------------------------------------------------------------------------",file=report)
for row in data:
for d in row:
print ("{:<11}".format(d),end=' ',file=report)
print('\n_________________________________________________________________________________________________________________________________________',file=report)
cur.execute('SELECT drive_cap,drive_type, bus, dae, slot, iops_p95,lat_p95,abql_p95,pool_name FROM DRIVES ORDER BY lat_p95 DESC')
data=cur.fetchmany(20)
print('\n',file=report)
print(" ------------------------------------------------------------------------------------------------------------------------------------------",file=report)
print('| Top DRIVES by Latency |',file=report)
print(" ------------------------------------------------------------------------------------------------------------------------------------------",file=report)
print("|drive_cap type bus enc slot iops_p95 lat_p95 abql_p95 pool_name |",file=report)
print(" ------------------------------------------------------------------------------------------------------------------------------------------",file=report)
for row in data:
for d in row:
if d!=None: print ("{:<11}".format(d),end=' ',file=report)
print('\n_________________________________________________________________________________________________________________________________________',file=report)
cur.execute('SELECT drive_cap,drive_type, bus, dae, slot, iops_p95,lat_p95,abql_p95,pool_name FROM DRIVES ORDER BY abql_p95 DESC')
data=cur.fetchmany(20)
print('\n',file=report)
print(" ------------------------------------------------------------------------------------------------------------------------------------------",file=report)
print("| Top DRIVES by ABQL |",file=report)
print(" ------------------------------------------------------------------------------------------------------------------------------------------",file=report)
print("|drive_cap type bus enc slot iops_p95 lat_p95 abql_p95 pool_name |",file=report)
print(" ------------------------------------------------------------------------------------------------------------------------------------------",file=report)
for row in data:
for d in row:
print ("{:<11}".format(d),end=' ',file=report)
print('\n_________________________________________________________________________________________________________________________________________',file=report)
cur.execute('''SELECT lun_id,cur_owner,alloc_owner,max_capacity,used_capacity,snapshots,warning,
iops_p95,lat_p95,abql_p95,pool_name FROM POOL_LUNS ORDER BY iops_p95 DESC''')
data=cur.fetchmany(20)
print('\n',file=report)
print(" ------------------------------------------------------------------------------------------------------------------------------------------",file=report)
print('| Top POOL_LUNS by IOPS |',file=report)
print(" ------------------------------------------------------------------------------------------------------------------------------------------",file=report)
print("|lun_id cur_owner alloc_owner max_cap used_cap snapshots warning iops_p95 lat_p95 abql_p95 pool_name |",file=report)
print(" ------------------------------------------------------------------------------------------------------------------------------------------",file=report)
for row in data:
for d in row:
print ("{:<12}".format(d),end=' ',file=report)
print('\n_________________________________________________________________________________________________________________________________________',file=report)
cur.execute('''SELECT lun_id,cur_owner,alloc_owner,max_capacity,used_capacity,snapshots,warning,
iops_p95,lat_p95,abql_p95,pool_name FROM POOL_LUNS ORDER BY lat_p95 DESC''')
data=cur.fetchmany(20)
print(" ------------------------------------------------------------------------------------------------------------------------------------------",file=report)
print('| Top POOL_LUNS by Latency |',file=report)
print(" ------------------------------------------------------------------------------------------------------------------------------------------",file=report)
print("|lun_id cur_owner alloc_owner max_cap used_cap snapshots warning iops_p95 lat_p95 abql_p95 pool_name |",file=report)
print(" ------------------------------------------------------------------------------------------------------------------------------------------",file=report)
for row in data:
for d in row:
print ("{:<12}".format(d),end=' ',file=report)
print('\n_________________________________________________________________________________________________________________________________________',file=report)
cur.execute('''SELECT lun_id,cur_owner,alloc_owner,max_capacity,used_capacity,snapshots,warning,
iops_p95,lat_p95,abql_p95,pool_name FROM POOL_LUNS ORDER BY abql_p95 DESC''')
data=cur.fetchmany(20)
print('',file=report)
print(" ------------------------------------------------------------------------------------------------------------------------------------------",file=report)
print('| Top POOL_LUNS by ABQL |',file=report)
print(" ------------------------------------------------------------------------------------------------------------------------------------------",file=report)
print("|lun_id cur_owner alloc_owner max_cap used_cap snapshots warning iops_p95 lat_p95 abql_p95 pool_name |",file=report)
print(" ------------------------------------------------------------------------------------------------------------------------------------------",file=report)
for row in data:
for d in row:
print ("{:<12}".format(d),end=' ',file=report)
print('\n_________________________________________________________________________________________________________________________________________',file=report)
cur.execute('''SELECT lun_id,cur_owner,def_owner,user_capacity,snaps_used_capacity,snapshots,warning,
iops_p95,lat_p95,abql_p95,pool_name FROM SNAPSHOTS ORDER BY iops_p95 DESC''')
data=cur.fetchmany(20)
print('',file=report)
print(" ------------------------------------------------------------------------------------------------------------------------------------------",file=report)
print('| Top SNAPSHOTS by IOPS |',file=report)
print(" ------------------------------------------------------------------------------------------------------------------------------------------",file=report)
print("|lun_id cur_owner def_owner max_cap used_cap snapshots warning iops_p95 lat_p95 abql_p95 pool_name|",file=report)
print(" ------------------------------------------------------------------------------------------------------------------------------------------",file=report)
for row in data:
for d in row:
print ("{:<12}".format(d),end=' ',file=report)
print('\n_________________________________________________________________________________________________________________________________________',file=report)
cur.execute('''SELECT lun_id,cur_owner,def_owner,user_capacity,snaps_used_capacity,snapshots,warning,
iops_p95,lat_p95,abql_p95,pool_name FROM SNAPSHOTS ORDER BY lat_p95 DESC''')
data=cur.fetchmany(20)
print('',file=report)
print(" ------------------------------------------------------------------------------------------------------------------------------------------",file=report)
print('| Top SNAPSHOTS by Latency |',file=report)
print(" ------------------------------------------------------------------------------------------------------------------------------------------",file=report)
print("|lun_id cur_owner def_owner max_cap used_cap snapshots warning iops_p95 lat_p95 abql_p95 pool_name|",file=report)
print(" ------------------------------------------------------------------------------------------------------------------------------------------",file=report)
for row in data:
for d in row:
print ("{:<12}".format(d),end=' ',file=report)
print('\n_________________________________________________________________________________________________________________________________________',file=report)
cur.execute('''SELECT lun_id,cur_owner,def_owner,user_capacity,snaps_used_capacity,snapshots,warning,
iops_p95,lat_p95,abql_p95,pool_name FROM SNAPSHOTS ORDER BY abql_p95 DESC''')
data=cur.fetchmany(20)
print('',file=report)
print(" ------------------------------------------------------------------------------------------------------------------------------------------",file=report)
print('| Top SNAPSHOTS by ABQL |',file=report)
print(" ------------------------------------------------------------------------------------------------------------------------------------------",file=report)
print("|lun_id cur_owner def_owner max_cap used_cap snapshots warning iops_p95 lat_p95 abql_p95 pool_name|",file=report)
print(" ------------------------------------------------------------------------------------------------------------------------------------------",file=report)
for row in data:
for d in row:
print ("{:<12}".format(d),end=' ',file=report)
print('\n_________________________________________________________________________________________________________________________________________',file=report)
print('\n',file=report)
print('-------------------------------------------------------------------------------',file=report)
print('| System IOPS Summary (AVG)',file=report)
print('-------------------------------------------------------------------------------',file=report)
sys_iops=0
cur.execute('SELECT SUM(iops_avg) FROM POOL_LUNS')
d=cur.fetchone()
#print(d)
if d[0]!=None: sys_iops=int(d[0])
cur.execute('SELECT SUM(iops_avg) FROM RG_LUNS')
d=cur.fetchone()
if d[0]!=None: sys_iops+=int(d[0])
cur.execute('SELECT SUM(iops_avg) FROM SNAPSHOTS')
d=cur.fetchone()
if d[0]!=None: sys_iops+=int(d[0])
print('| frontend all | ',sys_iops,'IOPS',file=report)
print('-------------------------------------------------------------------------------',file=report)
#if d[0]!=None : print('all backend',int(d[0]),'IOPS')
cur.execute('SELECT SUM(iops_avg) FROM DRIVES')
d=cur.fetchone()
if d[0]!=None :
print('| backend all | ',int(d[0]),'IOPS',file=report)
print('-------------------------------------------------------------------------------',file=report)
cur.execute('SELECT SUM(iops_avg) FROM DRIVES WHERE drive_type="SAS Flash" OR drive_type="SATA Flash"')
d=cur.fetchone()
if d[0]!=None :
print('| backend ssd | ',int(d[0]),end=' ',file=report)
cur.execute('SELECT SUM(iops_avg) FROM DRIVES WHERE pool_name="FAST_Cache"')
d=cur.fetchone()
if d[0]!=None :
print('(incl. fcache:',int(d[0]),') IOPS',file=report)
else: print('IOPS',file=report)
print('-------------------------------------------------------------------------------',file=report)
cur.execute('SELECT SUM(iops_avg) FROM DRIVES WHERE drive_type="SAS"')
d=cur.fetchone()
if d[0]!=None :
print('| backend sas | ',int(d[0]),'IOPS',file=report)
print('-------------------------------------------------------------------------------',file=report)
cur.execute('SELECT SUM(iops_avg) FROM DRIVES WHERE drive_type="NL SAS"')
d=cur.fetchone()
if d[0]!=None :
print('| backend nlsas | ',int(d[0]),'IOPS',file=report)
print('-------------------------------------------------------------------------------',file=report)
print("",file=report)
cur.execute('SELECT DISTINCT bus FROM DRIVES')
d=cur.fetchall()
print('\n-------------------------------------------------------------------------------',file=report)
print('| System Backend Summary',file=report)
print('-------------------------------------------------------------------------------',file=report)
print('| Total Busses:',len(d),file=report)
print('| Following bus numbers are present:',end='',file=report)
for bus in d: print(bus,end=',',file=report)
print('',file=report)
# input()
for b in d:
print('-------------------------------------------------------------------------------',file=report)
cur.execute('SELECT COUNT(bus) FROM DRIVES WHERE (drive_type="SAS Flash" OR drive_type="SATA Flash") AND bus=?',(b[0],))
d=cur.fetchall()
bus_ssd=str(d[0][0])
cur.execute('SELECT COUNT(bus) FROM DRIVES WHERE drive_type="SAS" AND bus=?',(b[0],))
d=cur.fetchall()
bus_sas=str(d[0][0])
cur.execute('SELECT COUNT(bus) FROM DRIVES WHERE drive_type="NL SAS" AND bus=?',(b[0],))
d=cur.fetchall()
bus_nlsas=str(d[0][0])
print('| bus ',b[0],' | ssd:',bus_ssd.rjust(3),' sas:',bus_sas.rjust(3),' nl sas:',bus_nlsas.rjust(3),file=report)
print('-------------------------------------------------------------------------------',file=report)
cur.execute('SELECT SUM(iops_avg) FROM DRIVES WHERE bus=?',(b[0],))
d=cur.fetchall()
if d[0][0]!=None:
bus_iops_avg=str(round(float(d[0][0]),0))
else:
print("No drives found on bus:",b[0],"!!!",file=report)
cur.execute('SELECT SUM(iops_p95) FROM DRIVES WHERE bus=?',(b[0],))
d=cur.fetchall()
if d[0][0]!=None:
bus_iops_p95=str(round(float(d[0][0]),0))
else:
print("No drives found on bus:",b,"!!!",file=report)
print('| bus ',b[0],' | iops avg ',bus_iops_avg.rjust(7),' | iops p95 ',bus_iops_p95.rjust(7),file=report)
print('-------------------------------------------------------------------------------',file=report)
cur.execute('SELECT SUM(mbps_avg) FROM DRIVES WHERE bus=?',(b[0],))
d=cur.fetchall()
if d[0][0]!=None:
bus_mbps_avg=str(round(float(d[0][0]),0))
else:
print("No drives found on bus:",b[0],"!!!",file=report)
cur.execute('SELECT SUM(mbps_p95) FROM DRIVES WHERE bus=?',(b[0],))
d=cur.fetchall()
if d[0][0]!=None:
bus_mbps_p95=str(round(float(d[0][0]),0))
else:
print("No drives found on bus:",b,"!!!",file=report)
print('| bus ',b[0],' | mbps avg ',bus_mbps_avg.rjust(7),' | mbps p95 ',bus_mbps_p95.rjust(7),file=report)
print('-------------------------------------------------------------------------------',file=report)
cur.execute('SELECT SUM(abql_avg) FROM DRIVES WHERE bus=?',(b[0],))
d=cur.fetchall()
if d[0][0]!=None:
bus_abql_avg=str(round(float(d[0][0]),0))
else:
print("No drives found on bus:",b[0],"!!!",file=report)
cur.execute('SELECT SUM(abql_p95) FROM DRIVES WHERE bus=?',(b[0],))
d=cur.fetchall()
if d[0][0]!=None:
bus_abql_p95=str(round(float(d[0][0]),0))
else:
print("No drives found on bus:",b[0],"!!!",file=report)
continue
print('| bus ',b[0],' | abql avg ',bus_abql_avg.rjust(7),' | abql p95 ',bus_abql_p95.rjust(7),file=report)
print('-------------------------------------------------------------------------------',file=report)
print("",file=report)
print('\n',file=report)
print('-------------------------------------------------------------------------------',file=report)
print('| Pools/RAID Groups and Backend IO Summary',file=report)
print('-------------------------------------------------------------------------------',file=report)
cur.execute('SELECT DISTINCT pool_name FROM DRIVES')
pools=cur.fetchall()
for pool in pools:
print('\n',file=report)
print('-------------------------------------------------------------------------------',file=report)
cur.execute('SELECT COUNT(drive_type) FROM DRIVES WHERE (drive_type="SAS Flash" OR drive_type="SATA Flash") AND pool_name=?', pool)
ssd_qty=cur.fetchall()[0][0]
# print(pool[0])
# print(ssd_qty)
# input()
cur.execute('SELECT COUNT(drive_type) FROM DRIVES WHERE drive_type="SAS" AND pool_name=?', pool)
sas_qty=cur.fetchall()[0][0]
cur.execute('SELECT COUNT(drive_type) FROM DRIVES WHERE drive_type="NL SAS" AND pool_name=?', pool)
nlsas_qty=cur.fetchall()[0][0]
if pool[0]=='FAST_Cache':
print('| FAST Cache SSDs',ssd_qty,file=report)
print('-------------------------------------------------------------------------------',file=report)
| |
<filename>neuralprophet/tools/plot_model_parameters.py<gh_stars>1-10
import datetime
import numpy as np
import pandas as pd
import logging
import torch
from neuralprophet.dataset import time_dataset
from neuralprophet.utils.utils import set_y_as_percent
log = logging.getLogger("NP.plotting")
try:
from matplotlib import pyplot as plt
from matplotlib.dates import (
MonthLocator,
num2date,
AutoDateLocator,
AutoDateFormatter,
)
from matplotlib.ticker import FuncFormatter
from pandas.plotting import deregister_matplotlib_converters
deregister_matplotlib_converters()
except ImportError:
log.error("Importing matplotlib failed. Plotting will not work.")
def plot_parameters(m, forecast_in_focus=None, weekly_start=0, yearly_start=0, figsize=None):
"""Plot the parameters that the model is composed of, visually.
Args:
m (NeuralProphet): fitted model.
forecast_in_focus (int): n-th step ahead forecast AR-coefficients to plot
weekly_start (int): specifying the start day of the weekly seasonality plot.
0 (default) starts the week on Sunday.
1 shifts by 1 day to Monday, and so on.
yearly_start (int): specifying the start day of the yearly seasonality plot.
0 (default) starts the year on Jan 1.
1 shifts by 1 day to Jan 2, and so on.
figsize (tuple): width, height in inches.
None (default): automatic (10, 3 * npanel)
Returns:
A matplotlib figure.
"""
# Identify components to be plotted
# as dict: {plot_name, }
components = [{"plot_name": "Trend"}]
if m.config_trend.n_changepoints > 0:
components.append({"plot_name": "Trend Rate Change"})
# Plot seasonalities, if present
if m.season_config is not None:
for name in m.season_config.periods:
components.append({"plot_name": "seasonality", "comp_name": name})
if m.n_lags > 0:
components.append(
{
"plot_name": "lagged weights",
"comp_name": "AR",
"weights": m.model.ar_weights.detach().numpy(),
"focus": forecast_in_focus,
}
)
# all scalar regressors will be plotted together
# collected as tuples (name, weights)
# Add Regressors
additive_future_regressors = []
multiplicative_future_regressors = []
if m.regressors_config is not None:
for regressor, configs in m.regressors_config.items():
mode = configs["mode"]
regressor_param = m.model.get_reg_weights(regressor)
if mode == "additive":
additive_future_regressors.append((regressor, regressor_param.detach().numpy()))
else:
multiplicative_future_regressors.append((regressor, regressor_param.detach().numpy()))
additive_events = []
multiplicative_events = []
# Add Events
# add the country holidays
if m.country_holidays_config is not None:
for country_holiday in m.country_holidays_config["holiday_names"]:
event_params = m.model.get_event_weights(country_holiday)
weight_list = [(key, param.detach().numpy()) for key, param in event_params.items()]
mode = m.country_holidays_config["mode"]
if mode == "additive":
additive_events = additive_events + weight_list
else:
multiplicative_events = multiplicative_events + weight_list
# add the user specified events
if m.events_config is not None:
for event, configs in m.events_config.items():
event_params = m.model.get_event_weights(event)
weight_list = [(key, param.detach().numpy()) for key, param in event_params.items()]
mode = configs["mode"]
if mode == "additive":
additive_events = additive_events + weight_list
else:
multiplicative_events = multiplicative_events + weight_list
# Add Covariates
lagged_scalar_regressors = []
if m.config_covar is not None:
for name in m.config_covar.keys():
if m.config_covar[name].as_scalar:
lagged_scalar_regressors.append((name, m.model.get_covar_weights(name).detach().numpy()))
else:
components.append(
{
"plot_name": "lagged weights",
"comp_name": 'Lagged Regressor "{}"'.format(name),
"weights": m.model.get_covar_weights(name).detach().numpy(),
"focus": forecast_in_focus,
}
)
if len(additive_future_regressors) > 0:
components.append({"plot_name": "Additive future regressor"})
if len(multiplicative_future_regressors) > 0:
components.append({"plot_name": "Multiplicative future regressor"})
if len(lagged_scalar_regressors) > 0:
components.append({"plot_name": "Lagged scalar regressor"})
if len(additive_events) > 0:
additive_events = [(key, weight * m.data_params["y"].scale) for (key, weight) in additive_events]
components.append({"plot_name": "Additive event"})
if len(multiplicative_events) > 0:
components.append({"plot_name": "Multiplicative event"})
npanel = len(components)
figsize = figsize if figsize else (10, 3 * npanel)
fig, axes = plt.subplots(npanel, 1, facecolor="w", figsize=figsize)
if npanel == 1:
axes = [axes]
multiplicative_axes = []
for ax, comp in zip(axes, components):
plot_name = comp["plot_name"].lower()
if plot_name.startswith("trend"):
if "change" in plot_name:
plot_trend_change(m=m, ax=ax, plot_name=comp["plot_name"])
else:
plot_trend(m=m, ax=ax, plot_name=comp["plot_name"])
elif plot_name.startswith("seasonality"):
name = comp["comp_name"]
if m.season_config.mode == "multiplicative":
multiplicative_axes.append(ax)
if name.lower() == "weekly" or m.season_config.periods[name].period == 7:
plot_weekly(m=m, ax=ax, weekly_start=weekly_start, comp_name=name)
elif name.lower() == "yearly" or m.season_config.periods[name].period == 365.25:
plot_yearly(m=m, ax=ax, yearly_start=yearly_start, comp_name=name)
elif name.lower() == "daily" or m.season_config.periods[name].period == 1:
plot_daily(m=m, ax=ax, comp_name=name)
else:
plot_custom_season(m=m, ax=ax, comp_name=name)
elif plot_name == "lagged weights":
plot_lagged_weights(weights=comp["weights"], comp_name=comp["comp_name"], focus=comp["focus"], ax=ax)
else:
if plot_name == "additive future regressor":
weights = additive_future_regressors
elif plot_name == "multiplicative future regressor":
multiplicative_axes.append(ax)
weights = multiplicative_future_regressors
elif plot_name == "lagged scalar regressor":
weights = lagged_scalar_regressors
elif plot_name == "additive event":
weights = additive_events
elif plot_name == "multiplicative event":
multiplicative_axes.append(ax)
weights = multiplicative_events
plot_scalar_weights(weights=weights, plot_name=comp["plot_name"], focus=forecast_in_focus, ax=ax)
fig.tight_layout()
# Reset multiplicative axes labels after tight_layout adjustment
for ax in multiplicative_axes:
ax = set_y_as_percent(ax)
return fig
def plot_trend_change(m, ax=None, plot_name="Trend Change", figsize=(10, 6)):
"""Make a barplot of the magnitudes of trend-changes.
Args:
m (NeuralProphet): fitted model.
ax (matplotlib axis): matplotlib Axes to plot on.
One will be created if this is not provided.
plot_name (str): Name of the plot Title.
figsize (tuple): width, height in inches. Ignored if ax is not None.
default: (10, 6)
Returns:
a list of matplotlib artists
"""
artists = []
if not ax:
fig = plt.figure(facecolor="w", figsize=figsize)
ax = fig.add_subplot(111)
start = m.data_params["ds"].shift
scale = m.data_params["ds"].scale
time_span_seconds = scale.total_seconds()
cp_t = []
for cp in m.model.config_trend.changepoints:
cp_t.append(start + datetime.timedelta(seconds=cp * time_span_seconds))
weights = m.model.get_trend_deltas.detach().numpy()
# add end-point to force scale to match trend plot
cp_t.append(start + scale)
weights = np.append(weights, [0.0])
width = time_span_seconds / 175000 / m.config_trend.n_changepoints
artists += ax.bar(cp_t, weights, width=width, color="#0072B2")
locator = AutoDateLocator(interval_multiples=False)
formatter = AutoDateFormatter(locator)
ax.xaxis.set_major_locator(locator)
ax.xaxis.set_major_formatter(formatter)
ax.grid(True, which="major", c="gray", ls="-", lw=1, alpha=0.2)
ax.set_xlabel("Trend Segment")
ax.set_ylabel(plot_name)
return artists
def plot_trend(m, ax=None, plot_name="Trend", figsize=(10, 6)):
"""Make a barplot of the magnitudes of trend-changes.
Args:
m (NeuralProphet): fitted model.
ax (matplotlib axis): matplotlib Axes to plot on.
One will be created if this is not provided.
plot_name (str): Name of the plot Title.
figsize (tuple): width, height in inches. Ignored if ax is not None.
default: (10, 6)
Returns:
a list of matplotlib artists
"""
artists = []
if not ax:
fig = plt.figure(facecolor="w", figsize=figsize)
ax = fig.add_subplot(111)
t_start = m.data_params["ds"].shift
t_end = t_start + m.data_params["ds"].scale
if m.config_trend.n_changepoints == 0:
fcst_t = pd.Series([t_start, t_end]).dt.to_pydatetime()
trend_0 = m.model.bias.detach().numpy()
if m.config_trend.growth == "off":
trend_1 = trend_0
else:
trend_1 = trend_0 + m.model.trend_k0.detach().numpy()
trend_0 = trend_0 * m.data_params["y"].scale + m.data_params["y"].shift
trend_1 = trend_1 * m.data_params["y"].scale + m.data_params["y"].shift
artists += ax.plot(fcst_t, [trend_0, trend_1], ls="-", c="#0072B2")
else:
days = pd.date_range(start=t_start, end=t_end, freq=m.data_freq)
df_y = pd.DataFrame({"ds": days})
df_trend = m.predict_trend(df_y)
artists += ax.plot(df_y["ds"].dt.to_pydatetime(), df_trend["trend"], ls="-", c="#0072B2")
# Specify formatting to workaround matplotlib issue #12925
locator = AutoDateLocator(interval_multiples=False)
formatter = AutoDateFormatter(locator)
ax.xaxis.set_major_locator(locator)
ax.xaxis.set_major_formatter(formatter)
ax.grid(True, which="major", c="gray", ls="-", lw=1, alpha=0.2)
ax.set_xlabel("ds")
ax.set_ylabel(plot_name)
return artists
def plot_scalar_weights(weights, plot_name, focus=None, ax=None, figsize=(10, 6)):
"""Make a barplot of the regressor weights.
Args:
weights (list): tuples (name, weights)
plot_name (string): name of the plot
ax (matplotlib axis): matplotlib Axes to plot on.
One will be created if this is not provided.
focus (int): if provided, show weights for this forecast
None (default) plot average
figsize (tuple): width, height in inches. Ignored if ax is not None.
default: (10, 6)
Returns:
a list of matplotlib artists
"""
artists = []
if not ax:
fig = plt.figure(facecolor="w", figsize=figsize)
ax = fig.add_subplot(111)
# if len(regressors) == 1:
# else:
names = []
values = []
for name, weights in weights:
names.append(name)
weight = np.squeeze(weights)
if len(weight.shape) > 1:
raise ValueError("Not scalar " + plot_name)
if len(weight.shape) == 1 and len(weight) > 1:
if focus is not None:
weight = weight[focus - 1]
else:
weight = np.mean(weight)
values.append(weight)
artists += ax.bar(names, values, width=0.8, color="#0072B2")
ax.grid(True, which="major", c="gray", ls="-", lw=1, alpha=0.2)
ax.set_xlabel(plot_name + " name")
xticks = ax.get_xticklabels()
if len("_".join(names)) > 100:
for tick in xticks:
tick.set_ha("right")
tick.set_rotation(20)
if "lagged" in plot_name.lower():
if focus is None:
ax.set_ylabel(plot_name + " weight (avg)")
else:
ax.set_ylabel(plot_name + " weight ({})-ahead".format(focus))
else:
ax.set_ylabel(plot_name + " weight")
return artists
def plot_lagged_weights(weights, comp_name, focus=None, ax=None, figsize=(10, 6)):
"""Make a barplot of the importance of lagged inputs.
Args:
weights (np.array): model weights as matrix or vector
comp_name (str): name of lagged inputs
focus (int): if provided, show weights for this forecast
None (default) sum over all forecasts and plot as relative percentage
ax (matplotlib axis): matplotlib Axes to plot on.
One will be created if this is not provided.
figsize (tuple): width, height in inches. Ignored if ax is not None.
default: (10, 6)
Returns:
a list of matplotlib artists
"""
artists = []
if not ax:
fig = plt.figure(facecolor="w", figsize=figsize)
ax = fig.add_subplot(111)
n_lags = weights.shape[1]
lags_range = list(range(1, 1 + n_lags))[::-1]
if focus is None:
weights = np.sum(np.abs(weights), axis=0)
weights = weights / np.sum(weights)
artists += ax.bar(lags_range, weights, width=1.00, color="#0072B2")
else:
if | |
<reponame>spidezad/python-pptx
# -*- coding: utf-8 -*-
#
# oxml.py
#
# Copyright (C) 2012, 2013 <NAME> <EMAIL>
#
# This module is part of python-pptx and is released under
# the MIT License: http://www.opensource.org/licenses/mit-license.php
"""
Classes that directly manipulate Open XML and provide direct object-oriented
access to the XML elements. Classes are implemented as a wrapper around their
bit of the lxml graph that spans the entire Open XML package part, e.g. a
slide.
"""
import re
from datetime import datetime, timedelta
from lxml import etree, objectify
from pptx.spec import nsmap
from pptx.spec import (
PH_ORIENT_HORZ, PH_SZ_FULL, PH_TYPE_BODY, PH_TYPE_CTRTITLE, PH_TYPE_OBJ,
PH_TYPE_SUBTITLE, PH_TYPE_TITLE
)
# import logging
# log = logging.getLogger('pptx.oxml')
# oxml-specific constants --------------
XSD_TRUE = '1'
# configure objectified XML parser
fallback_lookup = objectify.ObjectifyElementClassLookup()
element_class_lookup = etree.ElementNamespaceClassLookup(fallback_lookup)
oxml_parser = etree.XMLParser(remove_blank_text=True)
oxml_parser.set_element_class_lookup(element_class_lookup)
# ============================================================================
# API functions
# ============================================================================
def _Element(tag, nsmap=None):
return oxml_parser.makeelement(qn(tag), nsmap=nsmap)
def _SubElement(parent, tag, nsmap=None):
return objectify.SubElement(parent, qn(tag), nsmap=nsmap)
def new(tag, **extra):
return objectify.Element(qn(tag), **extra)
def nsdecls(*prefixes):
return ' '.join(['xmlns:%s="%s"' % (pfx, nsmap[pfx]) for pfx in prefixes])
def oxml_fromstring(text):
"""``etree.fromstring()`` replacement that uses oxml parser"""
return objectify.fromstring(text, oxml_parser)
def oxml_parse(source):
"""``etree.parse()`` replacement that uses oxml parser"""
return objectify.parse(source, oxml_parser)
def oxml_tostring(elm, encoding=None, pretty_print=False, standalone=None):
# if xsi parameter is not set to False, PowerPoint won't load without a
# repair step; deannotate removes some original xsi:type tags in core.xml
# if this parameter is left out (or set to True)
objectify.deannotate(elm, xsi=False, cleanup_namespaces=True)
return etree.tostring(elm, encoding=encoding, pretty_print=pretty_print,
standalone=standalone)
def qn(tag):
"""
Stands for "qualified name", a utility function to turn a namespace
prefixed tag name into a Clark-notation qualified tag name for lxml. For
example, ``qn('p:cSld')`` returns ``'{http://schemas.../main}cSld'``.
"""
prefix, tagroot = tag.split(':')
uri = nsmap[prefix]
return '{%s}%s' % (uri, tagroot)
def sub_elm(parent, tag, **extra):
return objectify.SubElement(parent, qn(tag), **extra)
# ============================================================================
# utility functions
# ============================================================================
def _child(element, child_tagname):
"""
Return direct child of *element* having *child_tagname* or |None|
if no such child element is present.
"""
xpath = './%s' % child_tagname
matching_children = element.xpath(xpath, namespaces=nsmap)
return matching_children[0] if len(matching_children) else None
def _child_list(element, child_tagname):
"""
Return list containing the direct children of *element* having
*child_tagname*.
"""
xpath = './%s' % child_tagname
return element.xpath(xpath, namespaces=nsmap)
def _get_or_add(start_elm, *path_tags):
"""
Retrieve the element at the end of the branch starting at parent and
traversing each of *path_tags* in order, creating any elements not found
along the way. Not a good solution when sequence of added children is
likely to be a concern.
"""
parent = start_elm
for tag in path_tags:
child = _child(parent, tag)
if child is None:
child = _SubElement(parent, tag, nsmap)
parent = child
return child
# ============================================================================
# Custom element classes
# ============================================================================
class CT_CoreProperties(objectify.ObjectifiedElement):
"""
``<cp:coreProperties>`` element, the root element of the Core Properties
part stored as ``/docProps/core.xml``. Implements many of the Dublin Core
document metadata elements. String elements resolve to an empty string
('') if the element is not present in the XML. String elements are
limited in length to 255 unicode characters.
"""
_date_tags = {
'created': 'dcterms:created',
'last_printed': 'cp:lastPrinted',
'modified': 'dcterms:modified',
}
_str_tags = {
'author': 'dc:creator',
'category': 'cp:category',
'comments': 'dc:description',
'content_status': 'cp:contentStatus',
'identifier': 'dc:identifier',
'keywords': 'cp:keywords',
'language': 'dc:language',
'last_modified_by': 'cp:lastModifiedBy',
'subject': 'dc:subject',
'title': 'dc:title',
'version': 'cp:version',
}
_coreProperties_tmpl = (
'<cp:coreProperties %s/>\n' % nsdecls('cp', 'dc', 'dcterms')
)
@staticmethod
def new_coreProperties():
"""Return a new ``<cp:coreProperties>`` element"""
xml = CT_CoreProperties._coreProperties_tmpl
coreProperties = oxml_fromstring(xml)
return coreProperties
def __getattribute__(self, name):
"""
Intercept attribute access to generalize property getters.
"""
if name in CT_CoreProperties._str_tags:
return self.__get_str_prop(name)
elif name in CT_CoreProperties._date_tags:
return self.__get_date_prop(name)
elif name == 'revision':
return self.__get_revision()
else:
return super(CT_CoreProperties, self).__getattribute__(name)
def __setattr__(self, name, value):
"""
Override ``__setattr__`` defined in ObjectifiedElement super class
to intercept messages intended for custom property setters.
"""
if name in CT_CoreProperties._str_tags:
self.__set_str_prop(name, value)
elif name in CT_CoreProperties._date_tags:
self.__set_date_prop(name, value)
elif name == 'revision':
self.__set_revision(value)
else:
super(CT_CoreProperties, self).__setattr__(name, value)
def __get_str_prop(self, name):
"""Return string value of *name* property."""
# explicit class reference avoids another pass through getattribute
tag = qn(CT_CoreProperties._str_tags[name])
if not hasattr(self, tag):
return ''
return getattr(self, tag).text
def __get_date_prop(self, name):
"""Return datetime value of *name* property."""
# explicit class reference avoids another pass through getattribute
tag = qn(CT_CoreProperties._date_tags[name])
# date properties return None when property element not present
if not hasattr(self, tag):
return None
datetime_str = getattr(self, tag).text
try:
return self._parse_W3CDTF_to_datetime(datetime_str)
except ValueError:
# invalid datetime strings are ignored
return None
def __get_revision(self):
"""Return integer value of revision property."""
tag = qn('cp:revision')
# revision returns zero when element not present
if not hasattr(self, tag):
return 0
revision_str = getattr(self, tag).text
try:
revision = int(revision_str)
except ValueError:
# non-integer revision strings also resolve to 0
revision = 0
# as do negative integers
if revision < 0:
revision = 0
return revision
def __set_str_prop(self, name, value):
"""Set string value of *name* property to *value*"""
value = str(value)
if len(value) > 255:
tmpl = ("exceeded 255 char max length of property '%s', got:"
"\n\n'%s'")
raise ValueError(tmpl % (name, value))
tag = qn(CT_CoreProperties._str_tags[name])
setattr(self, tag, value)
def __set_date_prop(self, name, value):
"""Set datetime value of *name* property to *value*"""
if not isinstance(value, datetime):
tmpl = ("'%s' property requires <type 'datetime.datetime'> objec"
"t, got %s")
raise ValueError(tmpl % (name, type(value)))
tagname = CT_CoreProperties._date_tags[name]
tag = qn(tagname)
dt_str = value.strftime('%Y-%m-%dT%H:%M:%SZ')
setattr(self, tag, dt_str)
if name in ('created', 'modified'):
# these two require an explicit 'xsi:type' attribute
# first and last line are a hack required to add the xsi
# namespace to the root element rather than each child element
# in which it is referenced
self.set(qn('xsi:foo'), 'bar')
self[tag].set(qn('xsi:type'), 'dcterms:W3CDTF')
del self.attrib[qn('xsi:foo')]
def __set_revision(self, value):
"""Set integer value of revision property to *value*"""
if not isinstance(value, int) or value < 1:
tmpl = "revision property requires positive int, got '%s'"
raise ValueError(tmpl % value)
tag = qn('cp:revision')
setattr(self, tag, str(value))
_offset_pattern = re.compile('([+-])(\d\d):(\d\d)')
@classmethod
def _offset_dt(cls, dt, offset_str):
"""
Return a |datetime| instance that is offset from datetime *dt* by
the timezone offset specified in *offset_str*, a string like
``'-07:00'``.
"""
match = cls._offset_pattern.match(offset_str)
if match is None:
raise ValueError("'%s' is not a valid offset string" % offset_str)
sign, hours_str, minutes_str = match.groups()
sign_factor = -1 if sign == '+' else 1
hours = int(hours_str) * sign_factor
minutes = int(minutes_str) * sign_factor
td = timedelta(hours=hours, minutes=minutes)
return dt + td
@classmethod
def _parse_W3CDTF_to_datetime(cls, w3cdtf_str):
# valid W3CDTF date cases:
# yyyy e.g. '2003'
# yyyy-mm e.g. '2003-12'
# yyyy-mm-dd e.g. '2003-12-31'
# UTC timezone e.g. '2003-12-31T10:14:55Z'
# numeric timezone e.g. '2003-12-31T10:14:55-08:00'
templates = (
'%Y-%m-%dT%H:%M:%S',
'%Y-%m-%d',
'%Y-%m',
'%Y',
)
# strptime isn't smart enough to parse literal timezone offsets like
# '-07:30', so we have to do it ourselves
parseable_part = w3cdtf_str[:19]
offset_str = w3cdtf_str[19:]
dt = None
for tmpl in templates:
try:
dt = datetime.strptime(parseable_part, tmpl)
except ValueError:
continue
if dt is None:
tmpl = "could not parse W3CDTF datetime string '%s'"
raise ValueError(tmpl % w3cdtf_str)
if len(offset_str) == 6:
return cls._offset_dt(dt, offset_str)
return dt
class CT_GraphicalObjectFrame(objectify.ObjectifiedElement):
"""
``<p:graphicFrame>`` element, which is a container for a table, a chart,
or another graphical object.
"""
DATATYPE_TABLE = 'http://schemas.openxmlformats.org/drawingml/2006/table'
_graphicFrame_tmpl = (
'<p:graphicFrame %s>\n'
' <p:nvGraphicFramePr>\n'
' <p:cNvPr id="%s" name="%s"/>\n'
' <p:cNvGraphicFramePr>\n'
' <a:graphicFrameLocks noGrp="1"/>\n'
' </p:cNvGraphicFramePr>\n'
' <p:nvPr/>\n'
' </p:nvGraphicFramePr>\n'
' <p:xfrm>\n'
' <a:off x="%s" y="%s"/>\n'
' <a:ext cx="%s" cy="%s"/>\n'
' </p:xfrm>\n'
' <a:graphic>\n'
' <a:graphicData/>\n'
' </a:graphic>\n'
'</p:graphicFrame>' %
(nsdecls('a', 'p'), '%d', '%s', '%d', '%d', '%d', '%d')
)
@property
def has_table(self):
"""True if graphicFrame contains a table, False otherwise"""
datatype = self[qn('a:graphic')].graphicData.get('uri')
if datatype == CT_GraphicalObjectFrame.DATATYPE_TABLE:
return True
return False
@staticmethod
def new_graphicFrame(id_, name, left, top, width, height):
"""
Return a new ``<p:graphicFrame>`` element tree suitable for containing
a table or chart. Note that a graphicFrame element is not a valid
shape until it contains a graphical object such as a table.
"""
xml = CT_GraphicalObjectFrame._graphicFrame_tmpl % (
id_, name, left, top, width, height)
graphicFrame = oxml_fromstring(xml)
objectify.deannotate(graphicFrame, cleanup_namespaces=True)
return graphicFrame
@staticmethod
def new_table(id_, name, rows, cols, left, top, width, height):
"""
Return a ``<p:graphicFrame>`` element tree populated with a table
element.
"""
graphicFrame = CT_GraphicalObjectFrame.new_graphicFrame(
id_, name, left, top, width, height)
# set type of contained graphic to table
graphicData = graphicFrame[qn('a:graphic')].graphicData
graphicData.set('uri', | |
= 100 # membrane area [m^2]
pressure_atm = 101325 # atmospheric pressure [Pa]
# feed
# feed_flow_mass = 1*pyunits.kg/pyunits.s
if Cin is None:
Cin = 70
feed_temperature = 273.15 + 20
# initialize feed
m.fs.feed.pressure[0].fix(pressure_atm)
m.fs.feed.temperature[0].fix(feed_temperature)
m.fs.feed.properties[0].conc_mass_phase_comp["Liq", "NaCl"] = Cin
m.fs.feed.properties.calculate_state(
var_args={
("conc_mass_phase_comp", ("Liq", "NaCl")): value(
m.fs.feed.properties[0].conc_mass_phase_comp["Liq", "NaCl"]
), # feed mass concentration
("flow_vol_phase", "Liq"): 1e-3,
}, # volumetric feed flowrate [-]
hold_state=True, # fixes the calculated component mass flow rates
)
# initialize pumps
for pump in m.fs.PrimaryPumps.values():
pump.control_volume.properties_out[0].pressure = 75e5
pump.efficiency_pump.fix(pump_efi)
pump.control_volume.properties_out[0].pressure.fix()
iscale.set_scaling_factor(pump.control_volume.work, 1e-3)
# initialize eq pumps
for pump in m.fs.BoosterPumps.values():
pump.efficiency_pump.fix(pump_efi)
iscale.set_scaling_factor(pump.control_volume.work, 1e-3)
# initialize stages
for idx, stage in m.fs.ROUnits.items():
if idx == m.fs.FirstStage:
B_scale = 1.0
else:
B_scale = 100.0
stage.A_comp.fix(mem_A)
stage.B_comp.fix(mem_B * B_scale)
stage.area.fix(area / float(idx))
stage.width.fix(width)
stage.mixed_permeate[0].pressure.fix(pressure_atm)
if (
stage.config.mass_transfer_coefficient == MassTransferCoefficient.calculated
) or stage.config.pressure_change_type == PressureChangeType.calculated:
stage.channel_height.fix(height)
stage.spacer_porosity.fix(spacer_porosity)
# energy recovery devices
for erd in m.fs.EnergyRecoveryDevices.values():
erd.efficiency_pump.fix(erd_efi)
iscale.set_scaling_factor(erd.control_volume.work, 1e-3)
# if FirstStage *is* LastStage, we'll just overwrite the pressure
m.fs.EnergyRecoveryDevices[m.fs.FirstStage].control_volume.properties_out[
0
].pressure.fix(70e5)
m.fs.EnergyRecoveryDevices[m.fs.LastStage].control_volume.properties_out[
0
].pressure.fix(pressure_atm)
# ---scaling---
m.fs.properties.set_default_scaling("flow_mass_phase_comp", 1, index=("Liq", "H2O"))
m.fs.properties.set_default_scaling(
"flow_mass_phase_comp", 1e2, index=("Liq", "NaCl")
)
iscale.calculate_scaling_factors(m)
# ---checking model---
assert_units_consistent(m)
assert_no_degrees_of_freedom(m)
print(
"Feed Concentration = %.1f ppt"
% (value(m.fs.feed.flow_mass_phase_comp[0, "Liq", "NaCl"]) * 1000)
)
def _lsrro_mixer_guess_initializer(
mixer, solvent_multiplier, solute_multiplier, optarg
):
for vname in mixer.upstream.vars:
if vname == "flow_mass_phase_comp":
for time, phase, comp in mixer.upstream.vars[vname]:
if comp in mixer.config.property_package.solute_set:
mixer.downstream.vars[vname][time, phase, comp].value = (
solute_multiplier
* mixer.upstream.vars[vname][time, phase, comp].value
)
elif comp in mixer.config.property_package.solvent_set:
mixer.downstream.vars[vname][time, phase, comp].value = (
solvent_multiplier
* mixer.upstream.vars[vname][time, phase, comp].value
)
else:
raise RuntimeError(f"Unknown component {comp}")
else: # copy the state
for idx in mixer.upstream.vars[vname]:
mixer.downstream.vars[vname][idx].value = mixer.upstream.vars[vname][
idx
].value
mixer.initialize(optarg=optarg)
def do_forward_initialization_pass(m, optarg, guess_mixers):
print("--------------------START FORWARD INITIALIZATION PASS--------------------")
# start with the feed
m.fs.feed.initialize(optarg=optarg)
propagate_state(m.fs.feed_to_pump)
last_stage = m.fs.LastStage
first_stage = m.fs.FirstStage
for stage in m.fs.Stages:
m.fs.PrimaryPumps[stage].initialize(optarg=optarg)
if stage == last_stage:
propagate_state(m.fs.pumpN_to_stageN)
else:
propagate_state(m.fs.pump_to_mixer[stage])
if guess_mixers:
_lsrro_mixer_guess_initializer(
m.fs.Mixers[stage],
solvent_multiplier=0.5,
solute_multiplier=0.2,
optarg=optarg,
)
else:
m.fs.Mixers[stage].initialize(optarg=optarg)
propagate_state(m.fs.mixer_to_stage[stage])
m.fs.ROUnits[stage].initialize(optarg=optarg)
if stage == first_stage:
propagate_state(m.fs.primary_RO_to_product)
m.fs.product.initialize(optarg=optarg)
if value(m.fs.NumberOfStages) > 1:
propagate_state(m.fs.primary_RO_to_erd)
m.fs.EnergyRecoveryDevices[first_stage].initialize(optarg=optarg)
propagate_state(m.fs.primary_ERD_to_pump)
else:
propagate_state(m.fs.stage_permeate_to_booster_pump[stage])
m.fs.BoosterPumps[stage].initialize(optarg=optarg)
propagate_state(m.fs.booster_pump_to_mixer[stage])
if stage in m.fs.IntermediateStages:
propagate_state(m.fs.stage_retentate_to_pump[stage])
# for the end stage
propagate_state(m.fs.stage_to_erd)
m.fs.EnergyRecoveryDevices[last_stage].initialize(optarg=optarg)
propagate_state(m.fs.erd_to_disposal)
m.fs.disposal.initialize(optarg=optarg)
def do_backward_initialization_pass(m, optarg):
print("--------------------START BACKWARD INITIALIZATION PASS--------------------")
first_stage = m.fs.FirstStage
for stage in reversed(m.fs.NonFinalStages):
m.fs.Mixers[stage].initialize(optarg=optarg)
propagate_state(m.fs.mixer_to_stage[stage])
m.fs.ROUnits[stage].initialize(optarg=optarg)
if stage == first_stage:
if value(m.fs.NumberOfStages) > 1:
propagate_state(m.fs.primary_ERD_to_pump)
m.fs.EnergyRecoveryDevices[first_stage].initialize(optarg=optarg)
propagate_state(m.fs.primary_RO_to_erd)
propagate_state(m.fs.primary_RO_to_product)
m.fs.product.initialize(optarg=optarg)
else:
propagate_state(m.fs.stage_retentate_to_pump[stage])
propagate_state(m.fs.stage_permeate_to_booster_pump[stage])
m.fs.BoosterPumps[stage].initialize(optarg=optarg)
propagate_state(m.fs.booster_pump_to_mixer[stage])
def initialize(m, verbose=False, solver=None):
# ---initializing---
# set up solvers
if solver is None:
solver = get_solver()
optarg = solver.options
do_forward_initialization_pass(m, optarg=optarg, guess_mixers=True)
for _ in range(m.fs.NumberOfStages.value // 2):
do_backward_initialization_pass(m, optarg=optarg)
do_forward_initialization_pass(m, optarg=optarg, guess_mixers=False)
# # set up SD tool
seq = SequentialDecomposition()
seq.options.tear_method = "Direct"
seq.options.iterLim = m.fs.NumberOfStages
seq.options.tear_set = list(m.fs.booster_pump_to_mixer.values())
seq.options.log_info = True
# run SD tool
def func_initialize(unit):
outlvl = idaeslogger.INFO if verbose else idaeslogger.CRITICAL
unit.initialize(optarg=solver.options, outlvl=outlvl)
seq.run(m, func_initialize)
m.fs.costing.initialize()
def solve(model, solver=None, tee=False, raise_on_failure=False):
# ---solving---
if solver is None:
solver = get_solver()
results = solver.solve(model, tee=tee)
if check_optimal_termination(results):
return results
msg = (
"The current configuration is infeasible. Please adjust the decision variables."
)
if raise_on_failure:
raise RuntimeError(msg)
else:
print(msg)
return results
def optimize_set_up(
m,
water_recovery=None,
Cbrine=None,
A_case=ACase.fixed,
B_case=BCase.optimize,
AB_tradeoff=ABTradeoff.none,
A_value=None,
permeate_quality_limit=None,
AB_gamma_factor=None,
B_max=None,
):
"""
Get the LSRRO flowsheet ready to optimize
Attributes
----------
B_case: 'single_optimum' or anything else to optimize B value at every LSR stage
A_case: 'fixed' or 'optimize' or 'single_optimum' A at every LSR stage
AB_tradeoff: 'inequality_constraint' B >= function of A
'equality_constraint' B = function of A
'none' no constraint relating B value to A value
A_value: if A_case='fixed', then provide a value to fix A with
Returns
-------
model (Pyomo ConcreteModel) : The LSRRO flowsheet.
"""
for idx, pump in m.fs.PrimaryPumps.items():
pump.control_volume.properties_out[0].pressure.unfix()
pump.deltaP.setlb(0)
if idx > m.fs.Stages.first():
pump.max_lsrro_pressure_con = Constraint(
expr=(
m.fs.lsrro_min_pressure,
pump.control_volume.properties_out[0].pressure,
m.fs.lsrro_max_pressure,
)
)
iscale.constraint_scaling_transform(
pump.max_lsrro_pressure_con,
iscale.get_scaling_factor(
pump.control_volume.properties_out[0].pressure
),
)
else:
pump.max_ro_pressure_con = Constraint(
expr=(
m.fs.ro_min_pressure,
pump.control_volume.properties_out[0].pressure,
m.fs.ro_max_pressure,
)
)
iscale.constraint_scaling_transform(
pump.max_ro_pressure_con,
iscale.get_scaling_factor(
pump.control_volume.properties_out[0].pressure
),
)
if value(m.fs.NumberOfStages) > 1:
m.fs.EnergyRecoveryDevices[1].control_volume.properties_out[0].pressure.unfix()
m.fs.EnergyRecoveryDevices[1].deltaP.setub(0)
# unfix eq pumps
for idx, pump in m.fs.BoosterPumps.items():
pump.control_volume.properties_out[0].pressure.unfix()
pump.max_ro_pressure_con = Constraint(
expr=(
m.fs.ro_min_pressure,
pump.control_volume.properties_out[0].pressure,
m.fs.ro_max_pressure,
)
)
iscale.constraint_scaling_transform(
pump.max_ro_pressure_con,
iscale.get_scaling_factor(pump.control_volume.properties_out[0].pressure),
)
pump.deltaP.setlb(0)
if B_case == BCase.single_optimum:
m.fs.B_comp_system = Var(
domain=NonNegativeReals,
units=pyunits.m * pyunits.s**-1,
doc="Solute permeability coeff. constant in all LSR stages",
)
m.fs.B_comp_system.set_value(
m.fs.ROUnits[m.fs.LSRRO_Stages.first()].B_comp[0, "NaCl"]
)
m.fs.B_comp_system.setlb(3.5e-8)
if B_max is None:
m.fs.B_comp_system.setub(3.5e-8 * 1e2)
else:
m.fs.B_comp_system.setub(m.fs.B_max)
if A_case == ACase.single_optimum:
m.fs.A_comp_system = Var(
domain=NonNegativeReals,
units=pyunits.m * pyunits.s**-1 * pyunits.Pa**-1,
doc="Water permeability coeff. constant in all LSR stages",
)
m.fs.A_comp_system.set_value(m.fs.ROUnits[2].A_comp[0, "H2O"])
m.fs.A_comp_system.setlb(2.78e-12)
m.fs.A_comp_system.setub(4.2e-11)
if (
AB_tradeoff == ABTradeoff.equality_constraint
or AB_tradeoff == ABTradeoff.inequality_constraint
):
m.fs.AB_tradeoff_coeff = Param(initialize=0.01333, mutable=True)
m.fs.AB_tradeoff_coeff.set_value(
AB_gamma_factor * value(m.fs.AB_tradeoff_coeff)
)
# unfix stages
for idx, stage in m.fs.ROUnits.items():
stage.area.unfix()
stage.width.unfix()
stage.area.setlb(1)
stage.area.setub(20000)
stage.width.setlb(0.1)
stage.width.setub(1000)
if (
stage.config.mass_transfer_coefficient == MassTransferCoefficient.calculated
) or (stage.config.pressure_change_type == PressureChangeType.calculated):
stage.N_Re[0, 0].unfix()
if idx > m.fs.Stages.first():
stage.B_comp.unfix()
stage.B_comp.setlb(3.5e-8)
if B_max is not None:
stage.B_comp.setub(m.fs.B_max)
else:
stage.B_comp.setub(None)
if B_case == BCase.single_optimum:
stage.B_comp_equal = Constraint(
expr=stage.B_comp[0, "NaCl"] == m.fs.B_comp_system
)
if A_case == ACase.single_optimum:
stage.A_comp_equal = Constraint(
expr=stage.A_comp[0, "H2O"] == m.fs.A_comp_system
)
stage.A_min = Param(
initialize=2.78e-12, units=pyunits.m**2 / pyunits.kg * pyunits.s
)
stage.A_max = Param(
initialize=4.2e-11, units=pyunits.m**2 / pyunits.kg * pyunits.s
)
stage._A_comp_con = Constraint(
expr=(stage.A_min, stage.A_comp[0, "H2O"], stage.A_max)
)
iscale.constraint_scaling_transform(
stage._A_comp_con, iscale.get_scaling_factor(stage.A_comp[0, "H2O"])
)
if A_case == ACase.optimize or A_case == ACase.single_optimum:
stage.A_comp.unfix()
stage.A_comp.setlb(2.78e-12)
stage.A_comp.setub(4.2e-11)
elif A_case == ACase.fixed:
if not isinstance(A_value, (int, float)):
raise TypeError("A_value must be a numeric value")
stage.A_comp.unfix()
stage.A_comp.fix(A_value)
else:
raise TypeError(
f'A_case must be set to "fix", "single_optimum", "optimize" or None.'
f" A_case was set to {A_case}"
)
if AB_tradeoff == ABTradeoff.equality_constraint:
stage.ABtradeoff = Constraint(
expr=pyunits.convert(
stage.B_comp[0, "NaCl"],
to_units=pyunits.L * pyunits.m**-2 * pyunits.hour**-1,
)
== m.fs.AB_tradeoff_coeff
* pyunits.convert(
stage.A_comp[0, "H2O"],
to_units=pyunits.L
* pyunits.m**-2
* pyunits.bar**-1
* pyunits.hour**-1,
)
** 3
* pyunits.L**-2
* pyunits.m**4
* pyunits.hour**2
* pyunits.bar**3
)
elif AB_tradeoff == ABTradeoff.inequality_constraint:
stage.ABtradeoff = Constraint(
expr=pyunits.convert(
stage.B_comp[0, "NaCl"],
to_units=pyunits.L * pyunits.m**-2 * pyunits.hour**-1,
)
>= m.fs.AB_tradeoff_coeff
* pyunits.convert(
stage.A_comp[0, "H2O"],
to_units=pyunits.L
* pyunits.m**-2
* pyunits.bar**-1
* pyunits.hour**-1,
)
** 3
* pyunits.L**-2
* pyunits.m**4
* pyunits.hour**2
* pyunits.bar**3
)
else:
pass
min_avg_flux = 1 # minimum average water flux [kg/m2-h]
# [kg/m2-s]
min_avg_flux = min_avg_flux / 3600 * pyunits.kg / pyunits.m**2 / pyunits.s
# additional constraints
if water_recovery is not None:
# product mass flow rate fraction of feed [-]
m.fs.water_recovery.fix(water_recovery)
if Cbrine is not None:
# Final brine concentration
m.fs.ROUnits[m.fs.Stages.last()].feed_side.properties[
0, 1
].conc_mass_phase_comp["Liq", "NaCl"].fix(Cbrine)
# add upper bound for permeate concentration
if permeate_quality_limit is not None:
if isinstance(permeate_quality_limit, (int, float)):
m.fs.ROUnits[1].mixed_permeate[0].mass_frac_phase_comp["Liq", "NaCl"].setub(
permeate_quality_limit
)
else:
raise TypeError("permeate_quality_limit must be None, integer, or float")
# ---checking model---
assert_units_consistent(m)
assert_degrees_of_freedom(
m,
4 * m.fs.NumberOfStages
- (1 if (water_recovery is not None) else 0)
- (1 if value(m.fs.NumberOfStages) == 1 else 0),
)
return m
def display_design(m):
print("--decision variables--")
for stage in m.fs.Stages:
print(
"Stage %d operating pressure %.1f bar"
% (stage, m.fs.ROUnits[stage].inlet.pressure[0].value / 1e5)
)
print(
"Stage %d membrane area %.1f m2"
% (stage, m.fs.ROUnits[stage].area.value)
)
print(
"Stage %d water perm. coeff. %.1f LMH/bar"
% (stage, m.fs.ROUnits[stage].A_comp[0, "H2O"].value * (3.6e11))
)
print(
"Stage %d salt perm. coeff. %.1f LMH"
% (stage, m.fs.ROUnits[stage].B_comp[0, "NaCl"].value * (1000.0 * 3600.0))
)
def display_state(m):
print("--------state---------")
def print_state(s, b):
flow_mass = sum(
b.flow_mass_phase_comp[0, "Liq", j].value for j in ["H2O", "NaCl"]
)
mass_frac_ppm = b.flow_mass_phase_comp[0, "Liq", "NaCl"].value / flow_mass * 1e6
pressure_bar = b.pressure[0].value / 1e5
print(
s.ljust(20)
+ ": %.3f kg/s, %.0f ppm, %.1f bar"
% (flow_mass, mass_frac_ppm, pressure_bar)
)
print_state("Feed", m.fs.feed.outlet)
for stage in m.fs.Stages:
print_state(f"Primary Pump {stage} out", m.fs.PrimaryPumps[stage].outlet)
if stage == m.fs.LastStage:
pass
else:
print_state(f"Mixer {stage} recycle", m.fs.Mixers[stage].downstream)
print_state(f"Mixer {stage} out", m.fs.Mixers[stage].outlet)
print_state(f"RO {stage} permeate", m.fs.ROUnits[stage].permeate)
print_state(f"RO {stage} retentate", m.fs.ROUnits[stage].retentate)
wr = m.fs.ROUnits[stage].recovery_vol_phase[0, "Liq"].value
if stage == m.fs.FirstStage:
pass
else:
print_state(f"Booster Pump {stage} out", m.fs.BoosterPumps[stage].outlet)
print_state(f"Disposal", m.fs.disposal.inlet)
print_state(f"Product", m.fs.product.inlet)
def display_system(m):
print("----system metrics----")
feed_flow_mass = sum(
m.fs.feed.flow_mass_phase_comp[0, "Liq", j].value for j in ["H2O", "NaCl"]
)
feed_mass_frac_NaCl = (
m.fs.feed.flow_mass_phase_comp[0, "Liq", "NaCl"].value / feed_flow_mass
)
print("Feed: %.2f kg/s, %.0f ppm" % (feed_flow_mass, feed_mass_frac_NaCl * 1e6))
prod_flow_mass = sum(
m.fs.product.flow_mass_phase_comp[0, "Liq", j].value for j in ["H2O", "NaCl"]
)
prod_mass_frac_NaCl = (
m.fs.product.flow_mass_phase_comp[0, | |
# encoding: utf-8
#
# Copyright (C) 2018 ycmd contributors
#
# This file is part of ycmd.
#
# ycmd is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# ycmd is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with ycmd. If not, see <http://www.gnu.org/licenses/>.
from __future__ import absolute_import
from __future__ import unicode_literals
from __future__ import print_function
from __future__ import division
from hamcrest.core.base_matcher import BaseMatcher
from hamcrest import ( assert_that,
contains,
contains_string,
equal_to,
has_entries,
has_entry,
matches_regexp )
from pprint import pprint
import requests
import os.path
from ycmd.tests.clangd import ( IsolatedYcmd,
SharedYcmd,
PathToTestFile,
RunAfterInitialized )
from ycmd.tests.test_utils import ( BuildRequest,
ChunkMatcher,
CombineRequest,
LineColMatcher,
LocationMatcher,
ErrorMatcher,
WithRetry,
WaitUntilCompleterServerReady )
from ycmd.utils import ReadFile
# This test is isolated to trigger objcpp hooks, rather than fetching completer
# from cache.
@IsolatedYcmd()
def Subcommands_DefinedSubcommands_test( app ):
file_path = PathToTestFile( 'GoTo_Clang_ZeroBasedLineAndColumn_test.cc' )
RunAfterInitialized( app, {
'request': {
'completer_target': 'filetype_default',
'line_num': 10,
'column_num': 3,
'filetype': 'objcpp',
'filepath': file_path
},
'expect': {
'response': requests.codes.ok,
'data': contains( *sorted( [ 'ExecuteCommand',
'FixIt',
'Format',
'GetDoc',
'GetDocImprecise',
'GetType',
'GetTypeImprecise',
'GoTo',
'GoToDeclaration',
'GoToDefinition',
'GoToImprecise',
'GoToInclude',
'GoToReferences',
'RefactorRename',
'RestartServer' ] ) )
},
'route': '/defined_subcommands',
} )
@SharedYcmd
def Subcommands_GoTo_ZeroBasedLineAndColumn_test( app ):
file_path = PathToTestFile( 'GoTo_Clang_ZeroBasedLineAndColumn_test.cc' )
RunAfterInitialized( app, {
'request': {
'contents': ReadFile( file_path ),
'completer_target': 'filetype_default',
'command_arguments': [ 'GoToDefinition' ],
'line_num': 10,
'column_num': 3,
'filetype': 'cpp',
'filepath': file_path
},
'expect': {
'response': requests.codes.ok,
'data': {
'filepath': os.path.abspath( file_path ),
'line_num': 2,
'column_num': 8
}
},
'route': '/run_completer_command',
} )
@SharedYcmd
def RunGoToTest_all( app, folder, command, test ):
filepath = PathToTestFile( folder, test[ 'req' ][ 0 ] )
common_request = {
'completer_target' : 'filetype_default',
'filepath' : filepath,
'command_arguments': [ command ],
'contents' : ReadFile( filepath ),
'filetype' : 'cpp'
}
request = common_request
request.update( {
'line_num' : test[ 'req' ][ 1 ],
'column_num': test[ 'req' ][ 2 ],
} )
response = test[ 'res' ]
if isinstance( response, list ):
expect = {
'response': requests.codes.ok,
'data': contains( *[
LocationMatcher(
PathToTestFile( folder, os.path.normpath( location[ 0 ] ) ),
location[ 1 ],
location[ 2 ]
) for location in response
] )
}
elif isinstance( response, tuple ):
expect = {
'response': requests.codes.ok,
'data': LocationMatcher(
PathToTestFile( folder, os.path.normpath( response[ 0 ] ) ),
response[ 1 ],
response[ 2 ]
)
}
else:
expect = {
'response': requests.codes.internal_server_error,
'data': ErrorMatcher( RuntimeError, test[ 'res' ] )
}
RunAfterInitialized( app, {
'request': request,
'route' : '/run_completer_command',
'expect' : expect
} )
def Subcommands_GoTo_all_test():
tests = [
# Local::x -> definition/declaration of x
{ 'req': ( 'goto.cc', 23, 21 ), 'res': ( 'goto.cc', 4, 9 ) },
# Local::in_line -> definition/declaration of Local::in_line
{ 'req': ( 'goto.cc', 24, 26 ), 'res': ( 'goto.cc', 6, 10 ) },
# Local -> definition/declaration of Local
{ 'req': ( 'goto.cc', 24, 16 ), 'res': ( 'goto.cc', 2, 11 ) },
# Local::out_of_line -> definition of Local::out_of_line
{ 'req': ( 'goto.cc', 25, 27 ), 'res': ( 'goto.cc', 14, 13 ) },
# GoToDeclaration alternates between definition and declaration
{ 'req': ( 'goto.cc', 14, 13 ), 'res': ( 'goto.cc', 11, 10 ) },
{ 'req': ( 'goto.cc', 11, 10 ), 'res': ( 'goto.cc', 14, 13 ) },
# test -> definition and declaration of test
{ 'req': ( 'goto.cc', 21, 5 ), 'res': ( 'goto.cc', 19, 5 ) },
{ 'req': ( 'goto.cc', 19, 5 ), 'res': ( 'goto.cc', 21, 5 ) },
# Unicøde
{ 'req': ( 'goto.cc', 34, 9 ), 'res': ( 'goto.cc', 32, 26 ) },
# Another_Unicøde
{ 'req': ( 'goto.cc', 36, 17 ), 'res': ( 'goto.cc', 32, 54 ) },
{ 'req': ( 'goto.cc', 36, 25 ), 'res': ( 'goto.cc', 32, 54 ) },
{ 'req': ( 'goto.cc', 38, 3 ), 'res': ( 'goto.cc', 36, 28 ) },
# Expected failures
{ 'req': ( 'goto.cc', 13, 1 ), 'res': 'Cannot jump to location' },
{ 'req': ( 'goto.cc', 16, 6 ), 'res': 'Cannot jump to location' },
]
for test in tests:
for cmd in [ 'GoToDefinition', 'GoTo', 'GoToImprecise' ]:
yield RunGoToTest_all, '', cmd, test
def Subcommands_GoToDeclaration_all_test():
tests = [
# Local::x -> definition/declaration of x
{ 'req': ( 'goto.cc', 23, 21 ), 'res': ( 'goto.cc', 4, 9 ) },
# Local::in_line -> definition/declaration of Local::in_line
{ 'req': ( 'goto.cc', 24, 26 ), 'res': ( 'goto.cc', 6, 10 ) },
# Local -> definition/declaration of Local
{ 'req': ( 'goto.cc', 24, 16 ), 'res': ( 'goto.cc', 2, 11 ) },
# Local::out_of_line -> declaration of Local::out_of_line
{ 'req': ( 'goto.cc', 25, 27 ), 'res': ( 'goto.cc', 11, 10 ) },
# GoToDeclaration alternates between definition and declaration
{ 'req': ( 'goto.cc', 14, 13 ), 'res': ( 'goto.cc', 11, 10 ) },
{ 'req': ( 'goto.cc', 11, 10 ), 'res': ( 'goto.cc', 14, 13 ) },
# test -> definition and declaration of test
{ 'req': ( 'goto.cc', 21, 5 ), 'res': ( 'goto.cc', 19, 5 ) },
{ 'req': ( 'goto.cc', 19, 5 ), 'res': ( 'goto.cc', 21, 5 ) },
# Unicøde
{ 'req': ( 'goto.cc', 34, 9 ), 'res': ( 'goto.cc', 32, 26 ) },
# Another_Unicøde
{ 'req': ( 'goto.cc', 36, 17 ), 'res': ( 'goto.cc', 32, 54 ) },
{ 'req': ( 'goto.cc', 36, 25 ), 'res': ( 'goto.cc', 32, 54 ) },
{ 'req': ( 'goto.cc', 38, 3 ), 'res': ( 'goto.cc', 36, 28 ) },
# Expected failures
{ 'req': ( 'goto.cc', 13, 1 ), 'res': 'Cannot jump to location' },
{ 'req': ( 'goto.cc', 16, 6 ), 'res': 'Cannot jump to location' },
]
for test in tests:
yield RunGoToTest_all, '', 'GoToDeclaration', test
def Subcommands_GoToInclude_test():
tests = [
{ 'req': ( 'main.cpp', 1, 6 ), 'res': ( 'a.hpp', 1, 1 ) },
{ 'req': ( 'main.cpp', 2, 14 ), 'res': ( 'system/a.hpp', 1, 1 ) },
{ 'req': ( 'main.cpp', 3, 1 ), 'res': ( 'quote/b.hpp', 1, 1 ) },
# FIXME: should fail since b.hpp is included with angled brackets but its
# folder is added with -iquote.
{ 'req': ( 'main.cpp', 4, 10 ), 'res': ( 'quote/b.hpp', 1, 1 ) },
{ 'req': ( 'main.cpp', 5, 11 ), 'res': ( 'system/c.hpp', 1, 1 ) },
{ 'req': ( 'main.cpp', 6, 11 ), 'res': ( 'system/c.hpp', 1, 1 ) },
# Expected failures
{ 'req': ( 'main.cpp', 7, 1 ), 'res': 'Cannot jump to location' },
{ 'req': ( 'main.cpp', 10, 13 ), 'res': 'Cannot jump to location' },
]
for test in tests:
for cmd in [ 'GoToInclude', 'GoTo', 'GoToImprecise' ]:
yield RunGoToTest_all, 'test-include', cmd, test
def Subcommands_GoToReferences_test():
tests = [
# Function
{ 'req': ( 'goto.cc', 14, 21 ), 'res': [ ( 'goto.cc', 11, 10 ),
( 'goto.cc', 14, 13 ),
( 'goto.cc', 25, 22 ) ] },
# Namespace
{ 'req': ( 'goto.cc', 24, 17 ), 'res': [ ( 'goto.cc', 2, 11 ),
( 'goto.cc', 14, 6 ),
( 'goto.cc', 23, 14 ),
( 'goto.cc', 24, 15 ),
( 'goto.cc', 25, 15 ) ] },
# Expected failure
{ 'req': ( 'goto.cc', 27, 8 ), 'res': 'Cannot jump to location' },
]
for test in tests:
yield RunGoToTest_all, '', 'GoToReferences', test
@SharedYcmd
def RunGetSemanticTest( app,
filepath,
filetype,
test,
command,
response = requests.codes.ok ):
contents = ReadFile( filepath )
common_args = {
'completer_target' : 'filetype_default',
'command_arguments': command,
'line_num' : 10,
'column_num' : 3,
'filepath' : filepath,
'contents' : contents,
'filetype' : filetype
}
args = test[ 0 ]
if response == requests.codes.ok:
if not isinstance( test[ 1 ], BaseMatcher ):
expected = has_entry( 'message', contains_string( test[ 1 ] ) )
else:
expected = has_entry( 'message', test[ 1 ] )
| |
<reponame>hzm2016/assistive-gym-robosuite<filename>envs/envs_assistive/env_viewer.py
import gym, sys, argparse
import numpy as np
np.set_printoptions(precision=5)
import transforms3d as transforms3d
import matplotlib.pyplot as plt
import seaborn as sns
import mujoco_py
from mujoco_py.generated import const
import pybullet as p
from envs.gym_kuka_mujoco.controllers import iMOGVIC
from envs.gym_kuka_mujoco.utils.transform_utils import *
from envs.envs_assistive.feeding_envs import *
from envs.envs_assistive.drinking_envs import *
from envs.envs_assistive.scratch_itch_envs import *
from code.pytorch.LAMPO.core.rl_bench_box import *
import os, sys, multiprocessing, gym, ray, shutil, argparse, importlib, glob
import time
# from .learn import make_env
# import assistive_gym
import imageio
import commentjson
from code.pytorch.LAMPO.core.rl_bench_box import Mujoco_model, Mujoco_RL_model, AssistiveDRL
from envs.robosuite.robosuite.controllers import *
if sys.version_info < (3, 0):
print('Please use Python 3')
exit()
def render_frame(viewer, pos, euler):
viewer.add_marker(pos=pos,
label='',
type=const.GEOM_SPHERE,
size=[.01, .01, .01])
# mat = quat2mat(quat)
mat = transforms3d.euler.euler2mat(euler[0], euler[1], euler[2], 'sxyz')
cylinder_half_height = 0.02
pos_cylinder = pos + mat.dot([0.0, 0.0, cylinder_half_height])
viewer.add_marker(pos=pos_cylinder,
label='',
type=const.GEOM_CYLINDER,
size=[.005, .005, cylinder_half_height],
mat=mat)
def render_point(viewer, pos):
viewer.add_marker(pos=pos,
label='',
type=const.GEOM_SPHERE,
size=[.01, .01, .01])
def vis_impedance_random_sawyer_setpoint(initial_angles=None):
options = dict()
num_waypoints = 3
options['model_path'] = 'a_sawyer_test.xml'
options['rot_scale'] = .3
options['stiffness'] = np.array([1., 1., 1., 3., 3., 3.])
options['controlled_joints'] = ["robot0_right_j0", "robot0_right_j1",
"robot0_right_j2", "robot0_right_j3",
"robot0_right_j4", "robot0_right_j5",
"robot0_right_j6"]
options['num_waypoints'] = 3
options['null_space_damping'] = 1.0
import os
from envs.gym_kuka_mujoco import kuka_asset_dir
model_path = os.path.join(kuka_asset_dir(), 'a_sawyer_test.xml')
model = mujoco_py.load_model_from_path(model_path)
sim = mujoco_py.MjSim(model)
controller = iMOGVIC(sim, **options)
frame_skip = 50
high = np.array([.1, .1, .1, 2, 2, 2])
low = -np.array([.1, .1, .1, 2, 2, 2])
viewer = mujoco_py.MjViewer(sim)
# set parameters :::
scale = np.array([8.0, 0.0, 0.0])
scale_list = scale.repeat([6, 6, 6], axis=0).reshape(num_waypoints, 6)
stiffness_list = np.array([[20., 4., 4., 4., 4., 4.],
[0., 0., 0., 0., 0., 0.],
[0., 0., 0., 0., 0., 0.]])
control_scale = np.ones_like(stiffness_list) * 100
stiffness_list = control_scale * stiffness_list
print("stiffness_list :::", stiffness_list)
damping_list = scale_list * np.sqrt(stiffness_list)
print("damping_list :::", damping_list)
weight_list = np.array([1.0, 0.05, 0.01])
controller.set_params_direct(stiffness_list, damping_list, weight_list)
# Set a different random state and run the controller.
# qpos = np.random.uniform(-1., 1., size=7)
# qpos = np.array([0.5538, -0.8208, 0.4155, 1.8409, -0.4955, 0.6482, 1.9628])
qpos = initial_angles
controller.update_initial_joints(qpos)
qvel = np.zeros(7)
sim_state = sim.get_state()
sim_state.qpos[:] = qpos
sim_state.qvel[:] = qvel
sim.set_state(sim_state)
sim.forward()
controller.update_state()
print("current ee_pose :::", controller.ee_pose)
target_pos, target_mat = controller.get_pose_site("target_ee_site")
print("target ee_pose :::", target_pos)
while True:
viewer.render()
# set way_points :::
initial_state = np.array([-0.60349109, 0.09318907, 0.27348721,
1.9265446606661554, -0.40240192959667226, -1.541555812071902])
optimal_state = np.array([-0.80349109, 0.09318907, 0.07348721,
1.9265446606661554, -0.40240192959667226, -1.541555812071902])
state_scale = initial_state - optimal_state
pos_set_list = np.array([[0.1, 0., 1.2],
[0.1, 0., 1.2],
[0.1, 0., 1.2]])
quat_set_list = np.array([[-3.128104, 0.00437383, -2.08817412],
[-3.128104, 0.00437383, -2.08817412],
[-3.128104, 0.00437383, -2.08817412]])
way_points_list = np.concatenate((pos_set_list, quat_set_list), axis=1)
print("way_point_list :::", way_points_list)
controller.set_way_points(way_points_list)
print("reference list :::", controller.reference_list)
optimal_pose = pos_set_list[0, :]
velocity_list = []
position_list = []
stiffness_matrix = []
damping_matrix = []
energy_list = []
# for i in range(1):
# # qpos = np.random.uniform(-1., 1., size=7)
# qpos = np.array([-0.5538, -0.8208, 0.4155, 1.8409, -0.4955, 0.6482, 1.9628])
# # qpos = np.array([-0.5538, -0.8208, 0.4155, 0.8409, -0.4955, 0.6482, 1.9628])
# qvel = np.zeros(7)
# state = np.concatenate([qpos, qvel])
#
# sim_state = sim.get_state()
# sim_state.qpos[:] = qpos
# sim_state.qvel[:] = qvel
# sim.set_state(sim_state)
# sim.forward()
# for j in range(1000):
# controller.update_state()
# torque, V, pose_err, vel_err, stiffness_eqv, damping_eqv = controller.update_vic_torque()
# energy_list.append(V)
# position_list.append(pose_err)
# velocity_list.append(vel_err)
# stiffness_matrix.append(stiffness_eqv)
# damping_matrix.append(damping_eqv)
# # torque = controller.get_euler_torque(way_points_list)
# # torque = controller.update_torque(way_points_list)
# print("final state", np.linalg.norm(controller.state, ord=2))
# sim.data.ctrl[:] = torque[:7]
# sim.step()
# render_frame(viewer, pos_set_list[0, :], quat_set_list[0, :])
# viewer.render()
def make_env(env_name, coop=False, seed=1001):
if not coop:
env = gym.make('assistive_gym:'+env_name)
else:
# module = importlib.import_module('assistive_gym.envs')
env_class = globals()[env_name.split('-')[0] + 'Env']
print(env_class)
env = env_class()
env.seed(seed)
return env
def sample_action(env, coop):
if coop:
return {'robot': env.action_space_robot.sample(), 'human': env.action_space_human.sample()}
return env.action_space.sample()
def viewer(env_name):
coop = 'Human' in env_name
# env = make_env(env_name, coop=True) if coop else gym.make(env_name)
env = FeedingSawyerHumanEnv()
# env = DrinkingSawyerHumanEnv()
options = dict()
options['model_path'] = 'a_sawyer_test.xml'
options['rot_scale'] = .3
options['stiffness'] = np.array([1., 1., 1., 3., 3., 3.])
options['controlled_joints'] = ["robot0_right_j0",
"robot0_right_j1",
"robot0_right_j2",
"robot0_right_j3",
"robot0_right_j4",
"robot0_right_j5",
"robot0_right_j6"]
options['num_waypoints'] = 3
# options['frame_skip'] = 10
options['null_space_damping'] = 1.0
param_dir = '/home/zhimin/code/5_thu/rl-robotic-assembly-control/code/pytorch/LAMPO/params/'
param_file = 'IMOGICAssitive.json'
param_file = os.path.join(param_dir, param_file)
with open(param_file) as f:
set_params = commentjson.load(f)
mujoco_model = Mujoco_model(set_params["controller_options"], render=True)
while True:
done = False
env.render()
# observation, spoon_pos, spoon_orient = env.reset()
observation = env.reset()
# print("Initial observation :", observation)
print('+' * 100)
# spoon_pos_inital, spoon_orient_initial = env.get_tool_pose()
print("robot_joint_angles :", observation['robot_joint_angles'])
# print("spoon pos :", spoon_pos, "spoon orient :", spoon_orient)
# print("spoon orient :", spoon_orient)
# set way points : target pose
pos, ori = env.robot.get_ee_pose()
start_euler = transforms3d.euler.quat2euler(ori, 'sxyz')
print("EE pos :", pos, "ee euler :", start_euler)
# target_pose = env.get_context()
# print("target pos :", env.target_pos)
# # print("target ori :", env.target_orient)
# print("target euler :", transforms3d.euler.quat2euler(env.target_orient, 'sxyz'))
# # p.getQuaternionFromEuler()
target_euler = transforms3d.euler.quat2euler(env.target_orient, 'sxyz')
print("target pos :", env.target_pos, "target euler :", target_euler)
delta_pos = env.target_pos - spoon_pos
# delta_pos = np.array([0., 0.3, 0.1])
# print("des_pos", pos + delta_pos)
# print('+' * 100)
print("delta_pos :", delta_pos)
ee_pose = mujoco_model.reset(observation['robot_joint_angles'])
print("initial_pose :", np.array(ee_pose))
print('+' * 100)
mujoco_model.set_waypoints(ee_pose[:3] + delta_pos, ee_pose[3:])
# mujoco_model.set_waypoints(ee_pose[:3] + np.array([0., -0.1, 0.2]), transforms3d.euler.quat2euler(ee_pose[3:], 'sxyz'))
# set impedance params
mujoco_model.set_impedance_params(params=None)
# time.sleep(10)
joint_list = []
joint_last = observation['robot_joint_angles']
time_steps = 0
while not done:
# action = sample_action(env, coop)
joint = mujoco_model.step(np.zeros(7))
# print("robot joints :", joint[0])
human_action = np.zeros(env.action_human_len)
action = {'robot': joint[0].copy() - joint_last, 'human': human_action} # env.action_space_human.sample()
joint_list.append(joint[0].copy())
# print("sample_action :", action)
observation, reward, done, info = env.step(action)
# print('robot joints pybullet:', observation['robot_joint_angles'])
if coop:
done = done['__all__']
# print('Robot reward:', reward['robot'], 'Human reward:', reward['human'])
# time.sleep(0.1)
joint_last = observation['robot_joint_angles']
time_steps += 1
print('+' * 100)
print("target pos :", env.target_pos)
print("target euler :", transforms3d.euler.quat2euler(env.target_orient, 'sxyz'))
spoon_pos, spoon_orient = env.get_tool_pose()
print("spoon pos :", spoon_pos)
print("spoon orient :", spoon_orient)
# set way points : target pose
pos, ori = env.robot.get_ee_pose()
start_euler = transforms3d.euler.quat2euler(ori, 'sxyz')
print("EE pos :", pos, "ee euler :", start_euler)
print("time_steps :", time_steps)
print("Mujoco ee pose :", mujoco_model.get_ee_pose())
print("Error :", mujoco_model.get_ee_pose() - ee_pose)
print("Pybullet error :", spoon_pos - spoon_pos_inital)
def mujoco_eval(env_name):
coop = 'Human' in env_name
env = make_env(env_name, coop=True) if coop else gym.make(env_name)
env.render()
# env.reset()
observation = env.reset()
print("obs :", observation['robot_joint_angles'])
param_dir = '/home/zhimin/code/5_thu/rl-robotic-assembly-control/code/pytorch/LAMPO/params/'
param_file = 'VICESAssitiveItch.json'
param_file = os.path.join(param_dir, param_file)
with open(param_file) as f:
params = commentjson.load(f)
mujoco_model = Mujoco_RL_model(params["controller_options"], render=True)
# qpos = np.array([0.5538, -0.8208, 0.4155, 1.8409, -0.4955, 1.6482, 1.9628])
# qpos = np.array([1.73155, 1.91932, 1.47255, -2.29171, 0.42262, 1.13446, 1.75369])
qpos = np.array([[1.73155, 1.91932, 1.47255, 3.99147, 0.42262, 1.13446, 1.75369]])
ee_pose = mujoco_model.reset(qpos)
# # ee_pose = mujoco_model.reset(np.array([2.95, 4.07, -0.06, 1.44171, -6.2, 3.7, -0.35369]))
# # print("ee_pose :", ee_pose)
# # # print("goal_pose :", mujoco_model.controller.goal_pos, mujoco_model.controller.goal_ori)
# # # # ee_pose = mujoco_model.reset(np.zeros(7))
# # # ee_euler = np.array(transforms3d.euler.euler2mat(ee_pose[3], ee_pose[4], ee_pose[5], 'sxyz'))
#
# while True:
# mujoco_model.viewer_render()
#
# action = np.array([-0.0, 0.1, 0.0, 0.0, 0.0, 0.0])
# joint = mujoco_model.step(action)
# # # joint = mujoco_model.step(action, set_pos=ee_pose[:3], set_ori=ee_euler)
# print("ee_pose :", mujoco_model.get_ee_pose())
# while True:
# action = np.array([0.0, 0.0, 0.0, 0.0, 0.0, 0.0])
# target_euler = transforms3d.euler.mat2euler(mujoco_model.controller.goal_ori, 'sxyz')
# print("target pos :", mujoco_model.controller.goal_pos, "target euler :", target_euler)
# joint = mujoco_model.step(action)
# print("ee_pose :", mujoco_model.get_ee_pose())
# mujoco_model.viewer_render()
# done = False
# while not done:
# # action = sample_action(env, coop)
# action = np.array([0., 0.00, 0.0, 0.0, 0.0, 0.])
# print("goal_pos :", mujoco_model.controller.goal_pos)
# print("ee_pos :", mujoco_model.get_ee_pose())
# joint = mujoco_model.step(action, set_pos=ee_pose[:3], set_ori=ee_euler)
while True:
done = False
env.render()
print('+' * 100)
observation = env.reset()
if observation['robot_joint_angles'] is not None:
print("Done !!!")
# observation, spoon_pos, spoon_orient = env.reset()
# print("Initial observation :", observation)
# spoon_pos_inital, spoon_orient_initial = env.get_tool_pose()
# print("robot_joint_angles :", observation['robot_joint_angles'])
# print("spoon pos :", spoon_pos, "spoon orient :", spoon_orient)
# print("spoon orient :", spoon_orient)
human_action = np.zeros(env.action_human_len)
# action = {'robot': np.array([0.0, 0.0, 0., 0.0, 0.0, 0.0, 0.0]), 'human': human_action} # env.action_space_human.sample()
#
# # print("sample_action :", action)
# observation, reward, | |
from random import random, randint
import pygame
from pygame import *
pygame.init()
# hover = what button to hover over, main = main menu buttons (0 = none, 1 = play, 2 = help, 3 = credits, 4 = quit)
# type = game mode (1 = single-player, 2 = multi-player, 3 = back), exit = when 1 will set all others to 0)
# ------------------------------------------------
def AAfilledRoundedRect(surface, color, rect, radius=0.4):
rect = Rect(rect)
color = Color(*color)
alpha = color.a
color.a = 0
pos = rect.topleft
rect.topleft = 0, 0
rectangle = Surface(rect.size, SRCALPHA)
circle = Surface([min(rect.size) * 3] * 2, SRCALPHA)
draw.ellipse(circle, (0, 0, 0), circle.get_rect(), 0)
circle = transform.smoothscale(circle, [int(min(rect.size) * radius)] * 2)
radius = rectangle.blit(circle, (0, 0))
radius.bottomright = rect.bottomright
rectangle.blit(circle, radius)
radius.topright = rect.topright
rectangle.blit(circle, radius)
radius.bottomleft = rect.bottomleft
rectangle.blit(circle, radius)
rectangle.fill((0, 0, 0), rect.inflate(-radius.w, 0))
rectangle.fill((0, 0, 0), rect.inflate(0, -radius.h))
rectangle.fill(color, special_flags=BLEND_RGBA_MAX)
rectangle.fill((255, 255, 255, alpha), special_flags=BLEND_RGBA_MIN)
return surface.blit(rectangle, pos)
def make_dollars(dollars):
if dollars is float or int:
dollars = str(round(dollars / 1.0, 2))
if dollars[-2:-1] == ".":
dollars += "0"
return dollars
class ClientInstance:
def __init__(self):
self.GameObject = None
self.WIDTH = 1080
self.HEIGHT = 720
self.window = pygame.display.set_mode((self.WIDTH, self.HEIGHT))
self.icon = pygame.image.load("images/Icon.png").convert_alpha()
self.icon.set_colorkey((0, 255, 255))
pygame.display.set_icon(self.icon)
self.last_next_item = 0
self.last_keyboard_choose = 0
self.title_background = pygame.transform.scale2x(
pygame.image.load("images/scrolling_ground2.png")).convert_alpha()
self.game_background = pygame.image.load("images/back.png").convert_alpha()
self.night_background = pygame.image.load("images/NightHills.png").convert_alpha()
self.clouds = pygame.image.load("images/Sky.png").convert()
self.nightclouds = pygame.image.load("images/Night.png").convert()
self.title = pygame.image.load("images/title.png").convert_alpha()
self.carrot = pygame.image.load("images/Carrot.png").convert_alpha()
self.potato = pygame.image.load("images/Potato.png").convert_alpha()
self.wheat = pygame.image.load("images/Wheat.png").convert_alpha()
self.tomato = pygame.image.load("images/Tomato.png").convert_alpha()
self.corn = pygame.image.load("images/Corn.png").convert_alpha()
self.cabbage = pygame.image.load("images/Cabbage.png").convert_alpha()
self.pumpkin = pygame.image.load("images/Pumpkin.png").convert_alpha()
self.melon = pygame.image.load("images/Melon.png").convert_alpha()
self.volume = 5
pygame.mixer.music.load("music/SlushHike.mp3")
pygame.mixer.music.play(-1)
pygame.mixer.music.set_volume(self.volume / 10)
self.valid_chars = "`1234567890-= qwertyuiop[]\\asdfghjkl;'zxcvbnm,./" + '~!@#$%^&*()_+QWERTYUIOP{}|ASDFGHJKL:"ZXCVBNM<>?'
self.valid_nums = "1234567890"
self.inventory_open = False
self.loading = False
self.run = True
self.menu = True
self.game = False
self.chatbox = False
self.quantitybox = False
self.settings = False
self.help = False
self.market = False
self.exchange = False
self.over_box_limit = False
self.offerbox_txt = "Custom"
self.offer_amt = 0.0
self.offerbox = False
self.box_filled_color_title = (120 - 16, 150, 80 - 16)
self.background_color = (120 - 16, 160, 80 - 16)
self.sky_blue = (135, 206, 235)
self.bright_green_title = self.box_filled_color_title
self.green_title = (120, 180, 80)
self.white = (253, 245, 232)
self.dark_white = (253 - 25, 245 - 25, 232 - 25)
self.beige = (198, 198, 178)
self.beige2 = (188, 188, 168)
self.beige3 = (84, 84, 74)
self.brown = (153, 102, 51)
self.light_brown = (204, 153, 0)
self.black = (0, 0, 0)
self.yellow = (120 - 16, 140, 80 - 16)
self.X = 0
self.Y = 0
self.x, self.y = pygame.mouse.get_pos()
self.Y_increment = 0.2
self.RGB = 20
self.RGB_increment = 3
self.inventory_percentage = 0.3
self.cloud_x = 1500
self.market_selection = 1
print("pre-font")
pygame.font.init()
self.font2 = pygame.font.Font("fonts/orange_juice.ttf", 60)
self.font3 = pygame.font.Font("fonts/FreeSansBold.ttf", 16)
self.font5 = pygame.font.Font("fonts/orange_juice.ttf", 35)
self.newspaperfont = pygame.font.Font("fonts/MonotypeCorsiva.ttf", 60)
self.newspaperfont2 = pygame.font.Font("fonts/MonotypeCorsiva.ttf", 30)
pygame.display.set_caption("The Farmer's Market")
self.menu_gui = {"hover": 1, "main": 0, "type": 0}
self.game_options = [0, 14], [1, 25], [2, 15], [3, []]
self.custom = ["Custom", "Custom", "Custom"]
self.selection = None
self.event_help = ["Hover over an event number", "Stock Shortage!", "Stock Surplus!", "Complete Stock Shortage!", "1/4 of All Vegetables Rot!", "1/2 of Random Vegetable Rotten!", "Prices at Record Highs!", "Prices at Record Lows!", "Everyone Taxed at 25%!"]
self.event_helper = 0
self.option_titles = [["Days", 14, 17, 23], ["Day Timer", 25, 35, 45], ["Night Timer", 15, 20, 25],
"Disabled Events"]
# self.delta1, self.delta2, self.delta3, self.delta4 = 1, 1, 1, 1
self.e = [self.potato, self.carrot, self.wheat, self.tomato, self.corn, self.cabbage, self.pumpkin, self.melon]
# self.d = [self.delta1, self.delta2, self.delta3, self.delta4]
self.chat_gui = False
self.leaderboard = False
self.chatbox_msg = "Enter message"
self.quantitybox_txt = "Custom"
self.quantity = 1
self.night = 0
self.loading_X = 0
# self.daily_message = "Vegetables in stock this season: " + self.GameObject.vegetables[self.GameObject.g1][
# "name"] + ": $" + self.make_dollars(
# self.GameObject.vegetables[self.GameObject.g1]["cost"] * self.GameObject.prices[0][self.day]) + ", with " + str(
# self.GameObject.vegetables[self.GameObject.g1]["stock"]) + " in stock. " + \
# self.GameObject.vegetables[self.GameObject.g2][
# "name"] + ": $" + self.make_dollars(
# self.GameObject.vegetables[self.GameObject.g2]["cost"] * self.GameObject.prices[1][self.day]) + ", with " + str(
# self.GameObject.vegetables[self.GameObject.g2]["stock"]) + " in stock. " + self.GameObject.vegetables[self.GameObject.g3]["name"] + ": $" + self.make_dollars(
# self.GameObject.vegetables[self.GameObject.g3]["cost"] * self.GameObject.prices[2][self.day]) + ", with " + str(
# self.GameObject.vegetables[self.GameObject.g3]["stock"]) + " in stock. " + \
# self.GameObject.vegetables[self.GameObject.g4][
# "name"] + ": $" + self.make_dollars(
# self.GameObject.vegetables[self.GameObject.g4]["cost"] * self.GameObject.prices[3][self.day]) + ", with " + str(
# self.GameObject.vegetables[self.GameObject.g4]["stock"]) + " in stock. " + "High demand this season! " + "Here for " + str(
# self.GameObject.day_limit) + " days only!"
# print(self.GameObject.dayevent)
# print(self.GameObject.prices)
self.Clock = pygame.time.Clock()
self.options_done = False
self.inventory_position = -60 + self.inventory_percentage * 150
self.title_height = self.font5.get_height() / 2 - 3
self.bright_green = (183, 214, 143 - 10)
self.green = (160, 200, 104)
self.background_filled_color = (183, 221, 176 - 25)
self.news = True
self.dark_green = (92, 158, 64)
self.inv1color, self.inv2color, self.inv3color, self.inv4color = self.bright_green, self.bright_green, self.bright_green, self.bright_green
def make_text(self, text, font, color, center_x, center_y):
text_surface = font.render(text, True, color)
text_box = text_surface.get_rect()
text_box.center = (center_x, center_y)
self.window.blit(text_surface, text_box)
def check_mouse_hover(self, click=False):
self.x, self.y = pygame.mouse.get_pos()
x, y = self.x, self.y
if self.menu or self.settings:
if self.WIDTH * 0.25 <= x <= self.WIDTH * 0.75 and self.HEIGHT * 0.39 <= y <= self.HEIGHT * 0.49:
self.menu_gui["hover"] = 1
if click:
self.keyboard_choose()
elif self.WIDTH * 0.25 <= x <= self.WIDTH * 0.75 and self.HEIGHT * 0.54 <= y <= self.HEIGHT * 0.64:
self.menu_gui["hover"] = 2
if click:
self.keyboard_choose()
elif self.WIDTH * 0.25 <= x <= self.WIDTH * 0.75 and self.HEIGHT * 0.69 <= y <= self.HEIGHT * 0.79:
self.menu_gui["hover"] = 3
if click:
self.keyboard_choose()
elif self.WIDTH * 0.25 <= x <= self.WIDTH * 0.75 and self.HEIGHT * 0.84 <= y <= self.HEIGHT * 0.94 and \
self.menu_gui["main"] == 0:
self.menu_gui["hover"] = 4
if click:
self.keyboard_choose()
def mouse_choose(self):
self.check_mouse_hover(True)
def next_item(self, increment):
if pygame.time.get_ticks() > self.last_next_item + 100:
# goes to the next item in the gui
self.menu_gui["hover"] += increment
if self.menu_gui["main"] == 0 and self.menu_gui["hover"] > 4:
self.menu_gui["hover"] = 1
elif not self.menu_gui["main"] == 0 and self.menu_gui["type"] == 0 and self.menu_gui["hover"] > 3:
self.menu_gui["hover"] = 1
elif self.menu_gui["hover"] < 1 and self.menu_gui["main"] == 0:
self.menu_gui["hover"] = 4
elif self.menu_gui["hover"] < 1 and self.menu_gui["type"] == 0:
self.menu_gui["hover"] = 3
# elif menu_gui["exit"] == 0 and menu_gui["hover"] > 1:
# menu_gui["hover"] = 0
self.last_next_item = pygame.time.get_ticks()
def keyboard_choose(self):
# presses the button that's hovered
if pygame.time.get_ticks() > self.last_keyboard_choose + 100:
if self.menu_gui["main"] == 0:
if self.menu_gui["hover"] == 4:
self.run = False
elif self.menu_gui["hover"] == 2:
self.settings = True
self.menu_gui["main"] = 2
else:
self.menu_gui["main"] = self.menu_gui["hover"]
self.menu_gui["hover"] = 1
elif self.menu_gui["main"] == 1:
if self.menu_gui["hover"] == 3:
self.menu_gui["main"] = 0
self.menu_gui["hover"] = 1
elif self.menu_gui["hover"] == 1 and self.menu_gui["main"] == 1:
self.menu = False
self.loading = True
self.options_done = False
self.menu_gui["type"] = 1
elif self.menu_gui["hover"] == 2 and self.menu_gui["main"] == 1:
self.menu = False
self.loading = True
self.menu_gui["type"] = 2
self.options_done = False
else:
self.menu_gui["type"] = self.menu_gui["hover"]
self.menu_gui["hover"] = 1
self.last_keyboard_choose = pygame.time.get_ticks()
def blit_text(self, max_width, max_height, text, pos, font, color=(153, 102, 51), extra_padding=0):
words = [word.split(' ') for word in text.splitlines()] # 2D array where each row is a list of words.
space = font.size(' ')[0] # The self.WIDTH of a space.
pos_x, pos_y = pos
for line in words:
word_height = 0
for word in line:
word_surface = font.render(word, True, color)
word_width, word_height = word_surface.get_width(), word_surface.get_height() + extra_padding
if pos_x + word_width >= pos[0] + max_width:
pos_x = pos[0] # Reset the x.
pos_y += word_height # Start on new row.
if pos_y >= pos[1] + max_height - word_height:
return pos_y
self.window.blit(word_surface, (pos_x, pos_y))
pos_x += word_width + space
pos_x = pos[0] # Reset the x.
pos_y += word_height # Start on new row.
return pos_y
def send_message(self, msg, player=None):
# print(msg)
self.GameObject.send_message(msg, player)
self.over_box_limit = False
return msg
def next_night(self):
self.news = True
self.leaderboard = True
self.market = False
self.exchange = False
self.night = self.GameObject.day + 1
self.GameObject.next_night()
def run_menu(self):
pygame.time.wait(1)
self.check_mouse_hover()
for event in pygame.event.get():
if event.type == pygame.QUIT:
| |
<reponame>DataEconomistDK/Recession-Predictor
"""
This module runs backtests.
"""
import json
import pandas as pd
import RecessionPredictor_paths as path
from models.knn import KNN
from models.elastic_net import ElasticNet
from models.naive_bayes import NaiveBayes
from models.svm import SupportVectorMachine
from models.gp import GaussianProcess
from models.xgboost import XGBoost
from models.weighted_average import WeightedAverage
class CrossValidate:
"""
Methods and attributes for cross-validation.
"""
def __init__(self):
self.cv_params = {}
self.test_name = ''
self.full_df = pd.DataFrame()
self.feature_names = []
self.feature_dict = {}
self.output_names = []
self.optimal_params_by_output = {}
self.cv_metadata_by_output = {}
self.cv_predictions_by_output = {}
def walk_forward_cv(self):
"""
Runs walk-forward cross-validation, and saves cross-validation
metrics.
"""
for output_name in self.output_names:
print('\t\t\t|--Prediction type: {}'.format(output_name))
optimal_params_by_model = {}
cv_metadata_by_model = {}
cv_predictions_by_model = {}
print('\t\t\t\t|--KNN Model')
knn = KNN()
knn.cv_params = self.cv_params
knn.test_name = self.test_name
knn.full_df = self.full_df
knn.feature_names = self.feature_names
knn.output_name = output_name
knn.run_knn_cv()
optimal_params_by_model['KNN'] = knn.knn_optimal_params
cv_predictions_by_model['KNN'] = knn.knn_cv_predictions
print('\t\t\t\t|--Elastic Net Model')
elastic_net = ElasticNet()
elastic_net.cv_params = self.cv_params
elastic_net.test_name = self.test_name
elastic_net.full_df = self.full_df
elastic_net.feature_names = self.feature_names
elastic_net.feature_dict = self.feature_dict
elastic_net.output_name = output_name
elastic_net.run_elastic_net_cv()
optimal_params_by_model['Elastic_Net'] = elastic_net.elastic_net_optimal_params
cv_metadata_by_model['Elastic_Net'] = elastic_net.metadata
cv_predictions_by_model['Elastic_Net'] = elastic_net.elastic_net_cv_predictions
print('\t\t\t\t|--Naive Bayes Model')
naive_bayes = NaiveBayes()
naive_bayes.cv_params = self.cv_params
naive_bayes.test_name = self.test_name
naive_bayes.full_df = self.full_df
naive_bayes.feature_names = self.feature_names
naive_bayes.feature_dict = self.feature_dict
naive_bayes.output_name = output_name
naive_bayes.run_bayes_cv()
cv_predictions_by_model['Naive_Bayes'] = naive_bayes.bayes_cv_predictions
optimal_params_by_model['Naive_Bayes'] = naive_bayes.bayes_optimal_params
print('\t\t\t\t|--SVM Model')
svm = SupportVectorMachine()
svm.cv_params = self.cv_params
svm.test_name = self.test_name
svm.full_df = self.full_df
svm.feature_names = self.feature_names
svm.output_name = output_name
svm.run_svm_cv()
optimal_params_by_model['SVM'] = svm.svm_optimal_params
cv_metadata_by_model['SVM'] = svm.metadata
cv_predictions_by_model['SVM'] = svm.svm_cv_predictions
print('\t\t\t\t|--Gaussian Process Model')
gauss = GaussianProcess()
gauss.cv_params = self.cv_params
gauss.test_name = self.test_name
gauss.full_df = self.full_df
gauss.feature_names = self.feature_names
gauss.feature_dict = self.feature_dict
gauss.output_name = output_name
gauss.run_gauss_cv()
cv_predictions_by_model['Gaussian_Process'] = gauss.gauss_cv_predictions
cv_metadata_by_model['Gaussian_Process'] = gauss.metadata
optimal_params_by_model['Gaussian_Process'] = gauss.gauss_optimal_params
print('\t\t\t\t|--XGBoost Model')
xgboost = XGBoost()
xgboost.cv_params = self.cv_params
xgboost.test_name = self.test_name
xgboost.full_df = self.full_df
xgboost.feature_names = self.feature_names
xgboost.feature_dict = self.feature_dict
xgboost.output_name = output_name
xgboost.run_xgboost_cv()
optimal_params_by_model['XGBoost'] = xgboost.xgboost_optimal_params
cv_metadata_by_model['XGBoost'] = xgboost.metadata
cv_predictions_by_model['XGBoost'] = xgboost.xgboost_cv_predictions
self.optimal_params_by_output[output_name] = optimal_params_by_model
self.cv_metadata_by_output[output_name] = cv_metadata_by_model
self.cv_predictions_by_output[output_name] = cv_predictions_by_model
class Predict:
"""
Methods and attributes for prediction.
"""
def __init__(self):
self.pred_start = ''
self.pred_end = ''
self.full_df = pd.DataFrame()
self.pred_indices = []
self.feature_names = []
self.feature_dict = {}
self.model_names = []
self.output_names = []
self.prediction_errors_by_output = {}
self.predictions_by_output = {}
self.cv_predictions_by_output = {}
self.optimal_params_by_output = {}
self.pred_metadata_by_output = {}
def get_prediction_indices(self):
"""
Gets indices for rows to be used during prediction.
"""
if self.full_df['Dates'][0] > self.full_df['Dates'][len(self.full_df) - 1]:
self.full_df = self.full_df[::-1]
self.full_df.reset_index(inplace=True)
self.full_df.drop('index', axis=1, inplace=True)
date_condition = ((self.full_df['Dates'] <= self.pred_end) &
(self.full_df['Dates'] >= self.pred_start))
self.pred_indices = list(self.full_df[date_condition].index)
def walk_forward_prediction(self):
"""
Runs walk-forward prediction, and saves prediction metrics.
"""
for output_name in self.output_names:
print('\t\t\t|--Prediction type: {}'.format(output_name))
prediction_errors_by_model = {}
predictions_by_model = {}
pred_metadata_by_model = {}
print('\t\t\t\t|--KNN Model')
knn = KNN()
knn.pred_indices = self.pred_indices
knn.full_df = self.full_df
knn.feature_names = self.feature_names
knn.output_name = output_name
knn.knn_optimal_params = self.optimal_params_by_output[output_name]['KNN']
knn.run_knn_prediction()
prediction_errors_by_model['KNN'] = knn.knn_pred_error
predictions_by_model['KNN'] = knn.knn_predictions
print('\t\t\t\t|--Elastic Net Model')
elastic_net = ElasticNet()
elastic_net.pred_indices = self.pred_indices
elastic_net.full_df = self.full_df
elastic_net.feature_names = self.feature_names
elastic_net.feature_dict = self.feature_dict
elastic_net.output_name = output_name
elastic_net.elastic_net_optimal_params = self.optimal_params_by_output[output_name]['Elastic_Net']
elastic_net.run_elastic_net_prediction()
prediction_errors_by_model['Elastic_Net'] = elastic_net.elastic_net_pred_error
predictions_by_model['Elastic_Net'] = elastic_net.elastic_net_predictions
pred_metadata_by_model['Elastic_Net'] = elastic_net.metadata
print('\t\t\t\t|--Naive Bayes Model')
naive_bayes = NaiveBayes()
naive_bayes.pred_indices = self.pred_indices
naive_bayes.full_df = self.full_df
naive_bayes.feature_names = self.feature_names
naive_bayes.output_name = output_name
naive_bayes.run_bayes_prediction()
prediction_errors_by_model['Naive_Bayes'] = naive_bayes.bayes_pred_error
predictions_by_model['Naive_Bayes'] = naive_bayes.bayes_predictions
print('\t\t\t\t|--SVM Model')
svm = SupportVectorMachine()
svm.pred_indices = self.pred_indices
svm.full_df = self.full_df
svm.feature_names = self.feature_names
svm.output_name = output_name
svm.svm_optimal_params = self.optimal_params_by_output[output_name]['SVM']
svm.run_svm_prediction()
prediction_errors_by_model['SVM'] = svm.svm_pred_error
predictions_by_model['SVM'] = svm.svm_predictions
pred_metadata_by_model['SVM'] = svm.metadata
print('\t\t\t\t|--Gaussian Process Model')
gauss = GaussianProcess()
gauss.pred_indices = self.pred_indices
gauss.full_df = self.full_df
gauss.feature_names = self.feature_names
gauss.output_name = output_name
gauss.run_gauss_prediction()
prediction_errors_by_model['Gaussian_Process'] = gauss.gauss_pred_error
predictions_by_model['Gaussian_Process'] = gauss.gauss_predictions
pred_metadata_by_model['Gaussian_Process'] = gauss.metadata
print('\t\t\t\t|--XGBoost Model')
xgboost = XGBoost()
xgboost.pred_indices = self.pred_indices
xgboost.full_df = self.full_df
xgboost.feature_names = self.feature_names
xgboost.feature_dict = self.feature_dict
xgboost.output_name = output_name
xgboost.xgboost_optimal_params = self.optimal_params_by_output[output_name]['XGBoost']
xgboost.run_xgboost_prediction()
prediction_errors_by_model['XGBoost'] = xgboost.xgboost_pred_error
predictions_by_model['XGBoost'] = xgboost.xgboost_predictions
pred_metadata_by_model['XGBoost'] = xgboost.metadata
print('\t\t\t\t|--Weighted Average Model')
weighted_average = WeightedAverage()
weighted_average.model_names = self.model_names
weighted_average.cv_results = self.optimal_params_by_output[output_name]
weighted_average.predictions_by_model = predictions_by_model
weighted_average.run_weighted_average_prediction()
predictions_by_model['Weighted_Average'] = weighted_average.weighted_average_predictions
pred_metadata_by_model['Weighted_Average'] = weighted_average.metadata
self.prediction_errors_by_output[output_name] = prediction_errors_by_model
self.predictions_by_output[output_name] = predictions_by_model
self.pred_metadata_by_output[output_name] = pred_metadata_by_model
def run_prediction(self):
"""
Gets indices for rows to be used during prediction, and performs
walk-forward prediction.
"""
self.get_prediction_indices()
self.walk_forward_prediction()
class Backtester:
"""
The manager class for this module.
"""
def __init__(self):
"""
feature_names: names of features to include in backtest
feature_dict: used for naming columns of model outputs
model_names: names of the models to include in backtest
output_names: names of the outputs to include in backtest
"""
self.final_df_output = pd.DataFrame()
self.testing_dates = {}
self.optimal_params = {}
self.cv_model_metadata = {}
self.pred_model_metadata = {}
self.prediction_errors = {}
self.full_predictions = {}
self.feature_names = ['Payrolls_3mo_vs_12mo',
'Real_Fed_Funds_Rate_12mo_chg',
'CPI_3mo_pct_chg_annualized',
'10Y_Treasury_Rate_12mo_chg',
'3M_10Y_Treasury_Spread',
'S&P_500_12mo_chg']
self.feature_dict = {0: 'Payrolls_3mo_vs_12mo',
1: 'Real_Fed_Funds_Rate_12mo_chg',
2: 'CPI_3mo_pct_chg_annualized',
3: '10Y_Treasury_Rate_12mo_chg',
4: '3M_10Y_Treasury_Spread',
5: 'S&P_500_12mo_chg'}
self.model_names = ['KNN', 'Elastic_Net', 'Naive_Bayes',
'SVM', 'Gaussian_Process', 'XGBoost']
self.output_names = ['Recession',
'Recession_within_6mo',
'Recession_within_12mo',
'Recession_within_24mo']
def fill_testing_dates(self):
"""
Stores testing dates, for each test number.
"""
self.testing_dates[1] = {'cv_start': '1972-01-01',
'cv_end': '1975-12-01',
'pred_start': '1976-01-01',
'pred_end': '1981-07-01'}
self.testing_dates[2] = {'cv_start': '1976-01-01',
'cv_end': '1981-07-01',
'pred_start': '1981-08-01',
'pred_end': '1983-07-01'}
self.testing_dates[3] = {'cv_start': '1976-01-01',
'cv_end': '1983-07-01',
'pred_start': '1983-08-01',
'pred_end': '1992-12-01'}
self.testing_dates[4] = {'cv_start': '1983-08-01',
'cv_end': '1992-12-01',
'pred_start': '1993-01-01',
'pred_end': '2003-07-01'}
self.testing_dates[5] = {'cv_start': '1993-01-01',
'cv_end': '2003-07-01',
'pred_start': '2003-08-01',
'pred_end': '2010-09-01'}
def perform_backtests(self):
"""
Performs cross-validation and prediction.
"""
for test_name in self.testing_dates:
print('\t|--Test #{}'.format(test_name))
test_dates = self.testing_dates[test_name]
print('\t\t|--Performing Nested Cross-Validation')
cross_validation = CrossValidate()
cross_validation.output_names = self.output_names
cross_validation.feature_names = self.feature_names
cross_validation.feature_dict = self.feature_dict
cross_validation.full_df = self.final_df_output
cross_validation.cv_params = self.testing_dates
cross_validation.test_name = test_name
cross_validation.walk_forward_cv()
self.optimal_params['Test #{}'.format(test_name)] = cross_validation.optimal_params_by_output
self.cv_model_metadata['Test #{}'.format(test_name)] = cross_validation.cv_metadata_by_output
print('\t\t|--Performing Out-Of-Sample Testing')
prediction = Predict()
prediction.output_names = self.output_names
prediction.feature_names = self.feature_names
prediction.feature_dict = self.feature_dict
prediction.model_names = self.model_names
prediction.optimal_params_by_output = cross_validation.optimal_params_by_output
prediction.cv_predictions_by_output = cross_validation.cv_predictions_by_output
prediction.full_df = self.final_df_output
prediction.pred_start = test_dates['pred_start']
prediction.pred_end = test_dates['pred_end']
prediction.run_prediction()
self.prediction_errors['Test #{}'.format(test_name)] = prediction.prediction_errors_by_output
self.full_predictions['Test #{}'.format(test_name)] = prediction.predictions_by_output
self.pred_model_metadata['Test #{}'.format(test_name)] = prediction.pred_metadata_by_output
print('\nSaving model metadata...')
with open(path.cv_results, 'w') as file:
json.dump(self.optimal_params, file)
with open(path.cv_metadata, 'w') as file:
json.dump(self.cv_model_metadata, file)
with open(path.pred_model_metadata, 'w') as file:
json.dump(self.pred_model_metadata, file)
with open(path.prediction_errors, 'w') as file:
json.dump(self.prediction_errors, file)
with open(path.full_predictions, 'w') as file:
json.dump(self.full_predictions, file)
def read_full_predictions(self, model_name):
"""
Given a specific model, loops through each Test to save model predictions
into a single dataframe.
model_name: name of the model
"""
model_name = str(model_name)
dates = []
true_0mo = []
true_6mo = []
pred_6mo = []
true_12mo = []
pred_12mo = []
true_24mo = []
pred_24mo = []
for test in self.full_predictions:
test_data = self.full_predictions[test]
dates.extend(test_data[self.output_names[0]][model_name]['Dates'])
true_0mo.extend(test_data[self.output_names[0]][model_name]['True'])
true_6mo.extend(test_data[self.output_names[1]][model_name]['True'])
pred_6mo.extend(test_data[self.output_names[1]][model_name]['Predicted'])
true_12mo.extend(test_data[self.output_names[2]][model_name]['True'])
pred_12mo.extend(test_data[self.output_names[2]][model_name]['Predicted'])
true_24mo.extend(test_data[self.output_names[3]][model_name]['True'])
pred_24mo.extend(test_data[self.output_names[3]][model_name]['Predicted'])
results = pd.DataFrame()
results['Dates'] = dates
results['True_{}'.format(self.output_names[0])] = true_0mo
results['True_{}'.format(self.output_names[1])] = true_6mo
results['Pred_{}'.format(self.output_names[1])] = pred_6mo
results['True_{}'.format(self.output_names[2])] = true_12mo
results['Pred_{}'.format(self.output_names[2])] = pred_12mo
results['True_{}'.format(self.output_names[3])] = true_24mo
results['Pred_{}'.format(self.output_names[3])] = pred_24mo
return(results)
def create_full_predictions_dataframe(self):
"""
Organizes predictions for each model into a single dataframe.
"""
print('\nSaving Full Predictions as dataframes...')
with open(path.full_predictions, 'r') as file:
self.full_predictions = json.load(file)
self.read_full_predictions('KNN').to_json(path.knn_test_results)
print('\t|--KNN results saved to {}'.format(path.knn_test_results))
self.read_full_predictions('Elastic_Net').to_json(path.elastic_net_test_results)
print('\t|--Elastic Net results saved to {}'.format(path.elastic_net_test_results))
self.read_full_predictions('Naive_Bayes').to_json(path.naive_bayes_test_results)
print('\t|--Naive Bayes results saved to {}'.format(path.naive_bayes_test_results))
self.read_full_predictions('SVM').to_json(path.svm_test_results)
print('\t|--SVM results saved to {}'.format(path.svm_test_results))
self.read_full_predictions('Gaussian_Process').to_json(path.gauss_test_results)
print('\t|--Gaussian Process results saved to {}'.format(path.gauss_test_results))
self.read_full_predictions('XGBoost').to_json(path.xgboost_test_results)
print('\t|--XGBoost results saved to {}'.format(path.xgboost_test_results))
self.read_full_predictions('Weighted_Average').to_json(path.weighted_average_test_results)
print('\t|--Weighted Average results saved to {}'.format(path.weighted_average_test_results))
def run_test_procedures(self):
"""
Runs test procedures on final dataset.
"""
print('\nPerforming backtests...\n')
self.final_df_output = pd.read_json(path.data_final)
self.final_df_output.sort_index(inplace=True)
self.fill_testing_dates()
self.perform_backtests()
self.create_full_predictions_dataframe()
print('\nBacktesting complete!')
#MIT License
#
#Copyright (c) 2019 <NAME>
#
#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, | |
to repeat for recurrence.
startdate = startdate.astimezone(timezone) # transform "+hh:mm" timezone
rset1 = rrule.rrulestr(str(event.rrule), dtstart=startdate, forceset=True)
ids_depending = self.search(cr, uid, [('recurrent_id', '=', event.id), '|', ('active', '=', False), ('active', '=', True)], context=context)
all_events = self.browse(cr, uid, ids_depending, context=context)
for ev in all_events:
rset1._exdate.append(todate(ev.recurrent_id_date))
return [d.astimezone(pytz.UTC) for d in rset1]
def _get_recurrency_end_date(self, cr, uid, id, context=None):
data = self.read(cr, uid, id, ['final_date', 'recurrency', 'rrule_type', 'count', 'end_type', 'stop'], context=context)
if not data.get('recurrency'):
return False
end_type = data.get('end_type')
final_date = data.get('final_date')
if end_type == 'count' and all(data.get(key) for key in ['count', 'rrule_type', 'stop']):
count = data['count'] + 1
delay, mult = {
'daily': ('days', 1),
'weekly': ('days', 7),
'monthly': ('months', 1),
'yearly': ('years', 1),
}[data['rrule_type']]
deadline = datetime.strptime(data['stop'], tools.DEFAULT_SERVER_DATETIME_FORMAT)
return deadline + relativedelta(**{delay: count * mult})
return final_date
def _find_my_attendee(self, cr, uid, meeting_ids, context=None):
"""
Return the first attendee where the user connected has been invited from all the meeting_ids in parameters
"""
user = self.pool['res.users'].browse(cr, uid, uid, context=context)
for meeting_id in meeting_ids:
for attendee in self.browse(cr, uid, meeting_id, context).attendee_ids:
if user.partner_id.id == attendee.partner_id.id:
return attendee
return False
def get_date_formats(self, cr, uid, context):
lang = context.get("lang")
res_lang = self.pool.get('res.lang')
lang_params = {}
if lang:
ids = res_lang.search(request.cr, uid, [("code", "=", lang)])
if ids:
lang_params = res_lang.read(request.cr, uid, ids[0], ["date_format", "time_format"])
# formats will be used for str{f,p}time() which do not support unicode in Python 2, coerce to str
format_date = lang_params.get("date_format", '%B-%d-%Y').encode('utf-8')
format_time = lang_params.get("time_format", '%I-%M %p').encode('utf-8')
return (format_date, format_time)
def get_display_time_tz(self, cr, uid, ids, tz=False, context=None):
context = dict(context or {})
if tz:
context["tz"] = tz
ev = self.browse(cr, uid, ids, context=context)[0]
return self._get_display_time(cr, uid, ev.start, ev.stop, ev.duration, ev.allday, context=context)
def _get_display_time(self, cr, uid, start, stop, zduration, zallday, context=None):
"""
Return date and time (from to from) based on duration with timezone in string :
eg.
1) if user add duration for 2 hours, return : August-23-2013 at (04-30 To 06-30) (Europe/Brussels)
2) if event all day ,return : AllDay, July-31-2013
"""
context = dict(context or {})
tz = context.get('tz', False)
if not tz: # tz can have a value False, so dont do it in the default value of get !
context['tz'] = self.pool.get('res.users').read(cr, SUPERUSER_ID, uid, ['tz'])['tz']
tz = context['tz']
tz = tools.ustr(tz).encode('utf-8') # make safe for str{p,f}time()
format_date, format_time = self.get_date_formats(cr, uid, context=context)
date = fields.datetime.context_timestamp(cr, uid, datetime.strptime(start, tools.DEFAULT_SERVER_DATETIME_FORMAT), context=context)
date_deadline = fields.datetime.context_timestamp(cr, uid, datetime.strptime(stop, tools.DEFAULT_SERVER_DATETIME_FORMAT), context=context)
event_date = date.strftime(format_date)
display_time = date.strftime(format_time)
if zallday:
time = _("AllDay , %s") % (event_date)
elif zduration < 24:
duration = date + timedelta(hours=zduration)
time = ("%s at (%s To %s) (%s)") % (event_date, display_time, duration.strftime(format_time), tz)
else:
time = ("%s at %s To\n %s at %s (%s)") % (event_date, display_time, date_deadline.strftime(format_date), date_deadline.strftime(format_time), tz)
return time
def _compute(self, cr, uid, ids, fields, arg, context=None):
res = {}
if not isinstance(fields, list):
fields = [fields]
for meeting in self.browse(cr, uid, ids, context=context):
meeting_data = {}
res[meeting.id] = meeting_data
attendee = self._find_my_attendee(cr, uid, [meeting.id], context)
for field in fields:
if field == 'is_attendee':
meeting_data[field] = bool(attendee)
elif field == 'attendee_status':
meeting_data[field] = attendee.state if attendee else 'needsAction'
elif field == 'display_time':
meeting_data[field] = self._get_display_time(cr, uid, meeting.start, meeting.stop, meeting.duration, meeting.allday, context=context)
elif field == "display_start":
meeting_data[field] = meeting.start_date if meeting.allday else meeting.start_datetime
elif field == 'start':
meeting_data[field] = meeting.start_date if meeting.allday else meeting.start_datetime
elif field == 'stop':
meeting_data[field] = meeting.stop_date if meeting.allday else meeting.stop_datetime
return res
def _get_rulestring(self, cr, uid, ids, name, arg, context=None):
"""
Gets Recurrence rule string according to value type RECUR of iCalendar from the values given.
@return: dictionary of rrule value.
"""
result = {}
if not isinstance(ids, list):
ids = [ids]
#read these fields as SUPERUSER because if the record is private a normal search could raise an error
events = self.read(cr, SUPERUSER_ID, ids,
['id', 'byday', 'recurrency', 'final_date', 'rrule_type', 'month_by',
'interval', 'count', 'end_type', 'mo', 'tu', 'we', 'th', 'fr', 'sa',
'su', 'day', 'week_list'], context=context)
for event in events:
if event['recurrency']:
result[event['id']] = self.compute_rule_string(event)
else:
result[event['id']] = ''
return result
# retro compatibility function
def _rrule_write(self, cr, uid, ids, field_name, field_value, args, context=None):
return self._set_rulestring(self, cr, uid, ids, field_name, field_value, args, context=context)
def _set_rulestring(self, cr, uid, ids, field_name, field_value, args, context=None):
if not isinstance(ids, list):
ids = [ids]
data = self._get_empty_rrule_data()
if field_value:
data['recurrency'] = True
for event in self.browse(cr, uid, ids, context=context):
rdate = event.start
update_data = self._parse_rrule(field_value, dict(data), rdate)
data.update(update_data)
self.write(cr, uid, ids, data, context=context)
return True
def _set_date(self, cr, uid, values, id=False, context=None):
if context is None:
context = {}
if values.get('start_datetime') or values.get('start_date') or values.get('start') \
or values.get('stop_datetime') or values.get('stop_date') or values.get('stop'):
allday = values.get("allday", None)
event = self.browse(cr, uid, id, context=context)
if allday is None:
if id:
allday = event.allday
else:
allday = False
_logger.warning("Calendar - All day is not specified, arbitrarily set to False")
#raise osv.except_osv(_('Error!'), ("Need to know if it's an allday or not..."))
key = "date" if allday else "datetime"
notkey = "datetime" if allday else "date"
for fld in ('start', 'stop'):
if values.get('%s_%s' % (fld, key)) or values.get(fld):
values['%s_%s' % (fld, key)] = values.get('%s_%s' % (fld, key)) or values.get(fld)
values['%s_%s' % (fld, notkey)] = None
if fld not in values.keys():
values[fld] = values['%s_%s' % (fld, key)]
diff = False
if allday and (values.get('stop_date') or values.get('start_date')):
stop_date = values.get('stop_date') or event.stop_date
start_date = values.get('start_date') or event.start_date
if stop_date and start_date:
diff = openerp.fields.Date.from_string(stop_date) - openerp.fields.Date.from_string(start_date)
elif values.get('stop_datetime') or values.get('start_datetime'):
stop_datetime = values.get('stop_datetime') or event.stop_datetime
start_datetime = values.get('start_datetime') or event.start_datetime
if stop_datetime and start_datetime:
diff = openerp.fields.Datetime.from_string(stop_datetime) - openerp.fields.Datetime.from_string(start_datetime)
if diff:
duration = float(diff.days) * 24 + (float(diff.seconds) / 3600)
values['duration'] = round(duration, 2)
_track = {
'location': {
'calendar.subtype_invitation': lambda self, cr, uid, obj, ctx=None: True,
},
'start': {
'calendar.subtype_invitation': lambda self, cr, uid, obj, ctx=None: True,
},
}
_columns = {
'id': fields.integer('ID', readonly=True),
'state': fields.selection([('draft', 'Unconfirmed'), ('open', 'Confirmed')], string='Status', readonly=True, track_visibility='onchange'),
'name': fields.char('Meeting Subject', required=True, states={'done': [('readonly', True)]}),
'is_attendee': fields.function(_compute, string='Attendee', type="boolean", multi='attendee'),
'attendee_status': fields.function(_compute, string='Attendee Status', type="selection", selection=calendar_attendee.STATE_SELECTION, multi='attendee'),
'display_time': fields.function(_compute, string='Event Time', type="char", multi='attendee'),
'display_start': fields.function(_compute, string='Date', type="char", multi='attendee', store=True),
'allday': fields.boolean('All Day', states={'done': [('readonly', True)]}),
'start': fields.function(_compute, string='Calculated start', type="datetime", multi='attendee', store=True, required=True),
'stop': fields.function(_compute, string='Calculated stop', type="datetime", multi='attendee', store=True, required=True),
'start_date': fields.date('Start Date', states={'done': [('readonly', True)]}, track_visibility='onchange'),
'start_datetime': fields.datetime('Start DateTime', states={'done': [('readonly', True)]}, track_visibility='onchange'),
'stop_date': fields.date('End Date', states={'done': [('readonly', True)]}, track_visibility='onchange'),
'stop_datetime': fields.datetime('End Datetime', states={'done': [('readonly', True)]}, track_visibility='onchange'), # old date_deadline
'duration': fields.float('Duration', states={'done': [('readonly', True)]}),
'description': fields.text('Description', states={'done': [('readonly', True)]}),
'class': fields.selection([('public', 'Public'), ('private', 'Private'), ('confidential', 'Public for Employees')], 'Privacy', states={'done': [('readonly', True)]}),
'location': fields.char('Location', help="Location of Event", track_visibility='onchange', states={'done': [('readonly', True)]}),
'show_as': fields.selection([('free', 'Free'), ('busy', 'Busy')], 'Show Time as', states={'done': [('readonly', True)]}),
# RECURRENCE FIELD
'rrule': fields.function(_get_rulestring, type='char', fnct_inv=_set_rulestring, store=True, string='Recurrent Rule'),
'rrule_type': fields.selection([('daily', 'Day(s)'), ('weekly', 'Week(s)'), ('monthly', 'Month(s)'), ('yearly', 'Year(s)')], 'Recurrency', states={'done': [('readonly', True)]}, help="Let the event automatically repeat at that interval"),
'recurrency': fields.boolean('Recurrent', help="Recurrent Meeting"),
'recurrent_id': fields.integer('Recurrent ID'),
'recurrent_id_date': fields.datetime('Recurrent ID date'),
'end_type': fields.selection([('count', 'Number of repetitions'), ('end_date', 'End date')], 'Recurrence Termination'),
'interval': fields.integer('Repeat Every', help="Repeat every (Days/Week/Month/Year)"),
'count': fields.integer('Repeat', help="Repeat x times"),
'mo': fields.boolean('Mon'),
'tu': fields.boolean('Tue'),
'we': fields.boolean('Wed'),
'th': fields.boolean('Thu'),
'fr': fields.boolean('Fri'),
'sa': fields.boolean('Sat'),
'su': fields.boolean('Sun'),
'month_by': fields.selection([('date', 'Date of month'), ('day', 'Day of month')], 'Option', oldname='select1'),
'day': fields.integer('Date of month'),
'week_list': fields.selection([('MO', 'Monday'), ('TU', 'Tuesday'), ('WE', 'Wednesday'), ('TH', 'Thursday'), ('FR', 'Friday'), ('SA', 'Saturday'), ('SU', 'Sunday')], 'Weekday'),
'byday': fields.selection([('1', 'First'), ('2', 'Second'), ('3', 'Third'), ('4', 'Fourth'), ('5', 'Fifth'), ('-1', 'Last')], 'By day'),
'final_date': fields.date('Repeat Until'), # The last event of a recurrence
'user_id': fields.many2one('res.users', 'Responsible', states={'done': [('readonly', True)]}),
'color_partner_id': fields.related('user_id', 'partner_id', 'id', type="integer", string="colorize", store=False), # Color of creator
'active': fields.boolean('Active', help="If the active field is set to false, it will allow you to hide the event alarm information without removing it."),
'categ_ids': fields.many2many('calendar.event.type', 'meeting_category_rel', 'event_id', 'type_id', 'Tags'),
'attendee_ids': fields.one2many('calendar.attendee', 'event_id', 'Attendees', ondelete='cascade'),
'partner_ids': fields.many2many('res.partner', 'calendar_event_res_partner_rel', string='Attendees', states={'done': [('readonly', True)]}),
'alarm_ids': fields.many2many('calendar.alarm', 'calendar_alarm_calendar_event_rel', string='Reminders', ondelete="restrict", copy=False),
}
def _get_default_partners(self, cr, uid, ctx=None):
ret = [self.pool['res.users'].browse(cr, | |
<reponame>arashb/pyclaw
r"""
Module specifying the interface to every solver in PyClaw.
"""
import logging
class CFLError(Exception):
"""Error raised when cfl_max is exceeded. Is this a
reasonable mechanism for handling that?"""
def __init__(self,msg):
super(CFLError,self).__init__(msg)
class BC():
"""Enumeration of boundary condition names.
This could instead just be a static dictionary."""
custom = 0
extrap = 1
periodic = 2
wall = 3
#################### Dummy routines ######################
def default_compute_gauge_values(q,aux):
r"""By default, record values of q at gauges.
"""
return q
class Solver(object):
r"""
Pyclaw solver superclass.
The pyclaw.Solver.solver class is an abstract class that should
not be instantiated; rather, all Solver classes should inherit from it.
A Solver is typically instantiated as follows::
>>> from clawpack import pyclaw
>>> solver = pyclaw.ClawSolver2D()
After which solver options may be set. It is always necessary to set
solver.num_waves to the number of waves used in the Riemann solver.
Typically it is also necessary to set the boundary conditions (for q, and
for aux if an aux array is used). Many other options may be set
for specific solvers; for instance the limiter to be used, whether to
use a dimensionally-split algorithm, and so forth.
Usually the solver is attached to a controller before being used::
>>> claw = pyclaw.Controller()
>>> claw.solver = solver
.. attribute:: dt
Current time step, ``default = 0.1``
.. attribute:: cfl
Current Courant-Freidrichs-Lewy number, ``default = 1.0``
.. attribute:: status
Dictionary of status values for the solver with the following keys:
- ``cflmax`` = Maximum CFL number
- ``dtmin`` = Minimum time step taken
- ``dtmax`` = Maximum time step taken
- ``numsteps`` = Current number of time steps that have been taken
solver.status is reset each time solver.evolve_to_time is called, and
it is also returned by solver.evolve_to_time.
.. attribute:: dt_variable
Whether to allow the time step to vary, ``default = True``.
If false, the initial time step size is used for all steps.
.. attribute:: max_steps
The maximum number of time steps allowd to reach the end time
requested, ``default = 1000``. If exceeded, an exception is
raised.
.. attribute:: logger
Default logger for all solvers. Records information about the run
and debugging messages (if requested).
.. attribute:: bc_lower
(list of ints) Lower boundary condition types, listed in the
same order as the Dimensions of the Patch. See Solver.BC for
an enumeration.
.. attribute:: bc_upper
(list of ints) Upper boundary condition types, listed in the
same order as the Dimensions of the Patch. See Solver.BC for
an enumeration.
.. attribute:: user_bc_lower
(func) User defined lower boundary condition.
Fills the values of qbc with the correct boundary values.
The appropriate signature is:
def user_bc_lower(patch,dim,t,qbc,num_ghost):
.. attribute:: user_bc_upper
(func) User defined upper boundary condition.
Fills the values of qbc with the correct boundary values.
The appropriate signature is:
def user_bc_upper(patch,dim,t,qbc,num_ghost):
:Initialization:
Output:
- (:class:`Solver`) - Initialized Solver object
"""
def __setattr__(self, key, value):
if not hasattr(self, '_isinitialized'):
self.__dict__['_isinitialized'] = False
if self._isinitialized and not hasattr(self, key):
raise TypeError("%s has no attribute %s" % (self.__class__,key))
object.__setattr__(self,key,value)
@property
def all_bcs(self):
return self.bc_lower, self.bc_upper
@all_bcs.setter
def all_bcs(self,all_bcs):
for i in range(self.num_dim):
self.bc_lower[i] = all_bcs
self.bc_upper[i] = all_bcs
# ======================================================================
# Initialization routines
# ======================================================================
def __init__(self,riemann_solver=None,claw_package=None):
r"""
Initialize a Solver object
See :class:`Solver` for full documentation
"""
# Setup solve logger
self.logger = logging.getLogger('evolve')
self.dt_initial = 0.1
self.dt_max = 1e99
self.max_steps = 1000
self.dt_variable = True
self.num_waves = None #Must be set later to agree with Riemann solver
self.qbc = None
self.auxbc = None
self.rp = None
self.fmod = None
self._is_set_up = False
# select package to build solver objects from, by default this will be
# the package that contains the module implementing the derived class
# for example, if ClawSolver1D is implemented in 'clawpack.petclaw.solver', then
# the computed claw_package will be 'clawpack.petclaw'
import sys
if claw_package is not None and claw_package in sys.modules:
self.claw_package = sys.modules[claw_package]
else:
def get_clawpack_dot_xxx(modname): return modname.rpartition('.')[0].rpartition('.')[0]
claw_package_name = get_clawpack_dot_xxx(self.__module__)
if claw_package_name in sys.modules:
self.claw_package = sys.modules[claw_package_name]
else:
raise NotImplementedError("Unable to determine solver package, please provide one")
# Initialize time stepper values
self.dt = self.dt_initial
self.cfl = self.claw_package.CFL(self.cfl_desired)
# Status Dictionary
self.status = {'cflmax':self.cfl.get_cached_max(),
'dtmin':self.dt,
'dtmax':self.dt,
'numsteps':0 }
# No default BCs; user must set them
self.bc_lower = [None]*self.num_dim
self.bc_upper = [None]*self.num_dim
self.aux_bc_lower = [None]*self.num_dim
self.aux_bc_upper = [None]*self.num_dim
self.user_bc_lower = None
self.user_bc_upper = None
self.user_aux_bc_lower = None
self.user_aux_bc_upper = None
self.compute_gauge_values = default_compute_gauge_values
r"""(function) - Function that computes quantities to be recorded at gauges"""
self.qbc = None
r""" Array to hold ghost cell values. This is the one that gets passed
to the Fortran code. """
if riemann_solver is not None:
self.rp = riemann_solver
rp_name = riemann_solver.__name__.split('.')[-1]
from clawpack import riemann
self.num_eqn = riemann.static.num_eqn[rp_name]
self.num_waves = riemann.static.num_waves[rp_name]
self._isinitialized = True
super(Solver,self).__init__()
# ========================================================================
# Solver setup and validation routines
# ========================================================================
def is_valid(self):
r"""
Checks that all required solver attributes are set.
Checks to make sure that all the required attributes for the solver
have been set correctly. All required attributes that need to be set
are contained in the attributes list of the class.
Will post debug level logging message of which required attributes
have not been set.
:Output:
- *valid* - (bool) True if the solver is valid, False otherwise
"""
valid = True
if any([bcmeth == BC.custom for bcmeth in self.bc_lower]):
if self.user_bc_lower is None:
self.logger.debug('Lower custom BC function has not been set.')
valid = False
if any([bcmeth == BC.custom for bcmeth in self.bc_upper]):
if self.user_bc_upper is None:
self.logger.debug('Upper custom BC function has not been set.')
valid = False
return valid
def setup(self,solution):
r"""
Stub for solver setup routines.
This function is called before a set of time steps are taken in order
to reach tend. A subclass should extend or override it if it needs to
perform some setup based on attributes that would be set after the
initialization routine. Typically this is initialization that
requires knowledge of the solution object.
"""
pass
def teardown(self):
r"""
Stub for solver teardown routines.
This function is called at the end of a simulation.
A subclass should override it only if it needs to
perform some cleanup, such as deallocating arrays in a Fortran module.
"""
pass
def __str__(self):
output = "Solver Status:\n"
for (k,v) in self.status.iteritems():
output = "\n".join((output,"%s = %s" % (k.rjust(25),v)))
return output
# ========================================================================
# Boundary Conditions
# ========================================================================
def allocate_bc_arrays(self,state):
r"""
Create numpy arrays for q and aux with ghost cells attached.
These arrays are referred to throughout the code as qbc and auxbc.
This is typically called by solver.setup().
"""
import numpy as np
qbc_dim = [n+2*self.num_ghost for n in state.grid.num_cells]
qbc_dim.insert(0,state.num_eqn)
self.qbc = np.zeros(qbc_dim,order='F')
auxbc_dim = [n+2*self.num_ghost for n in state.grid.num_cells]
auxbc_dim.insert(0,state.num_aux)
self.auxbc = np.empty(auxbc_dim,order='F')
if state.num_aux>0:
self.apply_aux_bcs(state)
def apply_q_bcs(self,state):
r"""
Fills in solver.qbc (the local vector), including ghost cell values.
This function returns an array of dimension determined by the
:attr:`num_ghost` attribute. The type of boundary condition set is
determined by :attr:`bc_lower` and :attr:`bc_upper` for the
approprate dimension. Valid values for :attr:`bc_lower` and
:attr:`bc_upper` include:
- 'custom' or 0: A user defined boundary condition will be used, the appropriate
Dimension method user_bc_lower or user_bc_upper will be called.
- 'extrap' or 1: Zero-order extrapolation.
- 'periodic' or 2: Periodic boundary conditions.
- 'wall' or 3: Wall boundary conditions. It is assumed that the second
component of q represents velocity or momentum.
:Input:
- *grid* - (:class:`Patch`) The grid being operated on.
- *state* - The state being operated on; this may or may not be the
same as *grid*. Generally it is the same | |
الأطفال',
'Child headed households (<18 yrs)': 'الأسر التي يرأسها أطفال (<18 عاما)',
'Child Protection': 'حماية الطفل',
'Children in juvenile detention': 'الأطفال الذين هم في محتجز الأحداث',
'Children orphaned by the disaster': 'الأطفال الذين تيتموا بسبب الكارثة',
'Children that have been sent to safe places': 'الأطفال الذين تم إرسالهم إلى أماكن آمنة',
'Children who have disappeared since the disaster': 'الأطفال الذين اختفوا منذ وقوع الكارثة',
"Children's Education": 'التعليم للأطفال',
'Chinese (Taiwan)': 'الصينية (تايوان)',
'Cholera-Treatment-Center': 'مركزعلاج الكوليرا',
'choose': 'أختر',
'Choose a type from the drop-down, or click the link to create a new type': 'اختر نوع من القائمة المنسدلة، أو انقر على الرابط لإنشاء نوع جديد',
'Choose File': 'اختيار مستند',
'Christian': 'مسيحي',
'Church': 'كنيسة',
'City': 'مدينة',
'Civil Society/NGOs': 'المجتمع / المنظمات غير الحكومية المدنية',
'Clean-Up Campaign': 'حملة تنظيف',
'Cleaner': 'المنظف',
'Clear': 'واضح',
'clear': 'واضح',
'Clear All': 'امسح الكل',
'Clear Color Selection': 'مسح لون التحديد',
'Clear Filter': 'مسح التصفية',
'Click anywhere on the map for full functionality': 'انقر فوق أي مكان على الخريطة للوظائف الكاملة',
'click for more details': 'اضغط هنا للمزيد من التفاصيل',
'click here': 'انقر هنا',
'Click on the link %(url)s to reset your password': 'انقر على الرابط %(url)s to reset your password',
'Click on the link %(url)s to verify your email': 'انقر على الرابط %(url)s للتحقق من بريدك الالكتروني',
'Click on the slider to choose a value': 'انقر على شريط التمرير لاختيار قيمة',
'Click to edit': 'إضغط للتعديل',
'Climate Change': 'تغير المناخ',
'Climate Change Adaptation ': 'التكيف مع تغير المناخ',
'Climate Change Mitigation': 'التخفيف من آثار تغير المناخ',
'Clinical Operations': 'عمليات سريرية',
'Clinical Status': 'حالة سريرية',
'Close': 'قريب',
'Close map': 'Close map',
'Closed': 'تم الغلق',
'Closure Reason': 'سبب الإغلاق',
'Clothing': 'ملابس',
'Cloud forecast': 'توقع الغيوم',
'Club 25 / Pledge 25': 'نادي 25 / تعهد 25',
'Cluster': 'الكتلة',
'Cluster added': 'أضافت الكتلة',
'Cluster deleted': 'تم حذف الكتلة',
'Cluster Details': 'تفاصيل الكتلة',
'Cluster Subsector': 'كتلة القطاع الفرعي',
'Cluster updated': 'تم تحديث الكتلة',
'Cluster(s)': 'كتلة(ج)',
'Clusters': 'الكتلة',
'Coalition added': 'تم إضافةالتحالف',
'Coalition Details': 'تفاصيل التحالف',
'Coalition removed': 'تم إزالةالتحالف',
'Coalition updated': 'تم تحديث التحالف',
'Coalitions': 'التحالفات',
'Coastal Conservation ': 'حفظ الساحلي',
'Code': 'كود',
'Code No.': 'رقم الكود.',
'Code Share': 'كود مشاركة',
'cohabiting': 'المعاشرة',
'Cold Wave': 'موجة برد',
'Collapse All': 'طي الكل',
'Color of Buttons when hovering': 'لون الأزرار عندما تحوم',
'Color of dropdown menus': 'لون القائمة المنسدلة',
'Color of selected Input fields': 'لون مجال المعلومات المختارة',
'Color of selected menu items': 'لون عناصر القائمة المختارة',
'Combined Method': 'طريقة مركبة',
'Comment': 'تعليق',
'Comments': 'التعليقات',
'Commit from %s': 'تسليم حسب %',
'Commit Status': 'حالة الإلتزام.',
'Commiting a changed spreadsheet to the database': 'الإلتزام بجدول التغيرات لقاعدة البيانات',
'Commitment Details': 'تفاصيل الالتزام',
'Commitment Item deleted': 'تم حذف الالتزام',
'Commitment Item Details': 'تفاصيل التزام العنصر',
'Commitment Updated': 'تم تحديث الالتزام',
'Commitments': 'الالتزامات',
'Commodities Loaded': 'السلع المحملة',
'Commune': 'البلدية',
'Communicable Diseases': 'الأمراض المعدية',
'Communication': 'الاتصالات',
'Communication Officer': 'موظف الاتصالات',
'Communities': 'المنظمات',
'Community': 'المجتمع',
'Community Action Planning': 'تخطيط العمل المجتمعي',
'Community Added': 'إضافة المجتمع',
'Community Based Health and First Aid (CBHFA)': ' الصحية والإسعافات الأولية المجتمعية (CBHFA)',
'Community Contacts': 'الاتصال المجتمع',
'Community Deleted': 'المجتمع تم حذفه',
'Community Details': 'تفاصيل المجتمع',
'Community Disaster Awareness': ' التوعية المجتمعية من الكوارث',
'Community Early Warning Systems': ' نظم الإنذار المبكر المجتمعية',
'Community Health': 'صحة المجتمع',
'Community Health Center': 'مركز لصحة المجتمع',
'Community Health Committees': 'لجان صحة المجتمع',
'Community Health Initiative/Projects': 'مبادرة صحة المجتمع / مشروعات',
'Community Health Risk Assessments': 'تقييم المخاطر الصحية المجتمعية',
'Community Mobilization': 'تعبئة المجتمع',
'Community Organization': 'منظمة المجتمع',
'Community Preparedness': 'تأهب المجتمع',
'Community Updated': ' المجتمع تم تحديثه',
'Community-based DRR': 'الحد من مخاطر الكوارث المجتمعية',
'Company': 'شركة',
'Comparison': 'مقارنة',
'Competencies': 'الكفاءات',
'Competency': 'كفاءة',
'Competency Details': 'تفاصيل الكفاءة',
'Competency Rating': 'تصنيف الكفاءات',
'Competency Rating added': ' تصنيف الكفاءات تم اضافته',
'Competency Rating Catalog': 'كاتالوج تصنيف الكفاءات',
'Competency Rating deleted': 'تصنيف الكفاءات تم حذفه',
'Competency Rating Details': 'تفاصيل تقييم الكفاءة',
'Competency Rating updated': 'تصنيف الكفاءات تم تحديثه',
'Completed': 'تم',
'completed': 'تم',
'Completion Date': 'موعد الإكمال',
'Completion Question': 'الاسئله التكميليه',
'Complex Emergency': 'حالات الطوارئ المعقدة',
'Complexion': 'مظهر عام',
'Compose': 'شكّل',
'Compromised': 'تسوية',
'Condition': 'الشروط',
'Configuration': 'إعداد',
'Configurations': 'إعدادات',
'Confirm Shipment Received': 'تأكيد تلقى الشحنة',
'Confirmed': 'تم تأكيد',
'Confirming Organization': 'المنظمة المؤكدة',
'Conflict Details': 'تفاصيل النزاع',
'Conflict Resolution': 'حل النزاع',
'Consenting to Data Disclosure': 'موافقة الكشف عن البيانات',
'consider': 'يعتبر',
'Construction Activities': 'أنشطة البناء',
'Construction of Transitional Shelter': 'بناء المأوى الانتقالي',
'Construction of Water Supply Systems': 'بناء أنظمة إمدادات المياه',
'Consumable': 'مستهلكات',
'Contact': 'اتصال',
'Contact added': ' الاتصال تم اضافته',
'Contact Added': 'تم إضافة الاتصال',
'Contact Data': 'بيانات الاتصال',
'Contact deleted': 'الاتصال تم حذفه',
'Contact Deleted': 'الاتصال تم حذفه',
'Contact Description': 'وصف الاتصال',
'Contact details': 'تفاصيل الاتصال',
'Contact Details': 'بيانات المتصل',
'Contact Details updated': 'تفاصيل الاتصال تم تحديثه',
'Contact Info': 'معلومات الاتصال',
'Contact Information': 'معلومات الشخص المُتصل به',
'Contact Information Added': 'معلومات الإتصال تم اضافتها',
'Contact Information Deleted': 'حُذفت معلومات المُتصل به',
'Contact information updated': 'تم تحديث معلومات الاتصال',
'Contact Information Updated': 'معلومات الإتصال تم تحديثه',
'Contact Method': 'طريقة الاتصال',
'Contact Name': '<NAME>',
'Contact People': 'إتصال الأفراد',
'Contact Person': 'الشخص الذي يمكن الاتصال به',
'Contact Phone': 'هاتف الاتصال',
'Contact Updated': 'الاتصال تم تحديثه',
'Contact Us': 'اتصل بنا',
'Contact us': 'اتصل بنا',
'Contacts': 'وسائل الاتصال',
'Contingency/Preparedness Planning': 'التخطيط للاستعداد / الطوارئ',
'Contract': 'العقد',
'Contract Details': 'تفاصيل العقد',
'Contract End Date': 'تاريخ انتهاء العقد',
'Contract Number': 'رقم العقد',
'Contractual Agreements (Community/Individual)': 'الاتفاقات التعاقدية (المجتمع / فردي)',
'Contractual Agreements (Governmental)': 'الاتفاقات التعاقدية (الحكومية)',
'Contributor': 'مشارك',
'Conversion Tool': 'أداة تحويل',
'Cook Islands': 'جزر كوك',
'Coordination and Partnerships': 'التنسيق والشراكات',
'Coordinator': 'المنسق',
'Copy': 'نسخ',
'Corporate Entity': 'الكيان المؤسسي',
'Cost per Megabyte': 'تكلفة لكل ميغا بايت',
'Cost Type': 'نوع التكلفة',
'Could not add person details': 'لا يمكن إضافة تفاصيل شخص',
'Could not add person record': 'لا يمكن اضافة سجل شخص',
'Could not create record.': 'لا يمكن إنشاء سجل.',
"couldn't be parsed so NetworkLinks not followed.": 'لا يمكن تحليل ذلك. تعذر تتبع NetworkLinks.',
'Counselor': 'مستشار',
'Count': 'العد',
'Country': 'البلد',
'Country Code': 'الرقم الدولي',
'Country of Deployment': 'بلد النشر',
'Course': 'الدورة',
'Course added': 'تم اضافة المقرر',
'Course Catalog': 'كتالوج الدورة',
'Course Certificate added': 'تم اضافة شهادة المقرر',
'Course Certificate deleted': 'تم حذف شهادة المقرر',
'Course Certificate Details': 'تفاصيل شهادة الدورة',
'Course Certificate updated': 'تم تحديث شهادة الدورة',
'Course Certificates': 'شهادات الدورات',
'Course deleted': 'تم حذف المقرر',
'Course Details': 'تفاصيل الدورة',
'Course updated': 'تم تحديث المقرر',
'Courses Attended': 'دورات تم حضورها',
'Create': 'إضافة',
'Create a new Group': 'إنشاء مجموعة جديدة',
'Create a new occupation type': 'إنشاء نوع وظيفة جديد',
'Create a new religion': 'إنشاء دين جديد',
'Create a new Team': 'إنشاء فريق جديد',
'Create a Person': 'إضافة شخص',
'Create Activity': 'إضافة نشاط',
'Create Activity Type': 'إنشاء نوع النشاط',
'Create Alternative Item': 'إنشاء عنصر بديل ',
'Create Assessment': 'اضافه تقييم',
'Create Asset': 'إضافة أصل جديد',
'Create Award': 'إنشاء جائزة',
'Create Award Type': 'إنشاء نوع جائزة ',
'Create Bed Type': 'إضافة نوع السرير',
'Create Beneficiary': 'إنشاء مستفيد',
'Create Beneficiary Type': 'إنشاء نوع المستفيد',
'Create Brand': 'اضافه علامه تجاريه جديده',
'Create Budget': 'اضافة ميزانية',
'Create Campaign': 'إنشاء حملة',
'Create Catalog': 'فهرس الدورة',
'Create Catalog Item': 'إنشاء عنصر كتالوج',
'Create Certificate': 'اضافة شهادة',
'Create Cholera Treatment Capability Information': 'أضف معلومات حول معالجة الكوليرا',
'Create Cluster': 'إنشاء كتلة',
'Create Coalition': 'إنشاء التحالف',
'Create Competency Rating': 'إنشاء تصنيف الكفاءات',
'Create Contact': 'إنشاء اتصال',
'Create Course': 'إضافة دورة أو درس',
'Create Dead Body Report': 'أضف تقريرا عن جثة',
'Create Department': 'اضافة قسم',
'Create Event Type': 'اضافة نوع النشاط',
'Create Facility': 'إضافة مرفق',
'Create Facility Type': 'إضافة نوع المرفق',
'Create Group': 'إضافة مجموعة',
'Create Group Member Role': 'إنشاء دور عضو المجموعة',
'Create Group Status': 'إنشاء حالة المجموعة',
'Create Hazard': 'إنشاء المخاطر',
'Create Hospital': 'إضافة مستشفى جديد',
'Create Identification Report': 'إضافة تقرير الهوية',
'Create Incident Report': 'اضافة تقرير لحادث',
'Create Incident Type': 'اضافة نوع الحادث',
'Create Indicator': 'إنشاء المؤشر',
'Create Item': 'إضافة عنصر جديد',
'Create Item Catalog': 'اضافه تصنيف جديد',
'Create Job': 'إنشاء الوظيفة',
'Create Job Title': 'اضافة عنوان العمل',
'Create Kit': 'إضافة أدوات جديدة',
'Create Location': 'إنشاء الموقع',
'Create Map Profile': 'اضافة تكوين خريطة',
'Create Marker': 'إضافة علامة',
'Create Milestone': 'إنشاء معلم',
'Create Mobile Impact Assessment': 'ايجاد تقييم للتأثير المتنقل',
'Create National Society': 'إنشاء جمعية وطنية',
'Create Occupation Type': 'إنشاء نوع الوظيفة ',
'Create Office': 'أضف مكتبا',
'Create Office Type': 'إنشاء نوع مكتب ',
'Create Organization': 'أضف منظمة',
'Create Organization Type': 'إنشاء نوع المنظمة',
'Create Partner Organization': 'انشاء منظمة شريكه',
'Create Policy or Strategy': 'إنشاء سياسة أو استراتيجية',
'Create Program': 'اضافة برنامج',
'Create Project': 'اضافه مشروع',
'Create Protection Response': 'انشاء (استجابة الحماية)',
'Create Religion': 'إنشاء الدين',
'Create Report': 'اضافة تقرير جديد',
'Create Request': 'إنشاء طلب',
'Create Resource': 'أضف موردا',
'Create Resource Type': 'تكوين نوع المورد',
'Create River': 'أضف نهرا',
'Create Role': 'إنشاء دور',
'Create Room': 'إضافة غرفة',
'Create Salary Grade': 'إنشاء درجة الراتب ',
'Create Sector': 'أضف قطاعا',
'Create Service': 'إنشاء خدمة',
'Create Shelter': 'أضف مأوى',
'Create Shelter Service': 'أضف خدمة مأوى',
'Create Skill': 'إضافة كفاءة',
'Create Skill Type': 'إنشاء نوع المهارة',
'Create Staff Level': 'إنشاء مستوى الموظفين',
'Create Staff Member': 'اضافه موظف',
'Create Staff or Volunteer': 'إنشاء الموظفين أو المتطوعين',
'Create Status': 'إنشاء حالة',
'Create Strategy': 'إنشاء استراتيجية',
'Create Subscription': 'إنشاء اشتراك',
'Create Supplier': 'اضافه مورد',
'Create Team': 'إنشاء فريق',
'Create Theme': 'إنشاء موضوع',
'Create Training Center': 'إنشاء مركز للتدريب',
'Create Training Event': 'اضافة نشاط تدريبي',
'Create User': 'إضافة مستخدم',
'Create Volunteer': 'أضف متطوعا',
'Create Volunteer Role': 'إنشاء دور المتطوعين',
'Create Warehouse': 'أضف مستودعا',
'Create Warehouse Type': 'إنشاء نوع مستودع ',
'Created By': 'انشأ من قبل',
'Created On': 'تم إنشاؤها على',
'Created on %s': 'تم إنشاؤها على %s',
'Created on %s by %s': 'تم إنشاؤها على %s بواسطة %s',
'Credential': 'ال<PASSWORD>',
'Credential added': 'تم اضافة الاعتماد',
'Credential deleted': 'تم حذف الاعتماد',
'Credential Details': 'تفاصيل الاعتماد',
'Credential updated': 'تم تحديث الاعتماد',
'Credentials': 'وثائق التفويض',
'Crime': 'جريمة',
'Criminal Record': 'سجل جنائي',
'Criteria': 'معيار',
'Critical Infrastructure': 'بنية تحتية حرجة',
'Crop Image': 'قص الصوره',
'Cumulative Status': 'الحالة التراكمية',
'curly': 'مجعد',
'Currency': 'عملة',
'Current': 'الحالية',
'current': | |
<filename>bgp_agent/platform/utils/linux_net.py
# Copyright 2021 Red Hat, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import ipaddress
import pyroute2
import random
import re
import sys
from pyroute2.netlink.rtnl import ndmsg
from socket import AF_INET
from socket import AF_INET6
from oslo_concurrency import processutils
from oslo_log import log as logging
from bgp_agent import constants
from bgp_agent.utils import utils
LOG = logging.getLogger(__name__)
def get_interfaces(filter_out=[]):
with pyroute2.NDB() as ndb:
return [iface.ifname for iface in ndb.interfaces
if iface.ifname not in filter_out]
def get_interface_index(nic):
with pyroute2.NDB() as ndb:
return ndb.interfaces[nic]['index']
def ensure_vrf(vrf_name, vrf_table):
with pyroute2.NDB() as ndb:
try:
with ndb.interfaces[vrf_name] as vrf:
if vrf['state'] != "up":
vrf['state'] = 'up'
except KeyError:
ndb.interfaces.create(
kind="vrf", ifname=vrf_name, vrf_table=int(vrf_table)).set(
'state', 'up').commit()
def ensure_bridge(bridge_name):
with pyroute2.NDB() as ndb:
try:
with ndb.interfaces[bridge_name] as bridge:
if bridge['state'] != "up":
bridge['state'] = 'up'
except KeyError:
ndb.interfaces.create(
kind="bridge", ifname=bridge_name, br_stp_state=0).set(
'state', 'up').commit()
def ensure_vxlan(vxlan_name, vni, lo_ip):
with pyroute2.NDB() as ndb:
try:
with ndb.interfaces[vxlan_name] as vxlan:
if vxlan['state'] != "up":
vxlan['state'] = 'up'
except KeyError:
# FIXME: Perhaps we need to set neigh_suppress on
ndb.interfaces.create(
kind="vxlan", ifname=vxlan_name, vxlan_id=int(vni),
vxlan_port=4789, vxlan_local=lo_ip, vxlan_learning=False).set(
'state', 'up').commit()
def set_master_for_device(device, master):
with pyroute2.NDB() as ndb:
# Check if already associated to the master, and associate it if not
if (ndb.interfaces[device].get('master') !=
ndb.interfaces[master]['index']):
with ndb.interfaces[device] as iface:
iface.set('master', ndb.interfaces[master]['index'])
def ensure_dummy_device(device):
with pyroute2.NDB() as ndb:
try:
with ndb.interfaces[device] as iface:
if iface['state'] != "up":
iface['state'] = 'up'
except KeyError:
ndb.interfaces.create(
kind="dummy", ifname=device).set('state', 'up').commit()
def ensure_ovn_device(ovn_ifname, vrf_name):
ensure_dummy_device(ovn_ifname)
set_master_for_device(ovn_ifname, vrf_name)
def delete_device(device):
try:
with pyroute2.NDB() as ndb:
ndb.interfaces[device].remove().commit()
except KeyError:
LOG.debug("Interfaces {} already deleted.".format(device))
def ensure_routing_table_for_bridge(ovn_routing_tables, bridge):
# check a routing table with the bridge name exists on
# /etc/iproute2/rt_tables
regex = '^[0-9]*[\s]*{}$'.format(bridge)
matching_table = [line.replace('\t', ' ')
for line in open('/etc/iproute2/rt_tables')
if re.findall(regex, line)]
if matching_table:
table_info = matching_table[0].strip().split()
ovn_routing_tables[table_info[1]] = int(table_info[0])
LOG.debug("Found routing table for {} with: {}".format(bridge,
table_info))
# if not configured, add random number for the table
else:
LOG.debug(("Routing table for bridge {} not configured "
"at /etc/iproute2/rt_tables").format(bridge))
regex = '^[0-9]+[\s]*'
existing_routes = [int(line.replace('\t', ' ').split(' ')[0])
for line in open('/etc/iproute2/rt_tables')
if re.findall(regex, line)]
# pick a number between 1 and 252
try:
table_number = random.choice(
[x for x in range(1, 253) if x not in existing_routes])
except IndexError:
LOG.error(("No more routing tables available for bridge {} "
"at /etc/iproute2/rt_tables").format(bridge))
sys.exit()
with open('/etc/iproute2/rt_tables', 'a') as rt_tables:
rt_tables.write('{} {}\n'.format(table_number, bridge))
ovn_routing_tables[bridge] = int(table_number)
LOG.debug("Added routing table for {} with number: {}".format(bridge,
table_number))
# add default route on that table if it does not exist
extra_routes = []
with pyroute2.NDB() as ndb:
table_route_dsts = set([r.dst for r in ndb.routes.summary().filter(
table=ovn_routing_tables[bridge])])
if not table_route_dsts:
ndb.routes.create(dst='default',
oif=ndb.interfaces[bridge]['index'],
table=ovn_routing_tables[bridge],
scope=253,
proto=3).commit()
ndb.routes.create(dst='default',
oif=ndb.interfaces[bridge]['index'],
table=ovn_routing_tables[bridge],
family=AF_INET6,
proto=3).commit()
else:
route_missing = True
route6_missing = True
for dst in table_route_dsts:
if not dst: # default route
try:
route = ndb.routes[
{'table': ovn_routing_tables[bridge],
'dst': '',
'family': AF_INET}]
if (ndb.interfaces[{'index': route['oif']}]['ifname']
== bridge):
route_missing = False
else:
extra_routes.append(route)
except KeyError:
pass # no ipv4 default rule
try:
route_6 = ndb.routes[
{'table': ovn_routing_tables[bridge],
'dst': '',
'family': AF_INET6}]
if (ndb.interfaces[{'index': route_6['oif']}]['ifname']
== bridge):
route6_missing = False
else:
extra_routes.append(route_6)
except KeyError:
pass # no ipv6 default rule
else:
extra_routes.append(
ndb.routes[{'table': ovn_routing_tables[bridge],
'dst': dst}]
)
if route_missing:
ndb.routes.create(dst='default',
oif=ndb.interfaces[bridge]['index'],
table=ovn_routing_tables[bridge],
scope=253,
proto=3).commit()
if route6_missing:
ndb.routes.create(dst='default',
oif=ndb.interfaces[bridge]['index'],
table=ovn_routing_tables[bridge],
family=AF_INET6,
proto=3).commit()
return extra_routes
def ensure_vlan_device_for_network(bridge, vlan_tag):
vlan_device_name = '{}.{}'.format(bridge, vlan_tag)
with pyroute2.NDB() as ndb:
try:
with ndb.interfaces[vlan_device_name] as iface:
if iface['state'] != "up":
iface['state'] = 'up'
except KeyError:
ndb.interfaces.create(
kind="vlan", ifname=vlan_device_name, vlan_id=vlan_tag,
link=ndb.interfaces[bridge]['index']).set('state',
'up').commit()
ipv4_flag = "net.ipv4.conf.{}/{}.proxy_arp".format(bridge, vlan_tag)
_set_kernel_flag(ipv4_flag, 1)
ipv6_flag = "net.ipv6.conf.{}/{}.proxy_ndp".format(bridge, vlan_tag)
_set_kernel_flag(ipv6_flag, 1)
def delete_vlan_device_for_network(bridge, vlan_tag):
vlan_device_name = '{}.{}'.format(bridge, vlan_tag)
delete_device(vlan_device_name)
def _set_kernel_flag(flag, value):
command = ["sysctl", "-w", "{}={}".format(flag, value)]
try:
return processutils.execute(*command, run_as_root=True)
except Exception as e:
LOG.error("Unable to execute {}. Exception: {}".format(
command, e))
raise
def get_exposed_ips(nic):
exposed_ips = []
with pyroute2.NDB() as ndb:
exposed_ips = [ip.address
for ip in ndb.interfaces[nic].ipaddr.summary()
if ip.prefixlen == 32 or ip.prefixlen == 128]
return exposed_ips
def get_nic_ip(nic, ip_version):
prefix = 32
if ip_version == constants.IP_VERSION_6:
prefix = 128
exposed_ips = []
with pyroute2.NDB() as ndb:
exposed_ips = [ip.address
for ip in ndb.interfaces[nic].ipaddr.summary().filter(
prefixlen=prefix)]
return exposed_ips
def get_exposed_ips_on_network(nic, network):
exposed_ips = []
with pyroute2.NDB() as ndb:
exposed_ips = [ip.address
for ip in ndb.interfaces[nic].ipaddr.summary()
if ((ip.prefixlen == 32 or ip.prefixlen == 128) and
ipaddress.ip_address(ip.address) in network)]
return exposed_ips
def get_ovn_ip_rules(routing_table):
# get the rules pointing to ovn bridges
ovn_ip_rules = {}
with pyroute2.NDB() as ndb:
rules_info = [(rule.table,
"{}/{}".format(rule.dst, rule.dst_len),
rule.family) for rule in ndb.rules.dump()
if rule.table in routing_table]
for table, dst, family in rules_info:
ovn_ip_rules[dst] = {'table': table, 'family': family}
return ovn_ip_rules
def delete_exposed_ips(ips, nic):
with pyroute2.NDB() as ndb:
for ip in ips:
address = '{}/32'.format(ip)
if utils.get_ip_version(ip) == constants.IP_VERSION_6:
address = '{}/128'.format(ip)
try:
ndb.interfaces[nic].ipaddr[address].remove().commit()
except KeyError:
LOG.debug("IP address {} already removed from nic {}.".format(
ip, nic))
def delete_ip_rules(ip_rules):
with pyroute2.NDB() as ndb:
for rule_ip, rule_info in ip_rules.items():
rule = {'dst': rule_ip.split("/")[0],
'dst_len': rule_ip.split("/")[1],
'table': rule_info['table'],
'family': rule_info['family']}
try:
with ndb.rules[rule] as r:
r.remove()
except KeyError:
LOG.debug("Rule {} already deleted".format(rule))
except pyroute2.netlink.exceptions.NetlinkError:
# FIXME: There is a issue with NDB and ip rules deletion:
# https://github.com/svinota/pyroute2/issues/771
LOG.debug("This should not happen, skipping")
def delete_bridge_ip_routes(routing_tables, routing_tables_routes,
extra_routes):
with pyroute2.NDB() as ndb:
for bridge, routes_info in routing_tables_routes.items():
if not extra_routes[bridge]:
continue
for route_info in routes_info:
oif = ndb.interfaces[bridge]['index']
if route_info['vlan']:
vlan_device_name = '{}.{}'.format(bridge,
route_info['vlan'])
oif = ndb.interfaces[vlan_device_name]['index']
if 'gateway' in route_info['route'].keys(): # subnet route
possible_matchings = [
r for r in extra_routes[bridge]
if (r['dst'] == route_info['route']['dst'] and
r['dst_len'] == route_info['route']['dst_len'] and
r['gateway'] == route_info['route']['gateway'])]
else: # cr-lrp
possible_matchings = [
r for r in extra_routes[bridge]
if (r['dst'] == route_info['route']['dst'] and
r['dst_len'] == route_info['route']['dst_len'] and
r['oif'] == oif)]
for r in possible_matchings:
extra_routes[bridge].remove(r)
for bridge, routes in extra_routes.items():
for route in routes:
r_info = {'dst': route['dst'],
'dst_len': route['dst_len'],
'family': route['family'],
'oif': route['oif'],
'gateway': route['gateway'],
'table': routing_tables[bridge]}
try:
with ndb.routes[r_info] as r:
r.remove()
except KeyError:
LOG.debug("Route already deleted: {}".format(route))
def delete_routes_from_table(table):
with pyroute2.NDB() as ndb:
# FIXME: problem in pyroute2 removing routes with local (254) scope
table_routes = [r for r in ndb.routes.dump().filter(table=table)
if r.scope != 254 and r.proto != 186]
for route in table_routes:
try:
with ndb.routes[route] as r:
r.remove()
except KeyError:
LOG.debug("Route already deleted: {}".format(route))
def get_routes_on_tables(table_ids):
with pyroute2.NDB() as ndb:
# NOTE: skip bgp routes (proto 186)
return [r for r in ndb.routes.dump()
if r.table in table_ids and r.dst != '' and r.proto != 186]
def delete_ip_routes(routes):
with pyroute2.NDB() as ndb:
for route in routes:
r_info = {'dst': route['dst'],
'dst_len': route['dst_len'],
'family': route['family'],
'oif': route['oif'],
'gateway': route['gateway'],
'table': route['table']}
try:
with ndb.routes[r_info] as r:
r.remove()
except KeyError:
LOG.debug("Route already deleted: {}".format(route))
def add_ndp_proxy(ip, dev, vlan=None):
# FIXME(ltomasbo): This should use pyroute instead but I didn't find
# out how
net_ip = str(ipaddress.IPv6Network(ip, strict=False).network_address)
dev_name = dev
if vlan:
dev_name = "{}.{}".format(dev, vlan)
command = ["ip", "-6", "nei", "add", "proxy", net_ip, "dev", dev_name]
try:
return processutils.execute(*command, run_as_root=True)
except Exception as e:
LOG.error("Unable to execute {}. Exception: {}".format(
command, e))
raise
def del_ndp_proxy(ip, dev, vlan=None):
# FIXME(ltomasbo): This should use pyroute instead but I didn't find
# out how
net_ip = str(ipaddress.IPv6Network(ip, strict=False).network_address)
dev_name = dev
if vlan:
dev_name = "{}.{}".format(dev, vlan)
command = ["ip", "-6", "nei", "del", "proxy", net_ip, "dev", dev_name]
try:
return processutils.execute(*command, run_as_root=True)
except Exception as e:
if "No such file or directory" in e.stderr:
# Already deleted
return
LOG.error("Unable to execute {}. Exception: {}".format(
command, e))
raise
def add_ips_to_dev(nic, ips, clear_local_route_at_table=False):
with pyroute2.NDB() as ndb:
try:
with ndb.interfaces[nic] as iface:
for ip in ips:
address = '{}/32'.format(ip)
if utils.get_ip_version(ip) == constants.IP_VERSION_6:
address = '{}/128'.format(ip)
iface.add_ip(address)
except KeyError:
# NDB raises KeyError: 'object exists'
# if the ip is already added
pass
if clear_local_route_at_table:
with pyroute2.NDB() as ndb:
for ip in ips:
route = {'table': clear_local_route_at_table,
'proto': | |
<reponame>ruofeidu/DuWebKit
"""Art defines a single art.
This class allows the user to format an art.
"""
import re
import math
import warnings
import os.path
from markdown import markdown
from scripts.app import App
from scripts.authors import Authors
from scripts.utils.constants import PUNCTUATION, FILE_LOWRES_MAXSIZE, LINK_SEPARATOR, LINK_COMMA
from scripts.utils.utils import Utils
from scripts.utils.dumark import DuMark
from scripts.utils.regex import Regex
from scripts.utils.dir import Dir
# Capitalizes a single word w.
def capitalize_single(w):
return w[0].upper() + w[1:]
# Capitalizes into APA format.
def capitalize_apa(s, spliter=' '):
LOWER_CASES = {
'a', 'an', 'the', 'to', 'on', 'in', 'of', 'at', 'by', 'for', 'or', 'and',
'vs.', 'iOS'
}
s = s.strip(',.- ')
# Reverse wrong order for IEEE proceedings.
# if comma is found and last word is 'on'
if s.rfind(',') > 0 and s[-3:].lower() == ' on':
p = s.rfind(',')
s = s[p + 2:] + s[:p]
# Split the words and capitalize with filters
words = s.split(spliter)
capitalized_words = []
start = True
for word in words:
if len(word) == 0:
continue
if not start and word.lower() in LOWER_CASES:
capitalized_words.append(word.lower())
else:
capitalized_words.append(capitalize_single(word))
start = word[-1] in '.:'
s = spliter.join(capitalized_words)
return s if spliter == '-' else capitalize_apa(s, '-')
# Capitalizes a string.
def capitalize_all(s):
return ' '.join(list(map(capitalize_single, s.split(' '))))
class Art:
__slots__ = ('_data')
_header = []
_bib_items = [
'b_title', 'b_author', 'journal', 'booktitle', 'school', 'institution',
'note', 'year', 'volume', 'number', 'editor', 'location', 'publisher',
'b_month', 'day', 'b_pages', 'b_numpages', 'series', 'doi'
]
_type_map = {
'conf': 'inproceedings',
'poster': 'inproceedings',
'lbw': 'inproceedings',
'poster': 'inproceedings',
'workshop': 'inproceedings',
'demo': 'inproceedings',
'journal': 'article',
'phd': 'phdthesis',
'ms': 'masterthesis',
'bs': 'bachelorthesis',
'patent': 'misc',
'arxiv': 'misc',
'report': 'techreport',
}
_month_map = [
'',
'Jan.',
'Feb.',
'Mar.',
'Apr.',
'May',
'Jun.',
'Jul.',
'Aug.',
'Sep.',
'Oct.',
'Nov.',
'Dec.',
]
def __init__(self, row):
"""Iniializes the data and defaul fields."""
self._data = {}
b = self._data
for i, label in enumerate(Art.get_header()):
b[label] = row[i] if i < len(row) else ''
self._create_authors()
self._create_title()
self._create_bib_id()
self._create_bib_date()
# Reformats proceeding or journal names.
# self._create_bib_type()
b['score'] = int(b['score'])
b['published'] = (b['published'] == '1')
b['visible'] = (b['visible'] == '1')
def get_youtube_url(self):
return 'https://youtu.be/%s' % self._data['youtube'] if self._data[
'youtube'] else ''
def get_vimeo_url(self):
return 'https://vimeo.com/%s' % self._data['vimeo'] if self._data[
'vimeo'] else ''
def get_slideshare_url(self):
return 'https://www.slideshare.net/duruofei/%s' % (
self._data['slideshare']) if self._data['slideshare'] else ''
def get_gslides_url(self):
gslides = self._data['gslides']
if gslides:
if gslides[:4] == 'http':
return gslides
else:
return 'https://docs.google.com/presentation/d/%s'
else:
return ''
def get_doi(self):
return self._data['doi']
def get_doi_markdown(self):
return DuMark.get_url('https://doi.org/%s' % self.get_doi(), 'doi')
def get_doi_html(self):
return Utils.remove_p(markdown(self.get_doi_markdown()))
def get_cite_html(self):
return '<a class="cite" href="%scites/%s.html">cite</a>' % (
App.root, self._data['bib'])
def export_cite_html(self):
html = ''
filename = os.path.join(Dir.cites, "%s.html" % self._data['bib'])
with open(filename, 'w', encoding='utf8') as f:
f.write(html)
def get_bibtex(self):
""" Returns BibTeX of this art.
References:
http://www.bibtex.org/Format
https://verbosus.com/bibtex-style-examples.html
"""
b = self._data
TAB, LB = Utils.get_tab(), Utils.get_line_break()
s = '@%s{%s,%s' % (b['b_type'], b['bib'], LB)
for label in Art.get_bib_items():
if label in b and b[label]:
key = label
if label[:2] == 'b_':
key = label[2:]
s += '%s%s = {%s},%s' % (TAB, key, b[label], LB)
s += '}%s' % LB
return s
def get_apa(self):
"""Returns APA style citation.
Reference:
TODO: https://owl.purdue.edu/owl/research_and_citation/apa_style/apa_formatting_and_style_guide/reference_list_author_authors.html
"""
b = self._data
TAB, LB = Utils.get_tab(), Utils.get_line_break()
s = self.get_authors().get_apa()
s += ' (%s).' % b['year']
s += LB
s += b['title'] + '.'
s += LB
s += 'In %s, ' % self.get_book()
# Appends volume and number for journal articles.
if b['volume']:
s += b['volume']
if b['number']:
s += '(%s)' % b['number']
s += ', '
# Appends pages.
if 'b_pages' in b:
s += b['b_pages'].replace('--', '-')
elif 'b_numpages' in b:
s += 'pp. ' + b['b_pages']
s += '.'
return s
def get_mla(self):
"""Returns MLA style citation."""
b = self._data
TAB, LB = Utils.get_tab(), Utils.get_line_break()
s = self.get_authors().get_mla()
s += LB
s += '"%s".' % b['title']
s += LB
s += self.get_book() + ', '
if b['volume']:
s += b['volume']
if b['number']:
s += '(%s)' % b['number']
s += ', '
if 'b_pages' in b:
s += b['b_pages'].replace('--', '-')
elif 'b_numpages' in b:
s += 'pp. %s' % b['b_pages']
s += '. %s.' % b['year']
return s
def get_chicago(self):
"""Returns MLA style citation."""
b = self._data
TAB, LB = Utils.get_tab(), Utils.get_line_break()
s = self.get_authors().get_mla()
s += LB
s += '"%s".' % b['title']
s += LB
s += self.get_book() + ', '
if b['volume']:
s += b['volume']
if b['number']:
s += '(%s)' % b['number']
s += ', '
if 'b_pages' in b:
s += b['b_pages'].replace('--', '-')
elif 'b_numpages' in b:
s += 'pp. %s' % b['b_pages']
s += '. %s.' % b['year']
return s
def get_harvard(self):
"""Returns Harvard style citation."""
b = self._data
TAB, LB = Utils.get_tab(), Utils.get_line_break()
s = self.get_authors().get_mla()
s += LB
s += '"%s".' % b['title']
s += LB
s += self.get_book() + ', '
if b['volume']:
s += b['volume']
if b['number']:
s += '(%s)' % b['number']
s += ', '
if 'b_pages' in b:
s += b['b_pages'].replace('--', '-')
elif 'b_numpages' in b:
s += 'pp. %s' % b['b_pages']
s += '. %s.' % b['year']
return s
def get_vancouver(self):
"""Returns Vancouver style citation."""
b = self._data
TAB, LB = Utils.get_tab(), Utils.get_line_break()
s = self.get_authors().get_mla()
s += LB
s += '"%s".' % b['title']
s += LB
s += self.get_book() + ', '
if b['volume']:
s += b['volume']
if b['number']:
s += '(%s)' % b['number']
s += ', '
if 'b_pages' in b:
s += b['b_pages'].replace('--', '-')
elif 'b_numpages' in b:
s += 'pp. %s' % b['b_pages']
s += '. %s.' % b['year']
return s
def get_resume(self):
b = self._data
s = ''
s = b['authors'].get_resume()
s += '. {\\it ' + b['title'] + '}. '
if 'book' in b and b['book']:
s += b['book'] + ' '
else:
return ''
s += b['year']
return s
def get_bib_id(self):
return self._data['b_id']
def get_authors(self):
"""Returns the full Authors class."""
return self._data['authors']
def get_filename(self):
"""Returns the PDF file name."""
b = self._data
return '%s.jpg' % (b['bib'])
def _create_authors(self):
"""Creates Authors into the `authors` field.
case 1: <NAME>, <NAME>. and <NAME> Froehlich, <NAME>.
case 2: <NAME>, <NAME>, <NAME>, and <NAME>
case 3: <NAME> and <NAME> and <NAME>
names = re.split(',|;|and', authors) will not work for all cases
"""
b = self._data
authors = b['authors']
names = authors.split('and')
spliter_and = True
for name in names:
if name.count(',') > 1:
spliter_and = False
if not spliter_and:
names = authors.split(',')
# Removes ' and ' from names.
names = [y for x in names for y in x.split('and ')]
# Removes leading and trailing spaces / and.
map(str.strip, names)
# Removes empty name.
names = list(filter(None, names))
b['authors'] = Authors(names)
b['b_author'] = b['authors'].get_bib()
def _create_bib_id(self):
"""Computes the bib ID using format Lastname2000Title format."""
b = self._data
b['b_id'] = b['authors'].first().get_last() + b['year'] + b['title_first']
if b['b_id'] != b['bib']:
print('* ', b['b_id'], 'and', b['bib'], ' do not match')
def _create_title(self):
"""Reformats the title."""
b = self._data
b['title'] = capitalize_apa(b['title'])
b['b_title'] = '{%s}' % b['title'].replace('° ', '\degree~')
if b['title'].count(' '):
word = b['title'][:b['title'].find(' ')]
for p in PUNCTUATION:
if word.count(p):
word = word[:word.find(p)]
b['title_first'] = capitalize_all(word)
else:
b['title_first'] = b['title'].strip(PUNCTUATION)
b['title_file'] = ''.join(
re.split(' |\.|\,|\!|\?',
capitalize_all(b['title']).replace(':', '-').replace('°', '')))
def _create_bib_type(self):
"""Reformats the bibtype."""
self._data['b_type'] = self._type_map[self._data['type']]
def debug_pdf(self):
"""Outputs whether the corresponding PDF and low-res version exist."""
if 'debugged_pdf' in self._data:
return True
self._data['debugged_pdf'] = True
rawname = self.get_filename()
filename = 'builds/papers/%s.pdf' % rawname
lowres = 'builds/papers/%s_lowres.pdf' % rawname
supp = 'builds/papers/%s_supp.pdf' % rawname
if not os.path.isfile(filename):
print('%s does not exist.' % filename)
return False
if os.path.getsize(filename) > FILE_LOWRES_MAXSIZE:
if not os.path.isfile(lowres):
print('%s does not have low-res version.' % filename)
return False
else:
self._data['lowres'] = True
if os.path.isfile(supp):
self._data['supp'] = '/papers/%s_supp.pdf' % rawname
return True
def _create_bib_date(self):
"""Reformat dates."""
if 'month' in self._data and self._data['month']:
self._data['month'] = int(self._data['month'])
self._data['b_month'] = self._month_map[self._data['month']]
def to_dict(self):
return self._data
def is_published(self):
return self._data['published']
def is_visible(self):
return self._data['visible']
@staticmethod
def get_bib_items():
return Art._bib_items
@staticmethod
def set_header(header):
Art._header = header
@staticmethod
def get_header():
return Art._header
def get_title_markdown(self):
return DuMark.get_paper(self.get_filename(), self._data['title'])
def get_title_html(self):
return Utils.remove_p(markdown(self.get_title_markdown()))
def get_pdf_markdown(self):
return DuMark.get_paper(self.get_filename(), 'pdf', self._data['title'])
def | |
# -*- coding: utf-8 -*-
"""
Created on Sun Jun 30 14:36:25 2019
@author: HASEE
Chapter 02 end to end machine learning project
"""
#################################### Set UP ###################################
import os
os.chdir(os.getcwd())
import numpy as np
import pandas as pd
# set the random seed
np.random.seed(42)
# to plot pretty figure, set the figure params
import matplotlib.pyplot as plt
plt.rcParams['font.sans-serif']=['SimHei']
plt.rcParams['axes.unicode_minus']=False
import matplotlib as mpl
mpl.rc("axes",labelsize=14)
mpl.rc("xtick",labelsize=12)
mpl.rc("ytick",labelsize=12)
# set the figure location
PROJECT_ROOT_DIR = "."
CHAPTER_ID = "end_to_end_project"
IMAGES_PATH = os.path.join(PROJECT_ROOT_DIR, "images", CHAPTER_ID)
# define the function that save the figure
def save_fig(fig_id, tight_layout=True, fig_extension="png", resolution=300):
path = os.path.join(IMAGES_PATH, fig_id + "." + fig_extension)
print("Saving figure", fig_id)
if tight_layout:
plt.tight_layout()
plt.savefig(path, format=fig_extension, dpi=resolution)
# Ignore useless warnings (see SciPy issue #5998)
import warnings
warnings.filterwarnings(action="ignore", message="^internal gelsd")
# sklearn model
#from sklearn.model_selection import train_test_split
from sklearn.model_selection import StratifiedShuffleSplit
from sklearn.externals import joblib
import time
################################## Get data ###################################
import os
import tarfile
from six.moves import urllib
DOWNLOAD_ROOT = "https://raw.githubusercontent.com/ageron/handson-ml/master/"
HOUSING_PATH = os.path.join("datasets", "housing")
HOUSING_URL = DOWNLOAD_ROOT + "datasets/housing/housing.tgz"
#download data from internet and decompress it to csv file
def fetch_housing_data(housing_url=HOUSING_URL, housing_path=HOUSING_PATH):
if not os.path.isdir(housing_path):
os.makedirs(housing_path)
tgz_path = os.path.join(housing_path, "housing.tgz")
urllib.request.urlretrieve(housing_url, tgz_path)
housing_tgz = tarfile.open(tgz_path)
housing_tgz.extractall(path=housing_path)
housing_tgz.close()
#load the housing data
def load_housing_data(housing_path=HOUSING_PATH):
if not os.path.exists(housing_path):
fetch_housing_data()
# load local file
csv_path=os.path.join(housing_path,"housing.csv")
return pd.read_csv(csv_path)
housing=load_housing_data()
print(">> Load housing data sucessfully!\n")
## check out the data infomation and structure
#print("First 5 lines of data:\n"+"-"*40+"\n",housing.head()) # show the first 5 lines of data
#print("Data info:\n"+"-"*40+"\n")
#print(housing.info()) # show the data infomation, such as type and missing number
#print("Data description:\n"+"-"*40+"\n",housing.describe()) # show the data structure
#print("Ocean_proximity value_counts:\n"+"-"*40+"\n",housing.ocean_proximity.value_counts()) # show the ocean_proximity distribution
#
######################### plot the data distributon ############################
##plt.figure()
#housing.hist(bins=50,figsize=(20,15))
#save_fig("attribute_histogram_plots")
#
################### Split the data to train_data and test data #################
############## split_train_test_01
##def split_train_test(data,test_ratio=0.2,seed=42,random_=True):
## if random_==True:
## np.random.seed(seed)
## # shuffle the data
## shuffled_indices=np.random.permutation(len(data))
## test_set_size=int(len(data)*test_ratio)
## test_indices=shuffled_indices[:test_set_size]
## train_indices=shuffled_indices[test_set_size:]
## return data.iloc[train_indices],data.iloc[test_indices]
##
##train_set, test_set = split_train_test(housing)
##print("Random: ",len(train_set), "train +", len(test_set), "test")
##
############### split_train_test_02
### to make sure that works well when new data loaded
##from zlib import crc32
##
### to create a array that mark whether the index should be added to test data
##def test_set_check(identifier,test_ratio):
## return crc32(np.int64(identifier)) & 0xffffffff < test_ratio * 2**32
##
##def split_train_test_by_id(data,test_ratio,id_column):
## ids=data[id_column]
## in_test_set=ids.apply(lambda id_: test_set_check(id_, test_ratio))
## return data.loc[~in_test_set],data.loc[in_test_set]
##
### by rows
##housing_with_id = housing.reset_index() # adds an `index` column
##train_set, test_set = split_train_test_by_id(housing_with_id, 0.2, "index")
##print("By rows: ",len(train_set), "train +", len(test_set), "test")
##
### by location
##housing_with_id["id"] = housing["longitude"] * 1000 + housing["latitude"]
##train_set, test_set = split_train_test_by_id(housing_with_id, 0.2, "id")
##print("By location: ",len(train_set), "train +", len(test_set), "test")
#
############## split_train_test_03
#
#train_set, test_set = train_test_split(housing, test_size=0.2, random_state=42)
#print("By sklearn train_test_split: ",len(train_set), "train +", len(test_set), "test")
#
############ Stratified Sampling
##plot the median income
##housing["median_income"].hist()
##pd.cut()
housing["income_cat"] = pd.cut(housing["median_income"],
bins=[0., 1.5, 3.0, 4.5, 6., np.inf],
labels=[1, 2, 3, 4, 5])
# bar plot
#housing["income_cat"].value_counts().sort_index().plot(kind="bar")
#plt.xticks(rotation=0)
split = StratifiedShuffleSplit(n_splits=1, test_size=0.2, random_state=42)
for train_index, test_index in split.split(housing, housing["income_cat"]):
strat_train_set = housing.loc[train_index]
strat_test_set = housing.loc[test_index]
print("By sklearn StratifiedShuffleSplit: ",len(strat_train_set), "train +", len(strat_test_set), "test")
#print(strat_test_set["income_cat"].value_counts() / len(strat_test_set))
#print(housing["income_cat"].value_counts() / len(housing))
################ compare the error between the Stratified and random
#def income_cat_proportions(data):
# return data["income_cat"].value_counts() / len(data)
#
#train_set, test_set = train_test_split(housing, test_size=0.2, random_state=42)
#
#compare_props = pd.DataFrame({
# "Overall": income_cat_proportions(housing),
# "Random": income_cat_proportions(test_set),
# "Stratified": income_cat_proportions(strat_test_set),
#}).sort_index()
#compare_props["Rand. %error"] = 100 * compare_props["Random"] / compare_props["Overall"] - 100
#compare_props["Strat. %error"] = 100 * compare_props["Stratified"] / compare_props["Overall"] - 100
#print(compare_props)
#delete the extra column
try:
for set_ in (strat_train_set, strat_test_set):
set_.drop("income_cat", axis=1, inplace=True)
except:
pass
############## Discover and visualize the data to gain insights ###############
housing=strat_train_set.copy()
#housing.plot(kind="scatter",x="longitude",y="latitude",alpha=0.1)
#
## set the scatter size and colors
#housing.plot(kind="scatter",x="longitude",y="latitude",alpha=0.4,
# s=housing.population/1000,label="population",
# c="median_house_value",cmap=plt.get_cmap("jet"),colorbar=True)
#plt.legend()
# add map png
#import matplotlib.image as mpimg
#california_img=mpimg.imread(PROJECT_ROOT_DIR + '/images/end_to_end_project/california.png')
#ax = housing.plot(kind="scatter", x="longitude", y="latitude", figsize=(10,7),
# s=housing['population']/100, label="Population",
# c="median_house_value", cmap=plt.get_cmap("jet"),
# colorbar=False, alpha=0.4,
# )
#plt.imshow(california_img, extent=[-124.55, -113.80, 32.45, 42.05], alpha=0.5,
# cmap=plt.get_cmap("jet"))
#plt.ylabel("Latitude", fontsize=14)
#plt.xlabel("Longitude", fontsize=14)
#
#prices = housing["median_house_value"]
#tick_values = np.linspace(prices.min(), prices.max(), 11)
#cbar = plt.colorbar()
#cbar.ax.set_yticklabels(["$%dk"%(round(v/1000)) for v in tick_values], fontsize=14)
#cbar.set_label('Median House Value', fontsize=16)
#
#plt.legend(fontsize=16)
#save_fig("california_housing_prices_plot")
#
## find correction
#corr_matrix=housing.corr()
#print("Correction:\n"+"-"*40+"\n",corr_matrix["median_house_value"].sort_values(ascending=False))
#
## scatter matrix
#print(">> Plotting the scatter matrix of 4 variables...\n")
#from pandas.plotting import scatter_matrix
#
#attributes=["median_house_value","median_income","total_rooms","housing_median_age"]
#scatter_matrix(housing[attributes],figsize=(12,8))
#save_fig("scatter_matrix_plot")
#
## plot scatter of median_house_value and median_income
#housing.plot(kind="scatter", x="median_income", y="median_house_value",
# alpha=0.1)
#plt.axis([0, 16, 0, 550000])
#save_fig("income_vs_house_value_scatterplot")
#
## create different variable
#print(">> Create some new variables...")
#housing["rooms_per_household"] = housing["total_rooms"]/housing["households"]
#housing["bedrooms_per_room"] = housing["total_bedrooms"]/housing["total_rooms"]
#housing["population_per_household"]=housing["population"]/housing["households"]
#
## check out the new correction
#corr_matrix=housing.corr()
#print("New Correction:\n"+"-"*40+"\n",corr_matrix["median_house_value"].sort_values(ascending=False))
# Prepare the data for Machine Learning algorithms
housing=strat_train_set.drop("median_house_value",axis=1)
housing_label=strat_train_set["median_house_value"].copy()
# clean the missing data
#print(">> Replace the missing data with median number...\n")
try:
from sklearn.impute import SimpleImputer # Scikit-Learn 0.20+
except ImportError:
from sklearn.preprocessing import Imputer as SimpleImputer
#imputer=SimpleImputer(strategy="median")
## imputer can only caculate the median value on numeric data, so we should drop the text label
housing_num=housing.drop("ocean_proximity",axis=1)
#imputer.fit(housing_num)
## 填补缺失值
#X=imputer.transform(housing_num)
#housing_tr=pd.DataFrame(X,columns=housing_num.columns)
# transform the character data
#print(">> Transform the Category to Number...\n")
#try:
# from sklearn.preprocessing import OrdinalEncoder
#except ImportError:
# from future_encoders import OrdinalEncoder # Scikit-Learn < 0.20
#housing_cat = housing[['ocean_proximity']]
#print("Raw label(first 10 lines):\n"+"-"*40+"\n",housing_cat.head(10))
#ordinal_encoder = OrdinalEncoder()
#housing_cat_encoded = ordinal_encoder.fit_transform(housing_cat)
#print("Transformed label(first 10 lines):\n"+"-"*40+"\n",housing_cat_encoded[:10])
#print("Transformed Rules:\n"+"-"*40+"\n",ordinal_encoder.categories_)
#
## Create OneHotEncoder
#print(">> Create OneHotEncoder...\n")
try:
#from sklearn.preprocessing import OrdinalEncoder # just to raise an ImportError if Scikit-Learn < 0.20
from sklearn.preprocessing import OneHotEncoder
except ImportError:
from future_encoders import OneHotEncoder # Scikit-Learn < 0.20
#cat_encoder = OneHotEncoder()
#housing_cat_1hot = cat_encoder.fit_transform(housing_cat)
#print("One hot encoder:\n"+"-"*40+"\n",housing_cat_1hot.toarray())
# add extra feature
# get the right column indices: safer than hard-coding indices 3, 4, 5, 6
#print(">> Add extra feature...\n")
rooms_ix, bedrooms_ix, population_ix, household_ix = [
list(housing.columns).index(col)
for col in ("total_rooms", "total_bedrooms", "population", "households")]
from sklearn.preprocessing import FunctionTransformer
def add_extra_features(X, add_bedrooms_per_room=True):
rooms_per_household = X[:, rooms_ix] / X[:, household_ix]
population_per_household = X[:, population_ix] / X[:, household_ix]
if add_bedrooms_per_room:
bedrooms_per_room = X[:, bedrooms_ix] / X[:, rooms_ix]
return np.c_[X, rooms_per_household, population_per_household,
bedrooms_per_room]
else:
return np.c_[X, rooms_per_household, population_per_household]
#attr_adder = FunctionTransformer(add_extra_features, validate=False,
# kw_args={"add_bedrooms_per_room": False})
#housing_extra_attribs = attr_adder.fit_transform(housing.values)
#housing_extra_attribs = pd.DataFrame(
# housing_extra_attribs,
# columns=list(housing.columns)+["rooms_per_household", "population_per_household"],
# index=housing.index)
#print("After adding extra features:\n"+"-"*40+"\n",housing_extra_attribs.head())
#
## Create a pipeline to prepare the data
#print(">> Create a pipeline to prepare the data...\n")
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import StandardScaler
try:
from sklearn.compose import ColumnTransformer
except ImportError:
from future_encoders import ColumnTransformer # Scikit-Learn < 0.20
# clean the numreric features
num_pipeline = Pipeline([
('imputer', SimpleImputer(strategy="median")),
('attribs_adder', FunctionTransformer(add_extra_features, validate=False)),
('std_scaler', StandardScaler()),
])
num_attribs = list(housing_num)
cat_attribs = ["ocean_proximity"]
full_pipeline = ColumnTransformer([
("num", num_pipeline, num_attribs),
("cat", OneHotEncoder(), cat_attribs),
])
housing_prepared = full_pipeline.fit_transform(housing)
print("\n>> prepare housing data sucessfully!\n")
#################################################################################################
###################################### Select and train a model ################################
#################################################################################################
def select_model(model='LR',housing_prepared=housing_prepared,housing_label=housing_label,load=True):
'''select the LinearRegression,DecisionTreeRegressor or RandomForestRegressor.'''
# save model
from sklearn.externals import joblib
# load the model if it exists
import time
time1=time.time()
if model=="LR":
from sklearn.linear_model import LinearRegression
time1=time.time()
model=LinearRegression()
model_name="LinearRegression"
elif model=="DT":
from sklearn.tree import DecisionTreeRegressor
model=DecisionTreeRegressor(random_state=42)
model_name="DecisionTreeRegressor"
elif model=="RF":
from sklearn.ensemble import RandomForestRegressor
model=RandomForestRegressor(n_estimators=10, random_state=42)
model_name="RandomForestRegressor"
elif model=="SVR":
from sklearn.svm import SVR
model = SVR(kernel="linear")
model_name="SVR"
else:
return None
if os.path.exists("model_set/%s.pkl"%model_name):
model=joblib.load("model_set/%s.pkl"%model_name)
print("\n>> Load < %s > model from the local sucessfully!\n"%model_name)
return model
# train the model
model.fit(housing_prepared,housing_label)
# caculate the RMSE
from sklearn.metrics import mean_squared_error
housing_predictions=model.predict(housing_prepared)
mse=mean_squared_error(housing_label,housing_predictions)
rmse=np.sqrt(mse)
time2=time.time()
print("%s trained sucessfully, use %.2fs, the rmse is %.6f."%(model_name,time2-time1,rmse))
with open("model_set/model_statistics.txt",'a+',encoding="utf-8") as f:
f.write("[ % s]"%time.ctime()+"%s trained sucessfully, use %.2fs, the rmse is %.6f."%(model_name,time2-time1,rmse))
# Fine-tune your model
from sklearn.model_selection import cross_val_score
print("\n>> %s Scores:\n"%model_name+"-"*40+"\n")
time1=time.time()
scores=cross_val_score(model,housing_prepared,housing_label,
scoring="neg_mean_squared_error",cv=10)
rmse_scores=np.sqrt(-scores)
time2=time.time()
# check out the final results
def display_scores(scores,time_=time2-time1):
print("scores:",scores)
print("Mean:",scores.mean())
print("Standard deviation:",scores.std())
print("time used: %.2fs"%time_)
with open("model_set/model_statistics.txt",'a+',encoding="utf-8") as f:
f.write("scores: {}\n".format(scores))
f.write("Mean: {}\n".format(scores.mean()))
f.write("Standard deviation: {}\n".format(scores.std()))
f.write("time used: %.2fs\n"%time_)
f.write("-"*100+"\n")
display_scores(rmse_scores)
# save the model
joblib.dump(model,"model_set/%s.pkl"%model_name)
return model
## LinearRegression
#lin_reg=select_model()
#
## DecisionTreeRegressor
#tree_reg=select_model("DT")
#
## RandomForestRegressor
#forest_reg=select_model("RF")
#
### SVR
#svr_reg=select_model("SVR")
#################################################################################################
###################################### Adjust the params smoothly ###############################
#################################################################################################
def find_best_model():
#from sklearn.model_selection import GridSearchCV
#import time
#print("\n>> Starting Search the best params,please wait some seconds...")
#time1=time.time()
#
#param_grid=[
# {'n_estimators':[3,10,30],'max_features':[2,4,6,8]},
# {'bootstrap':[False],'n_estimators':[3,10],'max_features':[2,3,4]},
# ]
## train the model
from sklearn.ensemble import RandomForestRegressor
#forest_reg=RandomForestRegressor()
#grid_search=GridSearchCV(forest_reg,param_grid,cv=5,
# scoring='neg_mean_squared_error')
#grid_search.fit(housing_prepared,housing_label)
#time2=time.time()
#print("\n>> Grid Search sucessfully,use time %.2fs\n"%(time2-time1))
#print("-"*40)
#print(grid_search.best_params_)
#print(grid_search.best_estimator_)
#print("-"*40)
#cvres = grid_search.cv_results_
#for mean_score, params in zip(cvres["mean_test_score"], cvres["params"]):
# print(np.sqrt(-mean_score), params)
# random to adjust the params
import time
print("\n>> Starting Search the best params randomly,please wait some seconds...")
from sklearn.model_selection import RandomizedSearchCV
from scipy.stats import randint
time1=time.time()
param_distribs = {
'n_estimators': randint(low=1, high=200),
'max_features': randint(low=1, high=8),
}
forest_reg = RandomForestRegressor(random_state=42)
rnd_search = RandomizedSearchCV(forest_reg, param_distributions=param_distribs,
n_iter=10, cv=5, scoring='neg_mean_squared_error', random_state=42)
rnd_search.fit(housing_prepared, housing_label)
time2=time.time()
print("\n>> Grid Search sucessfully,use time %.2fs\n"%(time2-time1))
cvres = rnd_search.cv_results_
for mean_score, params in zip(cvres["mean_test_score"], cvres["params"]):
print(np.sqrt(-mean_score), params)
# show the importance of features
feature_importances = rnd_search.best_estimator_.feature_importances_
extra_attribs = ["rooms_per_hhold", "pop_per_hhold", "bedrooms_per_room"]
#cat_encoder = cat_pipeline.named_steps["cat_encoder"] # old solution
cat_encoder = full_pipeline.named_transformers_["cat"]
cat_one_hot_attribs = list(cat_encoder.categories_[0])
attributes = num_attribs + extra_attribs + cat_one_hot_attribs
print("Importance of features:\n"+"-"*40+"\n")
import pprint
pprint.pprint(sorted(zip(feature_importances, attributes), reverse=True))
return rnd_search
#################################################################################################
###################################### Final model ##############################################
#################################################################################################
def main():
if os.path.exists("model_set/final_model.pkl"):
final_model=joblib.load("model_set/final_model.pkl")
else:
from sklearn.metrics import mean_squared_error
time1=time.time()
rnd_search=find_best_model()
final_model = rnd_search.best_estimator_
X_test = strat_test_set.drop("median_house_value", axis=1)
y_test = strat_test_set["median_house_value"].copy()
X_test_prepared = full_pipeline.transform(X_test)
final_predictions = final_model.predict(X_test_prepared)
final_mse = mean_squared_error(y_test, final_predictions)
final_rmse = np.sqrt(final_mse)
time2=time.time()
print("Final model finished,use time %.2fs,rmse is %.6f"%(time2-time1,final_rmse))
# confidence interval
from scipy import stats
confidence = 0.95
squared_errors = (final_predictions - y_test) ** 2
# mean = squared_errors.mean()
m = len(squared_errors)
interval_array=np.sqrt(stats.t.interval(confidence, m - | |
name including the extension.** (e.g. `main.py`)")
try:
option = await self.client.wait_for(
"message", check=lambda m: m.author == ctx.author and m.channel == ctx.channel, timeout=120
)
filename = option.content
except TimeoutError:
return await ctx.send("Cancelling compilation...")
data = {"files": [{"name": filename, "content": code}]}
headers = {
"Authorization": f"Token {config.glotIoKey}",
"Content-type": "application/json"
}
res = await funcs.postRequest(url=url, data=dumps(data), headers=headers, verify=False)
try:
data = res.json()
stderr = data["stderr"]
if stderr == "":
await option.reply(embed=Embed(title="Compilation", description=funcs.formatting(data["stdout"] or "None")))
else:
await option.reply(embed=funcs.errorEmbed(data["error"].title(), funcs.formatting(stderr)))
except AttributeError:
await option.reply(embed=funcs.errorEmbed(None, "Code exceeded the maximum allowed running time."))
except Exception as ex:
funcs.printError(ctx, ex)
@commands.cooldown(1, 3, commands.BucketType.user)
@commands.command(name="unix", description="Converts a unix timestamp to a proper date format in GMT.",
aliases=["time", "timestamp", "epoch", "gmt", "utc", "timezone"],
usage="[time zone (-12-14)] [timestamp value]")
async def unix(self, ctx, tz=None, timestamp=None):
mins = 0
if not tz:
tz = 0
else:
try:
tz = float(tz)
if not -12 <= tz <= 14:
raise Exception
if tz != int(tz):
mins = int((tz - int(tz)) * 60)
except:
return await ctx.reply(embed=funcs.errorEmbed(None, "Time zone must be -12-14 inclusive."))
td = timedelta(hours=int(tz), minutes=mins)
if not timestamp:
timestamp = mktime(gmtime())
dt = datetime.fromtimestamp(timestamp) + td
timestamp = timegm((dt - td).timetuple())
else:
try:
timestamp = int(float(timestamp))
dt = datetime.utcfromtimestamp(timestamp) + td
except:
return await ctx.reply(embed=funcs.errorEmbed(None, "Invalid timestamp."))
timezone = "" if not tz and not mins else f"{'+' if tz > 0 else ''}{int(tz)}{f':{abs(mins)}' if mins else ''}"
await ctx.reply(funcs.formatting(str(dt) + f" (GMT{timezone})\n\nTimestamp: {int(timestamp)}"))
@commands.cooldown(1, 3, commands.BucketType.user)
@commands.command(name="scisum", aliases=["science", "sci"], hidden=True,
description="Shows the science summary for the last month.")
async def scisum(self, ctx):
await ctx.reply("https://tiny.cc/sci-sum")
@commands.cooldown(1, 5, commands.BucketType.user)
@commands.command(name="dict", description="Returns the definition(s) of a word.",
aliases=["dictionary", "def", "definition", "meaning", "define"],
usage="<language code> <word>")
async def dict(self, ctx, langcode, *, word):
codes = ["en", "hi", "es", "fr", "ja", "ru", "de", "it", "ko", "pt-BR", "ar", "tr"]
languages = [
"English", "Hindi", "Spanish", "French", "Japanese", "Russian", "German",
"Italian", "Korean", "Brazilian Portuguese", "Arabic", "Turkish"
]
langcode = langcode.casefold() if langcode != "pt-BR" else langcode
if langcode not in codes:
codesList = ", ".join(f"`{code}` ({languages[codes.index(code)]})" for code in codes)
e = funcs.errorEmbed("Invalid language code!", f"Valid options:\n\n{codesList}")
else:
try:
res = await funcs.getRequest(f"https://api.dictionaryapi.dev/api/v2/entries/{langcode}/{word}")
data = res.json()
word = data[0]["word"].title()
output = ""
for i in data:
meanings = i["meanings"]
for j in meanings:
try:
partOfSpeech = f' [{j["partOfSpeech"]}]'
except:
partOfSpeech = ""
definitions = j["definitions"]
for k in definitions:
definition = k["definition"]
output += f"- {definition}{partOfSpeech}\n"
e = Embed(title=f'"{word}"').add_field(name="Definition(s)", value=funcs.formatting(output[:-1], limit=1000))
except Exception as ex:
funcs.printError(ctx, ex)
e = funcs.errorEmbed(None, "Unknown word.")
await ctx.reply(embed=e)
@commands.cooldown(1, 3, commands.BucketType.user)
@commands.command(name="reddit", description="Looks up a community or user on Reddit.",
aliases=["subreddit", "r", "redditor"], usage="<r/subreddit OR u/redditor>")
async def reddit(self, ctx, *, inp=""):
redditclient = Reddit(client_id=config.redditClientID, client_secret=config.redditClientSecret, user_agent="*")
inp = inp.casefold().replace(" ", "/")
inp = inp.split("reddit.com/")[1] if "reddit.com/" in inp else inp
while inp.startswith("/"):
inp = inp[1:]
while inp.endswith("/"):
inp = inp[:-1]
try:
icon_url = "https://www.redditinc.com/assets/images/site/reddit-logo.png"
if inp.startswith("r") and "/" in inp:
subreddit = await redditclient.subreddit(inp.split("/")[-1], fetch=True)
if subreddit.over18 and not isinstance(ctx.channel, channel.DMChannel) and not ctx.channel.is_nsfw():
e = funcs.errorEmbed("NSFW/Over 18!", "Please view this community in an NSFW channel.")
else:
tags = [
i for i in [
"Link Flairs" if subreddit.can_assign_link_flair else 0,
"User Flairs" if subreddit.can_assign_user_flair else 0,
"Spoilers Enabled" if subreddit.spoilers_enabled else 0,
"NSFW" if subreddit.over18 else 0
] if i
]
e = Embed(description=f"https://www.reddit.com/r/{subreddit.display_name}" + " ([Old Reddit](" +
f"https://old.reddit.com/r/{subreddit.display_name}))")
e.set_author(icon_url=icon_url, name="r/" + subreddit.display_name)
if tags:
e.add_field(name="Tags", value=", ".join(f"`{i}`" for i in tags))
e.set_footer(text=subreddit.public_description)
dt = datetime.utcfromtimestamp(subreddit.created_utc)
e.add_field(name="Creation Date", value=funcs.dateBirthday(dt.day, dt.month, dt.year))
e.add_field(name="Subscribers", value="`{:,}`".format(subreddit.subscribers))
async for submission in subreddit.new(limit=1):
sauthor = submission.author or "[deleted]"
if sauthor != "[deleted]":
sauthor = sauthor.name
e.add_field(
name="Latest Post ({:,} point{}; from u/{})".format(
submission.score, "" if submission.score == 1 else "s", sauthor
),
value=f"https://www.reddit.com{submission.permalink}" + " ([Old Reddit](" +
f"https://old.reddit.com{submission.permalink}))",
inline=False
)
elif inp.startswith("u") and "/" in inp:
redditor = await redditclient.redditor(inp.split("/")[-1], fetch=True)
try:
suspended = redditor.is_suspended
tags = ["Suspended"]
nickname = ""
except:
suspended = False
tags = [
i for i in [
"Verified" if redditor.has_verified_email else 0,
"Reddit Employee" if redditor.is_employee else 0,
"Moderator" if redditor.is_mod else 0,
"Gold" if redditor.is_gold else 0,
"NSFW" if redditor.subreddit["over_18"] else 0
] if i
]
nickname = redditor.subreddit["title"]
if "NSFW" in tags and not isinstance(ctx.channel, channel.DMChannel) and not ctx.channel.is_nsfw():
e = funcs.errorEmbed("NSFW/Over 18!", "Please view this profile in an NSFW channel.")
else:
e = Embed(description=f"https://www.reddit.com/user/{redditor.name}" + " ([Old Reddit](" +
f"https://old.reddit.com/user/{redditor.name}))")
e.set_author(icon_url=icon_url, name="u/" + redditor.name + (f" ({nickname})" if nickname else ""))
if tags:
e.add_field(name="Tags", value=", ".join(f"`{i}`" for i in tags))
if not suspended:
lkarma = redditor.link_karma
ckarma = redditor.comment_karma
trophies = await redditor.trophies()
e.set_thumbnail(url=redditor.icon_img)
dt = datetime.utcfromtimestamp(redditor.created_utc)
e.add_field(name="Join Date", value=funcs.dateBirthday(dt.day, dt.month, dt.year))
e.add_field(name="Total Karma", value="`{:,}`".format(lkarma + ckarma))
e.add_field(name="Post Karma", value="`{:,}`".format(lkarma))
e.add_field(name="Comment Karma", value="`{:,}`".format(ckarma))
if trophies:
e.add_field(
name="Trophies ({:,})".format(len(trophies)),
value=", ".join(f"`{trophy.name}`" for trophy in trophies[:50])
+ ("..." if len(trophies) > 50 else ""),
inline=False
)
async for submission in redditor.submissions.new(limit=1):
e.add_field(
name=f"Latest Post (on r/{submission.subreddit.display_name}; " +
f"{'{:,}'.format(submission.score)} point{'' if submission.score == 1 else 's'})",
value=f"https://www.reddit.com{submission.permalink}" + " ([Old Reddit](" +
f"https://old.reddit.com{submission.permalink}))",
inline=False
)
async for comment in redditor.comments.new(limit=1):
e.add_field(
name=f"Latest Comment (on r/{comment.subreddit.display_name}; " +
f"{'{:,}'.format(comment.score)} point{'' if comment.score == 1 else 's'})",
value=funcs.formatting(comment.body, limit=1000),
inline=False
)
e.set_footer(text=redditor.subreddit["public_description"])
e.set_image(url=redditor.subreddit["banner_img"])
else:
e = funcs.errorEmbed("Invalid input!", 'Please use `r/"subreddit name"` or `u/"username"`.')
except Exception as ex:
funcs.printError(ctx, ex)
e = funcs.errorEmbed(None, "Invalid search.")
await ctx.reply(embed=e)
@commands.cooldown(1, 1, commands.BucketType.user)
@commands.command(name="calc", description="Does simple math.",
aliases=["calculate", "calculator", "cal", "math", "maths", "safeeval"], usage="<input>")
async def calc(self, ctx, *, inp):
try:
e = Embed(description=funcs.formatting(funcs.removeDotZero(funcs.evalMath(inp))))
except ZeroDivisionError:
answer = [
"Stop right there, that's illegal!",
"Wait hol up...",
"FBI OPEN UP!!!",
"LOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOO" +
"OOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOO" +
"OOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOL",
"You madlad...",
"God damn you.",
"......................................................",
"Why the hell do you exist?",
"Mate I think you've got issues.",
"Are you okay?",
"You tell me the answer.",
"What is wrong with you?",
"Disgraceful.",
"Don't you dare.",
"HOW DARE YOU?!?",
"You bloody bastard...",
"Do that again and I will stick that zero down your throat. Egg for breakfast, anyone?",
"Get a life.",
"Dio taxista Ronnosessuale dio animale porca di quella madonna vacca in calore rotta in settecento mila pezzi",
"Naughty naughty naughty, you filthy old soomaka!",
"Hey that's my yarbles! Give it back!",
"*magic portal opens...*", "[magic humming]",
"Go to the den.",
"EXXXXXCCCCCCUUUUUSEEEE MEEE",
"what", "wat", "wut", "Negative nothing", "屌", "No.", "no",
"Der Mann sprach für seine Rechte\ner ist verstört, er ist ein egoistischer Gör!",
"ENOUGH! Because of you, I almost lost my way! But everycreature here has reminded me of " +
"the true power of friendship! There will always be darkness in the world, but there will " +
"also always be those who find the light!",
"Focusing on our differences keeps us divided! Villains and creatures use that division against us!",
"SSSSHHHHHAAAAAAAAAAAHHDAAAHHHPPP",
"YOU! YOU TRIPLE GREASY WALKING SECOND DINING COURSE, YOU'RE JUST A PHONY! YOU'RE A GIANT, MORALIST" +
" PHONY WHO CAN'T TAKE CARE OF ANYONE, ESPECIALLY HIMSELF! YOU HAVE YOUR OWN DISCIPLINE UP YOUR OWN" +
" ARSE AND YOU DON'T EVEN SEE IT!"
]
try:
answer.append(
(await funcs.readTxt(funcs.getResource(self.name, "copypasta.txt"))).replace("\*", "*")[:1994]
)
except Exception as ex:
funcs.printError(ctx, ex)
pass
e = Embed(description=f"```{choice(answer)}```")
except Exception as ex:
funcs.printError(ctx, ex)
e = funcs.errorEmbed(None, str(ex))
await ctx.reply(embed=e)
@commands.cooldown(1, 1, commands.BucketType.user)
@commands.command(name="sqrt", usage="<input>", hidden=True,
aliases=["square", "root"], description="Calculates the square root of a given value or math expession.")
async def sqrt(self, ctx, *, val):
try:
e = Embed(description=funcs.formatting(funcs.removeDotZero(sqrt([funcs.evalMath(val)])[0])))
except Exception as ex:
funcs.printError(ctx, ex)
e = funcs.errorEmbed(None, str(ex))
await ctx.reply(embed=e)
@commands.cooldown(1, 3, commands.BucketType.user)
@commands.command(name="wordcount", description="Counts the number of words and characters in an input.",
aliases=["lettercount", "countletter", "countchar", "countletters", "char", "chars", "letters",
"charcount", "wc", "countword", "word", "words", "countwords", "letter"],
usage="<input OR text attachment>")
async def wordcount(self, ctx, *, inp=""):
filename = f"{time()}"
if ctx.message.attachments:
try:
inp = await funcs.readTxtAttachment(ctx.message)
if not inp:
raise
except:
try:
attach = ctx.message.attachments[0]
filename += f"-{attach.filename}"
filepath = f"{funcs.PATH}/temp/{filename}"
await attach.save(filepath)
pdf = await funcs.funcToCoro(open, filepath, "rb")
reader = PdfFileReader(pdf)
inp = ""
for page | |
import re
from copy import deepcopy
import pytest
from scimschema._model import attribute, model
def test_default_meta_attribute():
d = {
"name": "_userName",
"type": "string",
"multiValued": False,
"description": "Unique identifier for the User, typically used by the user to directly authenticate to the "
"service provider. Each User MUST include a non-empty userName value. This identifier MUST be "
"unique across the service provider's entire set of Users. REQUIRED.",
"required": True,
"caseExact": False,
"mutability": "invalid",
}
maf = model.AttributeFactory.create(
d=d, locator_path="urn:ietf:params:scim:schemas:test:default_attribute"
)
expected_exception = None
try:
maf.validate_schema()
except AssertionError as ae:
expected_exception = ae
def grep_exception_counts(msg):
try:
prog = re.compile(r"(\d+) aggregated exceptions found")
return next(i for i in prog.findall(msg))
except TypeError:
return None
exception_msg = str(expected_exception)
count_msg = grep_exception_counts(exception_msg)
assert re.search(
re.compile("2 aggregated exceptions found"), exception_msg
), "Expected 2 aggregated exceptions found but got '{}'".format(count_msg)
assert re.search(
re.compile("'_userName'] and has 'name' property which must be valid name"),
exception_msg,
)
assert re.search(
re.compile(
"'_userName'] and has 'mutability' property which must be .* but got 'invalid'"
),
exception_msg,
)
def test_binary_attribute_validate():
schema = {
"caseExact": True,
"name": "data",
"type": "binary",
"required": True,
}
data = {"data": "kjj"}
maf = model.AttributeFactory.create(
d=schema, locator_path="urn:ietf:params:scim:schemas:test:binary_attribute"
)
maf.validate_schema()
maf.validate(data)
def test_complex_meta_attribute():
d = {
"name": "name",
"type": "complex",
"multiValued": False,
"description": "The components of the user's real name. Providers MAY return just the full name as a single string in the formatted sub-attribute, or they MAY return just the individual component attributes using the other sub-attributes, or they MAY return both. If both variants are returned, they SHOULD be describing the same name, with the formatted name indicating how the component attributes should be combined.",
"required": False,
"subAttributes": [
{
"name": "formatted",
"type": "string",
"multiValued": False,
"description": "The full name, including all middle names, titles, and suffixes as appropriate, formatted for display (e.g., 'Ms. <NAME>, III').",
"required": False,
"caseExact": False,
"mutability": "readWrite",
"returned": "default",
"uniqueness": "none",
},
{
"name": "familyName",
"type": "string",
"multiValued": False,
"description": "The family name of the User, or last name in most Western languages (e.g., 'Jensen' given the full name '<NAME>, III').",
"required": False,
"caseExact": False,
"mutability": "readWrite",
"returned": "default",
"uniqueness": "none",
},
{
"name": "givenName",
"type": "string",
"multiValued": False,
"description": "The given name of the User, or first name in most Western languages (e.g., 'Barbara' given the full name 'Ms. <NAME>, III').",
"required": False,
"caseExact": False,
"mutability": "readWrite",
"returned": "default",
"uniqueness": "none",
},
{
"name": "middleName",
"type": "string",
"multiValued": False,
"description": "The middle name(s) of the User (e.g., 'Jane' given the full name '<NAME>, III').",
"required": False,
"caseExact": False,
"mutability": "readWrite",
"returned": "default",
"uniqueness": "none",
},
{
"name": "honorificPrefix",
"type": "string",
"multiValued": False,
"description": "The honorific prefix(es) of the User, or title in most Western languages (e.g., 'Ms.' given the full name '<NAME>, III').",
"required": False,
"caseExact": False,
"mutability": "readWrite",
"returned": "default",
"uniqueness": "none",
},
{
"name": "honorificSuffix",
"type": "string",
"multiValued": False,
"description": "The honorific suffix(es) of the User, or suffix in most Western languages (e.g., 'III' given the full name 'Ms. <NAME>, III').",
"required": False,
"caseExact": False,
"mutability": "readWrite",
"returned": "default",
"uniqueness": "none",
},
],
"mutability": "readWrite",
"returned": "default",
"uniqueness": "none",
}
maf = model.AttributeFactory.create(
d=d, locator_path="urn:ietf:params:scim:schemas:test:complex_attribute"
)
maf.validate_schema()
@pytest.mark.parametrize("value", [1, 0, 99, -1])
def test_int_meta_attribute(value):
schema = {"name": "amount", "type": "integer", "required": True}
maf = model.AttributeFactory.create(
d=schema, locator_path="urn:ietf:params:scim:schemas:test:integer_attribute"
)
maf.validate_schema()
data = {"amount": value}
maf.validate(data)
def test_reference_meta_attribute():
d = {
"name": "profileUrl",
"type": "reference",
"referenceTypes": ["external"],
"multiValued": False,
"description": "A fully qualified URL pointing to a page representing the User's online profile.",
"required": False,
"caseExact": True,
"mutability": "readWrite",
"returned": "default",
"uniqueness": "none",
}
maf = model.AttributeFactory.create(
d=d,
locator_path="urn:ietf:params:scim:schemas:test:ref_attribute",
is_parent_multi_valued=True,
)
maf.validate_schema()
def test_datetime_meta_attribute():
schema = {"name": "birthday", "type": "dateTime", "required": True}
maf = model.AttributeFactory.create(
d=schema, locator_path="urn:ietf:params:scim:schemas:test:datetime_attribute"
)
maf.validate_schema()
data = {"birthday": "2008-01-23T04:56:22Z"}
maf.validate(data)
def test_invalid_datetime_meta_attribute():
schema = {
"name": "created",
"type": "dateTime",
"description": "The 'DateTime' that the resource was added to the service provider. This attribute MUST be a DateTime.",
"required": False,
}
maf = model.AttributeFactory.create(
d=schema, locator_path="urn:ietf:params:scim:schemas:test:datetime_attribute"
)
maf.validate_schema()
data = {"created": "xyz1-01-23T04:56:22"}
assert_exceptions = None
try:
maf.validate(data)
except AssertionError as ae:
assert_exceptions = ae
pattern = re.compile(
r"'Single-value attribute: 'xyz1-01-23T04:56:22' (\()at path.*(\)) is expected to be 'datetime with format 2008-01-23T04:56:22Z'"
)
assert re.search(pattern=pattern, string=str(assert_exceptions)) is not None
def test_decimal_meta_attribute():
schema = {"name": "open_price", "type": "decimal", "required": True}
maf = model.AttributeFactory.create(
d=schema, locator_path="urn:ietf:params:scim:schemas:test:decimal_attribute"
)
maf.validate_schema()
data = {"open_price": 0.1}
maf.validate(data)
def test_invalid_decimal_meta_attribute():
schema = {"name": "open_price", "type": "decimal", "required": True}
maf = model.AttributeFactory.create(
d=schema, locator_path="urn:ietf:params:scim:schemas:test:decimal_attribute"
)
maf.validate_schema()
data = {"open_price": ".1"}
assert_exceptions = None
try:
maf.validate(data)
except AssertionError as ae:
assert_exceptions = ae
pattern = re.compile(
r"'Single-value attribute: '.1' (\()at path:.*(\)) is expected to be 'must be a real number with at least one digit to the left and right of the period'"
)
assert re.search(pattern=pattern, string=str(assert_exceptions)) is not None
def test_string_meta_attribute():
schema = {"name": "userName", "type": "string", "required": True}
maf = model.AttributeFactory.create(
d=schema, locator_path="urn:ietf:params:scim:schemas:test:string_attribute"
)
maf.validate_schema()
data = {"userName": "Superuser"}
maf.validate(data)
def test_invalid_string_meta_attribute():
schema = {
"name": "userName",
"type": "string",
"multiValued": False,
"description": "Unique identifier for the User, typically used by the user to directly authenticate to the "
"service provider. Each User MUST include a non-empty userName value. "
"This identifier MUST be unique across the service provider's entire set of Users. REQUIRED.",
"required": True,
"caseExact": False,
"mutability": "readWrite",
"returned": "default",
"uniqueness": "server",
}
maf = model.AttributeFactory.create(
d=schema, locator_path="urn:ietf:params:scim:schemas:test:string_attribute"
)
maf.validate_schema()
data = {"userName": 123}
assert_exceptions = None
try:
maf.validate(data)
except AssertionError as ae:
assert_exceptions = ae
pattern = re.compile(
r"'(\()int(\))123' (\()at path.*(\)) is expected to be 'type string'"
)
assert re.search(pattern=pattern, string=str(assert_exceptions)) is not None
def test_multi_valued_string_meta_attribute():
schema = {
"name": "userName",
"type": "string",
"multiValued": True,
"required": True,
}
maf = model.AttributeFactory.create(
d=schema,
locator_path="urn:ietf:params:scim:schemas:test:multi_string_attribute",
)
maf.validate_schema()
data = {"userName": ["Superuser"]}
maf.validate(data)
def test_multi_valued_complex_meta_attribute():
schema = {
"name": "emails",
"type": "complex",
"multiValued": True,
"description": "Email addresses for the user. The value SHOULD be canonicalized by the service provider, e.g., '<EMAIL>' instead of '<EMAIL>'. Canonical type values of 'work', 'home', and 'other'.",
"required": False,
"subAttributes": [
{
"name": "value",
"type": "string",
"multiValued": False,
"description": "Email addresses for the user. The value SHOULD be canonicalized by the service provider, e.g., '<EMAIL>' instead of '<EMAIL>'. Canonical type values of 'work', 'home', and 'other'.",
"required": False,
"caseExact": False,
"mutability": "readWrite",
"returned": "default",
"uniqueness": "none",
},
{
"name": "display",
"type": "string",
"multiValued": False,
"description": "A human-readable name, primarily used for display purposes. READ-ONLY.",
"required": False,
"caseExact": False,
"mutability": "readWrite",
"returned": "default",
"uniqueness": "none",
},
{
"name": "type",
"type": "string",
"multiValued": False,
"description": "A label indicating the attribute's function, e.g., 'work' or 'home'.",
"required": False,
"caseExact": False,
"canonicalValues": ["work", "home", "other"],
"mutability": "readWrite",
"returned": "default",
"uniqueness": "none",
},
{
"name": "primary",
"type": "boolean",
"multiValued": False,
"description": "A Boolean value indicating the 'primary' or preferred attribute value for this attribute, e.g., the preferred mailing address or primary email address. The primary attribute value 'true' MUST appear no more than once.",
"required": False,
"mutability": "readWrite",
"returned": "default",
},
],
"mutability": "readWrite",
"returned": "default",
"uniqueness": "none",
}
response = {
"emails": [
{"value": "<EMAIL>", "type": "work", "primary": True},
{"value": "<EMAIL>", "type": "home"},
{},
{"primary": True},
]
}
maf = model.AttributeFactory.create(
d=schema,
locator_path="urn:ietf:params:scim:schemas:test:multi_complex_attribute",
)
assert maf.name == "emails"
assert maf.element_attribute.name == "emails"
maf.validate_schema()
original = deepcopy(response)
maf.validate(response)
assert response == original
def test_multi_valued_invalid_complex_meta_attribute():
schema = {
"name": "emails",
"type": "complex",
"multiValued": True,
"description": "Email addresses for the user. The value SHOULD be canonicalized by the service provider, e.g., '<EMAIL>' instead of '<EMAIL>'. Canonical type values of 'work', 'home', and 'other'.",
"required": False,
"subAttributes": [
{
"name": "value",
"type": "string",
"multiValued": False,
"description": "Email addresses for the user. The value SHOULD be canonicalized by the service provider, e.g., '<EMAIL>' instead of '<EMAIL>'. Canonical type values of 'work', 'home', and 'other'.",
"required": True,
"caseExact": False,
"mutability": "readWrite",
"returned": "default",
"uniqueness": "none",
},
{
"name": "display",
"type": "string",
"multiValued": False,
"description": "A human-readable name, primarily used for display purposes. READ-ONLY.",
"required": False,
"caseExact": False,
"mutability": "readWrite",
"returned": "default",
"uniqueness": "none",
| |
query, "select $1||', '||$2||'!'",
('Hello', u'мир!'))
def testQueryWithMixedParams(self):
self.assertEqual(self.c.query("select $1+2,$2||', world!'",
(1, 'Hello'),).getresult(), [(3, 'Hello, world!')])
self.assertEqual(self.c.query("select $1::integer,$2::date,$3::text",
(4711, None, 'Hello!'),).getresult(), [(4711, None, 'Hello!')])
def testQueryWithDuplicateParams(self):
self.assertRaises(pg.ProgrammingError,
self.c.query, "select $1+$1", (1,))
self.assertRaises(pg.ProgrammingError,
self.c.query, "select $1+$1", (1, 2))
def testQueryWithZeroParams(self):
self.assertEqual(self.c.query("select 1+1", []
).getresult(), [(2,)])
def testQueryWithGarbage(self):
garbage = r"'\{}+()-#[]oo324"
self.assertEqual(self.c.query("select $1::text AS garbage", (garbage,)
).dictresult(), [{'garbage': garbage}])
class TestQueryResultTypes(unittest.TestCase):
"""Test proper result types via a basic pg connection."""
def setUp(self):
self.c = connect()
self.c.query('set client_encoding=utf8')
self.c.query("set datestyle='ISO,YMD'")
def tearDown(self):
self.c.close()
def assert_proper_cast(self, value, pgtype, pytype):
q = 'select $1::%s' % (pgtype,)
try:
r = self.c.query(q, (value,)).getresult()[0][0]
except pg.ProgrammingError:
if pgtype in ('json', 'jsonb'):
self.skipTest('database does not support json')
self.assertIsInstance(r, pytype)
if isinstance(value, str):
if not value or ' ' in value or '{' in value:
value = '"%s"' % value
value = '{%s}' % value
r = self.c.query(q + '[]', (value,)).getresult()[0][0]
if pgtype.startswith(('date', 'time', 'interval')):
# arrays of these are casted by the DB wrapper only
self.assertEqual(r, value)
else:
self.assertIsInstance(r, list)
self.assertEqual(len(r), 1)
self.assertIsInstance(r[0], pytype)
def testInt(self):
self.assert_proper_cast(0, 'int', int)
self.assert_proper_cast(0, 'smallint', int)
self.assert_proper_cast(0, 'oid', int)
self.assert_proper_cast(0, 'cid', int)
self.assert_proper_cast(0, 'xid', int)
def testLong(self):
self.assert_proper_cast(0, 'bigint', long)
def testFloat(self):
self.assert_proper_cast(0, 'float', float)
self.assert_proper_cast(0, 'real', float)
self.assert_proper_cast(0, 'double', float)
self.assert_proper_cast(0, 'double precision', float)
self.assert_proper_cast('infinity', 'float', float)
def testFloat(self):
decimal = pg.get_decimal()
self.assert_proper_cast(decimal(0), 'numeric', decimal)
self.assert_proper_cast(decimal(0), 'decimal', decimal)
def testMoney(self):
decimal = pg.get_decimal()
self.assert_proper_cast(decimal('0'), 'money', decimal)
def testBool(self):
bool_type = bool if pg.get_bool() else str
self.assert_proper_cast('f', 'bool', bool_type)
def testDate(self):
self.assert_proper_cast('1956-01-31', 'date', str)
self.assert_proper_cast('10:20:30', 'interval', str)
self.assert_proper_cast('08:42:15', 'time', str)
self.assert_proper_cast('08:42:15+00', 'timetz', str)
self.assert_proper_cast('1956-01-31 08:42:15', 'timestamp', str)
self.assert_proper_cast('1956-01-31 08:42:15+00', 'timestamptz', str)
def testText(self):
self.assert_proper_cast('', 'text', str)
self.assert_proper_cast('', 'char', str)
self.assert_proper_cast('', 'bpchar', str)
self.assert_proper_cast('', 'varchar', str)
def testBytea(self):
self.assert_proper_cast('', 'bytea', bytes)
def testJson(self):
self.assert_proper_cast('{}', 'json', dict)
class TestInserttable(unittest.TestCase):
"""Test inserttable method."""
cls_set_up = False
@classmethod
def setUpClass(cls):
c = connect()
c.query("drop table if exists test cascade")
c.query("create table test ("
"i2 smallint, i4 integer, i8 bigint, b boolean, dt date, ti time,"
"d numeric, f4 real, f8 double precision, m money,"
"c char(1), v4 varchar(4), c4 char(4), t text)")
# Check whether the test database uses SQL_ASCII - this means
# that it does not consider encoding when calculating lengths.
c.query("set client_encoding=utf8")
try:
c.query("select 'ä'")
except (pg.DataError, pg.NotSupportedError):
cls.has_encoding = False
else:
cls.has_encoding = c.query(
"select length('ä') - length('a')").getresult()[0][0] == 0
c.close()
cls.cls_set_up = True
@classmethod
def tearDownClass(cls):
c = connect()
c.query("drop table test cascade")
c.close()
def setUp(self):
self.assertTrue(self.cls_set_up)
self.c = connect()
self.c.query("set client_encoding=utf8")
self.c.query("set datestyle='ISO,YMD'")
self.c.query("set lc_monetary='C'")
def tearDown(self):
self.c.query("truncate table test")
self.c.close()
data = [
(-1, -1, long(-1), True, '1492-10-12', '08:30:00',
-1.2345, -1.75, -1.875, '-1.25', '-', 'r?', '!u', 'xyz'),
(0, 0, long(0), False, '1607-04-14', '09:00:00',
0.0, 0.0, 0.0, '0.0', ' ', '0123', '4567', '890'),
(1, 1, long(1), True, '1801-03-04', '03:45:00',
1.23456, 1.75, 1.875, '1.25', 'x', 'bc', 'cdef', 'g'),
(2, 2, long(2), False, '1903-12-17', '11:22:00',
2.345678, 2.25, 2.125, '2.75', 'y', 'q', 'ijk', 'mnop\nstux!')]
@classmethod
def db_len(cls, s, encoding):
if cls.has_encoding:
s = s if isinstance(s, unicode) else s.decode(encoding)
else:
s = s.encode(encoding) if isinstance(s, unicode) else s
return len(s)
def get_back(self, encoding='utf-8'):
"""Convert boolean and decimal values back."""
data = []
for row in self.c.query("select * from test order by 1").getresult():
self.assertIsInstance(row, tuple)
row = list(row)
if row[0] is not None: # smallint
self.assertIsInstance(row[0], int)
if row[1] is not None: # integer
self.assertIsInstance(row[1], int)
if row[2] is not None: # bigint
self.assertIsInstance(row[2], long)
if row[3] is not None: # boolean
self.assertIsInstance(row[3], bool)
if row[4] is not None: # date
self.assertIsInstance(row[4], str)
self.assertTrue(row[4].replace('-', '').isdigit())
if row[5] is not None: # time
self.assertIsInstance(row[5], str)
self.assertTrue(row[5].replace(':', '').isdigit())
if row[6] is not None: # numeric
self.assertIsInstance(row[6], Decimal)
row[6] = float(row[6])
if row[7] is not None: # real
self.assertIsInstance(row[7], float)
if row[8] is not None: # double precision
self.assertIsInstance(row[8], float)
row[8] = float(row[8])
if row[9] is not None: # money
self.assertIsInstance(row[9], Decimal)
row[9] = str(float(row[9]))
if row[10] is not None: # char(1)
self.assertIsInstance(row[10], str)
self.assertEqual(self.db_len(row[10], encoding), 1)
if row[11] is not None: # varchar(4)
self.assertIsInstance(row[11], str)
self.assertLessEqual(self.db_len(row[11], encoding), 4)
if row[12] is not None: # char(4)
self.assertIsInstance(row[12], str)
self.assertEqual(self.db_len(row[12], encoding), 4)
row[12] = row[12].rstrip()
if row[13] is not None: # text
self.assertIsInstance(row[13], str)
row = tuple(row)
data.append(row)
return data
def testInserttable1Row(self):
data = self.data[2:3]
self.c.inserttable('test', data)
self.assertEqual(self.get_back(), data)
def testInserttable4Rows(self):
data = self.data
self.c.inserttable('test', data)
self.assertEqual(self.get_back(), data)
def testInserttableMultipleRows(self):
num_rows = 100
data = self.data[2:3] * num_rows
self.c.inserttable('test', data)
r = self.c.query("select count(*) from test").getresult()[0][0]
self.assertEqual(r, num_rows)
def testInserttableMultipleCalls(self):
num_rows = 10
data = self.data[2:3]
for _i in range(num_rows):
self.c.inserttable('test', data)
r = self.c.query("select count(*) from test").getresult()[0][0]
self.assertEqual(r, num_rows)
def testInserttableNullValues(self):
data = [(None,) * 14] * 100
self.c.inserttable('test', data)
self.assertEqual(self.get_back(), data)
def testInserttableMaxValues(self):
data = [(2 ** 15 - 1, int(2 ** 31 - 1), long(2 ** 31 - 1),
True, '2999-12-31', '11:59:59', 1e99,
1.0 + 1.0 / 32, 1.0 + 1.0 / 32, None,
"1", "1234", "1234", "1234" * 100)]
self.c.inserttable('test', data)
self.assertEqual(self.get_back(), data)
def testInserttableByteValues(self):
try:
self.c.query("select '€', 'käse', 'сыр', 'pont-l''évêque'")
except pg.DataError:
self.skipTest("database does not support utf8")
# non-ascii chars do not fit in char(1) when there is no encoding
c = u'€' if self.has_encoding else u'$'
row_unicode = (0, 0, long(0), False, u'1970-01-01', u'00:00:00',
0.0, 0.0, 0.0, u'0.0',
c, u'bäd', u'bäd', u"käse сыр pont-l'évêque")
row_bytes = tuple(s.encode('utf-8')
if isinstance(s, unicode) else s for s in row_unicode)
data = [row_bytes] * 2
self.c.inserttable('test', data)
if unicode_strings:
data = [row_unicode] * 2
self.assertEqual(self.get_back(), data)
def testInserttableUnicodeUtf8(self):
try:
self.c.query("select '€', 'käse', 'сыр', 'pont-l''évêque'")
except pg.DataError:
self.skipTest("database does not support utf8")
# non-ascii chars do not fit in char(1) when there is no encoding
c = u'€' if self.has_encoding else u'$'
row_unicode = (0, 0, long(0), False, u'1970-01-01', u'00:00:00',
0.0, 0.0, 0.0, u'0.0',
c, u'bäd', u'bäd', u"käse сыр pont-l'évêque")
data = [row_unicode] * 2
self.c.inserttable('test', data)
if not unicode_strings:
row_bytes = tuple(s.encode('utf-8')
if isinstance(s, unicode) else s for s in row_unicode)
data = [row_bytes] * 2
self.assertEqual(self.get_back(), data)
def testInserttableUnicodeLatin1(self):
try:
self.c.query("set client_encoding=latin1")
self.c.query("select '¥'")
except (pg.DataError, pg.NotSupportedError):
self.skipTest("database does not support latin1")
# non-ascii chars do not fit in char(1) when there is no encoding
c = u'€' if self.has_encoding else u'$'
row_unicode = (0, 0, long(0), False, u'1970-01-01', u'00:00:00',
0.0, 0.0, 0.0, u'0.0',
c, u'bäd', u'bäd', u"for käse and pont-l'évêque pay in €")
data = [row_unicode]
# cannot encode € sign with latin1 encoding
self.assertRaises(UnicodeEncodeError, self.c.inserttable, 'test', data)
row_unicode = tuple(s.replace(u'€', u'¥')
if isinstance(s, unicode) else s for s in row_unicode)
data = [row_unicode] * 2
self.c.inserttable('test', data)
if not unicode_strings:
row_bytes = tuple(s.encode('latin1')
if isinstance(s, unicode) else s for s in row_unicode)
data = [row_bytes] * 2
self.assertEqual(self.get_back('latin1'), data)
def testInserttableUnicodeLatin9(self):
try:
self.c.query("set client_encoding=latin9")
self.c.query("select '€'")
except (pg.DataError, pg.NotSupportedError):
self.skipTest("database does not support latin9")
return
# non-ascii chars do not fit in char(1) when there is no encoding
c = u'€' if self.has_encoding else u'$'
row_unicode = (0, 0, long(0), False, u'1970-01-01', u'00:00:00',
0.0, 0.0, 0.0, u'0.0',
c, u'bäd', u'bäd', u"for käse and pont-l'évêque pay in €")
data = [row_unicode] * 2
self.c.inserttable('test', data)
if not unicode_strings:
row_bytes = tuple(s.encode('latin9')
if isinstance(s, unicode) else s for s in row_unicode)
data = [row_bytes] * 2
self.assertEqual(self.get_back('latin9'), data)
def testInserttableNoEncoding(self):
self.c.query("set client_encoding=sql_ascii")
# non-ascii chars do not fit in char(1) when there is no encoding
c = u'€' if self.has_encoding else u'$'
row_unicode = (0, 0, long(0), False, u'1970-01-01', u'00:00:00',
0.0, 0.0, 0.0, u'0.0',
c, u'bäd', u'bäd', u"for käse and pont-l'évêque pay in €")
data = [row_unicode]
# cannot encode non-ascii unicode without a specific encoding
self.assertRaises(UnicodeEncodeError, self.c.inserttable, 'test', data)
class TestDirectSocketAccess(unittest.TestCase):
"""Test copy command with direct socket access."""
cls_set_up = False
@classmethod
def setUpClass(cls):
c = connect()
c.query("drop table if exists test cascade")
c.query("create table test (i int, v varchar(16))")
c.close()
cls.cls_set_up = True
@classmethod
def tearDownClass(cls):
c = connect()
c.query("drop table test cascade")
c.close()
def setUp(self):
self.assertTrue(self.cls_set_up)
self.c = connect()
self.c.query("set client_encoding=utf8")
def tearDown(self):
self.c.query("truncate table test")
| |
to a known ip
address or a domain name. If it is successful, that host will become the
selected host.
The default selected host is the local host.
Subsequent 'attach' commands will be done on the selected host.
Type 'help attach' for more information.""", self.m_stdout)
def help_stack(self):
_print("""stack [<tid> | '*']
(shorthand - k)
Without an argument, 'stack' prints the stack trace of the focused thread.
If the thread is waiting at break point a special character will mark the
focused frame.
<tid> - print the stack of thread <tid>
'*' - print the stacks of all active threads.
Type 'help break' for more information on breakpoints and threads.
Type 'help up' or 'help down' for more information on focused frames.""", self.m_stdout)
help_k = help_stack
def help_list(self):
_print("""list [<file_name>:][<line_no> | '+' | '-' | '^' | '*'] [',' <nlines>]
(shorthand - l)
Without an argument, 'list' prints the source lines around the current line
of the focused thread in the focused frame. A special character sequence will
mark the current line according to the event:
'C>' - call - A function is called.
'L>' - line - The interpreter is about to execute a new line of code.
'R>' - return - A function is about to return.
'E>' - exception - An exception has been thrown.
'*>' - running - The thread is running.
If a breakpoint is assigned to a line, that line will be marked with:
'B' - if the breakpoint is enabled
'D' - if the breakpoint is disabled
<file_name> - List source from filename
<line_no> - Print the source lines around that line number in the same file
of the current line.
'+' - Print the next lines in the file.
'-' - Print the previous lines in the file.
'^' - Print the entire file.
'*' - Print the source lines for each of the active threads.
<nlines> - Print <nlines> of source
Type 'help break' for more information on breakpoints and threads.
Type 'help up' or 'help down' for more information on focused frames.""", self.m_stdout)
help_l = help_list
def help_thread(self):
_print("""thread [<no> | <tid>]
(shorthand - t)
Without an argument, 'thread' prints the list of known active threads, with
their corresponding state, which can be either 'running' or
'waiting at break point'. A special character will mark the focused thread.
With an argument <tid>, 'thread' will attempt to set the debugger focus to
the thread of that tid.
With an argument <no>, 'thread' will attempt to set the debugger focus to
the thread of that order in the thread list.
Type 'help break' for more information on breakpoints and threads.""", self.m_stdout)
help_t = help_thread
def help_jump(self):
_print("""jump <lineno>
(shorthand - j)
Jump to line <lineno> in the current scope.""", self.m_stdout)
help_j = help_jump
def help_next(self):
_print("""next
(shorthand - n)
Continue execution until the next line in the current function
is reached or it returns.""", self.m_stdout)
help_n = help_next
def help_step(self):
_print("""step
(shorthand - s)
Execute the current line, stop at the first possible occasion
(either in a function that is called or in the current function).""", self.m_stdout)
help_s = help_step
def help_return(self):
_print("""next
(shorthand - r)
Continue execution until the current function returns.""", self.m_stdout)
help_r = help_return
def help_up(self):
_print("""up
move the debugger focus one frame up the stack of the debugged thread
(closer to the current, most recently executed frame). Evaluation of
expressions or execution of statements will be done at the local and global
name spaces of the focused frame.
Type 'help eval' for more information on evaluation of expressions.
Type 'help exec' for more information on execution of statements.""", self.m_stdout)
def help_down(self):
_print("""down
move the debugger focus one frame down the stack of the debugged thread
(closer to the current, most recently executed frame). Evaluation of
expressions or execution of statements will be done at the local and global
name spaces of the focused frame.
Type 'help eval' for more information on evaluation of expressions.
Type 'help exec' for more information on execution of statements.""", self.m_stdout)
def help_eval(self):
_print("""eval <expr>
(shorthand - v)
Evaluate the python expression <expr> under the global and local name spaces
of the currently focused frame.
Example:
'eval locals()' - will display the dictionary of the local variables.
IMPORTANT: Any changes to the global name space will be discarded unless the
focused stack frame is the top most frame.
Type 'help up' or 'help down' for more information on focused frames.""", self.m_stdout)
help_v = help_eval
def help_exec(self):
_print("""exec <stmt>
(shorthand - x)
Execute the python suite <stmt> under the global and local name spaces
of the currently focused frame.
Example:
'exec i += 1'
IMPORTANT: Any changes to the global name space will be discarded unless the
focused stack frame is the top most frame.
Type 'help up' or 'help down' for more information on focused frames.""", self.m_stdout)
help_x = help_exec
def help_encoding(self):
_print("""encoding [<encoding> [, raw]]
Set the source encoding for the exec and eval commands.
Without an argument returns the current encoding.
The specified encoding can be either 'auto' or any encoding accepted
by the codecs module. If 'auto' is specified, the source encoding of
the active scope will be used, which is utf-8 by default.
The default encoding value is 'auto'.
If 'raw' is specified, strings returned by the eval command
will represent non ASCII characters as an escape sequence.""", self.m_stdout)
def help_env(self):
_print("""env [-d key | key = value]
Set the environment variables mapping. This mapping is used
when a new script is launched to modify its environment.
Example for a mapping on Windows:
env Path = %Path%;c:\\mydir
Example for a mapping on Linux:
env PATH = $PATH:~/mydir
To delete the mapping for PATH
env -d PATH
Without an argument returns the current list of mappings.
Note that the mapping will be evaluated and used to modify
the environment after the debugger engine at the debuggee
has imported the modules it requires. The order in which the
mappings will be evaluated and applied is:
last set, last evaluated.""", self.m_stdout)
#
# ---------------------------------------- Replacement Functions ------------------------------------
#
def rpdb2_import_wrapper(*args, **kwargs):
if len(args) > 0:
name = args[0]
elif 'name' in kwargs:
name = kwargs['name']
else:
return g_import(*args, **kwargs)
if name in sys.modules:
return g_import(*args, **kwargs)
#
# rpdb2 avoids stepping through this
# function (rpdb2_import_wrapper) to
# prevent confusion when stepping into
# an import statement.
#
m = g_import(*args, **kwargs)
if name != 'gtk':
return m
try:
m.gdk.threads_init()
return m
except:
pass
try:
m.threads_init()
return m
except:
pass
return m
g_import = None
if __name__ == 'rpdb2' and g_builtins_module.__import__ != rpdb2_import_wrapper:
g_import = g_builtins_module.__import__
g_builtins_module.__import__ = rpdb2_import_wrapper
def __find_eval_exec_frame_in_stack():
f = sys._getframe(0)
while f != None:
filename = f.f_code.co_filename
name = f.f_code.co_name
if DEBUGGER_FILENAME in filename and name in ['_evaluate', '_execute'] and 'redirect_exc_info' in f.f_locals:
return f
f = f.f_back
return None
def __exc_info():
f = __find_eval_exec_frame_in_stack()
if f == None:
return g_sys_exc_info()
try:
frame_index = f.f_locals['frame_index']
fException = f.f_locals['fException']
e = g_debugger.get_exception(frame_index, fException)
exc_info = (e['type'], e['value'], e['traceback'])
return exc_info
except:
return g_sys_exc_info()
g_sys_exc_info = None
if __name__ == 'rpdb2' and 'exc_info' in dir(sys) and sys.exc_info != __exc_info:
g_sys_exc_info = sys.exc_info
sys.exc_info = __exc_info
def __setrecursionlimit(rl):
global g_recursionlimit
print_debug('rl = %d' % rl)
g_recursionlimit = max(rl, 64)
rl = g_recursionlimit
if sys.version_info[:2] == (2, 6):
rl *= 3
return g_sys_setrecursionlimit(rl + 64)
g_sys_setrecursionlimit = None
if __name__ == 'rpdb2' and 'setrecursionlimit' in dir(sys) and sys.setrecursionlimit != __setrecursionlimit:
g_sys_setrecursionlimit = sys.setrecursionlimit
sys.setrecursionlimit = __setrecursionlimit
__setrecursionlimit(sys.getrecursionlimit())
def __find_debugger_frame():
frame = None
f = sys._getframe(0)
while f != None:
filename = f.f_code.co_filename
name = f.f_code.co_name
if DEBUGGER_FILENAME in filename and (name.startswith('trace_dispatch') or name == 'profile'):
frame = f
f = f.f_back
return frame
class CSignalHandler:
def __del__(self):
while len(g_signals_pending) != 0:
(handler, signum, frameobj) = g_signals_pending.pop(0)
print_debug('Handling pending signal: %s, %s' % (repr(signum), repr(frameobj)))
try:
handler(signum, frameobj)
except:
#
# Can not raise from inside a destructor. Report that handler
# exception will be ignored.
#
(t, v, tb) = sys.exc_info()
_t = safe_repr(t)
if _t.startswith("<type '"):
_t = _t.split("'")[1]
event = CEventSignalException(signum, '%s: %s' % (_t, safe_repr(v)))
g_debugger.m_event_dispatcher.fire_event(event)
def signal_handler(signum, frameobj):
frame = __find_debugger_frame()
if frame == None:
#
# A | |
for i in range(self.n_components - 2, -1, -1):
self.gamma_[i, 2] = self.gamma_[i + 1, 2] + sz[i]
self.gamma_.T[2] += self.alpha
def _update_means(self, X, z):
"""Update the variational distributions for the means"""
n_features = X.shape[1]
for k in range(self.n_components):
if self.covariance_type in ['spherical', 'diag']:
num = np.sum(z.T[k].reshape((-1, 1)) * X, axis=0)
num *= self.precs_[k]
den = 1. + self.precs_[k] * np.sum(z.T[k])
self.means_[k] = num / den
elif self.covariance_type in ['tied', 'full']:
if self.covariance_type == 'tied':
cov = self.precs_
else:
cov = self.precs_[k]
den = np.identity(n_features) + cov * np.sum(z.T[k])
num = np.sum(z.T[k].reshape((-1, 1)) * X, axis=0)
num = np.dot(cov, num)
self.means_[k] = linalg.lstsq(den, num)[0]
def _update_precisions(self, X, z):
"""Update the variational distributions for the precisions"""
n_features = X.shape[1]
if self.covariance_type == 'spherical':
self.dof_ = 0.5 * n_features * np.sum(z, axis=0)
for k in range(self.n_components):
# could be more memory efficient ?
sq_diff = np.sum((X - self.means_[k]) ** 2, axis=1)
self.scale_[k] = 1.
self.scale_[k] += 0.5 * np.sum(z.T[k] * (sq_diff + n_features))
self.bound_prec_[k] = (
0.5 * n_features * (
digamma(self.dof_[k]) - np.log(self.scale_[k])))
self.precs_ = np.tile(self.dof_ / self.scale_, [n_features, 1]).T
elif self.covariance_type == 'diag':
for k in range(self.n_components):
self.dof_[k].fill(1. + 0.5 * np.sum(z.T[k], axis=0))
sq_diff = (X - self.means_[k]) ** 2 # see comment above
self.scale_[k] = np.ones(n_features) + 0.5 * np.dot(
z.T[k], (sq_diff + 1))
self.precs_[k] = self.dof_[k] / self.scale_[k]
self.bound_prec_[k] = 0.5 * np.sum(digamma(self.dof_[k])
- np.log(self.scale_[k]))
self.bound_prec_[k] -= 0.5 * np.sum(self.precs_[k])
elif self.covariance_type == 'tied':
self.dof_ = 2 + X.shape[0] + n_features
self.scale_ = (X.shape[0] + 1) * np.identity(n_features)
for k in range(self.n_components):
diff = X - self.means_[k]
self.scale_ += np.dot(diff.T, z[:, k:k + 1] * diff)
self.scale_ = pinvh(self.scale_)
self.precs_ = self.dof_ * self.scale_
self.det_scale_ = linalg.det(self.scale_)
self.bound_prec_ = 0.5 * wishart_log_det(
self.dof_, self.scale_, self.det_scale_, n_features)
self.bound_prec_ -= 0.5 * self.dof_ * np.trace(self.scale_)
elif self.covariance_type == 'full':
for k in range(self.n_components):
sum_resp = np.sum(z.T[k])
self.dof_[k] = 2 + sum_resp + n_features
self.scale_[k] = (sum_resp + 1) * np.identity(n_features)
diff = X - self.means_[k]
self.scale_[k] += np.dot(diff.T, z[:, k:k + 1] * diff)
self.scale_[k] = pinvh(self.scale_[k])
self.precs_[k] = self.dof_[k] * self.scale_[k]
self.det_scale_[k] = linalg.det(self.scale_[k])
self.bound_prec_[k] = 0.5 * wishart_log_det(
self.dof_[k], self.scale_[k], self.det_scale_[k],
n_features)
self.bound_prec_[k] -= 0.5 * self.dof_[k] * np.trace(
self.scale_[k])
def _monitor(self, X, z, n, end=False):
"""Monitor the lower bound during iteration
Debug method to help see exactly when it is failing to converge as
expected.
Note: this is very expensive and should not be used by default."""
if self.verbose > 0:
print("Bound after updating %8s: %f" % (n, self.lower_bound(X, z)))
if end:
print("Cluster proportions:", self.gamma_.T[1])
print("covariance_type:", self.covariance_type)
def _do_mstep(self, X, z, params):
"""Maximize the variational lower bound
Update each of the parameters to maximize the lower bound."""
self._monitor(X, z, "z")
self._update_concentration(z)
self._monitor(X, z, "gamma")
if 'm' in params:
self._update_means(X, z)
self._monitor(X, z, "mu")
if 'c' in params:
self._update_precisions(X, z)
self._monitor(X, z, "a and b", end=True)
def _initialize_gamma(self):
"Initializes the concentration parameters"
self.gamma_ = self.alpha * np.ones((self.n_components, 3))
def _bound_concentration(self):
"""The variational lower bound for the concentration parameter."""
logprior = gammaln(self.alpha) * self.n_components
logprior += np.sum((self.alpha - 1) * (
digamma(self.gamma_.T[2]) - digamma(self.gamma_.T[1] +
self.gamma_.T[2])))
logprior += np.sum(- gammaln(self.gamma_.T[1] + self.gamma_.T[2]))
logprior += np.sum(gammaln(self.gamma_.T[1]) +
gammaln(self.gamma_.T[2]))
logprior -= np.sum((self.gamma_.T[1] - 1) * (
digamma(self.gamma_.T[1]) - digamma(self.gamma_.T[1] +
self.gamma_.T[2])))
logprior -= np.sum((self.gamma_.T[2] - 1) * (
digamma(self.gamma_.T[2]) - digamma(self.gamma_.T[1] +
self.gamma_.T[2])))
return logprior
def _bound_means(self):
"The variational lower bound for the mean parameters"
logprior = 0.
logprior -= 0.5 * squared_norm(self.means_)
logprior -= 0.5 * self.means_.shape[1] * self.n_components
return logprior
def _bound_precisions(self):
"""Returns the bound term related to precisions"""
logprior = 0.
if self.covariance_type == 'spherical':
logprior += np.sum(gammaln(self.dof_))
logprior -= np.sum(
(self.dof_ - 1) * digamma(np.maximum(0.5, self.dof_)))
logprior += np.sum(- np.log(self.scale_) + self.dof_
- self.precs_[:, 0])
elif self.covariance_type == 'diag':
logprior += np.sum(gammaln(self.dof_))
logprior -= np.sum(
(self.dof_ - 1) * digamma(np.maximum(0.5, self.dof_)))
logprior += np.sum(- np.log(self.scale_) + self.dof_ - self.precs_)
elif self.covariance_type == 'tied':
logprior += _bound_wishart(self.dof_, self.scale_, self.det_scale_)
elif self.covariance_type == 'full':
for k in range(self.n_components):
logprior += _bound_wishart(self.dof_[k],
self.scale_[k],
self.det_scale_[k])
return logprior
def _bound_proportions(self, z):
"""Returns the bound term related to proportions"""
dg12 = digamma(self.gamma_.T[1] + self.gamma_.T[2])
dg1 = digamma(self.gamma_.T[1]) - dg12
dg2 = digamma(self.gamma_.T[2]) - dg12
cz = np.cumsum(z[:, ::-1], axis=-1)[:, -2::-1]
logprior = np.sum(cz * dg2[:-1]) + np.sum(z * dg1)
del cz # Save memory
z_non_zeros = z[z > np.finfo(np.float32).eps]
logprior -= np.sum(z_non_zeros * np.log(z_non_zeros))
return logprior
def _logprior(self, z):
logprior = self._bound_concentration()
logprior += self._bound_means()
logprior += self._bound_precisions()
logprior += self._bound_proportions(z)
return logprior
def lower_bound(self, X, z):
"""returns a lower bound on model evidence based on X and membership"""
check_is_fitted(self, 'means_')
if self.covariance_type not in ['full', 'tied', 'diag', 'spherical']:
raise NotImplementedError("This ctype is not implemented: %s"
% self.covariance_type)
X = np.asarray(X)
if X.ndim == 1:
X = X[:, np.newaxis]
c = np.sum(z * _bound_state_log_lik(X, self._initial_bound +
self.bound_prec_, self.precs_,
self.means_, self.covariance_type))
return c + self._logprior(z)
def _set_weights(self):
for i in xrange(self.n_components):
self.weights_[i] = self.gamma_[i, 1] / (self.gamma_[i, 1]
+ self.gamma_[i, 2])
self.weights_ /= np.sum(self.weights_)
def _fit(self, X, y=None):
"""Estimate model parameters with the variational
algorithm.
For a full derivation and description of the algorithm see
doc/modules/dp-derivation.rst
or
http://scikit-learn.org/stable/modules/dp-derivation.html
A initialization step is performed before entering the em
algorithm. If you want to avoid this step, set the keyword
argument init_params to the empty string '' when creating
the object. Likewise, if you would like just to do an
initialization, set n_iter=0.
Parameters
----------
X : array_like, shape (n, n_features)
List of n_features-dimensional data points. Each row
corresponds to a single data point.
Returns
-------
responsibilities : array, shape (n_samples, n_components)
Posterior probabilities of each mixture component for each
observation.
"""
self.random_state_ = check_random_state(self.random_state)
# initialization step
X = check_array(X)
if X.ndim == 1:
X = X[:, np.newaxis]
n_samples, n_features = X.shape
z = np.ones((n_samples, self.n_components))
z /= self.n_components
self._initial_bound = - 0.5 * n_features * np.log(2 * np.pi)
self._initial_bound -= np.log(2 * np.pi * np.e)
if (self.init_params != '') or not hasattr(self, 'gamma_'):
self._initialize_gamma()
if 'm' in self.init_params or not hasattr(self, 'means_'):
self.means_ = cluster.KMeans(
n_clusters=self.n_components,
random_state=self.random_state_).fit(X).cluster_centers_[::-1]
if 'w' in self.init_params or not hasattr(self, 'weights_'):
self.weights_ = np.tile(1.0 / self.n_components, self.n_components)
if 'c' in self.init_params or not hasattr(self, 'precs_'):
if self.covariance_type == 'spherical':
self.dof_ = np.ones(self.n_components)
self.scale_ = np.ones(self.n_components)
self.precs_ = np.ones((self.n_components, n_features))
self.bound_prec_ = 0.5 * n_features * (
digamma(self.dof_) - np.log(self.scale_))
elif self.covariance_type == 'diag':
self.dof_ = 1 + 0.5 * n_features
self.dof_ *= np.ones((self.n_components, n_features))
self.scale_ = np.ones((self.n_components, n_features))
self.precs_ = np.ones((self.n_components, n_features))
self.bound_prec_ = 0.5 * (np.sum(digamma(self.dof_) -
np.log(self.scale_), 1))
self.bound_prec_ -= 0.5 * np.sum(self.precs_, 1)
elif self.covariance_type == 'tied':
self.dof_ = 1.
self.scale_ = np.identity(n_features)
self.precs_ = np.identity(n_features)
self.det_scale_ = 1.
self.bound_prec_ = 0.5 * wishart_log_det(
self.dof_, self.scale_, self.det_scale_, n_features)
self.bound_prec_ -= 0.5 * self.dof_ * np.trace(self.scale_)
elif self.covariance_type == 'full':
self.dof_ = (1 + self.n_components + n_samples)
self.dof_ *= np.ones(self.n_components)
self.scale_ = [2 * np.identity(n_features)
for _ in range(self.n_components)]
self.precs_ = [np.identity(n_features)
for _ in range(self.n_components)]
self.det_scale_ = np.ones(self.n_components)
self.bound_prec_ = np.zeros(self.n_components)
for k in range(self.n_components):
self.bound_prec_[k] = wishart_log_det(
self.dof_[k], self.scale_[k], self.det_scale_[k],
n_features)
self.bound_prec_[k] -= (self.dof_[k] *
np.trace(self.scale_[k]))
self.bound_prec_ *= 0.5
# EM algorithms
current_log_likelihood = None
# reset self.converged_ to False
self.converged_ = False
for i in range(self.n_iter):
prev_log_likelihood = current_log_likelihood
# Expectation step
curr_logprob, z = self.score_samples(X)
current_log_likelihood = (
curr_logprob.mean() + self._logprior(z) / n_samples)
# Check for convergence.
if prev_log_likelihood is not None:
change = abs(current_log_likelihood - prev_log_likelihood)
if change < self.tol:
self.converged_ = True
break
# Maximization step
self._do_mstep(X, z, self.params)
if self.n_iter == 0:
# Need to make sure that there is a z value to output
# Output zeros because it was just a quick initialization
z = np.zeros((X.shape[0], self.n_components))
self._set_weights()
return z
@deprecated("The `DPGMM` class is not working correctly and it's better "
"to use `sklearn.mixture.BayesianGaussianMixture` class with "
"parameter `weight_concentration_prior_type='dirichlet_process'` "
"instead. DPGMM is deprecated in 0.18 and will be "
"removed | |
<filename>sdk/python/kfp/v2/google/aiplatform.py
# Copyright 2021 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.
"""Connector components of Google AI Platform (Unified) services."""
from typing import Any, Dict, List, Optional, Type, Union
from absl import logging
import collections
from kfp import dsl
from kfp.components import _structures
from kfp.dsl import io_types
from kfp.pipeline_spec import pipeline_spec_pb2
from kfp.dsl import dsl_utils
from kfp.dsl import type_utils
_AIPlatformCustomJobSpec = pipeline_spec_pb2.PipelineDeploymentConfig.AIPlatformCustomJobSpec
_DUMMY_CONTAINER_OP_IMAGE = 'dummy/image'
_DUMMY_PATH = 'dummy/path'
_MAX_PACKAGE_URIS = 100
_DEFAULT_CUSTOM_JOB_MACHINE_TYPE = 'n1-standard-4'
_ValueOrPipelineParam = Union[dsl.PipelineParam, str, float, int]
# TODO: Support all declared types in
# components._structures.CommandlineArgumenType
_CommandlineArgumentType = Union[str, int, float,
_structures.InputValuePlaceholder,
_structures.InputPathPlaceholder,
_structures.OutputPathPlaceholder,
_structures.InputUriPlaceholder,
_structures.OutputUriPlaceholder,]
# TODO: extract this to a utils module, and share with dsl.component_bridge
def _input_artifact_uri_placeholder(input_key: str) -> str:
return "{{{{$.inputs.artifacts['{}'].uri}}}}".format(input_key)
def _input_artifact_path_placeholder(input_key: str) -> str:
return "{{{{$.inputs.artifacts['{}'].path}}}}".format(input_key)
def _input_parameter_placeholder(input_key: str) -> str:
return "{{{{$.inputs.parameters['{}']}}}}".format(input_key)
def _output_artifact_uri_placeholder(output_key: str) -> str:
return "{{{{$.outputs.artifacts['{}'].uri}}}}".format(output_key)
def _output_artifact_path_placeholder(output_key: str) -> str:
return "{{{{$.outputs.artifacts['{}'].path}}}}".format(output_key)
def _output_parameter_path_placeholder(output_key: str) -> str:
return "{{{{$.outputs.parameters['{}'].output_file}}}}".format(output_key)
class AiPlatformCustomJobOp(dsl.ContainerOp):
"""V2 AiPlatformCustomJobOp class.
This class inherits V1 ContainerOp class so that it can be correctly picked
by compiler. The implementation of the task is an AiPlatformCustomJobSpec
proto message.
"""
def __init__(self,
name: str,
custom_job_spec: Dict[str, Any],
component_spec: pipeline_spec_pb2.ComponentSpec,
task_spec: pipeline_spec_pb2.PipelineTaskSpec,
task_inputs: Optional[List[dsl.InputArgumentPath]] = None,
task_outputs: Optional[Dict[str, str]] = None):
"""Instantiates the AiPlatformCustomJobOp object.
Args:
name: Name of the task.
custom_job_spec: JSON struct of the CustomJob spec, representing the job
that will be submitted to AI Platform (Unified) service. See
https://cloud.google.com/ai-platform-unified/docs/reference/rest/v1beta1/CustomJobSpec
for detailed reference.
task_inputs: Optional. List of InputArgumentPath of this task. Each
InputArgumentPath object has 3 attributes: input, path and argument we
actually only care about the input, which will be translated to the
input name of the component spec. Path and argument are tied to
artifact argument in Argo, which is not used in this case.
task_outputs: Optional. Mapping of task outputs to its URL.
"""
old_warn_value = dsl.ContainerOp._DISABLE_REUSABLE_COMPONENT_WARNING
dsl.ContainerOp._DISABLE_REUSABLE_COMPONENT_WARNING = True
super().__init__(
name=name,
image=_DUMMY_CONTAINER_OP_IMAGE,
artifact_argument_paths=task_inputs,
file_outputs=task_outputs)
self.component_spec = component_spec
self.task_spec = task_spec
self.custom_job_spec = custom_job_spec
dsl.ContainerOp._DISABLE_REUSABLE_COMPONENT_WARNING = old_warn_value
def _get_custom_job_op(
task_name: str,
job_spec: Dict[str, Any],
input_artifacts: Optional[Dict[str, dsl.PipelineParam]] = None,
input_parameters: Optional[Dict[str, _ValueOrPipelineParam]] = None,
output_artifacts: Optional[Dict[str, Type[io_types.Artifact]]] = None,
output_parameters: Optional[Dict[str, Any]] = None,
) -> AiPlatformCustomJobOp:
"""Gets an AiPlatformCustomJobOp from job spec and I/O definition."""
pipeline_task_spec = pipeline_spec_pb2.PipelineTaskSpec()
pipeline_component_spec = pipeline_spec_pb2.ComponentSpec()
pipeline_task_spec.task_info.CopyFrom(
pipeline_spec_pb2.PipelineTaskInfo(
name=dsl_utils.sanitize_task_name(task_name)))
# Iterate through the inputs/outputs declaration to get pipeline component
# spec.
for input_name, param in input_parameters.items():
if isinstance(param, dsl.PipelineParam):
pipeline_component_spec.input_definitions.parameters[
input_name].type = type_utils.get_parameter_type(param.param_type)
else:
pipeline_component_spec.input_definitions.parameters[
input_name].type = type_utils.get_parameter_type(type(param))
for input_name, art in input_artifacts.items():
if not isinstance(art, dsl.PipelineParam):
raise RuntimeError('Get unresolved input artifact for input %s. Input '
'artifacts must be connected to a producer task.' %
input_name)
pipeline_component_spec.input_definitions.artifacts[
input_name].artifact_type.CopyFrom(
type_utils.get_artifact_type_schema(art.param_type))
for output_name, param_type in output_parameters.items():
pipeline_component_spec.output_definitions.parameters[
output_name].type = type_utils.get_parameter_type(param_type)
for output_name, artifact_type in output_artifacts.items():
pipeline_component_spec.output_definitions.artifacts[
output_name].artifact_type.CopyFrom(
type_utils.get_artifact_type_schema(artifact_type))
pipeline_component_spec.executor_label = dsl_utils.sanitize_executor_label(
task_name)
# Iterate through the inputs/outputs specs to get pipeline task spec.
for input_name, param in input_parameters.items():
if isinstance(param, dsl.PipelineParam) and param.op_name:
# If the param has a valid op_name, this should be a pipeline parameter
# produced by an upstream task.
pipeline_task_spec.inputs.parameters[input_name].CopyFrom(
pipeline_spec_pb2.TaskInputsSpec.InputParameterSpec(
task_output_parameter=pipeline_spec_pb2.TaskInputsSpec
.InputParameterSpec.TaskOutputParameterSpec(
producer_task=dsl_utils.sanitize_task_name(param.op_name),
output_parameter_key=param.name)))
elif isinstance(param, dsl.PipelineParam) and not param.op_name:
# If a valid op_name is missing, this should be a pipeline parameter.
pipeline_task_spec.inputs.parameters[input_name].CopyFrom(
pipeline_spec_pb2.TaskInputsSpec.InputParameterSpec(
component_input_parameter=param.name))
else:
# If this is not a pipeline param, then it should be a value.
pipeline_task_spec.inputs.parameters[input_name].CopyFrom(
pipeline_spec_pb2.TaskInputsSpec.InputParameterSpec(
runtime_value=pipeline_spec_pb2.ValueOrRuntimeParameter(
constant_value=dsl_utils.get_value(param))))
for input_name, art in input_artifacts.items():
if art.op_name:
# If the param has a valid op_name, this should be an artifact produced
# by an upstream task.
pipeline_task_spec.inputs.artifacts[input_name].CopyFrom(
pipeline_spec_pb2.TaskInputsSpec.InputArtifactSpec(
task_output_artifact=pipeline_spec_pb2.TaskInputsSpec
.InputArtifactSpec.TaskOutputArtifactSpec(
producer_task=dsl_utils.sanitize_task_name(art.op_name),
output_artifact_key=art.name)))
else:
# Otherwise, this should be from the input of the subdag.
pipeline_task_spec.inputs.artifacts[input_name].CopyFrom(
pipeline_spec_pb2.TaskInputsSpec.InputArtifactSpec(
component_input_artifact=art.name))
# TODO: Add task dependencies/trigger policies/caching/iterator
pipeline_task_spec.component_ref.name = dsl_utils.sanitize_component_name(
task_name)
# Construct dummy I/O declaration for the op.
# TODO: resolve name conflict instead of raising errors.
dummy_outputs = collections.OrderedDict()
for output_name, _ in output_artifacts.items():
dummy_outputs[output_name] = _DUMMY_PATH
for output_name, _ in output_parameters.items():
if output_name in dummy_outputs:
raise KeyError('Got name collision for output key %s. Consider renaming '
'either output parameters or output '
'artifacts.' % output_name)
dummy_outputs[output_name] = _DUMMY_PATH
dummy_inputs = collections.OrderedDict()
for input_name, art in input_artifacts.items():
dummy_inputs[input_name] = _DUMMY_PATH
for input_name, param in input_parameters.items():
if input_name in dummy_inputs:
raise KeyError('Got name collision for input key %s. Consider renaming '
'either input parameters or input '
'artifacts.' % input_name)
dummy_inputs[input_name] = _DUMMY_PATH
# Construct the AIP (Unified) custom job op.
return AiPlatformCustomJobOp(
name=task_name,
custom_job_spec=job_spec,
component_spec=pipeline_component_spec,
task_spec=pipeline_task_spec,
task_inputs=[
dsl.InputArgumentPath(
argument=dummy_inputs[input_name],
input=input_name,
path=path,
) for input_name, path in dummy_inputs.items()
],
task_outputs=dummy_outputs)
def custom_job(
name: str,
input_artifacts: Optional[Dict[str, dsl.PipelineParam]] = None,
input_parameters: Optional[Dict[str, _ValueOrPipelineParam]] = None,
output_artifacts: Optional[Dict[str, Type[io_types.Artifact]]] = None,
output_parameters: Optional[Dict[str, Type[Union[str, float, int]]]] = None,
# Custom container training specs.
image_uri: Optional[str] = None,
commands: Optional[List[str]] = None,
# Custom Python training spec.
executor_image_uri: Optional[str] = None,
package_uris: Optional[List[str]] = None,
python_module: Optional[str] = None,
# Command line args of the user program.
args: Optional[List[Any]] = None,
machine_type: Optional[str] = None,
# Full-fledged custom job API spec. For details please see:
# https://cloud.google.com/ai-platform-unified/docs/reference/rest/v1beta1/CustomJobSpec
additional_job_spec: Optional[Dict[str, Any]] = None
) -> AiPlatformCustomJobOp:
"""DSL representation of a AI Platform (Unified) custom training job.
For detailed doc of the service, please refer to
https://cloud.google.com/ai-platform-unified/docs/training/create-custom-job
Args:
name: The name of this task.
input_artifacts: The input artifact specification. Should be a mapping from
input name to output from upstream tasks.
input_parameters: The input parameter specification. Should be a mapping
from input name to one of the following three: - output from upstream
tasks, or - pipeline parameter, or - constant value
output_artifacts: The output artifact declaration. Should be a mapping from
output name to a type subclassing artifact.Artifact.
output_parameters: The output parameter declaration. Should be a mapping
from output name to one of 1) str, 2) float, or 3) int.
image_uri: The URI of the container image containing the user training
program. Applicable for custom container training.
commands: The container command/entrypoint. Applicable for custom container
training.
executor_image_uri: The URI of the container image containing the
dependencies of user training program. Applicable for custom Python
training.
package_uris: The Python packages that are expected to be running on the
executor container. Applicable for custom Python training.
python_module: The entrypoint of user training program. Applicable for
custom Python training.
args: The command line arguments of user training program. This is expected
to be a list of either 1) constant string, or 2) KFP DSL placeholders, to
connect the user program with the declared component I/O.
machine_type: The machine type used to run the training program. The value
of this field will be propagated to all worker pools if not specified
otherwise in additional_job_spec.
additional_job_spec: Full-fledged custom job API spec. The value specified
in this field will override the defaults provided through other function
parameters.
For details please see:
https://cloud.google.com/ai-platform-unified/docs/reference/rest/v1beta1/CustomJobSpec
Returns:
A KFP ContainerOp object represents the launcher container job, from which
the user training program will be submitted to AI Platform (Unified) Custom
Job service.
Raises:
KeyError on name collision between parameter and artifact I/O declaration.
ValueError when:
1. neither or both image_uri and executor_image_uri are provided; or
2. no valid package_uris and python_module is provided for custom Python
training.
"""
# Check the sanity of the provided parameters.
input_artifacts = input_artifacts or {}
input_parameters = input_parameters or {}
output_artifacts = output_artifacts or {}
output_parameters = output_parameters or {}
if bool(set(input_artifacts.keys()) & set(input_parameters.keys())):
raise KeyError('Input key conflict between input parameters and artifacts.')
if bool(set(output_artifacts.keys()) & set(output_parameters.keys())):
raise KeyError('Output key conflict between output parameters and '
'artifacts.')
if not additional_job_spec and bool(image_uri) == bool(executor_image_uri):
raise ValueError('The user program needs to be either a custom container '
'training job, | |
131
self.SQL_CREATE_TABLE = 132
self.SQL_CREATE_TRANSLATION = 133
self.SQL_CREATE_VIEW = 134
self.SQL_DRIVER_HDESC = 135
self.SQL_DROP_ASSERTION = 136
self.SQL_DROP_CHARACTER_SET = 137
self.SQL_DROP_COLLATION = 138
self.SQL_DROP_DOMAIN = 139
self.SQL_DROP_SCHEMA = 140
self.SQL_DROP_TABLE = 141
self.SQL_DROP_TRANSLATION = 142
self.SQL_DROP_VIEW = 143
self.SQL_DYNAMIC_CURSOR_ATTRIBUTES1 = 144
self.SQL_DYNAMIC_CURSOR_ATTRIBUTES2 = 145
self.SQL_FORWARD_ONLY_CURSOR_ATTRIBUTES1 = 146
self.SQL_FORWARD_ONLY_CURSOR_ATTRIBUTES2 = 147
self.SQL_INDEX_KEYWORDS = 148
self.SQL_INFO_SCHEMA_VIEWS = 149
self.SQL_KEYSET_CURSOR_ATTRIBUTES1 = 150
self.SQL_KEYSET_CURSOR_ATTRIBUTES2 = 151
self.SQL_MAX_ASYNC_CONCURRENT_STATEMENTS = 10022
self.SQL_ODBC_INTERFACE_CONFORMANCE = 152
self.SQL_PARAM_ARRAY_ROW_COUNTS = 153
self.SQL_PARAM_ARRAY_SELECTS = 154
self.SQL_SCHEMA_TERM = self.SQL_OWNER_TERM
self.SQL_SCHEMA_USAGE = self.SQL_OWNER_USAGE
self.SQL_SQL92_DATETIME_FUNCTIONS = 155
self.SQL_SQL92_FOREIGN_KEY_DELETE_RULE = 156
self.SQL_SQL92_FOREIGN_KEY_UPDATE_RULE = 157
self.SQL_SQL92_GRANT = 158
self.SQL_SQL92_NUMERIC_VALUE_FUNCTIONS = 159
self.SQL_SQL92_PREDICATES = 160
self.SQL_SQL92_RELATIONAL_JOIN_OPERATORS = 161
self.SQL_SQL92_REVOKE = 162
self.SQL_SQL92_ROW_VALUE_CONSTRUCTOR = 163
self.SQL_SQL92_STRING_FUNCTIONS = 164
self.SQL_SQL92_VALUE_EXPRESSIONS = 165
self.SQL_STANDARD_CLI_CONFORMANCE = 166
self.SQL_STATIC_CURSOR_ATTRIBUTES1 = 167
self.SQL_STATIC_CURSOR_ATTRIBUTES2 = 168
self.SQL_AGGREGATE_FUNCTIONS = 169
self.SQL_DDL_INDEX = 170
self.SQL_DM_VER = 171
self.SQL_INSERT_STATEMENT = 172
self.SQL_UNION_STATEMENT = self.SQL_UNION
self.SQL_DTC_TRANSITION_COST = 1750
################################################################################
####SQLGetInfo - SQL_AGGREGATE_FUNCTIONS########################################
################################################################################
self.SQL_AF_AVG = 0x00000001
self.SQL_AF_COUNT = 0x00000002
self.SQL_AF_MAX = 0x00000004
self.SQL_AF_MIN = 0x00000008
self.SQL_AF_SUM = 0x00000010
self.SQL_AF_DISTINCT = 0x00000020
self.SQL_AF_ALL = 0x00000040
################################################################################
####SQLGetInfo - SQL_ALTER_DOMAIN###############################################
################################################################################
self.SQL_AD_CONSTRAINT_NAME_DEFINITION = 0x00000001
self.SQL_AD_ADD_DOMAIN_CONSTRAINT = 0x00000002
self.SQL_AD_DROP_DOMAIN_CONSTRAINT = 0x00000004
self.SQL_AD_ADD_DOMAIN_DEFAULT = 0x00000008
self.SQL_AD_DROP_DOMAIN_DEFAULT = 0x00000010
self.SQL_AD_ADD_CONSTRAINT_INITIALLY_DEFERRED = 0x00000020
self.SQL_AD_ADD_CONSTRAINT_INITIALLY_IMMEDIATE = 0x00000040
self.SQL_AD_ADD_CONSTRAINT_DEFERRABLE = 0x00000080
self.SQL_AD_ADD_CONSTRAINT_NON_DEFERRABLE = 0x00000100
################################################################################
####SQLGetInfo - SQL_ALTER_TABLE################################################
################################################################################
################################################################################
####The following 5 bitmasks are defined in sql.h###############################
################################################################################
####SQL_AT_ADD_COLUMN = 0x00000001##############################################
####SQL_AT_DROP_COLUMN = 0x00000002#############################################
####SQL_AT_ADD_CONSTRAINT = 0x00000008##########################################
################################################################################
self.SQL_AT_ADD_COLUMN_SINGLE = 0x00000020
self.SQL_AT_ADD_COLUMN_DEFAULT = 0x00000040
self.SQL_AT_ADD_COLUMN_COLLATION = 0x00000080
self.SQL_AT_SET_COLUMN_DEFAULT = 0x00000100
self.SQL_AT_DROP_COLUMN_DEFAULT = 0x00000200
self.SQL_AT_DROP_COLUMN_CASCADE = 0x00000400
self.SQL_AT_DROP_COLUMN_RESTRICT = 0x00000800
self.SQL_AT_ADD_TABLE_CONSTRAINT = 0x00001000
self.SQL_AT_DROP_TABLE_CONSTRAINT_CASCADE = 0x00002000
self.SQL_AT_DROP_TABLE_CONSTRAINT_RESTRICT = 0x00004000
self.SQL_AT_CONSTRAINT_NAME_DEFINITION = 0x00008000
self.SQL_AT_CONSTRAINT_INITIALLY_DEFERRED = 0x00010000
self.SQL_AT_CONSTRAINT_INITIALLY_IMMEDIATE = 0x00020000
self.SQL_AT_CONSTRAINT_DEFERRABLE = 0x00040000
self.SQL_AT_CONSTRAINT_NON_DEFERRABLE = 0x00080000
################################################################################
####SQLGetInfo - SQL_ASYNC_MODE#################################################
################################################################################
self.SQL_AM_NONE = 0
self.SQL_AM_CONNECTION = 1
self.SQL_AM_STATEMENT = 2
################################################################################
####SQLGetInfo - SQL_BATCH_ROW_COUNT############################################
################################################################################
self.SQL_BRC_PROCEDURES = 0x0000001
self.SQL_BRC_EXPLICIT = 0x0000002
self.SQL_BRC_ROLLED_UP = 0x0000004
################################################################################
####SQLGetInfo - SQL_BATCH_SUPPORT##############################################
################################################################################
self.SQL_BS_SELECT_EXPLICIT = 0x00000001
self.SQL_BS_ROW_COUNT_EXPLICIT = 0x00000002
self.SQL_BS_SELECT_PROC = 0x00000004
self.SQL_BS_ROW_COUNT_PROC = 0x00000008
################################################################################
####SQLGetInfo - SQL_BOOKMARK_PERSISTENCE#######################################
################################################################################
self.SQL_BP_CLOSE = 0x00000001
self.SQL_BP_DELETE = 0x00000002
self.SQL_BP_DROP = 0x00000004
self.SQL_BP_TRANSACTION = 0x00000008
self.SQL_BP_UPDATE = 0x00000010
self.SQL_BP_OTHER_HSTMT = 0x00000020
self.SQL_BP_SCROLL = 0x00000040
################################################################################
####SQLGetInfo - SQL_CONCAT_NULL_BEHAVIOR#######################################
################################################################################
self.SQL_CB_NULL = 0x0000
self.SQL_CB_NON_NULL = 0x0001
################################################################################
####SQLGetInfo - SQL_CONVERT_* bitmask values###################################
################################################################################
self.SQL_CVT_CHAR = 0x00000001
self.SQL_CVT_NUMERIC = 0x00000002
self.SQL_CVT_DECIMAL = 0x00000004
self.SQL_CVT_INTEGER = 0x00000008
self.SQL_CVT_SMALLINT = 0x00000010
self.SQL_CVT_FLOAT = 0x00000020
self.SQL_CVT_REAL = 0x00000040
self.SQL_CVT_DOUBLE = 0x00000080
self.SQL_CVT_VARCHAR = 0x00000100
self.SQL_CVT_LONGVARCHAR = 0x00000200
self.SQL_CVT_BINARY = 0x00000400
self.SQL_CVT_VARBINARY = 0x00000800
self.SQL_CVT_BIT = 0x00001000
self.SQL_CVT_TINYINT = 0x00002000
self.SQL_CVT_BIGINT = 0x00004000
self.SQL_CVT_DATE = 0x00008000
self.SQL_CVT_TIME = 0x00010000
self.SQL_CVT_TIMESTAMP = 0x00020000
self.SQL_CVT_LONGVARBINARY = 0x00040000
self.SQL_CVT_INTERVAL_YEAR_MONTH = 0x00080000
self.SQL_CVT_INTERVAL_DAY_TIME = 0x00100000
self.SQL_CVT_WCHAR = 0x00200000
self.SQL_CVT_WLONGVARCHAR = 0x00400000
self.SQL_CVT_WVARCHAR = 0x00800000
################################################################################
####SQLGetInfo - SQL_CONVERT_FUNCTIONS##########################################
################################################################################
self.SQL_FN_CVT_CONVERT = 0x00000001
self.SQL_FN_CVT_CAST = 0x00000002
################################################################################
####SQLGetInfo - SQL_CORRELATION_NAME###########################################
################################################################################
self.SQL_CN_NONE = 0x0000
self.SQL_CN_DIFFERENT = 0x0001
self.SQL_CN_ANY = 0x0002
################################################################################
####SQLGetInfo - SQL_CREATE_ASSERTION###########################################
################################################################################
self.SQL_CA_CREATE_ASSERTION = 0x00000001
self.SQL_CA_CONSTRAINT_INITIALLY_DEFERRED = 0x00000010
self.SQL_CA_CONSTRAINT_INITIALLY_IMMEDIATE = 0x00000020
self.SQL_CA_CONSTRAINT_DEFERRABLE = 0x00000040
self.SQL_CA_CONSTRAINT_NON_DEFERRABLE = 0x00000080
################################################################################
####SQLGetInfo - SQL_CREATE_CHARACTER_SET#######################################
################################################################################
self.SQL_CCS_CREATE_CHARACTER_SET = 0x00000001
self.SQL_CCS_COLLATE_CLAUSE = 0x00000002
self.SQL_CCS_LIMITED_COLLATION = 0x00000004
################################################################################
####SQLGetInfo - SQL_CREATE_COLLATION###########################################
################################################################################
self.SQL_CCOL_CREATE_COLLATION = 0x00000001
################################################################################
####SQLGetInfo - SQL_CREATE_DOMAIN##############################################
################################################################################
self.SQL_CDO_CREATE_DOMAIN = 0x00000001
self.SQL_CDO_DEFAULT = 0x00000002
self.SQL_CDO_CONSTRAINT = 0x00000004
self.SQL_CDO_COLLATION = 0x00000008
self.SQL_CDO_CONSTRAINT_NAME_DEFINITION = 0x00000010
self.SQL_CDO_CONSTRAINT_INITIALLY_DEFERRED = 0x00000020
self.SQL_CDO_CONSTRAINT_INITIALLY_IMMEDIATE = 0x00000040
self.SQL_CDO_CONSTRAINT_DEFERRABLE = 0x00000080
self.SQL_CDO_CONSTRAINT_NON_DEFERRABLE = 0x00000100
################################################################################
####SQLGetInfo - SQL_CREATE_SCHEMA##############################################
################################################################################
self.SQL_CS_CREATE_SCHEMA = 0x00000001
self.SQL_CS_AUTHORIZATION = 0x00000002
self.SQL_CS_DEFAULT_CHARACTER_SET = 0x00000004
################################################################################
####SQLGetInfo - SQL_CREATE_TABLE###############################################
################################################################################
self.SQL_CT_CREATE_TABLE = 0x00000001
self.SQL_CT_COMMIT_PRESERVE = 0x00000002
self.SQL_CT_COMMIT_DELETE = 0x00000004
self.SQL_CT_GLOBAL_TEMPORARY = 0x00000008
self.SQL_CT_LOCAL_TEMPORARY = 0x00000010
self.SQL_CT_CONSTRAINT_INITIALLY_DEFERRED = 0x00000020
self.SQL_CT_CONSTRAINT_INITIALLY_IMMEDIATE = 0x00000040
self.SQL_CT_CONSTRAINT_DEFERRABLE = 0x00000080
self.SQL_CT_CONSTRAINT_NON_DEFERRABLE = 0x00000100
self.SQL_CT_COLUMN_CONSTRAINT = 0x00000200
self.SQL_CT_COLUMN_DEFAULT = 0x00000400
self.SQL_CT_COLUMN_COLLATION = 0x00000800
self.SQL_CT_TABLE_CONSTRAINT = 0x00001000
self.SQL_CT_CONSTRAINT_NAME_DEFINITION = 0x00002000
################################################################################
####SQLGetInfo - SQL_CREATE_TRANSLATION#########################################
################################################################################
self.SQL_CTR_CREATE_TRANSLATION = 0x00000001
################################################################################
####SQLGetInfo - SQL_CREATE_VIEW################################################
################################################################################
self.SQL_CV_CREATE_VIEW = 0x00000001
self.SQL_CV_CHECK_OPTION = 0x00000002
self.SQL_CV_CASCADED = 0x00000004
self.SQL_CV_LOCAL = 0x00000008
################################################################################
####SQLGetInfo - SQL_DATETIME_LITERALS##########################################
################################################################################
self.SQL_DL_SQL92_DATE = 0x00000001
self.SQL_DL_SQL92_TIME = 0x00000002
self.SQL_DL_SQL92_TIMESTAMP = 0x00000004
self.SQL_DL_SQL92_INTERVAL_YEAR = 0x00000008
self.SQL_DL_SQL92_INTERVAL_MONTH = 0x00000010
self.SQL_DL_SQL92_INTERVAL_DAY = 0x00000020
self.SQL_DL_SQL92_INTERVAL_HOUR = 0x00000040
self.SQL_DL_SQL92_INTERVAL_MINUTE = 0x00000080
self.SQL_DL_SQL92_INTERVAL_SECOND = 0x00000100
self.SQL_DL_SQL92_INTERVAL_YEAR_TO_MONTH = 0x00000200
self.SQL_DL_SQL92_INTERVAL_DAY_TO_HOUR = 0x00000400
self.SQL_DL_SQL92_INTERVAL_DAY_TO_MINUTE = 0x00000800
self.SQL_DL_SQL92_INTERVAL_DAY_TO_SECOND = 0x00001000
self.SQL_DL_SQL92_INTERVAL_HOUR_TO_MINUTE = 0x00002000
self.SQL_DL_SQL92_INTERVAL_HOUR_TO_SECOND = 0x00004000
self.SQL_DL_SQL92_INTERVAL_MINUTE_TO_SECOND = 0x00008000
################################################################################
####SQLGetInfo - SQL_DDL_INDEX##################################################
################################################################################
self.SQL_DI_CREATE_INDEX = 0x00000001
self.SQL_DI_DROP_INDEX = 0x00000002
################################################################################
####SQLGetInfo - SQL_DROP_ASSERTION#############################################
################################################################################
self.SQL_DA_DROP_ASSERTION = 0x00000001
################################################################################
####SQLGetInfo - SQL_DROP_CHARACTER_SET#########################################
################################################################################
self.SQL_DCS_DROP_CHARACTER_SET = 0x00000001
################################################################################
####SQLGetInfo - SQL_DROP_COLLATION#############################################
################################################################################
self.SQL_DC_DROP_COLLATION = 0x00000001
################################################################################
####SQLGetInfo - SQL_DROP_DOMAIN################################################
################################################################################
self.SQL_DD_DROP_DOMAIN = 0x00000001
self.SQL_DD_RESTRICT = 0x00000002
self.SQL_DD_CASCADE = 0x00000004
################################################################################
####SQLGetInfo - SQL_DROP_SCHEMA################################################
################################################################################
self.SQL_DS_DROP_SCHEMA = 0x00000001
self.SQL_DS_RESTRICT = 0x00000002
self.SQL_DS_CASCADE = 0x00000004
################################################################################
####SQLGetInfo - SQL_DROP_TABLE#################################################
################################################################################
self.SQL_DT_DROP_TABLE = 0x00000001
self.SQL_DT_RESTRICT = 0x00000002
self.SQL_DT_CASCADE = 0x00000004
################################################################################
####SQLGetInfo - SQL_DROP_TRANSLATION###########################################
################################################################################
self.SQL_DTR_DROP_TRANSLATION = 0x00000001
################################################################################
####SQLGetInfo - SQL_DROP_VIEW##################################################
################################################################################
self.SQL_DV_DROP_VIEW = 0x00000001
self.SQL_DV_RESTRICT = 0x00000002
self.SQL_DV_CASCADE = 0x00000004
################################################################################
####SQLGetInfo - SQL_DTC_TRANSITION_COST########################################
################################################################################
self.SQL_DTC_ENLIST_EXPENSIVE = 0x00000001
self.SQL_DTC_UNENLIST_EXPENSIVE = 0x00000002
################################################################################
####SQLGetInfo - SQL_DYNAMIC_CURSOR_ATTRIBUTES1#################################
####SQLGetInfo - SQL_FORWARD_ONLY_CURSOR_ATTRIBUTES1############################
####SQLGetInfo - SQL_KEYSET_CURSOR_ATTRIBUTES1##################################
####SQLGetInfo - SQL_STATIC_CURSOR_ATTRIBUTES1##################################
################################################################################
################################################################################
####SQLFetchScroll - FetchOrientation###########################################
################################################################################
self.SQL_CA1_NEXT = 0x00000001
self.SQL_CA1_ABSOLUTE = 0x00000002
self.SQL_CA1_RELATIVE = 0x00000004
self.SQL_CA1_BOOKMARK = 0x00000008
################################################################################
####SQLSetPos - LockType########################################################
################################################################################
self.SQL_CA1_LOCK_NO_CHANGE = 0x00000040
self.SQL_CA1_LOCK_EXCLUSIVE = 0x00000080
self.SQL_CA1_LOCK_UNLOCK = 0x00000100
################################################################################
####SQLSetPos Operations########################################################
################################################################################
self.SQL_CA1_POS_POSITION = 0x00000200
self.SQL_CA1_POS_UPDATE = 0x00000400
self.SQL_CA1_POS_DELETE = 0x00000800
self.SQL_CA1_POS_REFRESH = 0x00001000
################################################################################
####positioned updates and deletes##############################################
################################################################################
self.SQL_CA1_POSITIONED_UPDATE = 0x00002000
self.SQL_CA1_POSITIONED_DELETE = 0x00004000
self.SQL_CA1_SELECT_FOR_UPDATE = 0x00008000
################################################################################
####SQLBulkOperations operations################################################
################################################################################
self.SQL_CA1_BULK_ADD = 0x00010000
self.SQL_CA1_BULK_UPDATE_BY_BOOKMARK = 0x00020000
self.SQL_CA1_BULK_DELETE_BY_BOOKMARK = 0x00040000
self.SQL_CA1_BULK_FETCH_BY_BOOKMARK = 0x00080000
################################################################################
####SQLGetInfo - SQL_DYNAMIC_CURSOR_ATTRIBUTES2#################################
####SQLGetInfo - SQL_FORWARD_ONLY_CURSOR_ATTRIBUTES2############################
####SQLGetInfo - SQL_KEYSET_CURSOR_ATTRIBUTES2##################################
####SQLGetInfo - SQL_STATIC_CURSOR_ATTRIBUTES2##################################
################################################################################
################################################################################
####SQL_ATTR_SCROLL_CONCURRENCY#################################################
################################################################################
self.SQL_CA2_READ_ONLY_CONCURRENCY = 0x00000001
self.SQL_CA2_LOCK_CONCURRENCY = 0x00000002
self.SQL_CA2_OPT_ROWVER_CONCURRENCY = 0x00000004
self.SQL_CA2_OPT_VALUES_CONCURRENCY = 0x00000008
################################################################################
####sensitivity of the cursor to its own inserts, deletes, and updates##########
################################################################################
self.SQL_CA2_SENSITIVITY_ADDITIONS = 0x00000010
self.SQL_CA2_SENSITIVITY_DELETIONS = 0x00000020
self.SQL_CA2_SENSITIVITY_UPDATES = 0x00000040
################################################################################
####SQL_ATTR_MAX_ROWS###########################################################
################################################################################
self.SQL_CA2_MAX_ROWS_SELECT = 0x00000080
self.SQL_CA2_MAX_ROWS_INSERT = 0x00000100
self.SQL_CA2_MAX_ROWS_DELETE = 0x00000200
self.SQL_CA2_MAX_ROWS_UPDATE = 0x00000400
self.SQL_CA2_MAX_ROWS_CATALOG = 0x00000800
self.SQL_CA2_MAX_ROWS_AFFECTS_ALL = self.SQL_CA2_MAX_ROWS_SELECT |\
self.SQL_CA2_MAX_ROWS_INSERT |\
self.SQL_CA2_MAX_ROWS_DELETE |\
self.SQL_CA2_MAX_ROWS_UPDATE |\
self.SQL_CA2_MAX_ROWS_CATALOG
################################################################################
####SQL_DIAG_CURSOR_ROW_COUNT###################################################
################################################################################
self.SQL_CA2_CRC_EXACT = 0x00001000
self.SQL_CA2_CRC_APPROXIMATE = 0x00002000
################################################################################
####the kinds of positioned statements that can be simulated####################
################################################################################
self.SQL_CA2_SIMULATE_NON_UNIQUE = 0x00004000
self.SQL_CA2_SIMULATE_TRY_UNIQUE = 0x00008000
self.SQL_CA2_SIMULATE_UNIQUE = 0x00010000
################################################################################
####SQLGetInfo - SQL_FETCH_DIRECTION############################################
################################################################################
self.SQL_FD_FETCH_RESUME = 0x00000040
self.SQL_FD_FETCH_BOOKMARK = 0x00000080
################################################################################
####SQLGetInfo - SQL_FILE_USAGE#################################################
################################################################################
self.SQL_FILE_NOT_SUPPORTED = 0x0000
self.SQL_FILE_TABLE = 0x0001
self.SQL_FILE_QUALIFIER = 0x0002
self.SQL_FILE_CATALOG = self.SQL_FILE_QUALIFIER
################################################################################
####SQLGetInfo - SQL_GETDATA_EXTENSIONS#########################################
################################################################################
self.SQL_GD_BLOCK = 0x00000004
self.SQL_GD_BOUND = 0x00000008
################################################################################
####SQLGetInfo - SQL_GROUP_BY###################################################
################################################################################
self.SQL_GB_NOT_SUPPORTED = 0x0000
self.SQL_GB_GROUP_BY_EQUALS_SELECT = 0x0001
self.SQL_GB_GROUP_BY_CONTAINS_SELECT = 0x0002
self.SQL_GB_NO_RELATION = 0x0003
self.SQL_GB_COLLATE = 0x0004
################################################################################
####SQLGetInfo - SQL_INDEX_KEYWORDS#############################################
################################################################################
self.SQL_IK_NONE = 0x00000000
self.SQL_IK_ASC = 0x00000001
self.SQL_IK_DESC = 0x00000002
self.SQL_IK_ALL = self.SQL_IK_ASC | self.SQL_IK_DESC
################################################################################
####SQLGetInfo - SQL_INFO_SCHEMA_VIEWS##########################################
################################################################################
self.SQL_ISV_ASSERTIONS = 0x00000001
self.SQL_ISV_CHARACTER_SETS = 0x00000002
self.SQL_ISV_CHECK_CONSTRAINTS = 0x00000004
self.SQL_ISV_COLLATIONS = 0x00000008
self.SQL_ISV_COLUMN_DOMAIN_USAGE = 0x00000010
self.SQL_ISV_COLUMN_PRIVILEGES = 0x00000020
self.SQL_ISV_COLUMNS = 0x00000040
self.SQL_ISV_CONSTRAINT_COLUMN_USAGE = 0x00000080
self.SQL_ISV_CONSTRAINT_TABLE_USAGE = 0x00000100
self.SQL_ISV_DOMAIN_CONSTRAINTS = 0x00000200
self.SQL_ISV_DOMAINS = 0x00000400
self.SQL_ISV_KEY_COLUMN_USAGE = 0x00000800
self.SQL_ISV_REFERENTIAL_CONSTRAINTS = 0x00001000
self.SQL_ISV_SCHEMATA = 0x00002000
self.SQL_ISV_SQL_LANGUAGES = 0x00004000
self.SQL_ISV_TABLE_CONSTRAINTS = 0x00008000
self.SQL_ISV_TABLE_PRIVILEGES = 0x00010000
self.SQL_ISV_TABLES = 0x00020000
self.SQL_ISV_TRANSLATIONS = 0x00040000
self.SQL_ISV_USAGE_PRIVILEGES = 0x00080000
self.SQL_ISV_VIEW_COLUMN_USAGE = 0x00100000
self.SQL_ISV_VIEW_TABLE_USAGE = 0x00200000
self.SQL_ISV_VIEWS = 0x00400000
################################################################################
####SQLGetInfo - SQL_INSERT_STATEMENT###########################################
################################################################################
self.SQL_IS_INSERT_LITERALS = 0x00000001
self.SQL_IS_INSERT_SEARCHED = 0x00000002
self.SQL_IS_SELECT_INTO = 0x00000004
################################################################################
####SQLGetInfo - SQL_LOCK_TYPES#################################################
################################################################################
self.SQL_LCK_NO_CHANGE = 0x00000001
self.SQL_LCK_EXCLUSIVE = 0x00000002
self.SQL_LCK_UNLOCK = 0x00000004
################################################################################
####SQLGetInfo - SQL_POS_OPERATIONS#############################################
################################################################################
self.SQL_POS_POSITION = 0x00000001
self.SQL_POS_REFRESH = 0x00000002
self.SQL_POS_UPDATE = 0x00000004
self.SQL_POS_DELETE = 0x00000008
self.SQL_POS_ADD = 0x00000010
################################################################################
####SQLGetInfo - SQL_NON_NULLABLE_COLUMNS#######################################
################################################################################
self.SQL_NNC_NULL = 0x0000
self.SQL_NNC_NON_NULL = 0x0001
################################################################################
####SQLGetInfo - SQL_NULL_COLLATION#############################################
################################################################################
self.SQL_NC_START = 0x0002
self.SQL_NC_END = 0x0004
################################################################################
####SQLGetInfo - SQL_NUMERIC_FUNCTIONS##########################################
################################################################################
self.SQL_FN_NUM_ABS = 0x00000001
self.SQL_FN_NUM_ACOS = 0x00000002
self.SQL_FN_NUM_ASIN = 0x00000004
self.SQL_FN_NUM_ATAN = 0x00000008
self.SQL_FN_NUM_ATAN2 = 0x00000010
self.SQL_FN_NUM_CEILING = 0x00000020
self.SQL_FN_NUM_COS = 0x00000040
self.SQL_FN_NUM_COT = 0x00000080
self.SQL_FN_NUM_EXP = 0x00000100
self.SQL_FN_NUM_FLOOR = 0x00000200
self.SQL_FN_NUM_LOG = 0x00000400
self.SQL_FN_NUM_MOD = 0x00000800
self.SQL_FN_NUM_SIGN = 0x00001000
self.SQL_FN_NUM_SIN = 0x00002000
self.SQL_FN_NUM_SQRT = 0x00004000
self.SQL_FN_NUM_TAN = 0x00008000
self.SQL_FN_NUM_PI = 0x00010000
self.SQL_FN_NUM_RAND = 0x00020000
self.SQL_FN_NUM_DEGREES = 0x00040000
self.SQL_FN_NUM_LOG10 = 0x00080000
self.SQL_FN_NUM_POWER = 0x00100000
self.SQL_FN_NUM_RADIANS = 0x00200000
self.SQL_FN_NUM_ROUND = 0x00400000
self.SQL_FN_NUM_TRUNCATE = 0x00800000
################################################################################
####SQLGetInfo - SQL_ODBC_API_CONFORMANCE#######################################
| |
<reponame>doom38/jython_v2.2.1
# -*- Mode: Python -*-
# Id: asyncore.py,v 2.51 2000/09/07 22:29:26 rushing Exp
# Author: <NAME> <<EMAIL>>
# ======================================================================
# Copyright 1996 by <NAME>
#
# All Rights Reserved
#
# Permission to use, copy, modify, and distribute this software and
# its documentation for any purpose and without fee is hereby
# granted, provided that the above copyright notice appear in all
# copies and that both that copyright notice and this permission
# notice appear in supporting documentation, and that the name of Sam
# Rushing not be used in advertising or publicity pertaining to
# distribution of the software without specific, written prior
# permission.
#
# SAM RUSHING DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE,
# INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN
# NO EVENT SHALL SAM RUSHING BE LIABLE FOR ANY SPECIAL, INDIRECT OR
# CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS
# OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT,
# NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
# CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
# ======================================================================
"""Basic infrastructure for asynchronous socket service clients and servers.
There are only two ways to have a program on a single processor do "more
than one thing at a time". Multi-threaded programming is the simplest and
most popular way to do it, but there is another very different technique,
that lets you have nearly all the advantages of multi-threading, without
actually using multiple threads. it's really only practical if your program
is largely I/O bound. If your program is CPU bound, then pre-emptive
scheduled threads are probably what you really need. Network servers are
rarely CPU-bound, however.
If your operating system supports the select() system call in its I/O
library (and nearly all do), then you can use it to juggle multiple
communication channels at once; doing other work while your I/O is taking
place in the "background." Although this strategy can seem strange and
complex, especially at first, it is in many ways easier to understand and
control than multi-threaded programming. The module documented here solves
many of the difficult problems for you, making the task of building
sophisticated high-performance network servers and clients a snap.
"""
import exceptions
import select
import socket
import sys
import time
import os
from errno import EALREADY, EINPROGRESS, EWOULDBLOCK, ECONNRESET, \
ENOTCONN, ESHUTDOWN, EINTR, EISCONN
try:
socket_map
except NameError:
socket_map = {}
class ExitNow (exceptions.Exception):
pass
DEBUG = 0
def poll (timeout=0.0, map=None):
if map is None:
map = socket_map
if map:
r = []; w = []; e = []
for fd, obj in map.items():
if obj.readable():
r.append (fd)
if obj.writable():
w.append (fd)
if [] == r == w == e:
time.sleep(timeout)
else:
try:
r,w,e = select.select (r,w,e, timeout)
except select.error, err:
if err[0] != EINTR:
raise
else:
return
if DEBUG:
print r,w,e
for fd in r:
try:
obj = map[fd]
except KeyError:
continue
try:
obj.handle_read_event()
except ExitNow:
raise ExitNow
except:
obj.handle_error()
for fd in w:
try:
obj = map[fd]
except KeyError:
continue
try:
obj.handle_write_event()
except ExitNow:
raise ExitNow
except:
obj.handle_error()
def poll2 (timeout=0.0, map=None):
import poll
if map is None:
map=socket_map
if timeout is not None:
# timeout is in milliseconds
timeout = int(timeout*1000)
if map:
l = []
for fd, obj in map.items():
flags = 0
if obj.readable():
flags = poll.POLLIN
if obj.writable():
flags = flags | poll.POLLOUT
if flags:
l.append ((fd, flags))
r = poll.poll (l, timeout)
for fd, flags in r:
try:
obj = map[fd]
except KeyError:
continue
try:
if (flags & poll.POLLIN):
obj.handle_read_event()
if (flags & poll.POLLOUT):
obj.handle_write_event()
except ExitNow:
raise ExitNow
except:
obj.handle_error()
def poll3 (timeout=0.0, map=None):
# Use the poll() support added to the select module in Python 2.0
if map is None:
map=socket_map
if timeout is not None:
# timeout is in milliseconds
timeout = int(timeout*1000)
pollster = select.poll()
if map:
for fd, obj in map.items():
flags = 0
if obj.readable():
flags = select.POLLIN
if obj.writable():
flags = flags | select.POLLOUT
if flags:
pollster.register(fd, flags)
try:
r = pollster.poll (timeout)
except select.error, err:
if err[0] != EINTR:
raise
r = []
for fd, flags in r:
try:
obj = map[fd]
except KeyError:
continue
try:
if (flags & select.POLLIN):
obj.handle_read_event()
if (flags & select.POLLOUT):
obj.handle_write_event()
except ExitNow:
raise ExitNow
except:
obj.handle_error()
def loop (timeout=30.0, use_poll=0, map=None):
if map is None:
map=socket_map
if use_poll:
if hasattr (select, 'poll'):
poll_fun = poll3
else:
poll_fun = poll2
else:
poll_fun = poll
while map:
poll_fun (timeout, map)
class dispatcher:
debug = 0
connected = 0
accepting = 0
closing = 0
addr = None
def __init__ (self, sock=None, map=None):
if sock:
self.set_socket (sock, map)
# I think it should inherit this anyway
self.socket.setblocking (0)
self.connected = 1
# XXX Does the constructor require that the socket passed
# be connected?
try:
self.addr = sock.getpeername()
except socket.error:
# The addr isn't crucial
pass
else:
self.socket = None
def __repr__ (self):
status = [self.__class__.__module__+"."+self.__class__.__name__]
if self.accepting and self.addr:
status.append ('listening')
elif self.connected:
status.append ('connected')
if self.addr is not None:
try:
status.append ('%s:%d' % self.addr)
except TypeError:
status.append (repr(self.addr))
return '<%s at %#x>' % (' '.join (status), id (self))
def add_channel (self, map=None):
#self.log_info ('adding channel %s' % self)
if map is None:
map=socket_map
map [self._fileno] = self
def del_channel (self, map=None):
fd = self._fileno
if map is None:
map=socket_map
if map.has_key (fd):
#self.log_info ('closing channel %d:%s' % (fd, self))
del map [fd]
def create_socket (self, family, type):
self.family_and_type = family, type
self.socket = socket.socket (family, type)
self.socket.setblocking(0)
self._fileno = self.socket.fileno()
self.add_channel()
def set_socket (self, sock, map=None):
self.socket = sock
## self.__dict__['socket'] = sock
self._fileno = sock.fileno()
self.add_channel (map)
def set_reuse_addr (self):
# try to re-use a server port if possible
try:
self.socket.setsockopt (
socket.SOL_SOCKET, socket.SO_REUSEADDR,
self.socket.getsockopt (socket.SOL_SOCKET,
socket.SO_REUSEADDR) | 1
)
except socket.error:
pass
# ==================================================
# predicates for select()
# these are used as filters for the lists of sockets
# to pass to select().
# ==================================================
def readable (self):
return 1
if os.name == 'mac':
# The macintosh will select a listening socket for
# write if you let it. What might this mean?
def writable (self):
return not self.accepting
else:
def writable (self):
return 1
# ==================================================
# socket object methods.
# ==================================================
def listen (self, num):
self.accepting = 1
if os.name == 'nt' and num > 5:
num = 1
return self.socket.listen (num)
def bind (self, addr):
self.addr = addr
return self.socket.bind (addr)
def connect (self, address):
self.connected = 0
err = self.socket.connect_ex(address)
if err in (EINPROGRESS, EALREADY, EWOULDBLOCK):
return
if err in (0, EISCONN):
self.addr = address
self.connected = 1
self.handle_connect()
else:
raise socket.error, err
def accept (self):
try:
conn, addr = self.socket.accept()
return conn, addr
except socket.error, why:
if why[0] == EWOULDBLOCK:
pass
else:
raise socket.error, why
def send (self, data):
try:
result = self.socket.send (data)
return result
except socket.error, why:
if why[0] == EWOULDBLOCK:
return 0
else:
raise socket.error, why
return 0
def recv (self, buffer_size):
try:
data = self.socket.recv (buffer_size)
if not data:
# a closed connection is indicated by signaling
# a read condition, and having recv() return 0.
self.handle_close()
return ''
else:
return data
except socket.error, why:
# winsock sometimes throws ENOTCONN
if why[0] in [ECONNRESET, ENOTCONN, ESHUTDOWN]:
self.handle_close()
return ''
else:
raise socket.error, why
def close (self):
self.del_channel()
self.socket.close()
# cheap inheritance, used to pass all other attribute
# references to the underlying socket object.
def __getattr__ (self, attr):
return getattr (self.socket, attr)
# log and log_info maybe overriden to provide more sophisticated
# logging and warning methods. In general, log is for 'hit' logging
# and 'log_info' is for informational, warning and error logging.
def log (self, message):
sys.stderr.write ('log: %s\n' % str(message))
def log_info (self, message, type='info'):
if __debug__ or type != 'info':
print '%s: %s' % (type, message)
def handle_read_event (self):
if self.accepting:
# for an accepting socket, getting a read implies
# that we are connected
if not self.connected:
self.connected = 1
self.handle_accept()
elif not self.connected:
self.handle_connect()
self.connected = 1
self.handle_read()
else:
self.handle_read()
def handle_write_event (self):
# getting a write implies that we are connected
if not | |
fp:
for line in fp:
if line.startswith('#'):
continue
line_split = line.split('=')
if len(line_split) > 1:
cfg[line_split[0].lower().strip()] = line_split[1].strip()
host, port = cfg.get('host'), cfg.get('port')
if host is None or port is None:
raise ValueError('You must specify the "host" and "port" in the config file')
domain = cfg.get('domain')
if domain is not None and not domain.startswith('@'):
domain = '@' + domain
if domain is not None and '@' not in to:
to += domain
if frm is None:
frm = to
elif domain is not None and '@' not in frm:
frm += domain
server = SMTP(host=host, port=int(port))
if cfg.get('use_encryption', 'no').lower()[0] in ('t', 'y', '1'):
server.ehlo()
server.starttls()
server.ehlo()
username, password = cfg.get('username'), cfg.get('password')
if username and password:
server.login(username, password)
msg = MIMEMultipart()
msg['From'] = frm
msg['To'] = to
msg['Subject'] = subject
msg.attach(MIMEText(body, 'plain'))
server.sendmail(msg['From'], msg['To'], msg.as_string())
server.close()
def get_basename(obj):
"""Get the :func:`~os.path.basename` of a file.
Parameters
----------
obj : :term:`path-like <path-like object>` or :term:`file-like <file object>`
The object to get the :func:`~os.path.basename` of. If the object does not
support the :func:`~os.path.basename` function then the
:attr:`__name__ <definition.__name__>` of the `obj` is returned.
Returns
-------
:class:`str`
The basename of `obj`.
"""
try:
return os.path.basename(obj)
except (TypeError, AttributeError):
try:
return os.path.basename(obj.name)
except AttributeError:
return obj.__class__.__name__
def git_head(directory):
"""Get information about the ``HEAD`` of a repository.
This function requires that `git <https://git-scm.com/>`_ is installed
and that it is available on ``PATH``.
Parameters
----------
directory : :class:`str`
A directory that is under version control.
Returns
-------
:class:`dict` or :data:`None`
Information about the most recent commit on the current branch.
If `directory` is not a directory that is under version control
then returns :data:`None`.
"""
cmd = ['git', 'show', '-s', '--format=%H %ct', 'HEAD']
try:
out = subprocess.check_output(cmd, cwd=directory, stderr=subprocess.PIPE)
except subprocess.CalledProcessError:
return None
sha, timestamp = out.split()
return {
'hash': sha.decode('ascii'),
'datetime': datetime.fromtimestamp(int(timestamp))
}
def remove_write_permissions(path):
"""Remove all write permissions of a file.
On Windows, this function will set the file attribute to be read only.
On linux and macOS the write permission is removed for the User,
Group and Others. The read and execute permissions are preserved.
Parameters
----------
path : :term:`path-like object`
The path to remove the write permissions of.
"""
current_permissions = stat.S_IMODE(os.lstat(path).st_mode)
disable_writing = ~stat.S_IWUSR & ~stat.S_IWGRP & ~stat.S_IWOTH
os.chmod(path, current_permissions & disable_writing)
def run_as_admin(args=None, executable=None, cwd=None, capture_stderr=False,
blocking=True, show=False, **kwargs):
"""Run a process as an administrator and return its output.
Parameters
----------
args : :class:`str` or :class:`list` of :class:`str`, optional
A sequence of program arguments or else a single string. Providing a
sequence of arguments is generally preferred, as it allows the module
to take care of any required escaping and quoting of arguments
(e.g., to permit spaces in file names).
executable : :class:`str`, optional
The executable to pass the `args` to.
cwd : :class:`str`, optional
The working directory for the elevated process.
capture_stderr : :class:`bool`, optional
Whether to send the stderr stream to stdout.
blocking : :class:`bool`, optional
Whether to wait for the process to finish before returning to the
calling program.
show : :class:`bool`, optional
Whether to show the elevated console (Windows only). If
:data:`True` then the stdout stream of the process is not captured.
kwargs
If the current process already has admin privileges or if the operating
system is not Windows then all additional keyword arguments are passed
to :func:`~subprocess.check_output`. Otherwise only a `timeout` keyword
argument is used (Windows).
Returns
-------
:class:`bytes`, :class:`int` or :class:`~subprocess.Popen`
The returned object depends on whether the process is executed in blocking
or non-blocking mode. If blocking then :class:`bytes` are returned (the
stdout stream of the process). If non-blocking, then the returned object
will either be the :class:`~subprocess.Popen` instance that is running the
process (POSIX) or an :class:`int` which is the process ID (Windows).
Examples
--------
.. invisible-code-block: pycon
>>> SKIP_RUN_AS_ADMIN()
Import the modules
>>> import sys
>>> from msl.io import run_as_admin
Run a shell script
>>> run_as_admin(['./script.sh', '--message', 'hello world'])
Run a Python script
>>> run_as_admin([sys.executable, 'script.py', '--verbose'], cwd='D:\\\\My Scripts')
Create a service in the Windows registry and in the Service Control Manager database
>>> run_as_admin(['sc', 'create', 'MyLogger', 'binPath=', 'C:\\\\logger.exe', 'start=', 'auto'])
"""
if not args and not executable:
raise ValueError('Must specify the args and/or an executable')
stderr = subprocess.STDOUT if capture_stderr else None
process = subprocess.check_output if blocking else subprocess.Popen
if is_admin():
return process(args, executable=executable, cwd=cwd,
stderr=stderr, **kwargs)
if cwd is None:
cwd = os.getcwd()
if os.name != 'nt':
if not args:
command = ['sudo', executable]
elif isinstance(args, str):
exe = executable or ''
command = 'sudo {} {}'.format(exe, args)
else:
exe = [executable] if executable else []
command = ['sudo'] + exe + list(args)
return process(command, cwd=cwd, stderr=stderr, **kwargs)
# Windows is more complicated
if args is None:
args = ''
if not isinstance(args, str):
args = subprocess.list2cmdline(args)
if executable is None:
executable = ''
else:
executable = subprocess.list2cmdline([executable])
# the 'runas' verb starts in C:\WINDOWS\system32
cd = subprocess.list2cmdline(['cd', '/d', cwd, '&&'])
# check if a Python environment needs to be activated
activate = ''
if executable == sys.executable or args.startswith(sys.executable):
conda = os.getenv('CONDA_PREFIX') # conda
venv = os.getenv('VIRTUAL_ENV') # venv
if conda:
env = os.getenv('CONDA_DEFAULT_ENV')
assert env, 'CONDA_DEFAULT_ENV environment variable does not exist'
if env == 'base':
bat = os.path.join(conda, 'Scripts', 'activate.bat')
else:
bat = os.path.abspath(os.path.join(conda, os.pardir, os.pardir,
'Scripts', 'activate.bat'))
assert os.path.isfile(bat), 'Cannot find {!r}'.format(bat)
activate = subprocess.list2cmdline([bat, env, '&&'])
elif venv:
bat = os.path.join(venv, 'Scripts', 'activate.bat')
assert os.path.isfile(bat), 'Cannot find {!r}'.format(bat)
activate = subprocess.list2cmdline([bat, '&&'])
# redirect stdout (stderr) to a file
redirect = ''
stdout_file = ''
if not show:
import uuid
import tempfile
stdout_file = os.path.join(tempfile.gettempdir(), str(uuid.uuid4()))
r = ['>', stdout_file]
if capture_stderr:
r.append('2>&1')
redirect = subprocess.list2cmdline(r)
if re.search(r'\d$', args):
# this number is also considered as a file handle, so add a space
redirect = ' ' + redirect
# the string that is passed to cmd.exe
params = '/S /C "{cd} {activate} {executable} {args}"{redirect}'.format(
cd=cd, activate=activate, executable=executable, args=args, redirect=redirect)
from ctypes.wintypes import DWORD, ULONG, HWND, LPCWSTR, INT, HINSTANCE, HKEY, HANDLE
class ShellExecuteInfoW(ctypes.Structure):
_fields_ = [
('cbSize', DWORD),
('fMask', ULONG),
('hwnd', HWND),
('lpVerb', LPCWSTR),
('lpFile', LPCWSTR),
('lpParameters', LPCWSTR),
('lpDirectory', LPCWSTR),
('nShow', INT),
('hInstApp', HINSTANCE),
('lpIDList', ctypes.c_void_p),
('lpClass', LPCWSTR),
('hkeyClass', HKEY),
('dwHotKey', DWORD),
('hIcon', HANDLE),
('hProcess', HANDLE)]
sei = ShellExecuteInfoW()
sei.fMask = 0x00000040 | 0x00008000 # SEE_MASK_NOCLOSEPROCESS | SEE_MASK_NO_CONSOLE
sei.lpVerb = kwargs.get('verb', u'runas') # change the verb when running the tests
sei.lpFile = u'cmd.exe'
sei.lpParameters = params
sei.lpDirectory = u'{}'.format(cwd) if cwd else None
sei.nShow = int(show)
sei.cbSize = ctypes.sizeof(sei)
if not ctypes.windll.Shell32.ShellExecuteExW(ctypes.byref(sei)):
raise ctypes.WinError()
if not blocking:
return sei.hProcess
kernel32 = ctypes.windll.kernel32
timeout = kwargs.get('timeout', -1) # INFINITE = -1
milliseconds = int(timeout * 1e3) if timeout > 0 else timeout
ret = kernel32.WaitForSingleObject(sei.hProcess, milliseconds)
if ret == 0: # WAIT_OBJECT_0
stdout = b''
if stdout_file and os.path.isfile(stdout_file):
with open(stdout_file, mode='rb') as fp:
stdout = fp.read()
os.remove(stdout_file)
code = DWORD()
if not kernel32.GetExitCodeProcess(sei.hProcess, ctypes.byref(code)):
raise ctypes.WinError()
if code.value != 0:
msg = ctypes.FormatError(code.value)
out_str = stdout.decode('utf-8', 'ignore').rstrip()
if show:
msg += '\nSet show=False to capture the stdout stream.'
else:
if not capture_stderr:
msg += '\nSet capture_stderr=True to see if ' \
'more information is available.'
if out_str:
msg += '\n{}'.format(out_str)
raise ctypes.WinError(code=code.value, descr=msg)
kernel32.CloseHandle(sei.hProcess)
return stdout
if ret == 0xFFFFFFFF: # WAIT_FAILED
raise ctypes.WinError()
if ret == 0x00000080: # WAIT_ABANDONED
msg = 'The specified object is a mutex object that was not ' \
'released by the thread that owned the mutex object before ' \
'the owning thread terminated. Ownership of the mutex ' \
'object is granted to the calling thread and the mutex state ' \
'is set to non-signaled. If the mutex was protecting persistent ' \
'state information, you should check it for consistency.'
elif ret == 0x00000102: # WAIT_TIMEOUT
msg = "The timeout interval elapsed after {} second(s) and the " \
"object's state is non-signaled.".format(timeout)
else:
msg = 'Unknown return value 0x{:x}'.format(ret)
raise WindowsError('WaitForSingleObject: | |
+ " = " + "xconfd_yang_tree_get_node" + "(yt, \"" + \
cppch.arg + "\");\n"
cppline += " read_grp_" + s.arg.replace('-', '_') + "__" + cppch.arg.replace('-','_') + "(" + \
ytname + ", " + (s.arg.replace('-', '_')) + "." + cppch.arg.replace('-','_') + ");\n"
fdcpp.write(cppline)
else:
print("err_ptr_groupfunc:" + str(cppch))
fdcpp.write("}\n\n")
# s.i_module.i_modulename : 当前节点所属的module名称
# s.arg : 当前节点的名称
# s.keyword : 当前节点的类型
# module : 当前遍历到的module
# get_flags_str(s, mode) : 当前节点的读写权限
# t = get_typename(s, prefix_with_modname) : 当前节点的数据类型
def print_read_func_first(s, module, fd, fdcpp, prefix, path, mode, depth, llen,
no_expand_uses, level, width, endofvec, alreadyGen, prefix_with_modname=False):
line = ""
# 第一次遍历的时候,先将所有的顶级的container或者list写出来
if (level == 0):
line = " void read_" + \
s.arg.replace('-', '_') + "(XCONFD_YANGTREE_T* yt);"
# 将当前的节点写入文件中
fd.write(line + '\n')
# 填写函数实现,直接在另一个文件中填写函数实现
print_read_func_realize(fdcpp, s, module, line, 0)
chs = [ch for ch in s.i_children
if ch.keyword in ['container', 'list']
and (judge_if_uses_state(s) == 2 or judge_if_uses_state(s) == 4)]
#chs += [ch for ch in ]
# 打印第二级read_functoin
for prt_ch in chs:
if prt_ch.keyword == "list":
line = " void read_" + s.arg.replace('-','_') + "__" + prt_ch.arg.replace('-','_') + "(XCONFD_YANGTREE_T* yt, " + \
"std::vector<std::shared_ptr<" + get_struct_name(prt_ch.arg)[0:-1] + ">>& " + prt_ch.arg.replace('-', '_') + ");"
fd.write(line + '\n')
# 填写函数声明,直接在另一个文件中填写函数实现
print_read_func_realize(fdcpp, prt_ch, module, line, 1)
if prt_ch.keyword == "container":
line = " void read_" + s.arg.replace('-','_') + "__" + prt_ch.arg.replace('-','_') + "(XCONFD_YANGTREE_T* yt, " + \
"" + get_struct_name(prt_ch.arg) + "& " + prt_ch.arg.replace('-', '_') + ");"
fd.write(line + '\n')
print_read_func_realize(fdcpp, prt_ch, module, line, 1)
if prt_ch.keyword == "leaf":
line = print_get_leaf_realize(prt_ch, s.arg.replace('-','_') + "_." + prt_ch.arg.replace('-','_'))
def judge_next_ctn(i_children, level):
if (i_children.keyword == "container" or i_children.keyword == "list") and level > 0:
return True
# print_children在printnode中被递归调用
# i_children一个module下的其中一个孩子节点,其中container或者list等容器节点下的所有孩子节点也都包括着
# i_children[-1] : 递归调用打印孩子节点的最后一个节点
# children.arg 当前遍历到的节点的名称
# prefix : 前序节点的路径
def print_children2(i_children, module, fd, prefix, path, mode, depth,
llen, no_expand_uses, level, alreadyGen, width=0, prefix_with_modname=False):
if depth == 0:
if i_children:
fd.write(prefix + ' ...\n')
return
def get_width(w, chs):
for ch in chs:
if ch.keyword in ['choice', 'case']:
nlen = 3 + get_width(0, ch.i_children)
else:
if ch.i_module.i_modulename == module.i_modulename:
nlen = len(ch.arg)
else:
nlen = len(ch.i_module.i_prefix) + 1 + len(ch.arg)
if nlen > w:
w = nlen
return w
if no_expand_uses:
i_children = unexpand_uses(i_children)
if width == 0:
width = get_width(0, i_children)
# 遍历这个孩子节点中的所有孩子节点
for ch in i_children:
endofvec = False
chs = []
# 当遍历到该节点所有子节点的最后一个节点时
if (ch == i_children[-1]
or (i_children[-1].keyword == 'output'
and len(i_children[-1].i_children) == 0)):
newprefix = prefix.upper() + '__' + ch.arg.upper()
if level != 0:
endofvec = True
else:
newprefix = prefix.upper() + '__' + ch.arg.upper()
# 将yang模型中的中划线删除
newprefix = newprefix.replace('-', '_')
if (prefix is not None):
#print('pre node is ' + prefix)
ch.prenode = prefix
# 查找所有非第一级的container和list
if ch.keyword == "container" or ch.keyword == "list":
for cht in ch.i_children:
if cht.keyword in statements.type_definition_keywords and cht.arg not in alreadyGen:
# 此时这个cht一定是一个list或者container
# print(cht)
line = "typedef struct struct" + \
cht.arg.replace("-", "").title() + "\n{"
fd.write(line + "\n")
alreadyGen.append(cht.arg)
print_node2(cht, module, fd, newprefix, path, mode, depth, llen,
no_expand_uses, level, width, endofvec, alreadyGen,
prefix_with_modname=prefix_with_modname)
# 遍历孩子节点
recursive_child(ch, module, fd, newprefix, path, mode, depth, llen,
no_expand_uses, level, width, endofvec, alreadyGen,
prefix_with_modname=prefix_with_modname)
def print_read_grp_func(groupname, module, fd, fdcpp, prefix, path, mode, depth,
llen, no_expand_uses, level, alreadyGen, width=0, prefix_with_modname=False):
chs = []
#if module.i_groupings[groupname]
# 打印第一级的grp
line = " void read_grp_" + groupname.replace('-', '_') + "(XCONFD_YANGTREE_T* yt, " + get_struct_name(
groupname) + "& " + groupname.replace('-', '_') + ");"
# 将当前的节点写入文件中
fd.write(line + '\n')
print_read_grp_func_realize(fdcpp, module.i_groupings[groupname], module, line, 0, False)
print_read_grp_next_func(groupname, module, fd, fdcpp, 1)
def print_read_grp_next_func(groupname, module, fd, fdcpp, level):
chs = [ch for ch in module.i_groupings[groupname].i_children
if ch.keyword in ['list', 'container']]
# 循环遍历grouping下所有的container或list,当container或list有孩子为container或list,则需要递归遍历该节点
for prt_ch in chs:
if prt_ch.keyword == "list":
#print(123)
line = " void read_grp_" + groupname.replace('-', '_') + "__" + prt_ch.arg.replace('-', '_') + "(XCONFD_YANGTREE_T* yt, std::vector<std::shared_ptr<" + get_struct_name(
judge_if_uses(prt_ch)) + ">>& " + prt_ch.arg.replace('-','_') + ");"
fd.write(line + '\n')
print_read_grp_func_realize(fdcpp, prt_ch, module, line, 1, False)
elif judge_if_optional_state(prt_ch) == 1:
line = " void read_grp_" + groupname.replace('-', '_') + "__" + prt_ch.arg.replace('-', '_') + "(XCONFD_YANGTREE_T* yt, std::shared_ptr<" + get_struct_name(
judge_if_uses(prt_ch)) + ">& " + prt_ch.arg.replace('-','_') + ");"
fd.write(line + '\n')
print_read_grp_func_realize(fdcpp, prt_ch, module, line, 1, True)
else:
line = " void read_grp_" + groupname.replace('-', '_') + "__" + prt_ch.arg.replace('-', '_') + "(XCONFD_YANGTREE_T* yt, " + get_struct_name(
judge_if_uses(prt_ch)) + "& " + prt_ch.arg.replace('-','_') + ");"
fd.write(line + '\n')
print_read_grp_func_realize(fdcpp, prt_ch, module, line, 1, False)
#else:
#read_grp_next_func(prt_ch, groupname, fd, 0)
# def read_grp_next_func(prt_ch, groupname, fd, level):
# # 当这个container或list中除了包含uses还包含了其他leaf、container等等
# chs2 = [ch2 for ch2 in prt_ch.substmts
# if ch2.keyword in statements.mem_definition_keywords]
# # TODO:第二级及其以后的container或list需要处理
# if (judge_if_uses_state(prt_ch) == 2) and len(chs2) > 0:
# print(prt_ch)
# chs = [ch for ch in prt_ch.i_children
# if ch.keyword in statements.type_definition_keywords]
# print_read_grp_next_func(groupname, fd, level + 1)
# if(len(chs) > 0):
# # 将grouping下所有的container或list递归出来
# print_grp_children(chs, module, fd, prefix, path, mode, depth,
# llen, no_expand_uses, level, alreadyGen, width=0, prefix_with_modname=False)
def judge_if_uses(child_node):
child_len = [ch for ch in child_node.substmts
if ch.keyword == "uses"]
child_all_len = [ch2 for ch2 in child_node.substmts]
if(len(child_len) == 1):
if str(child_len[0].arg).find(":") > 0:
return str(child_len[0].arg)[str(child_len[0].arg).find(":") + 1 :]
else:
return str(child_len[0].arg)
else:
if str(child_node.arg).find(":") > 0:
return str(child_node.arg)[str(child_node.arg).find(":") + 1 :]
else:
return str(child_node.arg)
def judge_if_optional_state(child_node):
child_len = [ch for ch in child_node.substmts
if ch.arg == "optional"]
#child_all_len = [ch2 for ch2 in child_node.substmts]
if(len(child_len) == 1):
return 1
elif(len(child_len) == 0):
return 2
else:
return 3
def judge_if_uses_state(child_node):
child_len = [ch for ch in child_node.substmts
if ch.keyword == "uses"]
child_all_len = [ch2 for ch2 in child_node.substmts
if ch2.keyword in ['leaf', 'container', 'list', 'leaf-list']]
# 如果使用了uses,且只使用到了uses
if(len(child_len) == 1 and len(child_all_len) == 0):
return 1
# 如果使用了uses,且存在其他的数据节点
elif(len(child_len) == 1 and len(child_all_len) > 0):
return 2
# 如果使用了多个uses
elif(len(child_len) >= 1):
return 3
# 如果没有使用uses
elif(len(child_len) == 0):
return 4
else:
return 5
def print_grp_children(i_children, module, fd, prefix, path, mode, depth,
llen, no_expand_uses, level, alreadyGen, width=0, prefix_with_modname=False):
# 遍历这个孩子节点中的所有孩子节点
for ch in i_children:
endofvec = False
chs = []
# 当遍历到该节点所有子节点的最后一个节点时
if (ch == i_children[-1]
or (i_children[-1].keyword == 'output'
and len(i_children[-1].i_children) == 0)):
newprefix = prefix.upper() + '__' + ch.arg.upper()
if level != 0:
endofvec = True
else:
newprefix = prefix.upper() + '__' + ch.arg.upper()
# 将yang模型中的中划线删除
newprefix = newprefix.replace('-', '_')
if (prefix is not None):
#print('pre node is ' + prefix)
ch.prenode = prefix
# 查找所有非第一级的container和list
if ch.keyword == "container" or ch.keyword == "list":
for cht in ch.i_children:
if cht.keyword in statements.type_definition_keywords and cht.arg not in alreadyGen:
# 此时这个cht一定是一个list或者container
# print(cht)
line = "typedef struct struct" + \
cht.arg.replace("-", "").title() + "\n{"
fd.write(line + "\n")
print_node2(cht, module, fd, newprefix, path, mode, depth, llen,
no_expand_uses, level, width, endofvec, alreadyGen,
prefix_with_modname=prefix_with_modname)
# 遍历孩子节点
recursive_child(ch, module, fd, newprefix, path, mode, depth, llen,
no_expand_uses, level, width, endofvec, alreadyGen,
prefix_with_modname=prefix_with_modname)
# s.i_module.i_modulename : 当前节点所属的module名称
# s.arg : 当前节点的名称
# s.keyword : 当前节点的类型
# module : 当前遍历到的module
# get_flags_str(s, mode) : 当前节点的读写权限
# t = get_typename(s, prefix_with_modname) : 当前节点的数据类型
def recursive_child(s, module, fd, prefix, path, mode, depth, llen,
no_expand_uses, level, width, endofvec, alreadyGen, prefix_with_modname=False):
# 如果当前节点有孩子
if hasattr(s, 'i_children') and s.keyword != 'uses':
if depth is not None:
depth = depth - 1
chs = s.i_children
if path is not None and len(path) > 0:
chs = [ch for ch in chs
if ch.arg == path[0]]
path = path[1:]
if s.keyword in ['choice', 'case']:
print_children2(chs, module, fd, prefix, path, mode, depth,
llen, no_expand_uses, level + 1, width - 3, alreadyGen,
prefix_with_modname=prefix_with_modname)
else:
print_children2(chs, module, fd, prefix, path, mode, depth, llen,
no_expand_uses, level + 1, alreadyGen,
prefix_with_modname=prefix_with_modname)
def print_node2(s, module, fd, prefix, path, mode, depth, llen,
no_expand_uses, level, width, endofvec, alreadyGen, prefix_with_modname=False):
line = ""
strname = get_struct_name(str(s.arg))
for children in s.i_children:
if ((children.keyword == "container")):
line = " %s %s; " % (get_struct_name(children.arg),
children.arg.replace('-', '_'))
elif ((children.keyword == "list")):
line = " std::vector<std::shared_ptr<" + \
get_struct_name(children.arg)[0:-1] + ">> " + \
children.arg.replace('-', '_') + ";"
elif children.keyword == "leaf-list":
line = " std::vector<std::shared_ptr<" + \
refine_type_name(get_typename(
children, prefix_with_modname)) + ">> " + children.arg.replace('-', '_') + ";"
else:
line = " %s %s; " % (refine_type_name(
| |
#!/usr/bin/env
""" Creates graphs of civ popularity. """
import argparse
from collections import defaultdict, Counter
import csv
from math import sqrt
import pathlib
import pickle
import os
import matplotlib.pyplot as plt
from utils.lookup import CIVILIZATIONS
CACHED_TEMPLATE = '{}/cached_civ_popularity_map_for_{}.pickle'
import utils.solo_models
import utils.team_models
MAP_ORDER = [
'Steppe',
'Mountain Pass',
'Scandinavia',
'Oasis',
'Wolf Hill',
'Hill Fort',
'Hideout',
'Arena',
'Black Forest',
'Golden Pit',
'Gold Rush',
'All Maps',
'Acropolis',
'Arabia',
'Serengeti',
'Kilimanjaro',
'MegaRandom',
'Four Lakes',
'Golden Swamp',
'Lombardia',
'Alpine Lakes',
'Nomad',
'Bog Islands',
'Mediterranean',
'Continental',
'Team Islands',
'Islands',
]
def default_ranking():
return 35
def default_popularity():
return 0
def to_heatmap_table(data, xlabels, ylabels, row_label_header, normalize):
""" Formats data into an html table with heatmap colors. Returns a string
data: 2-dimensional array of heatmap number (0.0-1.0) and text
xlabels: labels for headers
ylabels: labels for rows. """
html_rows = ['<table>',]
# Add header
html_rows.append(''.join(['<tr><th>{}</th>'.format(row_label_header)] + ['<th class="xlabel">{}</th>'.format(l) for l in xlabels] + ['</tr>']))
# Rows
for idx, row in enumerate(data):
html_rows.append(to_heatmap_row(row, ylabels[idx], normalize))
html_rows.append('</table>')
return '\n'.join(html_rows)
def to_heatmap_row(row, ylabel, normalize):
row_info = ['<tr><td class="ylabel">{}</td>'.format(ylabel),]
for heatmap, value in row:
row_info.append('<td class="data" style="background-color: hsl({}, 100%, 60%)">{}</td>'.format((1 - normalize(heatmap))*240, value))
row_info.append('</tr>')
return ''.join(row_info)
class CachedCiv:
""" To avoid serialization problems, same as civ but no functions. """
def __init__(self, civ):
self.name = civ.name
self.rankings = civ.rankings
self.popularity = civ.popularity
self.totals = civ.totals
class Rankable:
""" Derived supercalss from Civ so get similar functionality for Map."""
def __init__(self, name):
self.name = name
self.rankings = defaultdict(default_ranking)
self.popularity = defaultdict(default_popularity)
self.totals = defaultdict(default_popularity)
class Rating(Rankable):
""" Simple object for holding rankable data for ratings."""
pass
class Map(Rankable):
""" Simple object for holding rankable data for maps. """
pass
class Civ(Rankable):
""" Holds rankable data for a civ. """
def from_cache(cached_civ):
civ = Civ(cached_civ.name)
civ.rankings = cached_civ.rankings
civ.popularity = cached_civ.popularity
civ.totals = cached_civ.totals
return civ
def print_info(self, maps_with_data, rating_keys):
mt_array = ['{:18}', '{:^9s}'] + ['{:^9s}' for _ in rating_keys]
map_template = ' '.join(mt_array)
print('*'*(len(self.name)))
print(self.name)
print('*'*(len(self.name)))
print('Overall:', self.rankings['Overall'])
print(map_template.format('Map Name', 'Overall', *[rk for rk in rating_keys]))
print(map_template.format('All', str(round(self.popularity['Overall'], 2)), *[str(round(self.popularity[rk], 2)) for rk in rating_keys]))
for map_name in sorted(maps_with_data):
print(map_template.format(map_name, str(round(self.rankings[map_name], 3)), *[str(round(self.rankings['{}-{}'.format(map_name,rk)], 3)) for rk in rating_keys]))
print(map_template.format(map_name, str(round(self.popularity[map_name], 3)), *[str(round(self.popularity['{}-{}'.format(map_name,rk)], 3)) for rk in rating_keys]))
def map_x_rating_heatmap_table(self, maps, rating_keys, normalize):
html = ['\n<h3>{}</h3>'.format(self.name)]
map_dict = {}
xlabels = rating_keys
ylabels = []
data = []
for map_name in sorted(set(maps), key=lambda x: MAP_ORDER.index(x)):
ylabels.append(map_name)
data.append([(self.popularity['{}-{}'.format(map_name, rk)], self.rankings['{}-{}'.format(map_name, rk)],) for rk in rating_keys])
html.append(to_heatmap_table(data, xlabels, ylabels, 'Map Name', normalize))
return '\n'.join(html)
def heatmap_rating_data(self, map_name, rating_keys):
if map_name == 'all':
row = [(self.popularity[rk],
self.rankings[rk]) for rk in rating_keys]
else:
row = [(self.popularity['{}-{}'.format(map_name, rk)],
self.rankings['{}-{}'.format(map_name, rk)]) for rk in rating_keys]
return row
def civ_popularity_counters_for_map_bucketed_by_rating(players, map_name, edges):
""" Returns an array of counters, each of which represents the cumulative proportional popularity of a civilization
for every rated player for matches played when holding a rating between the edges. Note, a player is only checked
if the player's "best rating" falls within the edges.
players: the list of players to evaluate
map_name: which map to build the counters for. 'all' will ignore map as a filter
edges: an array of edges in which to delineate ratings. First edge should be greater than zero, so first "bucket"
will be from 1 to edges[0], second edge from edges[0] to edges[1], finishing at edges[-2] to edges[-1]."""
print('calculating civ_popularity_counters_for_map_bucketed_by_rating for map {} for {} edges'.format(map_name, len(edges)))
start = 0
counters = []
for edge in edges:
civ_ctr = Counter()
counters.append(civ_ctr)
snapshot_players = [p for p in players if start < p.best_rating() <= edge]
for player in snapshot_players:
player.add_civ_percentages(civ_ctr, map_name, start, edge)
start = edge - 50
return counters
def loaded_civs(data_set_type, module, players=None):
""" Calculates civ popularities overall, by map, by rating bucket, and by map-rating combination.
returns civs, the maps that have data, and the rating keys available in the civs."""
print('loading civs for', data_set_type)
# Setup
civs = {}
for k in CIVILIZATIONS:
civs[k] = Civ(k)
edges = [i for i in range(650, 1701, 50)]
start = 0
rating_keys = []
for edge in edges:
rating_keys.append('{}-{}'.format(start + 1, edge))
start = edge - 50
rating_keys.append('{}+'.format(edges[-1] - 49))
edges.append(10000)
if not players:
print('building players')
players = [p for p in module.Player.player_values(module.MatchReport.all(data_set_type), data_set_type) if p.best_rating()]
# Calculate overall popularity
for ctr in civ_popularity_counters_for_map_bucketed_by_rating(players, 'all', [10000]):
total = sum(ctr.values())
for idx, civ in enumerate(sorted(ctr, key=lambda x: ctr[x], reverse=True)):
civs[civ].rankings['Overall'] = idx + 1
civs[civ].popularity['Overall'] = ctr[civ]/total
civs[civ].totals['Overall'] = total
# # Calculate overall popularity per rating bucket
for ctr_idx, ctr in enumerate(civ_popularity_counters_for_map_bucketed_by_rating(players, 'all', edges)):
total = sum(ctr.values())
for idx, civ in enumerate(sorted(ctr, key=lambda x: ctr[x], reverse=True)):
civs[civ].rankings[rating_keys[ctr_idx]] = idx + 1
civs[civ].popularity[rating_keys[ctr_idx]] = ctr[civ]/total
civs[civ].totals[rating_keys[ctr_idx]] = total
# Calculate overall popularity by map
maps_with_data = []
for map_name in module.MAPS:
for ctr in civ_popularity_counters_for_map_bucketed_by_rating(players, map_name, [10000]):
if ctr:
maps_with_data.append(map_name)
total = sum(ctr.values())
for idx, civ in enumerate(sorted(ctr, key=lambda x: ctr[x], reverse=True)):
civs[civ].rankings[map_name] = idx + 1
civs[civ].popularity[map_name] = ctr[civ]/total
civs[civ].totals[map_name] = total
# Calculate overall popularity by map by rating bucket
for map_name in maps_with_data:
for ctr_idx, ctr in enumerate(civ_popularity_counters_for_map_bucketed_by_rating(players, map_name, edges)):
total = sum(ctr.values())
for idx, civ in enumerate(sorted(ctr, key=lambda x: ctr[x], reverse=True)):
civs[civ].rankings['{}-{}'.format(map_name, rating_keys[ctr_idx])] = idx + 1
civs[civ].popularity['{}-{}'.format(map_name, rating_keys[ctr_idx])] = ctr[civ]/total
civs[civ].totals['{}-{}'.format(map_name, rating_keys[ctr_idx])] = total
return civs, maps_with_data, rating_keys
def civs_x_maps_heatmap_table(civs, maps):
""" Returns a single heatmap html table of civs x maps """
# Build data arrays
civ_names = [civ.name for civ in sorted(civs.values(), key=lambda x: x.rankings['Overall'])]
map_dict = {}
header_row = civ_names
civ_popularities = []
for map_name in maps:
row = []
map_dict[map_name] = row
for civ_name in civ_names:
civ = civs[civ_name]
row.append((civ.popularity[map_name], civ.rankings[map_name],))
civ_popularities.append(civ.popularity[map_name])
max_value = sorted(civ_popularities, reverse=True)[len(maps)-1]
def normalize(x):
if x == 0: return x
if x > max_value: return 1
return x/max_value
# Format data as rows of html in proper order
html_rows = ['<h2>Overall Popularity of Civs per Map</h2>',]
xlabels = civ_names
ylabels = []
data = []
for map_name in sorted(map_dict, key=lambda x: MAP_ORDER.index(x)):
ylabels.append(map_name)
data.append(map_dict[map_name])
html_rows.append(to_heatmap_table(data, xlabels, ylabels, 'Map Name', normalize))
return '\n'.join(html_rows)
def civs_x_maps_heatmap_tables_per_rating_bucket(civs, maps, rating_keys):
""" Returns a set of heatmap html tables of civs x maps, one table for every rating bucket."""
html_rows = ['<h2>Popularity of Civs on Maps by Rating</h2>',]
civ_names = [civ.name for civ in sorted(civs.values(), key=lambda x: x.rankings['Overall'])]
for rk in rating_keys:
map_dict = {}
header_row = civ_names
civ_popularities = []
for map_name in maps:
row = []
map_dict[map_name] = row
for civ_name in civ_names:
civ = civs[civ_name]
row.append((civ.popularity['{}-{}'.format(map_name, rk)], civ.rankings['{}-{}'.format(map_name, rk)],))
civ_popularities.append(civ.popularity['{}-{}'.format(map_name, rk)])
max_value = sorted(civ_popularities, reverse=True)[len(civs) - 1]
def normalize(x):
if x == 0: return x
if x > max_value:
return 1
return x/max_value
# Format data as rows of html in proper order
html_rows.append('<h3>Popularity of Civs per Map for {}</h3>'.format(rk))
xlabels = civ_names
ylabels = []
data = []
for map_name in sorted(map_dict, key=lambda x: MAP_ORDER.index(x)):
ylabels.append(map_name)
data.append(map_dict[map_name])
html_rows.append(to_heatmap_table(data, xlabels, ylabels, 'Map Name', normalize))
return '\n'.join(html_rows)
def write_civs_x_maps_heatmaps_to_html(civs, maps, rating_keys, module):
""" Generates html representation of each rating's popularity by map and civ. """
with open('{}/rating_popularity_data.html'.format(module.GRAPH_DIR), 'w') as f:
f.write("""<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Civilization Popularity per Rating Segmented by Map</title>
<meta name="description" content="AOE2 info">
<meta name="author" content="porcpine1967">
<link rel="stylesheet" href="../styles/normalize.css">
<style>
body {margin: 5em}
th.xlabel { font-size: 6pt; padding: 0; width: 2.5em}
td.data { text-align: center; width: 2.5em}
</style>
</head>
<body>
""")
f.write(civs_x_maps_heatmap_table(civs, maps))
f.write(civs_x_maps_heatmap_tables_per_rating_bucket(civs, maps, rating_keys))
def write_maps_x_ratings_heatmaps_to_html(civs, maps, rating_keys, data_set_type, module):
""" Generates html representation of each civ's popularity by map and rating. """
with open('{}/civ_popularity_data.html'.format(module.GRAPH_DIR), 'w') as f:
f.write("""<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Civilization Rankings per Map Segmented by Rating</title>
<meta name="description" content="AOE2 info">
<meta name="author" content="porcpine1967">
<link rel="stylesheet" href="../styles/normalize.css">
<style>
body {margin: 5em}
td.ylabel { width: 7em; }
td.data { text-align: center; }
th { width: 4em; }
</style>
</head>
<body>
""")
f.write(all_civs_map_x_rating_heatmap_table(module, data_set_type, rating_keys))
civ_popularities = [civ.popularity['{}-{}'.format(map_name, rk)] for rk in rating_keys for civ in civs.values() for map_name in maps]
max_value = sorted(civ_popularities, reverse=True)[len(rating_keys)*len(civs)-1]
def normalize(x):
if max_value == 0:
return 0
if x > max_value:
return 1
return x/max_value
f.write('<h2>Popularity of Each Civ Segmented by Map and Ranking</h2>')
for civ in sorted(civs.values(), key=lambda x: x.rankings['Overall']):
f.write(civ.map_x_rating_heatmap_table(maps, rating_keys, normalize))
def civs_x_ratings_heatmap_table(civs, rating_keys, civ_names):
civ_popularities | |
PAGES = "pages"
PARENT_NOTEBOOK = "parentNotebook"
PARENT_SECTION_GROUP = "parentSectionGroup"
class Enum67(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)):
ASTERISK = "*"
PARENT_NOTEBOOK = "parentNotebook"
PARENT_SECTION_GROUP = "parentSectionGroup"
SECTION_GROUPS = "sectionGroups"
SECTIONS = "sections"
class Enum670(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)):
ASTERISK = "*"
PAGES = "pages"
PARENT_NOTEBOOK = "parentNotebook"
PARENT_SECTION_GROUP = "parentSectionGroup"
class Enum671(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)):
ID = "id"
ID_DESC = "id desc"
SELF = "self"
SELF_DESC = "self desc"
CREATED_DATE_TIME = "createdDateTime"
CREATED_DATE_TIME_DESC = "createdDateTime desc"
CREATED_BY = "createdBy"
CREATED_BY_DESC = "createdBy desc"
DISPLAY_NAME = "displayName"
DISPLAY_NAME_DESC = "displayName desc"
LAST_MODIFIED_BY = "lastModifiedBy"
LAST_MODIFIED_BY_DESC = "lastModifiedBy desc"
LAST_MODIFIED_DATE_TIME = "lastModifiedDateTime"
LAST_MODIFIED_DATE_TIME_DESC = "lastModifiedDateTime desc"
IS_DEFAULT = "isDefault"
IS_DEFAULT_DESC = "isDefault desc"
LINKS = "links"
LINKS_DESC = "links desc"
PAGES_URL = "pagesUrl"
PAGES_URL_DESC = "pagesUrl desc"
class Enum672(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)):
ID = "id"
SELF = "self"
CREATED_DATE_TIME = "createdDateTime"
CREATED_BY = "createdBy"
DISPLAY_NAME = "displayName"
LAST_MODIFIED_BY = "lastModifiedBy"
LAST_MODIFIED_DATE_TIME = "lastModifiedDateTime"
IS_DEFAULT = "isDefault"
LINKS = "links"
PAGES_URL = "pagesUrl"
PAGES = "pages"
PARENT_NOTEBOOK = "parentNotebook"
PARENT_SECTION_GROUP = "parentSectionGroup"
class Enum673(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)):
ASTERISK = "*"
PAGES = "pages"
PARENT_NOTEBOOK = "parentNotebook"
PARENT_SECTION_GROUP = "parentSectionGroup"
class Enum674(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)):
ID = "id"
SELF = "self"
CREATED_DATE_TIME = "createdDateTime"
CREATED_BY = "createdBy"
DISPLAY_NAME = "displayName"
LAST_MODIFIED_BY = "lastModifiedBy"
LAST_MODIFIED_DATE_TIME = "lastModifiedDateTime"
IS_DEFAULT = "isDefault"
LINKS = "links"
PAGES_URL = "pagesUrl"
PAGES = "pages"
PARENT_NOTEBOOK = "parentNotebook"
PARENT_SECTION_GROUP = "parentSectionGroup"
class Enum675(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)):
ASTERISK = "*"
PAGES = "pages"
PARENT_NOTEBOOK = "parentNotebook"
PARENT_SECTION_GROUP = "parentSectionGroup"
class Enum676(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)):
ID = "id"
SELF = "self"
CREATED_DATE_TIME = "createdDateTime"
CREATED_BY = "createdBy"
DISPLAY_NAME = "displayName"
LAST_MODIFIED_BY = "lastModifiedBy"
LAST_MODIFIED_DATE_TIME = "lastModifiedDateTime"
IS_DEFAULT = "isDefault"
LINKS = "links"
PAGES_URL = "pagesUrl"
PAGES = "pages"
PARENT_NOTEBOOK = "parentNotebook"
PARENT_SECTION_GROUP = "parentSectionGroup"
class Enum677(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)):
ASTERISK = "*"
PAGES = "pages"
PARENT_NOTEBOOK = "parentNotebook"
PARENT_SECTION_GROUP = "parentSectionGroup"
class Enum678(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)):
ID = "id"
SELF = "self"
CREATED_DATE_TIME = "createdDateTime"
CREATED_BY = "createdBy"
DISPLAY_NAME = "displayName"
LAST_MODIFIED_BY = "lastModifiedBy"
LAST_MODIFIED_DATE_TIME = "lastModifiedDateTime"
IS_DEFAULT = "isDefault"
IS_SHARED = "isShared"
LINKS = "links"
SECTION_GROUPS_URL = "sectionGroupsUrl"
SECTIONS_URL = "sectionsUrl"
USER_ROLE = "userRole"
SECTION_GROUPS = "sectionGroups"
SECTIONS = "sections"
class Enum679(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)):
ASTERISK = "*"
SECTION_GROUPS = "sectionGroups"
SECTIONS = "sections"
class Enum68(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)):
ID = "id"
ID_DESC = "id desc"
SELF = "self"
SELF_DESC = "self desc"
CREATED_DATE_TIME = "createdDateTime"
CREATED_DATE_TIME_DESC = "createdDateTime desc"
CREATED_BY = "createdBy"
CREATED_BY_DESC = "createdBy desc"
DISPLAY_NAME = "displayName"
DISPLAY_NAME_DESC = "displayName desc"
LAST_MODIFIED_BY = "lastModifiedBy"
LAST_MODIFIED_BY_DESC = "lastModifiedBy desc"
LAST_MODIFIED_DATE_TIME = "lastModifiedDateTime"
LAST_MODIFIED_DATE_TIME_DESC = "lastModifiedDateTime desc"
IS_DEFAULT = "isDefault"
IS_DEFAULT_DESC = "isDefault desc"
LINKS = "links"
LINKS_DESC = "links desc"
PAGES_URL = "pagesUrl"
PAGES_URL_DESC = "pagesUrl desc"
class Enum680(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)):
ID = "id"
ID_DESC = "id desc"
SELF = "self"
SELF_DESC = "self desc"
CREATED_DATE_TIME = "createdDateTime"
CREATED_DATE_TIME_DESC = "createdDateTime desc"
CREATED_BY = "createdBy"
CREATED_BY_DESC = "createdBy desc"
DISPLAY_NAME = "displayName"
DISPLAY_NAME_DESC = "displayName desc"
LAST_MODIFIED_BY = "lastModifiedBy"
LAST_MODIFIED_BY_DESC = "lastModifiedBy desc"
LAST_MODIFIED_DATE_TIME = "lastModifiedDateTime"
LAST_MODIFIED_DATE_TIME_DESC = "lastModifiedDateTime desc"
SECTION_GROUPS_URL = "sectionGroupsUrl"
SECTION_GROUPS_URL_DESC = "sectionGroupsUrl desc"
SECTIONS_URL = "sectionsUrl"
SECTIONS_URL_DESC = "sectionsUrl desc"
class Enum681(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)):
ID = "id"
SELF = "self"
CREATED_DATE_TIME = "createdDateTime"
CREATED_BY = "createdBy"
DISPLAY_NAME = "displayName"
LAST_MODIFIED_BY = "lastModifiedBy"
LAST_MODIFIED_DATE_TIME = "lastModifiedDateTime"
SECTION_GROUPS_URL = "sectionGroupsUrl"
SECTIONS_URL = "sectionsUrl"
PARENT_NOTEBOOK = "parentNotebook"
PARENT_SECTION_GROUP = "parentSectionGroup"
SECTION_GROUPS = "sectionGroups"
SECTIONS = "sections"
class Enum682(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)):
ASTERISK = "*"
PARENT_NOTEBOOK = "parentNotebook"
PARENT_SECTION_GROUP = "parentSectionGroup"
SECTION_GROUPS = "sectionGroups"
SECTIONS = "sections"
class Enum683(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)):
ID = "id"
SELF = "self"
CREATED_DATE_TIME = "createdDateTime"
CREATED_BY = "createdBy"
DISPLAY_NAME = "displayName"
LAST_MODIFIED_BY = "lastModifiedBy"
LAST_MODIFIED_DATE_TIME = "lastModifiedDateTime"
SECTION_GROUPS_URL = "sectionGroupsUrl"
SECTIONS_URL = "sectionsUrl"
PARENT_NOTEBOOK = "parentNotebook"
PARENT_SECTION_GROUP = "parentSectionGroup"
SECTION_GROUPS = "sectionGroups"
SECTIONS = "sections"
class Enum684(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)):
ASTERISK = "*"
PARENT_NOTEBOOK = "parentNotebook"
PARENT_SECTION_GROUP = "parentSectionGroup"
SECTION_GROUPS = "sectionGroups"
SECTIONS = "sections"
class Enum685(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)):
ID = "id"
SELF = "self"
CREATED_DATE_TIME = "createdDateTime"
CREATED_BY = "createdBy"
DISPLAY_NAME = "displayName"
LAST_MODIFIED_BY = "lastModifiedBy"
LAST_MODIFIED_DATE_TIME = "lastModifiedDateTime"
IS_DEFAULT = "isDefault"
IS_SHARED = "isShared"
LINKS = "links"
SECTION_GROUPS_URL = "sectionGroupsUrl"
SECTIONS_URL = "sectionsUrl"
USER_ROLE = "userRole"
SECTION_GROUPS = "sectionGroups"
SECTIONS = "sections"
class Enum686(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)):
ASTERISK = "*"
SECTION_GROUPS = "sectionGroups"
SECTIONS = "sections"
class Enum687(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)):
ID = "id"
SELF = "self"
CREATED_DATE_TIME = "createdDateTime"
CREATED_BY = "createdBy"
DISPLAY_NAME = "displayName"
LAST_MODIFIED_BY = "lastModifiedBy"
LAST_MODIFIED_DATE_TIME = "lastModifiedDateTime"
SECTION_GROUPS_URL = "sectionGroupsUrl"
SECTIONS_URL = "sectionsUrl"
PARENT_NOTEBOOK = "parentNotebook"
PARENT_SECTION_GROUP = "parentSectionGroup"
SECTION_GROUPS = "sectionGroups"
SECTIONS = "sections"
class Enum688(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)):
ASTERISK = "*"
PARENT_NOTEBOOK = "parentNotebook"
PARENT_SECTION_GROUP = "parentSectionGroup"
SECTION_GROUPS = "sectionGroups"
SECTIONS = "sections"
class Enum689(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)):
ID = "id"
ID_DESC = "id desc"
SELF = "self"
SELF_DESC = "self desc"
CREATED_DATE_TIME = "createdDateTime"
CREATED_DATE_TIME_DESC = "createdDateTime desc"
CREATED_BY = "createdBy"
CREATED_BY_DESC = "createdBy desc"
DISPLAY_NAME = "displayName"
DISPLAY_NAME_DESC = "displayName desc"
LAST_MODIFIED_BY = "lastModifiedBy"
LAST_MODIFIED_BY_DESC = "lastModifiedBy desc"
LAST_MODIFIED_DATE_TIME = "lastModifiedDateTime"
LAST_MODIFIED_DATE_TIME_DESC = "lastModifiedDateTime desc"
SECTION_GROUPS_URL = "sectionGroupsUrl"
SECTION_GROUPS_URL_DESC = "sectionGroupsUrl desc"
SECTIONS_URL = "sectionsUrl"
SECTIONS_URL_DESC = "sectionsUrl desc"
class Enum69(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)):
ID = "id"
SELF = "self"
CREATED_DATE_TIME = "createdDateTime"
CREATED_BY = "createdBy"
DISPLAY_NAME = "displayName"
LAST_MODIFIED_BY = "lastModifiedBy"
LAST_MODIFIED_DATE_TIME = "lastModifiedDateTime"
IS_DEFAULT = "isDefault"
LINKS = "links"
PAGES_URL = "pagesUrl"
PAGES = "pages"
PARENT_NOTEBOOK = "parentNotebook"
PARENT_SECTION_GROUP = "parentSectionGroup"
class Enum690(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)):
ID = "id"
SELF = "self"
CREATED_DATE_TIME = "createdDateTime"
CREATED_BY = "createdBy"
DISPLAY_NAME = "displayName"
LAST_MODIFIED_BY = "lastModifiedBy"
LAST_MODIFIED_DATE_TIME = "lastModifiedDateTime"
SECTION_GROUPS_URL = "sectionGroupsUrl"
SECTIONS_URL = "sectionsUrl"
PARENT_NOTEBOOK = "parentNotebook"
PARENT_SECTION_GROUP = "parentSectionGroup"
SECTION_GROUPS = "sectionGroups"
SECTIONS = "sections"
class Enum691(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)):
ASTERISK = "*"
PARENT_NOTEBOOK = "parentNotebook"
PARENT_SECTION_GROUP = "parentSectionGroup"
SECTION_GROUPS = "sectionGroups"
SECTIONS = "sections"
class Enum692(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)):
ID = "id"
SELF = "self"
CREATED_DATE_TIME = "createdDateTime"
CREATED_BY = "createdBy"
DISPLAY_NAME = "displayName"
LAST_MODIFIED_BY = "lastModifiedBy"
LAST_MODIFIED_DATE_TIME = "lastModifiedDateTime"
SECTION_GROUPS_URL = "sectionGroupsUrl"
SECTIONS_URL = "sectionsUrl"
PARENT_NOTEBOOK = "parentNotebook"
PARENT_SECTION_GROUP = "parentSectionGroup"
SECTION_GROUPS = "sectionGroups"
SECTIONS = "sections"
class Enum693(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)):
ASTERISK = "*"
PARENT_NOTEBOOK = "parentNotebook"
PARENT_SECTION_GROUP = "parentSectionGroup"
SECTION_GROUPS = "sectionGroups"
SECTIONS = "sections"
class Enum694(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)):
ID = "id"
ID_DESC = "id desc"
SELF = "self"
SELF_DESC = "self desc"
CREATED_DATE_TIME = "createdDateTime"
CREATED_DATE_TIME_DESC = "createdDateTime desc"
CREATED_BY = "createdBy"
CREATED_BY_DESC = "createdBy desc"
DISPLAY_NAME = "displayName"
DISPLAY_NAME_DESC = "displayName desc"
LAST_MODIFIED_BY = "lastModifiedBy"
LAST_MODIFIED_BY_DESC = "lastModifiedBy desc"
LAST_MODIFIED_DATE_TIME = "lastModifiedDateTime"
LAST_MODIFIED_DATE_TIME_DESC = "lastModifiedDateTime desc"
IS_DEFAULT = "isDefault"
IS_DEFAULT_DESC = "isDefault desc"
LINKS = "links"
LINKS_DESC = "links desc"
PAGES_URL = "pagesUrl"
PAGES_URL_DESC = "pagesUrl desc"
class Enum695(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)):
ID = "id"
SELF = "self"
CREATED_DATE_TIME = "createdDateTime"
CREATED_BY = "createdBy"
DISPLAY_NAME = "displayName"
LAST_MODIFIED_BY = "lastModifiedBy"
LAST_MODIFIED_DATE_TIME = "lastModifiedDateTime"
IS_DEFAULT = "isDefault"
LINKS = "links"
PAGES_URL = "pagesUrl"
PAGES = "pages"
PARENT_NOTEBOOK = "parentNotebook"
PARENT_SECTION_GROUP = "parentSectionGroup"
class Enum696(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)):
ASTERISK = "*"
PAGES = "pages"
PARENT_NOTEBOOK = "parentNotebook"
PARENT_SECTION_GROUP = "parentSectionGroup"
class Enum697(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)):
ID = "id"
SELF = "self"
CREATED_DATE_TIME = "createdDateTime"
CREATED_BY = "createdBy"
DISPLAY_NAME = "displayName"
LAST_MODIFIED_BY = "lastModifiedBy"
LAST_MODIFIED_DATE_TIME = "lastModifiedDateTime"
IS_DEFAULT = "isDefault"
LINKS = "links"
PAGES_URL = "pagesUrl"
PAGES = "pages"
PARENT_NOTEBOOK = "parentNotebook"
PARENT_SECTION_GROUP = "parentSectionGroup"
class Enum698(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)):
ASTERISK = "*"
PAGES = "pages"
PARENT_NOTEBOOK = "parentNotebook"
PARENT_SECTION_GROUP = "parentSectionGroup"
class Enum699(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)):
ID = "id"
ID_DESC = "id desc"
SELF = "self"
SELF_DESC = "self desc"
CREATED_DATE_TIME = "createdDateTime"
CREATED_DATE_TIME_DESC = "createdDateTime desc"
CREATED_BY = "createdBy"
CREATED_BY_DESC = "createdBy desc"
DISPLAY_NAME = "displayName"
DISPLAY_NAME_DESC = "displayName desc"
LAST_MODIFIED_BY = "lastModifiedBy"
LAST_MODIFIED_BY_DESC = "lastModifiedBy desc"
LAST_MODIFIED_DATE_TIME = "lastModifiedDateTime"
LAST_MODIFIED_DATE_TIME_DESC = "lastModifiedDateTime desc"
IS_DEFAULT = "isDefault"
IS_DEFAULT_DESC = "isDefault desc"
LINKS = "links"
LINKS_DESC = "links desc"
PAGES_URL = "pagesUrl"
PAGES_URL_DESC = "pagesUrl desc"
class Enum7(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)):
ID = "id"
SELF = "self"
CREATED_DATE_TIME = "createdDateTime"
CREATED_BY = "createdBy"
DISPLAY_NAME = "displayName"
LAST_MODIFIED_BY = "lastModifiedBy"
LAST_MODIFIED_DATE_TIME = "lastModifiedDateTime"
IS_DEFAULT = "isDefault"
IS_SHARED = "isShared"
LINKS = "links"
SECTION_GROUPS_URL = "sectionGroupsUrl"
SECTIONS_URL = "sectionsUrl"
USER_ROLE = "userRole"
SECTION_GROUPS = "sectionGroups"
SECTIONS = "sections"
class Enum70(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)):
ASTERISK = "*"
PAGES = "pages"
PARENT_NOTEBOOK = "parentNotebook"
PARENT_SECTION_GROUP = "parentSectionGroup"
class Enum700(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)):
ID | |
(Standards.ISIC4, "4922")),
((Standards.KSIC10, "49239"), (Standards.ISIC4, "4922")),
((Standards.KSIC10, "50201"), (Standards.ISIC4, "5021")),
((Standards.KSIC10, "49101"), (Standards.ISIC4, "4911")),
((Standards.KSIC10, "50111"), (Standards.ISIC4, "5011")),
((Standards.KSIC10, "50121"), (Standards.ISIC4, "5021")),
((Standards.KSIC10, "50201"), (Standards.ISIC4, "5011")),
((Standards.KSIC10, "50202"), (Standards.ISIC4, "5011")),
((Standards.KSIC10, "51100"), (Standards.ISIC4, "5110")),
((Standards.KSIC10, "49220"), (Standards.ISIC4, "4922")),
((Standards.KSIC10, "50121"), (Standards.ISIC4, "5011")),
((Standards.KSIC10, "49301"), (Standards.ISIC4, "4923")),
((Standards.KSIC10, "49309"), (Standards.ISIC4, "4923")),
((Standards.KSIC10, "49302"), (Standards.ISIC4, "4923")),
((Standards.KSIC10, "49303"), (Standards.ISIC4, "4923")),
((Standards.KSIC10, "49102"), (Standards.ISIC4, "4912")),
((Standards.KSIC10, "49500"), (Standards.ISIC4, "4930")),
((Standards.KSIC10, "50112"), (Standards.ISIC4, "5012")),
((Standards.KSIC10, "50130"), (Standards.ISIC4, "5012")),
((Standards.KSIC10, "50201"), (Standards.ISIC4, "5022")),
((Standards.KSIC10, "50209"), (Standards.ISIC4, "5022")),
((Standards.KSIC10, "51200"), (Standards.ISIC4, "5120")),
((Standards.KSIC10, "51100"), (Standards.ISIC4, "5120")),
((Standards.KSIC10, "52941"), (Standards.ISIC4, "5224")),
((Standards.KSIC10, "52913"), (Standards.ISIC4, "5224")),
((Standards.KSIC10, "52102"), (Standards.ISIC4, "5210")),
((Standards.KSIC10, "52104"), (Standards.ISIC4, "5210")),
((Standards.KSIC10, "52101"), (Standards.ISIC4, "5210")),
((Standards.KSIC10, "52103"), (Standards.ISIC4, "5210")),
((Standards.KSIC10, "52109"), (Standards.ISIC4, "5210")),
((Standards.KSIC10, "52911"), (Standards.ISIC4, "5221")),
((Standards.KSIC10, "52912"), (Standards.ISIC4, "5221")),
((Standards.KSIC10, "52914"), (Standards.ISIC4, "5221")),
((Standards.KSIC10, "52915"), (Standards.ISIC4, "5221")),
((Standards.KSIC10, "49301"), (Standards.ISIC4, "5221")),
((Standards.KSIC10, "52913"), (Standards.ISIC4, "5221")),
((Standards.KSIC10, "52921"), (Standards.ISIC4, "5222")),
((Standards.KSIC10, "52929"), (Standards.ISIC4, "5222")),
((Standards.KSIC10, "52931"), (Standards.ISIC4, "5223")),
((Standards.KSIC10, "52939"), (Standards.ISIC4, "5223")),
((Standards.KSIC10, "52991"), (Standards.ISIC4, "5229")),
((Standards.KSIC10, "52993"), (Standards.ISIC4, "5229")),
((Standards.KSIC10, "52919"), (Standards.ISIC4, "5221")),
((Standards.KSIC10, "52999"), (Standards.ISIC4, "5229")),
((Standards.KSIC10, "49401"), (Standards.ISIC4, "5320")),
((Standards.KSIC10, "49402"), (Standards.ISIC4, "5320")),
((Standards.KSIC10, "35120"), (Standards.ISIC4, "3510")),
((Standards.KSIC10, "35130"), (Standards.ISIC4, "3510")),
((Standards.KSIC10, "36010"), (Standards.ISIC4, "3600")),
((Standards.KSIC10, "64110"), (Standards.ISIC4, "6411")),
((Standards.KSIC10, "64121"), (Standards.ISIC4, "6419")),
((Standards.KSIC10, "64122"), (Standards.ISIC4, "6492")),
((Standards.KSIC10, "64121"), (Standards.ISIC4, "6492")),
((Standards.KSIC10, "64911"), (Standards.ISIC4, "6491")),
((Standards.KSIC10, "64991"), (Standards.ISIC4, "6499")),
((Standards.KSIC10, "64201"), (Standards.ISIC4, "6499")),
((Standards.KSIC10, "65110"), (Standards.ISIC4, "6511")),
((Standards.KSIC10, "65301"), (Standards.ISIC4, "6530")),
((Standards.KSIC10, "65302"), (Standards.ISIC4, "6530")),
((Standards.KSIC10, "65110"), (Standards.ISIC4, "6512")),
((Standards.KSIC10, "65121"), (Standards.ISIC4, "6512")),
((Standards.KSIC10, "65122"), (Standards.ISIC4, "6512")),
((Standards.KSIC10, "65200"), (Standards.ISIC4, "6520")),
((Standards.KSIC10, "64999"), (Standards.ISIC4, "6619")),
((Standards.KSIC10, "66121"), (Standards.ISIC4, "6612")),
((Standards.KSIC10, "66199"), (Standards.ISIC4, "6619")),
((Standards.KSIC10, "64209"), (Standards.ISIC4, "6630")),
((Standards.KSIC10, "66191"), (Standards.ISIC4, "6619")),
((Standards.KSIC10, "66110"), (Standards.ISIC4, "6611")),
((Standards.KSIC10, "66192"), (Standards.ISIC4, "6619")),
((Standards.KSIC10, "66199"), (Standards.ISIC4, "6612")),
((Standards.KSIC10, "66202"), (Standards.ISIC4, "6622")),
((Standards.KSIC10, "66201"), (Standards.ISIC4, "6621")),
((Standards.KSIC10, "66209"), (Standards.ISIC4, "6629")),
((Standards.KSIC10, "66209"), (Standards.ISIC4, "6630")),
((Standards.KSIC10, "66201"), (Standards.ISIC4, "6629")),
((Standards.KSIC10, "64992"), (Standards.ISIC4, "6420")),
((Standards.KSIC10, "64201"), (Standards.ISIC4, "6430")),
((Standards.KSIC10, "68111"), (Standards.ISIC4, "6810")),
((Standards.KSIC10, "68112"), (Standards.ISIC4, "6810")),
((Standards.KSIC10, "68121"), (Standards.ISIC4, "6810")),
((Standards.KSIC10, "68122"), (Standards.ISIC4, "6810")),
((Standards.KSIC10, "68129"), (Standards.ISIC4, "6810")),
((Standards.KSIC10, "68211"), (Standards.ISIC4, "6820")),
((Standards.KSIC10, "68212"), (Standards.ISIC4, "6820")),
((Standards.KSIC10, "68221"), (Standards.ISIC4, "6820")),
((Standards.KSIC10, "68223"), (Standards.ISIC4, "6820")),
((Standards.KSIC10, "68222"), (Standards.ISIC4, "6820")),
((Standards.KSIC10, "76110"), (Standards.ISIC4, "7710")),
((Standards.KSIC10, "76190"), (Standards.ISIC4, "7730")),
((Standards.KSIC10, "76190"), (Standards.ISIC4, "7710")),
((Standards.KSIC10, "76390"), (Standards.ISIC4, "7730")),
((Standards.KSIC10, "76310"), (Standards.ISIC4, "7730")),
((Standards.KSIC10, "76320"), (Standards.ISIC4, "7730")),
((Standards.KSIC10, "76299"), (Standards.ISIC4, "7729")),
((Standards.KSIC10, "76220"), (Standards.ISIC4, "7722")),
((Standards.KSIC10, "76210"), (Standards.ISIC4, "7721")),
((Standards.KSIC10, "76292"), (Standards.ISIC4, "7729")),
((Standards.KSIC10, "76291"), (Standards.ISIC4, "7729")),
((Standards.KSIC10, "58112"), (Standards.ISIC4, "5813")),
((Standards.KSIC10, "58113"), (Standards.ISIC4, "5911")),
((Standards.KSIC10, "58121"), (Standards.ISIC4, "5912")),
((Standards.KSIC10, "58122"), (Standards.ISIC4, "5913")),
((Standards.KSIC10, "58123"), (Standards.ISIC4, "5920")),
((Standards.KSIC10, "59111"), (Standards.ISIC4, "9000")),
((Standards.KSIC10, "76400"), (Standards.ISIC4, "7740")),
((Standards.KSIC10, "70111"), (Standards.ISIC4, "7210")),
((Standards.KSIC10, "70129"), (Standards.ISIC4, "7210")),
((Standards.KSIC10, "70121"), (Standards.ISIC4, "7210")),
((Standards.KSIC10, "70113"), (Standards.ISIC4, "7210")),
((Standards.KSIC10, "70112"), (Standards.ISIC4, "7210")),
((Standards.KSIC10, "70119"), (Standards.ISIC4, "7210")),
((Standards.KSIC10, "70209"), (Standards.ISIC4, "7220")),
((Standards.KSIC10, "70201"), (Standards.ISIC4, "7220")),
((Standards.KSIC10, "70130"), (Standards.ISIC4, "7210")),
((Standards.KSIC10, "71101"), (Standards.ISIC4, "6910")),
((Standards.KSIC10, "71102"), (Standards.ISIC4, "6910")),
((Standards.KSIC10, "71103"), (Standards.ISIC4, "6910")),
((Standards.KSIC10, "71109"), (Standards.ISIC4, "6910")),
((Standards.KSIC10, "71201"), (Standards.ISIC4, "6920")),
((Standards.KSIC10, "71202"), (Standards.ISIC4, "6920")),
((Standards.KSIC10, "71209"), (Standards.ISIC4, "6920")),
((Standards.KSIC10, "71101"), (Standards.ISIC4, "7020")),
((Standards.KSIC10, "71531"), (Standards.ISIC4, "7020")),
((Standards.KSIC10, "71511"), (Standards.ISIC4, "7010")),
((Standards.KSIC10, "71519"), (Standards.ISIC4, "7020")),
((Standards.KSIC10, "71532"), (Standards.ISIC4, "7020")),
((Standards.KSIC10, "62021"), (Standards.ISIC4, "6202")),
((Standards.KSIC10, "62022"), (Standards.ISIC4, "6202")),
((Standards.KSIC10, "62010"), (Standards.ISIC4, "6201")),
((Standards.KSIC10, "63112"), (Standards.ISIC4, "6311")),
((Standards.KSIC10, "63111"), (Standards.ISIC4, "6311")),
((Standards.KSIC10, "72111"), (Standards.ISIC4, "7110")),
((Standards.KSIC10, "72112"), (Standards.ISIC4, "7110")),
((Standards.KSIC10, "72129"), (Standards.ISIC4, "7110")),
((Standards.KSIC10, "72121"), (Standards.ISIC4, "7110")),
((Standards.KSIC10, "72923"), (Standards.ISIC4, "7110")),
((Standards.KSIC10, "72921"), (Standards.ISIC4, "7110")),
((Standards.KSIC10, "72924"), (Standards.ISIC4, "7110")),
((Standards.KSIC10, "73909"), (Standards.ISIC4, "7490")),
((Standards.KSIC10, "72911"), (Standards.ISIC4, "7120")),
((Standards.KSIC10, "72919"), (Standards.ISIC4, "7120")),
((Standards.KSIC10, "73100"), (Standards.ISIC4, "7500")),
((Standards.KSIC10, "71310"), (Standards.ISIC4, "7310")),
((Standards.KSIC10, "71391"), (Standards.ISIC4, "7310")),
((Standards.KSIC10, "71392"), (Standards.ISIC4, "7310")),
((Standards.KSIC10, "58123"), (Standards.ISIC4, "5813")),
((Standards.KSIC10, "60100"), (Standards.ISIC4, "6010")),
((Standards.KSIC10, "60210"), (Standards.ISIC4, "6020")),
((Standards.KSIC10, "63120"), (Standards.ISIC4, "6312")),
((Standards.KSIC10, "59113"), (Standards.ISIC4, "5811")),
((Standards.KSIC10, "71391"), (Standards.ISIC4, "5812")),
((Standards.KSIC10, "71400"), (Standards.ISIC4, "7320")),
((Standards.KSIC10, "73302"), (Standards.ISIC4, "7420")),
((Standards.KSIC10, "73201"), (Standards.ISIC4, "7410")),
((Standards.KSIC10, "73202"), (Standards.ISIC4, "7410")),
((Standards.KSIC10, "73209"), (Standards.ISIC4, "7410")),
((Standards.KSIC10, "73904"), (Standards.ISIC4, "7490")),
((Standards.KSIC10, "73902"), (Standards.ISIC4, "7490")),
((Standards.KSIC10, "73901"), (Standards.ISIC4, "7490")),
((Standards.KSIC10, "73903"), (Standards.ISIC4, "7490")),
((Standards.KSIC10, "61210"), (Standards.ISIC4, "6110")),
((Standards.KSIC10, "61210"), (Standards.ISIC4, "6120")),
((Standards.KSIC10, "61220"), (Standards.ISIC4, "6130")),
((Standards.KSIC10, "61299"), (Standards.ISIC4, "6190")),
((Standards.KSIC10, "61220"), (Standards.ISIC4, "6110")),
((Standards.KSIC10, "61299"), (Standards.ISIC4, "6130")),
((Standards.KSIC10, "61220"), (Standards.ISIC4, "6120")),
((Standards.KSIC10, "61299"), (Standards.ISIC4, "6120")),
((Standards.KSIC10, "61291"), (Standards.ISIC4, "6110")),
((Standards.KSIC10, "61291"), (Standards.ISIC4, "6120")),
((Standards.KSIC10, "61291"), (Standards.ISIC4, "6130")),
((Standards.KSIC10, "61291"), (Standards.ISIC4, "6190")),
((Standards.KSIC10, "61299"), (Standards.ISIC4, "6110")),
((Standards.KSIC10, "59112"), (Standards.ISIC4, "5911")),
((Standards.KSIC10, "58212"), (Standards.ISIC4, "5820")),
((Standards.KSIC10, "63910"), (Standards.ISIC4, "6391")),
((Standards.KSIC10, "90211"), (Standards.ISIC4, "9101")),
((Standards.KSIC10, "60210"), (Standards.ISIC4, "6010")),
((Standards.KSIC10, "60221"), (Standards.ISIC4, "6020")),
((Standards.KSIC10, "60222"), (Standards.ISIC4, "6010")),
((Standards.KSIC10, "60229"), (Standards.ISIC4, "6010")),
((Standards.KSIC10, "60221"), (Standards.ISIC4, "6010")),
((Standards.KSIC10, "75110"), (Standards.ISIC4, "7810")),
((Standards.KSIC10, "75121"), (Standards.ISIC4, "7810")),
((Standards.KSIC10, "75122"), (Standards.ISIC4, "7830")),
((Standards.KSIC10, "75330"), (Standards.ISIC4, "8030")),
((Standards.KSIC10, "75320"), (Standards.ISIC4, "8020")),
((Standards.KSIC10, "75310"), (Standards.ISIC4, "8010")),
((Standards.KSIC10, "74220"), (Standards.ISIC4, "8129")),
((Standards.KSIC10, "74212"), (Standards.ISIC4, "8129")),
((Standards.KSIC10, "74211"), (Standards.ISIC4, "8121")),
((Standards.KSIC10, "75994"), (Standards.ISIC4, "8292")),
((Standards.KSIC10, "75210"), (Standards.ISIC4, "7911")),
((Standards.KSIC10, "75210"), (Standards.ISIC4, "7990")),
((Standards.KSIC10, "75290"), (Standards.ISIC4, "7990")),
((Standards.KSIC10, "75992"), (Standards.ISIC4, "7990")),
((Standards.KSIC10, "75210"), (Standards.ISIC4, "7912")),
((Standards.KSIC10, "75993"), (Standards.ISIC4, "8291")),
((Standards.KSIC10, "75991"), (Standards.ISIC4, "8220")),
((Standards.KSIC10, "71600"), (Standards.ISIC4, "8211")),
((Standards.KSIC10, "75912"), (Standards.ISIC4, "8219")),
((Standards.KSIC10, "75999"), (Standards.ISIC4, "8299")),
((Standards.KSIC10, "75919"), (Standards.ISIC4, "8219")),
((Standards.KSIC10, "75911"), (Standards.ISIC4, "8219")),
((Standards.KSIC10, "75992"), (Standards.ISIC4, "8230")),
((Standards.KSIC10, "74300"), (Standards.ISIC4, "8130")),
((Standards.KSIC10, "74100"), (Standards.ISIC4, "7490")),
((Standards.KSIC10, "63991"), (Standards.ISIC4, "6399")),
((Standards.KSIC10, "73903"), (Standards.ISIC4, "8299")),
((Standards.KSIC10, "01412"), (Standards.ISIC4, "0163")),
((Standards.KSIC10, "01411"), (Standards.ISIC4, "0164")),
((Standards.KSIC10, "01411"), (Standards.ISIC4, "0111")),
((Standards.KSIC10, "01420"), (Standards.ISIC4, "0141")),
((Standards.KSIC10, "96995"), (Standards.ISIC4, "9609")),
((Standards.KSIC10, "01500"), (Standards.ISIC4, "0170")),
((Standards.KSIC10, "91199"), (Standards.ISIC4, "9319")),
((Standards.KSIC10, "02040"), (Standards.ISIC4, "0210")),
((Standards.KSIC10, "02040"), (Standards.ISIC4, "0240")),
((Standards.KSIC10, "03220"), (Standards.ISIC4, "0311")),
((Standards.KSIC10, "03220"), (Standards.ISIC4, "0321")),
((Standards.KSIC10, "08000"), (Standards.ISIC4, "0610")),
((Standards.KSIC10, "08000"), (Standards.ISIC4, "0510")),
((Standards.KSIC10, "34019"), (Standards.ISIC4, "3311")),
((Standards.KSIC10, "34019"), (Standards.ISIC4, "3312")),
((Standards.KSIC10, "34019"), (Standards.ISIC4, "9511")),
((Standards.KSIC10, "95211"), (Standards.ISIC4, "4520")),
((Standards.KSIC10, "95212"), (Standards.ISIC4, "4520")),
((Standards.KSIC10, "95213"), (Standards.ISIC4, "4520")),
((Standards.KSIC10, "95220"), (Standards.ISIC4, "4540")),
((Standards.KSIC10, "34019"), (Standards.ISIC4, "3315")),
((Standards.KSIC10, "95399"), (Standards.ISIC4, "9522")),
((Standards.KSIC10, "34020"), (Standards.ISIC4, "3314")),
((Standards.KSIC10, "95120"), (Standards.ISIC4, "9512")),
((Standards.KSIC10, "34020"), (Standards.ISIC4, "3313")),
((Standards.KSIC10, "95310"), (Standards.ISIC4, "9521")),
((Standards.KSIC10, "34011"), (Standards.ISIC4, "3312")),
((Standards.KSIC10, "34019"), (Standards.ISIC4, "4329")),
((Standards.KSIC10, "34019"), (Standards.ISIC4, "3319")),
((Standards.KSIC10, "95392"), (Standards.ISIC4, "9523")),
((Standards.KSIC10, "95393"), (Standards.ISIC4, "9529")),
((Standards.KSIC10, "95391"), (Standards.ISIC4, "9529")),
((Standards.KSIC10, "95399"), (Standards.ISIC4, "9524")),
((Standards.KSIC10, "95399"), (Standards.ISIC4, "3313")),
((Standards.KSIC10, "72129"), (Standards.ISIC4, "3320")),
((Standards.KSIC10, "62090"), (Standards.ISIC4, "6209")),
((Standards.KSIC10, "73909"), (Standards.ISIC4, "9521")),
((Standards.KSIC10, "10711"), (Standards.ISIC4, "1071")),
((Standards.KSIC10, "11201"), (Standards.ISIC4, "1104")),
((Standards.KSIC10, "13401"), (Standards.ISIC4, "1313")),
((Standards.KSIC10, "13402"), (Standards.ISIC4, "1313")),
((Standards.KSIC10, "13403"), (Standards.ISIC4, "1313")),
((Standards.KSIC10, "13409"), (Standards.ISIC4, "1313")),
((Standards.KSIC10, "14300"), (Standards.ISIC4, "1430")),
((Standards.KSIC10, "22191"), (Standards.ISIC4, "2219")),
((Standards.KSIC10, "25921"), (Standards.ISIC4, "2592")),
((Standards.KSIC10, "27193"), (Standards.ISIC4, "2670")),
((Standards.KSIC10, "30310"), (Standards.ISIC4, "2930")),
((Standards.KSIC10, "31999"), (Standards.ISIC4, "3099")),
((Standards.KSIC10, "30393"), (Standards.ISIC4, "3100")),
((Standards.KSIC10, "33402"), (Standards.ISIC4, "3240")),
((Standards.KSIC10, "33409"), (Standards.ISIC4, "3290")),
((Standards.KSIC10, "58121"), (Standards.ISIC4, "5819")),
((Standards.KSIC10, "58123"), (Standards.ISIC4, "5820")),
((Standards.KSIC10, "58190"), (Standards.ISIC4, "5920")),
((Standards.KSIC10, "18122"), (Standards.ISIC4, "1812")),
((Standards.KSIC10, "18200"), (Standards.ISIC4, "1820")),
((Standards.KSIC10, "24311"), (Standards.ISIC4, "2431")),
((Standards.KSIC10, "24321"), (Standards.ISIC4, "2432")),
((Standards.KSIC10, "25911"), (Standards.ISIC4, "2591")),
((Standards.KSIC10, "38311"), (Standards.ISIC4, "3830")),
((Standards.KSIC10, "38321"), (Standards.ISIC4, "3830")),
((Standards.KSIC10, "84111"), (Standards.ISIC4, "8411")),
((Standards.KSIC10, "84114"), (Standards.ISIC4, "8411")),
((Standards.KSIC10, "84119"), (Standards.ISIC4, "8411")),
((Standards.KSIC10, "84211"), (Standards.ISIC4, "8412")),
((Standards.KSIC10, "84214"), (Standards.ISIC4, "8412")),
((Standards.KSIC10, "84213"), (Standards.ISIC4, "8412")),
((Standards.KSIC10, "84212"), (Standards.ISIC4, "8412")),
((Standards.KSIC10, "84222"), (Standards.ISIC4, "8413")),
((Standards.KSIC10, "84229"), (Standards.ISIC4, "8413")),
((Standards.KSIC10, "84223"), (Standards.ISIC4, "8413")),
((Standards.KSIC10, "84120"), (Standards.ISIC4, "8413")),
((Standards.KSIC10, "84212"), (Standards.ISIC4, "8413")),
((Standards.KSIC10, "84221"), (Standards.ISIC4, "8413")),
((Standards.KSIC10, "84120"), (Standards.ISIC4, "8411")),
((Standards.KSIC10, "84310"), (Standards.ISIC4, "8421")),
((Standards.KSIC10, "84320"), (Standards.ISIC4, "8422")),
((Standards.KSIC10, "84404"), (Standards.ISIC4, "8423")),
((Standards.KSIC10, "84405"), (Standards.ISIC4, "8423")),
((Standards.KSIC10, "84401"), (Standards.ISIC4, "8423")),
((Standards.KSIC10, "84402"), (Standards.ISIC4, "8423")),
((Standards.KSIC10, "84403"), (Standards.ISIC4, "8423")),
((Standards.KSIC10, "84409"), (Standards.ISIC4, "8423")),
((Standards.KSIC10, "65131"), (Standards.ISIC4, "8430")),
((Standards.KSIC10, "65303"), (Standards.ISIC4, "8430")),
((Standards.KSIC10, "65139"), (Standards.ISIC4, "8430")),
((Standards.KSIC10, "84500"), (Standards.ISIC4, "8430")),
((Standards.KSIC10, "85110"), (Standards.ISIC4, "8510")),
((Standards.KSIC10, "85120"), (Standards.ISIC4, "8510")),
((Standards.KSIC10, "85211"), (Standards.ISIC4, "8521")),
((Standards.KSIC10, "85212"), (Standards.ISIC4, "8521")),
((Standards.KSIC10, "85221"), (Standards.ISIC4, "8522")),
((Standards.KSIC10, "85222"), (Standards.ISIC4, "8522")),
((Standards.KSIC10, "85229"), (Standards.ISIC4, "8522")),
((Standards.KSIC10, "85301"), (Standards.ISIC4, "8530")),
((Standards.KSIC10, "85302"), (Standards.ISIC4, "8530")),
((Standards.KSIC10, "85621"), (Standards.ISIC4, "8542")),
((Standards.KSIC10, "85611"), (Standards.ISIC4, "8541")),
((Standards.KSIC10, "85613"), (Standards.ISIC4, "8541")),
((Standards.KSIC10, "85640"), (Standards.ISIC4, "8549")),
((Standards.KSIC10, "85650"), (Standards.ISIC4, "8549")),
((Standards.KSIC10, "85661"), (Standards.ISIC4, "8549")),
((Standards.KSIC10, "85669"), (Standards.ISIC4, "8549")),
((Standards.KSIC10, "85501"), (Standards.ISIC4, "8549")),
((Standards.KSIC10, "85631"), (Standards.ISIC4, "8549")),
((Standards.KSIC10, "85502"), (Standards.ISIC4, "8549")),
((Standards.KSIC10, "85503"), (Standards.ISIC4, "8549")),
((Standards.KSIC10, "85632"), (Standards.ISIC4, "8549")),
((Standards.KSIC10, "85410"), (Standards.ISIC4, "8510")),
((Standards.KSIC10, "85420"), | |
args, defines)
def _instr_ori(args, instr_addr, symtab, defines):
return _instr_2reg_imm(_opcode_of('ori'), args, defines)
def _instr_andi(args, instr_addr, symtab, defines):
return _instr_2reg_imm(_opcode_of('andi'), args, defines)
def _instr_slli(args, instr_addr, symtab, defines):
return _instr_2reg_imm(_opcode_of('slli'), args, defines)
def _instr_srli(args, instr_addr, symtab, defines):
return _instr_2reg_imm(_opcode_of('srli'), args, defines)
def _instr_lli(args, instr_addr, symtab, defines):
# Pseudo-instruction: ORI rd, r0, const16
return _instr_2reg_imm( _opcode_of('ori'),
[args[0], Id('$r0'), args[1]],
defines)
def _instr_lui(args, instr_addr, symtab, defines):
rd = _reg(args[0])
c16 = _define_or_const(args[1], defines)
return AssembledInstruction(
op= build_bitfield(31, 26, _opcode_of('lui')) |
build_bitfield(25, 21, rd) |
build_bitfield(20, 16, 0) |
build_bitfield(15, 0, c16))
def _instr_load(op, args, defines):
""" A template for all Load instructions.
"""
rd = _reg(args[0])
rs, off16 = _memref(args[1], defines)
return AssembledInstruction(
op= build_bitfield(31, 26, op) |
build_bitfield(25, 21, rd) |
build_bitfield(20, 16, rs) |
build_bitfield(15, 0, off16))
def _instr_store(op, args, defines):
""" A template for all Store instructions.
"""
rs = _reg(args[0])
rd, off16 = _memref(args[1], defines)
return AssembledInstruction(
op= build_bitfield(31, 26, op) |
build_bitfield(25, 21, rd) |
build_bitfield(20, 16, rs) |
build_bitfield(15, 0, off16))
def _instr_lb(args, instr_addr, symtab, defines):
return _instr_load(_opcode_of('lb'), args, defines)
def _instr_lbu(args, instr_addr, symtab, defines):
return _instr_load(_opcode_of('lbu'), args, defines)
def _instr_lh(args, instr_addr, symtab, defines):
return _instr_load(_opcode_of('lh'), args, defines)
def _instr_lhu(args, instr_addr, symtab, defines):
return _instr_load(_opcode_of('lhu'), args, defines)
def _instr_lw(args, instr_addr, symtab, defines):
return _instr_load(_opcode_of('lw'), args, defines)
def _instr_sb(args, instr_addr, symtab, defines):
return _instr_store(_opcode_of('sb'), args, defines)
def _instr_sh(args, instr_addr, symtab, defines):
return _instr_store(_opcode_of('sh'), args, defines)
def _instr_sw(args, instr_addr, symtab, defines):
return _instr_store(_opcode_of('sw'), args, defines)
def _instr_jr(args, instr_addr, symtab, defines):
rd = _reg(args[0])
return AssembledInstruction(
op= build_bitfield(31, 26, _opcode_of('jr')) |
build_bitfield(25, 21, rd) |
build_bitfield(20, 0, 0))
def _instr_ret(args, instr_addr, symtab, defines):
# Pseudo-instruction: JR $ra
return _instr_jr([Id('$ra')], instr_addr, symtab, defines)
def _instr_b(args, instr_addr, symtab, defines):
off26 = _branch_offset(args[0], 26, instr_addr, symtab)
# Note: _branch_offset makes sure that the offset fits into
# a signed 26-bit field, so it's OK to take out the low 26
# bits from it with build_bitfield.
#
return AssembledInstruction(
op= build_bitfield(31, 26, _opcode_of('b')) |
build_bitfield(25, 0, off26))
def _instr_branch(op, args, instr_addr, symtab):
""" A template for all conditional relative branch
instructions.
"""
rd = _reg(args[0])
rs = _reg(args[1])
off16 = _branch_offset(args[2], 16, instr_addr, symtab)
# Note: _branch_offset makes sure that the offset fits into
# a signed 16-bit field, so it's OK to take out the low 16
# bits from it with build_bitfield.
#
return AssembledInstruction(
op= build_bitfield(31, 26, op) |
build_bitfield(25, 21, rd) |
build_bitfield(20, 16, rs) |
build_bitfield(15, 0, off16))
def _instr_beq(args, instr_addr, symtab, defines):
return _instr_branch(_opcode_of('beq'), args, instr_addr, symtab)
def _instr_bne(args, instr_addr, symtab, defines):
return _instr_branch(_opcode_of('bne'), args, instr_addr, symtab)
def _instr_bge(args, instr_addr, symtab, defines):
return _instr_branch(_opcode_of('bge'), args, instr_addr, symtab)
def _instr_bgt(args, instr_addr, symtab, defines):
return _instr_branch(_opcode_of('bgt'), args, instr_addr, symtab)
def _instr_ble(args, instr_addr, symtab, defines):
return _instr_branch(_opcode_of('ble'), args, instr_addr, symtab)
def _instr_blt(args, instr_addr, symtab, defines):
return _instr_branch(_opcode_of('blt'), args, instr_addr, symtab)
def _instr_bgeu(args, instr_addr, symtab, defines):
return _instr_branch(_opcode_of('bgeu'), args, instr_addr, symtab)
def _instr_bgtu(args, instr_addr, symtab, defines):
return _instr_branch(_opcode_of('bgtu'), args, instr_addr, symtab)
def _instr_bleu(args, instr_addr, symtab, defines):
return _instr_branch(_opcode_of('bleu'), args, instr_addr, symtab)
def _instr_bltu(args, instr_addr, symtab, defines):
return _instr_branch(_opcode_of('bltu'), args, instr_addr, symtab)
def _instr_beqz(args, instr_addr, symtab, defines):
# Pseudo-instruction: implemented as BEQ with r0 as the
# second argument
#
args = [args[0], Id('$r0'), args[1]]
return _instr_branch(_opcode_of('beq'), args, instr_addr, symtab)
def _instr_bnez(args, instr_addr, symtab, defines):
# Pseudo-instruction: implemented as BNE with r0 as the
# second argument
#
args = [args[0], Id('$r0'), args[1]]
return _instr_branch(_opcode_of('bne'), args, instr_addr, symtab)
def _instr_eret(args, instr_addr, symtab, defines):
return AssembledInstruction(
op= build_bitfield(31, 26, _opcode_of('eret')))
def _instr_halt(args, instr_addr, symtab, defines):
return AssembledInstruction(
op= build_bitfield(31, 26, _opcode_of('halt')))
def _instr_call(args, instr_addr, symtab, defines):
# CALL accepts an absolute address or a label. The label can
# either be external (not defined in the symbol table) or
# internal (defined in the symbol table).
#
# External labels:
# We don't know what the address of an external label is.
# Therefore, an import request is added into the assembled
# instruction. This import request will be connected to this
# instruction and the linker will patch the destination
# address when it becomes known.
#
# Internal labels:
# For internal labels a relocation is required. The label's
# address will be inserted into the destination field of the
# instruction, and a relocation request for the segment in
# which the label is defined will be returned with the
# assembled instruction. This relocation request will be
# seen by the linker that will patch the destination once the
# relocation address of the segment becomes known.
#
opcode_field = build_bitfield(31, 26, _opcode_of('call'))
if (isinstance(args[0], Number) or
(isinstance(args[0], Id) and args[0].id in defines)
):
# Number or defined constant
#
num = _define_or_const(args[0], defines, 26)
return AssembledInstruction(
op=opcode_field | build_bitfield(25, 0, num))
elif isinstance(args[0], Id):
label = args[0].id
if label in symtab:
# Relocation: place the label value into the
# destination field, and specify a relocation for the
# label's segment.
#
segment, addr = symtab[label]
return AssembledInstruction(
op= opcode_field |
build_bitfield(25, 0, addr / 4),
reloc_req=(RelocType.CALL, segment))
else:
# Import symbol: leave the destination field empty
# and specify an import symbol in the assembled
# instruction.
#
return AssembledInstruction(
op=opcode_field,
import_req=(ImportType.CALL, label))
else:
raise InstructionError('Invalid CALL destination: %s' % args[0])
def _instr_li(args, instr_addr, symtab, defines):
# Creates two instructions (LUI and ORI).
# The handling of labels is similar to _instr_call, except
# that the import/relocation information is computed for the
# LUI&ORI pair and a single import/reloc_req is created, only
# for LUI.
#
if (isinstance(args[1], Number) or
(isinstance(args[1], Id) and args[1].id in defines)
):
num = _define_or_const(args[1], defines, 32)
low_word = extract_bitfield(num, left=15, right=0)
high_word = extract_bitfield(num, left=31, right=16)
return [
_instr_lui( [args[0], Number(high_word)],
instr_addr, symtab, defines),
_instr_ori( [args[0], args[0], Number(low_word)],
instr_addr, symtab, defines)
]
elif isinstance(args[1], Id):
label = args[1].id
if label in symtab:
# Relocation
segment, addr = symtab[label]
low_word = extract_bitfield(addr, left=15, right=0)
high_word = extract_bitfield(addr, left=31, right=16)
lui = _instr_lui( [args[0], Number(high_word)],
instr_addr, symtab, defines)
ori = _instr_ori( [args[0], args[0], Number(low_word)],
instr_addr, symtab, defines)
lui.reloc_req = (RelocType.LI, segment)
return [lui, ori]
else:
# Import
lui = _instr_lui( [args[0], Number(0)],
instr_addr, symtab, defines)
ori = _instr_ori( [args[0], args[0], Number(0)],
instr_addr, symtab, defines)
lui.import_req = (ImportType.LI, label)
return [lui, ori]
else:
raise InstructionError('Invalid LI destination: %s' % args[1])
#
# The following functions are utilities for the use of the
# instruction constructors.
#
def _branch_offset(arg, nbits, instr_addr, symtab):
""" Constructor for relative branch offsets. Such an offset
can either be specified as an integer or as a label.
Integers are the simple case.
For labels, the instruction address is queried for the
segment and address of the instruction being assemblied,
and the label is extracted from the symbol table.
The segments of the label and instruction must match, and
the offset between them must be small enough to fit into
nbits as a signed number (also taking into account that
the offset is computed in words, not bytes).
If everyting is successful, the offset is returned.
"""
if isinstance(arg, Number):
num = arg.val
if num_fits_in_nbits(num, nbits, signed=True):
return num
else:
raise InstructionError('Branch offset too large for %d bits' % nbits)
elif not isinstance(arg, Id):
raise InstructionError('Invalid branch offset: %s' % arg)
label = arg.id
if not label in symtab:
raise InstructionError('Undefined label: %s' % label)
label_addr = symtab[label]
if label_addr[0] != instr_addr[0]:
raise InstructionError('Branch target in different segment')
elif label_addr[1] % 4 != 0:
raise InstructionError('Branch label not aligned at word boundary')
relative_offset = (label_addr[1] - instr_addr[1]) / 4
if not num_fits_in_nbits(relative_offset, nbits, signed=True):
raise InstructionError('Branch offset too large for %d bits' % nbits)
return relative_offset
# Alias names for registers
#
register_alias = {
'$zero': 0,
'$at': 1,
'$v0': 2,
'$v1': 3,
'$a0': 4,
'$a1': 5,
'$a2': 6,
'$a3': 7,
'$t0': 8,
'$t1': 9,
'$t2': 10,
'$t3': 11,
'$t4': 12,
'$t5': 13,
'$t6': 14,
'$t7': 15,
'$t8': 16,
'$t9': 17,
'$s0': 18,
'$s1': 19,
'$s2': 20,
'$s3': 21,
'$s4': 22,
'$s5': 23,
'$s6': 24,
'$s7': 25,
'$k0': 26,
'$k1': 27,
'$fp': 28,
'$sp': 29,
'$re': 30,
'$ra': 31,
}
# Inverted register_alias dictionary for lookup of aliases of
# | |
(Parkinson's)
query = { "previous_message_processing_plan": { "processing_actions": [
"create_message",
"add_qnode(name=DOID:14330, id=n00)",
"add_qnode(type=protein, is_set=true, id=n01)",
"add_qnode(type=chemical_substance, id=n02)",
"add_qedge(source_id=n00, target_id=n01, id=e00)",
"add_qedge(source_id=n01, target_id=n02, id=e01, type=molecularly_interacts_with)", # for KG2
#"add_qedge(source_id=n01, target_id=n02, id=e01, type=physically_interacts_with)", # for KG1
"expand(edge_id=[e00,e01], kp=ARAX/KG2)", # for KG2
#"expand(edge_id=[e00,e01], kp=ARAX/KG1)", # for KG1
"overlay(action=compute_jaccard, start_node_id=n00, intermediate_node_id=n01, end_node_id=n02, virtual_relation_label=J1)", # seems to work just fine
"filter_kg(action=remove_edges_by_attribute, edge_attribute=jaccard_index, direction=below, threshold=.008, remove_connected_nodes=t, qnode_id=n02)",
"resultify(ignore_edge_direction=true)",
"filter_results(action=sort_by_edge_attribute, edge_attribute=jaccard_index, direction=descending, max_results=15)",
"return(message=true, store=false)",
] } }
elif params.example_number == 203: # KG2 version of demo example 3 (but using idiopathic pulmonary fibrosis)
query = { "previous_message_processing_plan": { "processing_actions": [
"create_message",
#"add_qnode(id=n00, curie=DOID:0050156)", # idiopathic pulmonary fibrosis
"add_qnode(curie=DOID:9406, id=n00)", # hypopituitarism, original demo example
"add_qnode(id=n01, type=chemical_substance, is_set=true)",
"add_qnode(id=n02, type=protein)",
"add_qedge(id=e00, source_id=n00, target_id=n01)",
"add_qedge(id=e01, source_id=n01, target_id=n02)",
"expand(edge_id=[e00,e01], kp=ARAX/KG2)",
"overlay(action=overlay_clinical_info, observed_expected_ratio=true, virtual_relation_label=C1, source_qnode_id=n00, target_qnode_id=n01)",
"overlay(action=compute_ngd, virtual_relation_label=N1, source_qnode_id=n01, target_qnode_id=n02)",
"filter_kg(action=remove_edges_by_attribute, edge_attribute=observed_expected_ratio, direction=below, threshold=2, remove_connected_nodes=t, qnode_id=n01)",
"filter_kg(action=remove_orphaned_nodes, node_type=protein)",
"return(message=true, store=false)",
] } }
elif params.example_number == 2033: # KG2 version of demo example 3 (but using idiopathic pulmonary fibrosis), with all decorations
query = { "previous_message_processing_plan": { "processing_actions": [
"create_message",
"add_qnode(id=n00, curie=DOID:0050156)", # idiopathic pulmonary fibrosis
#"add_qnode(curie=DOID:9406, id=n00)", # hypopituitarism, original demo example
"add_qnode(id=n01, type=chemical_substance, is_set=true)",
"add_qnode(id=n02, type=protein)",
"add_qedge(id=e00, source_id=n00, target_id=n01)",
"add_qedge(id=e01, source_id=n01, target_id=n02)",
"expand(edge_id=[e00,e01], kp=ARAX/KG2)",
"overlay(action=overlay_clinical_info, observed_expected_ratio=true, virtual_relation_label=C1, source_qnode_id=n00, target_qnode_id=n01)",
"overlay(action=compute_ngd, virtual_relation_label=N1, source_qnode_id=n01, target_qnode_id=n02)",
#"filter_kg(action=remove_edges_by_attribute, edge_attribute=observed_expected_ratio, direction=below, threshold=0, remove_connected_nodes=t, qnode_id=n01)",
#"filter_kg(action=remove_orphaned_nodes, node_type=protein)",
"return(message=true, store=false)",
] } }
elif params.example_number == 222: # Simple BTE query
query = {"previous_message_processing_plan": {"processing_actions": [
"create_message",
"add_qnode(id=n00, curie=NCBIGene:1017)", # CDK2
"add_qnode(id=n01, type=chemical_substance, is_set=True)",
"add_qedge(id=e00, source_id=n01, target_id=n00)",
"expand(edge_id=e00, kp=BTE)",
"return(message=true, store=false)",
]}}
elif params.example_number == 233: # KG2 version of demo example 1 (acetaminophen)
query = {"previous_message_processing_plan": {"processing_actions": [
"create_message",
"add_qnode(id=n00, curie=CHEMBL.COMPOUND:CHEMBL112)", # acetaminophen
"add_qnode(id=n01, type=protein, is_set=true)",
"add_qedge(id=e00, source_id=n00, target_id=n01)",
"expand(edge_id=e00, kp=ARAX/KG2)",
"filter_kg(action=remove_edges_by_property, edge_property=provided_by, property_value=https://pharos.nih.gov)",
"return(message=true, store=false)",
]}}
elif params.example_number == 300: # KG2 version of demo example 1 (acetaminophen)
query = {"previous_message_processing_plan": {"processing_actions": [
"create_message",
"add_qnode(name=DOID:14330, id=n00)",
"add_qnode(type=protein, is_set=true, id=n01)",
"add_qnode(type=chemical_substance, id=n02)",
"add_qedge(source_id=n00, target_id=n01, id=e00)",
"add_qedge(source_id=n01, target_id=n02, id=e01, type=physically_interacts_with)",
"expand(edge_id=[e00,e01], kp=ARAX/KG1)",
"overlay(action=compute_jaccard, start_node_id=n00, intermediate_node_id=n01, end_node_id=n02, virtual_edge_type=J1)",
"filter_kg(action=remove_edges_by_attribute_default, edge_attribute=jaccard_index, type=std, remove_connected_nodes=t, qnode_id=n02)",
#"filter_kg(action=remove_edges_by_property, edge_property=provided_by, property_value=Pharos)", # can be removed, but shows we can filter by Knowledge provider
"resultify(ignore_edge_direction=true)",
"filter_results(action=sort_by_edge_attribute, edge_attribute=jaccard_index, direction=descending, max_results=15)",
"return(message=true, store=false)",
]}}
elif params.example_number == 690: # test issue 690
query = {"previous_message_processing_plan": {"processing_actions": [
"create_message",
"add_qnode(name=DOID:14330, id=n00)",
"add_qnode(type=not_a_real_type, is_set=true, id=n01)",
"add_qnode(type=chemical_substance, id=n02)",
"add_qedge(source_id=n00, target_id=n01, id=e00)",
"add_qedge(source_id=n01, target_id=n02, id=e01, type=molecularly_interacts_with)",
"expand(edge_id=[e00,e01], continue_if_no_results=true)",
"overlay(action=compute_jaccard, start_node_id=n00, intermediate_node_id=n01, end_node_id=n02, virtual_relation_label=J1)",
"return(message=true, store=false)"
]}}
elif params.example_number == 6231: # chunyu testing #623, all nodes already in the KG and QG
query = {"previous_message_processing_plan": {"processing_actions": [
"create_message",
"add_qnode(id=n00, curie=CHEMBL.COMPOUND:CHEMBL521, type=chemical_substance)",
"add_qnode(id=n01, is_set=true, type=protein)",
"add_qedge(id=e00, source_id=n00, target_id=n01)",
"add_qnode(id=n02, type=biological_process)",
"add_qedge(id=e01, source_id=n01, target_id=n02)",
"expand(edge_id=[e00, e01], kp=ARAX/KG1)",
"overlay(action=fisher_exact_test, source_qnode_id=n01, virtual_relation_label=FET, target_qnode_id=n02, cutoff=0.05)",
"resultify()",
"return(message=true, store=false)"
]}}
elif params.example_number == 6232: # chunyu testing #623, this should return the 10 smallest FET p-values and only add the virtual edge with top 10 FET p-values
query = {"previous_message_processing_plan": {"processing_actions": [
"create_message",
"add_qnode(id=n00, curie=CHEMBL.COMPOUND:CHEMBL521, type=chemical_substance)",
"add_qnode(id=n01, is_set=true, type=protein)",
"add_qedge(id=e00, source_id=n00, target_id=n01)",
"add_qnode(id=n02, type=biological_process)",
"add_qedge(id=e01, source_id=n01, target_id=n02)",
"expand(edge_id=[e00, e01], kp=ARAX/KG1)",
"overlay(action=fisher_exact_test, source_qnode_id=n01, virtual_relation_label=FET, target_qnode_id=n02, top_n=10)",
"resultify()",
"return(message=true, store=false)"
]}}
elif params.example_number == 6233: # chunyu testing #623, this DSL tests the FET module based on (source id - involved_in - target id) and only decorate/add virtual edge with pvalue<0.05
query = {"previous_message_processing_plan": {"processing_actions": [
"create_message",
"add_qnode(id=n00, curie=CHEMBL.COMPOUND:CHEMBL521, type=chemical_substance)",
"add_qnode(id=n01, is_set=true, type=protein)",
"add_qedge(id=e00, source_id=n00, target_id=n01)",
"add_qnode(id=n02, type=biological_process)",
"add_qedge(id=e01, source_id=n01, target_id=n02, type=involved_in)",
"expand(edge_id=[e00, e01], kp=ARAX/KG1)",
"overlay(action=fisher_exact_test, source_qnode_id=n01, virtual_relation_label=FET, target_qnode_id=n02, rel_edge_id=e01, cutoff=0.05)",
"resultify()",
"return(message=true, store=false)"
]}}
elif params.example_number == 6234: # chunyu testing #623, nodes not in the KG and QG. This should throw an error initially. In the future we might want to add these nodes.
query = {"previous_message_processing_plan": {"processing_actions": [
"create_message",
"add_qnode(id=n00, curie=CHEMBL.COMPOUND:CHEMBL521, type=chemical_substance)",
"add_qnode(id=n01, type=protein)",
"add_qedge(id=e00, source_id=n00, target_id=n01)",
"expand(edge_id=[e00], kp=ARAX/KG1)",
"overlay(action=fisher_exact_test, source_qnode_id=n01, virtual_relation_label=FET, target_qnode_id=n02, cutoff=0.05)",
"resultify()",
"return(message=true, store=false)"
]}}
elif params.example_number == 6235: # chunyu testing #623, this is a two-hop sample. First, find all edges between DOID:14330 and proteins and then filter out the proteins with connection having pvalue>0.001 to DOID:14330. Second, find all edges between proteins and chemical_substances and then filter out the chemical_substances with connection having pvalue>0.005 to proteins
query = {"previous_message_processing_plan": {"processing_actions": [
"create_message",
"add_qnode(curie=DOID:14330, id=n00, type=disease)",
"add_qnode(type=protein, is_set=true, id=n01)",
"add_qedge(source_id=n00, target_id=n01, id=e00)",
"expand(edge_id=e00, kp=ARAX/KG1)",
"overlay(action=fisher_exact_test, source_qnode_id=n00, target_qnode_id=n01, virtual_relation_label=FET1)",
"filter_kg(action=remove_edges_by_attribute, edge_attribute=fisher_exact_test_p-value, direction=above, threshold=0.001, remove_connected_nodes=t, qnode_id=n01)",
"add_qnode(type=chemical_substance, id=n02)",
"add_qedge(source_id=n01, target_id=n02, id=e01, type=physically_interacts_with)",
"expand(edge_id=e01, kp=ARAX/KG1)",
"overlay(action=fisher_exact_test, source_qnode_id=n01, target_qnode_id=n02, virtual_relation_label=FET2)",
"resultify()",
"return(message=true, store=false)"
]}}
elif params.example_number == 6236: # chunyu testing #623, this is a three-hop sample: DOID:14330 - protein - (physically_interacts_with) - chemical_substance - phenotypic_feature
query = {"previous_message_processing_plan": {"processing_actions": [
"create_message",
"add_qnode(curie=DOID:14330, id=n00, type=disease)",
"add_qnode(type=protein, is_set=true, id=n01)",
"add_qedge(source_id=n00, target_id=n01, id=e00)",
"expand(edge_id=e00, kp=ARAX/KG1)",
"overlay(action=fisher_exact_test, source_qnode_id=n00, target_qnode_id=n01, virtual_relation_label=FET1)",
"filter_kg(action=remove_edges_by_attribute, edge_attribute=fisher_exact_test_p-value, direction=above, threshold=0.001, remove_connected_nodes=t, qnode_id=n01)",
"add_qnode(type=chemical_substance, is_set=true, id=n02)",
"add_qedge(source_id=n01, target_id=n02, id=e01, type=physically_interacts_with)",
"expand(edge_id=e01, kp=ARAX/KG1)",
"overlay(action=fisher_exact_test, source_qnode_id=n01, target_qnode_id=n02, virtual_relation_label=FET2)",
"filter_kg(action=remove_edges_by_attribute, edge_attribute=fisher_exact_test_p-value, direction=above, threshold=0.001, remove_connected_nodes=t, qnode_id=n02)",
"add_qnode(type=phenotypic_feature, id=n03)",
"add_qedge(source_id=n02, target_id=n03, id=e02)",
"expand(edge_id=e02, kp=ARAX/KG1)",
"overlay(action=fisher_exact_test, source_qnode_id=n02, target_qnode_id=n03, virtual_relation_label=FET3)",
"resultify()",
"return(message=true, store=false)"
]}}
elif params.example_number == 6237: # chunyu testing #623, this is a four-hop sample: CHEMBL521 - protein - biological_process - protein - disease
query = {"previous_message_processing_plan": {"processing_actions": [
"create_message",
"add_qnode(id=n00, curie=CHEMBL.COMPOUND:CHEMBL521, type=chemical_substance)",
"add_qnode(id=n01, is_set=true, type=protein)",
"add_qedge(id=e00, source_id=n00, target_id=n01)",
"expand(edge_id=e00, kp=ARAX/KG1)",
"overlay(action=fisher_exact_test, source_qnode_id=n00, target_qnode_id=n01, virtual_relation_label=FET1)",
"filter_kg(action=remove_edges_by_attribute, edge_attribute=fisher_exact_test_p-value, direction=above, threshold=0.01, remove_connected_nodes=t, qnode_id=n01)",
"add_qnode(type=biological_process, is_set=true, id=n02)",
"add_qedge(source_id=n01, target_id=n02, id=e01)",
"expand(edge_id=e01, kp=ARAX/KG1)",
"overlay(action=fisher_exact_test, source_qnode_id=n01, target_qnode_id=n02, virtual_relation_label=FET2)",
"filter_kg(action=remove_edges_by_attribute, edge_attribute=fisher_exact_test_p-value, direction=above, threshold=0.01, remove_connected_nodes=t, qnode_id=n02)",
"add_qnode(type=protein, is_set=true, id=n03)",
"add_qedge(source_id=n02, target_id=n03, id=e02)",
"expand(edge_id=e02, kp=ARAX/KG1)",
"overlay(action=fisher_exact_test, source_qnode_id=n02, target_qnode_id=n03, virtual_relation_label=FET3)",
"filter_kg(action=remove_edges_by_attribute, edge_attribute=fisher_exact_test_p-value, direction=above, threshold=0.01, remove_connected_nodes=t, qnode_id=n03)",
"add_qnode(type=disease, id=n04)",
"add_qedge(source_id=n03, target_id=n04, id=e03)",
"expand(edge_id=e03, kp=ARAX/KG1)",
"overlay(action=fisher_exact_test, source_qnode_id=n03, target_qnode_id=n04, virtual_relation_label=FET4)",
"resultify()",
"return(message=true, store=false)"
]}}
elif params.example_number == 7680: # issue 768 test all but jaccard, uncomment any one you want to test
query = {"previous_message_processing_plan": {"processing_actions": [
"create_message",
"add_qnode(curie=DOID:1588, id=n0)",
"add_qnode(type=chemical_substance, id=n1)",
"add_qedge(source_id=n0, target_id=n1, id=e0)",
"expand(edge_id=e0)",
#"overlay(action=predict_drug_treats_disease)",
#"overlay(action=predict_drug_treats_disease, source_qnode_id=n1, target_qnode_id=n0, virtual_relation_label=P1)",
#"overlay(action=overlay_clinical_info,paired_concept_frequency=true)",
#"overlay(action=overlay_clinical_info,observed_expected_ratio=true)",
#"overlay(action=overlay_clinical_info,chi_square=true)",
#"overlay(action=overlay_clinical_info,paired_concept_frequency=true, source_qnode_id=n0, target_qnode_id=n1, virtual_relation_label=CP1)",
#"overlay(action=overlay_clinical_info,observed_expected_ratio=true, source_qnode_id=n0, target_qnode_id=n1, virtual_relation_label=OE1)",
#"overlay(action=overlay_clinical_info,chi_square=true, source_qnode_id=n0, target_qnode_id=n1, virtual_relation_label=C1)",
"overlay(action=fisher_exact_test, source_qnode_id=n0, target_qnode_id=n1, virtual_relation_label=FET)",
"resultify()",
"filter_results(action=limit_number_of_results, max_results=15)",
"return(message=true, store=true)",
]}}
elif params.example_number == 7681: # issue 768 with jaccard
query = {"previous_message_processing_plan": {"processing_actions": [
"create_message",
"add_qnode(curie=DOID:14330, id=n00)", # parkinsons
"add_qnode(type=protein, is_set=True, id=n01)",
"add_qnode(type=chemical_substance, is_set=False, id=n02)",
"add_qedge(source_id=n01, target_id=n00, id=e00)",
"add_qedge(source_id=n01, target_id=n02, id=e01)",
"expand(edge_id=[e00,e01])",
"overlay(action=compute_jaccard, start_node_id=n00, intermediate_node_id=n01, end_node_id=n02, virtual_relation_label=J1)",
"resultify()",
"filter_results(action=limit_number_of_results, max_results=15)",
"return(message=true, store=true)",
]}}
elif params.example_number == 7200: # issue 720, example 2
query = {"previous_message_processing_plan": {"processing_actions": [
"create_message",
"add_qnode(curie=DOID:14330, id=n00)",
"add_qnode(type=protein, is_set=true, id=n01)",
"add_qnode(type=chemical_substance, id=n02)",
"add_qedge(source_id=n00, target_id=n01, id=e00)",
"add_qedge(source_id=n01, target_id=n02, id=e01, type=physically_interacts_with)",
"expand(edge_id=[e00,e01], kp=ARAX/KG1)",
"overlay(action=compute_jaccard, start_node_id=n00, intermediate_node_id=n01, end_node_id=n02, virtual_relation_label=J1)",
#"filter_kg(action=remove_edges_by_attribute, edge_attribute=jaccard_index, direction=below, threshold=.2, remove_connected_nodes=t, qnode_id=n02)",
#"filter_kg(action=remove_edges_by_property, edge_property=provided_by, property_value=Pharos)",
#"overlay(action=predict_drug_treats_disease, source_qnode_id=n02, target_qnode_id=n00, virtual_relation_label=P1)",
"resultify(ignore_edge_direction=true, debug=true)",
"return(message=true, store=true)",
]}}
elif params.example_number == 885:
query = {"previous_message_processing_plan": {"processing_actions": [
"create_message",
"add_qnode(name=DOID:11830, id=n00)",
"add_qnode(type=protein, is_set=true, id=n01)",
"add_qnode(type=chemical_substance, id=n02)",
"add_qedge(source_id=n00, target_id=n01, id=e00)",
"add_qedge(source_id=n01, target_id=n02, id=e01, type=molecularly_interacts_with)",
"expand(edge_id=[e00,e01], kp=ARAX/KG2)",
# overlay a bunch of clinical info
"overlay(action=overlay_clinical_info, paired_concept_frequency=true, source_qnode_id=n00, target_qnode_id=n02, virtual_relation_label=C1)",
"overlay(action=overlay_clinical_info, observed_expected_ratio=true, source_qnode_id=n00, target_qnode_id=n02, virtual_relation_label=C2)",
"overlay(action=overlay_clinical_info, chi_square=true, source_qnode_id=n00, target_qnode_id=n02, virtual_relation_label=C3)",
# return results
"resultify(ignore_edge_direction=true)",
"return(message=true, store=true)",
]}}
elif params.example_number == 887:
query = {"previous_message_processing_plan": {"processing_actions": [
"add_qnode(name=DOID:9406, id=n00)",
"add_qnode(type=chemical_substance, is_set=true, id=n01)",
"add_qnode(type=protein, id=n02)",
"add_qedge(source_id=n00, target_id=n01, id=e00)",
"add_qedge(source_id=n01, target_id=n02, id=e01)",
"expand(edge_id=[e00,e01])",
"overlay(action=overlay_clinical_info, observed_expected_ratio=true, virtual_relation_label=C1, source_qnode_id=n00, target_qnode_id=n01)",
"filter_kg(action=remove_edges_by_attribute, edge_attribute=observed_expected_ratio, direction=below, threshold=3, remove_connected_nodes=t, qnode_id=n01)",
"filter_kg(action=remove_orphaned_nodes, node_type=protein)",
"overlay(action=compute_ngd, virtual_relation_label=N1, source_qnode_id=n01, target_qnode_id=n02)",
"filter_kg(action=remove_edges_by_attribute, edge_attribute=normalized_google_distance, direction=above, threshold=0.85, remove_connected_nodes=t, qnode_id=n02)",
"resultify(ignore_edge_direction=true)",
"return(message=true, store=true)"
]}}
elif params.example_number == 892: # drug disease prediction with BTE
query = {"previous_message_processing_plan": {"processing_actions": [
"add_qnode(curie=DOID:11830, type=disease, id=n00)",
"add_qnode(type=gene, curie=[UniProtKB:P39060, UniProtKB:O43829, UniProtKB:P20849], is_set=true, id=n01)",
"add_qnode(type=chemical_substance, id=n02)",
"add_qedge(source_id=n00, target_id=n01, id=e00)",
"add_qedge(source_id=n01, target_id=n02, id=e01)",
"expand(kp=BTE)",
"overlay(action=predict_drug_treats_disease, source_qnode_id=n02, target_qnode_id=n00, virtual_relation_label=P1)",
"resultify(ignore_edge_direction=true)",
"return(message=true, store=true)"
]}}
elif params.example_number == 8922: # drug disease prediction with BTE and KG2
query = {"previous_message_processing_plan": {"processing_actions": [
"add_qnode(curie=DOID:11830, id=n0, type=disease)",
"add_qnode(type=chemical_substance, id=n1)",
"add_qedge(source_id=n0, target_id=n1, id=e1)",
"expand(edge_id=e1, kp=ARAX/KG2)",
"expand(edge_id=e1, kp=BTE)",
#"overlay(action=overlay_clinical_info, paired_concept_frequency=true)",
#"overlay(action=overlay_clinical_info, observed_expected_ratio=true)",
#"overlay(action=overlay_clinical_info, chi_square=true)",
"overlay(action=predict_drug_treats_disease)",
#"overlay(action=compute_ngd)",
"resultify(ignore_edge_direction=true)",
#"filter_results(action=limit_number_of_results, max_results=50)",
"return(message=true, store=true)"
]}}
elif params.example_number == 8671: # test_one_hop_kitchen_sink_BTE_1
query = {"previous_message_processing_plan": {"processing_actions": [
"create_message",
"add_qnode(curie=DOID:11830, id=n0, type=disease)",
"add_qnode(type=chemical_substance, id=n1)",
"add_qedge(source_id=n0, target_id=n1, id=e1)",
# "expand(edge_id=e00, kp=ARAX/KG2)",
"expand(edge_id=e1, kp=BTE)",
"overlay(action=overlay_clinical_info, paired_concept_frequency=true)",
"overlay(action=overlay_clinical_info, observed_expected_ratio=true)",
"overlay(action=overlay_clinical_info, chi_square=true)",
"overlay(action=predict_drug_treats_disease)",
"overlay(action=compute_ngd)",
"resultify(ignore_edge_direction=true)",
"filter_results(action=limit_number_of_results, max_results=50)",
"return(message=true, store=true)",
]}}
| |
the message, use :py:meth:`pyryver.ryver.Ryver.upload_file()`
to upload the file you wish to attach. Alternatively, use
:py:meth:`pyryver.ryver.Ryver.create_link()` for a link attachment.
.. warning::
``from_user`` **must** be set when using attachments with private messages.
Otherwise, a ``ValueError`` will be raised. It should be set to the user that
is sending the message (the user currently logged in).
It is not required to be set if the message is being sent to a forum/team.
If any parameters are unspecified or :py:const:`NO_CHANGE`, they will be left
as-is. Passing ``None`` for parameters for which ``None`` is not a valid value
will also result in the value being unchanged.
:param message: The new message contents (optional).
:param creator: The new creator (optional).
:param attachment: An attachment for this message, e.g. a file or a link (optional). Can be either a ``Storage`` or a ``File`` object.
:param from_user: The user that is sending this message (the user currently logged in); **must** be set when using attachments in private messages (optional).
:raises ValueError: If a ``from_user`` is not provided for a private message attachment.
"""
url = self._ryver.get_api_url(
self.get_chat_type(), self.get_chat_id(), "Chat.UpdateMessage()", format="json")
data = {
"id": self.get_id(),
}
if message is not NO_CHANGE and message is not None:
data["body"] = message
if creator is not NO_CHANGE:
data["createSource"] = creator.to_dict() if creator is not None else None
if attachment is not NO_CHANGE:
# Clear attachment
if attachment is None:
data["embeds"] = {}
else:
chat = await self.get_chat()
data.update(await chat._process_attachment(message, attachment, from_user))
await self._ryver._session.post(url, json=data)
self._data.update(data)
class Chat(Object):
"""
Any Ryver chat you can send messages to.
E.g. Teams, forums, user DMs, etc.
"""
__slots__ = ()
_OBJ_TYPE = "__chat"
def get_jid(self) -> str:
"""
Get the JID (JabberID) of this chat.
The JID is used in the websockets interface.
:return: The JID of this chat.
"""
return self._data["jid"]
@abstractmethod
def get_name(self) -> str:
"""
Get the name of this chat.
:return: The name of this chat.
"""
def get_task_tags(self) -> typing.List[TaskTag]:
"""
Get a list of task tags defined in this chat, as ``TaskTag`` objects.
:return: The defined task tags of this chat.
"""
return [TaskTag.from_data(data) for data in self._data["tagDefs"]]
async def set_task_tags(self, tags: typing.Iterable[TaskTag]):
"""
Set the task tags defined in this chat.
.. note::
This will erase any existing tags.
This method also updates the task tags property of this object.
:param tags: The new tags as a list of ``TaskTag``s.
"""
data = {
"tagDefs": [tag.to_dict() for tag in tags]
}
url = self.get_api_url()
await self._ryver._session.patch(url, json=data)
self._data["tagDefs"] = data["tagDefs"]
async def _process_attachment(self, message: str, attachment: typing.Union["Storage", "File"],
from_user: "User" = None) -> typing.Dict[str, typing.Any]:
"""
Process a ``Storage`` object for attaching to a chat message.
.. warning::
This method is intended for internal use only.
:param message: The chat message.
:param attachment: The attachment to process. Can be either a ``Storage`` or a ``File`` object.
:param from_user: The user that is sending this message (the user currently logged in); **must** be set when using attachments in private messages (optional).
:raises ValueError: If a ``from_user`` is not provided for a private message attachment.
:return: The data that can be used to send this message attachment.
"""
if from_user is None and isinstance(self, User):
raise ValueError("Message attachments in private messages require from_user to be set!")
# The Ryver API is weird
out_assoc = {
"results": [
{
"inId": self.get_id(),
"inSecured": True,
"inType": self.get_entity_type(),
"inName": self.get_name(),
}
]
}
if isinstance(self, User):
out_assoc["results"].insert(0, {
"inId": from_user.get_id(),
"inSecured": True,
"inType": from_user.get_entity_type(),
"inName": from_user.get_name(),
})
# Extract some values to be used later
if isinstance(attachment, File):
content_id = attachment.get_id()
content_url = attachment.get_url()
content_mime = attachment.get_MIME_type()
else:
content_id = attachment.get_content_id()
content_url = attachment.get_content_url()
content_mime = attachment.get_content_MIME_type()
# PATCH to update the outAssociations of the file
patch_url = self._ryver.get_api_url(TYPE_FILE, content_id, format="json")
await self._ryver._session.patch(patch_url, json={
"outAssociations": out_assoc
})
# Now GET to get the embeds
embeds_url = self._ryver.get_api_url(TYPE_FILE, content_id, select="embeds")
async with self._ryver._session.get(embeds_url) as resp:
embeds = await resp.json()
data = {
"extras": {
"file": {
"fileName": attachment.get_name(),
"fileSize": attachment.get_size(),
"id": content_id,
"outAssociations": out_assoc,
"url": content_url,
"fileType": content_mime,
"chatBody": message
}
},
"embeds": embeds["d"]["results"]["embeds"],
"body": message + f"\n\n[{attachment.get_name()}]({content_url})"
}
return data
async def send_message(self, message: str, creator: typing.Optional[Creator] = None,
attachment: typing.Optional[typing.Union["Storage", "File"]] = None,
from_user: typing.Optional["User"] = None) -> str:
"""
Send a message to this chat.
Specify a creator to override the username and profile of the message creator.
.. tip::
To attach a file to the message, use :py:meth:`pyryver.ryver.Ryver.upload_file()`
to upload the file you wish to attach. Alternatively, use
:py:meth:`pyryver.ryver.Ryver.create_link()` for a link attachment.
.. warning::
``from_user`` **must** be set when using attachments with private messages.
Otherwise, a ``ValueError`` will be raised. It should be set to the user that
is sending the message (the user currently logged in).
It is not required to be set if the message is being sent to a forum/team.
Returns the ID of the chat message sent (**not** the message object itself).
Note that message IDs are strings.
:param message: The message contents.
:param creator: The overridden creator; optional, if unset uses the logged-in user's profile.
:param attachment: An attachment for this message, e.g. a file or a link (optional). Can be either a ``Storage`` or a ``File`` object.
:param from_user: The user that is sending this message (the user currently logged in); **must** be set when using attachments in private messages (optional).
:raises ValueError: If a ``from_user`` is not provided for a private message attachment.
:return: The ID of the chat message that was sent.
"""
url = self.get_api_url("Chat.PostMessage()", format="json")
data = {
"body": message
}
if creator is not None:
data["createSource"] = creator.to_dict()
if attachment:
data.update(await self._process_attachment(message, attachment, from_user))
async with self._ryver._session.post(url, json=data) as resp:
return (await resp.json())["d"]["id"]
async def get_topics(self, archived: bool = False, top: int = -1, skip: int = 0) -> typing.AsyncIterator[Topic]:
"""
Get all the topics in this chat.
:param archived: If True, only include archived topics in the results, otherwise, only include non-archived topics.
:param top: Maximum number of results; optional, if unspecified return all results.
:param skip: Skip this many results.
:return: An async iterator for the topics of this chat.
"""
url = self.get_api_url(
f"Post.Stream(archived={'true' if archived else 'false'})", format="json")
async for topic in self._ryver.get_all(url=url, top=top, skip=skip):
yield Topic(self._ryver, topic) #NOSONAR
async def get_messages(self, count: int, skip: int = 0) -> typing.List[ChatMessage]:
"""
Get a number of messages (most recent **first**) in this chat.
:param count: Maximum number of results.
:param skip: The number of results to skip (optional).
:return: A list of messages.
"""
# Interestingly, this does not have the same 50-result restriction as the other API methods...
url = self.get_api_url(
"Chat.History()", format="json", top=count, skip=skip)
async with self._ryver._session.get(url) as resp:
messages = (await resp.json())["d"]["results"]
return [ChatMessage(self._ryver, data) for data in messages]
async def get_message(self, msg_id: str) -> ChatMessage:
"""
Get a single message from this chat by its ID.
.. note::
There is a chance that this method might result in a 404 Not Found for
messages that were sent recently (such as when using the realtime
websocket API (:py:class:`pyryver.ryver_ws.RyverWS`) to respond to
messages), as those messages have not been fully added to Ryver's
database yet.
You can use :py:func:`pyryver.util.retry_until_available()` to wrap
around this coroutine to get around this.
:param msg_id: The ID of the chat message to get.
:return: The message object.
"""
url = self.get_api_url(
f"Chat.History.Message(id='{msg_id}')", format="json")
async with self._ryver._session.get(url) as resp:
messages = (await resp.json())["d"]["results"]
return ChatMessage(self._ryver, messages[0])
async def get_messages_surrounding(self, msg_id: str, before: int = 0, after: int = 0) -> typing.List[ChatMessage]:
"""
Get a range of messages (most recent **last**) before and after a chat message (given by ID).
.. warning::
Before and after cannot exceed 25 messages, otherwise a :py:exc:`aiohttp.ClientResponseError`
will be raised with the code 400 Bad Request.
.. note::
There is a | |
<filename>policy_driven_attack/train_grad_model.py<gh_stars>1-10
#!/usr/bin/env python3
import sys
import os
import os.path as osp
import socket
import functools
import getpass
import argparse
import json
import random
import copy
from collections import OrderedDict
from glob import glob
import glog as log
import numpy as np
import pickle
import torch
import torch.nn.functional as F
import torch.distributed as dist
import torch.multiprocessing as mp
import torch.utils.data.distributed
from models import make_victim_model, make_policy_model
from loaders import make_loader
# record best model
best_train_unseen_tuple_sim = 0
def parse_args():
"""
Parse input arguments
"""
parser = argparse.ArgumentParser(description='')
parser.add_argument('--exp-dir', default='output/debug', type=str,
help='directory to save results and logs')
parser.add_argument('--grad-dir', default='', type=str,
help='directory where gradients are stored')
parser.add_argument('--num-train', default=1000, type=int,
help='number of image ids in training')
parser.add_argument('--max-query', default=20000, type=int,
help='maximum number of queries allowed')
parser.add_argument('--save-every-epoch', action='store_true',
help='save model every epoch')
parser.add_argument('--dataset', default='mnist', type=str, choices=['mnist01', 'mnist', 'cifar10', 'imagenet'],
help='which dataset to use')
parser.add_argument('--phase', default='test', type=str, choices=['train', 'val', 'valv2', 'test'],
help='train, val, test')
parser.add_argument('--num-test', default=100, type=int,
help='number of test images')
parser.add_argument('--victim-arch', default='carlinet', type=str,
help='victim network architecture')
parser.add_argument('--policy-arch', default='empty', type=str,
help='policy network architecture')
parser.add_argument('--policy-weight-fname', default='', type=str,
help='pre-trained policy weight filename')
parser.add_argument('--policy-init-std', default=3e-3, type=float,
help='initial value of std for policy network')
parser.add_argument('--policy-bilinear', action='store_true',
help='use bilinear in policy network if applicable')
parser.add_argument('--policy-normalization-type', default='none', type=str, choices=['none', 'bn', 'gn'],
help='normalization type in policy network if applicable')
parser.add_argument('--policy-use-tanh', action='store_true',
help='use tanh in policy network if applicable')
parser.add_argument('--policy-base-width', default=16, type=int,
help='set base width parameter in policy network if applicable')
parser.add_argument('--policy-calibrate', action='store_true',
help='calibrate output of policy network using mean in policy network if applicable')
parser.add_argument('--grad-size', default=0, type=int,
help='force to use a specific shape for grad')
parser.add_argument('--use-true-grad', action='store_true',
help='use true gradient instead of estimated gradient for training')
parser.add_argument('--image-gaussian-std', default=0.0, type=float,
help='add gaussian noise for data augmentation')
parser.add_argument('--grad-gaussian-std', default=0.0, type=float,
help='add gaussian noise for data augmentation')
parser.add_argument('--no-init-eval', action='store_true',
help='do not evaluate performance after model initialization')
parser.add_argument('--ce-lmbd', nargs=4, default=[1.0, 0.01, 0.01, 0.01],
help='cross entropy coefficient in loss, only applied if policy net could output logit')
parser.add_argument('--optimizer', default='SGD', choices=['Adam', 'SGD'],
help='type of optimizer')
parser.add_argument('--epochs', default=30, type=int,
help='number of epochs')
parser.add_argument('--warmup-epochs', default=0, type=int,
help='number of warmup epochs')
parser.add_argument('--lr', default=1e-2, type=float,
help='learning rate')
parser.add_argument('--step-mult', nargs='+', default=[0.1, 0.01],
help='multiplier for step lr policy')
parser.add_argument('--step-at', nargs='+', default=[250, 350],
help='step at specified epochs')
parser.add_argument('--decay', default=1e-4, type=float,
help='weight decay')
parser.add_argument('--momentum', default=0.9, type=float,
help='momentum')
parser.add_argument('--clip-grad', default=5., type=float,
help='max gradient norm')
parser.add_argument('--batch-size', default=50, type=int,
help='batch size during training and testing')
parser.add_argument('--print-freq', default=1, type=int,
help='print each args.print_freq batches')
parser.add_argument('--num-worker', default=4, type=int,
help='number of workers used for gradient data loader')
parser.add_argument('--pre-load', action='store_true',
help='pre-load all grad training data into cpu memory before training')
parser.add_argument('--check-unseen-tuple', action='store_true',
help='if set to True, we will also load and check train_unseen tuple sim')
parser.add_argument('--seed', default=1234, type=int,
help='random seed')
parser.add_argument('--ssh', action='store_true',
help='whether or not we are executing command via ssh. '
'If set to True, we will not print anything to screen and only redirect them to log file')
# data parallel parameters
parser.add_argument('--use-ddp', action='store_true',
help='Use pytorch ddp')
parser.add_argument('--ddp-world-size', default=1, type=int,
help='number of nodes for distributed training')
parser.add_argument('--ddp-rank', default=0, type=int,
help='node rank for distributed training')
parser.add_argument('--ddp-url', default='tcp://127.0.0.1:12345', type=str,
help='url used to set up distributed training')
parser.add_argument('--ddp-backend', default='nccl', type=str,
help='distributed backend')
if len(sys.argv) == 1:
parser.print_help()
sys.exit(1)
args = parser.parse_args()
args.step_at = list(map(int, args.step_at))
args.step_mult = list(map(float, args.step_mult))
args.ce_lmbd = list(map(float, args.ce_lmbd))
return args
def norm(v, p=2):
v = v.view(v.shape[0], -1)
if p == 2:
return torch.clamp(v.norm(dim=1).view(-1, 1, 1, 1), min=1e-8)
elif p == 1:
return torch.clamp(v.abs().sum(dim=1).view(-1, 1, 1, 1), min=1e-8)
else:
raise ValueError('Unknown norm p={}'.format(p))
def test_tuple(train_phases, grad_loader, model, policy, gpu, args):
# check sim of predicted gradients on saved grad tuples
log.info('Testing sim on tuples @ gpu {}, phase: {}'.format(gpu, train_phases))
policy.eval()
result = dict()
with torch.no_grad():
for phase in train_phases:
num_tuple = len(grad_loader[phase].dataset)
log.info('Testing sim on {} tuples @ gpu {}, {} in total'.format(phase, gpu, num_tuple))
# if args.dataset == 'imagenet' and phase == 'train_seen':
# log.info('Ignore train_seen for imagenet')
# result['train_seen_tuple_sim'.format(phase)] = 0
# continue
sim_all = torch.zeros(num_tuple)
for batch_index, (adv_image, image, label, grad) in enumerate(grad_loader[phase]):
# move inputs to device
adv_image = adv_image.cuda(gpu)
image = image.cuda(gpu)
label = label.cuda(gpu)
grad = grad.cuda(gpu)
# get target label
logit = model(adv_image)
argsort = logit.argsort(dim=1, descending=True)
target = argsort[:, 0] * (1 - argsort[:, 0].eq(label)).long() +\
argsort[:, 1] * (argsort[:, 0].eq(label)).long()
assert not label.eq(target).any().item()
# make select indicator
selected = torch.arange(batch_index * grad_loader[phase].batch_size,
batch_index * grad_loader[phase].batch_size + adv_image.shape[0])
# get estimated gradients
pred = policy(adv_image, image, label, target, output_fields=('grad',))['grad']
if pred.shape != grad.shape:
pred = F.interpolate(pred, size=grad.shape[-1], mode='bilinear', align_corners=True)
assert grad.shape == pred.shape
sim = (grad * pred).sum(dim=(1, 2, 3)) / norm(grad).view(-1) / norm(pred).view(-1)
sim_all[selected] = sim.detach().cpu()
n = batch_index * args.batch_size + adv_image.shape[0]
if batch_index % args.print_freq == 0 or batch_index == len(grad_loader[phase]) - 1:
log.info('Performance of batch {} @ gpu {} (tuple {} - {}):'.format(
batch_index, gpu, n - adv_image.shape[0], n))
log.info(' {}: {} / {} @ gpu {}, tuple sim: {:.4f}'.format(
phase, n, num_tuple, gpu, sim_all[:n].mean()))
# clear gpu memory cache
if args.dataset == 'imagenet':
torch.cuda.empty_cache()
if args.dataset == 'imagenet' and n >= 10000:
log.info('Early break for imagenet')
break
# save result for current phase
result['{}_tuple_sim'.format(phase)] = sim_all.mean().item()
log.info('Performance of current model (tuple sim) @ gpu {}:'.format(gpu))
max_len = max(list(map(lambda t: len(t), train_phases)))
for phase in train_phases:
log.info(' ' * (max_len + 1 - len(phase)) + ' {} tuple sim @ gpu {}: {:.4f}'.format(
phase.replace('_', ' '), gpu, result['{}_tuple_sim'.format(phase)]))
return result
def test(train_image_ids, stage1_image_ids, loader, model, policy, gpu, num_gpu_per_node, args):
# check sim of predicted gradients on clean images
log.info('Testing sim on clean images')
policy.eval()
sim_train_seen, train_seen_index = torch.zeros(len(train_image_ids['train_seen'])), 0
sim_train_unseen, train_unseen_index = torch.zeros(len(train_image_ids['train_unseen'])), 0
sim_test, test_index = torch.zeros(args.num_test), 0
assert sim_train_seen.shape[0] + sim_train_unseen.shape[0] == len(stage1_image_ids)
# record test image ids to make sure we use the same test set across each epoch
# note we do not guarantee the test set keeps the same across different experiments, since the number of stage1
# images might be different across different experiments
test_image_ids = list()
# start test
with torch.no_grad():
for batch_index, (image_id, image, label) in enumerate(loader):
# move inputs to device
image = image.cuda(gpu)
label = label.cuda(gpu)
# temporarily allows gradient calculation to get logit and true grad
with torch.enable_grad():
image.requires_grad = True
logit = model(image)
acc = logit.argmax(dim=1).eq(label)
# get true gradients using logit diff (cw) loss
# we only use correctly classified images, others will not be counted
target = logit.argsort(dim=1, descending=True)[:, 1]
loss = logit[torch.arange(image.shape[0]), target] - logit[torch.arange(image.shape[0]), label]
true_grad = torch.autograd.grad(loss.mean() * image.shape[0], image)[0]
true_grad = true_grad.detach()
image.requires_grad = False
# get estimated gradients
pred = policy(image, image, label, target, output_fields=('grad',))['grad']
if pred.shape != true_grad.shape:
pred = F.interpolate(pred, size=true_grad.shape[-1], mode='bilinear', align_corners=True)
# calculate cosine similarity
assert true_grad.shape == pred.shape
sim = (true_grad * pred).sum(dim=(1, 2, 3)).abs() / norm(true_grad).view(-1) / norm(pred).view(-1)
# assign each similarity into train_seen, train_unseen, test
for image_index_in_batch in range(image_id.shape[0]):
t = int(image_id[image_index_in_batch].item())
if t in train_image_ids['train_seen']:
if train_seen_index < sim_train_seen.shape[0]:
sim_train_seen[train_seen_index] = sim[image_index_in_batch].cpu()
train_seen_index += 1
elif t in train_image_ids['train_unseen']:
if train_unseen_index < sim_train_unseen.shape[0]:
sim_train_unseen[train_unseen_index] = sim[image_index_in_batch].cpu()
train_unseen_index += 1
else:
if test_index < sim_test.shape[0] and acc[image_index_in_batch].item():
sim_test[test_index] = sim[image_index_in_batch].cpu()
test_index += 1
test_image_ids.append(t)
n = batch_index * args.batch_size + image.shape[0]
if batch_index % args.print_freq == 0 or test_index >= args.num_test:
log.info('Performance of batch {} @ gpu {} (image {} - {}):'.format(
batch_index, gpu, n - image.shape[0], n))
log.info(' train seen @ gpu {}: {} / {}, sim: {:.4f}'.format(
gpu, train_seen_index, sim_train_seen.shape[0], sim_train_seen[:train_seen_index].mean().item()))
log.info(' train unseen @ gpu {}: {} / {}, sim: {:.4f}'.format(
gpu, train_unseen_index, sim_train_unseen.shape[0],
sim_train_unseen[:train_unseen_index].mean().item()))
log.info(' test seen @ gpu {}: {} / {}, sim: {:.4f}'.format(
gpu, test_index, sim_test.shape[0], sim_test[:test_index].mean().item()))
# clear gpu memory cache
if args.dataset == 'imagenet':
del image, label, logit, acc, target, loss, true_grad, pred, sim
torch.cuda.empty_cache()
if args.dataset == 'imagenet' and n >= 10000:
log.info('Early break for imagenet')
break
# check test done
if test_index >= args.num_test:
assert train_seen_index >= sim_train_seen.shape[0]
assert train_unseen_index >= sim_train_unseen.shape[0]
log.info('We have tested {} images @ gpu {}, break'.format(args.num_test, gpu))
break
log.info('Performance of current model (clean sim) @ gpu {}:'.format(gpu))
log.info(' train seen sim @ gpu {}: {:.4f}'.format(gpu, sim_train_seen.mean().item()))
log.info(' train unseen sim @ gpu {}: {:.4f}'.format(gpu , sim_train_unseen.mean().item()))
log.info(' test sim | |
int
:rtype: Run
"""
return Testrail._get_object_by_id(Run,
run_id)
@staticmethod
def get_test_by_id(test_id):
"""
:type test_id: int
:rtype: Test
"""
return Testrail._get_object_by_id(Test,
test_id)
################################################################################
# API methods as-is (can be used, but not intended to)
################################################################################
class TestrailAPI(object):
@staticmethod
def get_case(case_id):
return Testrail.get('get_case/%s' % case_id)
@staticmethod
def get_cases(project_id, suite_id, section_id=None, created_after=None,
created_before=None, created_by=None, milestone_id=None,
priority_id=None, type_id=None, updated_after=None,
updated_before=None, updated_by=None):
pattern = 'get_cases/%s&suite_id=%s' % (project_id, suite_id)
if section_id is not None:
pattern += '§ion_id=%s' % section_id
if created_after is not None:
pattern += '&created_after=%s' % created_after
if created_before is not None:
pattern += '&created_before=%s' % created_before
if created_by is not None:
pattern += '&created_by=%s' % ','.join(created_by)
if milestone_id is not None:
pattern += '&milestone_id=%s' % ','.join(milestone_id)
if priority_id is not None:
pattern += '&priority_id=%s' % ','.join(priority_id)
if type_id is not None:
pattern += '&type_id=%s' % ','.join(type_id)
if updated_after is not None:
pattern += '&updated_after=%s' % updated_after
if updated_before is not None:
pattern += '&updated_before=%s' % updated_before
if updated_by is not None:
pattern += '&updated_by=%s' % ','.join(updated_by)
return Testrail.get(pattern)
@staticmethod
def add_case(section_id, **kwargs):
"""
The following POST fields are supported (system fields):
title string The title of the test case (required)
type_id int The ID of the case type
priority_id int The ID of the case priority
estimate timespan The estimate, e.g. "30s" or "1m 45s"
milestone_id int The ID of the milestone to link to the test case
refs string A comma-separated list of references/
requirements
"""
return Testrail.post('add_case/%s' % section_id,
data=kwargs)
@staticmethod
def update_case(case_id, **kwargs):
"""
Same fields as _add_case
"""
return Testrail.post('update_case/%s' % case_id,
data=kwargs)
@staticmethod
def delete_case(case_id):
return Testrail.post('delete_case/%s' % case_id)
@staticmethod
def get_case_fields():
return Testrail.get('get_case_fields')
@staticmethod
def get_case_types():
return Testrail.get('get_case_types')
@staticmethod
def get_configs(project_id):
return Testrail.get('get_configs/%s' % project_id)
@staticmethod
def get_milestone(milestone_id):
return Testrail.get('get_milestone/%s' % milestone_id)
@staticmethod
def get_milestones(project_id, is_completed=None):
pattern = 'get_milestones/%s' % project_id
if is_completed is not None:
pattern += '&is_completed=%s' % int(is_completed)
return Testrail.get(pattern)
@staticmethod
def add_milestone(project_id, **kwargs):
"""
The following POST fields are supported:
name string The name of the milestone (required)
description string The description of the milestone
due_on timestamp The due date of the milestone
(as UNIX timestamp)
"""
return Testrail.post('add_milestone/%s' % project_id,
data=kwargs)
@staticmethod
def update_milestone(milestone_id, **kwargs):
"""
Same fields as _add_milestone, and also:
is_completed bool Specifies whether a milestone is considered
completed or not
"""
return Testrail.post('update_milestone/%s' % milestone_id,
data=kwargs)
@staticmethod
def delete_milestone(milestone_id):
return Testrail.post('delete_milestone/%s' % milestone_id)
@staticmethod
def get_plan(plan_id):
return Testrail.get('get_plan/%s' % plan_id)
@staticmethod
def get_plans(project_id, created_after=None, created_before=None,
created_by=None, is_completed=None, limit=None,
offset=None, milestone_id=None):
pattern = 'get_plans/%s' % project_id
if created_after is not None:
pattern += '&created_after=%s' % created_after
if created_before is not None:
pattern += '&created_before=%s' % created_before
if created_by is not None:
pattern += '&created_by=%s' % ','.join(created_by)
if is_completed is not None:
pattern += '&is_completed=%s' % int(is_completed)
if limit is not None:
pattern += '&limit=%s' % limit
if offset is not None:
pattern += '&offset=%s' % offset
if milestone_id is not None:
pattern += '&milestone_id=%s' % ','.join(milestone_id)
return Testrail.get(pattern)
@staticmethod
def add_plan(project_id, **kwargs):
"""
The following POST fields are supported:
name string The name of the test plan (required)
description string The description of the test plan
milestone_id int The ID of the milestone to link to the test plan
entries array An array of objects describing the test runs of
the plan, see _add_plan_entry
"""
return Testrail.post('add_plan/%s' % project_id,
data=kwargs)
@staticmethod
def add_plan_entry(plan_id, **kwargs):
"""
The following POST fields are supported:
suite_id int The ID of the test suite for the test run(s)
(required)
name string The name of the test run (s)
assignedto_id int The ID of the user the test run(s) should be
assigned to
include_all bool True for including all test cases of the test
suite and false for a custom case selection
(default: true)
case_ids array An array of case IDs for the custom case
selection
config_ids array An array of configuration IDs used for the test
runs of the test plan entry
(requires TestRail 3.1 or later)
runs array An array of test runs with configurations
(requires TestRail 3.1 or later)
"""
return Testrail.post('add_plan_entry/%s' % plan_id,
data=kwargs)
@staticmethod
def update_plan(plan_id, **kwargs):
"""
Same fields as _add_plan
"""
return Testrail.post('update_plan/%s' % plan_id,
data=kwargs)
@staticmethod
def update_plan_entry(plan_id, entry_id, **kwargs):
"""
The following POST fields are supported:
name string The name of the test run(s)
assignedto_id int The ID of the user the test run(s) should be
assigned to
include_all bool True for including all test cases of the test
suite and false for a custom case selection
(default: true)
case_ids array An array of case IDs for the custom case
selection
"""
return Testrail.post('update_plan_entry/%s/%s' % (plan_id, entry_id),
data=kwargs)
@staticmethod
def close_plan(plan_id):
return Testrail.post('close_plan/%s' % plan_id)
@staticmethod
def delete_plan(plan_id):
return Testrail.post('delete_plan/%s' % plan_id)
@staticmethod
def delete_plan_entry(plan_id, entry_id):
return Testrail.post('delete_plan_entry/%s/%s' % (plan_id, entry_id))
@staticmethod
def get_priorities():
return Testrail.get('get_priorities')
@staticmethod
def get_project(project_id):
return Testrail.get('get_project/%s' % project_id)
@staticmethod
def get_projects(is_completed=None):
pattern = 'get_projects'
if is_completed is not None:
pattern += '&is_completed=%s' % int(is_completed)
return Testrail.get(pattern)
@staticmethod
def add_project(**kwargs):
"""
The following POST fields are supported:
name string The name of the project (required)
announcement string The description of the project
show_announcement bool True if the announcement should be displayed
on the project's overview page and
false otherwise
suite_mode integer The suite mode of the project (1 for single
suite mode, 2 for single suite + baselines,
3 for multiple suites)
(added with TestRail 4.0)
"""
return Testrail.post('add_project',
data=kwargs)
@staticmethod
def update_project(project_id, **kwargs):
"""
Same fields as _add_project, and also:
is_completed bool Specifies whether a project is considered
completed or not
"""
return Testrail.post('update_project/%s' % project_id,
data=kwargs)
@staticmethod
def delete_project(project_id):
return Testrail.post('delete_project/%s' % project_id)
@staticmethod
def get_results(test_id, limit=None, offset=None, status_id=None):
pattern = 'get_results/%s' % test_id
if limit is not None:
pattern += '&limit=%s' % limit
if offset is not None:
pattern += '&offset=%s' % offset
if status_id is not None:
pattern += '&status_id=%s' % ','.join(status_id)
return Testrail.get(pattern)
@staticmethod
def get_results_for_case(run_id, case_id, limit=None,
offset=None, status_id=None):
pattern = 'get_results_for_case/%s/%s' % (run_id, case_id)
if limit is not None:
pattern += '&limit=%s' % limit
if offset is not None:
pattern += '&offset=%s' % offset
if status_id is not None:
pattern += '&status_id=%s' % ','.join(status_id)
return Testrail.get(pattern)
@staticmethod
def get_results_for_run(run_id, created_after=None,
created_before=None, created_by=None, limit=None,
offset=None, status_id=None):
pattern = 'get_results_for_run/%s' % run_id
if created_after is not None:
pattern += '&created_after=%s' % created_after
if created_before is not None:
pattern += '&created_before=%s' % created_before
if created_by is not None:
pattern += '&created_by=%s' % ','.join(created_by)
if limit is not None:
pattern += '&limit=%s' % limit
if offset is not None:
pattern += '&offset=%s' % offset
if status_id is not None:
pattern += '&status_id=%s' % ','.join(status_id)
return Testrail.get(pattern)
@staticmethod
def add_result(test_id, **kwargs):
"""
The following POST fields are supported (system fields):
status_id int The ID of the test status. The built-in system
statuses have the following IDs:
1 Passed
2 Blocked
3 Untested
4 Retest
5 Failed
You can get a full list of system and custom
statuses via get_statuses.
comment string The comment / description for the test result
version string The version or build you tested against
elapsed timespan The time it took to execute the test,
e.g. "30s" or "1m 45s"
defects string A comma-separated list of defects to link to
the test result
assignedto_id int The ID of a user the test should be assigned to
"""
return Testrail.post('add_result/%s' % test_id,
data=kwargs)
@staticmethod
def add_result_for_case(run_id, case_id, **kwargs):
"""
Same fields as _add_result
"""
return Testrail.post('add_result_for_case/%s/%s' % (run_id, case_id),
data=kwargs)
@staticmethod
def add_results(run_id, **kwargs):
"""
This method expects an array of test results (via the 'results' field).
Each test result must specify the test ID and can pass in the same
fields as _add_result
"""
return Testrail.post('add_results/%s' % run_id,
data=kwargs)
@staticmethod
def add_results_for_cases(run_id, **kwargs):
"""
Same as _add_results but with Case_ID rather than Test_ID.
"""
return Testrail.post('add_results_for_cases/%s' % run_id,
data=kwargs)
@staticmethod
def get_result_fields():
return Testrail.get('get_result_fields')
@staticmethod
def get_run(run_id):
return Testrail.get('get_run/%s' % run_id)
@staticmethod
def get_runs(project_id, created_after=None, created_before=None,
created_by=None, is_completed=None, limit=None,
offset=None, milestone_id=None, suite_id=None):
pattern = 'get_runs/%s' % project_id
if created_after is not None:
pattern += '&created_after=%s' % created_after
if created_before is not None:
pattern += '&created_before=%s' % created_before
if | |
prebuilt_path = os.path.join(unpack_dir, "IMAGES", prebuilt_name)
if os.path.exists(prebuilt_path):
print "using prebuilt %s from IMAGES..." % (prebuilt_name,)
return File.FromLocalFile(name, prebuilt_path)
#print "building image from target_files %s..." % (tree_subdir,)
#fs_config = "META/" + tree_subdir.lower() + "_filesystem_config.txt"
#data = BuildBootableImage(os.path.join(unpack_dir, tree_subdir),
# os.path.join(unpack_dir, fs_config),
# info_dict)
#if data:
# return File(name, data)
return None
def UnzipTemp(filename, pattern=None):
"""Unzip the given archive into a temporary directory and return the name.
If filename is of the form "foo.zip+bar.zip", unzip foo.zip into a
temp dir, then unzip bar.zip into that_dir/BOOTABLE_IMAGES.
Returns (tempdir, zipobj) where zipobj is a zipfile.ZipFile (of the
main file), open for reading.
"""
tmp = tempfile.mkdtemp(prefix="targetfiles-")
OPTIONS.tempfiles.append(tmp)
def unzip_to_dir(filename, dirname):
cmd = ["unzip", "-o", "-q", filename, "-d", dirname]
if pattern is not None:
cmd.append(pattern)
p = Run(cmd, stdout=subprocess.PIPE)
p.communicate()
if p.returncode != 0:
raise ExternalError("failed to unzip input target-files \"%s\"" %
(filename,))
m = re.match(r"^(.*[.]zip)\+(.*[.]zip)$", filename, re.IGNORECASE)
if m:
unzip_to_dir(m.group(1), tmp)
unzip_to_dir(m.group(2), os.path.join(tmp, "BOOTABLE_IMAGES"))
filename = m.group(1)
else:
unzip_to_dir(filename, tmp)
return tmp, zipfile.ZipFile(filename, "r")
def GetKeyPasswords(keylist):
"""Given a list of keys, prompt the user to enter passwords for
those which require them. Return a {key: password} dict. password
will be None if the key has no password."""
no_passwords = []
need_passwords = []
key_passwords = {}
devnull = open("/dev/null", "w+b")
for k in sorted(keylist):
# We don't need a password for things that aren't really keys.
if k in SPECIAL_CERT_STRINGS:
no_passwords.append(k)
continue
p = Run(["openssl", "pkcs8", "-in", k+OPTIONS.private_key_suffix,
"-inform", "DER", "-nocrypt"],
stdin=devnull.fileno(),
stdout=devnull.fileno(),
stderr=subprocess.STDOUT)
p.communicate()
if p.returncode == 0:
# Definitely an unencrypted key.
no_passwords.append(k)
else:
p = Run(["openssl", "pkcs8", "-in", k+OPTIONS.private_key_suffix,
"-inform", "DER", "-passin", "pass:"],
stdin=devnull.fileno(),
stdout=devnull.fileno(),
stderr=subprocess.PIPE)
_, stderr = p.communicate()
if p.returncode == 0:
# Encrypted key with empty string as password.
key_passwords[k] = ''
elif stderr.startswith('Error decrypting key'):
# Definitely encrypted key.
# It would have said "Error reading key" if it didn't parse correctly.
need_passwords.append(k)
else:
# Potentially, a type of key that openssl doesn't understand.
# We'll let the routines in signapk.jar handle it.
no_passwords.append(k)
devnull.close()
key_passwords.update(PasswordManager().GetPasswords(need_passwords))
key_passwords.update(dict.fromkeys(no_passwords, None))
return key_passwords
def SignFile(input_name, output_name, key, password, align=None,
whole_file=False):
"""Sign the input_name zip/jar/apk, producing output_name. Use the
given key and password (the latter may be None if the key does not
have a password.
If align is an integer > 1, zipalign is run to align stored files in
the output zip on 'align'-byte boundaries.
If whole_file is true, use the "-w" option to SignApk to embed a
signature that covers the whole file in the archive comment of the
zip file.
"""
if align == 0 or align == 1:
align = None
if align:
temp = tempfile.NamedTemporaryFile()
sign_name = temp.name
else:
sign_name = output_name
cmd = [OPTIONS.java_path, OPTIONS.java_args, "-jar",
os.path.join(OPTIONS.search_path, OPTIONS.signapk_path)]
cmd.extend(OPTIONS.extra_signapk_args)
if whole_file:
cmd.append("-w")
cmd.extend([key + OPTIONS.public_key_suffix,
key + OPTIONS.private_key_suffix,
input_name, sign_name])
p = Run(cmd, stdin=subprocess.PIPE, stdout=subprocess.PIPE)
if password is not None:
password += "\n"
p.communicate(password)
if p.returncode != 0:
raise ExternalError("signapk.jar failed: return code %s" % (p.returncode,))
if align:
p = Run(["zipalign", "-f", "-p", str(align), sign_name, output_name])
p.communicate()
if p.returncode != 0:
raise ExternalError("zipalign failed: return code %s" % (p.returncode,))
temp.close()
def CheckSize(data, target, info_dict):
"""Check the data string passed against the max size limit, if
any, for the given target. Raise exception if the data is too big.
Print a warning if the data is nearing the maximum size."""
if target.endswith(".img"):
target = target[:-4]
mount_point = "/" + target
fs_type = None
limit = None
if info_dict["fstab"]:
if mount_point == "/userdata":
mount_point = "/data"
p = info_dict["fstab"][mount_point]
fs_type = p.fs_type
device = p.device
if "/" in device:
device = device[device.rfind("/")+1:]
limit = info_dict.get(device + "_size", None)
if not fs_type or not limit:
return
if fs_type == "yaffs2":
# image size should be increased by 1/64th to account for the
# spare area (64 bytes per 2k page)
limit = limit / 2048 * (2048+64)
size = len(data)
pct = float(size) * 100.0 / limit
msg = "%s size (%d) is %.2f%% of limit (%d)" % (target, size, pct, limit)
if pct >= 99.0:
raise ExternalError(msg)
elif pct >= 95.0:
print
print " WARNING: ", msg
print
elif OPTIONS.verbose:
print " ", msg
def ReadApkCerts(tf_zip):
"""Given a target_files ZipFile, parse the META/apkcerts.txt file
and return a {package: cert} dict."""
certmap = {}
for line in tf_zip.read("META/apkcerts.txt").split("\n"):
line = line.strip()
if not line:
continue
m = re.match(r'^name="(.*)"\s+certificate="(.*)"\s+'
r'private_key="(.*)"$', line)
if m:
name, cert, privkey = m.groups()
public_key_suffix_len = len(OPTIONS.public_key_suffix)
private_key_suffix_len = len(OPTIONS.private_key_suffix)
if cert in SPECIAL_CERT_STRINGS and not privkey:
certmap[name] = cert
elif (cert.endswith(OPTIONS.public_key_suffix) and
privkey.endswith(OPTIONS.private_key_suffix) and
cert[:-public_key_suffix_len] == privkey[:-private_key_suffix_len]):
certmap[name] = cert[:-public_key_suffix_len]
else:
raise ValueError("failed to parse line from apkcerts.txt:\n" + line)
return certmap
COMMON_DOCSTRING = """
-p (--path) <dir>
Prepend <dir>/bin to the list of places to search for binaries
run by this script, and expect to find jars in <dir>/framework.
-s (--device_specific) <file>
Path to the python module containing device-specific
releasetools code.
-x (--extra) <key=value>
Add a key/value pair to the 'extras' dict, which device-specific
extension code may look at.
-v (--verbose)
Show command lines being executed.
-h (--help)
Display this usage message and exit.
"""
def Usage(docstring):
print docstring.rstrip("\n")
print COMMON_DOCSTRING
def ParseOptions(argv,
docstring,
extra_opts="", extra_long_opts=(),
extra_option_handler=None):
"""Parse the options in argv and return any arguments that aren't
flags. docstring is the calling module's docstring, to be displayed
for errors and -h. extra_opts and extra_long_opts are for flags
defined by the caller, which are processed by passing them to
extra_option_handler."""
try:
opts, args = getopt.getopt(
argv, "hvp:s:x:" + extra_opts,
["help", "verbose", "path=", "signapk_path=", "extra_signapk_args=",
"java_path=", "java_args=", "public_key_suffix=",
"private_key_suffix=", "boot_signer_path=", "boot_signer_args=",
"verity_signer_path=", "verity_signer_args=", "device_specific=",
"extra="] +
list(extra_long_opts))
except getopt.GetoptError as err:
Usage(docstring)
print "**", str(err), "**"
sys.exit(2)
for o, a in opts:
if o in ("-h", "--help"):
Usage(docstring)
sys.exit()
elif o in ("-v", "--verbose"):
OPTIONS.verbose = True
elif o in ("-p", "--path"):
OPTIONS.search_path = a
elif o in ("--signapk_path",):
OPTIONS.signapk_path = a
elif o in ("--extra_signapk_args",):
OPTIONS.extra_signapk_args = shlex.split(a)
elif o in ("--java_path",):
OPTIONS.java_path = a
elif o in ("--java_args",):
OPTIONS.java_args = a
elif o in ("--public_key_suffix",):
OPTIONS.public_key_suffix = a
elif o in ("--private_key_suffix",):
OPTIONS.private_key_suffix = a
elif o in ("--boot_signer_path",):
OPTIONS.boot_signer_path = a
elif o in ("--boot_signer_args",):
OPTIONS.boot_signer_args = shlex.split(a)
elif o in ("--verity_signer_path",):
OPTIONS.verity_signer_path = a
elif o in ("--verity_signer_args",):
OPTIONS.verity_signer_args = shlex.split(a)
elif o in ("-s", "--device_specific"):
OPTIONS.device_specific = a
elif o in ("-x", "--extra"):
key, value = a.split("=", 1)
OPTIONS.extras[key] = value
else:
if extra_option_handler is None or not extra_option_handler(o, a):
assert False, "unknown option \"%s\"" % (o,)
if OPTIONS.search_path:
os.environ["PATH"] = (os.path.join(OPTIONS.search_path, "bin") +
os.pathsep + os.environ["PATH"])
return args
def MakeTempFile(prefix=None, suffix=None):
"""Make a temp file and add it to the list of things to be deleted
when Cleanup() is called. Return the filename."""
fd, fn = tempfile.mkstemp(prefix=prefix, suffix=suffix)
os.close(fd)
OPTIONS.tempfiles.append(fn)
return fn
def Cleanup():
for i in OPTIONS.tempfiles:
if os.path.isdir(i):
shutil.rmtree(i)
else:
os.remove(i)
class PasswordManager(object):
def __init__(self):
self.editor = os.getenv("EDITOR", None)
self.pwfile = os.getenv("ANDROID_PW_FILE", None)
def GetPasswords(self, items):
"""Get passwords corresponding to each string in 'items',
returning a dict. (The dict may have keys in addition to the
values in 'items'.)
Uses the passwords in $ANDROID_PW_FILE if available, letting the
user edit that file to add more needed passwords. If no editor is
available, or $ANDROID_PW_FILE isn't define, prompts the user
interactively in the ordinary way.
"""
current = self.ReadFile()
first = True
while True:
missing = []
for i in items:
if i not in current or not current[i]:
missing.append(i)
# Are all the passwords already in the file?
if not missing:
return current
for i in missing:
current[i] = ""
if not first:
print "key file %s still missing some passwords." % (self.pwfile,)
answer = raw_input("try to edit again? [y]> ").strip()
if answer and answer[0] not in 'yY':
raise RuntimeError("key passwords unavailable")
first = False
current = self.UpdateAndReadFile(current)
def PromptResult(self, current): # pylint: disable=no-self-use
"""Prompt the user to enter a value (password) for each key in
'current' | |
import torch.nn as nn
import torch
import math
import torch.utils.model_zoo as model_zoo
from torchvision.ops import nms
from retinanet.utils import BasicBlock, Bottleneck, BBoxTransform, ClipBoxes
from retinanet.anchors import Anchors
from retinanet import losses
import numpy as np
model_urls = {
'resnet18': 'https://download.pytorch.org/models/resnet18-5c106cde.pth',
'resnet34': 'https://download.pytorch.org/models/resnet34-333f7ec4.pth',
'resnet50': 'https://download.pytorch.org/models/resnet50-19c8e357.pth',
'resnet101': 'https://download.pytorch.org/models/resnet101-5d3b4d8f.pth',
'resnet152': 'https://download.pytorch.org/models/resnet152-b121ed2d.pth',
}
class SFU(nn.Module):
def __init__(self,out_channels):
super(SFU,self).__init__()
self.out_channels = 2 * out_channels
def forward(self,x_RGB,x_DOL):
out = torch.cat((x_RGB,x_DOL),1)
return out
class GFU(nn.Module):
def __init__(self,out_channels):
super(GFU,self).__init__()
self.input_channels = out_channels
self.out_channels = out_channels
self.conv_RGB = nn.Conv2d(self.input_channels,2*self.input_channels,kernel_size=3,padding=1)
self.act_RGB = nn.ReLU()
self.conv_DOL = nn.Conv2d(self.input_channels,2*self.input_channels,kernel_size=3,padding=1)
self.act_DOL = nn.ReLU()
self.conv_MIX = nn.Conv2d(4*self.input_channels,self.out_channels,kernel_size=1)
self.act_MIX = nn.ReLU()
def forward(self,x_RGB,x_DOL):
x_concat_1 = torch.cat((x_RGB,x_DOL),1)
x_RGB = self.conv_RGB(x_RGB)
x_RGB = self.act_RGB(x_RGB)
x_DOL = self.conv_DOL(x_DOL)
x_DOL = self.act_DOL(x_DOL)
x_RGB = x_RGB.add(x_concat_1)
x_DOL = x_DOL.add(x_concat_1)
x_concat_2 = torch.cat((x_RGB,x_DOL),1)
x_MIX = self.conv_MIX(x_concat_2)
x_MIX = self.act_MIX(x_MIX)
return x_MIX
class PyramidFeatures(nn.Module):
def __init__(self, C3_size, C4_size, C5_size, feature_size=256):
super(PyramidFeatures, self).__init__()
# upsample C5 to get P5 from the FPN paper
self.P5_1 = nn.Conv2d(C5_size, feature_size, kernel_size=1, stride=1, padding=0)
self.P5_upsampled = nn.Upsample(scale_factor=2, mode='nearest')
self.P5_2 = nn.Conv2d(feature_size, feature_size, kernel_size=3, stride=1, padding=1)
# add P5 elementwise to C4
self.P4_1 = nn.Conv2d(C4_size, feature_size, kernel_size=1, stride=1, padding=0)
self.P4_upsampled = nn.Upsample(scale_factor=2, mode='nearest')
self.P4_2 = nn.Conv2d(feature_size, feature_size, kernel_size=3, stride=1, padding=1)
# add P4 elementwise to C3
self.P3_1 = nn.Conv2d(C3_size, feature_size, kernel_size=1, stride=1, padding=0)
self.P3_2 = nn.Conv2d(feature_size, feature_size, kernel_size=3, stride=1, padding=1)
# "P6 is obtained via a 3x3 stride-2 conv on C5"
self.P6 = nn.Conv2d(C5_size, feature_size, kernel_size=3, stride=2, padding=1)
# "P7 is computed by applying ReLU followed by a 3x3 stride-2 conv on P6"
self.P7_1 = nn.ReLU()
self.P7_2 = nn.Conv2d(feature_size, feature_size, kernel_size=3, stride=2, padding=1)
def forward(self, inputs):
C3, C4, C5 = inputs
P5_x = self.P5_1(C5)
P5_upsampled_x = self.P5_upsampled(P5_x)
P5_x = self.P5_2(P5_x)
P4_x = self.P4_1(C4)
P4_x = P5_upsampled_x + P4_x
P4_upsampled_x = self.P4_upsampled(P4_x)
P4_x = self.P4_2(P4_x)
P3_x = self.P3_1(C3)
P3_x = P3_x + P4_upsampled_x
P3_x = self.P3_2(P3_x)
P6_x = self.P6(C5)
P7_x = self.P7_1(P6_x)
P7_x = self.P7_2(P7_x)
return [P3_x, P4_x, P5_x, P6_x, P7_x]
class RegressionModel(nn.Module):
def __init__(self, num_features_in, num_anchors=9, feature_size=256):
super(RegressionModel, self).__init__()
self.conv1 = nn.Conv2d(num_features_in, feature_size, kernel_size=3, padding=1)
self.act1 = nn.ReLU()
self.conv2 = nn.Conv2d(feature_size, feature_size, kernel_size=3, padding=1)
self.act2 = nn.ReLU()
self.conv3 = nn.Conv2d(feature_size, feature_size, kernel_size=3, padding=1)
self.act3 = nn.ReLU()
self.conv4 = nn.Conv2d(feature_size, feature_size, kernel_size=3, padding=1)
self.act4 = nn.ReLU()
self.output = nn.Conv2d(feature_size, num_anchors * 4, kernel_size=3, padding=1)
def forward(self, x):
out = self.conv1(x)
out = self.act1(out)
out = self.conv2(out)
out = self.act2(out)
out = self.conv3(out)
out = self.act3(out)
out = self.conv4(out)
out = self.act4(out)
out = self.output(out)
# out is B x C x W x H, with C = 4*num_anchors
out = out.permute(0, 2, 3, 1)
return out.contiguous().view(out.shape[0], -1, 4)
class ClassificationModel(nn.Module):
def __init__(self, num_features_in, num_anchors=9, num_classes=80, prior=0.01, feature_size=256,dataset=None):
super(ClassificationModel, self).__init__()
self.dataset = dataset
self.num_classes = num_classes
self.num_anchors = num_anchors
self.conv1 = nn.Conv2d(num_features_in, feature_size, kernel_size=3, padding=1)
self.act1 = nn.ReLU()
self.conv2 = nn.Conv2d(feature_size, feature_size, kernel_size=3, padding=1)
self.act2 = nn.ReLU()
self.conv3 = nn.Conv2d(feature_size, feature_size, kernel_size=3, padding=1)
self.act3 = nn.ReLU()
self.conv4 = nn.Conv2d(feature_size, feature_size, kernel_size=3, padding=1)
self.act4 = nn.ReLU()
if self.dataset is None:
self.output = nn.Conv2d(feature_size, num_anchors * num_classes, kernel_size=3, padding=1)
self.output_act = nn.Sigmoid()
else:
setattr(self,'output_{}'.format(self.dataset),nn.Conv2d(feature_size, num_anchors * num_classes, kernel_size=3, padding=1))
setattr(self,'output_act_{}'.format(self.dataset),nn.Sigmoid())
def forward(self, x):
out = self.conv1(x)
out = self.act1(out)
out = self.conv2(out)
out = self.act2(out)
out = self.conv3(out)
out = self.act3(out)
out = self.conv4(out)
out = self.act4(out)
if self.dataset is None:
out = self.output(out)
out = self.output_act(out)
else:
out = getattr(self,'output_{}'.format(self.dataset))(out)
out = getattr(self,'output_act_{}'.format(self.dataset))(out)
# out is B x C x W x H, with C = n_classes + n_anchors
out1 = out.permute(0, 2, 3, 1)
batch_size, width, height, channels = out1.shape
out2 = out1.view(batch_size, width, height, self.num_anchors, self.num_classes)
return out2.contiguous().view(x.shape[0], -1, self.num_classes)
class ResNet(nn.Module):
def __init__(self, num_classes, block, layers, evaluate=False,ignore_class=False,dataset=None):
if ignore_class:
num_classes -= 1
self.ignore_index = num_classes
else:
self.ignore_index = None
self.dataset = dataset
self.evaluate=evaluate
self.inplanes = 64
super(ResNet, self).__init__()
self.conv1 = nn.Conv2d(3, 64, kernel_size=7, stride=2, padding=3, bias=False)
self.bn1 = nn.BatchNorm2d(64)
self.relu = nn.ReLU(inplace=True)
self.maxpool = nn.MaxPool2d(kernel_size=3, stride=2, padding=1)
self.layer1 = self._make_layer(block, 64, layers[0])
self.layer2 = self._make_layer(block, 128, layers[1], stride=2)
self.layer3 = self._make_layer(block, 256, layers[2], stride=2)
self.layer4 = self._make_layer(block, 512, layers[3], stride=2)
if block == BasicBlock:
fpn_sizes = [self.layer2[layers[1] - 1].conv2.out_channels, self.layer3[layers[2] - 1].conv2.out_channels,
self.layer4[layers[3] - 1].conv2.out_channels]
elif block == Bottleneck:
fpn_sizes = [self.layer2[layers[1] - 1].conv3.out_channels, self.layer3[layers[2] - 1].conv3.out_channels,
self.layer4[layers[3] - 1].conv3.out_channels]
else:
raise ValueError(f"Block type {block} not understood")
self.fpn = PyramidFeatures(fpn_sizes[0], fpn_sizes[1], fpn_sizes[2])
self.regressionModel = RegressionModel(256)
self.classificationModel = ClassificationModel(256, num_classes=num_classes,dataset=dataset)
self.anchors = Anchors()
self.regressBoxes = BBoxTransform()
self.clipBoxes = ClipBoxes()
self.focalLoss = losses.FocalLoss()
for m in self.modules():
if isinstance(m, nn.Conv2d):
n = m.kernel_size[0] * m.kernel_size[1] * m.out_channels
m.weight.data.normal_(0, math.sqrt(2. / n))
elif isinstance(m, nn.BatchNorm2d):
m.weight.data.fill_(1)
m.bias.data.zero_()
prior = 0.01
if self.dataset is None:
self.classificationModel.output.weight.data.fill_(0)
self.classificationModel.output.bias.data.fill_(-math.log((1.0 - prior) / prior))
else:
with torch.no_grad():
getattr(self.classificationModel,'output_{}'.format(self.dataset)).weight.data.fill_(0)
getattr(self.classificationModel,'output_{}'.format(self.dataset)).bias.data.fill_(-math.log((1.0 - prior) / prior))
self.regressionModel.output.weight.data.fill_(0)
self.regressionModel.output.bias.data.fill_(0)
self.freeze_bn()
def _make_layer(self, block, planes, blocks, stride=1):
downsample = None
if stride != 1 or self.inplanes != planes * block.expansion:
downsample = nn.Sequential(
nn.Conv2d(self.inplanes, planes * block.expansion,
kernel_size=1, stride=stride, bias=False),
nn.BatchNorm2d(planes * block.expansion),
)
layers = [block(self.inplanes, planes, False, stride, downsample)]
self.inplanes = planes * block.expansion
for i in range(1, blocks):
layers.append(block(self.inplanes, planes, False))
return nn.Sequential(*layers)
def freeze_bn(self):
'''Freeze BatchNorm layers.'''
for layer in self.modules():
if isinstance(layer, nn.BatchNorm2d):
layer.eval()
def forward(self, inputs):
if not self.evaluate:
img_batch, annotations = inputs
else:
img_batch = inputs
x = self.conv1(img_batch)
x = self.bn1(x)
x = self.relu(x)
x = self.maxpool(x)
x1 = self.layer1(x)
x2 = self.layer2(x1)
x3 = self.layer3(x2)
x4 = self.layer4(x3)
features = self.fpn([x2, x3, x4])
regression = torch.cat([self.regressionModel(feature) for feature in features], dim=1)
classification = torch.cat([self.classificationModel(feature) for feature in features], dim=1)
#TMP
classification = torch.Tensor(np.zeros((1,181089,8),dtype=np.float32)).cuda()
regression = torch.Tensor(np.zeros((1,181089,4),dtype=np.float32)).cuda()
for i in [10000]: #[ 8524, 8528, 9982, 9990, 9991, 9992, 9993, 9994, 9999, 10000, 10001, 10002, 10003, 10004, 10008, 10009, 10010, 10011, 10012, 10018, 11476, 11480]:
classification[0,i,0]=1
anchors = self.anchors(img_batch)
transformed_anchors = self.regressBoxes(anchors, regression)
transformed_anchors = self.clipBoxes(transformed_anchors, img_batch)
scores = torch.max(classification, dim=2, keepdim=True)[0]
scores_over_thresh = (scores > 0.05)[0, :, 0]
classification_2 = classification[:, scores_over_thresh, :]
transformed_anchors = transformed_anchors[:, scores_over_thresh, :]
scores = scores[:, scores_over_thresh, :]
anchors_nms_idx = nms(transformed_anchors[0,:,:], scores[0,:,0], 0.5)
nms_scores, nms_class = classification_2[0, anchors_nms_idx, :].max(dim=1)
return classification, regression, anchors, annotations, (nms_scores, nms_class, transformed_anchors[0, anchors_nms_idx, :])
def resnet18(num_classes, pretrained=False, color_mode='RGB', fusion_type=0, step=1, **kwargs):
"""Constructs a ResNet-18 model.
Args:
pretrained (bool): If True, returns a model pre-trained on ImageNet
"""
if step==2:
model = Double_ResNet(num_classes, BasicBlock, [2, 2, 2, 2], color_mode, fusion_type, step, **kwargs)
else:
model = ResNet(num_classes, BasicBlock, [2, 2, 2, 2], **kwargs)
if pretrained:
model.load_state_dict(model_zoo.load_url(model_urls['resnet18'], model_dir='.'), strict=False)
return model
def resnet34(num_classes, pretrained=False, color_mode='RGB', fusion_type=0, step=1, **kwargs):
"""Constructs a ResNet-34 model.
Args:
pretrained (bool): If True, returns a model pre-trained on ImageNet
"""
if step==2:
model = Double_ResNet(num_classes, BasicBlock, [3, 4, 6, 3], color_mode, fusion_type, step, **kwargs)
else:
model = ResNet(num_classes, BasicBlock, [3, 4, 6, 3], **kwargs)
if pretrained:
model.load_state_dict(model_zoo.load_url(model_urls['resnet34'], model_dir='.'), strict=False)
return model
def resnet50(num_classes, pretrained=False, color_mode='RGB', fusion_type=0, step=1, **kwargs):
"""Constructs a ResNet-50 model.
Args:
pretrained (bool): If True, returns a model pre-trained on ImageNet
"""
if step==2:
model = Double_ResNet(num_classes, Bottleneck, [3, 4, 6, 3], color_mode, fusion_type, step, **kwargs)
else:
model = ResNet(num_classes, Bottleneck, [3, 4, 6, 3], **kwargs)
if pretrained:
model.load_state_dict(model_zoo.load_url(model_urls['resnet50'], model_dir='.'), strict=False)
return model
def resnet101(num_classes, pretrained=False, color_mode='RGB', fusion_type=0, step=1, **kwargs):
"""Constructs a ResNet-101 model.
Args:
pretrained (bool): If True, returns a model pre-trained on ImageNet
"""
if step==2:
model = Double_ResNet(num_classes, Bottleneck, [3, 4, 23, 3], color_mode, fusion_type, step, **kwargs)
else:
model = ResNet(num_classes, Bottleneck, [3, 4, 23, 3], **kwargs)
if pretrained:
model.load_state_dict(model_zoo.load_url(model_urls['resnet101'], model_dir='.'), strict=False)
return model
def resnet152(num_classes, pretrained=False, color_mode='RGB', fusion_type=0, step=1, **kwargs):
"""Constructs a ResNet-152 model.
Args:
pretrained (bool): If True, returns a model pre-trained on ImageNet
"""
if step==2:
model = Double_ResNet(num_classes, Bottleneck, [3, 8, 36, 3], color_mode, fusion_type, step, **kwargs)
else:
model = ResNet(num_classes, Bottleneck, [3, 8, 36, 3], **kwargs)
if pretrained:
model.load_state_dict(model_zoo.load_url(model_urls['resnet152'], model_dir='.'), strict=False)
return model
#################################################################################################################
class Double_ResNet(nn.Module):
def __init__(self, num_classes, block, layers, color_mode, fusion_type, step, evaluate = False, ignore_class=False,dataset=None):
if ignore_class:
num_classes -= 1
self.ignore_index = num_classes
else:
self.ignore_index = None
self.dataset = dataset
self.evaluate=evaluate
self.fusion_type = fusion_type
| |
<gh_stars>1-10
# -*- coding: utf-8 -*-
import csv
from collections import defaultdict, namedtuple
from datetime import datetime, timedelta
import pkg_resources
import re
from zipfile import ZipFile
from enum import Enum, unique
from io import TextIOWrapper
Train = namedtuple("Train", ["name", "kind", "direction", "stops", "service_windows"])
Station = namedtuple("Station", ["name", "zone"])
Stop = namedtuple(
"Stop", ["arrival", "arrival_day", "departure", "departure_day", "stop_number"]
)
ServiceWindow = namedtuple(
"ServiceWindow", ["id", "name", "start", "end", "days", "removed"]
)
_BASE_DATE = datetime(1970, 1, 1, 0, 0, 0, 0)
class Trip(namedtuple("Trip", ["departure", "arrival", "duration", "train"])):
def __str__(self):
return "[{kind} {name}] Departs: {departs}, Arrives: {arrives} ({duration})".format(
kind=self.train.kind,
name=self.train.name,
departs=self.departure,
arrives=self.arrival,
duration=self.duration,
)
def __unicode__(self):
return unicode(self.__str__())
def __repr__(self):
return (
"Trip(departure={departure}, arrival={arrival}, duration={duration}, "
"train=Train(name={train}))".format(
departure=repr(self.departure),
arrival=repr(self.arrival),
duration=repr(self.duration),
train=self.train.name,
)
)
def _sanitize_name(name):
"""
Pre-sanitization to increase the likelihood of finding
a matching station.
:param name: the station name
:type name: str or unicode
:returns: sanitized station name
"""
return (
"".join(re.split("[^A-Za-z0-9]", name)).lower().replace("station", "").strip()
)
def _resolve_time(t):
"""
Resolves the time string into datetime.time. This method
is needed because Caltrain arrival/departure time hours
can exceed 23 (e.g. 24, 25), to signify trains that arrive
after 12 AM. The 'day' variable is incremented from 0 in
these situations, and the time resolved back to a valid
datetime.time (e.g. 24:30:00 becomes days=1, 00:30:00).
:param t: the time to resolve
:type t: str or unicode
:returns: tuple of days and datetime.time
"""
hour, minute, second = [int(x) for x in t.split(":")]
day, hour = divmod(hour, 24)
r = _BASE_DATE + timedelta(hours=hour, minutes=minute, seconds=second)
return day, r.time()
def _resolve_duration(start, end):
"""
Resolves the duration between two times. Departure/arrival
times that exceed 24 hours or cross a day boundary are correctly
resolved.
:param start: the time to resolve
:type start: Stop
:param end: the time to resolve
:type end: Stop
:returns: tuple of days and datetime.time
"""
start_time = _BASE_DATE + timedelta(
hours=start.departure.hour,
minutes=start.departure.minute,
seconds=start.departure.second,
days=start.departure_day,
)
end_time = _BASE_DATE + timedelta(
hours=end.arrival.hour,
minutes=end.arrival.minute,
seconds=end.arrival.second,
days=end.departure_day,
)
return end_time - start_time
_STATIONS_RE = re.compile(r"^(.+) Caltrain( Station)?$")
_RENAME_MAP = {
"SO. SAN FRANCISCO": "SOUTH SAN FRANCISCO",
"MT VIEW": "MOUNTAIN VIEW",
"CALIFORNIA AVE": "CALIFORNIA AVENUE",
}
_DEFAULT_GTFS_FILE = "data/GTFSTransitData_ct.zip"
_ALIAS_MAP_RAW = {
"SAN FRANCISCO": ("SF", "SAN FRAN"),
"SOUTH SAN FRANCISCO": (
"S SAN FRANCISCO",
"SOUTH SF",
"SOUTH SAN FRAN",
"S SAN FRAN",
"S SAN FRANCISCO",
"S SF",
"SO SF",
"SO SAN FRANCISCO",
"SO SAN FRAN",
),
"22ND ST": (
"TWENTY-SECOND STREET",
"TWENTY-SECOND ST",
"22ND STREET",
"22ND",
"TWENTY-SECOND",
"22",
),
"MOUNTAIN VIEW": "MT VIEW",
"CALIFORNIA AVENUE": (
"CAL AVE",
"CALIFORNIA",
"CALIFORNIA AVE",
"CAL",
"CAL AV",
"CALIFORNIA AV",
),
"REDWOOD CITY": "REDWOOD",
"<NAME>": ("DIRIDON", "<NAME>", "<NAME>", "SJ"),
"COL<NAME>ARK": "COLLEGE",
"BLOSSOM HILL": "BLOSSOM",
"<NAME>": "MORGAN",
"HAYWARD PARK": "HAYWARD",
"MENLO PARK": "MENLO",
}
_ALIAS_MAP = {}
for k, v in _ALIAS_MAP_RAW.items():
if not isinstance(v, list) and not isinstance(v, tuple):
v = (v,)
for x in v:
_ALIAS_MAP[_sanitize_name(x)] = _sanitize_name(k)
@unique
class Direction(Enum):
north = 0
south = 1
@unique
class TransitType(Enum):
shuttle = 0
local = 1
limited = 2
baby_bullet = 3
weekend_game_train = 4
@staticmethod
def from_trip_id(trip_id):
if trip_id[0] == "s":
return TransitType.shuttle
if trip_id[0] in ("3", "8"):
return TransitType.baby_bullet
if trip_id[0] in ("1", "4"):
return TransitType.local
if trip_id[0] in ("2", "5"):
return TransitType.limited
if trip_id[0] == "6":
return TransitType.weekend_game_train
raise ValueError(
"unable to derive transit type from trip ID: {}".format(trip_id)
)
def __str__(self):
return self.name.replace("_", " ").title()
class UnexpectedGTFSLayoutError(Exception):
pass
class UnknownStationError(Exception):
pass
class Caltrain(object):
def __init__(self, gtfs_path=None):
self.version = None
self.trains = {}
self.stations = {}
self._unambiguous_stations = {}
self._service_windows = {}
self._fares = {}
self.load_from_gtfs(gtfs_path)
def load_from_gtfs(self, gtfs_path=None):
"""
Loads a GTFS zip file and builds the data model from it.
If not specified, the internally stored GTFS zip file from
Caltrain is used instead.
:param gtfs_path: the path of the GTFS zip file to load
:type gtfs_path: str or unicode
"""
# Use the default path if not specified.
if gtfs_path is None:
gtfs_handle = pkg_resources.resource_stream(__name__, _DEFAULT_GTFS_FILE)
else:
gtfs_handle = open(gtfs_path, "rb")
with gtfs_handle as f:
self._load_from_gtfs(f)
def _load_from_gtfs(self, handle):
z = ZipFile(handle)
self.trains, self.stations = {}, {}
self._service_windows, self._fares = defaultdict(list), {}
# -------------------
# 1. Record fare data
# -------------------
fare_lookup = {}
# Create a map if (start, dest) -> price
with z.open("fare_attributes.txt", "r") as csvfile:
fare_reader = csv.DictReader(TextIOWrapper(csvfile))
for r in fare_reader:
fare_lookup[r["fare_id"]] = tuple(int(x) for x in r["price"].split("."))
# Read in the fare IDs from station X to station Y.
with z.open("fare_rules.txt", "r") as csvfile:
fare_reader = csv.DictReader(TextIOWrapper(csvfile))
for r in fare_reader:
if r["origin_id"] == "" or r["destination_id"] == "":
continue
k = (int(r["origin_id"]), int(r["destination_id"]))
self._fares[k] = fare_lookup[r["fare_id"]]
# ------------------------
# 2. Record calendar dates
# ------------------------
# Record the days when certain trains are active.
with z.open("calendar.txt", "r") as csvfile:
calendar_reader = csv.reader(TextIOWrapper(csvfile))
next(calendar_reader) # skip the header
for r in calendar_reader:
self._service_windows[r[0]].append(
ServiceWindow(
id=r[0],
name=r[1],
start=datetime.strptime(r[-2], "%Y%m%d").date(),
end=datetime.strptime(r[-1], "%Y%m%d").date(),
days=set(i for i, j in enumerate(r[2:9]) if int(j) == 1),
removed=False,
)
)
# Find special events/holiday windows where trains are active.
with z.open("calendar_dates.txt", "r") as csvfile:
calendar_reader = csv.reader(TextIOWrapper(csvfile))
next(calendar_reader) # skip the header
for r in calendar_reader:
when = datetime.strptime(r[1], "%Y%m%d").date()
self._service_windows[r[0]].insert(
0,
ServiceWindow(
id=r[0],
name=r[1],
start=when,
end=when,
days={when.weekday()},
removed=r[-1] == "2",
),
)
# ------------------
# 3. Record stations
# ------------------
with z.open("stops.txt", "r") as csvfile:
trip_reader = csv.DictReader(TextIOWrapper(csvfile))
for r in trip_reader:
# From observation, non-numeric stop IDs are useless information
# that should be skipped.
if not r["stop_id"].isdigit():
continue
stop_name = _STATIONS_RE.match(r["stop_name"]).group(1).strip().upper()
self.stations[r["stop_id"]] = {
"name": _RENAME_MAP.get(stop_name, stop_name).title(),
"zone": int(r["zone_id"]) if r["zone_id"] else -1,
}
# ---------------------------
# 4. Record train definitions
# ---------------------------
with z.open("trips.txt", "r") as csvfile:
train_reader = csv.DictReader(TextIOWrapper(csvfile))
for r in train_reader:
train_dir = int(r["direction_id"])
transit_type = TransitType.from_trip_id(r["trip_id"])
service_windows = self._service_windows[r["service_id"]]
self.trains[r["trip_id"]] = Train(
name=r["trip_short_name"] if r["trip_short_name"] else r["trip_id"],
kind=transit_type,
direction=Direction(train_dir),
stops={},
service_windows=service_windows,
)
self.stations = dict(
(k, Station(v["name"], v["zone"])) for k, v in self.stations.items()
)
# -----------------------
# 5. Record trip stations
# -----------------------
with z.open("stop_times.txt", "r") as csvfile:
stop_times_reader = csv.DictReader(TextIOWrapper(csvfile))
for r in stop_times_reader:
stop_id = r["stop_id"]
train = self.trains[r["trip_id"]]
arrival_day, arrival = _resolve_time(r["arrival_time"])
departure_day, departure = _resolve_time(r["departure_time"])
train.stops[self.stations[stop_id]] = Stop(
arrival=arrival,
arrival_day=arrival_day,
departure=departure,
departure_day=departure_day,
stop_number=int(r["stop_sequence"]),
)
# For display
self.stations = dict(
("_".join(re.split("[^A-Za-z0-9]", v.name)).lower(), v)
for _, v in self.stations.items()
)
# For station lookup by string
self._unambiguous_stations = dict(
(k.replace("_", ""), v) for k, v in self.stations.items()
)
def get_station(self, name):
"""
Attempts to resolves a station name from a string into an
actual station. An UnknownStationError is thrown if no
Station can be derived
:param name: the name to resolve
:type name: str or unicode
:returns: the resolved Station object
"""
sanitized = _sanitize_name(name)
sanitized = _ALIAS_MAP.get(sanitized, sanitized)
station = self._unambiguous_stations.get(sanitized, None)
if station:
return station
else:
raise UnknownStationError(name)
def fare_between(self, a, b):
"""
Returns the fare to travel between stations a and b. Caltrain fare
is always dependent on the distance and not the train type.
:param a: the starting station
:type a: str or unicode or Station
:param b: the destination station
:type b: str or unicode or Station
:returns: tuple of the dollar and cents cost
"""
a = self.get_station(a) if not isinstance(a, Station) else a
b = self.get_station(b) if not isinstance(b, Station) else b
return self._fares[(a.zone, b.zone)]
def next_trips(self, a, b, after=None):
"""
Returns a list of possible trips to get from stations a to b
following the after date. These are ordered from soonest to
latest and terminate at the end of the Caltrain's 'service day'.
:param a: the starting station
:type a: str or unicode or Station
:param b: the destination station
:type b: str or unicode or Station
:param after: the time to find the next trips after
(default datetime.now())
:type after: datetime
:returns: a list of possible trips
"""
if after is None:
after = datetime.now()
a = self.get_station(a) if not isinstance(a, Station) else a
b = self.get_station(b) if not isinstance(b, Station) else b
possibilities = []
for name, train in self.trains.items():
should_skip = set()
for sw in train.service_windows:
in_time_window = (
sw.start <= after.date() <= sw.end and after.weekday() in sw.days
)
stops_at_stations | |
mask
0x02: Repeat mask
0x04: Gate mask
These values may be OR'ed together to enable any desired set
of markers for each point in the sequence.
0: All waveform event markers are disabled.
This array must have same length as wfm_handles array.
Return:
-------
seq_handle: Integer:
Handle identifying the created advanced sequence
'''
wfm_handles = np.array(wfm_handles)
loop_counts = np.array(loop_counts)
adv_modes = np.array(adv_modes)
marker_masks = np.array(marker_masks)
array_len = len(wfm_handles)
if not all([len(array) == array_len for array in
[loop_counts, adv_modes, marker_masks]]):
raise ValueError("All arrays must have equal length")
ViInt32Array = array_len * ViInt32
ViUInt8Array = array_len * ViUInt8
wfm_handles = wfm_handles.astype(ViInt32)
loop_counts = loop_counts.astype(ViInt32)
adv_modes = adv_modes.astype(ViUInt8)
marker_masks = marker_masks.astype(ViUInt8)
seq_handle = ViInt32(0)
rc = self._dll.AGN6030A_CreateAdvancedSequence(self._handle,
ViInt32(array_len), ViInt32Array(*wfm_handles), ViInt32Array(*loop_counts),
ViUInt8Array(*adv_modes), ViUInt8Array(*marker_masks), byref(seq_handle))
self._status_handle(rc)
return seq_handle.value
def create_arb_scenario(self, seq_handles, loop_counts, marker_masks):
'''
Create an arbitrary scenario handle
Parameters:
-----------
seq_handles: 1D List/Array of Integers
Array of advanced sequence handles.
loop_counts: 1D List/Array of Integers
Array of loop counts for arbitrary sequences of the new scenario.
Each loop_counts array element corresponds to a seq_handles array
element and indicates how many times to repeat that advanced
sequence. Must have same length as seq_handles
marker_masks: 1D List/Array of Integers
For each sequence, you can enable or disable markers that are
automatically generated when the sequence stars, repeats,
or during the time the sequence is being played (gate) using
the following values:
0x01: Start mask
0x02: Repeat mask
0x04: Gate mask
These values may be OR'ed together to enable any desired set
of markers for each point in the scenario.
0: All waveform event markers are disabled.
This array must have same length as seq_handles array.
'''
seq_handles = np.array(seq_handles)
loop_counts = np.array(loop_counts)
marker_masks = np.array(marker_masks)
array_len = len(seq_handles)
if not all([len(array) == array_len for array in
[loop_counts, marker_masks]]):
raise ValueError("All arrays must have equal length")
ViInt32Array = array_len * ViInt32
ViUInt8Array = array_len * ViUInt8
seq_handles = seq_handles.astype(ViInt32)
loop_counts = loop_counts.astype(ViInt32)
marker_masks = marker_masks.astype(ViUInt8)
scenario_handle = ViInt32(0)
rc = self._dll.AGN6030A_CreateArbScenario(self._handle, ViInt32(array_len),
ViInt32Array(*seq_handles), ViInt32Array(*loop_counts),
ViUInt8Array(*marker_masks), byref(scenario_handle)
)
self._status_handle(rc)
return scenario_handle.value
def clear_arb_memory(self):
'''
Clears all previously created waveforms and sequences from the memory
and invalidates all waveform and sequence handles
'''
self.abort_generation()
rc = self._dll.AGN6030A_ClearArbMemory(self._handle)
self._status_handle(rc)
def configure_output_configuration(self,
ch, configuration, filter_enabled, filter_bandwidth):
'''
Configure the output configuration and the filter and
filter bandwidth attributes.
Parameters:
-----------
ch: Integer
Channel number
configuration: Integer
0: differential output
1: single ended output
2: amplified output
filter_enabled: Boolean
If True, filter is enabled
filter_bandwidth: float
250e6: Limit bandwidth to 250MHz
500e6: Limit bandwidth to 500MHz
'''
rc = self._dll.AGN6030A_ConfigureOutputConfiguration(
self._handle, ViString(basestring(ch)),
ViInt32(configuration),
ViBoolean(filter_enabled),
ViReal64(filter_bandwidth)
)
self._status_handle(rc)
self.get_all()
def _set_sample_clock_source(self, source):
if source == 'Internal':
self.configure_sample_clock(0, 1.25e9)
elif source == 'External':
self.configure_sample_clock(0, self.clock_frequency())
def _set_sample_clock_frequency(self, freq):
if self.clock_source():
self.configure_sample_clock(1, freq)
else:
logging.warning('Cannot set frequency in internal clock source mode. Clock frequency is 1.25 GHz')
def configure_sample_clock(self, source, freq):
'''
Configure the sample clock to be used
Call abort_generation prior to calling this function and then restart
waveform playback with initiate_generation.
Parameters:
-----------
source: Integer
0: Internal clock
1: External clock
freq: Float
Frequency of the clock in Hz.
Restrictions:
internal: Fixed to 1.25e9
external: 100e6 to 1.25e9
'''
rc = self._dll.AGN6030A_ConfigureSampleClock(
self._handle, ViInt32(source), ViReal64(freq))
self._status_handle(rc)
self.clock_source()
self.clock_frequency()
def initiate_generation(self):
'''Initiate the generation of the output signal.'''
rc = self._dll.AGN6030A_InitiateGeneration(self._handle)
self._status_handle(rc)
def run(self):
'''Initiate generation of the output signal and slave triggers.'''
self.initiate_generation()
if self.sync() and (self.sync_mode() == 'Master'):
if hasattr(self, '_sync_marker_source'):
self.m4.source(self._sync_marker_source)
def wait(self):
'''Does nothing.'''
pass
def clear_arb_waveform(self, wfm_handle):
'''
Removes a previously created arbitrary waveform from the memory and
invalidates the waveform handle
Parameters:
-----------
wfm_handle: Integer
Waveform handle
'''
if not isinstance(wfm_handle, ViInt32):
wfm_handle = ViInt32(wfm_handle)
rc = self._dll.AGN6030A_ClearArbWaveform(self._handle, wfm_handle)
self._status_handle(rc)
def _pad_wfm(self, wfm_data):
wfm_len = len(wfm_data)
remain = wfm_len % 8
add_samples = 0
if remain != 0:
add_samples = 8 - remain
logging.debug(__name__ + ": waveform length not an integer"
" multiple of 8. Append last element {:d} times"
" to match this condition.". format(add_samples))
wfm_len += add_samples
wfm_data = np.pad(wfm_data, (add_samples, 0), 'constant')
return wfm_data
def create_arb_waveform(self, wfm_data):
'''
Create a new waveform handle without markers
Parameters:
-----------
wfm_data: 1 dimensional list or np.ndarray
Waveform to be uploaded. All elements must be normalized
between -1.00 and +1.00
Restrictions:
Length must be an integer multiple of 8.
return:
-------
wfm_handle: Integer
Waveform handle referencing the uploaded waveform
'''
# Make waveform length integer multiple of 8
# and convert waveform to correct type
wfm_data = np.array(wfm_data)
wfm_data = self._pad_wfm(wfm_data)
wfm_len = len(wfm_data)
wfm_data = wfm_data.astype(np.float64)
ViReal64Array = wfm_len * ViReal64
wfm_handle = ViInt32(0)
rc = self._dll.AGN6030A_CreateArbWaveform(self._handle, ViInt32(wfm_len),
ViReal64Array(*wfm_data), byref(wfm_handle)
)
self._status_handle(rc)
return wfm_handle.value
def configure_arb_waveform(self, ch, wfm_handle, gain, offset):
'''
Configure the gain and offset of a specific waveform
Parameters:
-----------
ch: Integer
Channel number
wfm_handle: Integer
Waveform handle that identifies the arbitrary waveform to
generate.
gain: Float
Output amplitude (Vpp/2) of the waveform in Volts.
Restrictions:
single ended: 0.170 <= gain <= 0.250
amplified/differential: 0.340 <= gain <= 0.500
offset: Float
DC offset in Volts added to the waveform output.
Restrictions:
-1.00 <= offset <= 1.00
'''
if not isinstance(wfm_handle, ViInt32):
wfm_handle = ViInt32(wfm_handle)
rc = self._dll.AGN6030A_ConfigureArbWaveform(
self._handle, ViString(basestring(ch)),wfm_handle, ViReal64(gain), ViReal64(offset))
self._status_handle(rc)
self.get_all()
def clear_advanced_sequence(self, seq_handle):
'''
Removes the previously created advanced sequence from the memory and
invalidates the sequence handle
Parameters:
-----------
seq_handle: Integer
Advanced sequence handle
'''
if not isinstance(seq_handle, ViInt32):
seq_handle = ViInt32(seq_handle)
rc = self._dll.AGN6030A_ClearAdvancedSquence(self._handle, seq_handle)
self._status_handle(rc)
def clear_arb_sequence(self, seq_handle):
'''
Removes the previously created arbitrary sequence from the memory and
invalidates the sequence handle
Parameters:
-----------
seq_handle: Integer
Handle that identifies the arbitrary sequence to clear
'''
if not isinstance(seq_handle, ViInt32):
seq_handle = ViInt32(seq_handle)
rc = self._dll.AGN6030A_ClearArbSquence(self._handle, seq_handle)
self._status_handle(rc)
def configure_arb_sequence(self, ch, seq_handle, gain, offset):
'''
Configure the gain and offset attribute of the arbitrary waveform generator
that affect sequence generation
Parameters:
-----------
ch: Integer
Channel number
seq_handle: Integer
Sequence handle that identifies the arbitrary sequence to
generate.
gain: Float
Output amplitude (Vpp/2) of the waveform in Volts.
Restrictions:
single ended: 0.170 <= gain <= 0.250
amplified/differential: 0.340 <= gain <= 0.500
offset: Float
DC offset in Volts added to the waveform output.
Restrictions:
-1.00 <= offset <= 1.00
'''
if not isinstance(seq_handle, ViInt32):
seq_handle = ViInt32(seq_handle)
rc = self._dll.AGN6030A_ConfigureArbSequence(
self._handle, ViString(basestring(ch)), seq_handle, ViReal64(gain), ViReal64(offset))
self._status_handle(rc)
self.get_all()
def create_arb_sequence(self, wfm_handles, loop_counts):
# TODO: Check for maximal loop count
'''
Create a new waveform handle without markers
Parameters:
-----------
wfm_handles: 1 dimensional list or np.ndarray
An array of waveform handles for the new sequence
loop_counts: 1 dimensional list or np.ndarray of 32 bit integers
An array that specifies the loop counts for the new sequence.
Each element corresponds to a wfm_handles array element and indicates
how many times to repeat that waveform.
Must have the same length as wfm_handles.
return:
-------
seq_handle: Integer
Arbitrary sequence handle referencing the generated sequence.
'''
wfm_handles = np.array(wfm_handles)
loop_counts = np.array(loop_counts)
wfm_handles_len = len(wfm_handles)
if wfm_handles_len != len(loop_counts):
raise ValueError("`wfm_handles` and `loop_counts` must have same length.")
wfm_handles = wfm_handles.astype(ViInt32)
loop_counts = loop_counts.astype(ViInt32)
ViInt32Array = wfm_handles_len * ViInt32
seq_handle = ViInt32(0)
rc = self._dll.AGN6030A_CreateArbSequence(
self._handle, ViInt32(wfm_handles_len), ViInt32Array(*wfm_handles),
ViInt32Array(*loop_counts), byref(seq_handle)
)
self._status_handle(rc)
return seq_handle.value
def clear_arb_scenario(self, scenario_handle):
'''
Remove a previously created advanced sequence scenario from the memory
and invalidate the handle that identifies it
Parameter:
----------
scenario_handle: Integer
Handle identifying the scenario to be cleared.
'''
rc = self._dll.AGN6030A_ClearArbScenario(self._handle, ViInt32(scenario_handle))
self._status_handle(rc)
def configure_arb_scenario(
self, ch, scenario_handle, play_mode, jump_mode, gain, offset):
'''
Configure the attributes that affect | |
<reponame>oasys-kit/dabax<gh_stars>0
#
# dabax functions with the same interface as xraylib
#
import numpy
import scipy.constants as codata
from silx.io.specfile import SpecFile
from dabax.common_tools import atomic_symbols, atomic_names, atomic_number
from dabax.common_tools import bragg_metrictensor
from dabax.common_tools import calculate_f0_from_f0coeff
class DabaxXraylibDecorator(object):
#########################
# crystals
#########################
def Crystal_GetCrystal(self, entry_name='YB66'):
"""
parse a complex crystal structure file into a dictionary (like xraylib.Crystal_GetCrystal('Si'))
it has an additional fiels for each atom: the charge
return a dictionary containing crystal infomation
"""
dabax_repository = self.get_dabax_repository()
filename = self.get_file_Crystals()
file1 = self.get_dabax_file(filename)
sf = SpecFile(file1)
flag_found = False
for index in range(len(sf)):
s1 = sf[index]
name = s1.scan_header_dict["S"]
if name.split(' ')[1] == entry_name:
flag_found = True
index_found = index
if not flag_found:
raise (Exception("Entry name not found: %s" % entry_name))
cryst = {'name': entry_name} # returned dictionary like that one created by xraylib.Crystal_GetCrystal(descriptor)
cell_parameters = sf[index_found].scan_header_dict["UCELL"]
cell_parameters = ' '.join(cell_parameters.split()) # remove multiple blanks
a = cell_parameters.split(' ')
cryst['a'] = float(a[0])
cryst['b'] = float(a[1])
cryst['c'] = float(a[2])
cryst['alpha'] = float(a[3])
cryst['beta'] = float(a[4])
cryst['gamma'] = float(a[5])
volume = bragg_metrictensor(float(a[0]), float(a[1]), float(a[2]),
float(a[3]), float(a[4]), float(a[5]), RETURN_VOLUME=1)
cryst['volume'] = volume
cell_data = numpy.array(sf[index_found].data)
cryst['n_atom'] = cell_data.shape[1]
atom = []
for i in range(cell_data.shape[1]):
if cell_data.shape[0] == 5: # standard 5 columns
# not here, this info is not in the dabax file
# s = symbol_to_from_atomic_number(int(cell_data[0,i]))
atom.append({
'Zatom': int(cell_data[0, i]),
'fraction': cell_data[1, i],
'x': cell_data[2, i],
'y': cell_data[3, i],
'z': cell_data[4, i],
'charge': 0.0, })
else: # 6 columns (charge)
# 'AtomicName' required to compatible my current code
# s = symbol_to_from_atomic_number(int(cell_data[0,i]))
# if cell_data[5, i] != 0: #charged
# s = s + f'%+.6g'%cell_data[5, i]
atom.append({
# 'AtomicName': s,
'Zatom': int(cell_data[0, i]),
'fraction': cell_data[1, i],
'x': cell_data[2, i],
'y': cell_data[3, i],
'z': cell_data[4, i],
'charge': cell_data[5, i], })
cryst['atom'] = atom
cryst['cpointer'] = None
ANISO_KEY = "UANISO_COFF" # prefix for a line with anisotropic coefficients
d = sf[index_found].scan_header_dict
AnisoItem = {'Name': ' ',
'start': 0,
'end': 0,
'beta11': 0.0,
'beta22': 0.0,
'beta33': 0.0,
'beta12': 0.0,
'beta13': 0.0,
'beta23': 0.0}
a = [(x, d[x].split()) for x in d if x[:len(ANISO_KEY)] == ANISO_KEY]
if len(a) > 0: # found Anisotropic coefficients in the header, process it
a = sorted(a, key=lambda x: int(x[1][0]),
reverse=False) # sort 'Start' ascendant, avoid order changed by the SpecFile
n = 0
Aniso = []
for x in a: # tuple('UANISO_COFF_B1',[1 96 0.00038 0.00044 0.00039 0 0 0])
AnisoItem['Name'] = x[0][len(ANISO_KEY) + 1:] # get site atom name starting from 13th character 'B1', etc
AnisoItem['start'] = int(x[1][0])
AnisoItem['end'] = int(x[1][1])
AnisoItem['beta11'] = float(x[1][2])
AnisoItem['beta22'] = float(x[1][3])
AnisoItem['beta33'] = float(x[1][4])
AnisoItem['beta12'] = float(x[1][5])
AnisoItem['beta13'] = float(x[1][6])
AnisoItem['beta23'] = float(x[1][7])
Aniso.append(AnisoItem.copy())
n = n + 1
cryst['Aniso'] = Aniso # if having key 'Ansio' when there is anisotropic data,otherwise no
cryst['n_aniso'] = n
else: # create a dummy Aniso to compatible with xraylib
cryst['Aniso'] = [AnisoItem.copy()]
cryst['n_aniso'] = 1
return cryst
def Crystal_GetCrystalsList(self):
"""
get crystal names from crystals.dat
"""
file1 = self.get_dabax_file(self.get_file_Crystals())
sf = SpecFile(file1)
crystals = []
for index in range(len(sf)):
s1 = sf[index]
name = s1.scan_header_dict["S"]
crystals.append(name.split(' ')[1])
return crystals
def Crystal_dSpacing(self, cryst, h, k, l):
return bragg_metrictensor(cryst['a'], cryst['b'], cryst['c'],
cryst['alpha'], cryst['beta'], cryst['gamma'],
HKL=[h, k, l])
def Bragg_angle(self, cryst, E_keV, h, k, l):
dspacing = self.Crystal_dSpacing(cryst, h, k, l) # in A
wavelength = codata.h * codata.c / codata.e / (E_keV * 1e3) * 1e10 # in A
return numpy.arcsin(wavelength / 2 / dspacing)
def Crystal_F_H_StructureFactor(self,
crystal_id,
energy_in_kev,
millerH,
millerK,
millerL,
debyeWaller,
ratio_theta_thetaB=1.0):
energy = energy_in_kev * 1e3
wavelength = codata.h * codata.c / codata.e / energy * 1e10
# print(crystal_id["n_atom"])
atom = crystal_id['atom']
natom = len(atom)
list_fraction = [atom[i]['fraction'] for i in range(natom)]
list_x = [atom[i]['x'] for i in range(natom)]
list_y = [atom[i]['y'] for i in range(natom)]
list_z = [atom[i]['z'] for i in range(natom)]
F_H = numpy.zeros(numpy.array(energy).size, dtype=complex)
for i in range(natom):
atom_i = atom[i]
if (i > 0) and (atom_i['Zatom'] == Z_i) and (atom_i['charge'] == charge_i):
pass # avoid re-calculating f0 if inputs are identical to previous call
else:
Z_i = atom_i['Zatom']
charge_i = atom_i['charge']
coeffs = self.f0_with_fractional_charge(Z_i, charge=charge_i)
if (millerH == 0 and millerK == 0 and millerL == 0):
ratio = 0.0
else:
angle = self.Bragg_angle(crystal_id, energy_in_kev,
millerH, millerK, millerL) * ratio_theta_thetaB
ratio = numpy.sin(angle) / wavelength
f0_i = calculate_f0_from_f0coeff(coeffs, ratio)
Fi = self.Fi(Z_i, energy_in_kev)
Fii = self.Fii(Z_i, energy_in_kev)
F_H += (f0_i + Fi - Fii * 1j) * list_fraction[i] * \
numpy.exp(2j*numpy.pi*(millerH*list_x[i]+millerK*list_y[i]+millerL*list_z[i]))
return F_H * debyeWaller
#########################
# misc
#########################
def CompoundParser(self, descriptor):
return self.compound_parser(descriptor)
def SymbolToAtomicNumber(self, symbol):
return atomic_number(symbol)
def AtomicNumberToSymbol(self, Z):
return atomic_symbols()[Z]
def ElementDensity(self, Z):
return self.element_density(self.AtomicNumberToSymbol(Z))
def AtomicWeight(self, Z):
return self.atomic_weights(self.AtomicNumberToSymbol(Z))
#########################
# scattering functions
#########################
def Fi(self, Z, energy):
return self.FiAndFii(Z, energy)[0]
def Fii(self, Z, energy):
return self.FiAndFii(Z, energy)[1]
def FF_Rayl(self, Z, q):
coeffs = self.f0_with_fractional_charge(Z, charge=0.0)
return calculate_f0_from_f0coeff(coeffs, q)
#########################
# cross sections
#########################
# main (barns)
def CSb_Total(self, Z, energy):
return self.crosssec_interpolate(self.AtomicNumberToSymbol(Z), energy * 1e3,
partial='TotalCrossSection[barn/atom]',)
def CSb_Photo(self, Z, energy):
return self.crosssec_interpolate(self.AtomicNumberToSymbol(Z), energy * 1e3,
partial='PhotoElectric[barn/atom]',)
def CSb_Rayl(self, Z, energy):
return self.crosssec_interpolate(self.AtomicNumberToSymbol(Z), energy * 1e3,
partial='Rayleigh(coherent)[barn/atom]',)
def CSb_Compt(self, Z, energy):
return self.crosssec_interpolate(self.AtomicNumberToSymbol(Z), energy * 1e3,
partial='Compton(incoherent)[barn/atom]',)
# in cm2/g
def CS_Total(self, Z, energy):
return self.CSb_Total(Z, energy) * (codata.Avogadro * 1e-24 / self.AtomicWeight(Z))
def CS_Photo(self, Z, energy):
return self.CSb_Photo(Z, energy) * (codata.Avogadro * 1e-24 / self.AtomicWeight(Z))
def CS_Rayl(self, Z, energy):
return self.CSb_Rayl(Z, energy) * (codata.Avogadro * 1e-24 / self.AtomicWeight(Z))
def CS_Compt(self, Z, energy):
return self.CSb_Compt(Z, energy) * (codata.Avogadro * 1e-24 / self.AtomicWeight(Z))
# for compounds
def CS_Total_CP(self, descriptor, energy):
cp = self.CompoundParserCheckingNIST(descriptor,)
out = 0.0
for i in range(cp["nElements"]):
out += self.CS_Total(cp["Elements"][i], energy) * cp["massFractions"][i]
return out
def CSb_Total_CP(self, descriptor, energy):
cp = self.CompoundParserCheckingNIST(descriptor,)
out = 0.0
for i in range(cp["nElements"]):
out += self.CSb_Total(cp["Elements"][i], energy) * cp["massFractions"][i]
return out
def CS_Photo_CP(self, descriptor, energy):
cp = self.CompoundParserCheckingNIST(descriptor,)
out = 0.0
for i in range(cp["nElements"]):
out += self.CS_Photo(cp["Elements"][i], energy) * cp["massFractions"][i]
return out
def CSb_Photo_CP(self, descriptor, energy):
cp = self.CompoundParserCheckingNIST(descriptor,)
out = 0.0
for i in range(cp["nElements"]):
out += self.CSb_Photo(cp["Elements"][i], energy) * cp["massFractions"][i]
return out
def CS_Rayl_CP(self, descriptor, energy):
cp = self.CompoundParserCheckingNIST(descriptor,)
out = 0.0
for i in range(cp["nElements"]):
out += self.CS_Rayl(cp["Elements"][i], energy) * cp["massFractions"][i]
return out
def CSb_Rayl_CP(self, descriptor, energy):
cp = self.CompoundParserCheckingNIST(descriptor,)
out = 0.0
for i in range(cp["nElements"]):
out += self.CSb_Rayl(cp["Elements"][i], energy) * cp["massFractions"][i]
return out
def CS_Compt_CP(self, descriptor, energy):
cp = self.CompoundParserCheckingNIST(descriptor,)
out = 0.0
for i in range(cp["nElements"]):
out += self.CS_Compt(cp["Elements"][i], energy) * cp["massFractions"][i]
return out
def CSb_Compt_CP(self, descriptor, energy):
cp = self.CompoundParserCheckingNIST(descriptor,)
out = 0.0
for i in range(cp["nElements"]):
out += self.CSb_Compt(cp["Elements"][i], energy) * cp["massFractions"][i]
return out
#########################
# refractive index
#########################
def Refractive_Index_Re(self, descriptor, energy, density):
cp = self.compound_parser(descriptor)
KD = 4.15179082788e-4 # TODO: recalculate with codata....
rv = 0.0
for i in range(cp["nElements"]):
Z = cp["Elements"][i]
rv += cp["massFractions"][i] * KD * (Z + self.Fi(Z, energy)) / \
self.AtomicWeight(Z) / energy / energy
return (1 - rv * density)
def Refractive_Index_Im(self, descriptor, energy, density):
cp = self.compound_parser(descriptor)
rv = 0.0
for i in range(cp["nElements"]):
Z = cp["Elements"][i]
rv += self.CS_Total(Z, energy) * cp["massFractions"][i]
# /*9.8663479e-9 is calculated as planck's constant * speed of light / 4Pi */
# return rv * density * 9.8663479e-9 / E;
return rv * density * 9.8663479e-9 / energy
#
# NIST compounds
#
def GetCompoundDataNISTList(self):
file1 = self.get_dabax_file("CompoundsNIST.dat")
sf = SpecFile(file1)
list1 = []
for index in range(len(sf)):
list1.append(sf[index].scan_header_dict["Uname"])
return list1
def GetCompoundDataNISTByIndex(self, index_found):
file1 = self.get_dabax_file("CompoundsNIST.dat")
sf = SpecFile(file1)
s1 = sf[index_found]
data = s1.data
name = s1.scan_header_dict["Uname"]
nElements = int(s1.scan_header_dict["UnElements"])
density = float(s1.scan_header_dict["Udensity"])
Elements = []
massFractions = []
for i in range(nElements):
Elements.append(int(data[0][i]))
massFractions.append(data[1][i])
return {"name": name, 'nElements': nElements, 'density': density, 'Elements': Elements,
'massFractions': massFractions}
def GetCompoundDataNISTByName(self, entry_name):
list1 = self.GetCompoundDataNISTList()
return self.GetCompoundDataNISTByIndex(list1.index(entry_name))
#
#
# DONE:
#
#
# (used in xoppy_xraylib_util):
# xraylib.Crystal_GetCrystal(descriptor)
# xraylib.Crystal_dSpacing(cryst, hh, kk, ll)
# xraylib.Crystal_dSpacing
# xraylib.CompoundParser(descriptor)
# xraylib.SymbolToAtomicNumber(descriptor)
# xraylib.AtomicNumberToSymbol(zi)
# xraylib.ElementDensity(Z)
# xraylib.AtomicWeight
# xraylib.FF_Rayl(xraylib.SymbolToAtomicNumber(descriptor), iqscale)
# xraylib.Fi(Z,1e-3*ienergy)
# xraylib.Fii(Z,1e-3*ienergy)
# xraylib.Crystal_F_H_StructureFactor(_crystal, | |
feats
else:
return images_recon
##################################################################################
# Encoder and Decoders
##################################################################################
class E_adaIN(nn.Module):
def __init__(self, input_nc, output_nc=1, nef=64, n_layers=4,
norm=None, nl_layer=None, vae=False):
# style encoder
super(E_adaIN, self).__init__()
self.enc_style = StyleEncoder(n_layers, input_nc, nef, output_nc, norm='none', activ='relu', vae=vae)
def forward(self, image):
style = self.enc_style(image)
return style
class StyleEncoder(nn.Module):
def __init__(self, n_downsample, input_dim, dim, style_dim, norm, activ, vae=False):
super(StyleEncoder, self).__init__()
self.vae = vae
self.model = []
self.model += [Conv2dBlock(input_dim, dim, 7, 1, 3, norm=norm, activation=activ, pad_type='reflect')]
for i in range(2):
self.model += [Conv2dBlock(dim, 2 * dim, 4, 2, 1, norm=norm, activation=activ, pad_type='reflect')]
dim *= 2
for i in range(n_downsample - 2):
self.model += [Conv2dBlock(dim, dim, 4, 2, 1, norm=norm, activation=activ, pad_type='reflect')]
self.model += [nn.AdaptiveAvgPool2d(1)] # global average pooling
if self.vae:
self.fc_mean = nn.Linear(dim, style_dim) # , 1, 1, 0)
self.fc_var = nn.Linear(dim, style_dim) # , 1, 1, 0)
else:
self.model += [nn.Conv2d(dim, style_dim, 1, 1, 0)]
self.model = nn.Sequential(*self.model)
self.output_dim = dim
def forward(self, x):
if self.vae:
output = self.model(x)
output = output.view(x.size(0), -1)
output_mean = self.fc_mean(output)
output_var = self.fc_var(output)
return output_mean, output_var
else:
return self.model(x).view(x.size(0), -1)
class ContentEncoder(nn.Module):
def __init__(self, n_downsample, n_res, input_dim, dim, norm, activ, pad_type='zero'):
super(ContentEncoder, self).__init__()
self.model = []
self.model += [Conv2dBlock(input_dim, dim, 7, 1, 3, norm=norm, activation=activ, pad_type='reflect')]
# downsampling blocks
for i in range(n_downsample):
self.model += [Conv2dBlock(dim, 2 * dim, 4, 2, 1, norm=norm, activation=activ, pad_type='reflect')]
dim *= 2
# residual blocks
self.model += [ResBlocks(n_res, dim, norm=norm, activation=activ, pad_type=pad_type)]
self.model = nn.Sequential(*self.model)
self.output_dim = dim
def forward(self, x, nce_layers=[], encode_only=False):
if len(nce_layers) > 0:
feat = x
feats = []
for layer_id, layer in enumerate(self.model):
feat = layer(feat)
if layer_id in nce_layers:
feats.append(feat)
if layer_id == nce_layers[-1] and encode_only:
return None, feats
return feat, feats
else:
return self.model(x), None
for layer_id, layer in enumerate(self.model):
print(layer_id, layer)
class Decoder_all(nn.Module):
def __init__(self, n_upsample, n_res, dim, output_dim, norm='batch', activ='relu', pad_type='zero', nz=0):
super(Decoder_all, self).__init__()
# AdaIN residual blocks
self.resnet_block = ResBlocks(n_res, dim, norm, activ, pad_type=pad_type, nz=nz)
self.n_blocks = 0
# upsampling blocks
for i in range(n_upsample):
block = [Upsample2(scale_factor=2), Conv2dBlock(dim + nz, dim // 2, 5, 1, 2, norm='ln', activation=activ, pad_type='reflect')]
setattr(self, 'block_{:d}'.format(self.n_blocks), nn.Sequential(*block))
self.n_blocks += 1
dim //= 2
# use reflection padding in the last conv layer
setattr(self, 'block_{:d}'.format(self.n_blocks), Conv2dBlock(dim + nz, output_dim, 7, 1, 3, norm='none', activation='tanh', pad_type='reflect'))
self.n_blocks += 1
def forward(self, x, y=None):
if y is not None:
output = self.resnet_block(cat_feature(x, y))
for n in range(self.n_blocks):
block = getattr(self, 'block_{:d}'.format(n))
if n > 0:
output = block(cat_feature(output, y))
else:
output = block(output)
return output
class Decoder(nn.Module):
def __init__(self, n_upsample, n_res, dim, output_dim, norm='batch', activ='relu', pad_type='zero', nz=0):
super(Decoder, self).__init__()
self.model = []
# AdaIN residual blocks
self.model += [ResBlocks(n_res, dim, norm, activ, pad_type=pad_type, nz=nz)]
# upsampling blocks
for i in range(n_upsample):
if i == 0:
input_dim = dim + nz
else:
input_dim = dim
self.model += [Upsample2(scale_factor=2), Conv2dBlock(input_dim, dim // 2, 5, 1, 2, norm='ln', activation=activ, pad_type='reflect')]
dim //= 2
# use reflection padding in the last conv layer
self.model += [Conv2dBlock(dim, output_dim, 7, 1, 3, norm='none', activation='tanh', pad_type='reflect')]
self.model = nn.Sequential(*self.model)
def forward(self, x, y=None):
if y is not None:
return self.model(cat_feature(x, y))
else:
return self.model(x)
##################################################################################
# Sequential Models
##################################################################################
class ResBlocks(nn.Module):
def __init__(self, num_blocks, dim, norm='inst', activation='relu', pad_type='zero', nz=0):
super(ResBlocks, self).__init__()
self.model = []
for i in range(num_blocks):
self.model += [ResBlock(dim, norm=norm, activation=activation, pad_type=pad_type, nz=nz)]
self.model = nn.Sequential(*self.model)
def forward(self, x):
return self.model(x)
##################################################################################
# Basic Blocks
##################################################################################
def cat_feature(x, y):
y_expand = y.view(y.size(0), y.size(1), 1, 1).expand(
y.size(0), y.size(1), x.size(2), x.size(3))
x_cat = torch.cat([x, y_expand], 1)
return x_cat
class ResBlock(nn.Module):
def __init__(self, dim, norm='inst', activation='relu', pad_type='zero', nz=0):
super(ResBlock, self).__init__()
model = []
model += [Conv2dBlock(dim + nz, dim, 3, 1, 1, norm=norm, activation=activation, pad_type=pad_type)]
model += [Conv2dBlock(dim, dim + nz, 3, 1, 1, norm=norm, activation='none', pad_type=pad_type)]
self.model = nn.Sequential(*model)
def forward(self, x):
residual = x
out = self.model(x)
out += residual
return out
class Conv2dBlock(nn.Module):
def __init__(self, input_dim, output_dim, kernel_size, stride,
padding=0, norm='none', activation='relu', pad_type='zero'):
super(Conv2dBlock, self).__init__()
self.use_bias = True
# initialize padding
if pad_type == 'reflect':
self.pad = nn.ReflectionPad2d(padding)
elif pad_type == 'zero':
self.pad = nn.ZeroPad2d(padding)
else:
assert 0, "Unsupported padding type: {}".format(pad_type)
# initialize normalization
norm_dim = output_dim
if norm == 'batch':
self.norm = nn.BatchNorm2d(norm_dim)
elif norm == 'inst':
self.norm = nn.InstanceNorm2d(norm_dim, track_running_stats=False)
elif norm == 'ln':
self.norm = LayerNorm(norm_dim)
elif norm == 'none':
self.norm = None
else:
assert 0, "Unsupported normalization: {}".format(norm)
# initialize activation
if activation == 'relu':
self.activation = nn.ReLU(inplace=True)
elif activation == 'lrelu':
self.activation = nn.LeakyReLU(0.2, inplace=True)
elif activation == 'prelu':
self.activation = nn.PReLU()
elif activation == 'selu':
self.activation = nn.SELU(inplace=True)
elif activation == 'tanh':
self.activation = nn.Tanh()
elif activation == 'none':
self.activation = None
else:
assert 0, "Unsupported activation: {}".format(activation)
# initialize convolution
self.conv = nn.Conv2d(input_dim, output_dim, kernel_size, stride, bias=self.use_bias)
def forward(self, x):
x = self.conv(self.pad(x))
if self.norm:
x = self.norm(x)
if self.activation:
x = self.activation(x)
return x
class LinearBlock(nn.Module):
def __init__(self, input_dim, output_dim, norm='none', activation='relu'):
super(LinearBlock, self).__init__()
use_bias = True
# initialize fully connected layer
self.fc = nn.Linear(input_dim, output_dim, bias=use_bias)
# initialize normalization
norm_dim = output_dim
if norm == 'batch':
self.norm = nn.BatchNorm1d(norm_dim)
elif norm == 'inst':
self.norm = nn.InstanceNorm1d(norm_dim)
elif norm == 'ln':
self.norm = LayerNorm(norm_dim)
elif norm == 'none':
self.norm = None
else:
assert 0, "Unsupported normalization: {}".format(norm)
# initialize activation
if activation == 'relu':
self.activation = nn.ReLU(inplace=True)
elif activation == 'lrelu':
self.activation = nn.LeakyReLU(0.2, inplace=True)
elif activation == 'prelu':
self.activation = nn.PReLU()
elif activation == 'selu':
self.activation = nn.SELU(inplace=True)
elif activation == 'tanh':
self.activation = nn.Tanh()
elif activation == 'none':
self.activation = None
else:
assert 0, "Unsupported activation: {}".format(activation)
def forward(self, x):
out = self.fc(x)
if self.norm:
out = self.norm(out)
if self.activation:
out = self.activation(out)
return out
##################################################################################
# Normalization layers
##################################################################################
class LayerNorm(nn.Module):
def __init__(self, num_features, eps=1e-5, affine=True):
super(LayerNorm, self).__init__()
self.num_features = num_features
self.affine = affine
self.eps = eps
if self.affine:
self.gamma = nn.Parameter(torch.Tensor(num_features).uniform_())
self.beta = nn.Parameter(torch.zeros(num_features))
def forward(self, x):
shape = [-1] + [1] * (x.dim() - 1)
mean = x.view(x.size(0), -1).mean(1).view(*shape)
std = x.view(x.size(0), -1).std(1).view(*shape)
x = (x - mean) / (std + self.eps)
if self.affine:
shape = [1, -1] + [1] * (x.dim() - 2)
x = x * self.gamma.view(*shape) + self.beta.view(*shape)
return x
class ResnetGenerator(nn.Module):
"""Resnet-based generator that consists of Resnet blocks between a few downsampling/upsampling operations.
We adapt Torch code and idea from <NAME>'s neural style transfer project(https://github.com/jcjohnson/fast-neural-style)
"""
def __init__(self, input_nc, output_nc, ngf=64, norm_layer=nn.BatchNorm2d, use_dropout=False, n_blocks=6, padding_type='reflect', no_antialias=False, no_antialias_up=False, opt=None):
"""Construct a Resnet-based generator
Parameters:
input_nc (int) -- the number of channels in input images
output_nc (int) -- the number of channels in output images
ngf (int) -- the number of filters in the last conv layer
norm_layer -- normalization layer
use_dropout (bool) -- if use dropout layers
n_blocks (int) -- the number of ResNet blocks
padding_type (str) -- the name of padding layer in conv layers: reflect | replicate | zero
"""
assert(n_blocks >= 0)
super(ResnetGenerator, self).__init__()
self.opt = opt
if type(norm_layer) == functools.partial:
use_bias = norm_layer.func == nn.InstanceNorm2d
else:
use_bias = norm_layer == nn.InstanceNorm2d
model = [nn.ReflectionPad2d(3),
nn.Conv2d(input_nc, ngf, kernel_size=7, padding=0, bias=use_bias),
norm_layer(ngf),
nn.ReLU(True)]
n_downsampling = 2
for i in range(n_downsampling): # add downsampling layers
mult = 2 ** i
if(no_antialias):
model += [nn.Conv2d(ngf * mult, ngf * mult * 2, kernel_size=3, stride=2, padding=1, bias=use_bias),
norm_layer(ngf * mult * 2),
nn.ReLU(True)]
else:
model += [nn.Conv2d(ngf * mult, ngf * mult * 2, kernel_size=3, stride=1, padding=1, bias=use_bias),
norm_layer(ngf * mult * 2),
nn.ReLU(True),
Downsample(ngf * mult * 2)]
mult = 2 ** n_downsampling
for i in range(n_blocks): # add ResNet blocks
model += [ResnetBlock(ngf * mult, padding_type=padding_type, norm_layer=norm_layer, use_dropout=use_dropout, use_bias=use_bias)]
for i in range(n_downsampling): # add upsampling layers
mult = 2 ** (n_downsampling - i)
if no_antialias_up:
model += [nn.ConvTranspose2d(ngf * mult, int(ngf * mult / 2),
kernel_size=3, stride=2,
padding=1, output_padding=1,
bias=use_bias),
norm_layer(int(ngf * mult / 2)),
nn.ReLU(True)]
else:
model += [Upsample(ngf * mult),
nn.Conv2d(ngf * mult, int(ngf * mult / 2),
kernel_size=3, stride=1,
padding=1, # output_padding=1,
bias=use_bias),
norm_layer(int(ngf * mult / 2)),
nn.ReLU(True)]
model += [nn.ReflectionPad2d(3)]
model += [nn.Conv2d(ngf, | |
<gh_stars>0
import torch
import torch.nn as nn
from torch.utils.data import DataLoader
from torch.utils.tensorboard import SummaryWriter
import sys
import os
import json
import numpy as np
import time
from datetime import timedelta
from copy import deepcopy
from sklearn.metrics import precision_recall_fscore_support
from ACSConv.experiments.mylib.utils import categorical_to_one_hot
from unet_2d import UNet
from unet_2d import UNetGN
from unet_2d import UNetGN4
from unet_2d import UNetGNAffine
from unet_2d import UNetBIGGN
from unet_2d import UNetSmall
from unet_2d import UNetSmallGN
from unet_3d import UNet3D as Unet3D_Counterpart_to_2D
from unet_3d import UNet3DGN
from unet_3d import UNet3D1M
from unet_3d import UNet3D1MGN
from unet_2d import UnetACSWithClassifier
from unet_2d import UnetACSWithClassifierGN
from unet_2d import UnetACSAxisAwareDecoder
from unet_2d import UnetACSWithClassifierOnly
from unet_2d import UnetACSAxisAwareDecoderNoSpatial
from unet3d import UNet3D
from dataset import Dataset
from dataset_2d import Dataset2D
from dataset_pytorch import DatasetPytorch
from datasets_pytorch import DatasetsPytorch
from finetune_config import FineTuneConfig
from config import models_genesis_config
from stats import Statistics
from dice_loss import DiceLoss
from image_transformations import generate_pair
from utils import pad_if_necessary, save_object, make_1_hot_mask_for_dice
class Trainer:
"""
Initializing model from scratch allows for:
- Training on dataset from scratch with ModelGenesis self supervised framework
Using pretrained weights as a starting point this class allows for finetuning the model by:
- Using ModelGenesis self supervised framework (finetune_self_supervised)
- Performing supervised task
"""
def __init__(self, config: FineTuneConfig, dataset: Dataset):
self.dataset = dataset
self.config = config
self.stats = Statistics(self.config, self.dataset)
self.tb_writer = SummaryWriter(config.summarywriter_dir)
self.device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
print("DEVICE: ", self.device)
def finetune_supervised(self):
self.start_time = time.time()
train_dataset = DatasetPytorch(self.dataset, self.config, type_="train", apply_mg_transforms=False)
train_data_loader = DataLoader(
train_dataset,
batch_size=self.config.batch_size_sup,
num_workers=self.config.workers,
collate_fn=DatasetPytorch.custom_collate,
pin_memory=True,
)
val_dataset = DatasetPytorch(self.dataset, self.config, type_="val", apply_mg_transforms=False)
val_data_loader = DataLoader(
val_dataset,
batch_size=self.config.batch_size_sup,
num_workers=self.config.workers,
collate_fn=DatasetPytorch.custom_collate,
pin_memory=True,
)
test_dataset = DatasetPytorch(self.dataset, self.config, type_="test", apply_mg_transforms=False)
test_data_loader = DataLoader(
test_dataset,
batch_size=self.config.batch_size_sup,
num_workers=self.config.workers,
collate_fn=DatasetPytorch.custom_collate,
pin_memory=True,
)
if self.config.loss_function_sup.lower() == "binary_cross_entropy":
criterion = nn.BCELoss() # if model outputs sigmoid no use of BCEwithLogits
criterion.to(self.device)
elif self.config.loss_function_sup.lower() == "binary_cross_entropy_with_logits":
criterion = nn.BCEWithLogitsLoss()
criterion.to(self.device)
elif self.config.loss_function_sup.lower() == "dice":
criterion = DiceLoss.dice_loss
elif self.config.loss_function_sup.lower() == "cross_entropy":
criterion = nn.CrossEntropyLoss()
if "unet_acs_with_cls" in self.config.model.lower():
criterion_cls = nn.CrossEntropyLoss()
criterion_cls.to(self.device)
if self.epoch_sup_check > 0:
print("RESUMING SUP TRAINING FROM EPOCH {} out of max {}".format(self.epoch_sup_check, self.config.nb_epoch_sup))
print(
"PREVIOUS BEST SUP LOSS: {} // NUM SUP EPOCHS WITH NO IMPROVEMENT {}".format(
self.best_loss_sup, self.num_epoch_no_improvement_sup
)
)
try:
print("CURRNT SUP LR: {}, SCHEDULER: {}".format(self.scheduler_sup.get_last_lr(), self.config.scheduler_sup))
except AttributeError:
print("CURRNT SUP LR: {}, SCHEDULER: {}".format(self.optimizer_sup.param_groups[0]["lr"], self.config.scheduler_sup))
else:
print("STARTING SUP TRAINING FROM SCRATCH")
print("{} TRAINING EXAMPLES".format(train_dataset.__len__()))
print("{} VALIDATION EXAMPLES".format(val_dataset.__len__()))
print("{} TESTING EXAMPLES".format(test_dataset.__len__()))
GLOBAL_TRAIN_ITER = 0
GLOBAL_VAL_ITER = 0
GLOBAL_TEST_ITER = 0
for self.epoch_sup_current in range(self.epoch_sup_check, self.config.nb_epoch_sup):
self.model.train()
self.stats.training_losses_sup = []
self.stats.validation_losses_sup = []
self.stats.testing_losses_sup = []
if "unet_acs_with_cls" in self.config.model.lower():
self.stats.training_losses_sup_cls = []
self.stats.validation_losses_sup_cls = []
self.stats.testing_losses_sup_cls = []
self.stats.training_losses_sup_seg = []
self.stats.validation_losses_sup_seg = []
self.stats.testing_losses_sup_seg = []
self.stats.training_recall = []
self.stats.training_precision = []
self.stats.training_f1 = []
self.stats.training_accuracy = []
self.stats.validation_recall = []
self.stats.validation_precision = []
self.stats.validation_f1 = []
self.stats.validation_accuracy = []
self.stats.testing_recall = []
self.stats.testing_precision = []
self.stats.testing_f1 = []
self.stats.testing_accuracy = []
for iteration, (x, y) in enumerate(train_data_loader):
start_time = time.time()
if x is None:
raise RuntimeError
if y is not None:
x, y = x.float().to(self.device), y.float().to(self.device)
else:
x = x.float().to(self.device)
y = make_1_hot_mask_for_dice(y)
assert ((y == 0) | (y == 1)).all()
pred = self.model(x)
if "unet_acs_with_cls" in self.config.model.lower():
pred_, x_cls, targets_cls = pred
x_cls, targets_cls = x_cls.to(self.device), targets_cls.to(self.device)
pred = pred_ # for segmentation
pr, rc, f1, accu = self.compute_precision_recall_f1(x_cls.cpu(), targets_cls.cpu())
if self.config.introduce_surrogate_at_epoch <= self.epoch_sup_current:
self.tb_writer.add_scalars(
"Classification Metrics/",
{
"Train Precision": pr,
"Train Recall": rc,
"Train F1": f1,
"Train Accuracy": accu,
},
GLOBAL_TRAIN_ITER,
)
else:
self.tb_writer.add_scalars(
"Classification Metrics PRE USE/",
{
"Train Precision": pr,
"Train Recall": rc,
"Train F1": f1,
"Train Accuracy": accu,
},
GLOBAL_TRAIN_ITER,
)
self.stats.training_precision.append(pr)
self.stats.training_recall.append(rc)
self.stats.training_f1.append(f1)
self.stats.training_accuracy.append(accu)
loss_cls = criterion_cls(x_cls, targets_cls)
loss_cls.to(self.device)
loss_cls *= self.config.surrogate_loss_weight
self.tb_writer.add_scalar("Loss/Train CLS", loss_cls.item(), GLOBAL_TRAIN_ITER)
self.stats.training_losses_sup_cls.append(loss_cls.item())
loss = criterion(pred, y)
loss.to(self.device)
self.optimizer_sup.zero_grad()
if "unet_acs_with_cls" in self.config.model.lower():
self.tb_writer.add_scalar("Loss/Train Segmentation", loss.item(), GLOBAL_TRAIN_ITER)
if self.config.introduce_surrogate_at_epoch <= self.epoch_sup_current:
tmp_cls_loss = loss_cls.item()
else:
tmp_cls_loss = 0
self.tb_writer.add_scalars(
"Losses Train/",
{"Segmentation": loss.item(), "CLS": tmp_cls_loss, "GLOBAL": loss.item() + loss_cls.item()},
GLOBAL_TRAIN_ITER,
)
self.stats.training_losses_sup_seg.append(loss.item())
if self.config.introduce_surrogate_at_epoch <= self.epoch_sup_current:
loss += loss_cls
loss.backward()
self.optimizer_sup.step()
self.tb_writer.add_scalar("Loss/Train", loss.item(), GLOBAL_TRAIN_ITER)
self.stats.training_losses_sup.append(loss.item())
per_class_dice = DiceLoss.dice_loss(
pred, y, per_class=True, return_loss=False
) # list per channel + average on last position
dice_dict = {}
for idx, class_dice in enumerate(per_class_dice):
if idx == len(per_class_dice) - 1:
self.tb_writer.add_scalar("Dice/Train Average", class_dice, GLOBAL_TRAIN_ITER)
else:
dice_dict["Train Class {}".format(idx)] = class_dice
self.tb_writer.add_scalar("Dice/Train Class {}".format(idx), class_dice, GLOBAL_TRAIN_ITER)
self.tb_writer.add_scalars("Dice Train/", dice_dict, GLOBAL_TRAIN_ITER)
timedelta_iter = timedelta(seconds=time.time() - start_time)
self.tb_writer.add_scalar("Time Delta/Train", timedelta_iter.seconds, GLOBAL_TRAIN_ITER)
epoch_5_way_division = int((int(train_dataset.__len__() / self.config.batch_size_sup)) / 5)
if epoch_5_way_division <= 0:
epoch_5_way_division = 3
if (iteration + 1) % epoch_5_way_division == 0:
if "unet_acs_with_cls" in self.config.model.lower():
print(
"Epoch [{}/{}], iteration {}, TRAINING Loss: {:.6f}, TRAINING Loss(SEG): {:.6f}, TRAINING Loss(CLS): {:.6f}".format(
self.epoch_sup_current + 1,
self.config.nb_epoch_sup,
iteration + 1,
np.average(self.stats.training_losses_sup),
np.average(self.stats.training_losses_sup_seg),
np.average(self.stats.training_losses_sup_cls),
)
)
else:
print(
"Epoch [{}/{}], iteration {}, Loss: {:.6f}".format(
self.epoch_sup_current + 1,
self.config.nb_epoch_sup,
iteration + 1,
np.average(self.stats.training_losses_sup),
)
)
sys.stdout.flush()
GLOBAL_TRAIN_ITER += 1
with torch.no_grad():
self.model.eval()
axis_view = None
for iteration, (x, y) in enumerate(val_data_loader):
start_time = time.time()
x, y = x.float().to(self.device), y.float().to(self.device)
y = make_1_hot_mask_for_dice(y)
pred = self.model(x)
if "unet_acs_with_cls" in self.config.model.lower():
pred_, x_cls, targets_cls = pred
x_cls, targets_cls = x_cls.to(self.device), targets_cls.to(self.device)
pred = pred_ # for segmentation
pr, rc, f1, accu = self.compute_precision_recall_f1(x_cls.cpu(), targets_cls.cpu())
self.stats.validation_precision.append(pr)
self.stats.validation_recall.append(rc)
self.stats.validation_f1.append(f1)
self.stats.validation_accuracy.append(accu)
if self.config.introduce_surrogate_at_epoch <= self.epoch_sup_current:
self.tb_writer.add_scalars(
"Classification Metrics/",
{
"Validation Precision": pr,
"Validation Recall": rc,
"Validation F1": f1,
"Validation Accuracy": accu,
},
GLOBAL_VAL_ITER,
)
else:
self.tb_writer.add_scalars(
"Classification Metrics PRE USE/",
{
"Validation Precision": pr,
"Validation Recall": rc,
"Validation F1": f1,
"Validation Accuracy": accu,
},
GLOBAL_VAL_ITER,
)
loss_cls = criterion_cls(x_cls, targets_cls)
loss_cls.to(self.device)
loss_cls *= self.config.surrogate_loss_weight
self.tb_writer.add_scalar("Loss/Validation CLS", loss_cls.item(), GLOBAL_VAL_ITER)
self.stats.validation_losses_sup_cls.append(loss_cls.item())
loss = criterion(pred, y)
if "unet_acs_with_cls" in self.config.model.lower():
self.tb_writer.add_scalar("Loss/Validation Segmentation", loss.item(), GLOBAL_VAL_ITER)
self.stats.validation_losses_sup_seg.append(loss.item())
if self.config.introduce_surrogate_at_epoch <= self.epoch_sup_current:
tmp_cls_loss = loss_cls.item()
else:
tmp_cls_loss = 0
self.tb_writer.add_scalars(
"Losses Validation/",
{"Segmentation": loss.item(), "CLS": tmp_cls_loss, "GLOBAL": loss.item() + loss_cls.item()},
GLOBAL_VAL_ITER,
)
# model stops based on segmentation perforamnce
self.stats.validation_losses_sup.append(loss.item())
if self.config.introduce_surrogate_at_epoch <= self.epoch_sup_current:
loss += loss_cls
self.tb_writer.add_scalar("Loss/Validation", loss.item(), GLOBAL_VAL_ITER)
if "unet_acs_with_cls" not in self.config.model.lower():
# was already appended
self.stats.validation_losses_sup.append(loss.item())
per_class_dice = DiceLoss.dice_loss(pred, y, per_class=True, return_loss=False)
dice_dict = {}
for idx, class_dice in enumerate(per_class_dice):
if idx == len(per_class_dice) - 1:
self.tb_writer.add_scalar("Dice/Validation Average", class_dice, GLOBAL_VAL_ITER)
else:
dice_dict["Validation Class {}".format(idx)] = class_dice
self.tb_writer.add_scalar("Dice/Validation Class {}".format(idx), class_dice, GLOBAL_VAL_ITER)
self.tb_writer.add_scalars("Dice Validation/", dice_dict, GLOBAL_VAL_ITER)
timedelta_iter = timedelta(seconds=time.time() - start_time)
self.tb_writer.add_scalar("Time Delta/Validation", timedelta_iter.seconds, GLOBAL_VAL_ITER)
GLOBAL_VAL_ITER += 1
with torch.no_grad():
self.model.eval()
for iteration, (x, y) in enumerate(test_data_loader):
start_time = time.time()
x, y = x.float().to(self.device), y.float().to(self.device)
y = make_1_hot_mask_for_dice(y)
pred = self.model(x)
if "unet_acs_with_cls" in self.config.model.lower():
pred_, x_cls, targets_cls = pred
x_cls, targets_cls = x_cls.to(self.device), targets_cls.to(self.device)
pred = pred_ # for segmentation
pr, rc, f1, accu = self.compute_precision_recall_f1(x_cls.cpu(), targets_cls.cpu())
self.stats.testing_precision.append(pr)
self.stats.testing_recall.append(rc)
self.stats.testing_f1.append(f1)
self.stats.testing_accuracy.append(accu)
if self.config.introduce_surrogate_at_epoch <= self.epoch_sup_current:
self.tb_writer.add_scalars(
"Classification Metrics/",
{
"Testing Precision": pr,
"Testing Recall": rc,
"Testing F1": f1,
"Testing Accuracy": accu,
},
GLOBAL_TEST_ITER,
)
else:
self.tb_writer.add_scalars(
"Classification Metrics PRE USE/",
{
"Testing Precision": pr,
"Testing Recall": rc,
"Testing F1": f1,
"Testing Accuracy": accu,
},
GLOBAL_TEST_ITER,
)
loss_cls = criterion_cls(x_cls, targets_cls)
loss_cls.to(self.device)
loss_cls *= self.config.surrogate_loss_weight
self.tb_writer.add_scalar("Loss/Testing CLS", loss_cls.item(), GLOBAL_TEST_ITER)
self.stats.testing_losses_sup_cls.append(loss_cls.item())
loss = criterion(pred, y)
if "unet_acs_with_cls" in self.config.model.lower():
self.tb_writer.add_scalar("Loss/Testing Segmentation", loss.item(), GLOBAL_TEST_ITER)
self.stats.testing_losses_sup_seg.append(loss.item())
if self.config.introduce_surrogate_at_epoch <= self.epoch_sup_current:
tmp_cls_loss = loss_cls.item()
else:
tmp_cls_loss = 0
self.tb_writer.add_scalars(
"Losses Testing/",
{"Segmentation": loss.item(), "CLS": tmp_cls_loss, "GLOBAL": loss.item() + loss_cls.item()},
GLOBAL_TEST_ITER,
)
# model stops based on segmentation perforamnce
self.stats.testing_losses_sup.append(loss.item())
if self.config.introduce_surrogate_at_epoch <= self.epoch_sup_current:
loss += loss_cls
self.tb_writer.add_scalar("Loss/Testing", loss.item(), GLOBAL_TEST_ITER)
if "unet_acs_with_cls" not in self.config.model.lower():
# was already appended
self.stats.testing_losses_sup.append(loss.item())
per_class_dice = DiceLoss.dice_loss(pred, y, per_class=True, return_loss=False)
dice_dict = {}
for idx, class_dice in enumerate(per_class_dice):
if idx == len(per_class_dice) - 1:
self.tb_writer.add_scalar("Dice/Testing Average", class_dice, GLOBAL_TEST_ITER)
else:
dice_dict["Test Class {}".format(idx)] = class_dice
self.tb_writer.add_scalar("Dice/Testing Class {}".format(idx), class_dice, GLOBAL_TEST_ITER)
self.tb_writer.add_scalars("Dice Testing/", dice_dict, GLOBAL_TEST_ITER)
timedelta_iter = timedelta(seconds=time.time() - start_time)
self.tb_writer.add_scalar("Time Delta/Testing", timedelta_iter.seconds, GLOBAL_TEST_ITER)
GLOBAL_TEST_ITER += 1
train_dataset.reset()
val_dataset.reset()
test_dataset.reset()
self.dataset.reset()
avg_training_loss_of_epoch = np.average(self.stats.training_losses_sup)
avg_validation_loss_of_epoch = np.average(self.stats.validation_losses_sup)
avg_testing_loss_of_epoch = np.average(self.stats.testing_losses_sup)
self.tb_writer.add_scalar("Avg Loss Epoch/Train ", avg_training_loss_of_epoch, self.epoch_sup_current + 1)
self.tb_writer.add_scalar("Avg Loss Epoch/Validation", avg_validation_loss_of_epoch, self.epoch_sup_current + 1)
self.tb_writer.add_scalar("Avg Loss Epoch/Testing", avg_testing_loss_of_epoch, self.epoch_sup_current + 1)
self.tb_writer.add_scalars(
"Avg Loss Epoch/",
{"train": avg_training_loss_of_epoch, "val": avg_validation_loss_of_epoch, "test": avg_testing_loss_of_epoch},
self.epoch_sup_current + 1,
)
self.stats.avg_training_loss_per_epoch_sup.append(avg_training_loss_of_epoch)
self.stats.avg_validation_loss_per_epoch_sup.append(avg_validation_loss_of_epoch)
self.stats.avg_testing_loss_per_epoch_sup.append(avg_testing_loss_of_epoch)
self.stats.iterations_sup.append(iteration)
if "unet_acs_with_cls" in self.config.model.lower():
avg_training_precision_of_epoch = np.average(self.stats.training_precision)
self.tb_writer.add_scalar(
"Avg Epoch Classification Metrics/Train Precision", avg_training_precision_of_epoch, self.epoch_sup_current + 1
| |
__title__ = "Code for resampling Geoscape building and surface cover data"
__version__ = "2022-28-01"
__author__ = "<NAME>"
__email__ = "<EMAIL>"
'''
Associated with the manuscript: A transformation in city-descriptive input data for urban climate models
Manuscript authors: <NAME>, <NAME>, <NAME>, <NAME>, <NAME>
Copyright 2022 <NAME>
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.
Instructions:
1. Get sample data from Geoscape: https://geoscape.com.au/get-sample/
2. Install necessary python dependancies
3. Update project and data paths as required
4. Run script
'''
import os
import numpy as np
import pandas as pd
import xarray as xr
import rioxarray as rxr
from rioxarray import merge
import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid1 import make_axes_locatable
import shapely
import geopandas as gpd
import cartopy.geodesic as cgeo
################################################################################
# user input
domain = 'sample'
output_v = 'v0.97'
projpath = f'.' # update path to working folder
datapath = f'{projpath}/data' # update path to geoscape data
outpath = f'{projpath}/outputs' # netcdf/tif outputs
plotpath = f'{projpath}/figures' # figures output
res_list = [30,100,300] # list of resolutions to process in m
split_by_grid = False # if true, splits buildings on grid edges (long processing)
plot_comp = True # if true, plots comparison between different resolutions (for sample)
missing_float = -999.
################################################################################
def main():
for res in res_list:
print(f'processing {res} m')
main_resample_cover(res)
main_calculate_morphology(res)
if plot_comp:
main_plot_sample()
return
def main_resample_cover(res):
'''main function for resampling geoscape surface cover data to a lower resolution and recategorise'''
print(f'opening {domain} geotif')
# read tif
tif_list = []
for tif_fpath in tif_fpaths:
tif_list.append(rxr.open_rasterio(tif_fpath))
print('merging tifs')
rorig = merge.merge_arrays(tif_list)
# get band 1
orig_ds = rorig.drop(['band']).squeeze()
# remove fill value
orig_ds = orig_ds.where(orig_ds!=orig_ds._FillValue)
################################################################################
print('creating downscaled geoscape dataset')
geoscape = create_dataset_from_geoscape(orig_ds,res)
################################################################################
print('saving geoscape dataset')
fname = f'{outpath}/{domain.capitalize()}_geoscape_surface_cover_{res}mx{res}m_{output_v}'
encoding = {var:{'zlib':True} for var in geoscape.data_vars}
geoscape.to_netcdf(f'{fname}.nc',format='NETCDF4', encoding=encoding)
geoscape = xr.open_dataset(f'{fname}.nc')
# geoscape.rio.write_crs("epsg:4326", inplace=True)
# geoscape.rio.to_raster(f'{fname}.tiff', compress='LZW')
################################################################################
derived = calc_derived_fractions(geoscape,res)
derived = set_attributes(derived,res)
print('saving derived surface cover')
fname = f'{outpath}/{domain.capitalize()}_derived_surface_cover_{res}mx{res}m_{output_v}'
compression = {'zlib':True}
encoding = {var:compression for var in derived.data_vars}
derived.to_netcdf(f'{fname}.nc',format='NETCDF4', encoding=encoding)
# derived.rio.write_crs("epsg:4326", inplace=True)
# derived.rio.to_raster(f'{fname}.tiff', compress='LZW')
################################################################################
assert_tests(geoscape,derived)
return
def calc_fraction(key,ds,res,long_name=None):
'''function to take categorical band and calculate its fraction at lower resolution'''
print(f'calculating {key} fraction at {res} m')
# get resolution factors
orig_res = ds.rio.resolution()[0]
sfactor = int(res/orig_res)
da = ds.where(ds == key)
# get all key values, convert to 1
tmp = da.copy()
tmp.values = np.where(da.values==key,1,np.nan)
# calculate sums over coarsened grid
tmp_sum = tmp.coarsen(x=sfactor,y=sfactor,boundary='pad').sum()
# get all non-nan values, convert to 1
tmp = da.copy()
tmp.values = np.where(np.isnan(ds).values,ds.values,1)
# calculate sums over coarsened grid
tmp_all = tmp.coarsen(x=sfactor,y=sfactor,boundary='pad').sum()
result = tmp_sum/tmp_all
result = result.rename(str(key))
result.attrs['long_name'] = long_name
result.encoding['_FillValue'] = missing_float
return result
def create_dataset_from_geoscape(orig_ds,res):
'''create netcdf attributes from geoscape surface cover data
# Table 2: SURFACE_COVER_2M_TYPE_AUT Codes from 'Surface Cover 1.6 Product Description.pdf'
2 Bare Earth Includes sand dunes, desert, rock outcrops, bare soil other than bare agricultural land, and sparsely vegetated areas of grass and shrub. Non-vegetated strip mines and quarries except where covered by development or water.
3 Road and Path Roads and parking lots covered in a man-made material excluding hard packed dirt trails.
4 Grass Grass and herbaceous areas. The category may include herbaceous wetlands if images are collected during dry season or periods of drought.
5 Trees All trees including deciduous and evergreen woody vegetation.
6 Unspecified Vegetation Any other vegetative material not included within the Grass or Tree class. This may include, but is not limited to, shrub, sc rub, agriculture, and aquatic plants.
7 Built-up Areas Any areas of man-made environments and infrastructure excluding road and paths and buildings.
8 Water Depending on the resolution quality of the imagery used, natural water will include streams, canals, ponds, lakes, reservoirs, estuaries and bays.
9 Buildings Where the majority of a pixel intersects a Building, vector building polygon representation.
10 Cloud The area covered with cloud on Date of collection.
11 Shadow The area covered with shadow on Date/time of collection.
12 Swimming Pool An area identified as a swimming pool.
'''
print('creating dataset')
ds = xr.Dataset({
'bare_earth': calc_fraction(2,orig_ds,res=res,
long_name= 'Bare earth: includes bare soil, sand, desert, rock outcrops'),
'road_path': calc_fraction(3,orig_ds,res=res,
long_name = 'Road and path: includes roads, parking lots and hard packed dirt trails'),
'grass': calc_fraction(4,orig_ds,res=res,
long_name = 'Grass and herbaceous areas'),
'trees': calc_fraction(5,orig_ds,res=res,
long_name = 'All trees including deciduous and evergreen'),
'other_veg': calc_fraction(6,orig_ds,res=res,
long_name = 'Other vegetation including shrub, scrub, agriculture and aquatic plants'),
'built_area': calc_fraction(7,orig_ds,res=res,
long_name = 'Human-made environments and infrastructure excluding road, paths and buildings'),
'water': calc_fraction(8,orig_ds,res=res,
long_name = 'Open water including streams, canals, lakes, reservoirs and bays'),
'buildings': calc_fraction(9,orig_ds,res=res,
long_name = 'Buildings'),
'cloud': calc_fraction(10,orig_ds,res=res,
long_name = 'Area covered with cloud at time of collection'),
'shadow': calc_fraction(11,orig_ds,res=res,
long_name = 'Area covered with shadow at time of collection'),
'swimming_pool': calc_fraction(12,orig_ds,res=res,
long_name = 'Swimming pool'),
})
ds.attrs['title'] = f'{domain.capitalize()} surface cover at {res}m resolution derived from 2m resolution GeoScape product'
ds.attrs['version'] = output_v
ds.attrs['authors'] = '<NAME> <<EMAIL>>'
ds.attrs['institution'] = 'ARC Centre of Excellence for Climate Extremes, UNSW Sydney, Australia'
ds.attrs['source'] = 'Geoscape Surface Cover v1.6. PSMA Australia, 2020. https://geoscape.com.au/'
ds.attrs['comment'] = 'The contents of this file are restricted, not to be used or distributed without permission from the authors.'
geoscape = ds.rio.reproject(dst_crs=4326)
geoscape = geoscape.rename({'y':'latitude','x':'longitude'}).drop('spatial_ref')
return geoscape
def calc_derived_fractions(ds,res):
'''create derived classes and attributes (normalising for cloud and shadow fractions)'''
derived = xr.Dataset()
derived['building_fraction'] = (ds['buildings'])/(1. - ds['cloud'] - ds['shadow'])
derived['tree_fraction'] = (ds['trees'])/(1. - ds['cloud'] - ds['shadow'])
derived['lowveg_fraction'] = (ds['grass'] + ds['other_veg'])/(1. - ds['cloud'] - ds['shadow'])
derived['bareearth_fraction'] = (ds['bare_earth'])/(1. - ds['cloud'] - ds['shadow'])
derived['roadpath_fraction'] = (ds['road_path'] + ds['built_area'])/(1. - ds['cloud'] - ds['shadow'])
derived['water_fraction'] = (ds['water'] + ds['swimming_pool'])/(1. - ds['cloud'] - ds['shadow'])
derived['total_built'] = (ds['road_path'] + ds['built_area'] + ds['buildings'])/(1. - ds['cloud'] - ds['shadow'])
derived['total_pervious'] = (ds['grass'] + ds['trees'] + ds['other_veg'] + ds['bare_earth'] + ds['water'] + ds['swimming_pool'])/(1. - ds['cloud'] - ds['shadow'])
return derived
def assert_tests(geoscape,derived):
'''test fractions sum to 1'''
# test geoscape classess sum to 1
total = np.full_like(geoscape.buildings.values,0)
for key in geoscape.keys():
total = total + geoscape[key]
np.testing.assert_allclose(total.to_series().dropna().values, 1, 1E-10)
# test derived classes sum to 1
total = np.full_like(derived.building_fraction.values,0)
for key in ['building_fraction','tree_fraction','lowveg_fraction','bareearth_fraction','roadpath_fraction','water_fraction']:
total = total + derived[key]
np.testing.assert_allclose(total.to_series().dropna().values, 1, 1E-10)
# test total classes sum to 1
total = np.full_like(derived.building_fraction.values,0)
for key in ['total_built','total_pervious']:
total = total + derived[key]
np.testing.assert_allclose(total.to_series().dropna().values, 1, 1E-10)
# test total classes sum to 1
total = np.full_like(derived.building_fraction.values,0)
for key in ['roadpath_fraction','total_pervious','building_fraction']:
total = total + derived[key]
np.testing.assert_allclose(total.to_series().dropna().values, 1, 1E-10)
return
################################################################################
def main_calculate_morphology(res):
'''main function for calculating grid-level morphology from geoscape building and tree data
split_by_grid=False: building morphology information placed at centroid point of building for faster processing
split_by_grid=True splits buildings at grid edges so morphology data sits in multiple cells'''
################################################################################
# format individual building information
print('reading building shapefile')
raw = gpd.read_file(shp_fname)
raw.columns= raw.columns.str.lower()
if domain == 'melbourne':
# drop buildings without height info
raw = raw.rename(columns={'vic_heig_4':'bld_hgt'})
raw = raw[raw.bld_hgt.notna()]
else:
print('calculating average of roof and eave height per building')
raw['bld_hgt'] = (raw['roof_hgt']+raw['eave_hgt'])/2
buildings = raw[['bld_pid','bld_hgt','geometry']]
print('creating grid from template')
fname = f'{outpath}/{domain.capitalize()}_geoscape_surface_cover_{res}mx{res}m_{output_v}.nc'
template = xr.open_dataset(fname)
cell = create_grid_from_template(template)
# split buildings where intersecting with grid (warning, very long processing)
if split_by_grid:
spg='_split'
# split buildings into cells by clipping
print('splitting geometry by grid')
total_list = []
for shape in cell.geometry:
bounds = gpd.GeoDataFrame(crs='EPSG:4283', geometry=[shape])
try:
total_list.append(gpd.clip(buildings,bounds))
except Exception:
pass
buildings = pd.concat(total_list)
else:
spg=''
print('calculating building area and centroid')
x,y = get_midpoint(buildings)
new_proj = buildings['geometry'].set_crs(epsg=4283).to_crs(f'+proj=cea +lat_0={y} +lon_0={x} +units=m')
buildings = buildings.assign(area=new_proj.area)
print('calculating perimeter per building')
buildings['perimeter'] = buildings.geometry.apply(get_perimeter)
print('calculating wall area per building')
buildings['wall_area'] = buildings['perimeter']*buildings['bld_hgt']
print('calculating frontal area per building')
x_frontal = buildings.apply(get_dist_x,axis=1)*buildings['bld_hgt']
y_frontal = buildings.apply(get_dist_y,axis=1)*buildings['bld_hgt']
buildings['avg_frontal'] = (x_frontal + y_frontal)/2
print('saving geometry as geopackage')
buildings.to_file(f'{projpath}/geopackages/buildings{spg}_{domain}.gpkg', driver='GPKG')
################################################################################
# create gridded data from buildings information
print('reading tree file')
tree_orig = rxr.open_rasterio(tree_fname,masked=True).squeeze(['band'],drop=True)
tree_orig = tree_orig.where(tree_orig>0)
print('creating grid | |
fom_matches_up["FOM"].apply(compute_nth)
inv_fom_total = inv_fom_series.sum()
# Calculate requests based on % value of 1/FOM
fom_reqs = inv_fom_series.apply(compute_weighted_share, args=(inv_fom_total, job_count))
fom_matches_up["ResourceRequests"] = fom_reqs
dbg_info.append(
f"{job_count} jobs requesting {req_cpus} cpus matching {len(matches)} entries (fom_up: {len(fom_matches_up)}): "
)
for _index, row in fom_matches_up.iterrows():
key = (row.get("CollectorHost"), row.get("Name"))
direct_match[key] = direct_match.get(key, 0) + job_count
fraction = row.get("ResourceRequests", 0)
prop_match[key] = prop_match.get(key, 0) + fraction
glidein_cpus = row.get("GLIDEIN_CPUS", 1)
prop_match_cpu[key] = math.ceil(
(prop_match_cpu.get(key, 0) + (fraction * req_cpus)) / glidein_cpus
)
hereonly_match[key] = hereonly_match.get(key, 0)
dbg_info.append(
f" entry i {len(matches)}: ({prop_match_cpu.get(key, 0)}, {(fraction * req_cpus) / glidein_cpus}, fr: {fraction}) {prop_match_cpu[key]}, {key} "
)
# Add stats for all entries in downtime or FOM == INFINITY
fom_matches_down = entries_with_cpus.query("GLIDEIN_In_Downtime==True")
fom_matches_inf = fom_matches.query(f"FOM=={sys.float_info.max:f}")
for rejected_matches in (fom_matches_down, fom_matches_inf):
for _index, row in rejected_matches.iterrows():
key = (row["CollectorHost"], row["Name"])
direct_match[key] = direct_match.get(key, 0)
hereonly_match[key] = hereonly_match.get(key, 0)
prop_match[key] = prop_match.get(key, 0)
total = job_types[job_type]["abs"]
# TODO: MMDB should be debug
# self.logger.info('\n'.join(dbg_info))
return (direct_match, prop_match, hereonly_match, prop_match_cpu, total)
def count_match_fom_dff(self, job_types, job_type, entries):
"""
Count the matches. This will use FOM for calculations to
count direct matches and proportionate matches and do depth first fill
"""
# TODO: This needs to be expanded to use more attrs and not just
# RequestCpus. Similar to glideFrontendLib.countMatch()
direct_match = {} # Number of direct job matches
prop_match = {} #
hereonly_match = {} # Jobs that can only run here
prop_match_cpu = {} # Total Cpus: prop_match * GLIDEIN_CPUS
jobs = job_types[job_type]["dataframe"]
if not jobs.empty:
# Get group of jobs based on request cpus
job_groups = jobs.groupby("RequestCpus")
for (req_cpus, job_group) in job_groups:
# Group jobs by matching criteria: RequestCpus for now
# We care about job counts for each group
job_count = len(job_group)
# Figure out which entries match this job group
# Figure out how may glideins to request based on the FOM
# Algorithm:
# 1. Fill the sites with lowest FOM first
# 2. If there are multiple sites with FOM split the request
# equally amongst them
matches = set()
for _index, row in entries.query(f"GLIDEIN_CPUS >= {req_cpus}").iterrows():
matches.add((row.get("CollectorHost"), row.get("Name")))
if len(matches) == 0:
# These jobs do not match anywhere. Special entry (None, None)
direct_match[(None, None)] = direct_match.get((None, None), 0) + job_count
prop_match[(None, None)] = prop_match.get((None, None), 0) + job_count
hereonly_match[(None, None)] = hereonly_match.get((None, None), 0) + job_count
prop_match_cpu[(None, None)] = prop_match_cpu.get((None, None), 0) + (job_count * req_cpus)
elif len(matches) == 1:
# These jobs can only run here
key = next(iter(matches))
direct_match[key] = direct_match.get(key, 0) + job_count
prop_match[key] = prop_match.get(key, 0) + job_count
this_entry = entries.query(f'Name=="{key[1]}"')
# glidein_cpus = 1 # default to 1 if not defined
glidein_cpus = this_entry.get("GLIDEIN_CPUS", 1)
prop_match_cpu[key] = math.ceil((prop_match_cpu.get(key, 0) + float(req_cpus)) / glidein_cpus)
else:
fom_matches = self.group_matches_by_fom(matches, entries)
# How many jobs have been considered so far
# Start with entries with lowest FOM and fill them first
job_count_matched = 0
for (_fom, fom_group_entries) in fom_matches:
job_count_unmatched = job_count - job_count_matched
if job_count_unmatched > 0:
# Distribute the jobs equally among this entry group
# TODO: Currently this will only consider first
# FOM group. Need to spill over to other groups
# by looking at the entries max capacity
# TODO: Check if we need to really go depth first
# or fill all FOM groups but in ratio of their
# FOMs
for key in matches:
this_entry_df = fom_group_entries.query(
f'(Name=="{key[1]}") and (GLIDEIN_In_Downtime != True)'
)
if len(this_entry_df) > 0:
if (job_count - job_count_matched) > 0:
direct_match[key] = direct_match.get(key, 0) + job_count
else:
# We already matched everything
# Just populate the stats
direct_match[key] = direct_match.get(key, 0)
prop_match[key] = prop_match.get(key, 0)
# hereonly_match remains same
hereonly_match[key] = hereonly_match.get(key, 0)
# Populate info for entries that are in downtime
# down_entries_df = fom_group_entries.query('(GLIDEIN_In_Downtime == True)')
else:
# Consider other FOM groups that also matched
# We already matched everything to other FOM groups
# Populate the stats as downtime doesnt mattter
for key in matches:
direct_match[key] = direct_match.get(key, 0)
hereonly_match[key] = hereonly_match.get(key, 0)
prop_match[key] = prop_match.get(key, 0)
# Add stats for all entries in downtime
# in case they are not considered above
fom_group_entries_down = fom_group_entries.query("(GLIDEIN_In_Downtime == True)")
for _index, row in fom_group_entries_down.iterrows():
key = (row["CollectorHost"], row["Name"])
direct_match[key] = direct_match.get(key, 0)
hereonly_match[key] = hereonly_match.get(key, 0)
prop_match[key] = prop_match.get(key, 0)
# self.logger.info('---------- count_match return keys ----------')
# self.logger.info('---------- count_match return keys ----------')
total = job_types[job_type]["abs"]
return (direct_match, prop_match, hereonly_match, prop_match_cpu, total)
def matches_with_fom(self, matches, entries):
"""
Given the entries and matches, return matches with entire entry
classad and FOM series added to the df
"""
# self.logger.info('---------- %s ----------' % 'group_matches_by_fom')
# ASSUMTION: Entry names are unique
# Get all the classad names for the entries from the matches
entry_classad_names = [x[1] for x in matches]
df1 = pandas.DataFrame({"Name": entry_classad_names})
# Get the intersection of rows with column 'Name'
matches_df = pandas.merge(entries, df1, on=["Name"], how="inner")
# Get the intersection of matches_df and fom_entries
# Following will give all the matches with entire entry classad and FOM
return pandas.merge(self.fom_entries, matches_df, on=["EntryName"], how="inner")
def group_matches_by_fom(self, matches, entries):
"""
Given the entries and matches, group entries by their respective FOM
Return a dataframe groupby object with FOM and entries dataframe with
that FOM sorted by the FOM
"""
return self.matches_matches_with_fom(matches, entries).groupby(["FOM"])
###############################################################################
# Common functions
# TODO: Move them to a common library outside this module
###############################################################################
def count_total_cores(slots):
"""
Counts total cores in the nondynamic slots dataframe
"""
count = 0
if not slots.empty:
# TotalSlotCpus should always be the correct number but
# is not defined pre partitionable slots
count = slots.loc[slots["SlotType"] == "Partitionable", "TotalSlotCpus"].sum()
count += slots.loc[slots["SlotType"] != "Partitionable", "Cpus"].sum()
return count
def count_idle_cores(slots):
"""
Counts cores in the idle slots dataframe
"""
count = 0
if not slots.empty:
count = slots["Cpus"].sum()
return count
def count_running_cores(slots):
"""
Counts cores in the running slots dataframe
"""
count = 0
if not slots.empty:
count = slots.loc[slots["SlotType"] != "Partitionable", "Cpus"].sum()
return count
def get_vo_entries(vo, all_entries):
"""
Get the list of entries where the given VO is allowed
"""
entries = pandas.DataFrame()
for _index, row in all_entries.iterrows():
allowed_vos = row.get("GLIDEIN_Supported_VOs")
if pandas.notnull(allowed_vos):
allowed_vo_list = [i.strip() for i in allowed_vos.split(",")]
if vo in allowed_vo_list:
entries = entries.append(row)
return entries
def create_credential_list(credentials, group_descript, logger):
"""
Create a list of Credential objects from the credentials
configured in the frontend
"""
credential_list = []
for num, cred in enumerate(credentials):
credential_list.append(Credential(num, cred, group_descript, logger))
return credential_list
def append_running_on(jobs, slots, logger):
"""
For every running job add the RunningOn info to the jobs dataframe
"""
# TODO: Is there a better way to do this in pandas?
ro_list = []
for _index, job in jobs.iterrows():
ro = "UNKNOWN"
remote_host = job.get("RemoteHost")
if pandas.notnull(remote_host):
matching_slots = slots.query(f'Name == "{remote_host}"')
if len(matching_slots) > 1:
logger.info(f"ERROR: Multiple slots {matching_slots['Name'].tolist()} running same job found")
elif len(matching_slots) == 1:
# TODO: Find a better way to do this through pandas
schedd = matching_slots.get("GLIDEIN_Schedd").tolist()[0].split("@")
factory_pool = schedd[-1].split(":")[0]
entry_name = matching_slots.get("GLIDEIN_ENTRY_NAME").tolist()[0]
glidein_name = matching_slots.get("GLIDEIN_Name").tolist()[0]
factory_name = matching_slots.get("GLIDEIN_Factory").tolist()[0]
# factory_pool = matching_slots.get('CollectorHost').tolist()[0]
ro = f"{entry_name}@{glidein_name}@{factory_name}@{factory_pool}"
else:
# len(matching_slots) == 0
# NOTE: A job may be in final stages or maybe its not updated
# while the slot goes away. In that case
# len(matching_slots) will be 0. Just ignore it.
pass
ro_list.append(ro)
# TODO: Getting warning: SettingWithCopyWarning:
# A value is trying to be set on a copy of a slice from a DataFrame.
# Try using .loc[row_indexer,col_indexer] = value instead
# From https://stackoverflow.com/questions/20625582/how-to-deal-with-settingwithcopywarning-in-pandas
# For this use case you want to add RunningOn to the original dataframe
# pd.options.mode.chained_assignment = None # default='warn'
jobs["RunningOn"] = ro_list
def log_and_sum_factory_line(factory, is_down, factory_stat_arr, old_factory_stat_arr, logger, fom="-"):
"""
Will log the factory_stat_arr (tuple composed of 17 numbers)
and return a sum of factory_stat_arr+old_factory_stat_arr
"""
# if numbers are too big, reduce them to either k or M for presentation
form_arr = []
for i in factory_stat_arr:
if i < 100000:
form_arr.append("%5i" % i)
| |
'False'
else: return 'True'
elif obj[11]<=1:
# {"feature": "Bar", "instances": 30, "metric_value": 0.3367, "depth": 8}
if obj[7]>0.0:
# {"feature": "Restaurant20to50", "instances": 20, "metric_value": 0.2278, "depth": 9}
if obj[9]>0.0:
# {"feature": "Time", "instances": 18, "metric_value": 0.188, "depth": 10}
if obj[1]<=2:
# {"feature": "Gender", "instances": 13, "metric_value": 0.2601, "depth": 11}
if obj[3]<=0:
# {"feature": "Direction_same", "instances": 7, "metric_value": 0.2449, "depth": 12}
if obj[10]<=0:
return 'True'
else: return 'True'
elif obj[3]>0:
# {"feature": "Direction_same", "instances": 6, "metric_value": 0.2778, "depth": 12}
if obj[10]<=0:
return 'True'
else: return 'True'
else: return 'True'
elif obj[1]>2:
return 'True'
else: return 'True'
elif obj[9]<=0.0:
# {"feature": "Time", "instances": 2, "metric_value": 0.0, "depth": 10}
if obj[1]<=0:
return 'False'
elif obj[1]>0:
return 'True'
else: return 'True'
else: return 'False'
elif obj[7]<=0.0:
# {"feature": "Time", "instances": 10, "metric_value": 0.4444, "depth": 9}
if obj[1]>0:
# {"feature": "Restaurant20to50", "instances": 9, "metric_value": 0.4167, "depth": 10}
if obj[9]<=1.0:
# {"feature": "Gender", "instances": 8, "metric_value": 0.4286, "depth": 11}
if obj[3]>0:
# {"feature": "Direction_same", "instances": 7, "metric_value": 0.4898, "depth": 12}
if obj[10]<=0:
return 'True'
else: return 'True'
elif obj[3]<=0:
return 'True'
else: return 'True'
elif obj[9]>1.0:
return 'False'
else: return 'False'
elif obj[1]<=0:
return 'False'
else: return 'False'
else: return 'False'
else: return 'True'
elif obj[5]>3:
return 'True'
else: return 'True'
else: return 'True'
else: return 'True'
else: return 'True'
elif obj[8]>1.0:
# {"feature": "Distance", "instances": 2885, "metric_value": 0.412, "depth": 3}
if obj[11]<=2:
# {"feature": "Passanger", "instances": 2614, "metric_value": 0.4001, "depth": 4}
if obj[0]<=2:
# {"feature": "Occupation", "instances": 1699, "metric_value": 0.4228, "depth": 5}
if obj[6]<=18.185882392956827:
# {"feature": "Direction_same", "instances": 1580, "metric_value": 0.4321, "depth": 6}
if obj[10]<=0:
# {"feature": "Time", "instances": 1024, "metric_value": 0.4381, "depth": 7}
if obj[1]>1:
# {"feature": "Age", "instances": 553, "metric_value": 0.3955, "depth": 8}
if obj[4]>0:
# {"feature": "Bar", "instances": 472, "metric_value": 0.3798, "depth": 9}
if obj[7]<=1.0:
# {"feature": "Gender", "instances": 289, "metric_value": 0.3396, "depth": 10}
if obj[3]>0:
# {"feature": "Restaurant20to50", "instances": 171, "metric_value": 0.4008, "depth": 11}
if obj[9]<=2.0:
# {"feature": "Education", "instances": 153, "metric_value": 0.4132, "depth": 12}
if obj[5]>1:
return 'True'
elif obj[5]<=1:
return 'True'
else: return 'True'
elif obj[9]>2.0:
# {"feature": "Education", "instances": 18, "metric_value": 0.2708, "depth": 12}
if obj[5]<=2:
return 'True'
elif obj[5]>2:
return 'True'
else: return 'True'
else: return 'True'
elif obj[3]<=0:
# {"feature": "Education", "instances": 118, "metric_value": 0.2441, "depth": 11}
if obj[5]<=2:
# {"feature": "Restaurant20to50", "instances": 92, "metric_value": 0.2644, "depth": 12}
if obj[9]>0.0:
return 'True'
elif obj[9]<=0.0:
return 'True'
else: return 'True'
elif obj[5]>2:
# {"feature": "Restaurant20to50", "instances": 26, "metric_value": 0.1377, "depth": 12}
if obj[9]>0.0:
return 'True'
elif obj[9]<=0.0:
return 'True'
else: return 'True'
else: return 'True'
else: return 'True'
elif obj[7]>1.0:
# {"feature": "Education", "instances": 183, "metric_value": 0.4199, "depth": 10}
if obj[5]>1:
# {"feature": "Restaurant20to50", "instances": 136, "metric_value": 0.3896, "depth": 11}
if obj[9]<=3.0:
# {"feature": "Gender", "instances": 128, "metric_value": 0.3803, "depth": 12}
if obj[3]<=0:
return 'True'
elif obj[3]>0:
return 'True'
else: return 'True'
elif obj[9]>3.0:
# {"feature": "Gender", "instances": 8, "metric_value": 0.4667, "depth": 12}
if obj[3]<=0:
return 'False'
elif obj[3]>0:
return 'True'
else: return 'True'
else: return 'True'
elif obj[5]<=1:
# {"feature": "Gender", "instances": 47, "metric_value": 0.466, "depth": 11}
if obj[3]<=0:
# {"feature": "Restaurant20to50", "instances": 27, "metric_value": 0.4103, "depth": 12}
if obj[9]>0.0:
return 'True'
elif obj[9]<=0.0:
return 'False'
else: return 'False'
elif obj[3]>0:
# {"feature": "Restaurant20to50", "instances": 20, "metric_value": 0.4917, "depth": 12}
if obj[9]<=1.0:
return 'False'
elif obj[9]>1.0:
return 'False'
else: return 'False'
else: return 'False'
else: return 'True'
else: return 'True'
elif obj[4]<=0:
# {"feature": "Education", "instances": 81, "metric_value": 0.4418, "depth": 9}
if obj[5]<=3:
# {"feature": "Bar", "instances": 70, "metric_value": 0.4695, "depth": 10}
if obj[7]>0.0:
# {"feature": "Restaurant20to50", "instances": 48, "metric_value": 0.4407, "depth": 11}
if obj[9]<=3.0:
# {"feature": "Gender", "instances": 45, "metric_value": 0.4567, "depth": 12}
if obj[3]>0:
return 'True'
elif obj[3]<=0:
return 'True'
else: return 'True'
elif obj[9]>3.0:
return 'True'
else: return 'True'
elif obj[7]<=0.0:
# {"feature": "Restaurant20to50", "instances": 22, "metric_value": 0.3326, "depth": 11}
if obj[9]<=1.0:
# {"feature": "Gender", "instances": 13, "metric_value": 0.4256, "depth": 12}
if obj[3]>0:
return 'True'
elif obj[3]<=0:
return 'True'
else: return 'True'
elif obj[9]>1.0:
# {"feature": "Gender", "instances": 9, "metric_value": 0.1975, "depth": 12}
if obj[3]<=1:
return 'False'
else: return 'False'
else: return 'False'
else: return 'False'
elif obj[5]>3:
# {"feature": "Gender", "instances": 11, "metric_value": 0.1364, "depth": 10}
if obj[3]>0:
return 'True'
elif obj[3]<=0:
# {"feature": "Bar", "instances": 4, "metric_value": 0.375, "depth": 11}
if obj[7]<=0.0:
# {"feature": "Restaurant20to50", "instances": 4, "metric_value": 0.375, "depth": 12}
if obj[9]<=1.0:
return 'True'
else: return 'True'
else: return 'True'
else: return 'True'
else: return 'True'
else: return 'True'
elif obj[1]<=1:
# {"feature": "Bar", "instances": 471, "metric_value": 0.4804, "depth": 8}
if obj[7]>0.0:
# {"feature": "Education", "instances": 331, "metric_value": 0.489, "depth": 9}
if obj[5]<=3:
# {"feature": "Restaurant20to50", "instances": 309, "metric_value": 0.4916, "depth": 10}
if obj[9]>-1.0:
# {"feature": "Age", "instances": 306, "metric_value": 0.493, "depth": 11}
if obj[4]>0:
# {"feature": "Gender", "instances": 273, "metric_value": 0.4934, "depth": 12}
if obj[3]>0:
return 'True'
elif obj[3]<=0:
return 'True'
else: return 'True'
elif obj[4]<=0:
# {"feature": "Gender", "instances": 33, "metric_value": 0.484, "depth": 12}
if obj[3]>0:
return 'False'
elif obj[3]<=0:
return 'False'
else: return 'False'
else: return 'False'
elif obj[9]<=-1.0:
return 'True'
else: return 'True'
elif obj[5]>3:
# {"feature": "Age", "instances": 22, "metric_value": 0.3732, "depth": 10}
if obj[4]<=3:
# {"feature": "Restaurant20to50", "instances": 19, "metric_value": 0.4316, "depth": 11}
if obj[9]>3.0:
# {"feature": "Gender", "instances": 10, "metric_value": 0.42, "depth": 12}
if obj[3]<=0:
return 'True'
else: return 'True'
elif obj[9]<=3.0:
# {"feature": "Gender", "instances": 9, "metric_value": 0.4444, "depth": 12}
if obj[3]<=0:
return 'True'
elif obj[3]>0:
return 'True'
else: return 'True'
else: return 'True'
elif obj[4]>3:
return 'True'
else: return 'True'
else: return 'True'
elif obj[7]<=0.0:
# {"feature": "Age", "instances": 140, "metric_value": 0.4392, "depth": 9}
if obj[4]>2:
# {"feature": "Gender", "instances": 81, "metric_value": 0.4694, "depth": 10}
if obj[3]>0:
# {"feature": "Education", "instances": 52, "metric_value": 0.4414, "depth": 11}
if obj[5]<=2:
# {"feature": "Restaurant20to50", "instances": 42, "metric_value": 0.4179, "depth": 12}
if obj[9]>-1.0:
return 'True'
elif obj[9]<=-1.0:
return 'True'
else: return 'True'
elif obj[5]>2:
# {"feature": "Restaurant20to50", "instances": 10, "metric_value": 0.48, "depth": 12}
if obj[9]>1.0:
return 'False'
elif obj[9]<=1.0:
return 'True'
else: return 'True'
else: return 'True'
elif obj[3]<=0:
# {"feature": "Education", "instances": 29, "metric_value": 0.4803, "depth": 11}
if obj[5]<=3:
# {"feature": "Restaurant20to50", "instances": 28, "metric_value": 0.4671, "depth": 12}
if obj[9]>0.0:
return 'True'
elif obj[9]<=0.0:
return 'False'
else: return 'False'
elif obj[5]>3:
return 'True'
else: return 'True'
else: return 'False'
elif obj[4]<=2:
# {"feature": "Restaurant20to50", "instances": 59, "metric_value": 0.361, "depth": 10}
if obj[9]<=2.0:
# {"feature": "Education", "instances": 56, "metric_value": 0.3497, "depth": 11}
if obj[5]<=3:
# {"feature": "Gender", "instances": 48, "metric_value": 0.3296, "depth": 12}
if obj[3]>0:
return 'True'
elif obj[3]<=0:
return 'True'
else: return 'True'
elif obj[5]>3:
# {"feature": "Gender", "instances": 8, "metric_value": 0.3571, "depth": 12}
if obj[3]>0:
return 'True'
elif obj[3]<=0:
return 'False'
else: return 'False'
else: return 'True'
elif obj[9]>2.0:
# {"feature": "Gender", "instances": 3, "metric_value": 0.0, "depth": 11}
if obj[3]>0:
return 'False'
elif obj[3]<=0:
return 'True'
else: return 'True'
else: return 'False'
else: return 'True'
else: return 'True'
else: return 'True'
elif obj[10]>0:
# {"feature": "Time", "instances": 556, "metric_value": 0.3922, "depth": 7}
if obj[1]<=1:
# {"feature": "Education", "instances": 451, "metric_value": 0.3659, "depth": 8}
if obj[5]>1:
# {"feature": "Restaurant20to50", "instances": 273, "metric_value": 0.3959, "depth": 9}
if obj[9]<=1.0:
# {"feature": "Age", "instances": 157, "metric_value": 0.4229, "depth": 10}
if obj[4]>1:
# {"feature": "Bar", "instances": 105, "metric_value": 0.402, "depth": 11}
if obj[7]<=2.0:
# {"feature": "Gender", "instances": 88, "metric_value": 0.3856, "depth": 12}
if obj[3]>0:
return 'True'
elif obj[3]<=0:
return 'True'
else: return 'True'
elif obj[7]>2.0:
# {"feature": "Gender", "instances": 17, "metric_value": 0.4706, "depth": 12}
if obj[3]<=0:
return 'True'
elif obj[3]>0:
return 'True'
else: return 'True'
else: return 'True'
elif obj[4]<=1:
# {"feature": "Bar", "instances": 52, "metric_value": 0.4354, "depth": 11}
if obj[7]>0.0:
# {"feature": "Gender", "instances": 30, "metric_value": 0.3873, "depth": 12}
if obj[3]<=0:
return 'True'
elif obj[3]>0:
return 'True'
else: return 'True'
elif obj[7]<=0.0:
# {"feature": "Gender", "instances": 22, "metric_value": 0.4935, "depth": 12}
if obj[3]>0:
return 'True'
elif obj[3]<=0:
return 'True'
else: return 'True'
else: return 'True'
else: return 'True'
elif obj[9]>1.0:
# {"feature": "Bar", "instances": 116, "metric_value": 0.3455, "depth": 10}
if obj[7]>0.0:
# {"feature": "Age", "instances": 96, "metric_value": 0.3124, "depth": 11}
if obj[4]<=4:
# {"feature": "Gender", "instances": 76, "metric_value": 0.3463, "depth": 12}
if obj[3]>0:
return 'True'
elif obj[3]<=0:
return 'True'
else: return 'True'
elif obj[4]>4:
# {"feature": "Gender", "instances": 20, "metric_value": 0.1667, "depth": 12}
if obj[3]<=0:
return 'True'
elif obj[3]>0:
return 'True'
else: return 'True'
else: return 'True'
elif obj[7]<=0.0:
# {"feature": "Age", "instances": 20, "metric_value": 0.4484, "depth": 11}
if obj[4]<=4:
# {"feature": "Gender", "instances": 13, "metric_value": 0.4126, "depth": 12}
if obj[3]>0:
return 'True'
elif obj[3]<=0:
return 'True'
else: return 'True'
elif obj[4]>4:
# {"feature": "Gender", "instances": 7, "metric_value": 0.4898, "depth": 12}
if obj[3]<=1:
return 'False'
else: return 'False'
else: return 'False'
else: return 'True'
else: return 'True'
elif obj[5]<=1:
# {"feature": "Age", "instances": 178, "metric_value": 0.3119, "depth": 9}
if obj[4]>0:
# {"feature": "Bar", "instances": 161, "metric_value": 0.3267, "depth": 10}
if obj[7]<=3.0:
# {"feature": "Restaurant20to50", "instances": 155, "metric_value": 0.3162, "depth": 11}
if obj[9]>0.0:
# {"feature": "Gender", "instances": 132, "metric_value": 0.2974, "depth": 12}
if obj[3]>0:
return 'True'
elif obj[3]<=0:
return 'True'
else: return 'True'
elif obj[9]<=0.0:
# {"feature": "Gender", "instances": 23, "metric_value": 0.4099, "depth": 12}
if obj[3]<=0:
return 'True'
elif obj[3]>0:
return 'True'
else: return 'True'
else: return 'True'
elif obj[7]>3.0:
# {"feature": "Restaurant20to50", "instances": 6, "metric_value": 0.25, "depth": 11}
if obj[9]<=1.0:
# {"feature": "Gender", "instances": 4, "metric_value": 0.3333, "depth": 12}
if obj[3]>0:
return 'True'
elif obj[3]<=0:
return 'True'
else: return 'True'
elif obj[9]>1.0:
return 'False'
else: return 'False'
else: return 'False'
elif obj[4]<=0:
# {"feature": "Gender", "instances": 17, "metric_value": 0.0882, "depth": 10}
if obj[3]>0:
return 'True'
elif obj[3]<=0:
# {"feature": "Bar", "instances": 4, "metric_value": 0.25, "depth": 11}
if obj[7]<=2.0:
# {"feature": "Restaurant20to50", "instances": 2, "metric_value": 0.0, "depth": 12}
if obj[9]<=1.0:
return 'False'
elif obj[9]>1.0:
return 'True'
else: return 'True'
elif obj[7]>2.0:
return 'True'
else: return 'True'
else: return 'True'
else: return 'True'
else: return 'True'
elif obj[1]>1:
# {"feature": "Restaurant20to50", "instances": 105, "metric_value": 0.4749, "depth": 8}
if obj[9]<=2.0:
# {"feature": "Education", "instances": 90, "metric_value": 0.4651, "depth": 9}
if obj[5]<=3:
# {"feature": "Age", "instances": 86, "metric_value": 0.4826, "depth": 10}
if obj[4]<=6:
# {"feature": "Gender", "instances": 85, "metric_value": 0.4841, "depth": 11}
if obj[3]<=0:
# {"feature": "Bar", "instances": 45, "metric_value": 0.4876, "depth": 12}
if obj[7]>0.0:
return 'True'
elif obj[7]<=0.0:
return 'False'
else: return 'False'
elif obj[3]>0:
# {"feature": "Bar", "instances": 40, "metric_value": 0.4632, "depth": 12}
if obj[7]<=2.0:
return 'True'
elif obj[7]>2.0:
return 'True'
else: return 'True'
else: return 'True'
elif obj[4]>6:
return 'True'
else: return 'True'
elif obj[5]>3:
return 'True'
else: return 'True'
elif obj[9]>2.0:
# {"feature": "Bar", "instances": 15, "metric_value": 0.3636, "depth": 9}
if obj[7]>1.0:
# {"feature": "Age", "instances": 11, "metric_value": 0.2727, "depth": 10}
if obj[4]<=1:
# {"feature": "Education", "instances": 8, "metric_value": 0.3, "depth": 11}
if obj[5]<=2:
# {"feature": "Gender", "instances": 5, "metric_value": 0.4, "depth": 12}
if | |
from problem2 import *
import numpy as np
import sys
from sklearn.datasets import make_classification
'''
Unit test 2:
This file includes unit tests for problem2.py.
You could test the correctness of your code by typing `nosetests -v test2.py` in the terminal.
'''
#-------------------------------------------------------------------------
def test_python_version():
''' ----------- Problem 2 (50 points in total)--------------'''
assert sys.version_info[0]==3 # require python 3
#-------------------------------------------------------------------------
def test_compute_z1():
'''(2 point) compute_z1'''
x = np.mat('1.; 2.; 3.')
W1 = np.mat([[0.5,-0.6,0.3],
[0.6,-0.5,0.2]])
b1 = np.mat('0.2; 0.3')
z1 = compute_z1(x,W1,b1)
assert type(z1) == np.matrixlib.defmatrix.matrix
assert z1.shape == (2,1)
assert np.allclose(z1, np.mat([0.4,0.5]).T, atol = 1e-3)
x = np.mat([2., 5.,2.]).T
z1 = compute_z1(x,W1,b1)
assert np.allclose(z1.T, [-1.2,-0.6], atol = 1e-3)
#-------------------------------------------------------------------------
def test_compute_a1():
'''(3 point) compute_a1'''
z1 = np.mat([0.,1.]).T
a1 = compute_a1(z1)
assert type(a1) == np.matrixlib.defmatrix.matrix
assert a1.shape == (2,1)
assert np.allclose(a1.T, [0.5,0.731], atol = 1e-3)
z1 = np.mat([-1.,-100., 100]).T
a1 = compute_a1(z1)
assert a1.shape == (3,1)
assert np.allclose(a1.T, [0.2689, 0, 1], atol = 1e-2)
np.seterr(all='raise')
z1 = np.mat([1000., 1000.]).T
a1 = compute_a1(z1)
assert np.allclose(a1.T, [1., 1.], atol = 1e-2)
assert np.allclose(z1.T, [1000, 1000])
z1 = np.mat([-1000., -1000.]).T
a1 = compute_a1(z1)
assert np.allclose(a1.T, [0., 0.], atol = 1e-2)
assert np.allclose(z1.T, [-1000, -1000])
a1 = compute_a1(np.mat([1000., 100.]).T)
assert np.allclose(a1.T, [1., 1.], atol = 1e-2)
a = compute_a1(np.mat([-1000., -10.]).T)
assert np.allclose(a.T, [0., 0.], atol = 1e-2)
#-------------------------------------------------------------------------
def test_compute_z2():
'''(2 point) compute_z2'''
x = np.mat([1., 2., 3.]).T
W2 = np.mat([[0.5,-0.6,0.3],
[0.6,-0.5,0.2]])
b2 = np.mat([0.2, 0.3]).T
z2 = compute_z2(x,W2,b2)
assert type(z2) == np.matrixlib.defmatrix.matrix
assert z2.shape == (2,1)
assert np.allclose(z2.T, [0.4,0.5], atol = 1e-3)
x = np.mat([2., 5.,2.]).T
z2 = compute_z2(x,W2,b2)
assert np.allclose(z2.T, [-1.2,-0.6], atol = 1e-3)
#-------------------------------------------------------------------------
def test_compute_a2():
'''(3 point) compute_a2'''
z = np.mat([1., 1.]).T
a = compute_a2(z)
assert type(a) == np.matrixlib.defmatrix.matrix
assert np.allclose(a.T, [0.5, 0.5], atol = 1e-2)
assert np.allclose(z.T, [1., 1.])
a = compute_a2(np.mat([1., 1.,1., 1.]).T)
assert np.allclose(a.T, [0.25, 0.25, 0.25, 0.25], atol = 1e-2)
a = compute_a2(np.mat([-1., -1.,-1., -1.]).T)
assert np.allclose(a.T, [0.25, 0.25, 0.25, 0.25], atol = 1e-2)
a = compute_a2(np.mat([-2., -1.,1., 2.]).T)
assert np.allclose(a.T, [ 0.01275478,0.03467109,0.25618664,0.69638749], atol = 1e-2)
a = compute_a2(np.mat([100., 100.]).T)
assert np.allclose(a.T, [0.5, 0.5], atol = 1e-2)
a = compute_a2(np.mat([-100., -100.]).T)
assert np.allclose(a.T, [0.5, 0.5], atol = 1e-2)
np.seterr(all='raise')
z = np.mat([1000., 1000.]).T
a = compute_a2(z)
assert np.allclose(a.T, [0.5, 0.5], atol = 1e-2)
assert np.allclose(z.T, [1000, 1000])
z = np.mat([-1000., -1000.]).T
a = compute_a2(z)
assert np.allclose(a.T, [0.5, 0.5], atol = 1e-2)
assert np.allclose(z.T, [-1000, -1000])
a = compute_a2(np.mat([1000., 10.]).T)
assert np.allclose(a.T, [1., 0.], atol = 1e-2)
a = compute_a2(np.mat([-1000., -10.]).T)
assert np.allclose(a.T, [0., 1.], atol = 1e-2)
#-------------------------------------------------------------------------
def test_forward():
'''(2 point) forward'''
x = np.mat([1., 2.,3.,4]).T
# first layer with 3 neurons
W1 = np.mat([[0.,0.,0.,0.],
[0.,0.,0.,0.],
[0.,0.,0.,0.]])
b1 = np.mat([0.,0.,0.]).T
# second layer with 2 neurons
W2 = np.mat([[0.,0.,0.],
[0.,0.,0.]])
b2 = np.mat([100.,0.]).T
z1, a1, z2, a2 = forward(x,W1,b1,W2,b2)
assert type(z1) == np.matrixlib.defmatrix.matrix
assert type(a1) == np.matrixlib.defmatrix.matrix
assert z1.shape == (3,1)
assert a1.shape == (3,1)
assert type(z2) == np.matrixlib.defmatrix.matrix
assert type(a2) == np.matrixlib.defmatrix.matrix
assert z2.shape == (2,1)
assert a2.shape == (2,1)
assert np.allclose(z1.T, [0,0,0], atol = 1e-3)
assert np.allclose(a1.T, [0.5,0.5,0.5], atol = 1e-3)
assert np.allclose(z2.T, [100,0], atol = 1e-3)
assert np.allclose(a2.T, [1,0], atol = 1e-3)
#-------------------------------------------------------------------------
def test_compute_dL_da2():
'''(2 point) compute_dL_da2'''
a = np.mat([0.5,0.5]).T
y = 1
dL_da = compute_dL_da2(a,y)
assert type(dL_da) == np.matrixlib.defmatrix.matrix
assert dL_da.shape == (2,1)
assert np.allclose(dL_da.T, [0.,-2.], atol= 1e-3)
a = np.mat([0.5,0.5]).T
y = 0
dL_da = compute_dL_da2(a,y)
assert np.allclose(dL_da.T, [-2.,0.], atol= 1e-3)
a = np.mat([0.1,0.6,0.1,0.2]).T
y = 3
dL_da = compute_dL_da2(a,y)
assert np.allclose(dL_da.T, [0.,0.,0.,-5.], atol= 1e-3)
a = np.mat([1.,0.]).T
y = 1
dL_da = compute_dL_da2(a,y)
np.seterr(all='raise')
assert np.allclose(dL_da[0], 0., atol= 1e-3)
assert dL_da[1] < -1e5
assert dL_da[1] > -float('Inf')
assert np.allclose(a.T, [1.,0.])
#-------------------------------------------------------------------------
def test_compute_da2_dz2():
'''(2 point) compute_da2_dz2'''
a = np.mat([0.3, 0.7]).T
da_dz = compute_da2_dz2(a)
assert type(da_dz) == np.matrixlib.defmatrix.matrix
assert da_dz.shape == (2,2)
assert np.allclose(da_dz, [[.21,-.21],[-.21,.21]], atol= 1e-3)
a = np.mat([0.1, 0.2, 0.7]).T
da_dz = compute_da2_dz2(a)
assert da_dz.shape == (3,3)
da_dz_true = np.mat( [[ 0.09, -0.02, -0.07],
[-0.02, 0.16, -0.14],
[-0.07, -0.14, 0.21]])
assert np.allclose(da_dz,da_dz_true,atol= 1e-3)
#-------------------------------------------------------------------------
def test_compute_dz2_dW2():
'''(2 point) compute_dz2_dW2'''
x = np.mat([1., 2.,3.]).T
dz_dW = compute_dz2_dW2(x,2)
assert type(dz_dW) == np.matrixlib.defmatrix.matrix
assert dz_dW.shape == (2,3)
dz_dW_true = np.mat([[1., 2.,3],[1., 2.,3]])
assert np.allclose(dz_dW, dz_dW_true, atol=1e-2)
#-------------------------------------------------------------------------
def test_compute_dz2_db2():
'''(2 point) compute_dz2_db2'''
dz_db = compute_dz2_db2(2)
assert type(dz_db) == np.matrixlib.defmatrix.matrix
assert dz_db.shape == (2,1)
dz_db_true = np.mat([1.,1.])
assert np.allclose(dz_db, dz_db_true, atol=1e-2)
#-------------------------------------------------------------------------
def test_compute_dz2_da1():
'''(2 point) compute_dz2_da1'''
W2= np.mat([[1.,
.4,3.],
[8.,.5,
.2]])+.32
dz2_da1 = compute_dz2_da1(W2)
assert type(dz2_da1) == np.matrixlib.defmatrix.matrix
assert dz2_da1.shape == (2,3)
print (dz2_da1)
assert np.allclose(dz2_da1, [[ 1.32, 0.72, 3.32], [ 8.32, 0.82, 0.52]], atol= 1e-3)
#-------------------------------------------------------------------------
def test_compute_da1_dz1():
'''(2 point) compute_da1_dz1'''
a1= np.mat([.5,.5,.3,.6]).T
da1_dz1 = compute_da1_dz1(a1)
assert type(da1_dz1) == np.matrixlib.defmatrix.matrix
assert da1_dz1.shape == (4,1)
assert np.allclose(da1_dz1.T, [.25,.25,.21,.24], atol= 1e-3)
#-------------------------------------------------------------------------
def test_compute_dz1_dW1():
'''(2 point) compute_dz1_dW1'''
x = np.mat([1., 2.,3.]).T
dz_dW = compute_dz1_dW1(x,2)
assert type(dz_dW) == np.matrixlib.defmatrix.matrix
assert dz_dW.shape == (2,3)
dz_dW_true = np.mat([[1., 2.,3],[1., 2.,3]])
assert np.allclose(dz_dW, dz_dW_true, atol=1e-2)
#-------------------------------------------------------------------------
def test_compute_dz1_db1():
'''(2 point) compute_dz1_db1'''
dz_db = compute_dz1_db1(2)
assert type(dz_db) == np.matrixlib.defmatrix.matrix
assert dz_db.shape == (2,1)
dz_db_true = np.mat([1.,1.])
assert np.allclose(dz_db, dz_db_true, atol=1e-2)
#-------------------------------------------------------------------------
def test_backward():
'''(4 point) backward'''
x = np.mat([1., 2.,3.,4]).T
y = 1
# first layer with 3 hidden neurons
W1 = np.mat([[0.,0.,0.,0.],
[0.,0.,0.,0.],
[0.,0.,0.,0.]])
b1 = np.mat([0.,0.,0.]).T
# second layer with 2 hidden neurons
W2 = np.mat([[0.,0.,0.],
[0.,0.,0.]])
b2 = np.mat([0.,0.]).T
z1, a1, z2, a2 = forward(x, W1, b1, W2, b2)
dL_da2, da2_dz2, dz2_dW2, dz2_db2, dz2_da1, da1_dz1, dz1_dW1, dz1_db1= backward(x,y,a1,a2, W2)
assert type(dL_da2) == np.matrixlib.defmatrix.matrix
assert dL_da2.shape == (2,1)
np.allclose(dL_da2.T,[0.,-2.],atol=1e-3)
assert type(da2_dz2) == np.matrixlib.defmatrix.matrix
assert da2_dz2.shape == (2,2)
np.allclose(da2_dz2,[[.25,-.25],[-.25,.25]],atol=1e-3)
assert type(dz2_dW2) == np.matrixlib.defmatrix.matrix
assert dz2_dW2.shape == (2,3)
np.allclose(dz2_dW2,[[.5,.5,.5],[.5,.5,.5]],atol=1e-3)
assert type(dz2_db2) == np.matrixlib.defmatrix.matrix
assert dz2_db2.shape == (2,1)
np.allclose(dz2_db2.T,[1,1],atol=1e-3)
assert type(dz2_da1) == np.matrixlib.defmatrix.matrix
assert dz2_da1.shape == (2,3)
t = [[ 0., 0., 0.],
[ 0., 0., 0.]]
np.allclose(dz2_da1,t,atol=1e-3)
assert type(da1_dz1) == np.matrixlib.defmatrix.matrix
assert da1_dz1.shape == (3,1)
np.allclose(da1_dz1.T,[.25,.25,.25],atol=1e-3)
assert type(dz1_dW1) == np.matrixlib.defmatrix.matrix
assert dz1_dW1.shape == (3,4)
t = [[ 1., 2., 3., 4.],
[ 1., 2., 3., 4.],
[ 1., 2., 3., 4.]]
np.allclose(dz1_dW1,t,atol=1e-3)
assert type(dz1_db1) == np.matrixlib.defmatrix.matrix
assert dz1_db1.shape == (3,1)
np.allclose(dz1_db1.T,[1,1,1],atol=1e-3)
#-------------------------------------------------------------------------
def test_compute_dL_da1():
'''(3 point) compute_dL_da1'''
dL_dz2 = np.mat([ 0.09554921, 0.14753129, 0.47769828,-0.72077878]).T
dz2_da1 = np.mat([[ 0.26739761, 0.73446399, 0.24513834],
[ 0.80682023, 0.7841972 , 0.01415917],
[ 0.70592854, 0.73489433, 0.91355454],
[ 0.8558265 , 0.84993468, 0.24702029]])
dL_da1 = compute_dL_da1(dL_dz2,dz2_da1)
assert type(dL_da1) == np.matrixlib.defmatrix.matrix
assert dL_da1.shape == (3,1)
dL_da1_true = np.mat([-0.13505987,-0.07568605, 0.28386814]).T
assert np.allclose(dL_da1, dL_da1_true, atol=1e-3)
#-------------------------------------------------------------------------
def test_compute_dL_dz1():
'''(3 point) compute_dL_dz1'''
dL_da1 = np.mat([-0.03777044, 0.29040313,-0.42821076,-0.28597724 ]).T
da1_dz1 = np.mat([ 0.03766515, 0.09406613, 0.06316817, 0.05718137]).T
dL_dz1 = compute_dL_dz1(dL_da1, da1_dz1)
print (dL_dz1)
assert type(dL_dz1) == np.matrixlib.defmatrix.matrix
assert dL_dz1.shape == (4,1)
dL_dz1_true = np.mat([-0.00142263, 0.0273171, -0.02704929,-0.01635257]).T
assert np.allclose(dL_dz1, dL_dz1_true, atol=1e-3)
##-------------------------------------------------------------------------
def test_compute_gradients():
'''(4 point) compute_gradients'''
x = np.mat([1., 2.,3.,4]).T
y = 1
# first layer with 3 hidden neurons
W1 = np.mat([[0.,0.,0.,0.],
[0.,0.,0.,0.],
[0.,0.,0.,0.]])
b1 = np.mat([0.,0.,0.]).T
# second layer with 2 hidden neurons
W2 = np.mat([[0.,0.,0.],
[0.,0.,0.]])
b2 = np.mat([0.,0.]).T
# forward pass
z1, a1, z2, a2 = forward(x, W1, b1, W2, b2)
print ('a1:', a1)
# backward pass: prepare local gradients
dL_da2, da2_dz2, dz2_dW2, dz2_db2, dz2_da1, da1_dz1, dz1_dW1, dz1_db1= backward(x,y,a1,a2, W2)
# call the function
dL_dW2, dL_db2, dL_dW1, dL_db1 = compute_gradients(dL_da2, da2_dz2, dz2_dW2, dz2_db2, dz2_da1, da1_dz1, dz1_dW1, dz1_db1)
assert type(dL_dW2) == np.matrixlib.defmatrix.matrix
assert dL_dW2.shape == (2,3)
t = [[ 0.25, 0.25, 0.25],
[-0.25,-0.25,-0.25]]
np.allclose(dL_dW2,t,atol=1e-3)
assert type(dL_db2) == np.matrixlib.defmatrix.matrix
assert dL_db2.shape == (2,1)
t = [0.5,-0.5]
np.allclose(dL_db2.T,t,atol=1e-3)
assert type(dL_dW1) == np.matrixlib.defmatrix.matrix
assert dL_dW1.shape == (3,4)
t = np.zeros((3,4))
np.allclose(dL_dW1,t,atol=1e-3)
assert type(dL_db1) == np.matrixlib.defmatrix.matrix
assert dL_db1.shape == (3,1)
t = [0,0,0]
np.allclose(dL_db1.T,t,atol=1e-3)
##-------------------------------------------------------------------------
def test_check_compute_gradients():
'''(3 point) check gradients'''
for _ in range(20):
p = np.random.randint(2,10) # number of features
c = np.random.randint(2,10) # number of classes
h = np.random.randint(2,10) # number of neurons in the 1st layer
x = np.asmatrix(10*np.random.random((p,1))-5)
y = np.random.randint(c)
W1 = np.asmatrix(2*np.random.random((h,p))-1)
b1 = np.asmatrix(np.random.random((h,1)))
W2 = np.asmatrix(2*np.random.random((c,h))-1)
b2 | |
<gh_stars>1-10
from urllib.parse import quote
"""
The pyrealpro module provides classes that can be used to build a representation of a song, and render it in the import
URL format used by the iRealPro app. It assumes that you have a passing familiarity with the format as documented at
https://irealpro.com/ireal-pro-file-format/, but hopefully makes it easier to programmatically construct an iRealPro
song than resorting to brute-force string concatenation.
"""
KEY_SIGNATURES = ['C', 'Db', 'D', 'Eb', 'E', 'F', 'Gb', 'G', 'Ab', 'A', 'Bb', 'B', 'A-', 'Bb-', 'B-', 'C-', 'C#-',
'D-', 'Eb-', 'E-', 'F-', 'F#-', 'G-', 'G#-']
STYLES_JAZZ = ["Afro 12/8",
"Ballad Double Time Feel",
"Ballad Even",
"Ballad Melodic",
"Ballad Swing",
"Blue Note",
"Bossa Nova",
"Doo Doo Cats",
"Double Time Swing",
"Even 8ths",
"Even 8ths Open",
"Even 16ths",
"Guitar Trio",
"Gypsy Jazz",
"Latin",
"Latin/Swing",
"Long Notes",
"Medium Swing",
"Medium Up Swing",
"Medium Up Swing 2",
"New Orleans Swing",
"Second Line",
"Slow Swing",
"Swing Two/Four",
"Trad Jazz",
"Up Tempo Swing",
"Up Tempo Swing 2", ]
STYLES_LATIN = ["Argentina: Tango",
"Brazil: Bossa Acoustic",
"Brazil: Bossa Electric",
"Brazil: Samba",
"Cuba: Bolero",
"Cuba: Cha Cha Cha",
"Cuba: Son Montuno 2-3",
"Cuba: Son Montuno 3-2", ]
STYLES_POP = ["Bluegrass",
"Country",
"Disco",
"Funk",
"Glam Funk",
"House",
"Reggae",
"Rock",
"Rock 12/8",
"RnB",
"Shuffle",
"Slow Rock",
"Smooth",
"Soul",
"Virtual Funk", ]
STYLES_ALL = STYLES_JAZZ + STYLES_LATIN + STYLES_POP
class Song:
"""
A class for building fake-book style chord charts that can be imported into iRealPro. Implements the iRealPro
data format as described at https://irealpro.com/ireal-pro-file-format/.
"""
measures = None
def __init__(self, **kwargs):
"""
Initializes a new Song object.
:param title: (str) The title of the song. Defaults to "Unknown".
:param key: (str) The key signature of the song. Should be a value found in KEY_SIGNATURES.
:param composer_name_first: (str) The composer's first name. Defaults to "Unknown".
:param composer_name_last: (str) The composer's last name. Defaults to "Unknown".
:param style: (str) The song style. Must be a value found in STYLES_ALL. Defaults to "Medium Swing".
:param measures: (list) A list containing one or more Measure objects. If omitted, it will be initialized as an empty
list that can be appended to later.
"""
# Required properties:
if 'title' in kwargs:
self.title = kwargs['title']
else:
self.title = 'Untitled'
if 'key' in kwargs and kwargs['key'] in KEY_SIGNATURES:
if kwargs['key'] not in KEY_SIGNATURES:
raise ValueError("'{}' is not a valid key signature.".format(kwargs['key']))
self.key = kwargs['key']
else:
self.key = 'C'
if 'composer_name_first' in kwargs:
self.composer_name_first = kwargs['composer_name_first']
else:
self.composer_name_first = "Unknown"
if 'composer_name_last' in kwargs:
self.composer_name_last = kwargs['composer_name_last']
else:
self.composer_name_last = "Unknown"
if 'style' in kwargs:
if kwargs['style'] in STYLES_ALL:
self.style = kwargs['style']
else:
raise ValueError(f"{kwargs['style']} is not a valid iRealPro style.")
else:
self.style = 'Medium Swing'
if 'measures' in kwargs:
self.measures = kwargs['measures']
else:
self.measures = []
@property
def composer_name(self):
"""
:return: (str) The composer's full name in "Last First" format.
"""
if self.composer_name_first == 'Unknown' and self.composer_name_last == 'Unknown':
return 'Unknown'
else:
return f"{self.composer_name_last} {self.composer_name_first}"
def url(self, urlencode=True):
"""
Renders Song as an iRealPro data URL.
:param urlencode: (bool), optional
Indicates whether or not the result should be URL-encoded.
"""
# Import crashes without at least one measure
if len(self.measures) == 0:
self.measures.append(Measure(" "))
# If this song has any measures defined, force the first one to render its time signature
self.measures[0].render_ts = True
# If the first measure has no opening barline defined, make it a double barline
if self.measures[0].barline_open == "":
self.measures[0].barline_open = "["
# If the last measure has no barline or the default barline, make it a final double barline
if self.measures[-1].barline_close in ["", "|", None]:
self.measures[-1].barline_close = "Z"
measures_str = "".join(m.__str__() for m in self.measures)
url = f"irealbook://{self.title}={self.composer_name}={self.style}={self.key}=n={measures_str}"
if urlencode:
return quote(url, safe=":/=")
else:
return url
def __str__(self):
return "<{} {}: {}>".format(type(self).__name__, id(self), self.title)
class Measure:
"""Represents a single measure of an iRealPro song."""
BARLINES_OPEN = [
"[", # opening double bar line
"{", # opening repeat bar line
]
BARLINES_CLOSE = [
"|", # single bar line
"]", # closing double bar line
"}", # closing repeat bar line
"Z", # Final thick double bar line
]
REHEARSAL_MARKS = [
"*A", # A section
"*B", # B section
"*C", # C Section
"*D", # D Section
"*V", # Verse
"*i", # Intro
"S", # Segno
"Q", # Coda
"f", # Fermata
]
ENDINGS = [
"N1", # First ending
"N2", # Second Ending
"N3", # Third Ending
"N0", # No text Ending
]
chords = None
time_sig = None
rehearsal_marks = None
render_ts = False
barline_open = None
barline_close = None
ending = None
staff_text = None
def __init__(self, chords, time_sig=None, rehearsal_marks=[], barline_open="", barline_close=None, ending="",
staff_text="", render_ts=False):
"""
Initializes a Measure object.
:param chords: Union([str, list]) A string representing a single chord, or a list of chords. If a list is
provided, the list length must either match the number of beats indicated
by the time signature, or the number of beats in the time signature must be
evenly divisible by the number of chords in the list (in which case the chords
will be evenly spaced to fill the measure.)
:param time_sig: (TimeSignature), optional The measure time signature. Defaults to 4/4.
:param rehearsal_marks: Union([str, list]) optional
A string containing a single rehearsal mark, or a list containing
multiple rehearsal marks. See REHEARSAL_MARKS for possible values.
:param barline_open: (str), optional
A string indicating that this measure has a beginning barline. See BARLINES_OPEN for
possible values.
:param barline_close: (str), optional
A string indicating that this measure has an ending barline. See BARLINES_CLOSE for
possible values.
:param ending: (str), optional
When building a Song with repeats, indicates that this measure is the beginning of an
alternate ending. See ENDINGS for possible values.
:param staff_text: (str), optional
A string to be displayed below the measure.
:param render_ts: (bool), optional
Indicates whether the time signature should be included when this measure is output
as a string. Defaults to False.
"""
if time_sig is None:
time_sig = TimeSignature(4, 4)
self.time_sig = time_sig
self.rehearsal_marks = rehearsal_marks
if barline_open is None:
barline_open = ""
self.barline_open = barline_open
self.ending = ending
# Measure should always have an ending barline
if barline_close is None or barline_close == "":
barline_close = "|"
self.barline_close = barline_close
self.staff_text = staff_text
self.ending = ending
self.render_ts = render_ts
if type(chords) == str:
self.chords = [chords]
for i in range(0, self.time_sig.beats - 1):
self.chords.append(' ')
elif len(chords) == self.time_sig.beats:
# Replace any instances of `None` with spaces
self.chords = [' ' if c is None else c for c in chords]
elif self.time_sig.beats % len(chords) == 0:
# If beats modulo chords length is zero, then spread them out evenly to fill the measure
pad = int((self.time_sig.beats - len(chords)) / len(chords))
self.chords = []
for chord in chords:
self.chords.append(chord)
for i in range(0, pad):
self.chords.append(' ')
else:
raise ValueError("Expected data for {} beats, got {} instead.".format(self.time_sig.beats, len(chords)))
if type(rehearsal_marks) == str:
self.rehearsal_marks = [rehearsal_marks]
else:
self.rehearsal_marks = rehearsal_marks
if not all(x in self.REHEARSAL_MARKS for x in self.rehearsal_marks):
raise ValueError("Found one or more unrecognized rehearsal marks.")
def __str__(self):
chords_sep = ""
if len(self.chords) > 1:
chords_sep = ","
chords_str = chords_sep.join(self.chords)
if self.render_ts:
ts = self.time_sig
else:
ts = ""
if self.staff_text != "":
staff_text = f"<{self.staff_text}>"
else:
staff_text = ""
# Coda and Fermata go at the end of the measure, all others go at the start
rehearsal_marks_start = "".join([x for x in self.rehearsal_marks if x[0] not in ['Q', 'f']])
rehearsal_marks_end = "".join([x for x in self.rehearsal_marks if x[0] in ['Q', 'f']])
return f"{rehearsal_marks_start}{self.barline_open}{ts}{staff_text}{self.ending}{chords_str}{rehearsal_marks_end}{self.barline_close}"
class TimeSignature:
"""
Represents a musical time signature.
"""
VALID_TIME_SIGNATURES = ['T44', 'T34', 'T24', 'T54', 'T64', 'T74', 'T22', 'T32', 'T58', 'T68', 'T78', 'T98', 'T12']
beats = None
duration = None
def __init__(self, beats=4, duration=4):
"""
Initializes a TimeSignature object.
:param beats: (int) The number of beats per measure.
:param duration: (int) The duration per beat.
"""
if beats:
self.beats = beats
if duration:
self.duration = duration
if self.__str__() | |
<reponame>cocoaaa/interpretable-test
"""Simulation to examine the type-1 error or test power as the dimension
increases"""
from __future__ import print_function
from __future__ import absolute_import
from builtins import str
from builtins import range
__author__ = 'wittawat'
import freqopttest.ex.ex1_power_vs_n as ex1
import freqopttest.data as data
import freqopttest.tst as tst
import freqopttest.glo as glo
import freqopttest.util as util
import freqopttest.kernel as kernel
from . import exglobal
# need independent_jobs package
# https://github.com/karlnapf/independent-jobs
# The independent_jobs and freqopttest have to be in the globl search path (.bashrc)
import independent_jobs as inj
from independent_jobs.jobs.IndependentJob import IndependentJob
from independent_jobs.results.SingleResult import SingleResult
from independent_jobs.aggregators.SingleResultAggregator import SingleResultAggregator
from independent_jobs.engines.BatchClusterParameters import BatchClusterParameters
from independent_jobs.engines.SerialComputationEngine import SerialComputationEngine
from independent_jobs.engines.SlurmComputationEngine import SlurmComputationEngine
from independent_jobs.tools.Log import logger
import math
import autograd.numpy as np
import os
import sys
def job_met_opt(sample_source, tr, te, r):
"""MeanEmbeddingTest with test locations optimzied.
Return results from calling perform_test()"""
# MeanEmbeddingTest. optimize the test locations
with util.ContextTimer() as t:
met_opt_options = {'n_test_locs': J, 'max_iter': 200,
'locs_step_size': 0.1, 'gwidth_step_size': 0.1, 'seed': r+92856,
'tol_fun': 1e-3}
test_locs, gwidth, info = tst.MeanEmbeddingTest.optimize_locs_width(tr, alpha, **met_opt_options)
met_opt = tst.MeanEmbeddingTest(test_locs, gwidth, alpha)
met_opt_test = met_opt.perform_test(te)
return {
#'test_method': met_opt,
'test_result': met_opt_test,
'time_secs': t.secs}
def job_met_opt5(sample_source, tr, te, r):
"""MeanEmbeddingTest with test locations optimzied.
Large step size
Return results from calling perform_test()"""
with util.ContextTimer() as t:
# MeanEmbeddingTest. optimize the test locations
met_opt_options = {'n_test_locs': J, 'max_iter': 200,
'locs_step_size': 0.5, 'gwidth_step_size': 0.1, 'seed': r+92856,
'tol_fun': 1e-3}
test_locs, gwidth, info = tst.MeanEmbeddingTest.optimize_locs_width(tr, alpha, **met_opt_options)
met_opt = tst.MeanEmbeddingTest(test_locs, gwidth, alpha)
met_opt_test = met_opt.perform_test(te)
return {
#'test_method': met_opt,
'test_result': met_opt_test,
'time_secs': t.secs}
def job_met_opt10(sample_source, tr, te, r):
"""MeanEmbeddingTest with test locations optimzied.
Large step size
Return results from calling perform_test()"""
# MeanEmbeddingTest. optimize the test locations
with util.ContextTimer() as t:
met_opt_options = {'n_test_locs': J, 'max_iter': 100,
'locs_step_size': 10.0, 'gwidth_step_size': 0.2, 'seed': r+92856,
'tol_fun': 1e-3}
test_locs, gwidth, info = tst.MeanEmbeddingTest.optimize_locs_width(tr, alpha, **met_opt_options)
met_opt = tst.MeanEmbeddingTest(test_locs, gwidth, alpha)
met_opt_test = met_opt.perform_test(te)
return {
#'test_method': met_opt,
'test_result': met_opt_test,
'time_secs': t.secs}
def job_met_gwopt(sample_source, tr, te, r):
"""MeanEmbeddingTest. Optimize only the Gaussian width.
Fix the test locations."""
raise ValueError('Use job_met_gwgrid instead')
op_gwidth = {'max_iter': 200, 'gwidth_step_size': 0.1,
'batch_proportion': 1.0, 'tol_fun': 1e-3}
# optimize on the training set
T_randn = tst.MeanEmbeddingTest.init_locs_2randn(tr, J, seed=r+92856)
gwidth, info = tst.MeanEmbeddingTest.optimize_gwidth(tr, T_randn, **op_gwidth)
met_gwopt = tst.MeanEmbeddingTest(T_randn, gwidth, alpha)
return met_gwopt.perform_test(te)
def job_met_gwgrid(sample_source, tr, te, r):
"""MeanEmbeddingTest. Optimize only the Gaussian width with grid search
Fix the test locations."""
return ex1.job_met_gwgrid('', tr, te, r, -1, -1)
def job_scf_opt(sample_source, tr, te, r):
"""SmoothCFTest with frequencies optimized."""
with util.ContextTimer() as t:
op = {'n_test_freqs': J, 'max_iter': 200, 'freqs_step_size': 0.1,
'gwidth_step_size': 0.1, 'seed': r+92856, 'tol_fun': 1e-3}
test_freqs, gwidth, info = tst.SmoothCFTest.optimize_freqs_width(tr, alpha, **op)
scf_opt = tst.SmoothCFTest(test_freqs, gwidth, alpha)
scf_opt_test = scf_opt.perform_test(te)
return {
#'test_method': scf_opt,
'test_result': scf_opt_test,
'time_secs': t.secs}
def job_scf_opt10(sample_source, tr, te, r):
"""SmoothCFTest with frequencies optimized."""
with util.ContextTimer() as t:
op = {'n_test_freqs': J, 'max_iter': 100, 'freqs_step_size': 1.0,
'gwidth_step_size': 0.1, 'seed': r+92856, 'tol_fun': 1e-3}
test_freqs, gwidth, info = tst.SmoothCFTest.optimize_freqs_width(tr, alpha, **op)
scf_opt = tst.SmoothCFTest(test_freqs, gwidth, alpha)
scf_opt_test = scf_opt.perform_test(te)
return {
#'test_method': scf_opt,
'test_result': scf_opt_test,
'time_secs': t.secs}
def job_scf_gwopt(sample_source, tr, te, r):
"""SmoothCFTest. Optimize only the Gaussian width.
Fix the test frequencies"""
raise ValueError('Use job_scf_gwgrid instead')
op_gwidth = {'max_iter': 200, 'gwidth_step_size': 0.1,
'batch_proportion': 1.0, 'tol_fun': 1e-3}
# optimize on the training set
rand_state = np.random.get_state()
np.random.seed(seed=r+92856)
T_randn = np.random.randn(J, sample_source.dim())
np.random.set_state(rand_state)
gwidth, info = tst.SmoothCFTest.optimize_gwidth(tr, T_randn, **op_gwidth)
scf_gwopt = tst.SmoothCFTest(T_randn, gwidth, alpha)
return scf_gwopt.perform_test(te)
def job_scf_gwgrid(sample_source, tr, te, r):
return ex1.job_scf_gwgrid('', tr, te, r, -1 , -1)
def job_quad_mmd(sample_source, tr, te, r):
"""Quadratic mmd with grid search to choose the best Gaussian width."""
# If n is too large, pairwise meddian computation can cause a memory error.
with util.ContextTimer() as t:
med = util.meddistance(tr.stack_xy(), 1000)
list_gwidth = np.hstack( ( (med**2) *(2.0**np.linspace(-4, 4, 30) ) ) )
list_gwidth.sort()
list_kernels = [kernel.KGauss(gw2) for gw2 in list_gwidth]
# grid search to choose the best Gaussian width
besti, powers = tst.QuadMMDTest.grid_search_kernel(tr, list_kernels, alpha)
# perform test
best_ker = list_kernels[besti]
mmd_test = tst.QuadMMDTest(best_ker, n_permute=400, alpha=alpha)
test_result = mmd_test.perform_test(te)
return {
#'test_method': mmd_test,
'test_result': test_result,
'time_secs': t.secs}
def job_lin_mmd(sample_source, tr, te, r):
"""Linear mmd with grid search to choose the best Gaussian width."""
# should be completely deterministic
with util.ContextTimer() as t:
# If n is too large, pairwise meddian computation can cause a memory error.
X, Y = tr.xy()
Xr = X[:min(X.shape[0], 1000), :]
Yr = Y[:min(Y.shape[0], 1000), :]
med = util.meddistance(np.vstack((Xr, Yr)) )
widths = [ (med*f) for f in 2.0**np.linspace(-1, 4, 40)]
list_kernels = [kernel.KGauss( w**2 ) for w in widths]
# grid search to choose the best Gaussian width
besti, powers = tst.LinearMMDTest.grid_search_kernel(tr, list_kernels, alpha)
# perform test
best_ker = list_kernels[besti]
lin_mmd_test = tst.LinearMMDTest(best_ker, alpha)
test_result = lin_mmd_test.perform_test(te)
return {
#'test_method': lin_mmd_test,
'test_result': test_result,
'time_secs': t.secs}
def job_hotelling(sample_source, tr, te, r):
"""Hotelling T-squared test"""
with util.ContextTimer() as t:
htest = tst.HotellingT2Test(alpha=alpha)
result = htest.perform_test(te)
return {'test_method': htest,
'test_result': result,
'time_secs': t.secs}
# Define our custom Job, which inherits from base class IndependentJob
class Ex2Job(IndependentJob):
def __init__(self, aggregator, sample_source, prob_label, rep, job_func):
d = sample_source.dim()
#walltime = 60*59*24 if d*sample_size*tr_proportion/15 >= 8000 else 60*59
walltime = 60*59*24
memory = int(tr_proportion*sample_size*1e-2) + 50
IndependentJob.__init__(self, aggregator, walltime=walltime,
memory=memory)
self.sample_source = sample_source
self.prob_label = prob_label
self.rep = rep
self.job_func = job_func
# we need to define the abstract compute method. It has to return an instance
# of JobResult base class
def compute(self):
sample_source = self.sample_source
r = self.rep
d = sample_source.dim()
job_func = self.job_func
logger.info("computing. %s. r=%d, d=%d"%(job_func.__name__, r, d))
# sample_size is a global variable
tst_data = sample_source.sample(sample_size, seed=r)
tr, te = tst_data.split_tr_te(tr_proportion=tr_proportion, seed=r+20 )
prob_label = self.prob_label
test_result = job_func(sample_source, tr, te, r)
# create ScalarResult instance
result = SingleResult(test_result)
# submit the result to my own aggregator
self.aggregator.submit_result(result)
logger.info("done. ex2: %s, r=%d, d=%d, "%(job_func.__name__, r, d))
# save result
func_name = job_func.__name__
fname = '%s-%s-J%d_r%d_n%d_d%d_a%.3f_trp%.2f.p' \
%(prob_label, func_name, J, r, sample_size, d, alpha, tr_proportion)
glo.ex_save_result(ex, test_result, prob_label, fname)
# This import is needed so that pickle knows about the class Ex2Job.
# pickle is used when collecting the results from the submitted jobs.
from freqopttest.ex.ex2_vary_d import job_met_opt
from freqopttest.ex.ex2_vary_d import job_met_opt5
from freqopttest.ex.ex2_vary_d import job_met_opt10
from freqopttest.ex.ex2_vary_d import job_met_gwopt
from freqopttest.ex.ex2_vary_d import job_met_gwgrid
from freqopttest.ex.ex2_vary_d import job_scf_opt
from freqopttest.ex.ex2_vary_d import job_scf_opt10
from freqopttest.ex.ex2_vary_d import job_scf_gwopt
from freqopttest.ex.ex2_vary_d import job_scf_gwgrid
from freqopttest.ex.ex2_vary_d import job_quad_mmd
from freqopttest.ex.ex2_vary_d import job_lin_mmd
from freqopttest.ex.ex2_vary_d import job_hotelling
from freqopttest.ex.ex2_vary_d import Ex2Job
#--- experimental setting -----
ex = 2
# sample size = n (the number training and test sizes are n/2)
sample_size = 20000
# number of test locations / test frequencies J
J = 5
alpha = 0.01
tr_proportion = 0.5
# repetitions for each dimension
reps = 500
#method_job_funcs = [ job_met_opt, job_met_opt10, job_met_gwgrid,
# job_scf_opt, job_scf_opt10, job_scf_gwgrid, job_lin_mmd, job_hotelling]
method_job_funcs = [ job_met_opt10, job_met_gwgrid,
job_scf_opt10, job_scf_gwgrid,
#job_quad_mmd,
job_lin_mmd, job_hotelling]
#method_job_funcs = [ job_lin_mmd, job_hotelling]
# If is_rerun==False, do not rerun the experiment if a result file for the current
# setting of (di, r) already exists.
is_rerun = False
#---------------------------
def get_sample_source_list(prob_label):
"""Return a list of SampleSource's representing the problems, each
corresponding to one dimension in the list.
"""
# map: prob_label -> [sample_source]
# dimensions to try
dimensions = [5] + [100*i for i in range(1, 5+1)]
high_dims = [5] + [300*i for i in range(1, 5+1)]
low_dims = [2*d for d in range(1, 7+1)]
prob2ss = {
'gmd': [data.SSGaussMeanDiff(d=d, my=1.0) for d in high_dims],
'gvd': [data.SSGaussVarDiff(d=d) for d in dimensions],
# The null is true
'sg': [data.SSSameGauss(d=d) for d in high_dims],
'sg_low': [data.SSSameGauss(d=d) for d in low_dims]
}
if prob_label not in prob2ss:
raise ValueError('Unknown problem label. Need to be one of %s'%str(list(prob2ss.keys())) )
return prob2ss[prob_label]
def main():
if len(sys.argv) != 2:
print('Usage: %s problem_label'%sys.argv[0])
sys.exit(1)
prob_label = sys.argv[1]
run_dataset(prob_label)
def run_dataset(prob_label):
"""Run the experiment"""
list_ss = get_sample_source_list(prob_label)
dimensions = [ss.dim() for ss in list_ss]
# /////// submit jobs //////////
# create folder name string
home = os.path.expanduser("~")
foldername = os.path.join(home, "freqopttest_slurm", 'e%d'%ex)
logger.info("Setting engine folder to %s" % foldername)
# create parameter instance that is needed for any batch computation engine
logger.info("Creating batch parameter instance")
batch_parameters = | |
on an instance *instance* of the
owner class.
object.__set_name__(self, owner, name)
Called at the time the owning class *owner* is created. The
descriptor has been assigned to *name*.
New in version 3.6.
The attribute "__objclass__" is interpreted by the "inspect" module as
specifying the class where this object was defined (setting this
appropriately can assist in runtime introspection of dynamic class
attributes). For callables, it may indicate that an instance of the
given type (or a subclass) is expected or required as the first
positional argument (for example, CPython sets this attribute for
unbound methods that are implemented in C).
Invoking Descriptors
====================
In general, a descriptor is an object attribute with "binding
behavior", one whose attribute access has been overridden by methods
in the descriptor protocol: "__get__()", "__set__()", and
"__delete__()". If any of those methods are defined for an object, it
is said to be a descriptor.
The default behavior for attribute access is to get, set, or delete
the attribute from an object's dictionary. For instance, "a.x" has a
lookup chain starting with "a.__dict__['x']", then
"type(a).__dict__['x']", and continuing through the base classes of
"type(a)" excluding metaclasses.
However, if the looked-up value is an object defining one of the
descriptor methods, then Python may override the default behavior and
invoke the descriptor method instead. Where this occurs in the
precedence chain depends on which descriptor methods were defined and
how they were called.
The starting point for descriptor invocation is a binding, "a.x". How
the arguments are assembled depends on "a":
Direct Call
The simplest and least common call is when user code directly
invokes a descriptor method: "x.__get__(a)".
Instance Binding
If binding to an object instance, "a.x" is transformed into the
call: "type(a).__dict__['x'].__get__(a, type(a))".
Class Binding
If binding to a class, "A.x" is transformed into the call:
"A.__dict__['x'].__get__(None, A)".
Super Binding
If "a" is an instance of "super", then the binding "super(B,
obj).m()" searches "obj.__class__.__mro__" for the base class "A"
immediately preceding "B" and then invokes the descriptor with the
call: "A.__dict__['m'].__get__(obj, obj.__class__)".
For instance bindings, the precedence of descriptor invocation depends
on the which descriptor methods are defined. A descriptor can define
any combination of "__get__()", "__set__()" and "__delete__()". If it
does not define "__get__()", then accessing the attribute will return
the descriptor object itself unless there is a value in the object's
instance dictionary. If the descriptor defines "__set__()" and/or
"__delete__()", it is a data descriptor; if it defines neither, it is
a non-data descriptor. Normally, data descriptors define both
"__get__()" and "__set__()", while non-data descriptors have just the
"__get__()" method. Data descriptors with "__set__()" and "__get__()"
defined always override a redefinition in an instance dictionary. In
contrast, non-data descriptors can be overridden by instances.
Python methods (including "staticmethod()" and "classmethod()") are
implemented as non-data descriptors. Accordingly, instances can
redefine and override methods. This allows individual instances to
acquire behaviors that differ from other instances of the same class.
The "property()" function is implemented as a data descriptor.
Accordingly, instances cannot override the behavior of a property.
__slots__
=========
By default, instances of classes have a dictionary for attribute
storage. This wastes space for objects having very few instance
variables. The space consumption can become acute when creating large
numbers of instances.
The default can be overridden by defining *__slots__* in a class
definition. The *__slots__* declaration takes a sequence of instance
variables and reserves just enough space in each instance to hold a
value for each variable. Space is saved because *__dict__* is not
created for each instance.
object.__slots__
This class variable can be assigned a string, iterable, or sequence
of strings with variable names used by instances. *__slots__*
reserves space for the declared variables and prevents the
automatic creation of *__dict__* and *__weakref__* for each
instance.
Notes on using *__slots__*
--------------------------
* When inheriting from a class without *__slots__*, the *__dict__*
attribute of that class will always be accessible, so a *__slots__*
definition in the subclass is meaningless.
* Without a *__dict__* variable, instances cannot be assigned new
variables not listed in the *__slots__* definition. Attempts to
assign to an unlisted variable name raises "AttributeError". If
dynamic assignment of new variables is desired, then add
"'__dict__'" to the sequence of strings in the *__slots__*
declaration.
* Without a *__weakref__* variable for each instance, classes
defining *__slots__* do not support weak references to its
instances. If weak reference support is needed, then add
"'__weakref__'" to the sequence of strings in the *__slots__*
declaration.
* *__slots__* are implemented at the class level by creating
descriptors (Implementing Descriptors) for each variable name. As a
result, class attributes cannot be used to set default values for
instance variables defined by *__slots__*; otherwise, the class
attribute would overwrite the descriptor assignment.
* The action of a *__slots__* declaration is limited to the class
where it is defined. As a result, subclasses will have a *__dict__*
unless they also define *__slots__* (which must only contain names
of any *additional* slots).
* If a class defines a slot also defined in a base class, the
instance variable defined by the base class slot is inaccessible
(except by retrieving its descriptor directly from the base class).
This renders the meaning of the program undefined. In the future, a
check may be added to prevent this.
* Nonempty *__slots__* does not work for classes derived from
"variable-length" built-in types such as "int", "bytes" and "tuple".
* Any non-string iterable may be assigned to *__slots__*. Mappings
may also be used; however, in the future, special meaning may be
assigned to the values corresponding to each key.
* *__class__* assignment works only if both classes have the same
*__slots__*.
"""
, 'attribute-references':
"""Attribute references
********************
An attribute reference is a primary followed by a period and a name:
attributeref ::= primary "." identifier
The primary must evaluate to an object of a type that supports
attribute references, which most objects do. This object is then
asked to produce the attribute whose name is the identifier. This
production can be customized by overriding the "__getattr__()" method.
If this attribute is not available, the exception "AttributeError" is
raised. Otherwise, the type and value of the object produced is
determined by the object. Multiple evaluations of the same attribute
reference may yield different objects.
"""
, 'augassign':
"""Augmented assignment statements
*******************************
Augmented assignment is the combination, in a single statement, of a
binary operation and an assignment statement:
augmented_assignment_stmt ::= augtarget augop (expression_list | yield_expression)
augtarget ::= identifier | attributeref | subscription | slicing
augop ::= "+=" | "-=" | "*=" | "@=" | "/=" | "//=" | "%=" | "**="
| ">>=" | "<<=" | "&=" | "^=" | "|="
(See section Primaries for the syntax definitions of the last three
symbols.)
An augmented assignment evaluates the target (which, unlike normal
assignment statements, cannot be an unpacking) and the expression
list, performs the binary operation specific to the type of assignment
on the two operands, and assigns the result to the original target.
The target is only evaluated once.
An augmented assignment expression like "x += 1" can be rewritten as
"x = x + 1" to achieve a similar, but not exactly equal effect. In the
augmented version, "x" is only evaluated once. Also, when possible,
the actual operation is performed *in-place*, meaning that rather than
creating a new object and assigning that to the target, the old object
is modified instead.
Unlike normal assignments, augmented assignments evaluate the left-
hand side *before* evaluating the right-hand side. For example, "a[i]
+= f(x)" first looks-up "a[i]", then it evaluates "f(x)" and performs
the addition, and lastly, it writes the result back to "a[i]".
With the exception of assigning to tuples and multiple targets in a
single statement, the assignment done by augmented assignment
statements is handled the same way as normal assignments. Similarly,
with the exception of the possible *in-place* behavior, the binary
operation performed by augmented assignment is the same as the normal
binary operations.
For targets which are attribute references, the same caveat about
class and instance attributes applies as for regular assignments.
"""
, 'binary':
"""Binary arithmetic operations
****************************
The binary arithmetic operations have the conventional priority
levels. Note that some of these operations also apply to certain non-
numeric types. Apart from the power operator, there are only two
levels, one for multiplicative operators and one for additive
operators:
m_expr ::= u_expr | m_expr "*" u_expr | m_expr "@" m_expr |
m_expr | |
# T1 Plasti Element
import numpy as np
def Elmt_Init():
NoElementDim = 2
NoElementNodes = 3
NoElementHistory = 7
ElementDofNames = ["UX", "UY"]
ElementMaterialNames = ["E", "nu", "y0", "kh"]
ElementPostNames = ["UX", "UY", "SigMises", "a"]
return NoElementDim, NoElementNodes, ElementDofNames, NoElementHistory, ElementMaterialNames, ElementPostNames
def SH0_T1(xi, eta):
'''
SH0_T1(xi, eta) -> SH0
Return a two dimensional array containing shape functions and derivatives for T1 element.
Usage: SH0( NodeNumber, SHPIndex)
with SHPIndex = {
0 -> shape function,
1 -> derived shape function w.r.t. xi,
2 -> derived shape function w.r.t. eta
}
'''
return np.array([
[xi , 1.0, 0.0],
[eta , 0.0, 1.0],
[1 -xi -eta, -1.0, -1.0],
], dtype=np.float64)
def BmatVoigt2D(SHP):
'''
BmatVoigt(SHP) -> Bmat
Returns a B-Matrix (as dim:3) for computing the strain vector in voigt notation.
This B-Matrix assumes a 2D plane strain approximation.
SHP is a shape function matrix with derived functions w.r.t. physical space.
Input:
SHP( NodeNumber, SHPIndex)
with SHPIndex = {
0 -> shape function,
1 -> derived shape function w.r.t. x,
2 -> derived shape function w.r.t. y
}
Output:
Bmat(NodeNumber, i, j)
for eps_i = B_Iij * u_Ij
with
eps_i = [eps_11, eps_22, eps_33, 2*eps_12, 2*eps_23, 2*eps_13]
u_Ij = [[u_11, u_12] ... [u_n1, u_n2]]
'''
return np.array([
[
[N[1], 0 ],
[0 , N[2]],
[0 , 0 ],
[N[2], N[1]],
[0 , 0 ],
[0 , 0 ]
]
for N in SHP
], dtype=np.float64)
def HookeMatVoigt(kappa, mue):
'''
HookeMatVoigt(kappa, mue) -> Cmat
Returns the constitutive Voigt MATRIX(6,6) for a Hooke material law.
The input are the kompression modulus kappa and the shear modulus mue.
sig_i = Cmat_ij * eps_j
with
sig_i = [sig_11, sig_22, sig_33, sig_12, sig_23, sig_13]
eps_i = [eps_11, eps_22, eps_33, 2*eps_12, 2*eps_23, 2*eps_13]
'''
return np.array([
[kappa+(4.0/3.0)*mue, kappa-(2.0/3.0)*mue, kappa-(2.0/3.0)*mue, 0 , 0 , 0 ],
[kappa-(2.0/3.0)*mue, kappa+(4.0/3.0)*mue, kappa-(2.0/3.0)*mue, 0 , 0 , 0 ],
[kappa-(2.0/3.0)*mue, kappa-(2.0/3.0)*mue, kappa+(4.0/3.0)*mue, 0 , 0 , 0 ],
[0 , 0 , 0 , mue, 0 , 0 ],
[0 , 0 , 0 , 0 , mue, 0 ],
[0 , 0 , 0 , 0 , 0 , mue]
], dtype=np.float64)
# definition of auxillary matrix
pp1, pp2, pp3 = (2.0/3.0), -(1.0/3.0), (1.0/2.0)
PP = np.array( \
[[pp1, pp2, pp2, 0.0, 0.0, 0.0], \
[ pp2, pp1, pp2, 0.0, 0.0, 0.0], \
[ pp2, pp2, pp1, 0.0, 0.0, 0.0], \
[ 0.0, 0.0, 0.0, pp3, 0.0, 0.0], \
[ 0.0, 0.0, 0.0, 0.0, pp3, 0.0], \
[ 0.0, 0.0, 0.0, 0.0, 0.0, pp3]] \
,dtype=np.float64)
def Elmt_KS(XL, UL, Hn, Ht, Mat, dt):
'''
'''
verbose = False # True;
if verbose: print('XI :',XL) # XL = [x11, x12, x21, x22, x31, x32]
if verbose: print('UI :',UL) # UL = [u11, u12, u21, u22, u31, u32]
if verbose: print('Hn :',Hn) # Hn = [eps_pl_11, eps_pl_22, eps_pl_33, 2*eps_pl_12, 2*eps_pl_23, 2*eps_pl_13, a]
if verbose: print('Ht :',Ht) # Ht = [eps_pl_11, eps_pl_22, eps_pl_33, 2*eps_pl_12, 2*eps_pl_23, 2*eps_pl_13, a]
if verbose: print('b :',Mat) # Mat = [Emod, nue, y0, kh]
if verbose: print('dt :',dt) # dt = dt
# element specific paremeters
NoElementNodes = 3
NoNodalDOF = 2
NoDimension = 2
# initialize element vector /matrix
r_e = np.zeros(NoElementNodes*NoNodalDOF)
k_e = np.zeros((NoElementNodes*NoNodalDOF, NoElementNodes*NoNodalDOF))
# geometry and dofs
XI = XL.reshape(-1, NoDimension)
uI = UL.reshape(-1, NoNodalDOF)
# Material Parameters
Emod, nu, y0, kh = Mat[0], Mat[1], Mat[2], Mat[3]
kappa , mue = Emod/(3*(1.0-2.0*nu)), Emod/(2.0*(1.0+nu))
# constitutive matrix (hooke)
Cmat = HookeMatVoigt(kappa, mue)
# provide integration points
EGP = np.array([[(1.0/3.0), (1.0/3.0), (1.0/2.0)]])
NoInt = len(EGP)
# start integration Loop
for GP in range(NoInt):
if verbose: print('GP: ',GP)
xi, eta, wgp = EGP[GP]
# read gp history
NoHGP = 7 # number of history at each gp
eps_pl_n = Hn[ GP*NoHGP : GP*NoHGP+6]
a_n = Hn[ GP*NoHGP+6]
# compute current shape functions
SH0 = SH0_T1(xi, eta)
# compute mapping
Jed = np.einsum('Ii,Ij->ij', XI ,SH0[:,1:3])
detJ = np.linalg.det(Jed)
if (detJ <= 0): raise NameError("Error unphysical mapping detected.")
if verbose: print('detJ: ',detJ)
Jed_inv = np.linalg.inv(Jed)
# map shape function derivative
SHP = np.copy(SH0)
SHP[:,1:3] = np.einsum('Ij,ji->Ii', SH0[:,1:3], Jed_inv)
Bmat = BmatVoigt2D(SHP)
# compute strains / stresses
eps = np.einsum('Iij,Ij->i', Bmat, uI)
if verbose: print('eps: ')
if verbose: print(np.array([[eps[0], eps[3]/2, eps[4]/2], [eps[3]/2, eps[1], eps[5]/2], [eps[4]/2, eps[5]/2, eps[2]]]))
###############################################
############# begin plastic part ##############
###############################################
# compute elastic trail stresses
eps_el_tr = eps - eps_pl_n
if verbose: print('eps_el_tr: ')
if verbose: print(np.array([[eps_el_tr[0], eps_el_tr[3]/2, eps_el_tr[4]/2], [eps_el_tr[3]/2, eps_el_tr[1], eps_el_tr[5]/2], [eps_el_tr[4]/2, eps_el_tr[5]/2, eps_el_tr[2]]]))
# compute deviatoric trail stresses
sig_tr = np.einsum('ij,j->i' , Cmat, eps_el_tr)
tr_sig_tr = sig_tr[0] + sig_tr[1] + sig_tr[2]
dev_sig_tr = sig_tr - (1.0/3.0) * tr_sig_tr * np.array([1.0, 1.0, 1.0, 0.0, 0.0, 0.0])
# compute norm of deviatoric trail stresses
norm_dev_sig_tr = np.sqrt(
dev_sig_tr[0]**2 + dev_sig_tr[1]**2 + dev_sig_tr[2]**2 + \
2.0 * dev_sig_tr[3]**2 + 2.0 * dev_sig_tr[4]**2 + 2.0 * dev_sig_tr[5]**2
)
# compute yield criterion
phi_tr = norm_dev_sig_tr - np.sqrt(2.0/3.0) * (y0 + (2.0/3.0)*kh*a_n)
if verbose: print('norm_dev_sig_tr: ', norm_dev_sig_tr)
if verbose: print('yield: ', np.sqrt(2.0/3.0) * (y0 + (2.0/3.0)*kh*a_n))
if verbose: print('phi_tr: ', phi_tr)
# check yield criterion
if (phi_tr > 1e-8): # elasto-plastic loading
# compute plastic strain increment
delta_a = phi_tr/(2.0*mue + (2.0/3.0*kh))
a = a_n + np.sqrt(2.0/3.0) * delta_a
if verbose: print('delta_a: ', delta_a)
# compute plastic flow director
n_tr = dev_sig_tr/norm_dev_sig_tr
if verbose: print('n_tr: ')
if verbose: print(np.array([[n_tr[0], n_tr[3], n_tr[4]], [n_tr[3], n_tr[1], n_tr[5]], [n_tr[4], n_tr[5], n_tr[2]]]))
# compute plastic strain - take care of voigt notation!
eps_pl = eps_pl_n + delta_a * n_tr * np.array([1.0, 1.0, 1.0, 2.0, 2.0, 2.0])
if verbose: print('eps_pl: ')
if verbose: print(np.array([[eps_pl[0], eps_pl[3]/2, eps_pl[4]/2], [eps_pl[3]/2, eps_pl[1], eps_pl[5]/2], [eps_pl[4]/2, eps_pl[5]/2, eps_pl[2]]]))
# compute new elastic strains
eps_el = eps - eps_pl
if verbose: print('eps_el: ')
if verbose: print(np.array([[eps_el[0], eps_el[3]/2, eps_el[4]/2], [eps_el[3]/2, eps_el[1], eps_el[5]/2], [eps_el[4]/2, eps_el[5]/2, eps_el[2]]]))
sig = np.einsum('ij,j->i', Cmat, eps_el)
# modification of material tangent
fact1 = 1.0 - (2.0*mue*delta_a/norm_dev_sig_tr)
fact2 = 2.0*mue/(2.0*mue + (2.0/3.0*kh)) - (2.0*mue*delta_a/norm_dev_sig_tr)
Cmat += -2.0*mue*PP \
+ 2.0*mue*PP*fact1 \
- 2.0*mue*np.einsum('i,j->ij', n_tr, n_tr)*fact2
# export history
Ht[ GP*NoHGP : GP*NoHGP+6] = eps_pl
Ht[ GP*NoHGP+6] = a
else: # elastic loading
# old plastic state is stil valid
eps_pl = eps_pl_n
a = a_n
# compute elastic strains
eps_el = eps-eps_pl
sig = np.einsum('ij,j->i', Cmat, eps_el)
###############################################
############## end plastic part ###############
###############################################
# export right hand side | this element has 3 nodes with 2 dofs each
for I in range(NoElementNodes):
# compute nodal right hand side
nodal_rhs_vec = np.einsum('i,ij->j',sig, Bmat[I])
# integrate nodal right hand side and export
r_e[I*2+0] += nodal_rhs_vec[0] * wgp * detJ
r_e[I*2+1] += nodal_rhs_vec[1] * wgp * detJ
for J in range(NoElementNodes):
# compute nodal stiffness matrix
nodal_stiffness = np.einsum('ki,ko,oj->ij', Bmat[I], Cmat, Bmat[J])
# integrate nodal stiffness matrix and export
k_e[I*2+0, J*2+0] += nodal_stiffness[0,0] * wgp * detJ
k_e[I*2+0, J*2+1] += nodal_stiffness[0,1] * wgp * detJ
k_e[I*2+1, J*2+0] += nodal_stiffness[1,0] * wgp * detJ
k_e[I*2+1, J*2+1] += nodal_stiffness[1,1] * wgp * detJ
return r_e, k_e
def Elmt_Post(XL, UL, Hn, Ht, Mat, dt, PostName):
'''
'''
## NEW post strategy is to return indexes
# and contribuzions
# 3 nodes
r_post = np.zeros(3)
# geometry and dofs
XI = np.array([[XL[0], XL[1]], [XL[2], XL[3]], [XL[ 4], XL[ 5]]], dtype=np.float64)
uI = np.array([[UL[0], UL[1]], [UL[2], UL[3]], [UL[ 4], UL[ 5]]], dtype=np.float64)
# Material Parameters
Emod, nu, y0, kh = Mat[0], Mat[1], Mat[2], Mat[3]
lam , mue = (Emod*nu)/((1.0+nu)*(1.0-2.0*nu)), Emod/(2.0*(1.0+nu))
kappa = lam + (2.0/3.0)*mue
# constitutive matrix (hooke)
Cmat = HookeMatVoigt(kappa, mue)
# provide integration points
EGP = np.array([[(1.0/3.0), (1.0/3.0), (1.0/2.0)]])
NoInt = len(EGP)
# start integration Loop
for GP in range(NoInt):
xi, eta, wgp = EGP[GP]
# read gp history
NoHGP = 7 # number of history at each gp
eps_pl = Ht[ GP*NoHGP : GP*NoHGP+6]
a = Ht[ GP*NoHGP+6]
# compute current shape functions
SH0 = SH0_T1(xi, eta)
# compute mapping
Jed = np.einsum('Ii,Ij->ij', XI ,SH0[:,1:3])
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.