text
stringlengths 12
1.05M
| repo_name
stringlengths 5
86
| path
stringlengths 4
191
| language
stringclasses 1
value | license
stringclasses 15
values | size
int32 12
1.05M
| keyword
listlengths 1
23
| text_hash
stringlengths 64
64
|
|---|---|---|---|---|---|---|---|
# -*- coding: utf-8 -*-
# Author: Braden Czapla (2019)
# Last modified: 2019-04-29
# Original data: Kaiser et al. 1962, https://doi.org/10.1103/PhysRev.127.1950
from __future__ import absolute_import, division, print_function
import numpy as np
import matplotlib.pyplot as plt
###############################################################################
# Determine wavelengths to sample
def w(w_max, w_min, step):
linspace_lower = (np.floor_divide(w_min, step)+1)*step
N = np.floor_divide(w_max-w_min, step)
linspace_upper = linspace_lower + N*step
w = np.linspace(linspace_lower, linspace_upper, int(N)+1)
if not np.isclose(w[0], w_min, atol=step/5.):
w = np.concatenate((np.array([w_min]), w))
if not np.isclose(w[-1], w_max, atol=step/5.):
w = np.concatenate((w,np.array([w_max])))
return w, len(w)
# Compute dielectric function using Lorentzian model.
# Units of w and ResFreq must match and must be directly proportional to angular frequency. All other parameters are unitless.
def Lorentzian(w, ResFreq, Strength, Damping, Eps_Inf):
Permittivity = Eps_Inf*np.ones(len(w), dtype=np.complex)
for ii in range(len(ResFreq)):
Permittivity += Strength[ii]/( 1. - (w/ResFreq[ii])**2 - 1j*Damping[ii]*(w/ResFreq[ii]) )
return Permittivity
# Save w, n, k to YML file
def SaveYML(w_um, RefInd, filename, references='', comments=''):
header = np.empty(9, dtype=object)
header[0] = '# this file is part of refractiveindex.info database'
header[1] = '# refractiveindex.info database is in the public domain'
header[2] = '# copyright and related rights waived via CC0 1.0'
header[3] = ''
header[4] = 'REFERENCES:' + references
header[5] = 'COMMENTS:' + comments
header[6] = 'DATA:'
header[7] = ' - type: tabulated nk'
header[8] = ' data: |'
export = np.column_stack((w_um, np.real(RefInd), np.imag(RefInd)))
np.savetxt(filename, export, fmt='%4.2f %#.4g %#.4g', delimiter=' ', header='\n'.join(header), comments='',newline='\n ')
return
###############################################################################
## Wavelengths to sample ##
w_um_max = 80. # [um]
w_um_min = 10. # [um]
step_um = 0.05 # [um]
w_um, N_freq = w(w_um_max, w_um_min, step_um)
w_invcm = 10000./w_um
## ##
## Model Parameters ##
# See Table I
ResFreq = np.array([217., 316.]) # [cm^-1]
Strength = np.array([4.00, 0.07])
Damping = np.array([0.017, 0.25])
Eps_Inf = 2.07
## ##
## Generate and Save Data ##
eps = Lorentzian(w_invcm, ResFreq, Strength, Damping, Eps_Inf)
RefInd = np.sqrt(eps)
references = ' "W. Kaiser, W. G. Spitzer, R. H. Kaiser, and L. E. Howarth. Infrared Properties of CaF2, SrF2, and BaF2, <a href=\"https://doi.org/10.1103/PhysRev.127.1950\"><i>Phys. Rev.</i> <b>127</b>, 1950 (1962)</a>"'
comments = ' "Single crystal; Room temperature; Lorentz oscillator model parameters provided."'
SaveYML(w_um, RefInd, 'Kaiser-SrF2.yml', references, comments)
## ##
## Plotting ##
plt.figure('Figure 7 - n')
plt.plot(w_um, np.real(RefInd), label='SrF$_{2}$')
plt.legend(loc=1)
plt.xlim(10,80)
plt.ylim(0,14)
plt.figure('Figure 8 - k')
plt.plot(w_um, np.imag(RefInd), label='SrF$_{2}$')
plt.legend(loc=1)
plt.xlim(10,80)
plt.ylim(0,14)
## ##
|
polyanskiy/refractiveindex.info-scripts
|
scripts/Kaiser 1962 - SrF2.py
|
Python
|
gpl-3.0
| 3,299
|
[
"CRYSTAL"
] |
0135bc3a94f293f37aa89617e1211121ff00ef0d2f4124a72e63ffe76821d1e0
|
"""
This class deal with the relation between every three balls in n-dimensional world
"""
__author__ = 'Yinan Zhang'
__revision__ = '$Revision$'
import sys, os, math, time
sys.path.append('../basics/math')
from numpy.linalg import matrix_rank
from hyper_geometry import *
from l1_geometry import *
from Triangle import *
class Component:
def __init__(self, comp_dict):
self.dictionary = comp_dict;
def contains(self, sphere):
for triangle in self.dictionary.keys():
if sphere in triangle.spheres:
return True;
return False;
def spheres(self):
'''get all spheres in the component'''
spheres = {};
for tri in self.dictionary.keys():
for sphere in tri.spheres:
if not spheres.has_key(sphere):
spheres[sphere] = 1;
return spheres.keys();
class Nerve:
def __init__(self):
pass;
def __add2dict__(self, key, content, dictionary):
if dictionary.has_key( key ):
dictionary[key].append(content);
else:
dictionary[key] = [content];
def nerve(self, spheres):
'''Given a set of spheres
@return edges: (sphere1, sphere2) pairs
@return triangle_set: triangle set
@return graph_dict: dictionary{ sphere1:[sphere2, sphere3,...] }
@return edge_tri_dict: dictionary{ (sphere1, sphere2): triangle, .... }
@return sphere_tri_dict: dictionary{ sphere1: [triangle1, tri2...], ... }'''
edges = [];
triangle_set = [];
graph_dict = {};
edge_tri_dict = {};
sphere_tri_dict = {}
for i in range(0, len(spheres)):
sphere1 = spheres[i];
for j in range(0, len(spheres)):
sphere2 = spheres[j];
if not sphere1.intersects(sphere2) or sphere1 == sphere2:
continue;
if not (sphere1, sphere2) in edges:
edges.append( (sphere1, sphere2) );
self.__add2dict__(sphere1, sphere2, graph_dict);
for sphere3 in spheres:
if sphere1 == sphere3 or sphere2 == sphere3:
continue;
if sphere1.intersects(sphere3) and sphere2.intersects(sphere3):
triangle = Triangle(sphere1, sphere2, sphere3);
if triangle.is_filled():
triangle_set.append(triangle);
self.__add2dict__((sphere1,sphere2), triangle, edge_tri_dict);
self.__add2dict__((sphere2,sphere1), triangle, edge_tri_dict);
self.__add2dict__((sphere1,sphere3), triangle, edge_tri_dict);
self.__add2dict__((sphere3,sphere1), triangle, edge_tri_dict);
self.__add2dict__((sphere2,sphere3), triangle, edge_tri_dict);
self.__add2dict__((sphere3,sphere2), triangle, edge_tri_dict);
no_same_tri_set = [];
same = [];
for tri1 in triangle_set:
if tri1 in same:
continue;
no_same_tri_set.append(tri1);
for tri2 in triangle_set:
if tri1 == tri2:
continue;
if tri1.spheres[0] == tri2.spheres[0] or tri1.spheres[0] == tri2.spheres[1] or tri1.spheres[0] == tri2.spheres[2]:
if tri1.spheres[1] == tri2.spheres[0] or tri1.spheres[1] == tri2.spheres[1] or tri1.spheres[1] == tri2.spheres[2]:
if tri1.spheres[2] == tri2.spheres[0] or tri1.spheres[2] == tri2.spheres[1] or tri1.spheres[2] == tri2.spheres[2]:
#triangle_set.remove(tri2);
same.append(tri2);
print "initially we have {0} triangles".format(len(triangle_set))
for tri in no_same_tri_set:
self.__add2dict__(tri.spheres[0], tri, sphere_tri_dict);
self.__add2dict__(tri.spheres[1], tri, sphere_tri_dict);
self.__add2dict__(tri.spheres[2], tri, sphere_tri_dict);
return edges, no_same_tri_set, graph_dict, edge_tri_dict, sphere_tri_dict;
def build_topology_roadmap(self, components, graph_dict):
'''Build the topology roadmap of C-space.
@param components: contracted triangles (dictionaries).
@param graph_dict: relation between each sphere'''
def add2dict(dictionary, key, content):
connections = self.connections_between(key, content, graph_dict);
for i in range(0, connections):
dictionary[key].append( content );
#components = self.contract(triangle_set, edge_tri_dict);
new_comps = [];
for component in components:
new_comps.append(Component(component));
sphere_comp_dict = {}
new_graph = {}
for sphere in graph_dict.keys():
containing_component = self.containing_component(sphere, new_comps);
if containing_component is not None:
sphere_comp_dict[sphere] = containing_component;
for sphere in graph_dict.keys():
if not sphere_comp_dict.has_key(sphere): # This is a single sphere not in any component
new_graph[sphere] = [];
for neighbor in graph_dict[sphere]: # Loop every neighbor that connects with current sphere
if not sphere_comp_dict.has_key(neighbor):
add2dict(new_graph, sphere, neighbor)
elif not sphere_comp_dict[neighbor] in new_graph[sphere]:
add2dict(new_graph, sphere, sphere_comp_dict[neighbor]);
elif( not new_graph.has_key(sphere_comp_dict[sphere]) ):# the sphere is in a component
component = sphere_comp_dict[sphere]
if not new_graph.has_key(component):
new_graph[component] = [];
neighbors = self.component_neighbors(component, graph_dict)
for neighbor in neighbors:
if not sphere_comp_dict.has_key(neighbor):
add2dict(new_graph, component, neighbor)
elif not sphere_comp_dict[neighbor] in new_graph[component] and sphere_comp_dict[neighbor] != component:
add2dict(new_graph, component, sphere_comp_dict[neighbor])
return new_graph;
def GF2_matrix_rank( self, matrix, nrows, ncols ):
start_time = time.time();
rank = 0;
n = min(nrows, ncols)
for i in range(n):
''' Find the pivot '''
pivot_row = -1;
for k in range(i, nrows):
if matrix[k, i] == 1:
pivot_row = k;
break;
#print matrix;
#print pivot_row;
''' If there is no pivot, then go to the next row '''
if pivot_row == -1:
continue;
for j in range(ncols):
temp = matrix[i, j]
matrix[i,j] = matrix[pivot_row, j]
matrix[pivot_row, j] = temp
pivot_row = i
rank += 1;
for k in range(nrows):
if k == pivot_row or matrix[k, i] == 0:
continue;
for j in range(ncols):
matrix[k, j] = matrix[k, j] ^ matrix[pivot_row, j]
print '\t running time:{0}'.format( time.time() - start_time )
return rank;
def betti_number( self, triangle_set, edge_set, edge_tri_dict ):
'''Given some edges and triangles between edges, compute the first betti number.
Needs to make sure there is no (1,2), (2,1) kind of situations in the edge_set'''
vertices = [];
for edge in edge_set: # loop every edge
if not edge[0] in vertices: # put vertices in the vertices set
vertices.append(edge[0]);
if not edge[1] in vertices:
vertices.append(edge[1]);
print "Creating a {0} matrix".format((len(edge_set), len(triangle_set)))
matrix = numpy.zeros((len(edge_set), len(triangle_set) ), dtype='int32');
triangle_set_keys = triangle_set.keys()
triangle_mapping = {}
i = 0
for triangle in triangle_set_keys:
triangle_mapping[triangle] = i;
i += 1;
i = 0
for edge in edge_set:
triangles = edge_tri_dict[edge]
for triangle in triangles:
if triangle_mapping.has_key(triangle):
j = triangle_mapping[triangle]
matrix[i, j] = 1;
i += 1
#print "Before Gaussian Elimination:"
#print matrix, self.GF2_matrix_rank(matrix, len(edge_set), len(triangle_set))
#print "After Gaussian Elimination:"
#print matrix, matrix_rank(matrix)
return len(edge_set) - len(vertices) + 1 - self.GF2_matrix_rank(matrix, len(edge_set), len(triangle_set));
def contract(self, triangle_set, edge_tri_dict, sphere_tri_dict):
'''Contract a set of triangles to several sets of triangles, such that each set has first betti number of 0'''
visited_vertices = [];
dict_set = []; # we use a dictionary to store a set of triangles;
# The set of dictionaries is the set of contracted triangles.
used = {};
i = 0;
for triangle in triangle_set:
i+=1
if not used.has_key(triangle):
print "trying triangle: {0}".format(i);
# Do it recursively
#component = {};
#self.contrct_triangle_recursive(component, triangle, used, edge_tri_dict, sphere_tri_dict)
# Do it iteratively
component = self.contract_triangle(triangle, used, edge_tri_dict, sphere_tri_dict)
if len(component.keys()) > 0:
dict_set.append(component)
return dict_set;
def contrct_triangle_recursive( self, component, triangle, used, edge_tri_dict, sphere_tri_dict ):
'''Contract a triangle and its neighbor triangles'''
if used.has_key(triangle):
return;
component[triangle] = 1
used[triangle] = True
neighbors = self.find_component_neighbors(component, edge_tri_dict, sphere_tri_dict, used)
if len(neighbors) == 0:
return;
for neighbor in neighbors:
if not used.has_key(neighbor) and self.is_useful(component, neighbor, edge_tri_dict):
return self.contrct_triangle_recursive(component, neighbor, used, edge_tri_dict, sphere_tri_dict);
def contract_triangle(self, triangle, used, edge_tri_dict, sphere_tri_dict):
'''Contract a triangle and its neighbor triangles'''
neighbors = self.find_neighbor(triangle, edge_tri_dict, sphere_tri_dict, used)
component = {};
component[triangle] = 1
used[triangle] = True
found = True;
while found:
found = False;
for neighbor in neighbors.keys():
if not used.has_key(neighbor) and self.is_useful(component, neighbor, edge_tri_dict):
component[neighbor] = 1
used[neighbor] = True
#del neighbors[neighbor]
found = True;
new_neighbors = self.find_neighbor(neighbor, edge_tri_dict, sphere_tri_dict, used);
neighbors = new_neighbors
#for new_triangle in new_neighbors.keys():
# if not used.has_key(new_triangle) and not neighbors.has_key(new_triangle):
# neighbors[new_triangle] = 1
return component;
def is_useful(self, component, triangle, edge_tri_dict):
'''determine if a triangle can be added to current component without increasing 1st betti number.'''
component[triangle] = 1
edge_set = self.component_edges(component);
betti_number = self.betti_number(component, edge_set, edge_tri_dict);
print betti_number
if betti_number == 0:
del component[triangle]
return True;
del component[triangle]
return False;
def component_edges(self, component):
'''Get all edges of current component.'''
edge_set = {}
for triangle in component.keys():
for edge in triangle.edges():
(a, b) = edge
if not edge_set.has_key((a, b)) and not edge_set.has_key((b, a)):
edge_set[(a, b)] = 1
return edge_set.keys();
def find_component_neighbors( self, component, edge_tri_dict, sphere_tri_dict, used_triangles ):
'''find the neighbor triangle of a given component'''
neighbors = {};
for tri in component.keys():
tri_neighbors = self.find_neighbor(tri, edge_tri_dict, sphere_tri_dict, used_triangles);
for neighbor in tri_neighbors:
if not used_triangles.has_key(neighbor) and not neighbors.has_key(neighbor):
#print "find neighbor {0} for component".format(neighbor);
neighbors[neighbor] = 1;
return neighbors;
def find_neighbor(self, triangle, edge_tri_dict, sphere_tri_dict, used_triangles):
'''Find neighbor triangles of a given triangle'''
neighbors = {};
for sphere in triangle.spheres:
neighbor_tris = sphere_tri_dict[sphere];
for tri in neighbor_tris:
if not used_triangles.has_key( tri ) and tri != triangle and not neighbors.has_key(tri):
neighbors[tri] = 1;
'''
edges = triangle.edges();
for edge in edges:
if edge_tri_dict.has_key(edge):
for tri in edge_tri_dict[edge]:
if not neighbors.has_key(tri):
neighbors[tri] = 1;
'''
return neighbors
def component_neighbors(self, component, graph_dict):
'''get neighbors of a component'''
neighbors = {};
for sphere in component.spheres():
for neighbor in graph_dict[sphere]:
if not neighbors.has_key(neighbor):
neighbors[neighbor] = 1;
return neighbors.keys();
def containing_component(self, sphere, components):
'''Given a set of components, return the component that contains current sphere'''
for component in components:
if component.contains(sphere):
return component;
return None;
def connections_between( self, elem1, elem2, graph_dict ):
'''return the number of connections between the elem1 and the elem2'''
if (isinstance(elem1, hyper_sphere) or isinstance(elem1, l1_sphere)) and (isinstance(elem2, hyper_sphere) or isinstance(elem2, l1_sphere)):
return 1;
elif (isinstance(elem1, hyper_sphere) or isinstance(elem1, l1_sphere)) and isinstance(elem2, Component):
conn = 0;
for neighbor in graph_dict[elem1]:
if elem2.contains(neighbor):
conn += 1;
return conn;
elif isinstance(elem1, Component) and (isinstance(elem2, hyper_sphere) or isinstance(elem2, l1_sphere)):
conn = 0;
for neighbor in graph_dict[elem2]:
if elem1.contains(neighbor):
conn += 1;
return conn;
elif isinstance(elem1, Component) and isinstance(elem2, Component): ################## ==========================================
spheres = elem1.spheres();
conn = 1;
for sphere in spheres:
for neighbor in graph_dict[sphere]:
if elem2.contains(neighbor):
conn += 1;
return conn;
|
Yinan-Zhang/RichCSpace
|
alphashape/hyper_alpha_shape.py
|
Python
|
mit
| 13,140
|
[
"Gaussian"
] |
8103885ff542256cc96f792c16c2fc858d6b30b57df66f9849fb56a150bcbf63
|
import itertools
import logging
import re
import time
import urllib
from collections import defaultdict
from datetime import datetime, timedelta
from decimal import Decimal
from typing import Any, Callable, Dict, List, \
Optional, Set, Tuple, Type, Union
import pytz
from django.conf import settings
from django.urls import reverse
from django.db import connection
from django.db.models.query import QuerySet
from django.http import HttpRequest, HttpResponse, HttpResponseNotFound
from django.shortcuts import render
from django.template import loader
from django.utils.timezone import now as timezone_now, utc as timezone_utc
from django.utils.translation import ugettext as _
from django.core.validators import URLValidator
from django.core.exceptions import ValidationError
from jinja2 import Markup as mark_safe
from analytics.lib.counts import COUNT_STATS, CountStat
from analytics.lib.time_utils import time_range
from analytics.models import BaseCount, InstallationCount, \
RealmCount, StreamCount, UserCount, last_successful_fill, installation_epoch
from zerver.decorator import require_server_admin, require_server_admin_api, \
to_non_negative_int, to_utc_datetime, zulip_login_required, require_non_guest_user
from zerver.lib.exceptions import JsonableError
from zerver.lib.json_encoder_for_html import JSONEncoderForHTML
from zerver.lib.request import REQ, has_request_variables
from zerver.lib.response import json_success
from zerver.lib.timestamp import convert_to_UTC, timestamp_to_datetime
from zerver.lib.realm_icon import realm_icon_url
from zerver.views.invite import get_invitee_emails_set
from zerver.lib.subdomains import get_subdomain_from_hostname
from zerver.lib.actions import do_change_plan_type, do_deactivate_realm, \
do_reactivate_realm, do_scrub_realm
if settings.BILLING_ENABLED:
from corporate.lib.stripe import attach_discount_to_realm, get_discount_for_realm
from zerver.models import Client, get_realm, Realm, \
UserActivity, UserActivityInterval, UserProfile
if settings.ZILENCER_ENABLED:
from zilencer.models import RemoteInstallationCount, RemoteRealmCount, \
RemoteZulipServer
else:
from mock import Mock
RemoteInstallationCount = Mock() # type: ignore # https://github.com/JukkaL/mypy/issues/1188
RemoteZulipServer = Mock() # type: ignore # https://github.com/JukkaL/mypy/issues/1188
RemoteRealmCount = Mock() # type: ignore # https://github.com/JukkaL/mypy/issues/1188
def render_stats(request: HttpRequest, data_url_suffix: str, target_name: str,
for_installation: bool=False, remote: bool=False) -> HttpRequest:
page_params = dict(
data_url_suffix=data_url_suffix,
for_installation=for_installation,
remote=remote,
debug_mode=False,
)
return render(request,
'analytics/stats.html',
context=dict(target_name=target_name,
page_params=JSONEncoderForHTML().encode(page_params)))
@zulip_login_required
def stats(request: HttpRequest) -> HttpResponse:
realm = request.user.realm
if request.user.is_guest:
# TODO: Make @zulip_login_required pass the UserProfile so we
# can use @require_member_or_admin
raise JsonableError(_("Not allowed for guest users"))
return render_stats(request, '', realm.name or realm.string_id)
@require_server_admin
@has_request_variables
def stats_for_realm(request: HttpRequest, realm_str: str) -> HttpResponse:
try:
realm = get_realm(realm_str)
except Realm.DoesNotExist:
return HttpResponseNotFound("Realm %s does not exist" % (realm_str,))
return render_stats(request, '/realm/%s' % (realm_str,), realm.name or realm.string_id)
@require_server_admin
@has_request_variables
def stats_for_remote_realm(request: HttpRequest, remote_server_id: str,
remote_realm_id: str) -> HttpResponse:
server = RemoteZulipServer.objects.get(id=remote_server_id)
return render_stats(request, '/remote/%s/realm/%s' % (server.id, remote_realm_id),
"Realm %s on server %s" % (remote_realm_id, server.hostname))
@require_server_admin_api
@has_request_variables
def get_chart_data_for_realm(request: HttpRequest, user_profile: UserProfile,
realm_str: str, **kwargs: Any) -> HttpResponse:
try:
realm = get_realm(realm_str)
except Realm.DoesNotExist:
raise JsonableError(_("Invalid organization"))
return get_chart_data(request=request, user_profile=user_profile, realm=realm, **kwargs)
@require_server_admin_api
@has_request_variables
def get_chart_data_for_remote_realm(
request: HttpRequest, user_profile: UserProfile, remote_server_id: str,
remote_realm_id: str, **kwargs: Any) -> HttpResponse:
server = RemoteZulipServer.objects.get(id=remote_server_id)
return get_chart_data(request=request, user_profile=user_profile, server=server,
remote=True, remote_realm_id=int(remote_realm_id), **kwargs)
@require_server_admin
def stats_for_installation(request: HttpRequest) -> HttpResponse:
return render_stats(request, '/installation', 'Installation', True)
@require_server_admin
def stats_for_remote_installation(request: HttpRequest, remote_server_id: str) -> HttpResponse:
server = RemoteZulipServer.objects.get(id=remote_server_id)
return render_stats(request, '/remote/%s/installation' % (server.id,),
'remote Installation %s' % (server.hostname,), True, True)
@require_server_admin_api
@has_request_variables
def get_chart_data_for_installation(request: HttpRequest, user_profile: UserProfile,
chart_name: str=REQ(), **kwargs: Any) -> HttpResponse:
return get_chart_data(request=request, user_profile=user_profile, for_installation=True, **kwargs)
@require_server_admin_api
@has_request_variables
def get_chart_data_for_remote_installation(
request: HttpRequest,
user_profile: UserProfile,
remote_server_id: str,
chart_name: str=REQ(),
**kwargs: Any) -> HttpResponse:
server = RemoteZulipServer.objects.get(id=remote_server_id)
return get_chart_data(request=request, user_profile=user_profile, for_installation=True,
remote=True, server=server, **kwargs)
@require_non_guest_user
@has_request_variables
def get_chart_data(request: HttpRequest, user_profile: UserProfile, chart_name: str=REQ(),
min_length: Optional[int]=REQ(converter=to_non_negative_int, default=None),
start: Optional[datetime]=REQ(converter=to_utc_datetime, default=None),
end: Optional[datetime]=REQ(converter=to_utc_datetime, default=None),
realm: Optional[Realm]=None, for_installation: bool=False,
remote: bool=False, remote_realm_id: Optional[int]=None,
server: Optional[RemoteZulipServer]=None) -> HttpResponse:
if for_installation:
if remote:
aggregate_table = RemoteInstallationCount
assert server is not None
else:
aggregate_table = InstallationCount
else:
if remote:
aggregate_table = RemoteRealmCount
assert server is not None
assert remote_realm_id is not None
else:
aggregate_table = RealmCount
if chart_name == 'number_of_humans':
stats = [
COUNT_STATS['1day_actives::day'],
COUNT_STATS['realm_active_humans::day'],
COUNT_STATS['active_users_audit:is_bot:day']]
tables = [aggregate_table]
subgroup_to_label = {
stats[0]: {None: '_1day'},
stats[1]: {None: '_15day'},
stats[2]: {'false': 'all_time'}} # type: Dict[CountStat, Dict[Optional[str], str]]
labels_sort_function = None
include_empty_subgroups = True
elif chart_name == 'messages_sent_over_time':
stats = [COUNT_STATS['messages_sent:is_bot:hour']]
tables = [aggregate_table, UserCount]
subgroup_to_label = {stats[0]: {'false': 'human', 'true': 'bot'}}
labels_sort_function = None
include_empty_subgroups = True
elif chart_name == 'messages_sent_by_message_type':
stats = [COUNT_STATS['messages_sent:message_type:day']]
tables = [aggregate_table, UserCount]
subgroup_to_label = {stats[0]: {'public_stream': _('Public streams'),
'private_stream': _('Private streams'),
'private_message': _('Private messages'),
'huddle_message': _('Group private messages')}}
labels_sort_function = lambda data: sort_by_totals(data['everyone'])
include_empty_subgroups = True
elif chart_name == 'messages_sent_by_client':
stats = [COUNT_STATS['messages_sent:client:day']]
tables = [aggregate_table, UserCount]
# Note that the labels are further re-written by client_label_map
subgroup_to_label = {stats[0]:
{str(id): name for id, name in Client.objects.values_list('id', 'name')}}
labels_sort_function = sort_client_labels
include_empty_subgroups = False
else:
raise JsonableError(_("Unknown chart name: %s") % (chart_name,))
# Most likely someone using our API endpoint. The /stats page does not
# pass a start or end in its requests.
if start is not None:
start = convert_to_UTC(start)
if end is not None:
end = convert_to_UTC(end)
if start is not None and end is not None and start > end:
raise JsonableError(_("Start time is later than end time. Start: %(start)s, End: %(end)s") %
{'start': start, 'end': end})
if realm is None:
# Note that this value is invalid for Remote tables; be
# careful not to access it in those code paths.
realm = user_profile.realm
if remote:
# For remote servers, we don't have fillstate data, and thus
# should simply use the first and last data points for the
# table.
assert server is not None
if not aggregate_table.objects.filter(server=server).exists():
raise JsonableError(_("No analytics data available. Please contact your server administrator."))
if start is None:
start = aggregate_table.objects.filter(server=server).first().end_time
if end is None:
end = aggregate_table.objects.filter(server=server).last().end_time
else:
# Otherwise, we can use tables on the current server to
# determine a nice range, and some additional validation.
if start is None:
if for_installation:
start = installation_epoch()
else:
start = realm.date_created
if end is None:
end = max(last_successful_fill(stat.property) or
datetime.min.replace(tzinfo=timezone_utc) for stat in stats)
if start > end:
logging.warning("User from realm %s attempted to access /stats, but the computed "
"start time: %s (creation of realm or installation) is later than the computed "
"end time: %s (last successful analytics update). Is the "
"analytics cron job running?" % (realm.string_id, start, end))
raise JsonableError(_("No analytics data available. Please contact your server administrator."))
assert len(set([stat.frequency for stat in stats])) == 1
end_times = time_range(start, end, stats[0].frequency, min_length)
data = {'end_times': end_times, 'frequency': stats[0].frequency} # type: Dict[str, Any]
aggregation_level = {
InstallationCount: 'everyone',
RealmCount: 'everyone',
RemoteInstallationCount: 'everyone',
RemoteRealmCount: 'everyone',
UserCount: 'user',
}
# -1 is a placeholder value, since there is no relevant filtering on InstallationCount
id_value = {
InstallationCount: -1,
RealmCount: realm.id,
RemoteInstallationCount: server.id if server is not None else None,
# TODO: RemoteRealmCount logic doesn't correctly handle
# filtering by server_id as well.
RemoteRealmCount: remote_realm_id,
UserCount: user_profile.id,
}
for table in tables:
data[aggregation_level[table]] = {}
for stat in stats:
data[aggregation_level[table]].update(get_time_series_by_subgroup(
stat, table, id_value[table], end_times, subgroup_to_label[stat], include_empty_subgroups))
if labels_sort_function is not None:
data['display_order'] = labels_sort_function(data)
else:
data['display_order'] = None
return json_success(data=data)
def sort_by_totals(value_arrays: Dict[str, List[int]]) -> List[str]:
totals = [(sum(values), label) for label, values in value_arrays.items()]
totals.sort(reverse=True)
return [label for total, label in totals]
# For any given user, we want to show a fixed set of clients in the chart,
# regardless of the time aggregation or whether we're looking at realm or
# user data. This fixed set ideally includes the clients most important in
# understanding the realm's traffic and the user's traffic. This function
# tries to rank the clients so that taking the first N elements of the
# sorted list has a reasonable chance of doing so.
def sort_client_labels(data: Dict[str, Dict[str, List[int]]]) -> List[str]:
realm_order = sort_by_totals(data['everyone'])
user_order = sort_by_totals(data['user'])
label_sort_values = {} # type: Dict[str, float]
for i, label in enumerate(realm_order):
label_sort_values[label] = i
for i, label in enumerate(user_order):
label_sort_values[label] = min(i-.1, label_sort_values.get(label, i))
return [label for label, sort_value in sorted(label_sort_values.items(),
key=lambda x: x[1])]
def table_filtered_to_id(table: Type[BaseCount], key_id: int) -> QuerySet:
if table == RealmCount:
return RealmCount.objects.filter(realm_id=key_id)
elif table == UserCount:
return UserCount.objects.filter(user_id=key_id)
elif table == StreamCount:
return StreamCount.objects.filter(stream_id=key_id)
elif table == InstallationCount:
return InstallationCount.objects.all()
elif table == RemoteInstallationCount:
return RemoteInstallationCount.objects.filter(server_id=key_id)
elif table == RemoteRealmCount:
return RemoteRealmCount.objects.filter(realm_id=key_id)
else:
raise AssertionError("Unknown table: %s" % (table,))
def client_label_map(name: str) -> str:
if name == "website":
return "Website"
if name.startswith("desktop app"):
return "Old desktop app"
if name == "ZulipElectron":
return "Desktop app"
if name == "ZulipAndroid":
return "Old Android app"
if name == "ZulipiOS":
return "Old iOS app"
if name == "ZulipMobile":
return "Mobile app"
if name in ["ZulipPython", "API: Python"]:
return "Python API"
if name.startswith("Zulip") and name.endswith("Webhook"):
return name[len("Zulip"):-len("Webhook")] + " webhook"
return name
def rewrite_client_arrays(value_arrays: Dict[str, List[int]]) -> Dict[str, List[int]]:
mapped_arrays = {} # type: Dict[str, List[int]]
for label, array in value_arrays.items():
mapped_label = client_label_map(label)
if mapped_label in mapped_arrays:
for i in range(0, len(array)):
mapped_arrays[mapped_label][i] += value_arrays[label][i]
else:
mapped_arrays[mapped_label] = [value_arrays[label][i] for i in range(0, len(array))]
return mapped_arrays
def get_time_series_by_subgroup(stat: CountStat,
table: Type[BaseCount],
key_id: int,
end_times: List[datetime],
subgroup_to_label: Dict[Optional[str], str],
include_empty_subgroups: bool) -> Dict[str, List[int]]:
queryset = table_filtered_to_id(table, key_id).filter(property=stat.property) \
.values_list('subgroup', 'end_time', 'value')
value_dicts = defaultdict(lambda: defaultdict(int)) # type: Dict[Optional[str], Dict[datetime, int]]
for subgroup, end_time, value in queryset:
value_dicts[subgroup][end_time] = value
value_arrays = {}
for subgroup, label in subgroup_to_label.items():
if (subgroup in value_dicts) or include_empty_subgroups:
value_arrays[label] = [value_dicts[subgroup][end_time] for end_time in end_times]
if stat == COUNT_STATS['messages_sent:client:day']:
# HACK: We rewrite these arrays to collapse the Client objects
# with similar names into a single sum, and generally give
# them better names
return rewrite_client_arrays(value_arrays)
return value_arrays
eastern_tz = pytz.timezone('US/Eastern')
def make_table(title: str, cols: List[str], rows: List[Any], has_row_class: bool=False) -> str:
if not has_row_class:
def fix_row(row: Any) -> Dict[str, Any]:
return dict(cells=row, row_class=None)
rows = list(map(fix_row, rows))
data = dict(title=title, cols=cols, rows=rows)
content = loader.render_to_string(
'analytics/ad_hoc_query.html',
dict(data=data)
)
return content
def dictfetchall(cursor: connection.cursor) -> List[Dict[str, Any]]:
"Returns all rows from a cursor as a dict"
desc = cursor.description
return [
dict(list(zip([col[0] for col in desc], row)))
for row in cursor.fetchall()
]
def get_realm_day_counts() -> Dict[str, Dict[str, str]]:
query = '''
select
r.string_id,
(now()::date - pub_date::date) age,
count(*) cnt
from zerver_message m
join zerver_userprofile up on up.id = m.sender_id
join zerver_realm r on r.id = up.realm_id
join zerver_client c on c.id = m.sending_client_id
where
(not up.is_bot)
and
pub_date > now()::date - interval '8 day'
and
c.name not in ('zephyr_mirror', 'ZulipMonitoring')
group by
r.string_id,
age
order by
r.string_id,
age
'''
cursor = connection.cursor()
cursor.execute(query)
rows = dictfetchall(cursor)
cursor.close()
counts = defaultdict(dict) # type: Dict[str, Dict[int, int]]
for row in rows:
counts[row['string_id']][row['age']] = row['cnt']
result = {}
for string_id in counts:
raw_cnts = [counts[string_id].get(age, 0) for age in range(8)]
min_cnt = min(raw_cnts[1:])
max_cnt = max(raw_cnts[1:])
def format_count(cnt: int, style: Optional[str]=None) -> str:
if style is not None:
good_bad = style
elif cnt == min_cnt:
good_bad = 'bad'
elif cnt == max_cnt:
good_bad = 'good'
else:
good_bad = 'neutral'
return '<td class="number %s">%s</td>' % (good_bad, cnt)
cnts = (format_count(raw_cnts[0], 'neutral')
+ ''.join(map(format_count, raw_cnts[1:])))
result[string_id] = dict(cnts=cnts)
return result
def get_plan_name(plan_type: int) -> str:
return ['', 'self hosted', 'limited', 'standard', 'open source'][plan_type]
def realm_summary_table(realm_minutes: Dict[str, float]) -> str:
now = timezone_now()
query = '''
SELECT
realm.string_id,
realm.date_created,
realm.plan_type,
coalesce(user_counts.dau_count, 0) dau_count,
coalesce(wau_counts.wau_count, 0) wau_count,
(
SELECT
count(*)
FROM zerver_userprofile up
WHERE up.realm_id = realm.id
AND is_active
AND not is_bot
) user_profile_count,
(
SELECT
count(*)
FROM zerver_userprofile up
WHERE up.realm_id = realm.id
AND is_active
AND is_bot
) bot_count
FROM zerver_realm realm
LEFT OUTER JOIN
(
SELECT
up.realm_id realm_id,
count(distinct(ua.user_profile_id)) dau_count
FROM zerver_useractivity ua
JOIN zerver_userprofile up
ON up.id = ua.user_profile_id
WHERE
up.is_active
AND (not up.is_bot)
AND
query in (
'/json/send_message',
'send_message_backend',
'/api/v1/send_message',
'/json/update_pointer',
'/json/users/me/pointer',
'update_pointer_backend'
)
AND
last_visit > now() - interval '1 day'
GROUP BY realm_id
) user_counts
ON user_counts.realm_id = realm.id
LEFT OUTER JOIN
(
SELECT
realm_id,
count(*) wau_count
FROM (
SELECT
realm.id as realm_id,
up.delivery_email
FROM zerver_useractivity ua
JOIN zerver_userprofile up
ON up.id = ua.user_profile_id
JOIN zerver_realm realm
ON realm.id = up.realm_id
WHERE up.is_active
AND (not up.is_bot)
AND
ua.query in (
'/json/send_message',
'send_message_backend',
'/api/v1/send_message',
'/json/update_pointer',
'/json/users/me/pointer',
'update_pointer_backend'
)
GROUP by realm.id, up.delivery_email
HAVING max(last_visit) > now() - interval '7 day'
) as wau_users
GROUP BY realm_id
) wau_counts
ON wau_counts.realm_id = realm.id
WHERE EXISTS (
SELECT *
FROM zerver_useractivity ua
JOIN zerver_userprofile up
ON up.id = ua.user_profile_id
WHERE
up.realm_id = realm.id
AND up.is_active
AND (not up.is_bot)
AND
query in (
'/json/send_message',
'/api/v1/send_message',
'send_message_backend',
'/json/update_pointer',
'/json/users/me/pointer',
'update_pointer_backend'
)
AND
last_visit > now() - interval '2 week'
)
ORDER BY dau_count DESC, string_id ASC
'''
cursor = connection.cursor()
cursor.execute(query)
rows = dictfetchall(cursor)
cursor.close()
# Fetch all the realm administrator users
realm_admins = defaultdict(list) # type: Dict[str, List[str]]
for up in UserProfile.objects.select_related("realm").filter(
is_realm_admin=True,
is_active=True
):
realm_admins[up.realm.string_id].append(up.delivery_email)
for row in rows:
row['date_created_day'] = row['date_created'].strftime('%Y-%m-%d')
row['plan_type_string'] = get_plan_name(row['plan_type'])
row['age_days'] = int((now - row['date_created']).total_seconds()
/ 86400)
row['is_new'] = row['age_days'] < 12 * 7
row['realm_admin_email'] = ', '.join(realm_admins[row['string_id']])
# get messages sent per day
counts = get_realm_day_counts()
for row in rows:
try:
row['history'] = counts[row['string_id']]['cnts']
except Exception:
row['history'] = ''
# estimate annual subscription revenue
total_amount = 0
if settings.BILLING_ENABLED:
from corporate.lib.stripe import estimate_annual_recurring_revenue_by_realm
estimated_arrs = estimate_annual_recurring_revenue_by_realm()
for row in rows:
if row['string_id'] in estimated_arrs:
row['amount'] = estimated_arrs[row['string_id']]
total_amount += sum(estimated_arrs.values())
# augment data with realm_minutes
total_hours = 0.0
for row in rows:
string_id = row['string_id']
minutes = realm_minutes.get(string_id, 0.0)
hours = minutes / 60.0
total_hours += hours
row['hours'] = str(int(hours))
try:
row['hours_per_user'] = '%.1f' % (hours / row['dau_count'],)
except Exception:
pass
# formatting
for row in rows:
row['stats_link'] = realm_stats_link(row['string_id'])
row['string_id'] = realm_activity_link(row['string_id'])
# Count active sites
def meets_goal(row: Dict[str, int]) -> bool:
return row['dau_count'] >= 5
num_active_sites = len(list(filter(meets_goal, rows)))
# create totals
total_dau_count = 0
total_user_profile_count = 0
total_bot_count = 0
total_wau_count = 0
for row in rows:
total_dau_count += int(row['dau_count'])
total_user_profile_count += int(row['user_profile_count'])
total_bot_count += int(row['bot_count'])
total_wau_count += int(row['wau_count'])
total_row = dict(
string_id='Total',
plan_type_string="",
amount=total_amount,
stats_link = '',
date_created_day='',
realm_admin_email='',
dau_count=total_dau_count,
user_profile_count=total_user_profile_count,
bot_count=total_bot_count,
hours=int(total_hours),
wau_count=total_wau_count,
)
rows.insert(0, total_row)
content = loader.render_to_string(
'analytics/realm_summary_table.html',
dict(rows=rows, num_active_sites=num_active_sites,
now=now.strftime('%Y-%m-%dT%H:%M:%SZ'))
)
return content
def user_activity_intervals() -> Tuple[mark_safe, Dict[str, float]]:
day_end = timestamp_to_datetime(time.time())
day_start = day_end - timedelta(hours=24)
output = "Per-user online duration for the last 24 hours:\n"
total_duration = timedelta(0)
all_intervals = UserActivityInterval.objects.filter(
end__gte=day_start,
start__lte=day_end
).select_related(
'user_profile',
'user_profile__realm'
).only(
'start',
'end',
'user_profile__delivery_email',
'user_profile__realm__string_id'
).order_by(
'user_profile__realm__string_id',
'user_profile__delivery_email'
)
by_string_id = lambda row: row.user_profile.realm.string_id
by_email = lambda row: row.user_profile.delivery_email
realm_minutes = {}
for string_id, realm_intervals in itertools.groupby(all_intervals, by_string_id):
realm_duration = timedelta(0)
output += '<hr>%s\n' % (string_id,)
for email, intervals in itertools.groupby(realm_intervals, by_email):
duration = timedelta(0)
for interval in intervals:
start = max(day_start, interval.start)
end = min(day_end, interval.end)
duration += end - start
total_duration += duration
realm_duration += duration
output += " %-*s%s\n" % (37, email, duration)
realm_minutes[string_id] = realm_duration.total_seconds() / 60
output += "\nTotal Duration: %s\n" % (total_duration,)
output += "\nTotal Duration in minutes: %s\n" % (total_duration.total_seconds() / 60.,)
output += "Total Duration amortized to a month: %s" % (total_duration.total_seconds() * 30. / 60.,)
content = mark_safe('<pre>' + output + '</pre>')
return content, realm_minutes
def sent_messages_report(realm: str) -> str:
title = 'Recently sent messages for ' + realm
cols = [
'Date',
'Humans',
'Bots'
]
query = '''
select
series.day::date,
humans.cnt,
bots.cnt
from (
select generate_series(
(now()::date - interval '2 week'),
now()::date,
interval '1 day'
) as day
) as series
left join (
select
pub_date::date pub_date,
count(*) cnt
from zerver_message m
join zerver_userprofile up on up.id = m.sender_id
join zerver_realm r on r.id = up.realm_id
where
r.string_id = %s
and
(not up.is_bot)
and
pub_date > now() - interval '2 week'
group by
pub_date::date
order by
pub_date::date
) humans on
series.day = humans.pub_date
left join (
select
pub_date::date pub_date,
count(*) cnt
from zerver_message m
join zerver_userprofile up on up.id = m.sender_id
join zerver_realm r on r.id = up.realm_id
where
r.string_id = %s
and
up.is_bot
and
pub_date > now() - interval '2 week'
group by
pub_date::date
order by
pub_date::date
) bots on
series.day = bots.pub_date
'''
cursor = connection.cursor()
cursor.execute(query, [realm, realm])
rows = cursor.fetchall()
cursor.close()
return make_table(title, cols, rows)
def ad_hoc_queries() -> List[Dict[str, str]]:
def get_page(query: str, cols: List[str], title: str,
totals_columns: List[int]=[]) -> Dict[str, str]:
cursor = connection.cursor()
cursor.execute(query)
rows = cursor.fetchall()
rows = list(map(list, rows))
cursor.close()
def fix_rows(i: int,
fixup_func: Union[Callable[[Realm], mark_safe], Callable[[datetime], str]]) -> None:
for row in rows:
row[i] = fixup_func(row[i])
total_row = []
for i, col in enumerate(cols):
if col == 'Realm':
fix_rows(i, realm_activity_link)
elif col in ['Last time', 'Last visit']:
fix_rows(i, format_date_for_activity_reports)
elif col == 'Hostname':
for row in rows:
row[i] = remote_installation_stats_link(row[0], row[i])
if len(totals_columns) > 0:
if i == 0:
total_row.append("Total")
elif i in totals_columns:
total_row.append(str(sum(row[i] for row in rows if row[i] is not None)))
else:
total_row.append('')
if len(totals_columns) > 0:
rows.insert(0, total_row)
content = make_table(title, cols, rows)
return dict(
content=content,
title=title
)
pages = []
###
for mobile_type in ['Android', 'ZulipiOS']:
title = '%s usage' % (mobile_type,)
query = '''
select
realm.string_id,
up.id user_id,
client.name,
sum(count) as hits,
max(last_visit) as last_time
from zerver_useractivity ua
join zerver_client client on client.id = ua.client_id
join zerver_userprofile up on up.id = ua.user_profile_id
join zerver_realm realm on realm.id = up.realm_id
where
client.name like '%s'
group by string_id, up.id, client.name
having max(last_visit) > now() - interval '2 week'
order by string_id, up.id, client.name
''' % (mobile_type,)
cols = [
'Realm',
'User id',
'Name',
'Hits',
'Last time'
]
pages.append(get_page(query, cols, title))
###
title = 'Desktop users'
query = '''
select
realm.string_id,
client.name,
sum(count) as hits,
max(last_visit) as last_time
from zerver_useractivity ua
join zerver_client client on client.id = ua.client_id
join zerver_userprofile up on up.id = ua.user_profile_id
join zerver_realm realm on realm.id = up.realm_id
where
client.name like 'desktop%%'
group by string_id, client.name
having max(last_visit) > now() - interval '2 week'
order by string_id, client.name
'''
cols = [
'Realm',
'Client',
'Hits',
'Last time'
]
pages.append(get_page(query, cols, title))
###
title = 'Integrations by realm'
query = '''
select
realm.string_id,
case
when query like '%%external%%' then split_part(query, '/', 5)
else client.name
end client_name,
sum(count) as hits,
max(last_visit) as last_time
from zerver_useractivity ua
join zerver_client client on client.id = ua.client_id
join zerver_userprofile up on up.id = ua.user_profile_id
join zerver_realm realm on realm.id = up.realm_id
where
(query in ('send_message_backend', '/api/v1/send_message')
and client.name not in ('Android', 'ZulipiOS')
and client.name not like 'test: Zulip%%'
)
or
query like '%%external%%'
group by string_id, client_name
having max(last_visit) > now() - interval '2 week'
order by string_id, client_name
'''
cols = [
'Realm',
'Client',
'Hits',
'Last time'
]
pages.append(get_page(query, cols, title))
###
title = 'Integrations by client'
query = '''
select
case
when query like '%%external%%' then split_part(query, '/', 5)
else client.name
end client_name,
realm.string_id,
sum(count) as hits,
max(last_visit) as last_time
from zerver_useractivity ua
join zerver_client client on client.id = ua.client_id
join zerver_userprofile up on up.id = ua.user_profile_id
join zerver_realm realm on realm.id = up.realm_id
where
(query in ('send_message_backend', '/api/v1/send_message')
and client.name not in ('Android', 'ZulipiOS')
and client.name not like 'test: Zulip%%'
)
or
query like '%%external%%'
group by client_name, string_id
having max(last_visit) > now() - interval '2 week'
order by client_name, string_id
'''
cols = [
'Client',
'Realm',
'Hits',
'Last time'
]
pages.append(get_page(query, cols, title))
title = 'Remote Zulip servers'
query = '''
with icount as (
select
server_id,
max(value) as max_value,
max(end_time) as max_end_time
from zilencer_remoteinstallationcount
where
property='active_users:is_bot:day'
and subgroup='false'
group by server_id
),
remote_push_devices as (
select server_id, count(distinct(user_id)) as push_user_count from zilencer_remotepushdevicetoken
group by server_id
)
select
rserver.id,
rserver.hostname,
rserver.contact_email,
max_value,
push_user_count,
max_end_time
from zilencer_remotezulipserver rserver
left join icount on icount.server_id = rserver.id
left join remote_push_devices on remote_push_devices.server_id = rserver.id
order by max_value DESC NULLS LAST, push_user_count DESC NULLS LAST
'''
cols = [
'ID',
'Hostname',
'Contact email',
'Analytics users',
'Mobile users',
'Last update time',
]
pages.append(get_page(query, cols, title,
totals_columns=[3, 4]))
return pages
@require_server_admin
@has_request_variables
def get_activity(request: HttpRequest) -> HttpResponse:
duration_content, realm_minutes = user_activity_intervals() # type: Tuple[mark_safe, Dict[str, float]]
counts_content = realm_summary_table(realm_minutes) # type: str
data = [
('Counts', counts_content),
('Durations', duration_content),
]
for page in ad_hoc_queries():
data.append((page['title'], page['content']))
title = 'Activity'
return render(
request,
'analytics/activity.html',
context=dict(data=data, title=title, is_home=True),
)
@require_server_admin
def support(request: HttpRequest) -> HttpResponse:
context = {} # type: Dict[str, Any]
if settings.BILLING_ENABLED and request.method == "POST":
realm_id = request.POST.get("realm_id", None)
realm = Realm.objects.get(id=realm_id)
new_plan_type = request.POST.get("plan_type", None)
if new_plan_type is not None:
new_plan_type = int(new_plan_type)
current_plan_type = realm.plan_type
do_change_plan_type(realm, new_plan_type)
msg = "Plan type of {} changed from {} to {} ".format(realm.name,
get_plan_name(current_plan_type),
get_plan_name(new_plan_type))
context["message"] = msg
new_discount = request.POST.get("discount", None)
if new_discount is not None:
new_discount = Decimal(new_discount)
current_discount = get_discount_for_realm(realm)
attach_discount_to_realm(realm, new_discount)
msg = "Discount of {} changed to {} from {} ".format(realm.name, new_discount, current_discount)
context["message"] = msg
status = request.POST.get("status", None)
if status is not None:
if status == "active":
do_reactivate_realm(realm)
context["message"] = "{} reactivated.".format(realm.name)
elif status == "deactivated":
do_deactivate_realm(realm, request.user)
context["message"] = "{} deactivated.".format(realm.name)
scrub_realm = request.POST.get("scrub_realm", None)
if scrub_realm is not None:
if scrub_realm == "scrub_realm":
do_scrub_realm(realm)
context["message"] = "{} scrubbed.".format(realm.name)
query = request.GET.get("q", None)
if query:
key_words = get_invitee_emails_set(query)
users = UserProfile.objects.filter(delivery_email__in=key_words)
if users:
for user in users:
user.realm.realm_icon_url = realm_icon_url(user.realm)
user.realm.admin_emails = ", ".join(
user.realm.get_human_admin_users().values_list(
"delivery_email",
flat=True))
user.realm.default_discount = get_discount_for_realm(user.realm)
context["users"] = users
realms = set(Realm.objects.filter(string_id__in=key_words))
for key_word in key_words:
try:
URLValidator()(key_word)
parse_result = urllib.parse.urlparse(key_word)
hostname = parse_result.hostname
if parse_result.port:
hostname = "{}:{}".format(hostname, parse_result.port)
subdomain = get_subdomain_from_hostname(hostname)
try:
realms.add(get_realm(subdomain))
except Realm.DoesNotExist:
pass
except ValidationError:
pass
if realms:
for realm in realms:
realm.realm_icon_url = realm_icon_url(realm)
realm.admin_emails = ", ".join(realm.get_human_admin_users().values_list(
"delivery_email", flat=True))
realm.default_discount = get_discount_for_realm(realm)
context["realms"] = realms
return render(request, 'analytics/support.html', context=context)
def get_user_activity_records_for_realm(realm: str, is_bot: bool) -> QuerySet:
fields = [
'user_profile__full_name',
'user_profile__delivery_email',
'query',
'client__name',
'count',
'last_visit',
]
records = UserActivity.objects.filter(
user_profile__realm__string_id=realm,
user_profile__is_active=True,
user_profile__is_bot=is_bot
)
records = records.order_by("user_profile__delivery_email", "-last_visit")
records = records.select_related('user_profile', 'client').only(*fields)
return records
def get_user_activity_records_for_email(email: str) -> List[QuerySet]:
fields = [
'user_profile__full_name',
'query',
'client__name',
'count',
'last_visit'
]
records = UserActivity.objects.filter(
user_profile__delivery_email=email
)
records = records.order_by("-last_visit")
records = records.select_related('user_profile', 'client').only(*fields)
return records
def raw_user_activity_table(records: List[QuerySet]) -> str:
cols = [
'query',
'client',
'count',
'last_visit'
]
def row(record: QuerySet) -> List[Any]:
return [
record.query,
record.client.name,
record.count,
format_date_for_activity_reports(record.last_visit)
]
rows = list(map(row, records))
title = 'Raw Data'
return make_table(title, cols, rows)
def get_user_activity_summary(records: List[QuerySet]) -> Dict[str, Dict[str, Any]]:
#: `Any` used above should be `Union(int, datetime)`.
#: However current version of `Union` does not work inside other function.
#: We could use something like:
# `Union[Dict[str, Dict[str, int]], Dict[str, Dict[str, datetime]]]`
#: but that would require this long `Union` to carry on throughout inner functions.
summary = {} # type: Dict[str, Dict[str, Any]]
def update(action: str, record: QuerySet) -> None:
if action not in summary:
summary[action] = dict(
count=record.count,
last_visit=record.last_visit
)
else:
summary[action]['count'] += record.count
summary[action]['last_visit'] = max(
summary[action]['last_visit'],
record.last_visit
)
if records:
summary['name'] = records[0].user_profile.full_name
for record in records:
client = record.client.name
query = record.query
update('use', record)
if client == 'API':
m = re.match('/api/.*/external/(.*)', query)
if m:
client = m.group(1)
update(client, record)
if client.startswith('desktop'):
update('desktop', record)
if client == 'website':
update('website', record)
if ('send_message' in query) or re.search('/api/.*/external/.*', query):
update('send', record)
if query in ['/json/update_pointer', '/json/users/me/pointer', '/api/v1/update_pointer',
'update_pointer_backend']:
update('pointer', record)
update(client, record)
return summary
def format_date_for_activity_reports(date: Optional[datetime]) -> str:
if date:
return date.astimezone(eastern_tz).strftime('%Y-%m-%d %H:%M')
else:
return ''
def user_activity_link(email: str) -> mark_safe:
url_name = 'analytics.views.get_user_activity'
url = reverse(url_name, kwargs=dict(email=email))
email_link = '<a href="%s">%s</a>' % (url, email)
return mark_safe(email_link)
def realm_activity_link(realm_str: str) -> mark_safe:
url_name = 'analytics.views.get_realm_activity'
url = reverse(url_name, kwargs=dict(realm_str=realm_str))
realm_link = '<a href="%s">%s</a>' % (url, realm_str)
return mark_safe(realm_link)
def realm_stats_link(realm_str: str) -> mark_safe:
url_name = 'analytics.views.stats_for_realm'
url = reverse(url_name, kwargs=dict(realm_str=realm_str))
stats_link = '<a href="{}"><i class="fa fa-pie-chart"></i></a>'.format(url, realm_str)
return mark_safe(stats_link)
def remote_installation_stats_link(server_id: int, hostname: str) -> mark_safe:
url_name = 'analytics.views.stats_for_remote_installation'
url = reverse(url_name, kwargs=dict(remote_server_id=server_id))
stats_link = '<a href="{}"><i class="fa fa-pie-chart"></i>{}</a>'.format(url, hostname)
return mark_safe(stats_link)
def realm_client_table(user_summaries: Dict[str, Dict[str, Dict[str, Any]]]) -> str:
exclude_keys = [
'internal',
'name',
'use',
'send',
'pointer',
'website',
'desktop',
]
rows = []
for email, user_summary in user_summaries.items():
email_link = user_activity_link(email)
name = user_summary['name']
for k, v in user_summary.items():
if k in exclude_keys:
continue
client = k
count = v['count']
last_visit = v['last_visit']
row = [
format_date_for_activity_reports(last_visit),
client,
name,
email_link,
count,
]
rows.append(row)
rows = sorted(rows, key=lambda r: r[0], reverse=True)
cols = [
'Last visit',
'Client',
'Name',
'Email',
'Count',
]
title = 'Clients'
return make_table(title, cols, rows)
def user_activity_summary_table(user_summary: Dict[str, Dict[str, Any]]) -> str:
rows = []
for k, v in user_summary.items():
if k == 'name':
continue
client = k
count = v['count']
last_visit = v['last_visit']
row = [
format_date_for_activity_reports(last_visit),
client,
count,
]
rows.append(row)
rows = sorted(rows, key=lambda r: r[0], reverse=True)
cols = [
'last_visit',
'client',
'count',
]
title = 'User Activity'
return make_table(title, cols, rows)
def realm_user_summary_table(all_records: List[QuerySet],
admin_emails: Set[str]) -> Tuple[Dict[str, Dict[str, Any]], str]:
user_records = {}
def by_email(record: QuerySet) -> str:
return record.user_profile.delivery_email
for email, records in itertools.groupby(all_records, by_email):
user_records[email] = get_user_activity_summary(list(records))
def get_last_visit(user_summary: Dict[str, Dict[str, datetime]], k: str) -> Optional[datetime]:
if k in user_summary:
return user_summary[k]['last_visit']
else:
return None
def get_count(user_summary: Dict[str, Dict[str, str]], k: str) -> str:
if k in user_summary:
return user_summary[k]['count']
else:
return ''
def is_recent(val: Optional[datetime]) -> bool:
age = timezone_now() - val
return age.total_seconds() < 5 * 60
rows = []
for email, user_summary in user_records.items():
email_link = user_activity_link(email)
sent_count = get_count(user_summary, 'send')
cells = [user_summary['name'], email_link, sent_count]
row_class = ''
for field in ['use', 'send', 'pointer', 'desktop', 'ZulipiOS', 'Android']:
visit = get_last_visit(user_summary, field)
if field == 'use':
if visit and is_recent(visit):
row_class += ' recently_active'
if email in admin_emails:
row_class += ' admin'
val = format_date_for_activity_reports(visit)
cells.append(val)
row = dict(cells=cells, row_class=row_class)
rows.append(row)
def by_used_time(row: Dict[str, Any]) -> str:
return row['cells'][3]
rows = sorted(rows, key=by_used_time, reverse=True)
cols = [
'Name',
'Email',
'Total sent',
'Heard from',
'Message sent',
'Pointer motion',
'Desktop',
'ZulipiOS',
'Android',
]
title = 'Summary'
content = make_table(title, cols, rows, has_row_class=True)
return user_records, content
@require_server_admin
def get_realm_activity(request: HttpRequest, realm_str: str) -> HttpResponse:
data = [] # type: List[Tuple[str, str]]
all_user_records = {} # type: Dict[str, Any]
try:
admins = Realm.objects.get(string_id=realm_str).get_human_admin_users()
except Realm.DoesNotExist:
return HttpResponseNotFound("Realm %s does not exist" % (realm_str,))
admin_emails = {admin.delivery_email for admin in admins}
for is_bot, page_title in [(False, 'Humans'), (True, 'Bots')]:
all_records = list(get_user_activity_records_for_realm(realm_str, is_bot))
user_records, content = realm_user_summary_table(all_records, admin_emails)
all_user_records.update(user_records)
data += [(page_title, content)]
page_title = 'Clients'
content = realm_client_table(all_user_records)
data += [(page_title, content)]
page_title = 'History'
content = sent_messages_report(realm_str)
data += [(page_title, content)]
title = realm_str
return render(
request,
'analytics/activity.html',
context=dict(data=data, realm_link=None, title=title),
)
@require_server_admin
def get_user_activity(request: HttpRequest, email: str) -> HttpResponse:
records = get_user_activity_records_for_email(email)
data = [] # type: List[Tuple[str, str]]
user_summary = get_user_activity_summary(records)
content = user_activity_summary_table(user_summary)
data += [('Summary', content)]
content = raw_user_activity_table(records)
data += [('Info', content)]
title = email
return render(
request,
'analytics/activity.html',
context=dict(data=data, title=title),
)
|
tommyip/zulip
|
analytics/views.py
|
Python
|
apache-2.0
| 51,930
|
[
"VisIt"
] |
fbade33b1d93e2c8c34ab489dda41ed2e847555039f287195b1a77e8a7f71600
|
#!/usr/bin/env python
############################################################################
# Copyright (c) 2015-2019 Saint Petersburg State University
# Copyright (c) 2011-2014 Saint Petersburg Academic University
# All Rights Reserved
# See file LICENSE for details.
############################################################################
import os
import shutil
import sys
from distutils import dir_util
from site import addsitedir
from stages import stage
import support
from process_cfg import merge_configs
import commands_parser
import options_storage
def prepare_config_corr(filename, cfg, ext_python_modules_home):
addsitedir(ext_python_modules_home)
if sys.version.startswith("2."):
import pyyaml2 as pyyaml
elif sys.version.startswith("3."):
import pyyaml3 as pyyaml
data = pyyaml.load(open(filename))
data["dataset"] = cfg.dataset
data["output_dir"] = cfg.output_dir
data["work_dir"] = cfg.tmp_dir
# data["hard_memory_limit"] = cfg.max_memory
data["max_nthreads"] = cfg.max_threads
data["bwa"] = cfg.bwa
with open(filename, 'w') as file_c:
pyyaml.dump(data, file_c,
default_flow_style=False, default_style='"', width=float("inf"))
class CorrectionIterationStage(stage.Stage):
def __init__(self, cfg, assembly_type, corrected, assembled, *args):
super(CorrectionIterationStage, self).__init__(*args)
self.assembly_type = assembly_type
self.corrected = corrected
self.assembled = assembled
self.STAGE_NAME = "Mismatch correction %s" % assembly_type
self.tmp_dir_for_corrector = os.path.join(cfg["common"].output_dir, "mismatch_corrector", self.assembly_type)
cfg["mismatch_corrector"].__dict__["output_dir"] = self.tmp_dir_for_corrector
self.cfg = merge_configs(cfg["mismatch_corrector"], cfg["common"])
def get_command(self, cfg):
args = [os.path.join(self.python_modules_home, "spades_pipeline", "scripts", "correction_iteration_script.py"),
"--corrected", self.corrected,
"--assembled", self.assembled,
"--assembly_type", self.assembly_type,
"--output_dir", cfg["common"].output_dir,
"--bin_home", self.bin_home]
return [commands_parser.Command(STAGE=self.STAGE_NAME,
path=sys.executable,
args=args,
config_dir=os.path.relpath(self.cfg.output_dir, options_storage.args.output_dir),
short_name=self.short_name,
del_after=[os.path.join(self.cfg.output_dir, "tmp"),
self.cfg.tmp_dir])]
def generate_config(self, cfg):
dst_configs = os.path.join(self.cfg.output_dir, "configs")
if os.path.isdir(dst_configs):
shutil.rmtree(dst_configs)
dir_util.copy_tree(os.path.join(self.tmp_configs_dir, "corrector"), dst_configs, preserve_times=False)
cfg_file_name = os.path.join(dst_configs, "corrector.info")
self.cfg.tmp_dir = support.get_tmp_dir(prefix="corrector_")
prepare_config_corr(cfg_file_name, self.cfg, self.ext_python_modules_home)
class CorrectionStage(stage.Stage):
stages = []
STAGE_NAME = "Mismatch correction"
def __init__(self, cfg, *args):
super(CorrectionStage, self).__init__(*args)
cfg["mismatch_corrector"].__dict__["dataset"] = cfg["dataset"].yaml_filename
to_correct = dict()
to_correct["contigs"] = \
(self.output_files["result_contigs_filename"], self.output_files["assembled_contigs_filename"])
to_correct["scaffolds"] = \
(self.output_files["result_scaffolds_filename"], self.output_files["assembled_scaffolds_filename"])
for assembly_type, (corrected, assembled) in to_correct.items():
self.stages.append(CorrectionIterationStage(cfg, assembly_type, corrected, assembled,
"mc_%s" % assembly_type,
self.output_files,
self.tmp_configs_dir, self.dataset_data, self.log,
self.bin_home, self.ext_python_modules_home,
self.python_modules_home))
def generate_config(self, cfg):
for stage in self.stages:
stage.generate_config(cfg)
def get_command(self, cfg):
return [commands_parser.Command(STAGE=self.STAGE_NAME,
path="true",
args=[],
short_name=self.short_name + "_start")] + \
[x for stage in self.stages for x in stage.get_command(cfg)] + \
[commands_parser.Command(STAGE=self.STAGE_NAME,
path="true",
args=[],
short_name=self.short_name + "_finish")]
def add_to_pipeline(pipeline, cfg, output_files, tmp_configs_dir, dataset_data, log, bin_home,
ext_python_modules_home, python_modules_home):
if "assembly" in cfg and "mismatch_corrector" in cfg:
pipeline.add(CorrectionStage(cfg, "mc", output_files, tmp_configs_dir, dataset_data,
log, bin_home, ext_python_modules_home, python_modules_home))
|
B-UMMI/INNUca
|
src/SPAdes-3.14.0-Linux/share/spades/spades_pipeline/stages/correction_stage.py
|
Python
|
gpl-3.0
| 5,676
|
[
"BWA"
] |
d10a5208aff33e66b4581bebb9bc618afd7f81fd1c3f34144394eacb83d70f19
|
# coding: utf-8
# Copyright (c) Pymatgen Development Team.
# Distributed under the terms of the MIT License.
import warnings
import unittest
import os
from pymatgen.alchemy.transmuters import CifTransmuter, PoscarTransmuter
from pymatgen.alchemy.filters import ContainsSpecieFilter
from pymatgen.transformations.standard_transformations import \
SubstitutionTransformation, RemoveSpeciesTransformation, \
OrderDisorderedStructureTransformation
from pymatgen.transformations.advanced_transformations import \
SuperTransformation
'''
Created on Mar 5, 2012
'''
__author__ = "Shyue Ping Ong"
__copyright__ = "Copyright 2012, The Materials Project"
__version__ = "0.1"
__maintainer__ = "Shyue Ping Ong"
__email__ = "shyuep@gmail.com"
__date__ = "Mar 5, 2012"
test_dir = os.path.join(os.path.dirname(__file__), "..", "..", "..",
'test_files')
class CifTransmuterTest(unittest.TestCase):
def setUp(self):
warnings.simplefilter("ignore")
def tearDown(self):
warnings.simplefilter("default")
def test_init(self):
trans = []
trans.append(SubstitutionTransformation({"Fe": "Mn", "Fe2+": "Mn2+"}))
tsc = CifTransmuter.from_filenames([os.path.join(test_dir,
"MultiStructure.cif")],
trans)
self.assertEqual(len(tsc), 2)
expected_ans = set(["Mn", "O", "Li", "P"])
for s in tsc:
els = set([el.symbol
for el in s.final_structure.composition.elements])
self.assertEqual(expected_ans, els)
class PoscarTransmuterTest(unittest.TestCase):
def test_init(self):
trans = []
trans.append(SubstitutionTransformation({"Fe": "Mn"}))
tsc = PoscarTransmuter.from_filenames([os.path.join(test_dir,
"POSCAR"),
os.path.join(test_dir,
"POSCAR")],
trans)
self.assertEqual(len(tsc), 2)
expected_ans = set(["Mn", "O", "P"])
for s in tsc:
els = set([el.symbol
for el in s.final_structure.composition.elements])
self.assertEqual(expected_ans, els)
def test_transmuter(self):
tsc = PoscarTransmuter.from_filenames(
[os.path.join(test_dir, "POSCAR")])
tsc.append_transformation(RemoveSpeciesTransformation('O'))
self.assertEqual(len(tsc[0].final_structure), 8)
tsc.append_transformation(SubstitutionTransformation({"Fe":
{"Fe2+": 0.25,
"Mn3+": .75},
"P": "P5+"}))
tsc.append_transformation(OrderDisorderedStructureTransformation(),
extend_collection=50)
self.assertEqual(len(tsc), 4)
t = SuperTransformation([SubstitutionTransformation({"Fe2+": "Mg2+"}),
SubstitutionTransformation({"Fe2+": "Zn2+"}),
SubstitutionTransformation({"Fe2+": "Be2+"})])
tsc.append_transformation(t, extend_collection=True)
self.assertEqual(len(tsc), 12)
for x in tsc:
self.assertEqual(len(x), 5, 'something might be wrong with the number of transformations in the history') #should be 4 trans + starting structure
#test the filter
tsc.apply_filter(ContainsSpecieFilter(['Zn2+', 'Be2+', 'Mn4+'],
strict_compare=True, AND=False))
self.assertEqual(len(tsc), 8)
self.assertEqual(tsc.transformed_structures[0].as_dict()[
'history'][-1]['@class'], 'ContainsSpecieFilter')
tsc.apply_filter(ContainsSpecieFilter(['Be2+']))
self.assertEqual(len(tsc), 4)
#Test set_parameter and add_tag.
tsc.set_parameter("para1", "hello")
self.assertEqual(tsc.transformed_structures[0]
.as_dict()['other_parameters']['para1'], 'hello')
tsc.add_tags(["world", "universe"])
self.assertEqual(tsc.transformed_structures[0]
.as_dict()['other_parameters']['tags'],
["world", "universe"])
if __name__ == "__main__":
#import sys;sys.argv = ['', 'Test.testName']
unittest.main()
|
dongsenfo/pymatgen
|
pymatgen/alchemy/tests/test_transmuters.py
|
Python
|
mit
| 4,616
|
[
"pymatgen"
] |
32824dba742a855973a7a9110eae22af6e70c21ca5ea1720a704dbab6ccdd799
|
"""This file provides enhanced support for editing Python files
Nothing is done if the projects do not support python, otherwise, the
following are provided:
- Create highlight rules for python files
- Defines a convenient filter "Python File" to use when defining your
own actions
- New menu to reload the current script. This menu is only visible when
editing a python file.
- Easy access to standard python library through shift-F3
- Easy access to user-defined GPS configuration scripts through shift-F3
This is always active, even if the current project doesn't support
python
- Add links to python documentation on the internet
"""
############################################################################
# No user customization below this line
############################################################################
# To be added (from idle environment)
# - "indent region", "dedent region", "check module", "run module"
# - "class browser" -> project view in GPS
import GPS
import sys
import ast
import os.path
import gps_utils
import os_utils
from constructs import CAT_FUNCTION, VISIBILITY_PUBLIC, CAT_PARAMETER, \
VISIBILITY_PRIVATE, CAT_TYPE, CAT_LOOP_STATEMENT, CAT_IF_STATEMENT
import text_utils
try:
from gi.repository import Gtk
has_pygtk = 1
except ImportError:
Gtk = None
has_pygtk = 0
def get_last_body_statement(node):
if hasattr(node, "body"):
return get_last_body_statement(node.body[-1])
else:
return node
# noinspection PyPep8Naming
class ASTVisitor(ast.NodeVisitor):
def __init__(self, bufstr, clist):
self.buflines = bufstr.splitlines()
self.lines_offsets = [0 for _ in self.buflines]
for i in range(1, len(self.buflines)):
self.lines_offsets[i] = (self.lines_offsets[i - 1] +
len(self.buflines[i - 1]) + 1)
self.clist = clist
def get_offset(self, lineno, col):
return self.lines_offsets[lineno - 1] + col + 1
def make_tuple(self, line, col):
return line, col, self.get_offset(line, col)
def get_locations(self, n, kw=None):
end_line = n.end_line
start_pos = self.make_tuple(n.lineno, n.col_offset)
end_col = len(self.buflines[end_line - 1]) - 1
end_pos = self.make_tuple(end_line, end_col)
if kw:
entity_pos = self.make_tuple(n.lineno, n.col_offset + len(kw))
return start_pos, end_pos, entity_pos
else:
return start_pos, end_pos
@staticmethod
def make_fn_profile(fn_node):
args = fn_node.args
argsd = (a.id for a in args.args)
profile = "({0})".format(
", ".join(argsd) +
(", %s" % args.vararg if args.vararg else "") +
(", %s" % args.kwarg if args.kwarg else "")
)
return profile
def visit_FunctionDef(self, n):
self.generic_visit(n)
start_pos, end_pos, entity_pos = self.get_locations(n, "def ")
self.clist.add_construct(
CAT_FUNCTION, False, VISIBILITY_PUBLIC, n.name, "",
start_pos, end_pos, entity_pos
)
def visit_Name(self, node):
start_pos = self.make_tuple(node.lineno, node.col_offset)
if isinstance(node.ctx, ast.Param):
self.clist.add_construct(
CAT_PARAMETER, False, VISIBILITY_PRIVATE, node.id, "",
start_pos, start_pos, start_pos
)
def generic_visit(self, n):
ast.NodeVisitor.generic_visit(self, n)
if getattr(n, "lineno", None):
end_line = n.lineno
for node_name in n._fields:
_node = getattr(n, node_name)
node = _node
if isinstance(_node, list):
if not _node:
continue
node = _node[-1]
end_line = max(end_line, getattr(node, "end_line", 0))
n.end_line = end_line
else:
n.end_line = None
def visit_ClassDef(self, n):
self.generic_visit(n)
start_pos, end_pos, entity_pos = self.get_locations(n, "class ")
self.clist.add_construct(
CAT_TYPE, False, VISIBILITY_PUBLIC, n.name, "",
start_pos, end_pos, entity_pos
)
def add_private_construct(self, n, constructs_cat):
self.generic_visit(n)
start_pos, end_pos = self.get_locations(n)
self.clist.add_construct(
constructs_cat, False, VISIBILITY_PRIVATE, "", "",
start_pos, end_pos, start_pos
)
def visit_While(self, n):
self.add_private_construct(n, CAT_LOOP_STATEMENT)
def visit_If(self, n):
self.add_private_construct(n, CAT_IF_STATEMENT)
def visit_For(self, n):
self.add_private_construct(n, CAT_LOOP_STATEMENT)
# noinspection PyMethodMayBeStatic
class PythonLanguage(GPS.Language):
def __init__(self):
pass
def parse_constructs(self, constructs_list, gps_file, string):
del gps_file
try:
tree = ast.parse(string)
tree.lineno = 0
ASTVisitor(string, constructs_list).visit(tree)
except SyntaxError:
pass
class PythonSupport(object):
def __init__(self):
"""
Various initializations done before the gps_started hook
"""
self.port_pref = GPS.Preference("Documentation:Python/port")
self.port_pref.create(
"Pydoc port", "integer",
"Port that should be used when spawning the pydoc daemon. "
"This is a small local server to which your web browser "
"connects to display the documentation for the standard "
"python library. It is accessed through the /Python menu when "
"editing a python file",
9432)
# Add the language definition before the gps_started hook, so that
# python files are correctly found
GPS.Language.register(PythonLanguage(), "Python", ".py", "", ".pyc")
XML = """
<filter_and name="Python file">
<filter id="Source editor" />
<filter language="Python" />
</filter_and>
<documentation_file>
<name>http://docs.python.org/2/tutorial/</name>
<descr>Python tutorial</descr>
<menu>/Help/Python/Python Tutorial</menu>
<category>Scripts</category>
</documentation_file>
"""
if Gtk:
XML += """
<documentation_file>
<name>http://www.pygtk.org/pygtk2tutorial/index.html</name>
<descr>PyGTK tutorial</descr>
<menu>/Help/Python/PyGTK Tutorial</menu>
<category>Scripts</category>
</documentation_file>
<documentation_file>
<name>http://www.pygtk.org/pygtk2reference/index.html</name>
<descr>PyGTK Reference Manual</descr>
<menu>/Help/Python/PyGTK Reference Manual</menu>
<category>Scripts</category>
</documentation_file>
"""
GPS.parse_xml(XML)
def gps_started(self):
"""
Initializations done after the gps_started hook
"""
# This action requires pydoc
if os_utils.locate_exec_on_path('pydoc'):
gps_utils.make_interactive(
callback=self.show_python_library,
name='display python library help')
gps_utils.make_interactive(
callback=self.reload_file,
name='reload python file',
filter='Python file',
contextual='Python/Import & Reload')
gps_utils.make_interactive(
callback=self.indent_on_new_line,
name="Python Auto Indentation",
filter='Python file')
self.pydoc_proc = None
GPS.Hook("project_view_changed").add(self._project_recomputed)
GPS.Hook("before_exit_action_hook").add(self._before_exit)
def indent_on_new_line(self):
"""
This action parse the code (if it's python) and move cursor to
the desired indentation level.
"""
editor = GPS.EditorBuffer.get()
start = editor.selection_start()
end = editor.selection_end()
# if a block is selected, delete the block
if start.line() != end.line() or start.column() != end.column():
editor.delete(start, end)
# place the cursor at the head of a new line
editor.insert(start, "\n")
# do indentation
self.python_parse_indent(editor, start)
def python_parse_indent(self, e, start):
"""
parse the text and predict python indentation when hitting return
* return the indentation (int)
* text is edited with cursor at indentation level after returned
* end is position of cursor
"""
def find_level(on_this_string):
"""
Find relatively level change for a given string
Return relative level change and prefix to search
"""
# by default, no level change, no prefix to search
level, group = 0, []
# case : enter subprogram, innermost level decides
if on_this_string.endswith(":"):
level = 1
group = ["if", "else", "for", "while",
"def", "class", "try", "except"]
else:
# case: return to a function, previous def decides
if on_this_string.startswith("return"):
level = -2
group = ["def"]
# case: break out loops, innermost loop decides
if on_this_string.startswith("break") or \
on_this_string.startswith("continue"):
level = -1
group = ["for", "while"]
return (level, group)
source = e.get_chars(to=start).splitlines()
# initialize
last = source[0]
end = start
previous_indent = 0
for i in range(len(source) - 1, -1, -1):
# ident is same as last non-comment not-empty line, no level change
tmpstring = source[i].lstrip(" ")
if tmpstring != "" and not tmpstring.startswith("#"):
last = source[i]
previous_indent = len(last) - len(tmpstring)
end = e.at(i + 1, 1).end_of_line()
break
# STEP 1 parse parenthesis
level, group = 0, []
result = text_utils.parse_parentheses(e, end=end)
stack = result[0]
# go to responsible parentheses' line, if exists
if len(stack) > 0:
last_loc = stack.pop()
previous_indent = last_loc[1] + 1
# closing a (), same line responsible for level change
if result[1]:
level, group = find_level(source[last_loc[0]].lstrip(" "))
# else the last line is responsible
else:
tmphead = last.lstrip(" ")
level, group = find_level(tmphead)
# STEP 2 find prev indent quantity (number of whitespaces)
prefix = ""
begin = 0
# only when level changes
if level != 0:
for i in range(end.line() - 1, -1, -1):
for pref in group:
if source[i].lstrip(" ").startswith(pref):
begin = i
prefix = pref
break
# if hit the prefix during loop, modify previous_indent
if prefix is not "":
previous_indent = len(source[begin].split(prefix)[0])
break
# STEP 3 find the correct indent number
level = 0 if level < 0 else level
indent = previous_indent + level * 4
# STEP 4 do indentation and move the cursor
e.insert(e.at(start.line() + 1, 1), " " * indent)
e.main_cursor().move(e.at(start.line() + 1, indent + 1))
return indent
def reload_file(self):
"""
Reload the currently edited file in python.
If the file has not been imported yet, import it initially.
Otherwise, reload the current version of the file.
"""
try:
f = GPS.current_context().file()
module = os.path.splitext(os.path.basename(f.path))[0]
# The actual import and reload must be done in the context of the
# GPS console so that they are visible there. The current function
# executes in a different context, and would not impact the GPS
# console as a result otherwise.
# We cannot use execfile(...), since that would be the equivalent
# of "from ... import *", not of "import ..."
if module in sys.modules:
GPS.exec_in_console("reload(sys.modules[\"" + module + "\"])")
else:
try:
sys.path.index(os.path.dirname(f.path))
except Exception:
sys.path = [os.path.dirname(f.path)] + sys.path
__import__(module)
# This would import in the current context, not what we want
# exec (compile ("import " + module, "<cmdline>", "exec"))
# The proper solution is to execute in the context of the GPS
# console
GPS.exec_in_console("import " + module)
except Exception:
pass # Current context is not a file
def _project_recomputed(self, hook_name):
"""
if python is one of the supported language for the project, add various
predefined directories that may contain python files, so that shift-F3
works to open these files as it does for the Ada runtime
"""
GPS.Project.add_predefined_paths(
sources="%splug-ins" % GPS.get_home_dir())
try:
GPS.Project.root().languages(recursive=True).index("python")
# The rest is done only if we support python
GPS.Project.add_predefined_paths(sources=os.pathsep.join(sys.path))
except Exception:
pass
def show_python_library(self):
"""Open a navigator to show the help on the python library"""
base = port = self.port_pref.get()
if not self.pydoc_proc:
while port - base < 10:
self.pydoc_proc = GPS.Process(["pydoc", "-p", "%s" % port])
out = self.pydoc_proc.expect(
"pydoc server ready|Address already in use", 10000)
try:
out.rindex( # raise exception if not found
"Address already in use")
port += 1
except Exception:
break
GPS.HTML.browse("http://localhost:%s/" % port)
def _before_exit(self, hook_name):
"""Called before GPS exits"""
if self.pydoc_proc:
self.pydoc_proc.kill()
self.pydoc_proc = None
return 1
class PythonTracer(object):
""" Basic python tracer, useful for GPS plugin development and debug.
"""
def __init__(self):
self.logger = GPS.Logger("Python_Tracer")
self.prev_trace = sys.gettrace()
sys.settrace(self.trace)
def __del__(self):
sys.settrace(self.prev_trace)
def trace(self, frame, event, arg):
filename, lineno = frame.f_code.co_filename, frame.f_lineno
self.logger.log("%s:%s:%s:%s" % (filename, lineno, event, arg))
# Create the class once GPS is started, so that the filter is created
# immediately when parsing XML, and we can create our actions.
module = PythonSupport()
GPS.Hook("gps_started").add(lambda h: module.gps_started())
|
qunying/gps
|
share/support/languages/python_support.py
|
Python
|
gpl-3.0
| 15,959
|
[
"VisIt"
] |
542fdfab384e3bfe282e556eec02b656948801a85090062baeb39e6d1344d989
|
# Copyright (c) 2013,Vienna University of Technology, Department of Geodesy and Geoinformation
# All rights reserved.
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in the
# documentation and/or other materials provided with the distribution.
# * Neither the name of the Vienna University of Technology, Department of Geodesy and Geoinformation nor the
# names of its contributors may be used to endorse or promote products
# derived from this software without specific prior written permission.
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL VIENNA UNIVERSITY OF TECHNOLOGY,
# DEPARTMENT OF GEODESY AND GEOINFORMATION BE LIABLE FOR ANY
# DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
# (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
# ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
'''
Created on Jan 21, 2014
@author: Christoph Paulik christoph.paulik@geo.tuwien.ac.at
'''
import unittest
import numpy as np
import numpy.testing as nptest
import os
from netCDF4 import Dataset
import pytesmo.grid.netcdf as grid_nc
import pytesmo.grid.grids as grids
def curpath():
pth, _ = os.path.split(os.path.abspath(__file__))
return pth
class Test(unittest.TestCase):
def setUp(self):
lat, lon = np.arange(180) - 90, np.arange(360) - 180
self.lats, self.lons = np.meshgrid(lat, lon)
self.lats, self.lons = self.lats.flatten(), self.lons.flatten()
self.cells = grids.lonlat2cell(self.lons, self.lats)
self.subset = np.sort(np.random.choice(np.arange(self.lats.size),
size=500, replace=False))
self.basic = grids.BasicGrid(self.lons, self.lats, subset=self.subset,
shape=(360, 180))
self.basic_irregular = grids.BasicGrid(self.lons, self.lats,
subset=self.subset)
self.cellgrid = grids.CellGrid(self.lons, self.lats, self.cells,
subset=self.subset)
self.testfilename = os.path.join(curpath(), 'data', 'test.nc')
if not os.path.exists(os.path.join(curpath(), 'data')):
os.mkdir(os.path.join(curpath(), 'data'))
def tearDown(self):
os.remove(self.testfilename)
def test_save_lonlat_nc(self):
grid_nc.save_lonlat(self.testfilename,
self.lons, self.lats, self.cells,
subsets={'subset_flag': {'points': self.subset,
'meaning': 'water, land'}},
global_attrs={'test': 'test_attribute'})
with Dataset(self.testfilename) as nc_data:
nptest.assert_array_equal(self.lats, nc_data.variables['lat'][:])
nptest.assert_array_equal(self.lons, nc_data.variables['lon'][:])
nptest.assert_array_equal(self.cells, nc_data.variables['cell'][:])
nptest.assert_array_equal(
self.subset, np.where(nc_data.variables['subset_flag'][:] == 1)[0])
assert nc_data.test == 'test_attribute'
def test_save_basicgrid_nc(self):
grid_nc.save_grid(self.testfilename,
self.basic,
global_attrs={'test': 'test_attribute'})
with Dataset(self.testfilename) as nc_data:
nptest.assert_array_equal(np.unique(self.lats)[::-1],
nc_data.variables['lat'][:])
nptest.assert_array_equal(np.unique(self.lons),
nc_data.variables['lon'][:])
nptest.assert_array_equal(self.subset,
np.where(nc_data.variables['subset_flag'][:].flatten() == 1)[0])
assert nc_data.test == 'test_attribute'
assert nc_data.shape[0] == 360
assert nc_data.shape[1] == 180
def test_save_basicgrid_irregular_nc(self):
grid_nc.save_grid(self.testfilename,
self.basic_irregular,
global_attrs={'test': 'test_attribute'})
with Dataset(self.testfilename) as nc_data:
nptest.assert_array_equal(self.lats, nc_data.variables['lat'][:])
nptest.assert_array_equal(self.lons, nc_data.variables['lon'][:])
nptest.assert_array_equal(self.subset,
np.where(nc_data.variables['subset_flag'][:] == 1)[0])
assert nc_data.test == 'test_attribute'
assert nc_data.shape == 64800
def test_save_cellgrid_nc(self):
grid_nc.save_grid(self.testfilename,
self.cellgrid,
global_attrs={'test': 'test_attribute'})
with Dataset(self.testfilename) as nc_data:
nptest.assert_array_equal(self.lats, nc_data.variables['lat'][:])
nptest.assert_array_equal(self.lons, nc_data.variables['lon'][:])
nptest.assert_array_equal(self.cells, nc_data.variables['cell'][:])
nptest.assert_array_equal(
self.subset, np.where(nc_data.variables['subset_flag'][:] == 1)[0])
assert nc_data.test == 'test_attribute'
assert nc_data.gpidirect == 0x1b
def test_save_load_basicgrid(self):
grid_nc.save_grid(self.testfilename,
self.basic)
loaded_grid = grid_nc.load_grid(self.testfilename)
assert self.basic == loaded_grid
def test_save_load_basicgrid_irregular(self):
grid_nc.save_grid(self.testfilename,
self.basic_irregular)
loaded_grid = grid_nc.load_grid(self.testfilename)
assert self.basic_irregular == loaded_grid
def test_save_load_cellgrid(self):
grid_nc.save_grid(self.testfilename,
self.cellgrid)
loaded_grid = grid_nc.load_grid(self.testfilename)
assert self.cellgrid == loaded_grid
if __name__ == "__main__":
# import sys;sys.argv = ['', 'Test.testName']
unittest.main()
|
christophreimer/pytesmo
|
tests/test_grid/test_netcdf.py
|
Python
|
bsd-3-clause
| 6,962
|
[
"NetCDF"
] |
71f2b1192fd9f0420c08f5fc6aaa3a0333bac4917710ecac4c0e85bfbbfa6e18
|
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
import time
# !! This is the configuration of Nikola. !! #
# !! You should edit it to your liking. !! #
# ! Some settings can be different in different languages.
# ! A comment stating (translatable) is used to denote those.
# ! There are two ways to specify a translatable setting:
# ! (a) BLOG_TITLE = "My Blog"
# ! (b) BLOG_TITLE = {"en": "My Blog", "es": "Mi Blog"}
# ! Option (a) is used when you don't want that setting translated.
# ! Option (b) is used for settings that are different in different languages.
# Data about this site
BLOG_AUTHOR = "Jonathan Muller" # (translatable)
BLOG_TITLE = "Drylm - Thoughts from the void." # (translatable)
# This is the main URL for your site. It will be used
# in a prominent link
SITE_URL = "https://blog.drylm.org/"
# This is the URL where nikola's output will be deployed.
BLOG_EMAIL = "muller dot john at gmail.com"
BLOG_DESCRIPTION = "Drylm is a software craftmen orgzanization built by developer for developers. Drylm is involded in agile and scrum practising the Scrum Programming" #(translatable)
# Nikola is multilingual!
#
# Currently supported languages are:
#
# en English
# bg Bulgarian
# ca Catalan
# cs Czech [ALTERNATIVELY cz]
# de German
# el Greek [NOT gr]
# eo Esperanto
# es Spanish
# et Estonian
# eu Basque
# fa Persian
# fi Finnish
# fr French
# hi Hindi
# hr Croatian
# it Italian
# ja Japanese [NOT jp]
# nb Norwegian Bokmål
# nl Dutch
# pl Polish
# pt_br Portuguese (Brasil)
# ru Russian
# sk Slovak
# sl Slovene
# tr Turkish [NOT tr_TR]
# ur Urdu
# zh_cn Chinese (Simplified)
#
# If you want to use Nikola with a non-supported language you have to provide
# a module containing the necessary translations
# (cf. the modules at nikola/data/themes/base/messages/).
# If a specific post is not translated to a language, then the version
# in the default language will be shown instead.
# What is the default language?
DEFAULT_LANG = "en"
# What other languages do you have?
# The format is {"translationcode" : "path/to/translation" }
# the path will be used as a prefix for the generated pages location
TRANSLATIONS = {
DEFAULT_LANG: "",
# Example for another language:
# "es": "./es",
}
# What will translated input files be named like?
# If you have a page something.rst, then something.pl.rst will be considered
# its Polish translation.
# (in the above example: path == "something", ext == "rst", lang == "pl")
# this pattern is also used for metadata:
# something.meta -> something.pl.meta
TRANSLATIONS_PATTERN = "{path}.{lang}.{ext}"
# Links for the sidebar / navigation bar.
# You should provide a key-value pair for each used language.
# (the same way you would do with a (translatable) setting.)
NAVIGATION_LINKS = {
DEFAULT_LANG: (
('/index.html', 'Home', 'icon-home'),
('/archive.html', 'Archives', 'icon-folder-open-alt'),
('/categories/index.html', 'Tags', 'icon-tags'),
('/rss.xml', 'RSS', 'icon-rss'),
('/galleries/index.html', 'Galleries', 'icon-file'),
('http://jonathan.muller.drylm.org', 'CV', 'icon-user'),
('https://twitter.com/Bhaal22', 'My Twitter', 'icon-twitter'),
('https://github.com/Bhaal22', 'My Github', 'icon-github'),
),
}
# Name of the theme to use.
# THEME = "bootstrap3"
THEME = "zen"
# Below this point, everything is optional
# Post's dates are considered in UTC by default, if you want to use
# another time zone, please set TIMEZONE to match. Check the available
# list from Wikipedia:
# http://en.wikipedia.org/wiki/List_of_tz_database_time_zones
# (eg. 'Europe/Zurich')
# Also, if you want to use a different time zone in some of your posts,
# you can use the ISO 8601/RFC 3339 format (ex. 2012-03-30T23:00:00+02:00)
TIMEZONE = "UTC"
# If you want to use ISO 8601 (also valid RFC 3339) throughout Nikola
# (especially in new_post), set this to True.
# Note that this does not affect DATE_FORMAT.
# FORCE_ISO8601 = False
# Date format used to display post dates.
# (str used by datetime.datetime.strftime)
# DATE_FORMAT = '%Y-%m-%d %H:%M'
# While nikola can select a sensible locale for each language,
# sometimes explicit control can come handy.
# In this file we express locales in the string form that
# python's locales will accept in your OS, by example
# "en_US.utf8" in unix-like OS, "English_United States" in Windows.
# LOCALES = dict mapping language --> explicit locale for the languages
# in TRANSLATIONS. You can ommit one or more keys.
# LOCALE_FALLBACK = locale to use when an explicit locale is unavailable
# LOCALE_DEFAULT = locale to use for languages not mentioned in LOCALES; if
# not set the default Nikola mapping is used.
# POSTS and PAGES contains (wildcard, destination, template) tuples.
#
# The wildcard is used to generate a list of reSt source files
# (whatever/thing.txt).
#
# That fragment could have an associated metadata file (whatever/thing.meta),
# and optionally translated files (example for spanish, with code "es"):
# whatever/thing.es.txt and whatever/thing.es.meta
#
# This assumes you use the default TRANSLATIONS_PATTERN.
#
# From those files, a set of HTML fragment files will be generated:
# cache/whatever/thing.html (and maybe cache/whatever/thing.html.es)
#
# These files are combinated with the template to produce rendered
# pages, which will be placed at
# output / TRANSLATIONS[lang] / destination / pagename.html
#
# where "pagename" is the "slug" specified in the metadata file.
#
# The difference between POSTS and PAGES is that POSTS are added
# to feeds and are considered part of a blog, while PAGES are
# just independent HTML pages.
#
POSTS = (
("posts/*.md", "posts", "post.tmpl"),
("posts/*.rst", "posts", "post.tmpl"),
("posts/*.txt", "posts", "post.tmpl"),
)
PAGES = (
("stories/*.md", "stories", "story.tmpl"),
("stories/*.rst", "stories", "story.tmpl"),
("stories/*.txt", "stories", "story.tmpl"),
)
# One or more folders containing files to be copied as-is into the output.
# The format is a dictionary of "source" "relative destination".
# Default is:
# FILES_FOLDERS = {'files': '' }
# Which means copy 'files' into 'output'
# A mapping of languages to file-extensions that represent that language.
# Feel free to add or delete extensions to any list, but don't add any new
# compilers unless you write the interface for it yourself.
#
# 'rest' is reStructuredText
# 'markdown' is MarkDown
# 'html' assumes the file is html and just copies it
COMPILERS = {
"rest": ('.rst', '.txt'),
"markdown": ('.md', '.mdown', '.markdown'),
"textile": ('.textile',),
"txt2tags": ('.t2t',),
"bbcode": ('.bb',),
"wiki": ('.wiki',),
"ipynb": ('.ipynb',),
"html": ('.html', '.htm'),
# PHP files are rendered the usual way (i.e. with the full templates).
# The resulting files have .php extensions, making it possible to run
# them without reconfiguring your server to recognize them.
"php": ('.php',),
# Pandoc detects the input from the source filename
# but is disabled by default as it would conflict
# with many of the others.
# "pandoc": ('.rst', '.md', '.txt'),
}
# Create by default posts in one file format?
# Set to False for two-file posts, with separate metadata.
# ONE_FILE_POSTS = True
# If this is set to True, the DEFAULT_LANG version will be displayed for
# untranslated posts.
# If this is set to False, then posts that are not translated to a language
# LANG will not be visible at all in the pages in that language.
# Formerly known as HIDE_UNTRANSLATED_POSTS (inverse)
# SHOW_UNTRANSLATED_POSTS = True
# Nikola supports logo display. If you have one, you can put the URL here.
# Final output is <img src="LOGO_URL" id="logo" alt="BLOG_TITLE">.
# The URL may be relative to the site root.
# LOGO_URL = ''
# If you want to hide the title of your website (for example, if your logo
# already contains the text), set this to False.
# SHOW_BLOG_TITLE = True
# Paths for different autogenerated bits. These are combined with the
# translation paths.
# Final locations are:
# output / TRANSLATION[lang] / TAG_PATH / index.html (list of tags)
# output / TRANSLATION[lang] / TAG_PATH / tag.html (list of posts for a tag)
# output / TRANSLATION[lang] / TAG_PATH / tag.xml (RSS feed for a tag)
# TAG_PATH = "categories"
# If TAG_PAGES_ARE_INDEXES is set to True, each tag's page will contain
# the posts themselves. If set to False, it will be just a list of links.
# TAG_PAGES_ARE_INDEXES = False
# Final location for the main blog page and sibling paginated pages is
# output / TRANSLATION[lang] / INDEX_PATH / index-*.html
# INDEX_PATH = ""
# Create per-month archives instead of per-year
# CREATE_MONTHLY_ARCHIVE = False
# Create one large archive instead of per-year
# CREATE_SINGLE_ARCHIVE = False
# Final locations for the archives are:
# output / TRANSLATION[lang] / ARCHIVE_PATH / ARCHIVE_FILENAME
# output / TRANSLATION[lang] / ARCHIVE_PATH / YEAR / index.html
# output / TRANSLATION[lang] / ARCHIVE_PATH / YEAR / MONTH / index.html
# ARCHIVE_PATH = ""
# ARCHIVE_FILENAME = "archive.html"
# URLs to other posts/pages can take 3 forms:
# rel_path: a relative URL to the current page/post (default)
# full_path: a URL with the full path from the root
# absolute: a complete URL (that includes the SITE_URL)
# URL_TYPE = 'rel_path'
# Final location for the blog main RSS feed is:
# output / TRANSLATION[lang] / RSS_PATH / rss.xml
# RSS_PATH = ""
# Number of posts in RSS feeds
# FEED_LENGTH = 10
# Slug the Tag URL easier for users to type, special characters are
# often removed or replaced as well.
# SLUG_TAG_PATH = True
# A list of redirection tuples, [("foo/from.html", "/bar/to.html")].
#
# A HTML file will be created in output/foo/from.html that redirects
# to the "/bar/to.html" URL. notice that the "from" side MUST be a
# relative URL.
#
# If you don't need any of these, just set to []
REDIRECTIONS = []
WRITE_TAG_CLOUD = True;
# Commands to execute to deploy. Can be anything, for example,
# you may use rsync:
# "rsync -rav --delete output/ joe@my.site:/srv/www/site"
# And then do a backup, or run `nikola ping` from the `ping`
# plugin (`nikola install_plugin ping`).
# To do manual deployment, set it to []
DEPLOY_COMMANDS = {
'default': ["cp -r output/* /var/www/blog.drylm.org", "chown -R http:http /var/www/blog.drylm.org"]
}
# For user.github.io/organization.github.io pages, the DEPLOY branch
# MUST be 'master', and 'gh-pages' for other repositories.
# GITHUB_SOURCE_BRANCH = 'master'
# GITHUB_DEPLOY_BRANCH = 'gh-pages'
# The name of the remote where you wish to push to, using github_deploy.
# GITHUB_REMOTE_NAME = 'origin'
# Where the output site should be located
# If you don't use an absolute path, it will be considered as relative
# to the location of conf.py
# OUTPUT_FOLDER = 'output'
# where the "cache" of partial generated content should be located
# default: 'cache'
# CACHE_FOLDER = 'cache'
# Filters to apply to the output.
# A directory where the keys are either: a file extensions, or
# a tuple of file extensions.
#
# And the value is a list of commands to be applied in order.
#
# Each command must be either:
#
# A string containing a '%s' which will
# be replaced with a filename. The command *must* produce output
# in place.
#
# Or:
#
# A python callable, which will be called with the filename as
# argument.
#
# By default, there are no filters.
#
# Many filters are shipped with Nikola. A list is available in the manual:
# <http://getnikola.com/handbook.html#post-processing-filters>
# FILTERS = {
# ".jpg": ["jpegoptim --strip-all -m75 -v %s"],
# }
# Expert setting! Create a gzipped copy of each generated file. Cheap server-
# side optimization for very high traffic sites or low memory servers.
# GZIP_FILES = False
# File extensions that will be compressed
# GZIP_EXTENSIONS = ('.txt', '.htm', '.html', '.css', '.js', '.json', '.xml')
# Use an external gzip command? None means no.
# Example: GZIP_COMMAND = "pigz -k {filename}"
# GZIP_COMMAND = None
# Make sure the server does not return a "Accept-Ranges: bytes" header for
# files compressed by this option! OR make sure that a ranged request does not
# return partial content of another representation for these resources. Do not
# use this feature if you do not understand what this means.
# Compiler to process LESS files.
# LESS_COMPILER = 'lessc'
# A list of options to pass to the LESS compiler.
# Final command is: LESS_COMPILER LESS_OPTIONS file.less
# LESS_OPTIONS = []
# Compiler to process Sass files.
# SASS_COMPILER = 'sass'
# A list of options to pass to the Sass compiler.
# Final command is: SASS_COMPILER SASS_OPTIONS file.s(a|c)ss
# SASS_OPTIONS = []
# #############################################################################
# Image Gallery Options
# #############################################################################
# Galleries are folders in galleries/
# Final location of galleries will be output / GALLERY_PATH / gallery_name
# GALLERY_PATH = "galleries"
# THUMBNAIL_SIZE = 180
# MAX_IMAGE_SIZE = 1280
# USE_FILENAME_AS_TITLE = True
# EXTRA_IMAGE_EXTENSIONS = []
#
# If set to False, it will sort by filename instead. Defaults to True
# GALLERY_SORT_BY_DATE = True
# #############################################################################
# HTML fragments and diverse things that are used by the templates
# #############################################################################
# Data about post-per-page indexes.
# INDEXES_PAGES defaults to 'old posts, page %d' or 'page %d' (translated),
# depending on the value of INDEXES_PAGES_MAIN.
# INDEXES_TITLE = "" # If this is empty, defaults to BLOG_TITLE
# INDEXES_PAGES = "" # If this is empty, defaults to '[old posts,] page %d' (see above)
# INDEXES_PAGES_MAIN = False # If True, INDEXES_PAGES is also displayed on
# # the main (the newest) index page (index.html)
# Color scheme to be used for code blocks. If your theme provides
# "assets/css/code.css" this is ignored.
# Can be any of autumn borland bw colorful default emacs friendly fruity manni
# monokai murphy native pastie perldoc rrt tango trac vim vs
# CODE_COLOR_SCHEME = 'default'
# If you use 'site-reveal' theme you can select several subthemes
# THEME_REVEAL_CONFIG_SUBTHEME = 'sky'
# You can also use: beige/serif/simple/night/default
# Again, if you use 'site-reveal' theme you can select several transitions
# between the slides
# THEME_REVEAL_CONFIG_TRANSITION = 'cube'
# You can also use: page/concave/linear/none/default
# FAVICONS contains (name, file, size) tuples.
# Used for create favicon link like this:
# <link rel="name" href="file" sizes="size"/>
# FAVICONS = {
# ("icon", "/favicon.ico", "16x16"),
# ("icon", "/icon_128x128.png", "128x128"),
# }
# Show only teasers in the index pages? Defaults to False.
INDEX_TEASERS = True
# HTML fragments with the Read more... links.
# The following tags exist and are replaced for you:
# {link} A link to the full post page.
# {read_more} The string “Read more” in the current language.
# {reading_time} An estimate of how long it will take to read the post.
# {remaining_reading_time} An estimate of how long it will take to read the post, sans the teaser.
# {min_remaining_read} The string “{remaining_reading_time} min remaining to read” in the current language.
# {paragraph_count} The amount of paragraphs in the post.
# {remaining_paragraph_count} The amount of paragraphs in the post, sans the teaser.
# {{ A literal { (U+007B LEFT CURLY BRACKET)
# }} A literal } (U+007D RIGHT CURLY BRACKET)
# 'Read more...' for the index page, if INDEX_TEASERS is True (translatable)
INDEX_READ_MORE_LINK = '<p class="more"><a href="{link}">{read_more}…</a></p>'
# 'Read more...' for the RSS_FEED, if RSS_TEASERS is True (translatable)
# A HTML fragment describing the license, for the sidebar.
# (translatable)
LICENSE = ""
# I recommend using the Creative Commons' wizard:
# http://creativecommons.org/choose/
# LICENSE = """
# <a rel="license" href="http://creativecommons.org/licenses/by-nc-sa/2.5/ar/">
# <img alt="Creative Commons License BY-NC-SA"
# style="border-width:0; margin-bottom:12px;"
# src="http://i.creativecommons.org/l/by-nc-sa/2.5/ar/88x31.png"></a>"""
# A small copyright notice for the page footer (in HTML).
# (translatable)
CONTENT_FOOTER = 'Contents © {date} <a href="mailto:{email}">{author}</a> - Powered by <a href="http://getnikola.com" rel="nofollow">Nikola</a> {license}'
# Things that will be passed to CONTENT_FOOTER.format(). This is done
# for translatability, as dicts are not formattable. Nikola will
# intelligently format the setting properly.
# The setting takes a dict. The keys are languages. The values are
# tuples of tuples of positional arguments and dicts of keyword arguments
# to format(). For example, {'en': (('Hello'), {'target': 'World'})}
# results in CONTENT_FOOTER['en'].format('Hello', target='World').
# WARNING: If you do not use multiple languages with CONTENT_FOOTER, this
# still needs to be a dict of this format. (it can be empty if you
# do not need formatting)
# (translatable)
CONTENT_FOOTER_FORMATS = {
DEFAULT_LANG: (
(),
{
"email": BLOG_EMAIL,
"author": BLOG_AUTHOR,
"date": time.gmtime().tm_year,
"license": LICENSE
}
)
}
# To use comments, you can choose between different third party comment
# systems. The following comment systems are supported by Nikola:
# disqus, facebook, googleplus, intensedebate, isso, livefyre, muut
# You can leave this option blank to disable comments.
COMMENT_SYSTEM = "disqus"
# And you also need to add your COMMENT_SYSTEM_ID which
# depends on what comment system you use. The default is
# "nikolademo" which is a test account for Disqus. More information
# is in the manual.
COMMENT_SYSTEM_ID = "jonathanmuller"
# Enable annotations using annotateit.org?
# If set to False, you can still enable them for individual posts and pages
# setting the "annotations" metadata.
# If set to True, you can disable them for individual posts and pages using
# the "noannotations" metadata.
# ANNOTATIONS = False
# Create index.html for story folders?
# STORY_INDEX = False
# Enable comments on story pages?
# COMMENTS_IN_STORIES = False
# Enable comments on picture gallery pages?
# COMMENTS_IN_GALLERIES = False
# What file should be used for directory indexes?
# Defaults to index.html
# Common other alternatives: default.html for IIS, index.php
# INDEX_FILE = "index.html"
# If a link ends in /index.html, drop the index.html part.
# http://mysite/foo/bar/index.html => http://mysite/foo/bar/
# (Uses the INDEX_FILE setting, so if that is, say, default.html,
# it will instead /foo/default.html => /foo)
# (Note: This was briefly STRIP_INDEX_HTML in v 5.4.3 and 5.4.4)
# Default = False
# STRIP_INDEXES = False
# Should the sitemap list directories which only include other directories
# and no files.
# Default to True
# If this is False
# e.g. /2012 includes only /01, /02, /03, /04, ...: don't add it to the sitemap
# if /2012 includes any files (including index.html)... add it to the sitemap
# SITEMAP_INCLUDE_FILELESS_DIRS = True
# List of files relative to the server root (!) that will be asked to be excluded
# from indexing and other robotic spidering. * is supported. Will only be effective
# if SITE_URL points to server root. The list is used to exclude resources from
# /robots.txt and /sitemap.xml, and to inform search engines about /sitemapindex.xml.
# ROBOTS_EXCLUSIONS = ["/archive.html", "/category/*.html"]
# Instead of putting files in <slug>.html, put them in
# <slug>/index.html. Also enables STRIP_INDEXES
# This can be disabled on a per-page/post basis by adding
# .. pretty_url: False
# to the metadata
# PRETTY_URLS = False
# If True, publish future dated posts right away instead of scheduling them.
# Defaults to False.
# FUTURE_IS_NOW = False
# If True, future dated posts are allowed in deployed output
# Only the individual posts are published/deployed; not in indexes/sitemap
# Generally, you want FUTURE_IS_NOW and DEPLOY_FUTURE to be the same value.
# DEPLOY_FUTURE = False
# If False, draft posts will not be deployed
# DEPLOY_DRAFTS = True
# Allows scheduling of posts using the rule specified here (new_post -s)
# Specify an iCal Recurrence Rule: http://www.kanzaki.com/docs/ical/rrule.html
# SCHEDULE_RULE = ''
# If True, use the scheduling rule to all posts by default
# SCHEDULE_ALL = False
# Do you want a add a Mathjax config file?
# MATHJAX_CONFIG = ""
# If you are using the compile-ipynb plugin, just add this one:
# MATHJAX_CONFIG = """
# <script type="text/x-mathjax-config">
# MathJax.Hub.Config({
# tex2jax: {
# inlineMath: [ ['$','$'], ["\\\(","\\\)"] ],
# displayMath: [ ['$$','$$'], ["\\\[","\\\]"] ]
# },
# displayAlign: 'left', // Change this to 'center' to center equations.
# "HTML-CSS": {
# styles: {'.MathJax_Display': {"margin": 0}}
# }
# });
# </script>
# """
# Do you want to customize the nbconversion of your IPython notebook?
# IPYNB_CONFIG = {}
# With the following example configuracion you can use a custom jinja template
# called `toggle.tpl` which has to be located in your site/blog main folder:
# IPYNB_CONFIG = {'Exporter':{'template_file': 'toggle'}}
# What Markdown extensions to enable?
# You will also get gist, nikola and podcast because those are
# done in the code, hope you don't mind ;-)
# Note: most Nikola-specific extensions are done via the Nikola plugin system,
# with the MarkdownExtension class and should not be added here.
# MARKDOWN_EXTENSIONS = ['fenced_code', 'codehilite']
MARKDOWN_EXTENSIONS = ['fenced_code', 'codehilite', 'tables']
# Social buttons. This is sample code for AddThis (which was the default for a
# long time). Insert anything you want here, or even make it empty.
# (translatable)
SOCIAL_BUTTONS_CODE = """
"""
# <!-- Social buttons -->
# <div id="addthisbox" class="addthis_toolbox addthis_peekaboo_style addthis_default_style addthis_label_style addthis_32x32_style">
# <a class="addthis_button_more">Share</a>
# <ul><li><a class="addthis_button_facebook"></a>
# <li><a class="addthis_button_google_plusone_share"></a>
# <li><a class="addthis_button_linkedin"></a>
# <li><a class="addthis_button_twitter"></a>
# </ul>
# </div>
# <script src="//s7.addthis.com/js/300/addthis_widget.js#pubid=ra-4f7088a56bb93798"></script>
# <!-- End of social buttons -->
# Show link to source for the posts?
# Formerly known as HIDE_SOURCELINK (inverse)
# SHOW_SOURCELINK = True
# Copy the source files for your pages?
# Setting it to False implies SHOW_SOURCELINK = False
# COPY_SOURCES = True
# Modify the number of Post per Index Page
# Defaults to 10
# INDEX_DISPLAY_POST_COUNT = 10
# By default, Nikola generates RSS files for the website and for tags, and
# links to it. Set this to False to disable everything RSS-related.
# GENERATE_RSS = True
# RSS_LINK is a HTML fragment to link the RSS or Atom feeds. If set to None,
# the base.tmpl will use the feed Nikola generates. However, you may want to
# change it for a feedburner feed or something else.
# RSS_LINK = None
# Show only teasers in the RSS feed? Default to True
# RSS_TEASERS = True
# Strip HTML in the RSS feed? Default to False
# RSS_PLAIN = False
# A search form to search this site, for the sidebar. You can use a google
# custom search (http://www.google.com/cse/)
# Or a duckduckgo search: https://duckduckgo.com/search_box.html
# Default is no search form.
# (translatable)
# SEARCH_FORM = ""
#
# This search form works for any site and looks good in the "site" theme where
# it appears on the navigation bar:
#
# SEARCH_FORM = """
# <!-- Custom search -->
# <form method="get" id="search" action="//duckduckgo.com/"
# class="navbar-form pull-left">
# <input type="hidden" name="sites" value="%s"/>
# <input type="hidden" name="k8" value="#444444"/>
# <input type="hidden" name="k9" value="#D51920"/>
# <input type="hidden" name="kt" value="h"/>
# <input type="text" name="q" maxlength="255"
# placeholder="Search…" class="span2" style="margin-top: 4px;"/>
# <input type="submit" value="DuckDuckGo Search" style="visibility: hidden;" />
# </form>
# <!-- End of custom search -->
# """ % SITE_URL
#
# If you prefer a google search form, here's an example that should just work:
# SEARCH_FORM = """
# <!-- Custom search with google-->
# <form id="search" action="//www.google.com/search" method="get" class="navbar-form pull-left">
# <input type="hidden" name="q" value="site:%s" />
# <input type="text" name="q" maxlength="255" results="0" placeholder="Search"/>
# </form>
# <!-- End of custom search -->
#""" % SITE_URL
# Use content distribution networks for jquery, twitter-bootstrap css and js,
# and html5shiv (for older versions of Internet Explorer)
# If this is True, jquery and html5shiv is served from the Google and twitter-
# bootstrap is served from the NetDNA CDN
# Set this to False if you want to host your site without requiring access to
# external resources.
# USE_CDN = False
# Extra things you want in the pages HEAD tag. This will be added right
# before </head>
# (translatable)
# EXTRA_HEAD_DATA = ""
# Google Analytics or whatever else you use. Added to the bottom of <body>
# in the default template (base.tmpl).
# (translatable)
BODY_END = """
<!-- Start of Google Analytics -->
<script>
(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(window,document,'script','https://www.google-analytics.com/analytics.js','ga');
ga('create', 'UA-58774827-1', 'auto');
ga('send', 'pageview');
</script>
<!-- End of Google Analytics -->
"""
# The possibility to extract metadata from the filename by using a
# regular expression.
# To make it work you need to name parts of your regular expression.
# The following names will be used to extract metadata:
# - title
# - slug
# - date
# - tags
# - link
# - description
#
# An example re is the following:
# '(?P<date>\d{4}-\d{2}-\d{2})-(?P<slug>.*)-(?P<title>.*)\.md'
# FILE_METADATA_REGEXP = None
# If you hate "Filenames with Capital Letters and Spaces.md", you should
# set this to true.
UNSLUGIFY_TITLES = True
# Additional metadata that is added to a post when creating a new_post
# ADDITIONAL_METADATA = {}
# Nikola supports Open Graph Protocol data for enhancing link sharing and
# discoverability of your site on Facebook, Google+, and other services.
# Open Graph is enabled by default.
# USE_OPEN_GRAPH = True
# Nikola supports Twitter Card summaries
# Twitter cards are disabled by default. They make it possible for you to
# attach media to Tweets that link to your content.
#
# IMPORTANT:
# Please note, that you need to opt-in for using Twitter Cards!
# To do this please visit
# https://dev.twitter.com/form/participate-twitter-cards
#
# Uncomment and modify to following lines to match your accounts.
# Specifying the id for either 'site' or 'creator' will be preferred
# over the cleartext username. Specifying an ID is not necessary.
# Displaying images is currently not supported.
# TWITTER_CARD = {
# # 'use_twitter_cards': True, # enable Twitter Cards
# # 'site': '@website', # twitter nick for the website
# # 'site:id': 123456, # Same as site, but the website's Twitter user ID
# # instead.
# # 'creator': '@username', # Username for the content creator / author.
# # 'creator:id': 654321, # Same as creator, but the Twitter user's ID.
# }
# If webassets is installed, bundle JS and CSS to make site loading faster
USE_BUNDLES = True
LISTINGS_FOLDERS = {'listings': 'listings', 'code': 'formatted-code'}
# Plugins you don't want to use. Be careful :-)
# DISABLED_PLUGINS = ["render_galleries"]
# Add the absolute paths to directories containing plugins to use them.
# For example, the `plugins` directory of your clone of the Nikola plugins
# repository.
# EXTRA_PLUGINS_DIRS = []
# List of regular expressions, links matching them will always be considered
# valid by "nikola check -l"
# LINK_CHECK_WHITELIST = []
# If set to True, enable optional hyphenation in your posts (requires pyphen)
# HYPHENATE = False
# The <hN> tags in HTML generated by certain compilers (reST/Markdown)
# will be demoted by that much (1 → h1 will become h2 and so on)
# This was a hidden feature of the Markdown and reST compilers in the
# past. Useful especially if your post titles are in <h1> tags too, for
# example.
# (defaults to 1.)
DEMOTE_HEADERS = 2
# You can configure the logging handlers installed as plugins or change the
# log level of the default stderr handler.
# WARNING: The stderr handler allows only the loglevels of 'INFO' and 'DEBUG'.
# This is done for safety reasons, as blocking out anything other
# than 'DEBUG' may hide important information and break the user
# experience!
LOGGING_HANDLERS = {
'stderr': {'loglevel': 'INFO', 'bubble': True},
# 'smtp': {
# 'from_addr': 'test-errors@example.com',
# 'recipients': ('test@example.com'),
# 'credentials':('testusername', 'password'),
# 'server_addr': ('127.0.0.1', 25),
# 'secure': (),
# 'level': 'DEBUG',
# 'bubble': True
# }
}
# Templates will use those filters, along with the defaults.
# Consult your engine's documentation on filters if you need help defining
# those.
# TEMPLATE_FILTERS = {}
# Put in global_context things you want available on all your templates.
# It can be anything, data, functions, modules, etc.
GLOBAL_CONTEXT = {
}
|
Bhaal22/blog.drylm.org
|
conf.py
|
Python
|
mit
| 30,140
|
[
"VisIt"
] |
46e46035d40d0187a34380b9bc70589aa156f4bea39723173a4fa089843c1fc3
|
from pathlib import Path
import platform
import warnings
import numpy as np
import pandas as pd
from pkg_resources import parse_version
import pytest
import pvlib
pvlib_base_version = \
parse_version(parse_version(pvlib.__version__).base_version)
# decorator takes one argument: the base version for which it should fail
# for example @fail_on_pvlib_version('0.7') will cause a test to fail
# on pvlib versions 0.7a, 0.7b, 0.7rc1, etc.
# test function may not take args, kwargs, or fixtures.
def fail_on_pvlib_version(version):
# second level of decorator takes the function under consideration
def wrapper(func):
# third level defers computation until the test is called
# this allows the specific test to fail at test runtime,
# rather than at decoration time (when the module is imported)
def inner():
# fail if the version is too high
if pvlib_base_version >= parse_version(version):
pytest.fail('the tested function is scheduled to be '
'removed in %s' % version)
# otherwise return the function to be executed
else:
return func()
return inner
return wrapper
# commonly used directories in the tests
TEST_DIR = Path(__file__).parent
DATA_DIR = TEST_DIR.parent / 'data'
# pytest-rerunfailures variables
RERUNS = 5
RERUNS_DELAY = 2
platform_is_windows = platform.system() == 'Windows'
skip_windows = pytest.mark.skipif(platform_is_windows,
reason='does not run on windows')
try:
import scipy
has_scipy = True
except ImportError:
has_scipy = False
requires_scipy = pytest.mark.skipif(not has_scipy, reason='requires scipy')
try:
import tables
has_tables = True
except ImportError:
has_tables = False
requires_tables = pytest.mark.skipif(not has_tables, reason='requires tables')
try:
import ephem
has_ephem = True
except ImportError:
has_ephem = False
requires_ephem = pytest.mark.skipif(not has_ephem, reason='requires ephem')
def numpy_1_10():
return parse_version(np.__version__) >= parse_version('1.10.0')
needs_numpy_1_10 = pytest.mark.skipif(
not numpy_1_10(), reason='requires numpy 1.10 or greater')
def pandas_0_22():
return parse_version(pd.__version__) >= parse_version('0.22.0')
needs_pandas_0_22 = pytest.mark.skipif(
not pandas_0_22(), reason='requires pandas 0.22 or greater')
def has_spa_c():
try:
from pvlib.spa_c_files.spa_py import spa_calc
except ImportError:
return False
else:
return True
requires_spa_c = pytest.mark.skipif(not has_spa_c(), reason="requires spa_c")
def has_numba():
try:
import numba
except ImportError:
return False
else:
vers = numba.__version__.split('.')
if int(vers[0] + vers[1]) < 17:
return False
else:
return True
requires_numba = pytest.mark.skipif(not has_numba(), reason="requires numba")
try:
import siphon
has_siphon = True
except ImportError:
has_siphon = False
requires_siphon = pytest.mark.skipif(not has_siphon,
reason='requires siphon')
try:
import netCDF4 # noqa: F401
has_netCDF4 = True
except ImportError:
has_netCDF4 = False
requires_netCDF4 = pytest.mark.skipif(not has_netCDF4,
reason='requires netCDF4')
try:
import pvfactors # noqa: F401
has_pvfactors = True
except ImportError:
has_pvfactors = False
requires_pvfactors = pytest.mark.skipif(not has_pvfactors,
reason='requires pvfactors')
try:
import PySAM # noqa: F401
has_pysam = True
except ImportError:
has_pysam = False
requires_pysam = pytest.mark.skipif(not has_pysam, reason="requires PySAM")
@pytest.fixture(scope="session")
def sam_data():
data = {}
with warnings.catch_warnings():
# ignore messages about duplicate entries in the databases.
warnings.simplefilter("ignore", UserWarning)
data['sandiamod'] = pvlib.pvsystem.retrieve_sam('sandiamod')
data['adrinverter'] = pvlib.pvsystem.retrieve_sam('adrinverter')
return data
@pytest.fixture(scope="function")
def pvsyst_module_params():
"""
Define some PVSyst module parameters for testing.
The scope of the fixture is set to ``'function'`` to allow tests to modify
parameters if required without affecting other tests.
"""
parameters = {
'gamma_ref': 1.05,
'mu_gamma': 0.001,
'I_L_ref': 6.0,
'I_o_ref': 5e-9,
'EgRef': 1.121,
'R_sh_ref': 300,
'R_sh_0': 1000,
'R_s': 0.5,
'R_sh_exp': 5.5,
'cells_in_series': 60,
'alpha_sc': 0.001,
}
return parameters
@pytest.fixture(scope='function')
def cec_inverter_parameters():
"""
Define some CEC inverter parameters for testing.
The scope of the fixture is set to ``'function'`` to allow tests to modify
parameters if required without affecting other tests.
"""
parameters = {
'Name': 'ABB: MICRO-0.25-I-OUTD-US-208 208V [CEC 2014]',
'Vac': 208.0,
'Paco': 250.0,
'Pdco': 259.5220505,
'Vdco': 40.24260317,
'Pso': 1.771614224,
'C0': -2.48e-5,
'C1': -9.01e-5,
'C2': 6.69e-4,
'C3': -0.0189,
'Pnt': 0.02,
'Vdcmax': 65.0,
'Idcmax': 10.0,
'Mppt_low': 20.0,
'Mppt_high': 50.0,
}
return parameters
@pytest.fixture(scope='function')
def cec_module_params():
"""
Define some CEC module parameters for testing.
The scope of the fixture is set to ``'function'`` to allow tests to modify
parameters if required without affecting other tests.
"""
parameters = {
'Name': 'Example Module',
'BIPV': 'Y',
'Date': '4/28/2008',
'T_NOCT': 65,
'A_c': 0.67,
'N_s': 18,
'I_sc_ref': 7.5,
'V_oc_ref': 10.4,
'I_mp_ref': 6.6,
'V_mp_ref': 8.4,
'alpha_sc': 0.003,
'beta_oc': -0.04,
'a_ref': 0.473,
'I_L_ref': 7.545,
'I_o_ref': 1.94e-09,
'R_s': 0.094,
'R_sh_ref': 15.72,
'Adjust': 10.6,
'gamma_r': -0.5,
'Version': 'MM105',
'PTC': 48.9,
'Technology': 'Multi-c-Si',
}
return parameters
@pytest.fixture(scope='function')
def cec_module_cs5p_220m():
"""
Define Canadian Solar CS5P-220M module parameters for testing.
The scope of the fixture is set to ``'function'`` to allow tests to modify
parameters if required without affecting other tests.
"""
parameters = {
'Name': 'Canadian Solar CS5P-220M',
'BIPV': 'N',
'Date': '10/5/2009',
'T_NOCT': 42.4,
'A_c': 1.7,
'N_s': 96,
'I_sc_ref': 5.1,
'V_oc_ref': 59.4,
'I_mp_ref': 4.69,
'V_mp_ref': 46.9,
'alpha_sc': 0.004539,
'beta_oc': -0.22216,
'a_ref': 2.6373,
'I_L_ref': 5.114,
'I_o_ref': 8.196e-10,
'R_s': 1.065,
'R_sh_ref': 381.68,
'Adjust': 8.7,
'gamma_r': -0.476,
'Version': 'MM106',
'PTC': 200.1,
'Technology': 'Mono-c-Si',
}
return parameters
@pytest.fixture(scope='function')
def cec_module_spr_e20_327():
"""
Define SunPower SPR-E20-327 module parameters for testing.
The scope of the fixture is set to ``'function'`` to allow tests to modify
parameters if required without affecting other tests.
"""
parameters = {
'Name': 'SunPower SPR-E20-327',
'BIPV': 'N',
'Date': '1/14/2013',
'T_NOCT': 46,
'A_c': 1.631,
'N_s': 96,
'I_sc_ref': 6.46,
'V_oc_ref': 65.1,
'I_mp_ref': 5.98,
'V_mp_ref': 54.7,
'alpha_sc': 0.004522,
'beta_oc': -0.23176,
'a_ref': 2.6868,
'I_L_ref': 6.468,
'I_o_ref': 1.88e-10,
'R_s': 0.37,
'R_sh_ref': 298.13,
'Adjust': -0.1862,
'gamma_r': -0.386,
'Version': 'NRELv1',
'PTC': 301.4,
'Technology': 'Mono-c-Si',
}
return parameters
@pytest.fixture(scope='function')
def cec_module_fs_495():
"""
Define First Solar FS-495 module parameters for testing.
The scope of the fixture is set to ``'function'`` to allow tests to modify
parameters if required without affecting other tests.
"""
parameters = {
'Name': 'First Solar FS-495',
'BIPV': 'N',
'Date': '9/18/2014',
'T_NOCT': 44.6,
'A_c': 0.72,
'N_s': 216,
'I_sc_ref': 1.55,
'V_oc_ref': 86.5,
'I_mp_ref': 1.4,
'V_mp_ref': 67.9,
'alpha_sc': 0.000924,
'beta_oc': -0.22741,
'a_ref': 2.9482,
'I_L_ref': 1.563,
'I_o_ref': 2.64e-13,
'R_s': 6.804,
'R_sh_ref': 806.27,
'Adjust': -10.65,
'gamma_r': -0.264,
'Version': 'NRELv1',
'PTC': 89.7,
'Technology': 'CdTe',
}
return parameters
@pytest.fixture(scope='function')
def sapm_temperature_cs5p_220m():
# SAPM temperature model parameters for Canadian_Solar_CS5P_220M
# (glass/polymer) in open rack
return {'a': -3.40641, 'b': -0.0842075, 'deltaT': 3}
@pytest.fixture(scope='function')
def sapm_module_params():
"""
Define SAPM model parameters for Canadian Solar CS5P 220M module.
The scope of the fixture is set to ``'function'`` to allow tests to modify
parameters if required without affecting other tests.
"""
parameters = {'Material': 'c-Si',
'Cells_in_Series': 96,
'Parallel_Strings': 1,
'A0': 0.928385,
'A1': 0.068093,
'A2': -0.0157738,
'A3': 0.0016606,
'A4': -6.93E-05,
'B0': 1,
'B1': -0.002438,
'B2': 0.0003103,
'B3': -0.00001246,
'B4': 2.11E-07,
'B5': -1.36E-09,
'C0': 1.01284,
'C1': -0.0128398,
'C2': 0.279317,
'C3': -7.24463,
'C4': 0.996446,
'C5': 0.003554,
'C6': 1.15535,
'C7': -0.155353,
'Isco': 5.09115,
'Impo': 4.54629,
'Voco': 59.2608,
'Vmpo': 48.3156,
'Aisc': 0.000397,
'Aimp': 0.000181,
'Bvoco': -0.21696,
'Mbvoc': 0.0,
'Bvmpo': -0.235488,
'Mbvmp': 0.0,
'N': 1.4032,
'IXO': 4.97599,
'IXXO': 3.18803,
'FD': 1}
return parameters
|
anomam/pvlib-python
|
pvlib/tests/conftest.py
|
Python
|
bsd-3-clause
| 10,997
|
[
"pysam"
] |
8597a94ca01a780d757ec4ea93fc93d01cdffa40d1ad554e7063eb90a0dbad7b
|
from django.conf import settings
from django.conf.urls import include, url
from django.conf.urls.static import static
from django.contrib import admin
from django.views.generic import TemplateView
from django.views import defaults as default_views
from statapp.views import dcv_validation
urlpatterns = [
url(r'^$', TemplateView.as_view(template_name='pages/home.html'), name='home'),
url(r'^about/$', TemplateView.as_view(template_name='pages/about.html'), name='about'),
url(r'^dash/$', TemplateView.as_view(template_name='pages/dash.html'), name='dash'),
url(r'^store/$', TemplateView.as_view(template_name='pages/store.html'), name='store'),
url(r'^contact/', include('contact_form.urls')),
# url(r'^28DEBB2B1A4DBCD4063E02EDE09592EB.txt$', dcv_validation, name='dcv_validation'),
# Django Admin, use {% url 'admin:index' %}
url(settings.ADMIN_URL, admin.site.urls),
# User management
url(r'^users/', include('statapp.users.urls', namespace='users')),
url(r'^accounts/', include('allauth.urls')),
# Your stuff: custom urls includes go here
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
if settings.DEBUG:
# This allows the error pages to be debugged during development, just visit
# these url in browser to see how these error pages look like.
urlpatterns += [
url(r'^400/$', default_views.bad_request, kwargs={'exception': Exception('Bad Request!')}),
url(r'^403/$', default_views.permission_denied, kwargs={'exception': Exception('Permission Denied')}),
url(r'^404/$', default_views.page_not_found, kwargs={'exception': Exception('Page not Found')}),
url(r'^500/$', default_views.server_error),
]
if 'debug_toolbar' in settings.INSTALLED_APPS:
import debug_toolbar
urlpatterns = [
url(r'^__debug__/', include(debug_toolbar.urls)),
] + urlpatterns
|
AndrewBorst/statapp
|
config/urls.py
|
Python
|
mit
| 1,917
|
[
"VisIt"
] |
f6459c944abed4fbb2458fa7f820d4a2a6a07254bd6ce58dfc1597c504af64e1
|
#!/usr/bin/env python3
import re
import requests
from urllib.parse import urlsplit
def get_content(url):
spit_base_url = "https://spit.mixtape.moe/view/download/"
paste_info = {
'site': 'mixtape',
'url': url,
}
fragments = urlsplit(url)
subdomain = fragments.netloc.split(".")[0]
if subdomain == "spit": # we have a paste
ext = ""
paste_id = fragments.path.split("/")[-1]
content_url = spit_base_url + paste_id
elif subdomain == "my": # we have other content
paste_id, ext = fragments.path.split("/", 1)[-1].split(".", 1)
content_url = url
else:
return
response = requests.get(content_url)
if response.status_code != 200:
return
paste_info['ext'] = ext
paste_info['orig_filename'] = paste_id
paste_info['content'] = response.content
return [paste_info]
|
luceatnobis/harvester
|
harvester/mixtape/__init__.py
|
Python
|
unlicense
| 891
|
[
"MOE"
] |
065ac74d67a65364da2dd42e22542fc7ddba3d1c76ba009543982e15ba38cee9
|
"""HTTP related handlers.
Note that some other HTTP handlers live in more specific modules: _auth.py,
_gzip.py, etc.
Copyright 2002-2006 John J Lee <jjl@pobox.com>
This code is free software; you can redistribute it and/or modify it
under the terms of the BSD or ZPL 2.1 licenses (see the file
COPYING.txt included with the distribution).
"""
from __future__ import absolute_import
import logging
import socket
import time
from io import BytesIO
from . import _rfc3986, _sockettimeout
from ._headersutil import is_html
from ._request import Request
from ._response import response_seek_wrapper
from ._urllib2_fork import BaseHandler, HTTPError
from ._equiv import HTTPEquivParser
from .polyglot import create_response_info, RobotFileParser, is_py2, as_unicode
debug = logging.getLogger("mechanize").debug
debug_robots = logging.getLogger("mechanize.robots").debug
def parse_head(fileobj):
"""Return a list of key, value pairs."""
p = HTTPEquivParser(fileobj.read(4096))
return p()
class HTTPEquivProcessor(BaseHandler):
"""Append META HTTP-EQUIV headers to regular HTTP headers."""
handler_order = 300 # before handlers that look at HTTP headers
def http_response(self, request, response):
if not hasattr(response, "seek"):
response = response_seek_wrapper(response)
http_message = response.info()
url = response.geturl()
ct_hdrs = http_message.getheaders("content-type")
if is_html(ct_hdrs, url, True):
try:
try:
html_headers = parse_head(response)
finally:
response.seek(0)
except Exception:
pass
else:
for hdr, val in html_headers:
if is_py2:
# add a header
http_message.dict[hdr.lower()] = val
text = hdr + b": " + val
for line in text.split(b"\n"):
http_message.headers.append(line + b"\n")
else:
hdr = hdr.decode('iso-8859-1')
http_message[hdr] = val.decode('iso-8859-1')
return response
https_response = http_response
class MechanizeRobotFileParser(RobotFileParser):
def __init__(self, url='', opener=None):
RobotFileParser.__init__(self, url)
self._opener = opener
self._timeout = _sockettimeout._GLOBAL_DEFAULT_TIMEOUT
def set_opener(self, opener=None):
from . import _opener
if opener is None:
opener = _opener.OpenerDirector()
self._opener = opener
def set_timeout(self, timeout):
self._timeout = timeout
def read(self):
"""Reads the robots.txt URL and feeds it to the parser."""
if self._opener is None:
self.set_opener()
req = Request(self.url, unverifiable=True, visit=False,
timeout=self._timeout)
try:
f = self._opener.open(req)
except HTTPError as f:
pass
except (IOError, socket.error, OSError) as exc:
debug_robots("ignoring error opening %r: %s" %
(self.url, exc))
return
lines = []
line = f.readline()
while line:
lines.append(line.strip())
line = f.readline()
status = f.code
if status == 401 or status == 403:
self.disallow_all = True
debug_robots("disallow all")
elif status >= 400:
self.allow_all = True
debug_robots("allow all")
elif status == 200 and lines:
debug_robots("parse lines")
if is_py2:
self.parse(lines)
else:
self.parse(map(as_unicode, lines))
class RobotExclusionError(HTTPError):
def __init__(self, request, *args):
HTTPError.__init__(self, *args)
self.request = request
class HTTPRobotRulesProcessor(BaseHandler):
# before redirections, after everything else
handler_order = 800
http_response_class = None
def __init__(self, rfp_class=MechanizeRobotFileParser):
self.rfp_class = rfp_class
self.rfp = None
self._host = None
def __copy__(self):
return self.__class__(self.rfp_class)
def http_request(self, request):
scheme = request.get_type()
if scheme not in ["http", "https"]:
# robots exclusion only applies to HTTP
return request
if request.get_selector() == "/robots.txt":
# /robots.txt is always OK to fetch
return request
host = request.get_host()
# robots.txt requests don't need to be allowed by robots.txt :-)
origin_req = getattr(request, "_origin_req", None)
if (origin_req is not None and
origin_req.get_selector() == "/robots.txt" and
origin_req.get_host() == host):
return request
if host != self._host:
self.rfp = self.rfp_class()
try:
self.rfp.set_opener(self.parent)
except AttributeError:
debug("%r instance does not support set_opener" %
self.rfp.__class__)
self.rfp.set_url(scheme + "://" + host + "/robots.txt")
self.rfp.set_timeout(request.timeout)
self.rfp.read()
self._host = host
ua = request.get_header("User-agent", "")
if self.rfp.can_fetch(ua, request.get_full_url()):
return request
else:
# XXX This should really have raised URLError. Too late now...
factory = self.http_response_class or create_response_info
msg = b"request disallowed by robots.txt"
raise RobotExclusionError(
request,
request.get_full_url(),
403, msg,
factory(BytesIO()), BytesIO(msg))
https_request = http_request
class HTTPRefererProcessor(BaseHandler):
"""Add Referer header to requests.
This only makes sense if you use each RefererProcessor for a single
chain of requests only (so, for example, if you use a single
HTTPRefererProcessor to fetch a series of URLs extracted from a single
page, this will break).
There's a proper implementation of this in mechanize.Browser.
"""
def __init__(self):
self.referer = None
def http_request(self, request):
if ((self.referer is not None) and
not request.has_header("Referer")):
request.add_unredirected_header("Referer", self.referer)
return request
def http_response(self, request, response):
self.referer = response.geturl()
return response
https_request = http_request
https_response = http_response
def clean_refresh_url(url):
# e.g. Firefox 1.5 does (something like) this
if ((url.startswith('"') and url.endswith('"')) or
(url.startswith("'") and url.endswith("'"))):
url = url[1:-1]
return _rfc3986.clean_url(url, 'utf-8') # XXX encoding
def parse_refresh_header(refresh):
"""
>>> parse_refresh_header("1; url=http://example.com/")
(1.0, 'http://example.com/')
>>> parse_refresh_header("1; url='http://example.com/'")
(1.0, 'http://example.com/')
>>> parse_refresh_header("1")
(1.0, None)
>>> parse_refresh_header("blah") # doctest: +IGNORE_EXCEPTION_DETAIL
Traceback (most recent call last):
ValueError: invalid literal for float(): blah
"""
ii = refresh.find(";")
if ii != -1:
pause, newurl_spec = float(refresh[:ii]), refresh[ii + 1:]
jj = newurl_spec.find("=")
key = None
if jj != -1:
key, newurl = newurl_spec[:jj], newurl_spec[jj + 1:]
newurl = clean_refresh_url(newurl)
if key is None or key.strip().lower() != "url":
raise ValueError()
else:
pause, newurl = float(refresh), None
return pause, newurl
class HTTPRefreshProcessor(BaseHandler):
"""Perform HTTP Refresh redirections.
Note that if a non-200 HTTP code has occurred (for example, a 30x
redirect), this processor will do nothing.
By default, only zero-time Refresh headers are redirected. Use the
max_time attribute / constructor argument to allow Refresh with longer
pauses. Use the honor_time attribute / constructor argument to control
whether the requested pause is honoured (with a time.sleep()) or
skipped in favour of immediate redirection.
Public attributes:
max_time: see above
honor_time: see above
"""
handler_order = 1000
def __init__(self, max_time=0, honor_time=True):
self.max_time = max_time
self.honor_time = honor_time
self._sleep = time.sleep
def __copy__(self):
return self.__class__(self.max_time, self.honor_time)
def http_response(self, request, response):
code, msg, hdrs = response.code, response.msg, response.info()
if code == 200 and 'refresh' in hdrs:
refresh = hdrs.getheaders("refresh")[0]
try:
pause, newurl = parse_refresh_header(refresh)
except ValueError:
debug("bad Refresh header: %r" % refresh)
return response
if newurl is None:
newurl = response.geturl()
if (self.max_time is None) or (pause <= self.max_time):
if pause > 1E-3 and self.honor_time:
self._sleep(pause)
hdrs["location"] = newurl
# hardcoded http is NOT a bug
response = self.parent.error(
"http", request, response,
"refresh", msg, hdrs)
else:
debug("Refresh header ignored: %r" % refresh)
return response
https_response = http_response
|
Masood-M/yalih
|
mechanize/_http.py
|
Python
|
apache-2.0
| 10,064
|
[
"VisIt"
] |
0ba5bc641774071dc9fe2a306f4508b80bdf39d0e777dbaf730c9e22d479925b
|
#!/usr/bin/env python
import rospy
from geometry_msgs.msg import Twist
from turtlesim.msg import Pose
from math import pow,atan2,sqrt
import numpy as np
class turtle():
def __init__(self):
#Creating our node,publisher and subscriber
rospy.init_node('turtlebot_controller', anonymous=True)
self.velocity_publisher = rospy.Publisher('/turtle1/cmd_vel', Twist, queue_size=10)
self.pose_subscriber = rospy.Subscriber('/turtle1/pose', Pose, self.callback)
self.pose = Pose()
self.rate = rospy.Rate(10)
#This is the tolerance of the controller, because the turtlesim is not the most accurate simulator
self.tolerance = 0.1
#Callback function implementing the pose value received
#This saves the current position of the turtle in global coordinate system
def callback(self, data):
self.pose = data
self.pose.x = round(self.pose.x, 4)
self.pose.y = round(self.pose.y, 4)
#Distance to the actual goal
def get_distance(self, goal_x, goal_y):
distance = sqrt(pow((goal_x - self.pose.x), 2) + pow((goal_y - self.pose.y), 2))
return distance
#This function drives the correct behavior of the robot in the turtle sim map
def move2goal(self,posX,posY):
goal_pose = Pose()
goal_pose.x = posX
goal_pose.y = posY
distance_tolerance = self.tolerance
vel_msg = Twist()
while sqrt(pow((goal_pose.x - self.pose.x), 2) + pow((goal_pose.y - self.pose.y), 2)) >= distance_tolerance:
#Porportional Controller
#linear velocity in the x-axis:
vel_msg.linear.x = 1.5 * sqrt(pow((goal_pose.x - self.pose.x), 2) + pow((goal_pose.y - self.pose.y), 2))
vel_msg.linear.y = 0
vel_msg.linear.z = 0
#angular velocity in the z-axis:
vel_msg.angular.x = 0
vel_msg.angular.y = 0
vel_msg.angular.z = 4 * (atan2(goal_pose.y - self.pose.y, goal_pose.x - self.pose.x) - self.pose.theta)
#Publishing our vel_msg
self.velocity_publisher.publish(vel_msg)
self.rate.sleep()
#Stopping our robot after the movement is over
vel_msg.linear.x = 0
vel_msg.angular.z =0
self.velocity_publisher.publish(vel_msg)
def create_list_from_mission_plan(mission_plan):
coordinates = []
for mission in mission_plan :
currTask = mission[0]
currWayPoints = mission[1]
if currTask is 'SHORTESTPATH' :
currWayPoints = currWayPoints
for wp in currWayPoints :
coordinates.append(wp)
return coordinates
if __name__ == '__main__':
try:
#creating a turtle object
tb = turtle()
#list of coordinates to visit
#This can is the only thing to change in the model to text
mission = [['LINE',[(1,1),(1,2),(3,3),(6,6),(10,10),(1,1)]], ['LINE',[(1,1),(1,2),(3,3),(6,6),(10,10),(1,1)]] ]
coordinate_list = create_list_from_mission_plan(mission)
#making the the turtle follow the coordinates in sequence
for coordinate in coordinate_list:
x,y = coordinate
tb.move2goal(x,y)
except rospy.ROSInterruptException: pass
|
kribe48/wasp-mbse
|
WASP-turtlebot-DSL/ros_node_old.py
|
Python
|
mit
| 3,221
|
[
"VisIt"
] |
d70c2cea8c8ea66d3b3cb0c4ce03ec61d5259fffc018a97c452bba371154f5a0
|
"""Classes for ODHQLs Abstract Syntax Tree."""
from collections import Sequence
from enum import Enum
from hub.odhql.exceptions import TokenException
class ASTBase(object):
"""Base class for all AST classes."""
def accept(self, visitor):
""" Basic support for the visitor pattern. """
visitor.visit(self)
class Union(ASTBase):
"""Result for union queries."""
def __init__(self, queries, order):
"""
:type queries: list
:type order: list
"""
self.queries = queries
self.order = order
@classmethod
def parse(cls, tokens):
""" Convert pyparsings ParseResult into AST classes """
if len(tokens) < 1:
raise TokenException('malformed Union (no queries)')
if len(tokens) < 2:
return
queries = list(tokens.get('queries'))
order = list(tokens.get('sort')[0]) if 'sort' in tokens else []
return cls(queries, order)
def __repr__(self):
return '<Union queries={} order={}>'.format(self.queries, self.order)
def accept(self, visitor):
""" Basic support for the visitor pattern. """
visitor.visit(self)
for q in self.queries:
q.accept(visitor)
if self.order:
for o in self.order:
o.accept(visitor)
class Query(ASTBase):
"""Result for normal queries."""
def __init__(self, fields, data_sources, filter_definitions):
"""
:type fields: list
:type data_sources: list
:type filter_definitions: list
"""
self.fields = fields
self.data_sources = data_sources
self.filter_definitions = filter_definitions
@classmethod
def parse(cls, tokens):
""" Convert pyparsings ParseResult into AST classes """
if 'fields' not in tokens:
raise TokenException('malformed Query (no fields)')
if 'datasources' not in tokens:
raise TokenException('malformed Query (no data sources)')
fields = list(tokens.get('fields'))
data_sources = list(tokens.get('datasources'))
filter_definitions = tokens.get('filter')[0] if 'filter' in tokens else None
return cls(fields, data_sources, filter_definitions)
@classmethod
def parse_order_by(cls, tokens):
""" Convert pyparsings ParseResult into AST classes """
if 'fields' not in tokens:
raise TokenException('malformed OrderBy (no fields)')
return [tokens.get('fields')]
def __repr__(self):
return '<Query fields={} data_sources={} filter_definitions={}>'.format(self.fields, self.data_sources,
self.filter_definitions)
def accept(self, visitor):
""" Basic support for the visitor pattern. """
visitor.visit(self)
for f in self.fields:
f.accept(visitor)
for d in self.data_sources:
d.accept(visitor)
if self.filter_definitions:
for f in self.filter_definitions:
f.accept(visitor)
class Expression(ASTBase):
"""Base class for expression types."""
class Field(Expression):
"""Reference a field in a table."""
def __init__(self, name, prefix=None):
self.prefix = prefix
self.name = name
def __repr__(self):
return '<Field name=\'{}\' prefix=\'{}\'>'.format(self.name, self.prefix)
@classmethod
def parse(cls, tokens):
""" Convert pyparsings ParseResult into AST classes """
if 'name' not in tokens:
raise TokenException('malformed Field (name not found)')
if 'prefix' not in tokens:
raise TokenException('malformed Field (prefix not found)')
name = tokens.get('name')
prefix = tokens.get('prefix')
return cls(name, prefix)
class LiteralExpression(Expression):
"""Literal values are numbers, static strings, bools, null values..."""
def __init__(self, value):
self.value = value
def __repr__(self):
return '<LiteralExpression value={}>'.format(self.value)
@classmethod
def parse(cls, tokens):
""" Convert pyparsings ParseResult into AST classes """
if 'value' not in tokens:
raise TokenException('malformed Expression (no value)')
value = tokens.get('value')
return cls(value)
@classmethod
def parse_number(cls, tokens):
""" Parse number expressions into actual python numbers. """
try:
num = tokens.pop()
if len(num) > 1:
joined = ''.join(num)
return [float(joined)]
else:
return [int(num.pop())]
except ValueError:
pass
@classmethod
def parse_boolean(cls, tokens):
""" Parse boolean expressions into python booleans. """
if len(tokens) < 1:
raise TokenException('malformed boolean value (no value)')
value = tokens[0]
return [str(value).lower() == 'true']
@classmethod
def parse_null(cls):
""" Parse null expressions into None. """
return [None]
class CaseRule(ASTBase):
"""
A single rule ('when <condition> then <expression>' or 'else <expression>') in a case expression.
"""
def __init__(self, condition, expression):
"""
:type condition: any condition or types.NoneType
:type expression: hub.odhql.ast.Expression
"""
self.condition = condition
self.expression = expression
@classmethod
def parse_when(cls, tokens):
""" Convert pyparsings ParseResult into AST classes """
if 'condition' not in tokens:
raise TokenException('malformed CaseExpression (expected condition)')
if 'expression' not in tokens:
raise TokenException('malformed CaseExpression (expected expression)')
condition = tokens.get('condition')
expression = tokens.get('expression')
return cls(condition, expression)
@classmethod
def parse_else(cls, tokens):
""" Convert pyparsings ParseResult into AST classes """
if 'expression' not in tokens:
raise TokenException('malformed CaseExpression (expected expression)')
expression = tokens.get('expression')
return cls(None, expression)
def __repr__(self):
return '<CaseRule condition={} expression={}>'.format(self.condition, self.expression)
def accept(self, visitor):
""" Basic support for the visitor pattern. """
visitor.visit(self)
if self.condition:
self.condition.accept(visitor)
self.expression.accept(visitor)
class CaseExpression(Expression):
"""
'case when ... then ... end' expressions.
"""
def __init__(self, rules):
self.rules = rules
@classmethod
def parse(cls, tokens):
""" Convert pyparsings ParseResult into AST classes """
if 'when' not in tokens:
raise TokenException('malformed CaseExpression (expected at least one condition)')
rules = tokens.get('when')[:]
if 'else' in tokens:
rules.append(tokens.get('else')[0])
return cls(rules)
def accept(self, visitor):
""" Basic support for the visitor pattern. """
visitor.visit(self)
for r in self.rules:
r.accept(visitor)
def __repr__(self):
return '<CaseExpression rules={}>'.format(self.rules)
class AliasedExpression(ASTBase):
"""Expression with an alias"""
def __init__(self, expression, alias):
self.expression = expression
self.alias = alias
def __repr__(self):
return '<AliasedExpression expression={} alias=\'{}\'>'.format(self.expression, self.alias)
@classmethod
def parse(cls, tokens):
""" Convert pyparsings ParseResult into AST classes """
if 'expression' not in tokens and 'field' not in tokens:
raise TokenException('malformed AliasedExpression (no expression or field)')
if 'alias' not in tokens and 'field' not in tokens: # fields don't need an alias
raise TokenException('malformed AliasedExpression (no alias)')
if 'field' in tokens:
expression = tokens.get('field')
assert isinstance(expression, Field)
alias = tokens.get('alias', expression.name)
else:
expression = tokens.get('expression')
if not isinstance(expression, Expression):
raise TokenException('expected Expression, got {}'.format(type(expression)))
alias = tokens.get('alias')
return cls(expression, alias)
def accept(self, visitor):
""" Basic support for the visitor pattern. """
visitor.visit(self)
self.expression.accept(visitor)
class Function(Expression):
"""Function call. These may be nested."""
def __init__(self, name, args):
"""
:type name: unicode
:type args: list
"""
self.name = name
self.args = args
@classmethod
def parse(cls, tokens):
""" Convert pyparsings ParseResult into AST classes """
if 'name' not in tokens:
raise TokenException('malformed Function (no name)')
name = tokens.get('name')
# this one is weird: access by name makes it almost impossible to get a simple list of our own
# classes (i.e. no ParseResults)
args = list(tokens.get('args')) if 'args' in tokens else [] # get rid of ParseResult
return cls(name, args)
def __repr__(self):
return '<Function name=\'{}\' args={}>'.format(self.name, self.args or '')
def accept(self, visitor):
""" Basic support for the visitor pattern. """
visitor.visit(self)
for arg in self.args:
arg.accept(visitor)
class DataSource(ASTBase):
"""Reference to a data source (dataframe)"""
def __init__(self, name, alias=None):
"""
:type name: unicode
:type alias: unicode
"""
self.name = name
self.alias = alias or name
@classmethod
def parse(cls, tokens):
""" Convert pyparsings ParseResult into AST classes """
if len(tokens) < 1:
raise TokenException()
name = tokens.get('name')
alias = tokens.get('alias', None)
return cls(name, alias)
def __repr__(self):
return '<DataSource name=\'{}\' alias=\'{}\'>'.format(self.name, self.alias)
class JoinCondition(ASTBase):
"""Single join condition."""
def __init__(self, left, right):
"""
:type left: hub.odhql.ast.Field
:type right: hub.odhql.ast.Field
"""
self.left = left
self.right = right
@classmethod
def parse(cls, tokens):
""" Convert pyparsings ParseResult into AST classes """
if 'left' not in tokens or 'right' not in tokens:
raise TokenException('invalid join condition')
left = tokens.get('left')
right = tokens.get('right')
return cls(left, right)
def __repr__(self):
return '<JoinCondition left={} right={}>'.format(self.left, self.right)
def accept(self, visitor):
""" Basic support for the visitor pattern. """
visitor.visit(self)
self.left.accept(visitor)
self.right.accept(visitor)
class JoinConditionList(ASTBase, Sequence):
"""List of join conditions. All of these must match for a join - 'or' is not supported."""
def __init__(self, conditions):
"""
:param conditions: list of hub.odhql.ast.JoinCondition
"""
self.conditions = conditions
def __len__(self):
return len(self.conditions)
def __getitem__(self, index):
return self.conditions[index]
@classmethod
def parse(cls, tokens):
""" Convert pyparsings ParseResult into AST classes """
if len(tokens) == 0:
raise TokenException()
conditions = list(tokens.get('conditions'))
return cls(conditions)
def __repr__(self):
return '<JoinConditionList conditions={}>'.format(self.conditions)
def accept(self, visitor):
""" Basic support for the visitor pattern. """
visitor.visit(self)
for cond in self.conditions:
cond.accept(visitor)
class JoinedDataSource(DataSource):
"""Data source added via join. All data source after the first are of this type."""
class JoinType(Enum):
"""Join type."""
inner = 1
left = 2
right = 3
outer = 4
def __init__(self, name, alias, join_type, condition):
"""
:param name: Data source name
:param alias: Alias (may be identical to the name)
:param join_type: Join type.
:param condition: hub.odhql.ast.JoinCondition
"""
super(JoinedDataSource, self).__init__(name, alias)
self.join_type = join_type
self.condition = condition
@classmethod
def parse(cls, tokens):
""" Convert pyparsings ParseResult into AST classes """
if 'datasource' not in tokens:
raise TokenException('join without datasource')
if 'condition' not in tokens:
raise TokenException('join without conditions')
datasource = tokens.get('datasource')
join_type = tokens.get('join_type')
condition = tokens.get('condition')
return cls(datasource.name, datasource.alias, join_type, condition)
@classmethod
def parse_join_type(cls, tokens):
""" Convert join type expression into JoinType enum value. Default is inner join. """
lower_tokens = [token.lower() for token in tokens if isinstance(token, basestring)]
if 'left' in lower_tokens:
return cls.JoinType.left
elif 'right' in lower_tokens:
return cls.JoinType.right
elif 'full' in lower_tokens or 'outer' in lower_tokens:
return cls.JoinType.outer
return cls.JoinType.inner
def __repr__(self):
return '<JoinedDataSource name=\'{}\' alias=\'{}\' condition={}>'.format(self.name, self.alias, self.condition)
def accept(self, visitor):
""" Basic support for the visitor pattern. """
visitor.visit(self)
self.condition.accept(visitor)
class BinaryCondition(ASTBase):
"""Condition with two sides (thus binary)"""
class Operator(Enum):
"""Operators for binary conditions."""
equals = 1
not_equals = 2
less = 3
less_or_equal = 4
greater = 5
greater_or_equal = 6
like = 7
not_like = 8
def __init__(self, left, operator, right):
"""
:type left: hub.odhql.ast.Expression
:type operator: hub.odhql.ast.Operator
:type right: hub.odhql.ast.Expression
"""
self.left = left
self.operator = operator
self.right = right
@classmethod
def parse(cls, tokens):
""" Convert pyparsings ParseResult into AST classes """
if 'left' not in tokens:
raise TokenException('malformed BinaryCondition (no left side)')
if 'right' not in tokens:
raise TokenException('malformed BinaryCondition (no right side)')
if 'operator' not in tokens:
raise TokenException('malformed BinaryCondition (no operator)')
left = tokens.get('left')
right = tokens.get('right')
op = tokens.get('operator')
return cls(left, op, right)
@classmethod
def parse_operator(cls, tokens):
""" Convert operator expressions into Operator enum values. """
if len(tokens) < 1:
raise TokenException('malformed operator (no operator)')
op = tokens[0]
if op == '=':
return cls.Operator.equals
if op == '!=':
return cls.Operator.not_equals
if op == '<':
return cls.Operator.less
if op == '<=':
return cls.Operator.less_or_equal
if op == '>':
return cls.Operator.greater
if op == '>=':
return cls.Operator.greater_or_equal
if str(op).lower() == 'like':
return cls.Operator.like
if str(op).lower() == 'not' and str(tokens[1]).lower() == 'like':
return cls.Operator.not_like
raise TokenException('unregistered operation: {}'.format(op))
def __repr__(self):
return '<BinaryCondition left={} op={} right={}>'.format(self.left, self.operator, self.right)
def accept(self, visitor):
""" Basic support for the visitor pattern. """
visitor.visit(self)
self.left.accept(visitor)
self.right.accept(visitor)
class InCondition(ASTBase):
"""'<left> [not] in <list>' condition."""
def __init__(self, left, in_list, invert):
"""
:param left: hub.odhql.ast.Expression
:param in_list: list of hub.odhql.ast.Expression
:param invert: bool
"""
self.left = left
self.in_list = in_list
self.invert = invert
@classmethod
def parse(cls, tokens):
""" Convert pyparsings ParseResult into AST classes """
if 'left' not in tokens:
raise TokenException('malformed InCondition (no left side)')
if 'in_list' not in tokens:
raise TokenException('malformed InCondition (no in_list)')
left = tokens.get('left')
in_list = tokens.get('in_list')
invert = 'invert' in tokens
return cls(left, in_list, invert)
def __repr__(self):
return '<InCondition left={} in_list={}>'.format(self.left, self.in_list)
def accept(self, visitor):
""" Basic support for the visitor pattern. """
visitor.visit(self)
self.left.accept(visitor)
for item in self.in_list:
item.accept(visitor)
class IsNullCondition(ASTBase):
"""'<field> is [not] null' condition."""
def __init__(self, field, invert):
"""
:param field: hub.odhql.ast.Field
:param invert: bool
"""
self.field = field
self.invert = invert
@classmethod
def parse(cls, tokens):
""" Convert pyparsings ParseResult into AST classes """
if 'field' not in tokens:
raise TokenException('malformed IsNullCondition')
field = tokens.get('field')
invert = 'invert' in tokens
if not isinstance(field, Field):
raise TokenException('expected Field, got {}'.format(type(field)))
return cls(field, invert)
def accept(self, visitor):
""" Basic support for the visitor pattern. """
visitor.visit(self)
self.field.accept(visitor)
def __repr__(self):
return '<IsNullCondition field={} invert={}>'.format(self.field, self.invert)
class PredicateCondition(ASTBase):
"""'[not] <predicate()>' condition."""
def __init__(self, predicate, invert):
"""
:type predicate: hub.odhql.ast.Function
:type invert: bool
"""
self.predicate = predicate
self.invert = invert
@classmethod
def parse(cls, tokens):
""" Convert pyparsings ParseResult into AST classes """
if 'predicate' not in tokens:
raise TokenException('malformed PredicateCondition (no predicate)')
invert = 'invert' in tokens
predicate = tokens.get('predicate')
return cls(predicate, invert)
def accept(self, visitor):
""" Basic support for the visitor pattern. """
visitor.visit(self)
self.predicate.accept(visitor)
def __repr__(self):
return '<PredicateCondition predicate={}>'.format(self.predicate)
class FilterListBase(ASTBase, Sequence):
"""Base class for lists of filter conditions."""
def __init__(self, conditions):
"""
:type conditions: list
"""
self.conditions = conditions
@classmethod
def parse(cls, tokens):
""" Convert pyparsings ParseResult into AST classes """
if len(tokens) < 1:
raise TokenException('malformed {} (no conditions)'.format(cls.__name__))
conditions = list(tokens[:])
return [cls(conditions)]
def accept(self, visitor):
""" Basic support for the visitor pattern. """
visitor.visit(self)
for cond in self.conditions:
cond.accept(visitor)
def __len__(self):
return len(self.conditions)
def __getitem__(self, item):
return self.conditions[item]
def __repr__(self):
return '<{} conditions={}>'.format(self.__class__.__name__, self.conditions)
class FilterCombination(FilterListBase):
"""list of filters joined by AND"""
class FilterAlternative(FilterListBase):
"""list of filters joined by OR"""
class OrderByPosition(ASTBase):
"""Order by index in the field list."""
def __init__(self, position):
"""
:type position: int > 1
"""
self.position = position
@classmethod
def parse(cls, tokens):
""" Convert pyparsings ParseResult into AST classes """
if len(tokens) < 1:
raise TokenException('malformed OrderByPosition (no position)')
try:
position = int(tokens[0])
if position < 1:
raise TokenException('invalid OrderByPosition: Needs to be at least 1')
return cls(position)
except ValueError:
pass
def __repr__(self):
return '<OrderByPosition position={}>'.format(self.position)
class OrderByAlias(ASTBase):
"""Order by alias (alias == field name if no alias was specified)."""
def __init__(self, alias):
self.alias = alias
@classmethod
def parse(cls, tokens):
""" Convert pyparsings ParseResult into AST classes """
if len(tokens) < 1:
raise TokenException('malformed OrderByAlias (no alias)')
return cls(tokens[0])
def __repr__(self):
return '<OrderByAlias alias={}>'.format(self.alias)
class OrderBy(ASTBase):
"""Order by expression."""
class Direction(Enum):
""" Sort direction for order by. """
ascending = 1
descending = 2
def __init__(self, field, direction):
"""
:type field: hub.odhql.ast.OrderByPosition, hub.odhql.ast.OrderByAlias or hub.odhql.ast.Field
:type direction: hub.odhql.ast.Direction
"""
self.field = field
self.direction = direction
@classmethod
def parse(cls, tokens):
""" Convert pyparsings ParseResult into AST classes """
if 'field' not in tokens:
raise TokenException('malformed OrderByField (no field)')
field = tokens.get('field')
direction = str(tokens.get('direction', 'asc')).lower()
if direction == 'desc':
direction = OrderBy.Direction.descending
else:
direction = OrderBy.Direction.ascending
return cls(field, direction)
def __repr__(self):
return '<OrderBy field={} direction={}>'.format(self.field, self.direction)
def accept(self, visitor):
""" Basic support for the visitor pattern. """
visitor.visit(self)
self.field.accept(visitor)
|
hsr-ba-fs15-dat/opendatahub
|
src/main/python/hub/odhql/ast.py
|
Python
|
mit
| 23,543
|
[
"VisIt"
] |
c15eefea9cfd96427bcecf21ef4157a223b649dd5fba84074d0204cbf0b0ad6b
|
from ScriptingLanguage.Parser.AstNode import Ast
from ScriptingLanguage.Visitors.FunctionVisitor import visit_func_call
__author__ = 'chronium'
class FunctionCallNode(Ast):
def __init__(self, value):
super(FunctionCallNode, self).__init__(value, 'Function Call')
def visit(self):
return visit_func_call(self)
class FunctionDefNode(Ast):
def __init__(self, value):
super(FunctionDefNode, self).__init__(value, 'Function Def')
class FunctionNode(Ast):
def __init__(self, value):
super(FunctionNode, self).__init__(value, 'Function')
|
chronium/ChronoScript
|
ScriptingLanguage/Parser/AstNodes/FunctionNodes.py
|
Python
|
gpl-2.0
| 584
|
[
"VisIt"
] |
77c2f9e9f0ea8b5932c8fb4c5bc94d3fb85dab27065c2ae52bcdc63f73a6e943
|
# Copyright 2003, 2007 by Sebastian Bassi. sbassi@genesdigitales.com
# All rights reserved. This code is part of the Biopython
# distribution and governed by its license.
# Please see the LICENSE file that should have been included as part
# of this package.
"""Local Composition Complexity."""
import math
__docformat__ = "restructuredtext en"
def lcc_mult(seq, wsize):
"""Local Composition Complexity (LCC) values over sliding window.
Returns a list of floats, the LCC values for a sliding window over
the sequence.
seq - an unambiguous DNA sequence (a string or Seq object)
wsize - window size, integer
The result is the same as applying lcc_simp multiple times, but this
version is optimized for speed. The optimization works by using the
value of previous window as a base to compute the next one."""
l2 = math.log(2)
tamseq = len(seq)
try:
# Assume its a string
upper = seq.upper()
except AttributeError:
# Should be a Seq object then
upper = str(seq).upper()
compone = [0]
lccsal = [0]
for i in range(wsize):
compone.append(((i + 1) / float(wsize)) *
((math.log((i + 1) / float(wsize))) / l2))
window = seq[0:wsize]
cant_a = window.count('A')
cant_c = window.count('C')
cant_t = window.count('T')
cant_g = window.count('G')
term_a = compone[cant_a]
term_c = compone[cant_c]
term_t = compone[cant_t]
term_g = compone[cant_g]
lccsal.append(-(term_a + term_c + term_t + term_g))
tail = seq[0]
for x in range(tamseq - wsize):
window = upper[x + 1:wsize + x + 1]
if tail == window[-1]:
lccsal.append(lccsal[-1])
elif tail == 'A':
cant_a -= 1
if window.endswith('C'):
cant_c += 1
term_a = compone[cant_a]
term_c = compone[cant_c]
lccsal.append(-(term_a + term_c + term_t + term_g))
elif window.endswith('T'):
cant_t += 1
term_a = compone[cant_a]
term_t = compone[cant_t]
lccsal.append(-(term_a + term_c + term_t + term_g))
elif window.endswith('G'):
cant_g += 1
term_a = compone[cant_a]
term_g = compone[cant_g]
lccsal.append(-(term_a + term_c + term_t + term_g))
elif tail == 'C':
cant_c -= 1
if window.endswith('A'):
cant_a += 1
term_a = compone[cant_a]
term_c = compone[cant_c]
lccsal.append(-(term_a + term_c + term_t + term_g))
elif window.endswith('T'):
cant_t += 1
term_c = compone[cant_c]
term_t = compone[cant_t]
lccsal.append(-(term_a + term_c + term_t + term_g))
elif window.endswith('G'):
cant_g += 1
term_c = compone[cant_c]
term_g = compone[cant_g]
lccsal.append(-(term_a + term_c + term_t + term_g))
elif tail == 'T':
cant_t -= 1
if window.endswith('A'):
cant_a += 1
term_a = compone[cant_a]
term_t = compone[cant_t]
lccsal.append(-(term_a + term_c + term_t + term_g))
elif window.endswith('C'):
cant_c += 1
term_c = compone[cant_c]
term_t = compone[cant_t]
lccsal.append(-(term_a + term_c + term_t + term_g))
elif window.endswith('G'):
cant_g += 1
term_t = compone[cant_t]
term_g = compone[cant_g]
lccsal.append(-(term_a + term_c + term_t + term_g))
elif tail == 'G':
cant_g -= 1
if window.endswith('A'):
cant_a += 1
term_a = compone[cant_a]
term_g = compone[cant_g]
lccsal.append(-(term_a + term_c + term_t + term_g))
elif window.endswith('C'):
cant_c += 1
term_c = compone[cant_c]
term_g = compone[cant_g]
lccsal.append(-(term_a + term_c + term_t + term_g))
elif window.endswith('T'):
cant_t += 1
term_t = compone[cant_t]
term_g = compone[cant_g]
lccsal.append(-(term_a + term_c + term_t + term_g))
tail = window[0]
return lccsal
def lcc_simp(seq):
"""Local Composition Complexity (LCC) for a sequence.
seq - an unambiguous DNA sequence (a string or Seq object)
Returns the Local Composition Complexity (LCC) value for the entire
sequence (as a float).
Reference:
Andrzej K Konopka (2005) Sequence Complexity and Composition
DOI: 10.1038/npg.els.0005260
"""
wsize = len(seq)
try:
# Assume its a string
upper = seq.upper()
except AttributeError:
# Should be a Seq object then
upper = str(seq).upper()
l2 = math.log(2)
if 'A' not in seq:
term_a = 0
# Check to avoid calculating the log of 0.
else:
term_a = ((upper.count('A')) / float(wsize)) * ((math.log((upper.count('A'))
/ float(wsize))) / l2)
if 'C' not in seq:
term_c = 0
else:
term_c = ((upper.count('C')) / float(wsize)) * ((math.log((upper.count('C'))
/ float(wsize))) / l2)
if 'T' not in seq:
term_t = 0
else:
term_t = ((upper.count('T')) / float(wsize)) * ((math.log((upper.count('T'))
/ float(wsize))) / l2)
if 'G' not in seq:
term_g = 0
else:
term_g = ((upper.count('G')) / float(wsize)) * ((math.log((upper.count('G'))
/ float(wsize))) / l2)
return -(term_a + term_c + term_t + term_g)
|
Ambuj-UF/ConCat-1.0
|
src/Utils/Bio/SeqUtils/lcc.py
|
Python
|
gpl-2.0
| 6,135
|
[
"Biopython"
] |
9d480e03316dc3a3b95305406dada74c84105aae43ca99b2b9b298ff1461c641
|
#!/usr/bin/python
from math import ceil
class OverlapException:
pass
class OutOfRackException:
pass
class RackFullException:
pass
unitsize = 43.5
class Rack(object):
def __init__(self, name, attr, units):
self._name = name
self.units = units
self.affinity = "bottom"
self._elements = {}
self.__attributes = attr
## size things
self.width = 445
self.height = unitsize * self.units
def addElement(self, position, element):
if position > self.units or position < 0:
raise OutOfRackException
if self._elements.has_key(position):
raise OverlapException
if element.units > 1:
for i in range(position+1, position + element.units):
if i > self.units or i < 0:
raise OutOfRackException
if self._elements.has_key(i):
raise OverlapException
# all ok, place the element
self._elements[position] = element
for i in range(position + 1, position + element.units):
self._elements[i] = None
def visit(self, visitor):
return visitor.visitRack(self)
def _get_network(self):
ports = 0
for e in self._elements.keys():
if self._elements[e] is not None:
ports += self._elements[e].network
return ports
network = property(_get_network)
def _get_units(self):
return self._units
def _set_units(self, value):
self._units = int(value)
units = property(_get_units, _set_units)
def _get_power(self):
n = 0
for e in self._elements.keys():
if self._elements[e] is not None:
n += self._elements[e].power
return n
power = property(_get_power)
def __iadd__(self, o):
if self.affinity == "bottom":
r = range(0, self.units - o.units + 1)
else:
r = range(self.units - o.units, -1, -1)
for pos in r:
if not self._elements.has_key(pos):
try:
for i in range(pos+1, pos + o.units):
if self._elements.has_key(i):
raise OverlapException
except OverlapException:
continue
# all ok, place element
for i in range(pos+1, pos+o.units):
self._elements[i] = None
self._elements[pos] = o
break
if o not in self._elements.values():
raise RackFullException
return self
def update(self, d):
self.__dict__.update(d)
def _get_depth(self):
if self.__attributes.has_key('depth'):
return self.__attributes['depth']
else:
return 0
def _set_depth(self, value):
self.__attributes['depth'] = value
depth = property(_get_depth, _set_depth)
class RackElement(object):
def __init__(self, units=1, name="rack element", network=1, power=1, cliplock=4, image="", notes=""):
self.units = units
self.name = name
self.network = network
self.power = power
self.cliplock = cliplock
self.image = image
self.notes = notes
self._elements = []
print "units on %s is %s" % (self.__class__.__name__, units)
self._baseline = units * unitsize
print "baseline on %s is %s" % (self.__class__.__name__, self._baseline)
# evil hack
self.gap = 0
def addElement(self, element):
self._elements.append(element)
def __iadd__(self, o):
self._elements.append(o)
return self
def visit(self, visitor):
return visitor.visitRackElement(self)
def _get_units(self):
h = 0
for e in self._elements:
if e.height > h:
h = e.height
if self.__class__.__name__[:5] == "Shelf":
h += self._baseline
u = int(ceil(h / unitsize))
if self.__class__.__name__[:5] != "Shelf":
u += self._units
# evil hack
u -= self.gap
return u
def _set_units(self, units):
self._units = int(units)
self._baseline = self._units * unitsize
units = property(_get_units, _set_units)
def _get_network(self):
return self.__network
def _set_network(self, value):
self.__network = int(value)
network = property(_get_network, _set_network)
def _get_power(self):
return self.__power
def _set_power(self, value):
self.__power = int(value)
power = property(_get_power, _set_power)
def visit(self, visitor):
return getattr(visitor, 'visit%s' % (self.__class__.__name__,))(self)
class Rackmount(RackElement):
def __init__(self, units=1, name="rackmount", network=1, power=1, cliplock=4, image="", notes=""):
RackElement.__init__(self, units, name, network, power, cliplock, image, notes)
def visit(self, visitor):
return visitor.visitRackmount(self)
class APC(RackElement):
def __init__(self, units=1, name="APC", network=1, power=1, cliplock=4, image=""):
RackElement.__init__(self, units, name, network, power, cliplock, image)
def visit(self, visitor):
return visitor.visitAPC(self)
class PatchPanel(RackElement):
def __init__(self, units=1, name = "patch panel", network=0, power=0, cliplock=4):
RackElement.__init__(self, units, name, network, power, cliplock)
def visit(self, visitor):
return visitor.visitPatchPanel(self)
class CableManagement(RackElement):
def __init__(self, units=1, name = "cable management", network=0, power=0, cliplock=4):
RackElement.__init__(self, units, name, network, power, cliplock)
def visit(self, visitor):
return visitor.visitCableManagement(self)
class Gap(RackElement):
def __init__(self, units=1, name="gap"):
RackElement.__init__(self, units, name, 0, 0, 0)
self.units = units
def visit(self, visitor):
return visitor.visitGap(self)
def _get_units(self):
return self._units
def _set_units(self, units):
self._units = int(units)
units = property(_get_units, _set_units)
class Switch(RackElement):
def __init__(self, units=1, name="switch", network=1, power=1, cliplock=4, image="", notes=""):
RackElement.__init__(self,
units,
name,
network,
power,
cliplock,
image,
notes)
def visit(self, visitor):
return visitor.visitSwitch(self)
class Shelf(RackElement):
def __init__(self, units=1, name = "shelf", network=0, power=0, cliplock=4, gap=0, notes=""):
RackElement.__init__(self, units, name, network, power, cliplock, notes)
self._baseline = 43.5
self._bottomline = 0
self._bracketunits = 1
# hack to allow us to tell the builder if the elem above it has
# enough space to allow things to go into its space
self.gap = gap
def visit(self, visitor):
return visitor.visitShelf(self)
def _get_network(self):
n = self.__network
for e in self._elements:
n += e.network
return n
def _set_network(self, value):
self.__network = int(value)
network = property(_get_network, _set_network)
def _get_power(self):
n = self.__power
for e in self._elements:
n += e.power
return n
def _set_power(self, value):
self.__power = int(value)
power = property(_get_power, _set_power)
def _get_gap(self):
return self.__gap
def _set_gap(self, value):
self.__gap = int(value)
gap = property(_get_gap, _set_gap)
# def _get_units(self):
# h = 0
# for e in self._elements:
# if e.height > h:
# h = e.height
# h += self._baseline
# u = int(ceil(h/unitsize))
# u -= self.gap
# return u
# def _set_units(self, units):
# pass
# return
class ShelfThin(Shelf):
def __init__(self, units=1, name="Thin Black Shelf", network=0, power=0, cliplock=4, gap=0, notes=""):
Shelf.__init__(self, units, name, network, power, cliplock, gap, notes)
self._baseline=11
self._bottomline=0
self._bracketunits=0.3
class Shelf1RU(Shelf):
def __init__(self, units=1, name = "1RU shelf", network=0, power=0, cliplock=4, gap=0, notes=""):
Shelf.__init__(self, units, name, network, power, cliplock, gap, notes)
self._baseline = 35
self._bottomline = 10
self._bracketunits = 1
def visit(self, visitor):
return visitor.visitShelf1RU(self)
class Shelf2U(Shelf):
def __init__(self, units=2, name = "thin shelf w/ 30kg rating", network=0, power=0, cliplock=0, gap=0, notes=""):
Shelf.__init__(self, units, name, network, power, cliplock, gap, notes)
self._baseline = 0
self._bottomline = -15
self._bracketunits = 2
def visit(self, visitor):
return visitor.visitShelf2U(self)
class Shelf1a(Shelf):
def __init__(self, units=1, name="1U shelf",network=0,power=0,cliplock=0,gap=0, notes=""):
Shelf.__init__(self, units, name, network, power, cliplock, gap, notes)
self._baseline = 28.5
self._bottomline = 10
self._bracketunits = 1
def visit(self, visitor):
return visitor.visitShelf1a(self)
class ShelfElement(object):
def __init__(self, height=0, width=0, name="shelf element", network=1, power=1, cliplock=0, image="", notes=""):
self.width = width
self.height = height
self._name = name
self.network = network
self.power = power
self.cliplock = cliplock
self.image = image
self.notes = notes
def visit(self, visitor):
return visitor.visitShelfElement(self)
def _get_height(self):
return self.__height
def _set_height(self, value):
self.__height = float(value)
height = property(_get_height, _set_height)
def _get_width(self):
return self.__width
def _set_width(self, value):
self.__width = float(value)
width = property(_get_width, _set_width)
def _get_network(self):
return self.__network
def _set_network(self, value):
self.__network = int(value)
network = property(_get_network, _set_network)
def _get_power(self):
return self.__power
def _set_power(self, value):
self.__power = int(value)
power = property(_get_power, _set_power)
class Box(ShelfElement):
def __init__(self, height=0, width=0, name = "box", network=1, power=1, cliplock=0, image="", notes=""):
ShelfElement.__init__(self, height, width, name, network, power, cliplock, image, notes)
def visit(self, visitor):
return visitor.visitBox(self)
class RackArray:
def __init__(self):
self._elements = []
def addElement(self, rack):
self._elements.append(rack)
def visit(self, visitor):
return visitor.visitRackArray(self)
class RackVisitor:
"""Base class for visitors to inherit from"""
def __init__(self):
pass
def visit(self, ast):
pass
def visitRackArray(self, ast):
pass
def visitRack(self, ast):
pass
def visitRackElement(self, ast):
pass
def visitRackmount(self, ast):
pass
def visitPatchPanel(self, ast):
pass
def visitCableManagement(self, ast):
pass
def visitShelf(self, ast):
pass
def visitShelf1RU(self, ast):
pass
def visitShelf2U(self, ast):
pass
def visitShelfElement(self, ast):
pass
def visitBox(self, ast):
pass
|
jaqx0r/fengshui
|
rack.py
|
Python
|
gpl-2.0
| 10,254
|
[
"VisIt"
] |
96356b4272332240186f0ec9233ed2db53a981bf7b2b10b374848737fd39af87
|
""" :mod: RegisterReplica
==================
.. module: RegisterReplica
:synopsis: register replica handler
RegisterReplica operation handler
"""
__RCSID__ = "$Id $"
from DIRAC import S_OK, S_ERROR
from DIRAC.FrameworkSystem.Client.MonitoringClient import gMonitor
from DIRAC.DataManagementSystem.Agent.RequestOperations.DMSRequestOperationsBase import DMSRequestOperationsBase
########################################################################
class RegisterReplica( DMSRequestOperationsBase ):
"""
.. class:: RegisterReplica
RegisterReplica operation handler
"""
def __init__( self, operation = None, csPath = None ):
"""c'tor
:param self: self reference
:param Operation operation: Operation instance
:param str csPath: CS path for this handler
"""
DMSRequestOperationsBase.__init__( self, operation, csPath )
# # RegisterReplica specific monitor info
gMonitor.registerActivity( "RegisterReplicaAtt", "Attempted replicas registrations",
"RequestExecutingAgent", "Replicas/min", gMonitor.OP_SUM )
gMonitor.registerActivity( "RegisterReplicaOK", "Successful replicas registrations",
"RequestExecutingAgent", "Replicas/min", gMonitor.OP_SUM )
gMonitor.registerActivity( "RegisterReplicaFail", "Failed replicas registrations",
"RequestExecutingAgent", "Replicas/min", gMonitor.OP_SUM )
def __call__( self ):
""" call me maybe """
# # counter for failed replicas
failedReplicas = 0
# # catalog to use
catalog = self.operation.Catalog
# # get waiting files
waitingFiles = self.getWaitingFilesList()
# # loop over files
registerOperations = {}
for opFile in waitingFiles:
gMonitor.addMark( "RegisterReplicaAtt", 1 )
# # get LFN
lfn = opFile.LFN
# # and others
targetSE = self.operation.targetSEList[0]
replicaTuple = ( lfn , opFile.PFN, targetSE )
# # call ReplicaManager
registerReplica = self.dm.registerReplica( replicaTuple, catalog )
# # check results
if not registerReplica["OK"] or lfn in registerReplica["Value"]["Failed"]:
# There have been some errors
gMonitor.addMark( "RegisterReplicaFail", 1 )
self.dataLoggingClient().addFileRecord( lfn, "RegisterReplicaFail", catalog, "", "RegisterReplica" )
reason = registerReplica.get( "Message", registerReplica.get( "Value", {} ).get( "Failed", {} ).get( lfn, 'Unknown' ) )
errorStr = "failed to register LFN %s: %s" % ( lfn, str( reason ) )
# FIXME: this is incompatible with the change made in the DM that we ignore failures if successful in at least one catalog
if lfn in registerReplica["Value"].get( "Successful", {} ) and type( reason ) == type( {} ):
# As we managed, let's create a new operation for just the remaining registration
errorStr += ' - adding registerReplica operations to request'
for failedCatalog in reason:
key = '%s/%s' % ( targetSE, failedCatalog )
newOperation = self.getRegisterOperation( opFile, targetSE, type = 'RegisterReplica', catalog = failedCatalog )
if key not in registerOperations:
registerOperations[key] = newOperation
else:
registerOperations[key].addFile( newOperation[0] )
opFile.Status = 'Done'
else:
opFile.Error = errorStr
catMaster = True
if type( reason ) == type( {} ):
from DIRAC.Resources.Catalog.FileCatalog import FileCatalog
for failedCatalog in reason:
catMaster = catMaster and FileCatalog()._getCatalogConfigDetails( failedCatalog ).get( 'Value', {} ).get( 'Master', False )
# If one targets explicitly a catalog and it fails or if it fails on the master catalog
if ( catalog or catMaster ) and ( 'file does not exist' in opFile.Error.lower() or 'no such file' in opFile.Error.lower() ) :
opFile.Status = 'Failed'
failedReplicas += 1
self.log.warn( errorStr )
else:
# All is OK
gMonitor.addMark( "RegisterReplicaOK", 1 )
self.dataLoggingClient().addFileRecord( lfn, "RegisterReplicaOK", catalog, "", "RegisterReplica" )
self.log.info( "Replica %s has been registered at %s" % ( lfn, catalog ) )
opFile.Status = "Done"
# # if we have new replications to take place, put them at the end
if registerOperations:
self.log.info( "adding %d operations to the request" % len( registerOperations ) )
for operation in registerOperations.values():
self.operation._parent.addOperation( operation )
# # final check
if failedReplicas:
self.log.info( "all replicas processed, %s replicas failed to register" % failedReplicas )
self.operation.Error = "some replicas failed to register"
return S_ERROR( self.operation.Error )
return S_OK()
|
rajanandakumar/DIRAC
|
DataManagementSystem/Agent/RequestOperations/RegisterReplica.py
|
Python
|
gpl-3.0
| 5,015
|
[
"DIRAC"
] |
1c329d02e7b7cd2133085733fbda72016d32d68aa5c2e6a81057445498a487fb
|
'''
Created on Nov 7, 2010
@author: mkiyer
chimerascan: chimeric transcript discovery using RNA-seq
Copyright (C) 2011 Matthew Iyer
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
'''
import logging
import collections
import shutil
import os
import pysam
# local imports
from chimerascan.lib.chimera import Chimera, DiscordantRead, \
DiscordantTags, DISCORDANT_TAG_NAME, \
OrientationTags, ORIENTATION_TAG_NAME, get_orientation
from chimerascan.lib.base import LibraryTypes
def parse_group_by_attr(myiter, attr):
mylist = []
prev = None
for itm in myiter:
cur = getattr(itm, attr)
if prev != cur:
if len(mylist) > 0:
yield prev, mylist
mylist = []
prev = cur
mylist.append(itm)
if len(mylist) > 0:
yield prev, mylist
def parse_sync_by_breakpoint(chimera_file, bam_file):
# group reads by reference name (matches breakpoint name)
bamfh = pysam.Samfile(bam_file, "rb")
tid_rname_map = list(bamfh.references)
# initialize iterator through reads
read_iter = parse_group_by_attr(bamfh, "rname")
read_iter_valid = True
try:
rname, reads = read_iter.next()
read_breakpoint_name = tid_rname_map[rname]
except StopIteration:
bamfh.close()
read_iter_valid = False
reads = []
read_breakpoint_name = "ZZZZZZZZZZZZZZ"
# group chimeras by breakpoint name
for chimera_breakpoint_name, chimeras in \
parse_group_by_attr(Chimera.parse(open(chimera_file)),
"breakpoint_name"):
while (read_iter_valid) and (chimera_breakpoint_name > read_breakpoint_name):
try:
rname, reads = read_iter.next()
read_breakpoint_name = tid_rname_map[rname]
except StopIteration:
read_iter_valid = False
reads = []
if chimera_breakpoint_name < read_breakpoint_name:
yield chimeras, []
else:
yield chimeras, reads
bamfh.close()
def get_mismatch_positions(md):
x = 0
pos = []
digits = []
for y in xrange(len(md)):
if md[y].isdigit():
digits.append(md[y])
elif md[y].isalpha():
if len(digits) > 0:
offset = int(''.join(digits))
pos.append(x + offset)
x += 1
return pos
def check_breakpoint_alignment(c, r,
anchor_min,
anchor_length,
anchor_mismatches):
"""
returns True if read 'r' meets criteria for a valid
breakpoint spanning read, False otherwise
c - Chimera object
r - pysam AlignedRead object
"""
# get position of breakpoint along seq
breakpoint_pos = len(c.breakpoint_seq_5p)
# check if read spans breakpoint
if not (r.pos < breakpoint_pos < r.aend):
return False
# calculate amount in bp that read overlaps breakpoint
# and ensure overlap is sufficient
left_anchor_bp = breakpoint_pos - r.pos
if left_anchor_bp < max(c.homology_left, anchor_min):
return False
right_anchor_bp = r.aend - breakpoint_pos
if right_anchor_bp < max(c.homology_right, anchor_min):
return False
# ensure that alignments with anchor overlap less than 'anchor_length'
# do not have more than 'anchor_mismatches' mismatches in the
# first 'anchor_length' bases
if min(left_anchor_bp, right_anchor_bp) < anchor_length:
# find interval of smallest anchor
if left_anchor_bp < anchor_length:
anchor_interval = (0, left_anchor_bp)
else:
aligned_length = r.aend - r.pos
anchor_interval = (aligned_length - right_anchor_bp, aligned_length)
# get positions where mismatches occur
mmpos = get_mismatch_positions(r.opt('MD'))
# see if any mismatches lie in anchor interval
anchor_mm = [pos for pos in mmpos
if anchor_interval[0] <= pos < anchor_interval[1]]
if len(anchor_mm) > anchor_mismatches:
# too many mismatches within anchor position
return False
return True
def filter_spanning_reads(chimeras, reads,
anchor_min,
anchor_length,
anchor_mismatches,
library_type):
for i,r in enumerate(reads):
if r.is_unmapped:
continue
# make a discordant read object
# TODO: need to annotate reads elsewhere since they have already been sorted here
r.tags = r.tags + [("HI", 0),
("IH", 1),
("NH", 1),
(DISCORDANT_TAG_NAME, DiscordantTags.DISCORDANT_GENE),
(ORIENTATION_TAG_NAME, get_orientation(r, library_type))]
dr = DiscordantRead.from_read(r)
dr.is_spanning = True
# check read alignment against chimeras
for c in chimeras:
if check_breakpoint_alignment(c, r,
anchor_min,
anchor_length,
anchor_mismatches):
# valid spanning read
yield c,dr
def merge_spanning_alignments(breakpoint_chimera_file,
encomp_bam_file,
singlemap_bam_file,
output_chimera_file,
anchor_min,
anchor_length,
anchor_mismatches,
library_type,
tmp_dir):
#
# Process reads that are both encompassing and spanning
#
logging.debug("Processing encompassing/spanning reads")
tmp_encomp_chimera_file = os.path.join(tmp_dir, "tmp_encomp_chimeras.bedpe")
f = open(tmp_encomp_chimera_file, "w")
filtered_hits = 0
for chimeras, reads in parse_sync_by_breakpoint(breakpoint_chimera_file, encomp_bam_file):
# build dictionary of chimera name -> qname -> discordant pairs
chimera_qname_dict = collections.defaultdict(lambda: {})
for c in chimeras:
for dpair in c.encomp_frags:
chimera_qname_dict[c.name][dpair[0].qname] = dpair
# find valid spanning reads
for c, dr in filter_spanning_reads(chimeras, reads,
anchor_min, anchor_length,
anchor_mismatches, library_type):
# ensure encompassing read is present
if dr.qname not in chimera_qname_dict[c.name]:
continue
# get discordant pair
dpair = chimera_qname_dict[c.name][dr.qname]
# mark correct read (read1/read2) as a spanning read
if dr.readnum == dpair[0].readnum:
dpair[0].is_spanning = True
elif dr.readnum == dpair[1].readnum:
dpair[1].is_spanning = True
else:
assert False
filtered_hits += 1
# write chimeras back to file
for c in chimeras:
fields = c.to_list()
print >>f, '\t'.join(map(str, fields))
f.close()
logging.debug("\tFound %d hits" % (filtered_hits))
#
# Process reads that are single-mapped and spanning
#
logging.debug("Processing single-mapping/spanning reads")
tmp_singlemap_chimera_file = os.path.join(tmp_dir, "tmp_singlemap_chimeras.bedpe")
f = open(tmp_singlemap_chimera_file, "w")
filtered_hits = 0
for chimeras, reads in parse_sync_by_breakpoint(tmp_encomp_chimera_file, singlemap_bam_file):
# find valid spanning reads
for c, dr in filter_spanning_reads(chimeras, reads,
anchor_min, anchor_length,
anchor_mismatches, library_type):
# ensure mate maps to 5' or 3' gene
# TODO: implement this using sorted/indexed BAM file?
# add read as a spanning read
c.spanning_reads.append(dr)
filtered_hits += 1
# write chimeras back to file
for c in chimeras:
fields = c.to_list()
print >>f, '\t'.join(map(str, fields))
f.close()
logging.debug("\tFound %d hits" % (filtered_hits))
# output_chimera_file
shutil.copyfile(tmp_singlemap_chimera_file, output_chimera_file)
# remove temporary files
if os.path.exists(tmp_encomp_chimera_file):
os.remove(tmp_encomp_chimera_file)
if os.path.exists(tmp_singlemap_chimera_file):
os.remove(tmp_singlemap_chimera_file)
def main():
from optparse import OptionParser
logging.basicConfig(level=logging.DEBUG,
format="%(asctime)s - %(name)s - %(levelname)s - %(message)s")
parser = OptionParser("usage: %prog [options] <chimeras.breakpoint_sorted.txt> "
"<encomp.bam> <onemap.bam> <chimeras.out.txt>")
parser.add_option("--anchor-min", type="int", dest="anchor_min", default=4)
parser.add_option("--anchor-length", type="int", dest="anchor_length", default=8)
parser.add_option("--anchor-mismatches", type="int", dest="anchor_mismatches", default=0)
parser.add_option('--library', dest="library_type",
default=LibraryTypes.FR_UNSTRANDED)
options, args = parser.parse_args()
breakpoint_chimera_file = args[0]
encomp_bam_file = args[1]
singlemap_bam_file = args[2]
output_chimera_file = args[4]
merge_spanning_alignments(breakpoint_chimera_file,
encomp_bam_file,
singlemap_bam_file,
output_chimera_file,
options.anchor_min,
options.anchor_length,
options.anchor_mismatches,
options.library_type)
if __name__ == '__main__':
main()
|
tectronics/chimerascan
|
chimerascan/deprecated/merge_spanning_alignments_v1.py
|
Python
|
gpl-3.0
| 10,842
|
[
"pysam"
] |
5eaa723625ff8c438387f3917930aa6cd8bee20c388664549ab15faf17157891
|
# Principal Component Analysis Code :
from numpy import mean,cov,double,cumsum,dot,linalg,array,rank,size,flipud
from pylab import *
import numpy as np
import matplotlib.pyplot as pp
#from enthought.mayavi import mlab
import scipy.ndimage as ni
import roslib; roslib.load_manifest('sandbox_tapo_darpa_m3')
import rospy
#import hrl_lib.mayavi2_util as mu
import hrl_lib.viz as hv
import hrl_lib.util as ut
import hrl_lib.matplotlib_util as mpu
import pickle
from mvpa.clfs.knn import kNN
from mvpa.datasets import Dataset
from mvpa.clfs.transerror import TransferError
from mvpa.misc.data_generators import normalFeatureDataset
from mvpa.algorithms.cvtranserror import CrossValidatedTransferError
from mvpa.datasets.splitters import NFoldSplitter
import sys
sys.path.insert(0, '/home/tapo/svn/robot1_data/usr/tapo/data_code/Classification/Data/Single_Contact_kNN/Scaled')
from data_method_III import Fmat_original
def pca(X):
#get dimensions
num_data,dim = X.shape
#center data
mean_X = X.mean(axis=1)
M = (X-mean_X) # subtract the mean (along columns)
Mcov = cov(M)
###### Sanity Check ######
i=0
n=0
while i < 123:
j=0
while j < 140:
if X[i,j] != X[i,j]:
print X[i,j]
print i,j
n=n+1
j = j+1
i=i+1
print n
##########################
print 'PCA - COV-Method used'
val,vec = linalg.eig(Mcov)
#return the projection matrix, the variance and the mean
return vec,val,mean_X, M, Mcov
if __name__ == '__main__':
Fmat = Fmat_original
# Checking the Data-Matrix
m_tot, n_tot = np.shape(Fmat)
print 'Total_Matrix_Shape:',m_tot,n_tot
eigvec_total, eigval_total, mean_data_total, B, C = pca(Fmat)
#print eigvec_total
#print eigval_total
#print mean_data_total
m_eigval_total, n_eigval_total = np.shape(np.matrix(eigval_total))
m_eigvec_total, n_eigvec_total = np.shape(eigvec_total)
m_mean_data_total, n_mean_data_total = np.shape(np.matrix(mean_data_total))
print 'Eigenvalue Shape:',m_eigval_total, n_eigval_total
print 'Eigenvector Shape:',m_eigvec_total, n_eigvec_total
print 'Mean-Data Shape:',m_mean_data_total, n_mean_data_total
#Recall that the cumulative sum of the eigenvalues shows the level of variance accounted by each of the corresponding eigenvectors. On the x axis there is the number of eigenvalues used.
perc_total = cumsum(eigval_total)/sum(eigval_total)
# Reduced Eigen-Vector Matrix according to highest Eigenvalues..(Considering First 20 based on above figure)
W = eigvec_total[:,0:1]
m_W, n_W = np.shape(W)
print 'Reduced Dimension Eigenvector Shape:',m_W, n_W
# Normalizes the data set with respect to its variance (Not an Integral part of PCA, but useful)
length = len(eigval_total)
s = np.matrix(np.zeros(length)).T
i = 0
while i < length:
s[i] = sqrt(C[i,i])
i = i+1
Z = np.divide(B,s)
m_Z, n_Z = np.shape(Z)
print 'Z-Score Shape:', m_Z, n_Z
#Projected Data:
Y = (W.T)*B # 'B' for my Laptop: otherwise 'Z' instead of 'B'
m_Y, n_Y = np.shape(Y.T)
print 'Transposed Projected Data Shape:', m_Y, n_Y
#Using PYMVPA
PCA_data = np.array(Y.T)
PCA_label_1 = ['Fixed']*35 + ['Movable']*35 + ['Fixed']*35 + ['Movable']*35
PCA_chunk_1 = ['Styrofoam-Fixed']*5 + ['Books-Fixed']*5 + ['Bucket-Fixed']*5 + ['Bowl-Fixed']*5 + ['Can-Fixed']*5 + ['Box-Fixed']*5 + ['Pipe-Fixed']*5 + ['Styrofoam-Movable']*5 + ['Container-Movable']*5 + ['Books-Movable']*5 + ['Cloth-Roll-Movable']*5 + ['Black-Rubber-Movable']*5 + ['Can-Movable']*5 + ['Box-Movable']*5 + ['Rug-Fixed']*5 + ['Bubble-Wrap-1-Fixed']*5 + ['Pillow-1-Fixed']*5 + ['Bubble-Wrap-2-Fixed']*5 + ['Sponge-Fixed']*5 + ['Foliage-Fixed']*5 + ['Pillow-2-Fixed']*5 + ['Rug-Movable']*5 + ['Bubble-Wrap-1-Movable']*5 + ['Pillow-1-Movable']*5 + ['Bubble-Wrap-2-Movable']*5 + ['Pillow-2-Movable']*5 + ['Cushion-Movable']*5 + ['Sponge-Movable']*5
clf = kNN(k=5)
terr = TransferError(clf)
ds1 = Dataset(samples=PCA_data,labels=PCA_label_1,chunks=PCA_chunk_1)
print ds1.samples.shape
cvterr = CrossValidatedTransferError(terr,NFoldSplitter(cvtype=1),enable_states=['confusion'])
error = cvterr(ds1)
print error
print cvterr.confusion.asstring(description=False)
figure(1)
cvterr.confusion.plot(numbers='True')
show()
# Variances
figure(2)
title('Variances of PCs')
stem(range(len(perc_total)),perc_total,'--b')
axis([-0.3,30.3,0,1.2])
grid('True')
#show()
|
tapomayukh/projects_in_python
|
classification/Classification_with_kNN/Single_Contact_Classification/Scaled_Features/results/2_categories/test10_cross_validate_categories_mov_fixed_1200ms_scaled_method_iii.py
|
Python
|
mit
| 4,633
|
[
"Mayavi"
] |
e9867bd11dceea32906d6464fff22190ea59057b182c55882c949e70aa686e15
|
# -*- coding: utf-8 -*-
init_intro = """
_____ _ __
|_ _| __ __ _ _ __ ___(_)/ _| _____ __
| || '__/ _` | '_ \/ __| | |_ / _ \ \/ /
| || | | (_| | | | \__ \ | _| __/> <
|_||_| \__,_|_| |_|___/_|_| \___/_/\_\\
Welcome to the Transifex Client! Please follow the instructions to
initialize your project.
"""
init_initialized = "It seems that this project is already initialized."
init_reinit = "Do you want to delete it and reinit the project?"
init_host = "Transifex instance"
token_instructions = """
Transifex Client needs a Transifex API token to authenticate.
If you don’t have one yet, you can generate a token at
https://www.transifex.com/user/settings/api/.
"""
token_validation_failed = """
Error: Invalid token. You can generate a new token at
https://www.transifex.com/user/settings/api/.
"""
update_txrc = "Overwrite credentials in .transifexrc?"
token_msg = "[?] Enter your api token: "
running_tx_set = "Running tx config command for you..."
create_project_instructions = """To create a new project, head to {host}/{org}/add.
Once you’ve created the project, you can continue.
"""
TEXTS = {
"source_file": {
"description": ("""
The Transifex Client syncs files between your local directory and Transifex.
The mapping configuration between the two is stored in a file called .tx/config
in your current directory. For more information, visit
https://docs.transifex.com/client/config/.
"""),
"error": ("No file was found in that path. Please correct the path "
"or make sure a file exists in that location."),
"message": "[?] Enter the path to your local source file: "
},
"expression": {
"description": ("""
Next, we’ll need a path expression pointing to the location of the
translation files (whether they exist yet or not) associated with
the source file ‘{source_file}’. You should include <lang> as a
wildcard for the language code.
"""),
"error": "The path expression doesn’t contain the <lang> placeholder.",
"message": "[?] Enter a path expression: "
},
"formats": {
"description": ("""
Here’s a list of the supported file formats. For more information,
check our docs at https://docs.transifex.com/formats/.
"""),
"error": "Error: Invalid choice. Enter the number corresponding with the format you wish to select.",
"empty": "No formats found for this file extension. For more information, check our docs at https://docs.transifex.com/formats/",
"message": "[?] Select the file format type [{r}]: ",
},
"organization": {
"description": ("""
You’ll now choose a project in a Transifex organization to sync with your
local files. You belong to these organizations in Transifex:
"""),
"error": ("""
Error: Invalid choice. Enter the number corresponding with the organization you wish to select."""),
"message": "[?] Select the organization to use [{r}]: ",
},
"projects": {
"description": ("""We found these projects in your organization."""),
"error": """
Error: Invalid choice. Enter the number corresponding with the project you wish to select.""",
"message": "[?] Select the project to use [{r}]: ",
},
}
epilog = """
The Transifex Client syncs files between your local directory and Transifex.
The mapping configuration between the two is stored in a file called
.tx/config in your current directory. For more information, visit
https://docs.transifex.com/client/config/.
"""
final_instr = """
Here’s the content of the .tx/config file that was created:
[{resource}]
source_file = {source_file}
file_filter = {file_filter}
source_lang = {source_lang}
type = {type}
You could also have generated the same configuration by running a single command like:
tx config mapping -r {resource} -f {source_file} -s {source_lang} -t {type} '{file_filter}'
To learn more about the Config command, visit https://docs.transifex.com/client/config.
Here are some useful commands for your next steps:
Upload source files to Transifex:
tx push --source
Download translation files from Transifex once translations are done:
tx pull --all
"""
|
transifex/transifex-client
|
txclib/messages.py
|
Python
|
gpl-2.0
| 4,233
|
[
"VisIt"
] |
3f697aa10593b91343688547bb302e0c2715c1d60cb545139ef4c5d7a8eb4a2a
|
"""
Simulates Izhikevich's neuron model using the Runge-Kutta method.
Parameters for regular spiking, fast spiking and bursting
neurons extracted from:
http://www.izhikevich.org/publications/spikes.htm
"""
import numpy as np
IZ_PARAMETERS = {
'regular': {
'a': 0.02,
'b': 0.2,
'c': -65,
'd': 8,
},
'fast': {
'a': 0.02,
'b': 0.25,
'c': -65,
'd': 2,
},
'burst': {
'a': 0.02,
'b': 0.2,
'c': -50,
'd': 2,
},
}
class IzNeuron(object):
BASE_CURRENT = 10
THRESHOLD = 30
DIRAC_SPIKE = 30
def __init__(self, params, dt=0.01):
"""
params -- dictionary of a,b,c,d params
dt -- step size for tick and simulation
"""
self.a = params['a']
self.b = params['b']
self.c = params['c']
self.d = params['d']
self.dt = dt
self.v = -65 # default initial membrane potential
self.u = -1 # default initial rest potential
def simulate(self, duration=200):
"""
Implements the simulate interface, to yield the membrane potential over many iterations of
Runge-Kutta simulation.
"""
steps = int(duration / self.dt)
T = np.arange(0, duration, self.dt)
V = np.zeros(steps)
U = np.zeros(steps)
for i in xrange(steps - 1):
V[i] = self.v
U[i] = self.u
fired = self.tick(IzNeuron.BASE_CURRENT)
if fired:
V[i] = IzNeuron.DIRAC_SPIKE # pulse for visualisation
return T, V, U
def tick(self, i):
"""
Implements the tick interface, where the internal variables of the neuron are projected
forward by a single tick. Returns True if the neruon has fired, False otherwise.
"""
# Runge-Kutta method
k1 = self.__f(self.v, self.u, i)
k2 = self.__f(self.v + 0.5 * self.dt * k1, self.u, i)
k3 = self.__f(self.v + 0.5 * self.dt * k2, self.u, i)
k4 = self.__f(self.v + self.dt * k3, self.u, i)
# New projected v and u values
self.v = self.v + (self.dt / 6) * (k1 + 2 * k2 + 2 * k3 + k4)
self.u = self.u + self.dt * (self.a * (self.b * self.v - self.u))
if self.__above_threshold(self.v):
self.v = self.c # reset to resting potential
self.u = self.u + self.d # update recovery variable
return True
return False
def __above_threshold(self, value):
return value >= IzNeuron.THRESHOLD
def __f(self, v, u, i):
"""
Computes dv/dt for the values of v and u
"""
return (0.04 * v ** 2) + (5 * v) + 140 - u + i
|
lawrencejones/neuro
|
iz/IzNeuron.py
|
Python
|
gpl-3.0
| 2,752
|
[
"NEURON"
] |
108fc41bbde394f4d541882eb96332b9a96425abdf309b83b8f25219ae3a58b4
|
import pickle
from io import BytesIO
import numpy as np
import scipy.sparse
import warnings
from sklearn.datasets import load_digits
from sklearn.cross_validation import cross_val_score
from sklearn.utils.testing import assert_almost_equal
from sklearn.utils.testing import assert_array_equal
from sklearn.utils.testing import assert_array_almost_equal
from sklearn.utils.testing import assert_equal
from sklearn.utils.testing import assert_raises
from sklearn.utils.testing import assert_greater
from sklearn.naive_bayes import GaussianNB, BernoulliNB, MultinomialNB
# Data is just 6 separable points in the plane
X = np.array([[-2, -1], [-1, -1], [-1, -2], [1, 1], [1, 2], [2, 1]])
y = np.array([1, 1, 1, 2, 2, 2])
# A bit more random tests
rng = np.random.RandomState(0)
X1 = rng.normal(size=(10, 3))
y1 = (rng.normal(size=(10)) > 0).astype(np.int)
# Data is 6 random integer points in a 100 dimensional space classified to
# three classes.
X2 = rng.randint(5, size=(6, 100))
y2 = np.array([1, 1, 2, 2, 3, 3])
def test_gnb():
"""
Gaussian Naive Bayes classification.
This checks that GaussianNB implements fit and predict and returns
correct values for a simple toy dataset.
"""
clf = GaussianNB()
y_pred = clf.fit(X, y).predict(X)
assert_array_equal(y_pred, y)
y_pred_proba = clf.predict_proba(X)
y_pred_log_proba = clf.predict_log_proba(X)
assert_array_almost_equal(np.log(y_pred_proba), y_pred_log_proba, 8)
def test_gnb_prior():
"""Test whether class priors are properly set. """
clf = GaussianNB().fit(X, y)
assert_array_almost_equal(np.array([3, 3]) / 6.0,
clf.class_prior_, 8)
clf.fit(X1, y1)
# Check that the class priors sum to 1
assert_array_almost_equal(clf.class_prior_.sum(), 1)
def test_discrete_prior():
"""Test whether class priors are properly set. """
for cls in [BernoulliNB, MultinomialNB]:
clf = cls().fit(X2, y2)
assert_array_almost_equal(np.log(np.array([2, 2, 2]) / 6.0),
clf.class_log_prior_, 8)
def test_mnnb():
"""Test Multinomial Naive Bayes classification.
This checks that MultinomialNB implements fit and predict and returns
correct values for a simple toy dataset.
"""
for X in [X2, scipy.sparse.csr_matrix(X2)]:
# Check the ability to predict the learning set.
clf = MultinomialNB()
assert_raises(ValueError, clf.fit, -X, y2)
y_pred = clf.fit(X, y2).predict(X)
assert_array_equal(y_pred, y2)
# Verify that np.log(clf.predict_proba(X)) gives the same results as
# clf.predict_log_proba(X)
y_pred_proba = clf.predict_proba(X)
y_pred_log_proba = clf.predict_log_proba(X)
assert_array_almost_equal(np.log(y_pred_proba), y_pred_log_proba, 8)
# Check that incremental fitting yields the same results
clf2 = MultinomialNB()
clf2.partial_fit(X[:2], y2[:2], classes=np.unique(y2))
clf2.partial_fit(X[2:5], y2[2:5])
clf2.partial_fit(X[5:], y2[5:])
y_pred2 = clf2.predict(X)
assert_array_equal(y_pred2, y2)
y_pred_proba2 = clf2.predict_proba(X)
y_pred_log_proba2 = clf2.predict_log_proba(X)
assert_array_almost_equal(np.log(y_pred_proba2), y_pred_log_proba2, 8)
assert_array_almost_equal(y_pred_proba2, y_pred_proba)
assert_array_almost_equal(y_pred_log_proba2, y_pred_log_proba)
# Partial fit on the whole data at once should be the same as fit too
clf3 = MultinomialNB()
clf3.partial_fit(X, y2, classes=np.unique(y2))
y_pred3 = clf3.predict(X)
assert_array_equal(y_pred3, y2)
y_pred_proba3 = clf3.predict_proba(X)
y_pred_log_proba3 = clf3.predict_log_proba(X)
assert_array_almost_equal(np.log(y_pred_proba3), y_pred_log_proba3, 8)
assert_array_almost_equal(y_pred_proba3, y_pred_proba)
assert_array_almost_equal(y_pred_log_proba3, y_pred_log_proba)
def check_partial_fit(cls):
clf1 = cls()
clf1.fit([[0, 1], [1, 0]], [0, 1])
clf2 = cls()
clf2.partial_fit([[0, 1], [1, 0]], [0, 1], classes=[0, 1])
assert_array_equal(clf1.class_count_, clf2.class_count_)
assert_array_equal(clf1.feature_count_, clf2.feature_count_)
clf3 = cls()
clf3.partial_fit([[0, 1]], [0], classes=[0, 1])
clf3.partial_fit([[1, 0]], [1])
assert_array_equal(clf1.class_count_, clf3.class_count_)
assert_array_equal(clf1.feature_count_, clf3.feature_count_)
def test_discretenb_partial_fit():
for cls in [MultinomialNB, BernoulliNB]:
yield check_partial_fit, cls
def test_discretenb_pickle():
"""Test picklability of discrete naive Bayes classifiers"""
for cls in [BernoulliNB, MultinomialNB, GaussianNB]:
clf = cls().fit(X2, y2)
y_pred = clf.predict(X2)
store = BytesIO()
pickle.dump(clf, store)
clf = pickle.load(BytesIO(store.getvalue()))
assert_array_equal(y_pred, clf.predict(X2))
if cls is not GaussianNB:
# TODO re-enable me when partial_fit is implemented for GaussianNB
# Test pickling of estimator trained with partial_fit
clf2 = cls().partial_fit(X2[:3], y2[:3], classes=np.unique(y2))
clf2.partial_fit(X2[3:], y2[3:])
store = BytesIO()
pickle.dump(clf2, store)
clf2 = pickle.load(BytesIO(store.getvalue()))
assert_array_equal(y_pred, clf2.predict(X2))
def test_input_check_fit():
"""Test input checks for the fit method"""
for cls in [BernoulliNB, MultinomialNB, GaussianNB]:
# check shape consistency for number of samples at fit time
assert_raises(ValueError, cls().fit, X2, y2[:-1])
# check shape consistency for number of input features at predict time
clf = cls().fit(X2, y2)
assert_raises(ValueError, clf.predict, X2[:, :-1])
def test_input_check_partial_fit():
for cls in [BernoulliNB, MultinomialNB]:
# check shape consistency
assert_raises(ValueError, cls().partial_fit, X2, y2[:-1],
classes=np.unique(y2))
# classes is required for first call to partial fit
assert_raises(ValueError, cls().partial_fit, X2, y2)
# check consistency of consecutive classes values
clf = cls()
clf.partial_fit(X2, y2, classes=np.unique(y2))
assert_raises(ValueError, clf.partial_fit, X2, y2,
classes=np.arange(42))
# check consistency of input shape for partial_fit
assert_raises(ValueError, clf.partial_fit, X2[:, :-1], y2)
# check consistency of input shape for predict
assert_raises(ValueError, clf.predict, X2[:, :-1])
def test_discretenb_predict_proba():
"""Test discrete NB classes' probability scores"""
# The 100s below distinguish Bernoulli from multinomial.
# FIXME: write a test to show this.
X_bernoulli = [[1, 100, 0], [0, 1, 0], [0, 100, 1]]
X_multinomial = [[0, 1], [1, 3], [4, 0]]
# test binary case (1-d output)
y = [0, 0, 2] # 2 is regression test for binary case, 02e673
for cls, X in zip([BernoulliNB, MultinomialNB],
[X_bernoulli, X_multinomial]):
clf = cls().fit(X, y)
assert_equal(clf.predict(X[-1]), 2)
assert_equal(clf.predict_proba(X[0]).shape, (1, 2))
assert_array_almost_equal(clf.predict_proba(X[:2]).sum(axis=1),
np.array([1., 1.]), 6)
# test multiclass case (2-d output, must sum to one)
y = [0, 1, 2]
for cls, X in zip([BernoulliNB, MultinomialNB],
[X_bernoulli, X_multinomial]):
clf = cls().fit(X, y)
assert_equal(clf.predict_proba(X[0]).shape, (1, 3))
assert_equal(clf.predict_proba(X[:2]).shape, (2, 3))
assert_almost_equal(np.sum(clf.predict_proba(X[1])), 1)
assert_almost_equal(np.sum(clf.predict_proba(X[-1])), 1)
assert_almost_equal(np.sum(np.exp(clf.class_log_prior_)), 1)
assert_almost_equal(np.sum(np.exp(clf.intercept_)), 1)
def test_discretenb_uniform_prior():
"""Test whether discrete NB classes fit a uniform prior
when fit_prior=False and class_prior=None"""
for cls in [BernoulliNB, MultinomialNB]:
clf = cls()
clf.set_params(fit_prior=False)
clf.fit([[0], [0], [1]], [0, 0, 1])
prior = np.exp(clf.class_log_prior_)
assert_array_equal(prior, np.array([.5, .5]))
def test_discretenb_provide_prior():
"""Test whether discrete NB classes use provided prior"""
for cls in [BernoulliNB, MultinomialNB]:
clf = cls(class_prior=[0.5, 0.5])
clf.fit([[0], [0], [1]], [0, 0, 1])
prior = np.exp(clf.class_log_prior_)
assert_array_equal(prior, np.array([.5, .5]))
# Inconsistent number of classes with prior
assert_raises(ValueError, clf.fit, [[0], [1], [2]], [0, 1, 2])
assert_raises(ValueError, clf.partial_fit, [[0], [1]], [0, 1],
classes=[0, 1, 1])
def test_deprecated_fit_param():
warnings.simplefilter("always", DeprecationWarning)
try:
for cls in [BernoulliNB, MultinomialNB]:
clf = cls()
with warnings.catch_warnings(record=True) as w:
clf.fit([[0], [1], [2]], [0, 1, 1], class_prior=[0.5, 0.5])
# Passing class_prior as a fit param should raise a deprecation
# warning
assert_equal(len(w), 1)
assert_equal(w[0].category, DeprecationWarning)
with warnings.catch_warnings(record=True):
# Inconsistent number of classes with prior
assert_raises(ValueError, clf.fit, [[0], [1], [2]], [0, 1, 2],
class_prior=[0.5, 0.5])
finally:
warnings.filters.pop(0)
def test_sample_weight_multiclass():
for cls in [BernoulliNB, MultinomialNB]:
# check shape consistency for number of samples at fit time
yield check_sample_weight_multiclass, cls
def check_sample_weight_multiclass(cls):
X = [
[0, 0, 1],
[0, 1, 1],
[0, 1, 1],
[1, 0, 0],
]
y = [0, 0, 1, 2]
sample_weight = np.array([1, 1, 2, 2], dtype=np.float)
sample_weight /= sample_weight.sum()
clf = cls().fit(X, y, sample_weight=sample_weight)
assert_array_equal(clf.predict(X), [0, 1, 1, 2])
# Check wample weight using the partial_fit method
clf = cls()
clf.partial_fit(X[:2], y[:2], classes=[0, 1, 2],
sample_weight=sample_weight[:2])
clf.partial_fit(X[2:3], y[2:3], sample_weight=sample_weight[2:3])
clf.partial_fit(X[3:], y[3:], sample_weight=sample_weight[3:])
assert_array_equal(clf.predict(X), [0, 1, 1, 2])
def test_sample_weight_mnb():
clf = MultinomialNB()
clf.fit([[1, 2], [1, 2], [1, 0]],
[0, 0, 1],
sample_weight=[1, 1, 4])
assert_array_equal(clf.predict([1, 0]), [1])
positive_prior = np.exp(clf.intercept_[0])
assert_array_almost_equal([1 - positive_prior, positive_prior],
[1 / 3., 2 / 3.])
def test_coef_intercept_shape():
"""coef_ and intercept_ should have shapes as in other linear models.
Non-regression test for issue #2127.
"""
X = [[1, 0, 0], [1, 1, 1]]
y = [1, 2] # binary classification
for clf in [MultinomialNB(), BernoulliNB()]:
clf.fit(X, y)
assert_equal(clf.coef_.shape, (1, 3))
assert_equal(clf.intercept_.shape, (1,))
def test_check_accuracy_on_digits():
# Non regression test to make sure that any further refactoring / optim
# of the NB models do not harm the performance on a non linearly separable
# dataset
digits = load_digits()
X, y = digits.data, digits.target
binary_3v8 = np.logical_or(digits.target == 3, digits.target == 8)
X_3v8, y_3v8 = X[binary_3v8], y[binary_3v8]
# Multinomial NB
scores = cross_val_score(MultinomialNB(alpha=10), X, y, cv=10)
assert_greater(scores.mean(), 0.90)
scores = cross_val_score(MultinomialNB(alpha=10), X_3v8, y_3v8, cv=10)
assert_greater(scores.mean(), 0.95)
# Bernoulli NB
scores = cross_val_score(BernoulliNB(alpha=10), X > 4, y, cv=10)
assert_greater(scores.mean(), 0.85)
scores = cross_val_score(BernoulliNB(alpha=10), X_3v8 > 4, y_3v8, cv=10)
assert_greater(scores.mean(), 0.94)
# Gaussian NB
scores = cross_val_score(GaussianNB(), X, y, cv=10)
assert_greater(scores.mean(), 0.81)
scores = cross_val_score(GaussianNB(), X_3v8, y_3v8, cv=10)
assert_greater(scores.mean(), 0.86)
|
depet/scikit-learn
|
sklearn/tests/test_naive_bayes.py
|
Python
|
bsd-3-clause
| 12,739
|
[
"Gaussian"
] |
b9649f58577ae9046a0912087982964e9a62a8de7ee9778929ab5d21ca552309
|
#!/usr/bin/env python
'''
Fly Copter in SITL
AP_FLAKE8_CLEAN
'''
from __future__ import print_function
import copy
import math
import os
import shutil
import time
import numpy
from pymavlink import mavutil
from pymavlink import mavextra
from pymavlink import rotmat
from pysim import util
from pysim import vehicleinfo
from common import AutoTest
from common import NotAchievedException, AutoTestTimeoutException, PreconditionFailedException
from common import Test
from common import MAV_POS_TARGET_TYPE_MASK
from pymavlink.rotmat import Vector3
# get location of scripts
testdir = os.path.dirname(os.path.realpath(__file__))
SITL_START_LOCATION = mavutil.location(-35.362938, 149.165085, 584, 270)
# Flight mode switch positions are set-up in arducopter.param to be
# switch 1 = Circle
# switch 2 = Land
# switch 3 = RTL
# switch 4 = Auto
# switch 5 = Loiter
# switch 6 = Stabilize
class AutoTestCopter(AutoTest):
@staticmethod
def get_not_armable_mode_list():
return ["AUTO", "AUTOTUNE", "BRAKE", "CIRCLE", "FLIP", "LAND", "RTL", "SMART_RTL", "AVOID_ADSB", "FOLLOW"]
@staticmethod
def get_not_disarmed_settable_modes_list():
return ["FLIP", "AUTOTUNE"]
@staticmethod
def get_no_position_not_settable_modes_list():
return []
@staticmethod
def get_position_armable_modes_list():
return ["DRIFT", "GUIDED", "LOITER", "POSHOLD", "THROW"]
@staticmethod
def get_normal_armable_modes_list():
return ["ACRO", "ALT_HOLD", "SPORT", "STABILIZE", "GUIDED_NOGPS"]
def log_name(self):
return "ArduCopter"
def test_filepath(self):
return os.path.realpath(__file__)
def set_current_test_name(self, name):
self.current_test_name_directory = "ArduCopter_Tests/" + name + "/"
def sitl_start_location(self):
return SITL_START_LOCATION
def mavproxy_options(self):
ret = super(AutoTestCopter, self).mavproxy_options()
if self.frame != 'heli':
ret.append('--quadcopter')
return ret
def sitl_streamrate(self):
return 5
def vehicleinfo_key(self):
return 'ArduCopter'
def default_frame(self):
return "+"
def apply_defaultfile_parameters(self):
# Copter passes in a defaults_filepath in place of applying
# parameters afterwards.
pass
def defaults_filepath(self):
return self.model_defaults_filepath(self.frame)
def wait_disarmed_default_wait_time(self):
return 120
def close(self):
super(AutoTestCopter, self).close()
# [2014/05/07] FC Because I'm doing a cross machine build
# (source is on host, build is on guest VM) I cannot hard link
# This flag tells me that I need to copy the data out
if self.copy_tlog:
shutil.copy(self.logfile, self.buildlog)
def is_copter(self):
return True
def get_stick_arming_channel(self):
return int(self.get_parameter("RCMAP_YAW"))
def get_disarm_delay(self):
return int(self.get_parameter("DISARM_DELAY"))
def set_autodisarm_delay(self, delay):
self.set_parameter("DISARM_DELAY", delay)
def user_takeoff(self, alt_min=30, timeout=30, max_err=5):
'''takeoff using mavlink takeoff command'''
self.run_cmd(mavutil.mavlink.MAV_CMD_NAV_TAKEOFF,
0, # param1
0, # param2
0, # param3
0, # param4
0, # param5
0, # param6
alt_min # param7
)
self.wait_for_alt(alt_min, timeout=timeout, max_err=max_err)
def takeoff(self,
alt_min=30,
takeoff_throttle=1700,
require_absolute=True,
mode="STABILIZE",
timeout=120,
max_err=5):
"""Takeoff get to 30m altitude."""
self.progress("TAKEOFF")
self.change_mode(mode)
if not self.armed():
self.wait_ready_to_arm(require_absolute=require_absolute, timeout=timeout)
self.zero_throttle()
self.arm_vehicle()
if mode == 'GUIDED':
self.user_takeoff(alt_min=alt_min, timeout=timeout, max_err=max_err)
else:
self.set_rc(3, takeoff_throttle)
self.wait_for_alt(alt_min=alt_min, timeout=timeout, max_err=max_err)
self.hover()
self.progress("TAKEOFF COMPLETE")
def wait_for_alt(self, alt_min=30, timeout=30, max_err=5):
"""Wait for minimum altitude to be reached."""
self.wait_altitude(alt_min - 1,
(alt_min + max_err),
relative=True,
timeout=timeout)
def land_and_disarm(self, timeout=60):
"""Land the quad."""
self.progress("STARTING LANDING")
self.change_mode("LAND")
self.wait_landed_and_disarmed(timeout=timeout)
def wait_landed_and_disarmed(self, min_alt=6, timeout=60):
"""Wait to be landed and disarmed"""
m = self.mav.recv_match(type='GLOBAL_POSITION_INT', blocking=True)
alt = m.relative_alt / 1000.0 # mm -> m
if alt > min_alt:
self.wait_for_alt(min_alt, timeout=timeout)
# self.wait_statustext("SIM Hit ground", timeout=timeout)
self.wait_disarmed()
def hover(self, hover_throttle=1500):
self.set_rc(3, hover_throttle)
# Climb/descend to a given altitude
def setAlt(self, desiredAlt=50):
pos = self.mav.location(relative_alt=True)
if pos.alt > desiredAlt:
self.set_rc(3, 1300)
self.wait_altitude((desiredAlt-5), desiredAlt, relative=True)
if pos.alt < (desiredAlt-5):
self.set_rc(3, 1800)
self.wait_altitude((desiredAlt-5), desiredAlt, relative=True)
self.hover()
# Takeoff, climb to given altitude, and fly east for 10 seconds
def takeoffAndMoveAway(self, dAlt=50, dDist=50):
self.progress("Centering sticks")
self.set_rc_from_map({
1: 1500,
2: 1500,
3: 1000,
4: 1500,
})
self.takeoff(alt_min=dAlt, mode='GUIDED')
self.change_mode("ALT_HOLD")
self.progress("Yaw to east")
self.set_rc(4, 1580)
self.wait_heading(90)
self.set_rc(4, 1500)
self.progress("Fly eastbound away from home")
self.set_rc(2, 1800)
self.delay_sim_time(10)
self.set_rc(2, 1500)
self.hover()
self.progress("Copter staging 50 meters east of home at 50 meters altitude In mode Alt Hold")
# loiter - fly south west, then loiter within 5m position and altitude
def loiter(self, holdtime=10, maxaltchange=5, maxdistchange=5):
"""Hold loiter position."""
self.takeoff(10, mode="LOITER")
# first aim south east
self.progress("turn south east")
self.set_rc(4, 1580)
self.wait_heading(170)
self.set_rc(4, 1500)
# fly south east 50m
self.set_rc(2, 1100)
self.wait_distance(50)
self.set_rc(2, 1500)
# wait for copter to slow moving
self.wait_groundspeed(0, 2)
m = self.mav.recv_match(type='VFR_HUD', blocking=True)
start_altitude = m.alt
start = self.mav.location()
tstart = self.get_sim_time()
self.progress("Holding loiter at %u meters for %u seconds" %
(start_altitude, holdtime))
while self.get_sim_time_cached() < tstart + holdtime:
m = self.mav.recv_match(type='VFR_HUD', blocking=True)
pos = self.mav.location()
delta = self.get_distance(start, pos)
alt_delta = math.fabs(m.alt - start_altitude)
self.progress("Loiter Dist: %.2fm, alt:%u" % (delta, m.alt))
if alt_delta > maxaltchange:
raise NotAchievedException(
"Loiter alt shifted %u meters (> limit %u)" %
(alt_delta, maxaltchange))
if delta > maxdistchange:
raise NotAchievedException(
"Loiter shifted %u meters (> limit of %u)" %
(delta, maxdistchange))
self.progress("Loiter OK for %u seconds" % holdtime)
self.progress("Climb to 30m")
self.change_alt(30)
self.progress("Descend to 20m")
self.change_alt(20)
self.do_RTL()
def watch_altitude_maintained(self, min_alt, max_alt, timeout=10):
'''watch alt, relative alt must remain between min_alt and max_alt'''
tstart = self.get_sim_time_cached()
while True:
if self.get_sim_time_cached() - tstart > timeout:
return
m = self.mav.recv_match(type='VFR_HUD', blocking=True)
if m.alt <= min_alt:
raise NotAchievedException("Altitude not maintained: want >%f got=%f" % (min_alt, m.alt))
def test_mode_ALT_HOLD(self):
self.takeoff(10, mode="ALT_HOLD")
self.watch_altitude_maintained(9, 11, timeout=5)
# feed in full elevator and aileron input and make sure we
# retain altitude:
self.set_rc_from_map({
1: 1000,
2: 1000,
})
self.watch_altitude_maintained(9, 11, timeout=5)
self.set_rc_from_map({
1: 1500,
2: 1500,
})
self.do_RTL()
def fly_to_origin(self, final_alt=10):
origin = self.poll_message("GPS_GLOBAL_ORIGIN")
self.change_mode("GUIDED")
self.guided_move_global_relative_alt(origin.latitude,
origin.longitude,
final_alt)
def change_alt(self, alt_min, climb_throttle=1920, descend_throttle=1080):
"""Change altitude."""
def adjust_altitude(current_alt, target_alt, accuracy):
if math.fabs(current_alt - target_alt) <= accuracy:
self.hover()
elif current_alt < target_alt:
self.set_rc(3, climb_throttle)
else:
self.set_rc(3, descend_throttle)
self.wait_altitude(
(alt_min - 5),
alt_min,
relative=True,
called_function=lambda current_alt, target_alt: adjust_altitude(current_alt, target_alt, 1)
)
self.hover()
def setGCSfailsafe(self, paramValue=0):
# Slow down the sim rate if GCS Failsafe is in use
if paramValue == 0:
self.set_parameters({
"FS_GCS_ENABLE": paramValue,
"SIM_SPEEDUP": 10,
})
else:
self.set_parameters({
"SIM_SPEEDUP": 4,
"FS_GCS_ENABLE": paramValue,
})
# fly a square in alt_hold mode
def fly_square(self, side=50, timeout=300):
self.takeoff(20, mode="ALT_HOLD")
"""Fly a square, flying N then E ."""
tstart = self.get_sim_time()
# ensure all sticks in the middle
self.set_rc_from_map({
1: 1500,
2: 1500,
3: 1500,
4: 1500,
})
# switch to loiter mode temporarily to stop us from rising
self.change_mode('LOITER')
# first aim north
self.progress("turn right towards north")
self.set_rc(4, 1580)
self.wait_heading(10)
self.set_rc(4, 1500)
# save bottom left corner of box as waypoint
self.progress("Save WP 1 & 2")
self.save_wp()
# switch back to ALT_HOLD mode
self.change_mode('ALT_HOLD')
# pitch forward to fly north
self.progress("Going north %u meters" % side)
self.set_rc(2, 1300)
self.wait_distance(side)
self.set_rc(2, 1500)
# save top left corner of square as waypoint
self.progress("Save WP 3")
self.save_wp()
# roll right to fly east
self.progress("Going east %u meters" % side)
self.set_rc(1, 1700)
self.wait_distance(side)
self.set_rc(1, 1500)
# save top right corner of square as waypoint
self.progress("Save WP 4")
self.save_wp()
# pitch back to fly south
self.progress("Going south %u meters" % side)
self.set_rc(2, 1700)
self.wait_distance(side)
self.set_rc(2, 1500)
# save bottom right corner of square as waypoint
self.progress("Save WP 5")
self.save_wp()
# roll left to fly west
self.progress("Going west %u meters" % side)
self.set_rc(1, 1300)
self.wait_distance(side)
self.set_rc(1, 1500)
# save bottom left corner of square (should be near home) as waypoint
self.progress("Save WP 6")
self.save_wp()
# reduce throttle again
self.set_rc(3, 1500)
# descend to 10m
self.progress("Descend to 10m in Loiter")
self.change_mode('LOITER')
self.set_rc(3, 1200)
time_left = timeout - (self.get_sim_time() - tstart)
self.progress("timeleft = %u" % time_left)
if time_left < 20:
time_left = 20
self.wait_altitude(-10, 10, timeout=time_left, relative=True)
self.set_rc(3, 1500)
self.save_wp()
# save the stored mission to file
mavproxy = self.start_mavproxy()
num_wp = self.save_mission_to_file_using_mavproxy(
mavproxy,
os.path.join(testdir, "ch7_mission.txt"))
self.stop_mavproxy(mavproxy)
if not num_wp:
self.fail_list.append("save_mission_to_file")
self.progress("save_mission_to_file failed")
self.progress("test: Fly a mission from 1 to %u" % num_wp)
self.change_mode('AUTO')
self.set_current_waypoint(1)
self.wait_waypoint(0, num_wp-1, timeout=500)
self.progress("test: MISSION COMPLETE: passed!")
self.land_and_disarm()
# enter RTL mode and wait for the vehicle to disarm
def do_RTL(self, distance_min=None, check_alt=True, distance_max=10, timeout=250):
"""Enter RTL mode and wait for the vehicle to disarm at Home."""
self.change_mode("RTL")
self.hover()
self.wait_rtl_complete(check_alt=check_alt, distance_max=distance_max, timeout=timeout)
def wait_rtl_complete(self, check_alt=True, distance_max=10, timeout=250):
"""Wait for RTL to reach home and disarm"""
self.progress("Waiting RTL to reach Home and disarm")
tstart = self.get_sim_time()
while self.get_sim_time_cached() < tstart + timeout:
m = self.mav.recv_match(type='GLOBAL_POSITION_INT', blocking=True)
alt = m.relative_alt / 1000.0 # mm -> m
home_distance = self.distance_to_home(use_cached_home=True)
home = ""
alt_valid = alt <= 1
distance_valid = home_distance < distance_max
if check_alt:
if alt_valid and distance_valid:
home = "HOME"
else:
if distance_valid:
home = "HOME"
self.progress("Alt: %.02f HomeDist: %.02f %s" %
(alt, home_distance, home))
# our post-condition is that we are disarmed:
if not self.armed():
if home == "":
raise NotAchievedException("Did not get home")
# success!
return
raise AutoTestTimeoutException("Did not get home and disarm")
def fly_loiter_to_alt(self):
"""loiter to alt"""
self.context_push()
ex = None
try:
self.set_parameters({
"PLND_ENABLED": 1,
"PLND_TYPE": 4,
})
self.set_analog_rangefinder_parameters()
self.reboot_sitl()
num_wp = self.load_mission("copter_loiter_to_alt.txt")
self.change_mode('LOITER')
self.wait_ready_to_arm()
self.arm_vehicle()
self.change_mode('AUTO')
self.set_rc(3, 1550)
self.wait_current_waypoint(2)
self.set_rc(3, 1500)
self.wait_waypoint(0, num_wp-1, timeout=500)
self.wait_disarmed()
except Exception as e:
self.print_exception_caught(e)
ex = e
self.context_pop()
self.reboot_sitl()
if ex is not None:
raise ex
# Tests all actions and logic behind the radio failsafe
def fly_throttle_failsafe(self, side=60, timeout=360):
self.start_subtest("If you haven't taken off yet RC failure should be instant disarm")
self.change_mode("STABILIZE")
self.set_parameter("DISARM_DELAY", 0)
self.arm_vehicle()
self.set_parameter("SIM_RC_FAIL", 1)
self.disarm_wait(timeout=1)
self.set_parameter("SIM_RC_FAIL", 0)
self.set_parameter("DISARM_DELAY", 10)
# Trigger an RC failure with the failsafe disabled. Verify no action taken.
self.start_subtest("Radio failsafe disabled test: FS_THR_ENABLE=0 should take no failsafe action")
self.set_parameter('FS_THR_ENABLE', 0)
self.set_parameter('FS_OPTIONS', 0)
self.takeoffAndMoveAway()
self.set_parameter("SIM_RC_FAIL", 1)
self.delay_sim_time(5)
self.wait_mode("ALT_HOLD")
self.set_parameter("SIM_RC_FAIL", 0)
self.delay_sim_time(5)
self.wait_mode("ALT_HOLD")
self.end_subtest("Completed Radio failsafe disabled test")
# Trigger an RC failure, verify radio failsafe triggers,
# restore radio, verify RC function by changing modes to cicle
# and stabilize.
self.start_subtest("Radio failsafe recovery test")
self.set_parameter('FS_THR_ENABLE', 1)
self.set_parameter("SIM_RC_FAIL", 1)
self.wait_mode("RTL")
self.delay_sim_time(5)
self.set_parameter("SIM_RC_FAIL", 0)
self.delay_sim_time(5)
self.set_rc(5, 1050)
self.wait_mode("CIRCLE")
self.set_rc(5, 1950)
self.wait_mode("STABILIZE")
self.end_subtest("Completed Radio failsafe recovery test")
# Trigger and RC failure, verify failsafe triggers and RTL completes
self.start_subtest("Radio failsafe RTL with no options test: FS_THR_ENABLE=1 & FS_OPTIONS=0")
self.set_parameter("SIM_RC_FAIL", 1)
self.wait_mode("RTL")
self.wait_rtl_complete()
self.set_parameter("SIM_RC_FAIL", 0)
self.end_subtest("Completed Radio failsafe RTL with no options test")
# Trigger and RC failure, verify failsafe triggers and land completes
self.start_subtest("Radio failsafe LAND with no options test: FS_THR_ENABLE=3 & FS_OPTIONS=0")
self.set_parameter('FS_THR_ENABLE', 3)
self.takeoffAndMoveAway()
self.set_parameter("SIM_RC_FAIL", 1)
self.wait_mode("LAND")
self.wait_landed_and_disarmed()
self.set_parameter("SIM_RC_FAIL", 0)
self.end_subtest("Completed Radio failsafe LAND with no options test")
# Trigger and RC failure, verify failsafe triggers and SmartRTL completes
self.start_subtest("Radio failsafe SmartRTL->RTL with no options test: FS_THR_ENABLE=4 & FS_OPTIONS=0")
self.set_parameter('FS_THR_ENABLE', 4)
self.takeoffAndMoveAway()
self.set_parameter("SIM_RC_FAIL", 1)
self.wait_mode("SMART_RTL")
self.wait_disarmed()
self.set_parameter("SIM_RC_FAIL", 0)
self.end_subtest("Completed Radio failsafe SmartRTL->RTL with no options test")
# Trigger and RC failure, verify failsafe triggers and SmartRTL completes
self.start_subtest("Radio failsafe SmartRTL->Land with no options test: FS_THR_ENABLE=5 & FS_OPTIONS=0")
self.set_parameter('FS_THR_ENABLE', 5)
self.takeoffAndMoveAway()
self.set_parameter("SIM_RC_FAIL", 1)
self.wait_mode("SMART_RTL")
self.wait_disarmed()
self.set_parameter("SIM_RC_FAIL", 0)
self.end_subtest("Completed Radio failsafe SmartRTL_Land with no options test")
# Trigger a GPS failure and RC failure, verify RTL fails into
# land mode and completes
self.start_subtest("Radio failsafe RTL fails into land mode due to bad position.")
self.set_parameter('FS_THR_ENABLE', 1)
self.takeoffAndMoveAway()
self.set_parameter('SIM_GPS_DISABLE', 1)
self.delay_sim_time(5)
self.set_parameter("SIM_RC_FAIL", 1)
self.wait_mode("LAND")
self.wait_landed_and_disarmed()
self.set_parameter("SIM_RC_FAIL", 0)
self.set_parameter('SIM_GPS_DISABLE', 0)
self.wait_ekf_happy()
self.end_subtest("Completed Radio failsafe RTL fails into land mode due to bad position.")
# Trigger a GPS failure and RC failure, verify SmartRTL fails
# into land mode and completes
self.start_subtest("Radio failsafe SmartRTL->RTL fails into land mode due to bad position.")
self.set_parameter('FS_THR_ENABLE', 4)
self.takeoffAndMoveAway()
self.set_parameter('SIM_GPS_DISABLE', 1)
self.delay_sim_time(5)
self.set_parameter("SIM_RC_FAIL", 1)
self.wait_mode("LAND")
self.wait_landed_and_disarmed()
self.set_parameter("SIM_RC_FAIL", 0)
self.set_parameter('SIM_GPS_DISABLE', 0)
self.wait_ekf_happy()
self.end_subtest("Completed Radio failsafe SmartRTL->RTL fails into land mode due to bad position.")
# Trigger a GPS failure and RC failure, verify SmartRTL fails
# into land mode and completes
self.start_subtest("Radio failsafe SmartRTL->LAND fails into land mode due to bad position.")
self.set_parameter('FS_THR_ENABLE', 5)
self.takeoffAndMoveAway()
self.set_parameter('SIM_GPS_DISABLE', 1)
self.delay_sim_time(5)
self.set_parameter("SIM_RC_FAIL", 1)
self.wait_mode("LAND")
self.wait_landed_and_disarmed()
self.set_parameter("SIM_RC_FAIL", 0)
self.set_parameter('SIM_GPS_DISABLE', 0)
self.wait_ekf_happy()
self.end_subtest("Completed Radio failsafe SmartRTL->LAND fails into land mode due to bad position.")
# Trigger a GPS failure, then restore the GPS. Trigger an RC
# failure, verify SmartRTL fails into RTL and completes
self.start_subtest("Radio failsafe SmartRTL->RTL fails into RTL mode due to no path.")
self.set_parameter('FS_THR_ENABLE', 4)
self.takeoffAndMoveAway()
self.set_parameter('SIM_GPS_DISABLE', 1)
self.wait_statustext("SmartRTL deactivated: bad position", timeout=60)
self.set_parameter('SIM_GPS_DISABLE', 0)
self.wait_ekf_happy()
self.delay_sim_time(5)
self.set_parameter("SIM_RC_FAIL", 1)
self.wait_mode("RTL")
self.wait_rtl_complete()
self.set_parameter("SIM_RC_FAIL", 0)
self.end_subtest("Completed Radio failsafe SmartRTL->RTL fails into RTL mode due to no path.")
# Trigger a GPS failure, then restore the GPS. Trigger an RC
# failure, verify SmartRTL fails into Land and completes
self.start_subtest("Radio failsafe SmartRTL->LAND fails into land mode due to no path.")
self.set_parameter('FS_THR_ENABLE', 5)
self.takeoffAndMoveAway()
self.set_parameter('SIM_GPS_DISABLE', 1)
self.wait_statustext("SmartRTL deactivated: bad position", timeout=60)
self.set_parameter('SIM_GPS_DISABLE', 0)
self.wait_ekf_happy()
self.delay_sim_time(5)
self.set_parameter("SIM_RC_FAIL", 1)
self.wait_mode("LAND")
self.wait_landed_and_disarmed()
self.set_parameter("SIM_RC_FAIL", 0)
self.end_subtest("Completed Radio failsafe SmartRTL->LAND fails into land mode due to no path.")
# Trigger an RC failure in guided mode with the option enabled
# to continue in guided. Verify no failsafe action takes place
self.start_subtest("Radio failsafe with option to continue in guided mode: FS_THR_ENABLE=1 & FS_OPTIONS=4")
self.set_parameter("SYSID_MYGCS", self.mav.source_system)
self.setGCSfailsafe(1)
self.set_parameter('FS_THR_ENABLE', 1)
self.set_parameter('FS_OPTIONS', 4)
self.takeoffAndMoveAway()
self.change_mode("GUIDED")
self.set_parameter("SIM_RC_FAIL", 1)
self.delay_sim_time(5)
self.wait_mode("GUIDED")
self.set_parameter("SIM_RC_FAIL", 0)
self.delay_sim_time(5)
self.change_mode("ALT_HOLD")
self.setGCSfailsafe(0)
# self.change_mode("RTL")
# self.wait_disarmed()
self.end_subtest("Completed Radio failsafe with option to continue in guided mode")
# Trigger an RC failure in AUTO mode with the option enabled
# to continue the mission. Verify no failsafe action takes
# place
self.start_subtest("Radio failsafe RTL with option to continue mission: FS_THR_ENABLE=1 & FS_OPTIONS=1")
self.set_parameter('FS_OPTIONS', 1)
self.progress("# Load copter_mission")
num_wp = self.load_mission("copter_mission.txt", strict=False)
if not num_wp:
raise NotAchievedException("load copter_mission failed")
# self.takeoffAndMoveAway()
self.change_mode("AUTO")
self.set_parameter("SIM_RC_FAIL", 1)
self.delay_sim_time(5)
self.wait_mode("AUTO")
self.set_parameter("SIM_RC_FAIL", 0)
self.delay_sim_time(5)
self.wait_mode("AUTO")
# self.change_mode("RTL")
# self.wait_disarmed()
self.end_subtest("Completed Radio failsafe RTL with option to continue mission")
# Trigger an RC failure in AUTO mode without the option
# enabled to continue. Verify failsafe triggers and RTL
# completes
self.start_subtest("Radio failsafe RTL in mission without "
"option to continue should RTL: FS_THR_ENABLE=1 & FS_OPTIONS=0")
self.set_parameter('FS_OPTIONS', 0)
self.set_parameter("SIM_RC_FAIL", 1)
self.wait_mode("RTL")
self.wait_rtl_complete()
self.clear_mission(mavutil.mavlink.MAV_MISSION_TYPE_MISSION)
self.set_parameter("SIM_RC_FAIL", 0)
self.end_subtest("Completed Radio failsafe RTL in mission without option to continue")
self.progress("All radio failsafe tests complete")
self.set_parameter('FS_THR_ENABLE', 0)
self.reboot_sitl()
# Tests all actions and logic behind the GCS failsafe
def fly_gcs_failsafe(self, side=60, timeout=360):
try:
self.test_gcs_failsafe(side=side, timeout=timeout)
except Exception as ex:
self.setGCSfailsafe(0)
self.set_parameter('FS_OPTIONS', 0)
self.disarm_vehicle(force=True)
self.reboot_sitl()
raise ex
def test_gcs_failsafe(self, side=60, timeout=360):
# Test double-SmartRTL; ensure we do SmarRTL twice rather than
# landing (tests fix for actual bug)
self.set_parameter("SYSID_MYGCS", self.mav.source_system)
self.context_push()
self.start_subtest("GCS failsafe SmartRTL twice")
self.setGCSfailsafe(3)
self.set_parameter('FS_OPTIONS', 8)
self.takeoffAndMoveAway()
self.set_heartbeat_rate(0)
self.wait_mode("SMART_RTL")
self.wait_disarmed()
self.set_heartbeat_rate(self.speedup)
self.wait_statustext("GCS Failsafe Cleared", timeout=60)
self.takeoffAndMoveAway()
self.set_heartbeat_rate(0)
self.wait_statustext("GCS Failsafe")
def ensure_smartrtl(mav, m):
if m.get_type() != "HEARTBEAT":
return
# can't use mode_is here because we're in the message hook
print("Mode: %s" % self.mav.flightmode)
if self.mav.flightmode != "SMART_RTL":
raise NotAchievedException("Not in SMART_RTL")
self.install_message_hook_context(ensure_smartrtl)
self.set_heartbeat_rate(self.speedup)
self.wait_statustext("GCS Failsafe Cleared", timeout=60)
self.set_heartbeat_rate(0)
self.wait_statustext("GCS Failsafe")
self.wait_disarmed()
self.end_subtest("GCS failsafe SmartRTL twice")
self.set_heartbeat_rate(self.speedup)
self.wait_statustext("GCS Failsafe Cleared", timeout=60)
self.context_pop()
# Trigger telemetry loss with failsafe disabled. Verify no action taken.
self.start_subtest("GCS failsafe disabled test: FS_GCS_ENABLE=0 should take no failsafe action")
self.setGCSfailsafe(0)
self.takeoffAndMoveAway()
self.set_heartbeat_rate(0)
self.delay_sim_time(5)
self.wait_mode("ALT_HOLD")
self.set_heartbeat_rate(self.speedup)
self.delay_sim_time(5)
self.wait_mode("ALT_HOLD")
self.end_subtest("Completed GCS failsafe disabled test")
# Trigger telemetry loss with failsafe enabled. Verify
# failsafe triggers to RTL. Restore telemetry, verify failsafe
# clears, and change modes.
self.start_subtest("GCS failsafe recovery test: FS_GCS_ENABLE=1 & FS_OPTIONS=0")
self.setGCSfailsafe(1)
self.set_parameter('FS_OPTIONS', 0)
self.set_heartbeat_rate(0)
self.wait_mode("RTL")
self.set_heartbeat_rate(self.speedup)
self.wait_statustext("GCS Failsafe Cleared", timeout=60)
self.change_mode("LOITER")
self.end_subtest("Completed GCS failsafe recovery test")
# Trigger telemetry loss with failsafe enabled. Verify failsafe triggers and RTL completes
self.start_subtest("GCS failsafe RTL with no options test: FS_GCS_ENABLE=1 & FS_OPTIONS=0")
self.setGCSfailsafe(1)
self.set_parameter('FS_OPTIONS', 0)
self.set_heartbeat_rate(0)
self.wait_mode("RTL")
self.wait_rtl_complete()
self.set_heartbeat_rate(self.speedup)
self.wait_statustext("GCS Failsafe Cleared", timeout=60)
self.end_subtest("Completed GCS failsafe RTL with no options test")
# Trigger telemetry loss with failsafe enabled. Verify failsafe triggers and land completes
self.start_subtest("GCS failsafe LAND with no options test: FS_GCS_ENABLE=5 & FS_OPTIONS=0")
self.setGCSfailsafe(5)
self.takeoffAndMoveAway()
self.set_heartbeat_rate(0)
self.wait_mode("LAND")
self.wait_landed_and_disarmed()
self.set_heartbeat_rate(self.speedup)
self.wait_statustext("GCS Failsafe Cleared", timeout=60)
self.end_subtest("Completed GCS failsafe land with no options test")
# Trigger telemetry loss with failsafe enabled. Verify failsafe triggers and SmartRTL completes
self.start_subtest("GCS failsafe SmartRTL->RTL with no options test: FS_GCS_ENABLE=3 & FS_OPTIONS=0")
self.setGCSfailsafe(3)
self.takeoffAndMoveAway()
self.set_heartbeat_rate(0)
self.wait_mode("SMART_RTL")
self.wait_disarmed()
self.set_heartbeat_rate(self.speedup)
self.wait_statustext("GCS Failsafe Cleared", timeout=60)
self.end_subtest("Completed GCS failsafe SmartRTL->RTL with no options test")
# Trigger telemetry loss with failsafe enabled. Verify failsafe triggers and SmartRTL completes
self.start_subtest("GCS failsafe SmartRTL->Land with no options test: FS_GCS_ENABLE=4 & FS_OPTIONS=0")
self.setGCSfailsafe(4)
self.takeoffAndMoveAway()
self.set_heartbeat_rate(0)
self.wait_mode("SMART_RTL")
self.wait_disarmed()
self.set_heartbeat_rate(self.speedup)
self.wait_statustext("GCS Failsafe Cleared", timeout=60)
self.end_subtest("Completed GCS failsafe SmartRTL->Land with no options test")
# Trigger telemetry loss with an invalid failsafe value. Verify failsafe triggers and RTL completes
self.start_subtest("GCS failsafe invalid value with no options test: FS_GCS_ENABLE=99 & FS_OPTIONS=0")
self.setGCSfailsafe(99)
self.takeoffAndMoveAway()
self.set_heartbeat_rate(0)
self.wait_mode("RTL")
self.wait_rtl_complete()
self.set_heartbeat_rate(self.speedup)
self.wait_statustext("GCS Failsafe Cleared", timeout=60)
self.end_subtest("Completed GCS failsafe invalid value with no options test")
# Trigger telemetry loss with failsafe enabled to test FS_OPTIONS settings
self.start_subtest("GCS failsafe with option bit tests: FS_GCS_ENABLE=1 & FS_OPTIONS=64/2/16")
num_wp = self.load_mission("copter_mission.txt", strict=False)
if not num_wp:
raise NotAchievedException("load copter_mission failed")
self.setGCSfailsafe(1)
self.set_parameter('FS_OPTIONS', 16)
self.takeoffAndMoveAway()
self.progress("Testing continue in pilot controlled modes")
self.set_heartbeat_rate(0)
self.wait_statustext("GCS Failsafe - Continuing Pilot Control", timeout=60)
self.delay_sim_time(5)
self.wait_mode("ALT_HOLD")
self.set_heartbeat_rate(self.speedup)
self.wait_statustext("GCS Failsafe Cleared", timeout=60)
self.progress("Testing continue in auto mission")
self.set_parameter('FS_OPTIONS', 2)
self.change_mode("AUTO")
self.delay_sim_time(5)
self.set_heartbeat_rate(0)
self.wait_statustext("GCS Failsafe - Continuing Auto Mode", timeout=60)
self.delay_sim_time(5)
self.wait_mode("AUTO")
self.set_heartbeat_rate(self.speedup)
self.wait_statustext("GCS Failsafe Cleared", timeout=60)
self.progress("Testing continue landing in land mode")
self.set_parameter('FS_OPTIONS', 8)
self.change_mode("LAND")
self.delay_sim_time(5)
self.set_heartbeat_rate(0)
self.wait_statustext("GCS Failsafe - Continuing Landing", timeout=60)
self.delay_sim_time(5)
self.wait_mode("LAND")
self.wait_landed_and_disarmed()
self.set_heartbeat_rate(self.speedup)
self.wait_statustext("GCS Failsafe Cleared", timeout=60)
self.end_subtest("Completed GCS failsafe with option bits")
self.setGCSfailsafe(0)
self.set_parameter('FS_OPTIONS', 0)
self.progress("All GCS failsafe tests complete")
self.reboot_sitl()
# Tests all actions and logic behind the battery failsafe
def fly_battery_failsafe(self, timeout=300):
ex = None
try:
self.test_battery_failsafe(timeout=timeout)
except Exception as e:
self.print_exception_caught(e)
self.disarm_vehicle(force=True)
ex = e
self.set_parameters({
'BATT_LOW_VOLT': 0,
'BATT_CRT_VOLT': 0,
'BATT_FS_LOW_ACT': 0,
'BATT_FS_CRT_ACT': 0,
'FS_OPTIONS': 0,
})
self.reboot_sitl()
if ex is not None:
raise ex
def test_battery_failsafe(self, timeout=300):
self.progress("Configure battery failsafe parameters")
self.set_parameters({
'SIM_SPEEDUP': 4,
'BATT_LOW_VOLT': 11.5,
'BATT_CRT_VOLT': 10.1,
'BATT_FS_LOW_ACT': 0,
'BATT_FS_CRT_ACT': 0,
'FS_OPTIONS': 0,
'SIM_BATT_VOLTAGE': 12.5,
})
# Trigger low battery condition with failsafe disabled. Verify
# no action taken.
self.start_subtest("Batt failsafe disabled test")
self.takeoffAndMoveAway()
m = self.mav.recv_match(type='BATTERY_STATUS', blocking=True, timeout=1)
if m.charge_state != mavutil.mavlink.MAV_BATTERY_CHARGE_STATE_OK:
raise NotAchievedException("Expected state ok")
self.set_parameter('SIM_BATT_VOLTAGE', 11.4)
self.wait_statustext("Battery 1 is low", timeout=60)
m = self.mav.recv_match(type='BATTERY_STATUS', blocking=True, timeout=1)
if m.charge_state != mavutil.mavlink.MAV_BATTERY_CHARGE_STATE_LOW:
raise NotAchievedException("Expected state low")
self.delay_sim_time(5)
self.wait_mode("ALT_HOLD")
self.set_parameter('SIM_BATT_VOLTAGE', 10.0)
self.wait_statustext("Battery 1 is critical", timeout=60)
m = self.mav.recv_match(type='BATTERY_STATUS', blocking=True, timeout=1)
if m.charge_state != mavutil.mavlink.MAV_BATTERY_CHARGE_STATE_CRITICAL:
raise NotAchievedException("Expected state critical")
self.delay_sim_time(5)
self.wait_mode("ALT_HOLD")
self.change_mode("RTL")
self.wait_rtl_complete()
self.set_parameter('SIM_BATT_VOLTAGE', 12.5)
self.reboot_sitl()
self.end_subtest("Completed Batt failsafe disabled test")
# TWO STAGE BATTERY FAILSAFE: Trigger low battery condition,
# then critical battery condition. Verify RTL and Land actions
# complete.
self.start_subtest("Two stage battery failsafe test with RTL and Land")
self.takeoffAndMoveAway()
self.delay_sim_time(3)
self.set_parameters({
'BATT_FS_LOW_ACT': 2,
'BATT_FS_CRT_ACT': 1,
'SIM_BATT_VOLTAGE': 11.4,
})
self.wait_statustext("Battery 1 is low", timeout=60)
self.delay_sim_time(5)
self.wait_mode("RTL")
self.delay_sim_time(10)
self.set_parameter('SIM_BATT_VOLTAGE', 10.0)
self.wait_statustext("Battery 1 is critical", timeout=60)
self.delay_sim_time(5)
self.wait_mode("LAND")
self.wait_landed_and_disarmed()
self.set_parameter('SIM_BATT_VOLTAGE', 12.5)
self.reboot_sitl()
self.end_subtest("Completed two stage battery failsafe test with RTL and Land")
# TWO STAGE BATTERY FAILSAFE: Trigger low battery condition,
# then critical battery condition. Verify both SmartRTL
# actions complete
self.start_subtest("Two stage battery failsafe test with SmartRTL")
self.takeoffAndMoveAway()
self.set_parameter('BATT_FS_LOW_ACT', 3)
self.set_parameter('BATT_FS_CRT_ACT', 4)
self.delay_sim_time(10)
self.set_parameter('SIM_BATT_VOLTAGE', 11.4)
self.wait_statustext("Battery 1 is low", timeout=60)
self.delay_sim_time(5)
self.wait_mode("SMART_RTL")
self.change_mode("LOITER")
self.delay_sim_time(10)
self.set_parameter('SIM_BATT_VOLTAGE', 10.0)
self.wait_statustext("Battery 1 is critical", timeout=60)
self.delay_sim_time(5)
self.wait_mode("SMART_RTL")
self.wait_disarmed()
self.set_parameter('SIM_BATT_VOLTAGE', 12.5)
self.reboot_sitl()
self.end_subtest("Completed two stage battery failsafe test with SmartRTL")
# Trigger low battery condition in land mode with FS_OPTIONS
# set to allow land mode to continue. Verify landing completes
# uninterrupted.
self.start_subtest("Battery failsafe with FS_OPTIONS set to continue landing")
self.takeoffAndMoveAway()
self.set_parameter('FS_OPTIONS', 8)
self.change_mode("LAND")
self.delay_sim_time(5)
self.set_parameter('SIM_BATT_VOLTAGE', 11.4)
self.wait_statustext("Battery 1 is low", timeout=60)
self.delay_sim_time(5)
self.wait_mode("LAND")
self.wait_landed_and_disarmed()
self.set_parameter('SIM_BATT_VOLTAGE', 12.5)
self.reboot_sitl()
self.end_subtest("Completed battery failsafe with FS_OPTIONS set to continue landing")
# Trigger a critical battery condition, which triggers a land
# mode failsafe. Trigger an RC failure. Verify the RC failsafe
# is prevented from stopping the low battery landing.
self.start_subtest("Battery failsafe critical landing")
self.takeoffAndMoveAway(100, 50)
self.set_parameters({
'FS_OPTIONS': 0,
'BATT_FS_LOW_ACT': 1,
'BATT_FS_CRT_ACT': 1,
'FS_THR_ENABLE': 1,
})
self.delay_sim_time(5)
self.set_parameter('SIM_BATT_VOLTAGE', 10.0)
self.wait_statustext("Battery 1 is critical", timeout=60)
self.wait_mode("LAND")
self.delay_sim_time(10)
self.set_parameter("SIM_RC_FAIL", 1)
self.delay_sim_time(10)
self.wait_mode("LAND")
self.wait_landed_and_disarmed()
self.set_parameter('SIM_BATT_VOLTAGE', 12.5)
self.set_parameter("SIM_RC_FAIL", 0)
self.reboot_sitl()
self.end_subtest("Completed battery failsafe critical landing")
# Trigger low battery condition with failsafe set to terminate. Copter will disarm and crash.
self.start_subtest("Battery failsafe terminate")
self.takeoffAndMoveAway()
self.set_parameter('BATT_FS_LOW_ACT', 5)
self.delay_sim_time(10)
self.set_parameter('SIM_BATT_VOLTAGE', 11.4)
self.wait_statustext("Battery 1 is low", timeout=60)
self.wait_disarmed()
self.end_subtest("Completed terminate failsafe test")
self.progress("All Battery failsafe tests complete")
# Tests the vibration failsafe
def test_vibration_failsafe(self):
self.context_push()
# takeoff in Loiter to 20m
self.takeoff(20, mode="LOITER")
# simulate accel bias caused by high vibration
self.set_parameters({
'SIM_ACC1_BIAS_Z': 2,
'SIM_ACC2_BIAS_Z': 2,
'SIM_ACC3_BIAS_Z': 2,
})
# wait for Vibration compensation warning and change to LAND mode
self.wait_statustext("Vibration compensation ON", timeout=30)
self.change_mode("LAND")
# check vehicle descends to 2m or less within 40 seconds
self.wait_altitude(-5, 2, timeout=40, relative=True)
# force disarm of vehicle (it will likely not automatically disarm)
self.disarm_vehicle(force=True)
# revert simulated accel bias and reboot to restore EKF health
self.context_pop()
self.reboot_sitl()
# fly_stability_patch - fly south, then hold loiter within 5m
# position and altitude and reduce 1 motor to 60% efficiency
def fly_stability_patch(self,
holdtime=30,
maxaltchange=5,
maxdistchange=10):
self.takeoff(10, mode="LOITER")
# first south
self.progress("turn south")
self.set_rc(4, 1580)
self.wait_heading(180)
self.set_rc(4, 1500)
# fly west 80m
self.set_rc(2, 1100)
self.wait_distance(80)
self.set_rc(2, 1500)
# wait for copter to slow moving
self.wait_groundspeed(0, 2)
m = self.mav.recv_match(type='VFR_HUD', blocking=True)
start_altitude = m.alt
start = self.mav.location()
tstart = self.get_sim_time()
self.progress("Holding loiter at %u meters for %u seconds" %
(start_altitude, holdtime))
# cut motor 1's to efficiency
self.progress("Cutting motor 1 to 65% efficiency")
self.set_parameter("SIM_ENGINE_MUL", 0.65)
while self.get_sim_time_cached() < tstart + holdtime:
m = self.mav.recv_match(type='VFR_HUD', blocking=True)
pos = self.mav.location()
delta = self.get_distance(start, pos)
alt_delta = math.fabs(m.alt - start_altitude)
self.progress("Loiter Dist: %.2fm, alt:%u" % (delta, m.alt))
if alt_delta > maxaltchange:
raise NotAchievedException(
"Loiter alt shifted %u meters (> limit %u)" %
(alt_delta, maxaltchange))
if delta > maxdistchange:
raise NotAchievedException(
("Loiter shifted %u meters (> limit of %u)" %
(delta, maxdistchange)))
# restore motor 1 to 100% efficiency
self.set_parameter("SIM_ENGINE_MUL", 1.0)
self.progress("Stability patch and Loiter OK for %us" % holdtime)
self.progress("RTL after stab patch")
self.do_RTL()
def debug_arming_issue(self):
while True:
self.send_mavlink_arm_command()
m = self.mav.recv_match(blocking=True, timeout=1)
if m is None:
continue
if m.get_type() in ["STATUSTEXT", "COMMAND_ACK"]:
print("Got: %s" % str(m))
if self.mav.motors_armed():
self.progress("Armed")
return
# fly_fence_test - fly east until you hit the horizontal circular fence
avoid_behave_slide = 0
def fly_fence_avoid_test_radius_check(self, timeout=180, avoid_behave=avoid_behave_slide):
using_mode = "LOITER" # must be something which adjusts velocity!
self.change_mode(using_mode)
fence_radius = 15
fence_margin = 3
self.set_parameters({
"FENCE_ENABLE": 1, # fence
"FENCE_TYPE": 2, # circle
"FENCE_RADIUS": fence_radius,
"FENCE_MARGIN": fence_margin,
"AVOID_ENABLE": 1,
"AVOID_BEHAVE": avoid_behave,
"RC10_OPTION": 40, # avoid-enable
})
self.wait_ready_to_arm()
self.set_rc(10, 2000)
home_distance = self.distance_to_home(use_cached_home=True)
if home_distance > 5:
raise PreconditionFailedException("Expected to be within 5m of home")
self.zero_throttle()
self.arm_vehicle()
self.set_rc(3, 1700)
self.wait_altitude(10, 100, relative=True)
self.set_rc(3, 1500)
self.set_rc(2, 1400)
self.wait_distance_to_home(12, 20)
tstart = self.get_sim_time()
push_time = 70 # push against barrier for 60 seconds
failed_max = False
failed_min = False
while True:
if self.get_sim_time() - tstart > push_time:
self.progress("Push time up")
break
# make sure we don't RTL:
if not self.mode_is(using_mode):
raise NotAchievedException("Changed mode away from %s" % using_mode)
distance = self.distance_to_home(use_cached_home=True)
inner_radius = fence_radius - fence_margin
want_min = inner_radius - 1 # allow 1m either way
want_max = inner_radius + 1 # allow 1m either way
self.progress("Push: distance=%f %f<want<%f" %
(distance, want_min, want_max))
if distance < want_min:
if failed_min is False:
self.progress("Failed min")
failed_min = True
if distance > want_max:
if failed_max is False:
self.progress("Failed max")
failed_max = True
if failed_min and failed_max:
raise NotAchievedException("Failed both min and max checks. Clever")
if failed_min:
raise NotAchievedException("Failed min")
if failed_max:
raise NotAchievedException("Failed max")
self.set_rc(2, 1500)
self.do_RTL()
def fly_fence_avoid_test(self, timeout=180):
self.fly_fence_avoid_test_radius_check(avoid_behave=1, timeout=timeout)
self.fly_fence_avoid_test_radius_check(avoid_behave=0, timeout=timeout)
# fly_fence_test - fly east until you hit the horizontal circular fence
def fly_fence_test(self, timeout=180):
# enable fence, disable avoidance
self.set_parameters({
"FENCE_ENABLE": 1,
"AVOID_ENABLE": 0,
})
self.change_mode("LOITER")
self.wait_ready_to_arm()
# fence requires home to be set:
m = self.poll_home_position()
if m is None:
raise NotAchievedException("Did not receive HOME_POSITION")
self.progress("home: %s" % str(m))
self.start_subtest("ensure we can't arm if outside fence")
self.load_fence("fence-in-middle-of-nowhere.txt")
self.delay_sim_time(5) # let fence check run so it loads-from-eeprom
self.assert_prearm_failure("vehicle outside fence")
self.progress("Failed to arm outside fence (good!)")
self.clear_fence()
self.delay_sim_time(5) # let fence breach clear
self.drain_mav()
self.end_subtest("ensure we can't arm if outside fence")
self.start_subtest("ensure we can't arm with bad radius")
self.context_push()
self.set_parameter("FENCE_RADIUS", -1)
self.assert_prearm_failure("Invalid FENCE_RADIUS value")
self.context_pop()
self.progress("Failed to arm with bad radius")
self.drain_mav()
self.end_subtest("ensure we can't arm with bad radius")
self.start_subtest("ensure we can't arm with bad alt")
self.context_push()
self.set_parameter("FENCE_ALT_MAX", -1)
self.assert_prearm_failure("Invalid FENCE_ALT_MAX value")
self.context_pop()
self.progress("Failed to arm with bad altitude")
self.end_subtest("ensure we can't arm with bad radius")
self.start_subtest("Check breach-fence behaviour")
self.set_parameter("FENCE_TYPE", 2)
self.takeoff(10, mode="LOITER")
# first east
self.progress("turn east")
self.set_rc(4, 1580)
self.wait_heading(160, timeout=60)
self.set_rc(4, 1500)
fence_radius = self.get_parameter("FENCE_RADIUS")
self.progress("flying forward (east) until we hit fence")
pitching_forward = True
self.set_rc(2, 1100)
self.progress("Waiting for fence breach")
tstart = self.get_sim_time()
while not self.mode_is("RTL"):
if self.get_sim_time_cached() - tstart > 30:
raise NotAchievedException("Did not breach fence")
m = self.mav.recv_match(type='GLOBAL_POSITION_INT', blocking=True)
alt = m.relative_alt / 1000.0 # mm -> m
home_distance = self.distance_to_home(use_cached_home=True)
self.progress("Alt: %.02f HomeDistance: %.02f (fence radius=%f)" %
(alt, home_distance, fence_radius))
self.progress("Waiting until we get home and disarm")
tstart = self.get_sim_time()
while self.get_sim_time_cached() < tstart + timeout:
m = self.mav.recv_match(type='GLOBAL_POSITION_INT', blocking=True)
alt = m.relative_alt / 1000.0 # mm -> m
home_distance = self.distance_to_home(use_cached_home=True)
self.progress("Alt: %.02f HomeDistance: %.02f" %
(alt, home_distance))
# recenter pitch sticks once we're home so we don't fly off again
if pitching_forward and home_distance < 50:
pitching_forward = False
self.set_rc(2, 1475)
# disable fence
self.set_parameter("FENCE_ENABLE", 0)
if (alt <= 1 and home_distance < 10) or (not self.armed() and home_distance < 10):
# reduce throttle
self.zero_throttle()
self.change_mode("LAND")
self.wait_landed_and_disarmed()
self.progress("Reached home OK")
self.zero_throttle()
return
# give we're testing RTL, doing one here probably doesn't make sense
home_distance = self.distance_to_home(use_cached_home=True)
raise AutoTestTimeoutException(
"Fence test failed to reach home (%fm distance) - "
"timed out after %u seconds" % (home_distance, timeout,))
# fly_alt_max_fence_test - fly up until you hit the fence ceiling
def fly_alt_max_fence_test(self):
self.takeoff(10, mode="LOITER")
"""Hold loiter position."""
# enable fence, disable avoidance
self.set_parameters({
"FENCE_ENABLE": 1,
"AVOID_ENABLE": 0,
"FENCE_TYPE": 1,
})
self.change_alt(10)
# first east
self.progress("turning east")
self.set_rc(4, 1580)
self.wait_heading(160, timeout=60)
self.set_rc(4, 1500)
self.progress("flying east 20m")
self.set_rc(2, 1100)
self.wait_distance(20)
self.progress("flying up")
self.set_rc_from_map({
2: 1500,
3: 1800,
})
# wait for fence to trigger
self.wait_mode('RTL', timeout=120)
self.wait_rtl_complete()
self.zero_throttle()
# fly_alt_min_fence_test - fly down until you hit the fence floor
def fly_alt_min_fence_test(self):
self.takeoff(30, mode="LOITER", timeout=60)
# enable fence, disable avoidance
self.set_parameters({
"AVOID_ENABLE": 0,
"FENCE_TYPE": 8,
"FENCE_ALT_MIN": 20,
})
self.change_alt(30)
# Activate the floor fence
# TODO this test should run without requiring this
self.do_fence_enable()
# first east
self.progress("turn east")
self.set_rc(4, 1580)
self.wait_heading(160, timeout=60)
self.set_rc(4, 1500)
# fly forward (east) at least 20m
self.set_rc(2, 1100)
self.wait_distance(20)
# stop flying forward and start flying down:
self.set_rc_from_map({
2: 1500,
3: 1200,
})
# wait for fence to trigger
self.wait_mode('RTL', timeout=120)
self.wait_rtl_complete()
# Disable the fence using mavlink command to ensure cleaned up SITL state
self.do_fence_disable()
self.zero_throttle()
def fly_fence_floor_enabled_landing(self):
""" fly_fence_floor_enabled_landing. Ensures we can initiate and complete
an RTL while the fence is enabled. """
fence_bit = mavutil.mavlink.MAV_SYS_STATUS_GEOFENCE
self.progress("Test Landing while fence floor enabled")
self.set_parameters({
"AVOID_ENABLE": 0,
"FENCE_TYPE": 15,
"FENCE_ALT_MIN": 10,
"FENCE_ALT_MAX": 20,
})
self.change_mode("GUIDED")
self.wait_ready_to_arm()
self.arm_vehicle()
self.user_takeoff(alt_min=15)
# Check fence is enabled
self.do_fence_enable()
self.assert_fence_enabled()
# Change to RC controlled mode
self.change_mode('LOITER')
self.set_rc(3, 1800)
self.wait_mode('RTL', timeout=120)
self.wait_landed_and_disarmed()
self.assert_fence_enabled()
# Assert fence is not healthy
self.assert_sensor_state(fence_bit, healthy=False)
# Disable the fence using mavlink command to ensure cleaned up SITL state
self.do_fence_disable()
self.assert_fence_disabled()
def fly_gps_glitch_loiter_test(self, timeout=30, max_distance=20):
"""fly_gps_glitch_loiter_test. Fly south east in loiter and test
reaction to gps glitch."""
self.takeoff(10, mode="LOITER")
# turn on simulator display of gps and actual position
if self.use_map:
self.show_gps_and_sim_positions(True)
# set-up gps glitch array
glitch_lat = [0.0002996,
0.0006958,
0.0009431,
0.0009991,
0.0009444,
0.0007716,
0.0006221]
glitch_lon = [0.0000717,
0.0000912,
0.0002761,
0.0002626,
0.0002807,
0.0002049,
0.0001304]
glitch_num = len(glitch_lat)
self.progress("GPS Glitches:")
for i in range(1, glitch_num):
self.progress("glitch %d %.7f %.7f" %
(i, glitch_lat[i], glitch_lon[i]))
# turn south east
self.progress("turn south east")
self.set_rc(4, 1580)
try:
self.wait_heading(150)
self.set_rc(4, 1500)
# fly forward (south east) at least 60m
self.set_rc(2, 1100)
self.wait_distance(60)
self.set_rc(2, 1500)
# wait for copter to slow down
except Exception as e:
if self.use_map:
self.show_gps_and_sim_positions(False)
raise e
# record time and position
tstart = self.get_sim_time()
tnow = tstart
start_pos = self.sim_location()
# initialise current glitch
glitch_current = 0
self.progress("Apply first glitch")
self.set_parameters({
"SIM_GPS_GLITCH_X": glitch_lat[glitch_current],
"SIM_GPS_GLITCH_Y": glitch_lon[glitch_current],
})
# record position for 30 seconds
while tnow < tstart + timeout:
tnow = self.get_sim_time_cached()
desired_glitch_num = int((tnow - tstart) * 2.2)
if desired_glitch_num > glitch_current and glitch_current != -1:
glitch_current = desired_glitch_num
# turn off glitching if we've reached the end of glitch list
if glitch_current >= glitch_num:
glitch_current = -1
self.progress("Completed Glitches")
self.set_parameters({
"SIM_GPS_GLITCH_X": 0,
"SIM_GPS_GLITCH_Y": 0,
})
else:
self.progress("Applying glitch %u" % glitch_current)
# move onto the next glitch
self.set_parameters({
"SIM_GPS_GLITCH_X": glitch_lat[glitch_current],
"SIM_GPS_GLITCH_Y": glitch_lon[glitch_current],
})
# start displaying distance moved after all glitches applied
if glitch_current == -1:
m = self.mav.recv_match(type='GLOBAL_POSITION_INT',
blocking=True)
alt = m.alt/1000.0 # mm -> m
curr_pos = self.sim_location()
moved_distance = self.get_distance(curr_pos, start_pos)
self.progress("Alt: %.02f Moved: %.0f" %
(alt, moved_distance))
if moved_distance > max_distance:
raise NotAchievedException(
"Moved over %u meters, Failed!" % max_distance)
else:
self.drain_mav()
# disable gps glitch
if glitch_current != -1:
self.set_parameters({
"SIM_GPS_GLITCH_X": 0,
"SIM_GPS_GLITCH_Y": 0,
})
if self.use_map:
self.show_gps_and_sim_positions(False)
self.progress("GPS glitch test passed!"
" stayed within %u meters for %u seconds" %
(max_distance, timeout))
self.do_RTL()
# re-arming is problematic because the GPS is glitching!
self.reboot_sitl()
def fly_gps_glitch_loiter_test2(self):
"""test vehicle handles GPS glitch (aka EKF Reset) without twitching"""
self.context_push()
self.takeoff(10, mode="LOITER")
# wait for vehicle to level
self.wait_attitude(desroll=0, despitch=0, timeout=10, tolerance=1)
# apply glitch
self.set_parameter("SIM_GPS_GLITCH_X", 0.001)
# check lean angles remain stable for 20 seconds
tstart = self.get_sim_time()
while self.get_sim_time_cached() - tstart < 20:
m = self.mav.recv_match(type='ATTITUDE', blocking=True)
roll_deg = math.degrees(m.roll)
pitch_deg = math.degrees(m.pitch)
self.progress("checking att: roll=%f pitch=%f " % (roll_deg, pitch_deg))
if abs(roll_deg) > 2 or abs(pitch_deg) > 2:
raise NotAchievedException("fly_gps_glitch_loiter_test2 failed, roll or pitch moved during GPS glitch")
# RTL, remove glitch and reboot sitl
self.do_RTL()
self.context_pop()
self.reboot_sitl()
# fly_gps_glitch_auto_test - fly mission and test reaction to gps glitch
def fly_gps_glitch_auto_test(self, timeout=180):
# set-up gps glitch array
glitch_lat = [0.0002996,
0.0006958,
0.0009431,
0.0009991,
0.0009444,
0.0007716,
0.0006221]
glitch_lon = [0.0000717,
0.0000912,
0.0002761,
0.0002626,
0.0002807,
0.0002049,
0.0001304]
glitch_num = len(glitch_lat)
self.progress("GPS Glitches:")
for i in range(1, glitch_num):
self.progress("glitch %d %.7f %.7f" %
(i, glitch_lat[i], glitch_lon[i]))
# Fly mission #1
self.progress("# Load copter_glitch_mission")
# load the waypoint count
num_wp = self.load_mission("copter_glitch_mission.txt", strict=False)
if not num_wp:
raise NotAchievedException("load copter_glitch_mission failed")
# turn on simulator display of gps and actual position
if self.use_map:
self.show_gps_and_sim_positions(True)
self.progress("test: Fly a mission from 1 to %u" % num_wp)
self.set_current_waypoint(1)
self.change_mode("STABILIZE")
self.wait_ready_to_arm()
self.zero_throttle()
self.arm_vehicle()
# switch into AUTO mode and raise throttle
self.change_mode('AUTO')
self.set_rc(3, 1500)
# wait until 100m from home
try:
self.wait_distance(100, 5, 90)
except Exception as e:
if self.use_map:
self.show_gps_and_sim_positions(False)
raise e
# record time and position
tstart = self.get_sim_time()
# initialise current glitch
glitch_current = 0
self.progress("Apply first glitch")
self.set_parameters({
"SIM_GPS_GLITCH_X": glitch_lat[glitch_current],
"SIM_GPS_GLITCH_Y": glitch_lon[glitch_current],
})
# record position for 30 seconds
while glitch_current < glitch_num:
tnow = self.get_sim_time()
desired_glitch_num = int((tnow - tstart) * 2.2)
if desired_glitch_num > glitch_current and glitch_current != -1:
glitch_current = desired_glitch_num
# apply next glitch
if glitch_current < glitch_num:
self.progress("Applying glitch %u" % glitch_current)
self.set_parameters({
"SIM_GPS_GLITCH_X": glitch_lat[glitch_current],
"SIM_GPS_GLITCH_Y": glitch_lon[glitch_current],
})
# turn off glitching
self.progress("Completed Glitches")
self.set_parameters({
"SIM_GPS_GLITCH_X": 0,
"SIM_GPS_GLITCH_Y": 0,
})
# continue with the mission
self.wait_waypoint(0, num_wp-1, timeout=500)
# wait for arrival back home
self.wait_distance_to_home(0, 10, timeout=timeout)
# turn off simulator display of gps and actual position
if self.use_map:
self.show_gps_and_sim_positions(False)
self.progress("GPS Glitch test Auto completed: passed!")
self.wait_disarmed()
# re-arming is problematic because the GPS is glitching!
self.reboot_sitl()
# fly_simple - assumes the simple bearing is initialised to be
# directly north flies a box with 100m west, 15 seconds north,
# 50 seconds east, 15 seconds south
def fly_simple(self, side=50):
self.takeoff(10, mode="LOITER")
# set SIMPLE mode for all flight modes
self.set_parameter("SIMPLE", 63)
# switch to stabilize mode
self.change_mode('STABILIZE')
self.set_rc(3, 1545)
# fly south 50m
self.progress("# Flying south %u meters" % side)
self.set_rc(1, 1300)
self.wait_distance(side, 5, 60)
self.set_rc(1, 1500)
# fly west 8 seconds
self.progress("# Flying west for 8 seconds")
self.set_rc(2, 1300)
tstart = self.get_sim_time()
while self.get_sim_time_cached() < (tstart + 8):
self.mav.recv_match(type='VFR_HUD', blocking=True)
self.set_rc(2, 1500)
# fly north 25 meters
self.progress("# Flying north %u meters" % (side/2.0))
self.set_rc(1, 1700)
self.wait_distance(side/2, 5, 60)
self.set_rc(1, 1500)
# fly east 8 seconds
self.progress("# Flying east for 8 seconds")
self.set_rc(2, 1700)
tstart = self.get_sim_time()
while self.get_sim_time_cached() < (tstart + 8):
self.mav.recv_match(type='VFR_HUD', blocking=True)
self.set_rc(2, 1500)
# hover in place
self.hover()
self.do_RTL(timeout=500)
# fly_super_simple - flies a circle around home for 45 seconds
def fly_super_simple(self, timeout=45):
self.takeoff(10, mode="LOITER")
# fly forward 20m
self.progress("# Flying forward 20 meters")
self.set_rc(2, 1300)
self.wait_distance(20, 5, 60)
self.set_rc(2, 1500)
# set SUPER SIMPLE mode for all flight modes
self.set_parameter("SUPER_SIMPLE", 63)
# switch to stabilize mode
self.change_mode("ALT_HOLD")
self.set_rc(3, 1500)
# start copter yawing slowly
self.set_rc(4, 1550)
# roll left for timeout seconds
self.progress("# rolling left from pilot's POV for %u seconds"
% timeout)
self.set_rc(1, 1300)
tstart = self.get_sim_time()
while self.get_sim_time_cached() < (tstart + timeout):
self.mav.recv_match(type='VFR_HUD', blocking=True)
# stop rolling and yawing
self.set_rc(1, 1500)
self.set_rc(4, 1500)
# restore simple mode parameters to default
self.set_parameter("SUPER_SIMPLE", 0)
# hover in place
self.hover()
self.do_RTL()
# fly_circle - flies a circle with 20m radius
def fly_circle(self, holdtime=36):
# the following should not be required. But there appears to
# be a physics failure in the simulation which is causing CI
# to fall over a lot. -pb 202007021209
self.reboot_sitl()
self.takeoff(10, mode="LOITER")
# face west
self.progress("turn west")
self.set_rc(4, 1580)
self.wait_heading(270)
self.set_rc(4, 1500)
# set CIRCLE radius
self.set_parameter("CIRCLE_RADIUS", 3000)
# fly forward (east) at least 100m
self.set_rc(2, 1100)
self.wait_distance(100)
# return pitch stick back to middle
self.set_rc(2, 1500)
# set CIRCLE mode
self.change_mode('CIRCLE')
# wait
m = self.mav.recv_match(type='VFR_HUD', blocking=True)
start_altitude = m.alt
tstart = self.get_sim_time()
self.progress("Circle at %u meters for %u seconds" %
(start_altitude, holdtime))
while self.get_sim_time_cached() < tstart + holdtime:
m = self.mav.recv_match(type='VFR_HUD', blocking=True)
self.progress("heading %d" % m.heading)
self.progress("CIRCLE OK for %u seconds" % holdtime)
self.do_RTL()
# test_mag_fail - test failover of compass in EKF
def test_mag_fail(self):
# we want both EK2 and EK3
self.set_parameters({
"EK2_ENABLE": 1,
"EK3_ENABLE": 1,
})
self.takeoff(10, mode="LOITER")
self.change_mode('CIRCLE')
self.delay_sim_time(20)
self.context_collect("STATUSTEXT")
self.progress("Failing first compass")
self.set_parameter("SIM_MAG1_FAIL", 1)
# we want for the message twice, one for EK2 and again for EK3
self.wait_statustext("EKF2 IMU0 switching to compass 1", check_context=True)
self.wait_statustext("EKF3 IMU0 switching to compass 1", check_context=True)
self.progress("compass switch 1 OK")
self.delay_sim_time(2)
self.context_clear_collection("STATUSTEXT")
self.progress("Failing 2nd compass")
self.set_parameter("SIM_MAG2_FAIL", 1)
self.wait_statustext("EKF2 IMU0 switching to compass 2", check_context=True)
self.wait_statustext("EKF3 IMU0 switching to compass 2", check_context=True)
self.progress("compass switch 2 OK")
self.delay_sim_time(2)
self.context_clear_collection("STATUSTEXT")
self.progress("Failing 3rd compass")
self.set_parameter("SIM_MAG3_FAIL", 1)
self.delay_sim_time(2)
self.set_parameter("SIM_MAG1_FAIL", 0)
self.wait_statustext("EKF2 IMU0 switching to compass 0", check_context=True)
self.wait_statustext("EKF3 IMU0 switching to compass 0", check_context=True)
self.progress("compass switch 0 OK")
self.do_RTL()
def fly_flip(self):
ex = None
try:
self.set_message_rate_hz(mavutil.mavlink.MAVLINK_MSG_ID_ATTITUDE, 100)
self.takeoff(20)
self.hover()
old_speedup = self.get_parameter("SIM_SPEEDUP")
self.set_parameter('SIM_SPEEDUP', 1)
self.progress("Flipping in roll")
self.set_rc(1, 1700)
self.send_cmd_do_set_mode('FLIP') # don't wait for success
self.wait_attitude(despitch=0, desroll=45, tolerance=30)
self.wait_attitude(despitch=0, desroll=90, tolerance=30)
self.wait_attitude(despitch=0, desroll=-45, tolerance=30)
self.progress("Waiting for level")
self.set_rc(1, 1500) # can't change quickly enough!
self.wait_attitude(despitch=0, desroll=0, tolerance=5)
self.progress("Regaining altitude")
self.change_mode('ALT_HOLD')
self.wait_for_alt(20, max_err=40)
self.progress("Flipping in pitch")
self.set_rc(2, 1700)
self.send_cmd_do_set_mode('FLIP') # don't wait for success
self.wait_attitude(despitch=45, desroll=0, tolerance=30)
# can't check roll here as it flips from 0 to -180..
self.wait_attitude(despitch=90, tolerance=30)
self.wait_attitude(despitch=-45, tolerance=30)
self.progress("Waiting for level")
self.set_rc(2, 1500) # can't change quickly enough!
self.wait_attitude(despitch=0, desroll=0, tolerance=5)
self.set_parameter('SIM_SPEEDUP', old_speedup)
self.do_RTL()
except Exception as e:
self.print_exception_caught(e)
ex = e
self.set_message_rate_hz(mavutil.mavlink.MAVLINK_MSG_ID_ATTITUDE, 0)
if ex is not None:
raise ex
def configure_EKFs_to_use_optical_flow_instead_of_GPS(self):
'''configure EKF to use optical flow instead of GPS'''
ahrs_ekf_type = self.get_parameter("AHRS_EKF_TYPE")
if ahrs_ekf_type == 2:
self.set_parameter("EK2_GPS_TYPE", 3)
if ahrs_ekf_type == 3:
self.set_parameters({
"EK3_SRC1_POSXY": 0,
"EK3_SRC1_VELXY": 5,
"EK3_SRC1_VELZ": 0,
})
def optical_flow(self):
'''test optical low works'''
self.start_subtest("Make sure no crash if no rangefinder")
self.set_parameter("SIM_FLOW_ENABLE", 1)
self.set_parameter("FLOW_TYPE", 10)
self.configure_EKFs_to_use_optical_flow_instead_of_GPS()
self.reboot_sitl()
self.change_mode('LOITER')
self.delay_sim_time(5)
self.wait_statustext("Need Position Estimate", timeout=300)
# fly_optical_flow_limits - test EKF navigation limiting
def fly_optical_flow_limits(self):
ex = None
self.context_push()
try:
self.set_parameter("SIM_FLOW_ENABLE", 1)
self.set_parameter("FLOW_TYPE", 10)
self.configure_EKFs_to_use_optical_flow_instead_of_GPS()
self.set_analog_rangefinder_parameters()
self.set_parameter("SIM_GPS_DISABLE", 1)
self.set_parameter("SIM_TERRAIN", 0)
self.reboot_sitl()
# we can't takeoff in loiter as we need flow healthy
self.takeoff(alt_min=5, mode='ALT_HOLD', require_absolute=False, takeoff_throttle=1800)
self.change_mode('LOITER')
# speed should be limited to <10m/s
self.set_rc(2, 1000)
tstart = self.get_sim_time()
timeout = 60
started_climb = False
while self.get_sim_time_cached() - tstart < timeout:
m = self.mav.recv_match(type='GLOBAL_POSITION_INT', blocking=True)
spd = math.sqrt(m.vx**2 + m.vy**2) * 0.01
alt = m.relative_alt*0.001
# calculate max speed from altitude above the ground
margin = 2.0
max_speed = alt * 1.5 + margin
self.progress("%0.1f: Low Speed: %f (want <= %u) alt=%.1f" %
(self.get_sim_time_cached() - tstart,
spd,
max_speed, alt))
if spd > max_speed:
raise NotAchievedException(("Speed should be limited by"
"EKF optical flow limits"))
# after 30 seconds start climbing
if not started_climb and self.get_sim_time_cached() - tstart > 30:
started_climb = True
self.set_rc(3, 1900)
self.progress("Moving higher")
# check altitude is not climbing above 35m
if alt > 35:
raise NotAchievedException("Alt should be limited by EKF optical flow limits")
except Exception as e:
self.print_exception_caught(e)
ex = e
self.set_rc(2, 1500)
self.context_pop()
self.disarm_vehicle(force=True)
self.reboot_sitl()
if ex is not None:
raise ex
# fly_optical_flow_calibration - test optical flow calibration
def fly_optical_flow_calibration(self):
ex = None
self.context_push()
try:
self.set_parameter("SIM_FLOW_ENABLE", 1)
self.set_parameter("FLOW_TYPE", 10)
self.set_analog_rangefinder_parameters()
# RC9 starts/stops calibration
self.set_parameter("RC9_OPTION", 158)
# initialise flow scaling parameters to incorrect values
self.set_parameter("FLOW_FXSCALER", -200)
self.set_parameter("FLOW_FYSCALER", 200)
self.reboot_sitl()
# ensure calibration is off
self.set_rc(9, 1000)
# takeoff to 10m in loiter
self.takeoff(10, mode="LOITER", require_absolute=True, timeout=720)
# start calibration
self.set_rc(9, 2000)
tstart = self.get_sim_time()
timeout = 90
veh_dir_tstart = self.get_sim_time()
veh_dir = 0
while self.get_sim_time_cached() - tstart < timeout:
# roll and pitch vehicle until samples collected
# change direction of movement every 2 seconds
if self.get_sim_time_cached() - veh_dir_tstart > 2:
veh_dir_tstart = self.get_sim_time()
veh_dir = veh_dir + 1
if veh_dir > 3:
veh_dir = 0
if veh_dir == 0:
# move right
self.set_rc(1, 1800)
self.set_rc(2, 1500)
if veh_dir == 1:
# move left
self.set_rc(1, 1200)
self.set_rc(2, 1500)
if veh_dir == 2:
# move forward
self.set_rc(1, 1500)
self.set_rc(2, 1200)
if veh_dir == 3:
# move back
self.set_rc(1, 1500)
self.set_rc(2, 1800)
# return sticks to center
self.set_rc(1, 1500)
self.set_rc(2, 1500)
# stop calibration (not actually necessary)
self.set_rc(9, 1000)
# check scaling parameters have been restored to values near zero
flow_scalar_x = self.get_parameter("FLOW_FXSCALER")
flow_scalar_y = self.get_parameter("FLOW_FYSCALER")
if ((flow_scalar_x > 30) or (flow_scalar_x < -30)):
raise NotAchievedException("FlowCal failed to set FLOW_FXSCALER correctly")
if ((flow_scalar_y > 30) or (flow_scalar_y < -30)):
raise NotAchievedException("FlowCal failed to set FLOW_FYSCALER correctly")
except Exception as e:
self.print_exception_caught(e)
ex = e
self.context_pop()
self.disarm_vehicle(force=True)
self.reboot_sitl()
if ex is not None:
raise ex
def fly_autotune(self):
"""Test autotune mode"""
rlld = self.get_parameter("ATC_RAT_RLL_D")
rlli = self.get_parameter("ATC_RAT_RLL_I")
rllp = self.get_parameter("ATC_RAT_RLL_P")
self.set_parameter("ATC_RAT_RLL_SMAX", 1)
self.takeoff(10)
# hold position in loiter
self.change_mode('AUTOTUNE')
tstart = self.get_sim_time()
sim_time_expected = 5000
deadline = tstart + sim_time_expected
while self.get_sim_time_cached() < deadline:
now = self.get_sim_time_cached()
m = self.mav.recv_match(type='STATUSTEXT',
blocking=True,
timeout=1)
if m is None:
continue
self.progress("STATUSTEXT (%u<%u): %s" % (now, deadline, m.text))
if "AutoTune: Success" in m.text:
self.progress("AUTOTUNE OK (%u seconds)" % (now - tstart))
# near enough for now:
self.change_mode('LAND')
self.wait_landed_and_disarmed()
# check the original gains have been re-instated
if (rlld != self.get_parameter("ATC_RAT_RLL_D") or
rlli != self.get_parameter("ATC_RAT_RLL_I") or
rllp != self.get_parameter("ATC_RAT_RLL_P")):
raise NotAchievedException("AUTOTUNE gains still present")
return
raise NotAchievedException("AUTOTUNE failed (%u seconds)" %
(self.get_sim_time() - tstart))
def fly_autotune_switch(self):
"""Test autotune on a switch with gains being saved"""
# autotune changes a set of parameters on the vehicle which
# are not in our context. That changes the flight
# characterstics, which we can't afford between runs. So
# completely reset the simulated vehicle after the run is
# complete by "customising" the commandline here:
self.customise_SITL_commandline([])
self.context_push()
ex = None
try:
self.fly_autotune_switch_body()
except Exception as e:
self.print_exception_caught(e)
ex = e
self.context_pop()
if ex is not None:
raise ex
def fly_autotune_switch_body(self):
self.set_parameters({
"RC8_OPTION": 17,
"ATC_RAT_RLL_FLTT": 20,
})
rlld = self.get_parameter("ATC_RAT_RLL_D")
rlli = self.get_parameter("ATC_RAT_RLL_I")
rllp = self.get_parameter("ATC_RAT_RLL_P")
rllt = self.get_parameter("ATC_RAT_RLL_FLTT")
self.progress("AUTOTUNE pre-gains are P:%f I:%f D:%f" %
(self.get_parameter("ATC_RAT_RLL_P"),
self.get_parameter("ATC_RAT_RLL_I"),
self.get_parameter("ATC_RAT_RLL_D")))
self.takeoff(10, mode='LOITER')
# hold position in loiter and run autotune
self.set_rc(8, 1850)
self.wait_mode('AUTOTUNE')
tstart = self.get_sim_time()
sim_time_expected = 5000
deadline = tstart + sim_time_expected
while self.get_sim_time_cached() < deadline:
now = self.get_sim_time_cached()
m = self.mav.recv_match(type='STATUSTEXT',
blocking=True,
timeout=1)
if m is None:
continue
self.progress("STATUSTEXT (%u<%u): %s" % (now, deadline, m.text))
if "AutoTune: Success" in m.text:
self.progress("AUTOTUNE OK (%u seconds)" % (now - tstart))
# Check original gains are re-instated
self.set_rc(8, 1100)
self.delay_sim_time(1)
self.progress("AUTOTUNE original gains are P:%f I:%f D:%f" %
(self.get_parameter("ATC_RAT_RLL_P"), self.get_parameter("ATC_RAT_RLL_I"),
self.get_parameter("ATC_RAT_RLL_D")))
if (rlld != self.get_parameter("ATC_RAT_RLL_D") or
rlli != self.get_parameter("ATC_RAT_RLL_I") or
rllp != self.get_parameter("ATC_RAT_RLL_P")):
raise NotAchievedException("AUTOTUNE gains still present")
# Use autotuned gains
self.set_rc(8, 1850)
self.delay_sim_time(1)
self.progress("AUTOTUNE testing gains are P:%f I:%f D:%f" %
(self.get_parameter("ATC_RAT_RLL_P"), self.get_parameter("ATC_RAT_RLL_I"),
self.get_parameter("ATC_RAT_RLL_D")))
if (rlld == self.get_parameter("ATC_RAT_RLL_D") or
rlli == self.get_parameter("ATC_RAT_RLL_I") or
rllp == self.get_parameter("ATC_RAT_RLL_P")):
raise NotAchievedException("AUTOTUNE gains not present in pilot testing")
# land without changing mode
self.set_rc(3, 1000)
self.wait_for_alt(0)
self.wait_disarmed()
# Check gains are still there after disarm
if (rlld == self.get_parameter("ATC_RAT_RLL_D") or
rlli == self.get_parameter("ATC_RAT_RLL_I") or
rllp == self.get_parameter("ATC_RAT_RLL_P")):
raise NotAchievedException("AUTOTUNE gains not present on disarm")
self.reboot_sitl()
# Check gains are still there after reboot
if (rlld == self.get_parameter("ATC_RAT_RLL_D") or
rlli == self.get_parameter("ATC_RAT_RLL_I") or
rllp == self.get_parameter("ATC_RAT_RLL_P")):
raise NotAchievedException("AUTOTUNE gains not present on reboot")
# Check FLTT is unchanged
if rllt != self.get_parameter("ATC_RAT_RLL_FLTT"):
raise NotAchievedException("AUTOTUNE FLTT was modified")
return
raise NotAchievedException("AUTOTUNE failed (%u seconds)" %
(self.get_sim_time() - tstart))
# fly_auto_test - fly mission which tests a significant number of commands
def fly_auto_test(self):
# Fly mission #1
self.progress("# Load copter_mission")
# load the waypoint count
num_wp = self.load_mission("copter_mission.txt", strict=False)
if not num_wp:
raise NotAchievedException("load copter_mission failed")
self.fly_loaded_mission(num_wp)
self.progress("Auto mission completed: passed!")
def fly_loaded_mission(self, num_wp):
'''fly mission loaded on vehicle. FIXME: get num_wp from vehicle'''
self.progress("test: Fly a mission from 1 to %u" % num_wp)
self.set_current_waypoint(1)
self.change_mode("LOITER")
self.wait_ready_to_arm()
self.arm_vehicle()
# switch into AUTO mode and raise throttle
self.change_mode("AUTO")
self.set_rc(3, 1500)
# fly the mission
self.wait_waypoint(0, num_wp-1, timeout=500)
# set throttle to minimum
self.zero_throttle()
# wait for disarm
self.wait_disarmed()
self.progress("MOTORS DISARMED OK")
# fly_auto_test using CAN GPS - fly mission which tests normal operation alongside CAN GPS
def fly_auto_test_using_can_gps(self):
self.set_parameters({
"CAN_P1_DRIVER": 1,
"GPS_TYPE": 9,
"GPS_TYPE2": 9,
"SIM_GPS2_DISABLE": 0,
})
self.context_push()
self.set_parameter("ARMING_CHECK", 1 << 3)
self.context_collect('STATUSTEXT')
self.reboot_sitl()
# Test UAVCAN GPS ordering working
gps1_det_text = self.wait_text("GPS 1: specified as UAVCAN.*", regex=True, check_context=True)
gps2_det_text = self.wait_text("GPS 2: specified as UAVCAN.*", regex=True, check_context=True)
gps1_nodeid = int(gps1_det_text.split('-')[1])
gps2_nodeid = int(gps2_det_text.split('-')[1])
if gps1_nodeid is None or gps2_nodeid is None:
raise NotAchievedException("GPS not ordered per the order of Node IDs")
self.context_stop_collecting('STATUSTEXT')
GPS_Order_Tests = [[gps2_nodeid, gps2_nodeid, gps2_nodeid, 0,
"PreArm: Same Node Id {} set for multiple GPS".format(gps2_nodeid)],
[gps1_nodeid, int(gps2_nodeid/2), gps1_nodeid, 0,
"Selected GPS Node {} not set as instance {}".format(int(gps2_nodeid/2), 2)],
[int(gps1_nodeid/2), gps2_nodeid, 0, gps2_nodeid,
"Selected GPS Node {} not set as instance {}".format(int(gps1_nodeid/2), 1)],
[gps1_nodeid, gps2_nodeid, gps1_nodeid, gps2_nodeid, ""],
[gps2_nodeid, gps1_nodeid, gps2_nodeid, gps1_nodeid, ""],
[gps1_nodeid, 0, gps1_nodeid, gps2_nodeid, ""],
[0, gps2_nodeid, gps1_nodeid, gps2_nodeid, ""]]
for case in GPS_Order_Tests:
self.progress("############################### Trying Case: " + str(case))
self.set_parameters({
"GPS1_CAN_OVRIDE": case[0],
"GPS2_CAN_OVRIDE": case[1],
})
self.drain_mav()
self.context_collect('STATUSTEXT')
self.reboot_sitl()
gps1_det_text = None
gps2_det_text = None
try:
gps1_det_text = self.wait_text("GPS 1: specified as UAVCAN.*", regex=True, check_context=True)
except AutoTestTimeoutException:
pass
try:
gps2_det_text = self.wait_text("GPS 2: specified as UAVCAN.*", regex=True, check_context=True)
except AutoTestTimeoutException:
pass
self.context_stop_collecting('STATUSTEXT')
self.change_mode('LOITER')
if case[2] == 0 and case[3] == 0:
if gps1_det_text or gps2_det_text:
raise NotAchievedException("Failed ordering for requested CASE:", case)
if case[2] == 0 or case[3] == 0:
if bool(gps1_det_text is not None) == bool(gps2_det_text is not None):
print(gps1_det_text)
print(gps2_det_text)
raise NotAchievedException("Failed ordering for requested CASE:", case)
if gps1_det_text:
if case[2] != int(gps1_det_text.split('-')[1]):
raise NotAchievedException("Failed ordering for requested CASE:", case)
if gps2_det_text:
if case[3] != int(gps2_det_text.split('-')[1]):
raise NotAchievedException("Failed ordering for requested CASE:", case)
if len(case[4]):
self.context_collect('STATUSTEXT')
self.run_cmd(mavutil.mavlink.MAV_CMD_COMPONENT_ARM_DISARM,
1, # ARM
0,
0,
0,
0,
0,
0,
timeout=10,
want_result=mavutil.mavlink.MAV_RESULT_FAILED)
self.wait_statustext(case[4], check_context=True)
self.context_stop_collecting('STATUSTEXT')
self.progress("############################### All GPS Order Cases Tests Passed")
self.context_pop()
self.fly_auto_test()
def fly_motor_fail(self, fail_servo=0, fail_mul=0.0, holdtime=30):
"""Test flight with reduced motor efficiency"""
# we only expect an octocopter to survive ATM:
servo_counts = {
# 2: 6, # hexa
3: 8, # octa
# 5: 6, # Y6
}
frame_class = int(self.get_parameter("FRAME_CLASS"))
if frame_class not in servo_counts:
self.progress("Test not relevant for frame_class %u" % frame_class)
return
servo_count = servo_counts[frame_class]
if fail_servo < 0 or fail_servo > servo_count:
raise ValueError('fail_servo outside range for frame class')
self.takeoff(10, mode="LOITER")
self.change_alt(alt_min=50)
# Get initial values
start_hud = self.mav.recv_match(type='VFR_HUD', blocking=True)
start_attitude = self.mav.recv_match(type='ATTITUDE', blocking=True)
hover_time = 5
try:
tstart = self.get_sim_time()
int_error_alt = 0
int_error_yaw_rate = 0
int_error_yaw = 0
self.progress("Hovering for %u seconds" % hover_time)
failed = False
while True:
now = self.get_sim_time_cached()
if now - tstart > holdtime + hover_time:
break
servo = self.mav.recv_match(type='SERVO_OUTPUT_RAW',
blocking=True)
hud = self.mav.recv_match(type='VFR_HUD', blocking=True)
attitude = self.mav.recv_match(type='ATTITUDE', blocking=True)
if not failed and now - tstart > hover_time:
self.progress("Killing motor %u (%u%%)" %
(fail_servo+1, fail_mul))
self.set_parameters({
"SIM_ENGINE_FAIL": fail_servo,
"SIM_ENGINE_MUL": fail_mul,
})
failed = True
if failed:
self.progress("Hold Time: %f/%f" % (now-tstart, holdtime))
servo_pwm = [servo.servo1_raw,
servo.servo2_raw,
servo.servo3_raw,
servo.servo4_raw,
servo.servo5_raw,
servo.servo6_raw,
servo.servo7_raw,
servo.servo8_raw]
self.progress("PWM output per motor")
for i, pwm in enumerate(servo_pwm[0:servo_count]):
if pwm > 1900:
state = "oversaturated"
elif pwm < 1200:
state = "undersaturated"
else:
state = "OK"
if failed and i == fail_servo:
state += " (failed)"
self.progress("servo %u [pwm=%u] [%s]" % (i+1, pwm, state))
alt_delta = hud.alt - start_hud.alt
yawrate_delta = attitude.yawspeed - start_attitude.yawspeed
yaw_delta = attitude.yaw - start_attitude.yaw
self.progress("Alt=%fm (delta=%fm)" % (hud.alt, alt_delta))
self.progress("Yaw rate=%f (delta=%f) (rad/s)" %
(attitude.yawspeed, yawrate_delta))
self.progress("Yaw=%f (delta=%f) (deg)" %
(attitude.yaw, yaw_delta))
dt = self.get_sim_time() - now
int_error_alt += abs(alt_delta/dt)
int_error_yaw_rate += abs(yawrate_delta/dt)
int_error_yaw += abs(yaw_delta/dt)
self.progress("## Error Integration ##")
self.progress(" Altitude: %fm" % int_error_alt)
self.progress(" Yaw rate: %f rad/s" % int_error_yaw_rate)
self.progress(" Yaw: %f deg" % int_error_yaw)
self.progress("----")
if int_error_yaw_rate > 0.1:
raise NotAchievedException("Vehicle is spinning")
if alt_delta < -20:
raise NotAchievedException("Vehicle is descending")
self.set_parameters({
"SIM_ENGINE_FAIL": 0,
"SIM_ENGINE_MUL": 1.0,
})
except Exception as e:
self.set_parameters({
"SIM_ENGINE_FAIL": 0,
"SIM_ENGINE_MUL": 1.0,
})
raise e
self.do_RTL()
def fly_motor_vibration(self):
"""Test flight with motor vibration"""
self.context_push()
ex = None
try:
self.set_rc_default()
# magic tridge EKF type that dramatically speeds up the test
self.set_parameters({
"AHRS_EKF_TYPE": 10,
"INS_LOG_BAT_MASK": 3,
"INS_LOG_BAT_OPT": 0,
"LOG_BITMASK": 958,
"LOG_DISARMED": 0,
"SIM_VIB_MOT_MAX": 350,
# these are real values taken from a 180mm Quad:
"SIM_GYR1_RND": 20,
"SIM_ACC1_RND": 5,
"SIM_ACC2_RND": 5,
"SIM_INS_THR_MIN": 0.1,
})
self.reboot_sitl()
self.takeoff(15, mode="ALT_HOLD")
hover_time = 15
tstart = self.get_sim_time()
self.progress("Hovering for %u seconds" % hover_time)
while self.get_sim_time_cached() < tstart + hover_time:
self.mav.recv_match(type='ATTITUDE', blocking=True)
tend = self.get_sim_time()
# if we don't reduce vibes here then the landing detector
# may not trigger
self.set_parameter("SIM_VIB_MOT_MAX", 0)
self.do_RTL()
psd = self.mavfft_fttd(1, 0, tstart * 1.0e6, tend * 1.0e6)
# ignore the first 20Hz and look for a peak at -15dB or more
ignore_bins = 20
freq = psd["F"][numpy.argmax(psd["X"][ignore_bins:]) + ignore_bins]
if numpy.amax(psd["X"][ignore_bins:]) < -15 or freq < 180 or freq > 300:
raise NotAchievedException(
"Did not detect a motor peak, found %f at %f dB" %
(freq, numpy.amax(psd["X"][ignore_bins:])))
else:
self.progress("Detected motor peak at %fHz" % freq)
# now add a notch and check that post-filter the peak is squashed below 40dB
self.set_parameters({
"INS_LOG_BAT_OPT": 2,
"INS_NOTCH_ENABLE": 1,
"INS_NOTCH_FREQ": freq,
"INS_NOTCH_ATT": 50,
"INS_NOTCH_BW": freq/2,
"SIM_VIB_MOT_MAX": 350,
})
self.reboot_sitl()
self.takeoff(15, mode="ALT_HOLD")
tstart = self.get_sim_time()
self.progress("Hovering for %u seconds" % hover_time)
while self.get_sim_time_cached() < tstart + hover_time:
self.mav.recv_match(type='ATTITUDE', blocking=True)
tend = self.get_sim_time()
self.set_parameter("SIM_VIB_MOT_MAX", 0)
self.do_RTL()
psd = self.mavfft_fttd(1, 0, tstart * 1.0e6, tend * 1.0e6)
freq = psd["F"][numpy.argmax(psd["X"][ignore_bins:]) + ignore_bins]
peakdB = numpy.amax(psd["X"][ignore_bins:])
if peakdB < -23:
self.progress("Did not detect a motor peak, found %f at %f dB" % (freq, peakdB))
else:
raise NotAchievedException("Detected peak %.1f Hz %.2f dB" % (freq, peakdB))
except Exception as e:
self.print_exception_caught(e)
ex = e
self.disarm_vehicle(force=True)
self.context_pop()
self.reboot_sitl()
if ex is not None:
raise ex
def fly_vision_position(self):
"""Disable GPS navigation, enable Vicon input."""
# scribble down a location we can set origin to:
self.customise_SITL_commandline(["--uartF=sim:vicon:"])
self.progress("Waiting for location")
self.change_mode('LOITER')
self.wait_ready_to_arm()
old_pos = self.mav.recv_match(type='GLOBAL_POSITION_INT', blocking=True)
print("old_pos=%s" % str(old_pos))
self.context_push()
ex = None
try:
# configure EKF to use external nav instead of GPS
ahrs_ekf_type = self.get_parameter("AHRS_EKF_TYPE")
if ahrs_ekf_type == 2:
self.set_parameter("EK2_GPS_TYPE", 3)
if ahrs_ekf_type == 3:
self.set_parameters({
"EK3_SRC1_POSXY": 6,
"EK3_SRC1_VELXY": 6,
"EK3_SRC1_POSZ": 6,
"EK3_SRC1_VELZ": 6,
})
self.set_parameters({
"GPS_TYPE": 0,
"VISO_TYPE": 1,
"SERIAL5_PROTOCOL": 1,
})
self.reboot_sitl()
# without a GPS or some sort of external prompting, AP
# doesn't send system_time messages. So prompt it:
self.mav.mav.system_time_send(int(time.time() * 1000000), 0)
self.progress("Waiting for non-zero-lat")
tstart = self.get_sim_time()
while True:
self.mav.mav.set_gps_global_origin_send(1,
old_pos.lat,
old_pos.lon,
old_pos.alt)
gpi = self.mav.recv_match(type='GLOBAL_POSITION_INT',
blocking=True)
self.progress("gpi=%s" % str(gpi))
if gpi.lat != 0:
break
if self.get_sim_time_cached() - tstart > 60:
raise AutoTestTimeoutException("Did not get non-zero lat")
self.takeoff()
self.set_rc(1, 1600)
tstart = self.get_sim_time()
while True:
vicon_pos = self.mav.recv_match(type='VISION_POSITION_ESTIMATE',
blocking=True)
# print("vpe=%s" % str(vicon_pos))
self.mav.recv_match(type='GLOBAL_POSITION_INT',
blocking=True)
# self.progress("gpi=%s" % str(gpi))
if vicon_pos.x > 40:
break
if self.get_sim_time_cached() - tstart > 100:
raise AutoTestTimeoutException("Vicon showed no movement")
# recenter controls:
self.set_rc(1, 1500)
self.progress("# Enter RTL")
self.change_mode('RTL')
self.set_rc(3, 1500)
tstart = self.get_sim_time()
while True:
if self.get_sim_time_cached() - tstart > 200:
raise NotAchievedException("Did not disarm")
self.mav.recv_match(type='GLOBAL_POSITION_INT',
blocking=True)
# print("gpi=%s" % str(gpi))
self.mav.recv_match(type='SIMSTATE',
blocking=True)
# print("ss=%s" % str(ss))
# wait for RTL disarm:
if not self.armed():
break
except Exception as e:
self.print_exception_caught(e)
ex = e
self.context_pop()
self.zero_throttle()
self.reboot_sitl()
if ex is not None:
raise ex
def fly_body_frame_odom(self):
"""Disable GPS navigation, enable input of VISION_POSITION_DELTA."""
if self.get_parameter("AHRS_EKF_TYPE") != 3:
# only tested on this EKF
return
self.customise_SITL_commandline(["--uartF=sim:vicon:"])
if self.current_onboard_log_contains_message("XKFD"):
raise NotAchievedException("Found unexpected XKFD message")
# scribble down a location we can set origin to:
self.progress("Waiting for location")
self.change_mode('LOITER')
self.wait_ready_to_arm()
old_pos = self.mav.recv_match(type='GLOBAL_POSITION_INT', blocking=True)
print("old_pos=%s" % str(old_pos))
# configure EKF to use external nav instead of GPS
self.set_parameters({
"EK3_SRC1_POSXY": 6,
"EK3_SRC1_VELXY": 6,
"EK3_SRC1_POSZ": 6,
"EK3_SRC1_VELZ": 6,
"GPS_TYPE": 0,
"VISO_TYPE": 1,
"SERIAL5_PROTOCOL": 1,
"SIM_VICON_TMASK": 8, # send VISION_POSITION_DELTA
})
self.reboot_sitl()
# without a GPS or some sort of external prompting, AP
# doesn't send system_time messages. So prompt it:
self.mav.mav.system_time_send(int(time.time() * 1000000), 0)
self.progress("Waiting for non-zero-lat")
tstart = self.get_sim_time()
while True:
self.mav.mav.set_gps_global_origin_send(1,
old_pos.lat,
old_pos.lon,
old_pos.alt)
gpi = self.mav.recv_match(type='GLOBAL_POSITION_INT',
blocking=True)
self.progress("gpi=%s" % str(gpi))
if gpi.lat != 0:
break
if self.get_sim_time_cached() - tstart > 60:
raise AutoTestTimeoutException("Did not get non-zero lat")
self.takeoff(alt_min=5, mode='ALT_HOLD', require_absolute=False, takeoff_throttle=1800)
self.change_mode('LAND')
# TODO: something more elaborate here - EKF will only aid
# relative position
self.wait_disarmed()
if not self.current_onboard_log_contains_message("XKFD"):
raise NotAchievedException("Did not find expected XKFD message")
def fly_gps_vicon_switching(self):
"""Fly GPS and Vicon switching test"""
self.customise_SITL_commandline(["--uartF=sim:vicon:"])
"""Setup parameters including switching to EKF3"""
self.context_push()
ex = None
try:
self.set_parameters({
"VISO_TYPE": 2, # enable vicon
"SERIAL5_PROTOCOL": 2,
"EK3_ENABLE": 1,
"EK3_SRC2_POSXY": 6, # External Nav
"EK3_SRC2_POSZ": 6, # External Nav
"EK3_SRC2_VELXY": 6, # External Nav
"EK3_SRC2_VELZ": 6, # External Nav
"EK3_SRC2_YAW": 6, # External Nav
"RC7_OPTION": 80, # RC aux switch 7 set to Viso Align
"RC8_OPTION": 90, # RC aux switch 8 set to EKF source selector
"EK2_ENABLE": 0,
"AHRS_EKF_TYPE": 3,
})
self.reboot_sitl()
# switch to use GPS
self.set_rc(8, 1000)
# ensure we can get a global position:
self.poll_home_position(timeout=120)
# record starting position
old_pos = self.get_global_position_int()
print("old_pos=%s" % str(old_pos))
# align vicon yaw with ahrs heading
self.set_rc(7, 2000)
# takeoff to 10m in Loiter
self.progress("Moving to ensure location is tracked")
self.takeoff(10, mode="LOITER", require_absolute=True, timeout=720)
# fly forward in Loiter
self.set_rc(2, 1300)
# disable vicon
self.set_parameter("SIM_VICON_FAIL", 1)
# ensure vehicle remain in Loiter for 15 seconds
tstart = self.get_sim_time()
while self.get_sim_time() - tstart < 15:
if not self.mode_is('LOITER'):
raise NotAchievedException("Expected to stay in loiter for >15 seconds")
# re-enable vicon
self.set_parameter("SIM_VICON_FAIL", 0)
# switch to vicon, disable GPS and wait 10sec to ensure vehicle remains in Loiter
self.set_rc(8, 1500)
self.set_parameter("GPS_TYPE", 0)
# ensure vehicle remain in Loiter for 15 seconds
tstart = self.get_sim_time()
while self.get_sim_time() - tstart < 15:
if not self.mode_is('LOITER'):
raise NotAchievedException("Expected to stay in loiter for >15 seconds")
# RTL and check vehicle arrives within 10m of home
self.set_rc(2, 1500)
self.do_RTL()
except Exception as e:
self.print_exception_caught(e)
ex = e
self.context_pop()
self.disarm_vehicle(force=True)
self.reboot_sitl()
if ex is not None:
raise ex
def fly_rtl_speed(self):
"""Test RTL Speed parameters"""
rtl_speed_ms = 7
wpnav_speed_ms = 4
wpnav_accel_mss = 3
tolerance = 0.5
self.load_mission("copter_rtl_speed.txt")
self.set_parameters({
'WPNAV_ACCEL': wpnav_accel_mss * 100,
'RTL_SPEED': rtl_speed_ms * 100,
'WPNAV_SPEED': wpnav_speed_ms * 100,
})
self.change_mode('LOITER')
self.wait_ready_to_arm()
self.arm_vehicle()
self.change_mode('AUTO')
self.set_rc(3, 1600)
self.wait_altitude(19, 25, relative=True)
self.wait_groundspeed(wpnav_speed_ms-tolerance, wpnav_speed_ms+tolerance)
self.monitor_groundspeed(wpnav_speed_ms, timeout=20)
self.change_mode('RTL')
self.wait_groundspeed(rtl_speed_ms-tolerance, rtl_speed_ms+tolerance)
self.monitor_groundspeed(rtl_speed_ms, timeout=5)
self.change_mode('AUTO')
self.wait_groundspeed(0-tolerance, 0+tolerance)
self.wait_groundspeed(wpnav_speed_ms-tolerance, wpnav_speed_ms+tolerance)
self.monitor_groundspeed(wpnav_speed_ms, tolerance=0.6, timeout=5)
self.do_RTL()
def fly_nav_delay(self):
"""Fly a simple mission that has a delay in it."""
self.load_mission("copter_nav_delay.txt")
self.set_parameter("DISARM_DELAY", 0)
self.change_mode("LOITER")
self.wait_ready_to_arm()
self.arm_vehicle()
self.change_mode("AUTO")
self.set_rc(3, 1600)
count_start = -1
count_stop = -1
tstart = self.get_sim_time()
last_mission_current_msg = 0
last_seq = None
while self.armed(): # we RTL at end of mission
now = self.get_sim_time_cached()
if now - tstart > 200:
raise AutoTestTimeoutException("Did not disarm as expected")
m = self.mav.recv_match(type='MISSION_CURRENT', blocking=True)
at_delay_item = ""
if m.seq == 3:
at_delay_item = "(At delay item)"
if count_start == -1:
count_start = now
if ((now - last_mission_current_msg) > 1 or m.seq != last_seq):
dist = None
x = self.mav.messages.get("NAV_CONTROLLER_OUTPUT", None)
if x is not None:
dist = x.wp_dist
self.progress("MISSION_CURRENT.seq=%u dist=%s %s" %
(m.seq, dist, at_delay_item))
last_mission_current_msg = self.get_sim_time_cached()
last_seq = m.seq
if m.seq > 3:
if count_stop == -1:
count_stop = now
calculated_delay = count_stop - count_start
want_delay = 59 # should reflect what's in the mission file
self.progress("Stopped for %u seconds (want >=%u seconds)" %
(calculated_delay, want_delay))
if calculated_delay < want_delay:
raise NotAchievedException("Did not delay for long enough")
def test_rangefinder(self):
ex = None
self.context_push()
self.progress("Making sure we don't ordinarily get RANGEFINDER")
m = self.mav.recv_match(type='RANGEFINDER',
blocking=True,
timeout=5)
if m is not None:
raise NotAchievedException("Received unexpected RANGEFINDER msg")
# may need to force a rotation if some other test has used the
# rangefinder...
self.progress("Ensure no RFND messages in log")
self.set_parameter("LOG_DISARMED", 1)
if self.current_onboard_log_contains_message("RFND"):
raise NotAchievedException("Found unexpected RFND message")
try:
self.set_analog_rangefinder_parameters()
self.set_parameter("RC9_OPTION", 10) # rangefinder
self.set_rc(9, 2000)
self.reboot_sitl()
self.progress("Making sure we now get RANGEFINDER messages")
m = self.mav.recv_match(type='RANGEFINDER',
blocking=True,
timeout=10)
if m is None:
raise NotAchievedException("Did not get expected RANGEFINDER msg")
self.progress("Checking RangeFinder is marked as enabled in mavlink")
m = self.mav.recv_match(type='SYS_STATUS',
blocking=True,
timeout=10)
flags = m.onboard_control_sensors_enabled
if not flags & mavutil.mavlink.MAV_SYS_STATUS_SENSOR_LASER_POSITION:
raise NotAchievedException("Laser not enabled in SYS_STATUS")
self.progress("Disabling laser using switch")
self.set_rc(9, 1000)
self.delay_sim_time(1)
self.progress("Checking RangeFinder is marked as disabled in mavlink")
m = self.mav.recv_match(type='SYS_STATUS',
blocking=True,
timeout=10)
flags = m.onboard_control_sensors_enabled
if flags & mavutil.mavlink.MAV_SYS_STATUS_SENSOR_LASER_POSITION:
raise NotAchievedException("Laser enabled in SYS_STATUS")
self.progress("Re-enabling rangefinder")
self.set_rc(9, 2000)
self.delay_sim_time(1)
m = self.mav.recv_match(type='SYS_STATUS',
blocking=True,
timeout=10)
flags = m.onboard_control_sensors_enabled
if not flags & mavutil.mavlink.MAV_SYS_STATUS_SENSOR_LASER_POSITION:
raise NotAchievedException("Laser not enabled in SYS_STATUS")
self.takeoff(10, mode="LOITER")
m_r = self.mav.recv_match(type='RANGEFINDER',
blocking=True)
m_p = self.mav.recv_match(type='GLOBAL_POSITION_INT',
blocking=True)
if abs(m_r.distance - m_p.relative_alt/1000) > 1:
raise NotAchievedException(
"rangefinder/global position int mismatch %0.2f vs %0.2f" %
(m_r.distance, m_p.relative_alt/1000))
self.land_and_disarm()
if not self.current_onboard_log_contains_message("RFND"):
raise NotAchievedException("Did not see expected RFND message")
except Exception as e:
self.print_exception_caught(e)
ex = e
self.context_pop()
self.reboot_sitl()
if ex is not None:
raise ex
def test_terrain_spline_mission(self):
self.set_parameter("TERRAIN_ENABLE", 0)
self.fly_mission("wp.txt")
def WPNAV_SPEED(self):
'''ensure resetting WPNAV_SPEED works'''
loc = self.poll_home_position()
alt = 20
loc.alt = alt
items = []
# 100 waypoints in a line, 10m apart in a northerly direction
# for i in range(1, 100):
# items.append((mavutil.mavlink.MAV_CMD_NAV_WAYPOINT, i*10, 0, alt))
# 1 waypoint a long way away
items.append((mavutil.mavlink.MAV_CMD_NAV_WAYPOINT, 2000, 0, alt),)
items.append((mavutil.mavlink.MAV_CMD_NAV_RETURN_TO_LAUNCH, 0, 0, 0))
self.upload_simple_relhome_mission(items)
start_speed_ms = self.get_parameter('WPNAV_SPEED') / 100.0
self.takeoff(20)
self.change_mode('AUTO')
self.wait_groundspeed(start_speed_ms-1, start_speed_ms+1, minimum_duration=10)
for speed_ms in 7, 8, 7, 8, 9, 10, 11, 7:
self.set_parameter('WPNAV_SPEED', speed_ms*100)
self.wait_groundspeed(speed_ms-1, speed_ms+1, minimum_duration=10)
self.do_RTL()
def WPNAV_SPEED_UP(self):
'''ensure resetting WPNAV_SPEED_UP works'''
items = []
# 1 waypoint a long way up
items.append((mavutil.mavlink.MAV_CMD_NAV_WAYPOINT, 0, 0, 20000),)
items.append((mavutil.mavlink.MAV_CMD_NAV_RETURN_TO_LAUNCH, 0, 0, 0))
self.upload_simple_relhome_mission(items)
start_speed_ms = self.get_parameter('WPNAV_SPEED_UP') / 100.0
minimum_duration = 5
self.takeoff(20)
self.change_mode('AUTO')
self.wait_climbrate(start_speed_ms-1, start_speed_ms+1, minimum_duration=minimum_duration)
for speed_ms in 7, 8, 7, 8, 6, 2:
self.set_parameter('WPNAV_SPEED_UP', speed_ms*100)
self.wait_climbrate(speed_ms-1, speed_ms+1, minimum_duration=minimum_duration)
self.do_RTL(timeout=240)
def WPNAV_SPEED_DN(self):
'''ensure resetting WPNAV_SPEED_DN works'''
items = []
# 1 waypoint a long way back down
items.append((mavutil.mavlink.MAV_CMD_NAV_WAYPOINT, 0, 0, 10),)
items.append((mavutil.mavlink.MAV_CMD_NAV_RETURN_TO_LAUNCH, 0, 0, 0))
self.upload_simple_relhome_mission(items)
minimum_duration = 5
self.takeoff(500, timeout=60)
self.change_mode('AUTO')
start_speed_ms = self.get_parameter('WPNAV_SPEED_DN') / 100.0
self.wait_climbrate(-start_speed_ms-1, -start_speed_ms+1, minimum_duration=minimum_duration)
for speed_ms in 7, 8, 7, 8, 6, 2:
self.set_parameter('WPNAV_SPEED_DN', speed_ms*100)
self.wait_climbrate(-speed_ms-1, -speed_ms+1, minimum_duration=minimum_duration)
self.do_RTL()
def fly_mission(self, filename, strict=True):
num_wp = self.load_mission(filename, strict=strict)
self.set_parameter("AUTO_OPTIONS", 3)
self.change_mode('AUTO')
self.wait_ready_to_arm()
self.arm_vehicle()
self.wait_waypoint(num_wp-1, num_wp-1)
self.wait_disarmed()
def test_surface_tracking(self):
ex = None
self.context_push()
# we must start mavproxy here as otherwise we can't get the
# terrain database tiles - this leads to random failures in
# CI!
mavproxy = self.start_mavproxy()
try:
self.set_analog_rangefinder_parameters()
self.set_parameter("RC9_OPTION", 10) # rangefinder
self.set_rc(9, 2000)
self.reboot_sitl() # needed for both rangefinder and initial position
self.assert_vehicle_location_is_at_startup_location()
self.takeoff(10, mode="LOITER")
lower_surface_pos = mavutil.location(-35.362421, 149.164534, 584, 270)
here = self.mav.location()
bearing = self.get_bearing(here, lower_surface_pos)
self.change_mode("GUIDED")
self.guided_achieve_heading(bearing)
self.change_mode("LOITER")
self.delay_sim_time(2)
m = self.mav.recv_match(type='GLOBAL_POSITION_INT', blocking=True)
orig_absolute_alt_mm = m.alt
self.progress("Original alt: absolute=%f" % orig_absolute_alt_mm)
self.progress("Flying somewhere which surface is known lower compared to takeoff point")
self.set_rc(2, 1450)
tstart = self.get_sim_time()
while True:
if self.get_sim_time() - tstart > 200:
raise NotAchievedException("Did not reach lower point")
m = self.mav.recv_match(type='GLOBAL_POSITION_INT', blocking=True)
x = mavutil.location(m.lat/1e7, m.lon/1e7, m.alt/1e3, 0)
dist = self.get_distance(x, lower_surface_pos)
delta = (orig_absolute_alt_mm - m.alt)/1000.0
self.progress("Distance: %fm abs-alt-delta: %fm" %
(dist, delta))
if dist < 15:
if delta < 0.8:
raise NotAchievedException("Did not dip in altitude as expected")
break
self.set_rc(2, 1500)
self.do_RTL()
except Exception as e:
self.print_exception_caught(e)
self.disarm_vehicle(force=True)
ex = e
self.stop_mavproxy(mavproxy)
self.context_pop()
self.reboot_sitl()
if ex is not None:
raise ex
def test_rangefinder_switchover(self):
"""test that the EKF correctly handles the switchover between baro and rangefinder"""
ex = None
self.context_push()
try:
self.set_analog_rangefinder_parameters()
self.set_parameters({
"RNGFND1_MAX_CM": 1500
})
# configure EKF to use rangefinder for altitude at low altitudes
ahrs_ekf_type = self.get_parameter("AHRS_EKF_TYPE")
if ahrs_ekf_type == 2:
self.set_parameter("EK2_RNG_USE_HGT", 70)
if ahrs_ekf_type == 3:
self.set_parameter("EK3_RNG_USE_HGT", 70)
self.reboot_sitl() # needed for both rangefinder and initial position
self.assert_vehicle_location_is_at_startup_location()
self.change_mode("LOITER")
self.wait_ready_to_arm()
self.arm_vehicle()
self.set_rc(3, 1800)
self.set_rc(2, 1200)
# wait till we get to 50m
self.wait_altitude(50, 52, True, 60)
self.change_mode("RTL")
# wait till we get to 25m
self.wait_altitude(25, 27, True, 120)
# level up
self.set_rc(2, 1500)
self.wait_altitude(14, 15, relative=True)
self.wait_rtl_complete()
except Exception as e:
self.print_exception_caught(e)
self.disarm_vehicle(force=True)
ex = e
self.context_pop()
self.reboot_sitl()
if ex is not None:
raise ex
def test_parachute(self):
self.set_rc(9, 1000)
self.set_parameters({
"CHUTE_ENABLED": 1,
"CHUTE_TYPE": 10,
"SERVO9_FUNCTION": 27,
"SIM_PARA_ENABLE": 1,
"SIM_PARA_PIN": 9,
})
self.progress("Test triggering parachute in mission")
self.load_mission("copter_parachute_mission.txt")
self.change_mode('LOITER')
self.wait_ready_to_arm()
self.arm_vehicle()
self.change_mode('AUTO')
self.set_rc(3, 1600)
self.wait_statustext('BANG', timeout=60)
self.disarm_vehicle(force=True)
self.reboot_sitl()
self.progress("Test triggering with mavlink message")
self.takeoff(20)
self.run_cmd(mavutil.mavlink.MAV_CMD_DO_PARACHUTE,
2, # release
0,
0,
0,
0,
0,
0)
self.wait_statustext('BANG', timeout=60)
self.disarm_vehicle(force=True)
self.reboot_sitl()
self.progress("Testing three-position switch")
self.set_parameter("RC9_OPTION", 23) # parachute 3pos
self.progress("Test manual triggering")
self.takeoff(20)
self.set_rc(9, 2000)
self.wait_statustext('BANG', timeout=60)
self.set_rc(9, 1000)
self.disarm_vehicle(force=True)
self.reboot_sitl()
self.context_push()
self.progress("Crashing with 3pos switch in enable position")
self.takeoff(40)
self.set_rc(9, 1500)
self.set_parameters({
"SIM_ENGINE_MUL": 0,
"SIM_ENGINE_FAIL": 1,
})
self.wait_statustext('BANG', timeout=60)
self.set_rc(9, 1000)
self.disarm_vehicle(force=True)
self.reboot_sitl()
self.context_pop()
self.progress("Crashing with 3pos switch in disable position")
loiter_alt = 10
self.takeoff(loiter_alt, mode='LOITER')
self.set_rc(9, 1100)
self.set_parameters({
"SIM_ENGINE_MUL": 0,
"SIM_ENGINE_FAIL": 1,
})
tstart = self.get_sim_time()
while self.get_sim_time_cached() < tstart + 5:
m = self.mav.recv_match(type='STATUSTEXT', blocking=True, timeout=1)
if m is None:
continue
if "BANG" in m.text:
self.set_rc(9, 1000)
self.reboot_sitl()
raise NotAchievedException("Parachute deployed when disabled")
self.set_rc(9, 1000)
self.disarm_vehicle(force=True)
self.reboot_sitl()
def test_motortest(self, timeout=60):
self.start_subtest("Testing PWM output")
pwm_in = 1300
# default frame is "+" - start motor of 2 is "B", which is
# motor 1... see
# https://ardupilot.org/copter/docs/connect-escs-and-motors.html
self.run_cmd(mavutil.mavlink.MAV_CMD_DO_MOTOR_TEST,
2, # start motor
mavutil.mavlink.MOTOR_TEST_THROTTLE_PWM,
pwm_in, # pwm-to-output
2, # timeout in seconds
2, # number of motors to output
0, # compass learning
0,
timeout=timeout)
# long timeouts here because there's a pause before we start motors
self.wait_servo_channel_value(1, pwm_in, timeout=10)
self.wait_servo_channel_value(4, pwm_in, timeout=10)
self.wait_statustext("finished motor test")
self.end_subtest("Testing PWM output")
self.start_subtest("Testing percentage output")
percentage = 90.1
# since MOT_SPIN_MIN and MOT_SPIN_MAX are not set, the RC3
# min/max are used.
expected_pwm = 1000 + (self.get_parameter("RC3_MAX") - self.get_parameter("RC3_MIN")) * percentage/100.0
self.progress("expected pwm=%f" % expected_pwm)
self.run_cmd(mavutil.mavlink.MAV_CMD_DO_MOTOR_TEST,
2, # start motor
mavutil.mavlink.MOTOR_TEST_THROTTLE_PERCENT,
percentage, # pwm-to-output
2, # timeout in seconds
2, # number of motors to output
0, # compass learning
0,
timeout=timeout)
self.wait_servo_channel_value(1, expected_pwm, timeout=10)
self.wait_servo_channel_value(4, expected_pwm, timeout=10)
self.wait_statustext("finished motor test")
self.end_subtest("Testing percentage output")
def fly_precision_landing_drivers(self):
"""Use PrecLand backends precision messages to land aircraft."""
self.context_push()
for backend in [4, 2]: # SITL, SITL-IRLOCK
ex = None
try:
self.set_parameters({
"PLND_ENABLED": 1,
"PLND_TYPE": backend,
})
self.set_analog_rangefinder_parameters()
self.set_parameter("SIM_SONAR_SCALE", 12)
start = self.mav.location()
target = start
(target.lat, target.lng) = mavextra.gps_offset(start.lat, start.lng, 4, -4)
self.progress("Setting target to %f %f" % (target.lat, target.lng))
self.set_parameters({
"SIM_PLD_ENABLE": 1,
"SIM_PLD_LAT": target.lat,
"SIM_PLD_LON": target.lng,
"SIM_PLD_HEIGHT": 0,
"SIM_PLD_ALT_LMT": 15,
"SIM_PLD_DIST_LMT": 10,
})
self.reboot_sitl()
self.progress("Waiting for location")
self.zero_throttle()
self.takeoff(10, 1800, mode="LOITER")
self.change_mode("LAND")
self.zero_throttle()
self.wait_landed_and_disarmed()
self.mav.recv_match(type='GLOBAL_POSITION_INT', blocking=True)
new_pos = self.mav.location()
delta = self.get_distance(target, new_pos)
self.progress("Landed %f metres from target position" % delta)
max_delta = 1
if delta > max_delta:
raise NotAchievedException("Did not land close enough to target position (%fm > %fm" % (delta, max_delta))
if not self.current_onboard_log_contains_message("PL"):
raise NotAchievedException("Did not see expected PL message")
except Exception as e:
self.print_exception_caught(e)
ex = e
self.reboot_sitl()
self.zero_throttle()
self.context_pop()
self.reboot_sitl()
self.progress("All done")
if ex is not None:
raise ex
def get_system_clock_utc(self, time_seconds):
# this is a copy of ArduPilot's AP_RTC function!
# separate time into ms, sec, min, hour and days but all expressed
# in milliseconds
time_ms = time_seconds * 1000
ms = time_ms % 1000
sec_ms = (time_ms % (60 * 1000)) - ms
min_ms = (time_ms % (60 * 60 * 1000)) - sec_ms - ms
hour_ms = (time_ms % (24 * 60 * 60 * 1000)) - min_ms - sec_ms - ms
# convert times as milliseconds into appropriate units
secs = sec_ms / 1000
mins = min_ms / (60 * 1000)
hours = hour_ms / (60 * 60 * 1000)
return (hours, mins, secs, 0)
def calc_delay(self, seconds, delay_for_seconds):
# delay-for-seconds has to be long enough that we're at the
# waypoint before that time. Otherwise we'll try to wait a
# day....
if delay_for_seconds >= 3600:
raise ValueError("Won't handle large delays")
(hours,
mins,
secs,
ms) = self.get_system_clock_utc(seconds)
self.progress("Now is %uh %um %us" % (hours, mins, secs))
secs += delay_for_seconds # add seventeen seconds
mins += int(secs/60)
secs %= 60
hours += int(mins / 60)
mins %= 60
if hours > 24:
raise ValueError("Way too big a delay")
self.progress("Delay until %uh %um %us" %
(hours, mins, secs))
return (hours, mins, secs, 0)
def reset_delay_item(self, seq, seconds_in_future):
frame = mavutil.mavlink.MAV_FRAME_GLOBAL_RELATIVE_ALT_INT
command = mavutil.mavlink.MAV_CMD_NAV_DELAY
# retrieve mission item and check it:
tried_set = False
hours = None
mins = None
secs = None
while True:
self.progress("Requesting item")
self.mav.mav.mission_request_send(1,
1,
seq)
st = self.mav.recv_match(type='MISSION_ITEM',
blocking=True,
timeout=1)
if st is None:
continue
print("Item: %s" % str(st))
have_match = (tried_set and
st.seq == seq and
st.command == command and
st.param2 == hours and
st.param3 == mins and
st.param4 == secs)
if have_match:
return
self.progress("Mission mismatch")
m = None
tstart = self.get_sim_time()
while True:
if self.get_sim_time_cached() - tstart > 3:
raise NotAchievedException(
"Did not receive MISSION_REQUEST")
self.mav.mav.mission_write_partial_list_send(1,
1,
seq,
seq)
m = self.mav.recv_match(type='MISSION_REQUEST',
blocking=True,
timeout=1)
if m is None:
continue
if m.seq != st.seq:
continue
break
self.progress("Sending absolute-time mission item")
# we have to change out the delay time...
now = self.mav.messages["SYSTEM_TIME"]
if now is None:
raise PreconditionFailedException("Never got SYSTEM_TIME")
if now.time_unix_usec == 0:
raise PreconditionFailedException("system time is zero")
(hours, mins, secs, ms) = self.calc_delay(now.time_unix_usec/1000000, seconds_in_future)
self.mav.mav.mission_item_send(
1, # target system
1, # target component
seq, # seq
frame, # frame
command, # command
0, # current
1, # autocontinue
0, # p1 (relative seconds)
hours, # p2
mins, # p3
secs, # p4
0, # p5
0, # p6
0) # p7
tried_set = True
ack = self.mav.recv_match(type='MISSION_ACK',
blocking=True,
timeout=1)
self.progress("Received ack: %s" % str(ack))
def fly_nav_delay_abstime(self):
"""fly a simple mission that has a delay in it"""
self.fly_nav_delay_abstime_x(87)
def fly_nav_delay_abstime_x(self, delay_for, expected_delay=None):
"""fly a simple mission that has a delay in it, expect a delay"""
if expected_delay is None:
expected_delay = delay_for
self.load_mission("copter_nav_delay.txt")
self.change_mode("LOITER")
self.wait_ready_to_arm()
delay_item_seq = 3
self.reset_delay_item(delay_item_seq, delay_for)
delay_for_seconds = delay_for
reset_at_m = self.mav.recv_match(type='SYSTEM_TIME', blocking=True)
reset_at = reset_at_m.time_unix_usec/1000000
self.arm_vehicle()
self.change_mode("AUTO")
self.set_rc(3, 1600)
count_stop = -1
tstart = self.get_sim_time()
while self.armed(): # we RTL at end of mission
now = self.get_sim_time_cached()
if now - tstart > 240:
raise AutoTestTimeoutException("Did not disarm as expected")
m = self.mav.recv_match(type='MISSION_CURRENT', blocking=True)
at_delay_item = ""
if m.seq == delay_item_seq:
at_delay_item = "(delay item)"
self.progress("MISSION_CURRENT.seq=%u %s" % (m.seq, at_delay_item))
if m.seq > delay_item_seq:
if count_stop == -1:
count_stop_m = self.mav.recv_match(type='SYSTEM_TIME',
blocking=True)
count_stop = count_stop_m.time_unix_usec/1000000
calculated_delay = count_stop - reset_at
error = abs(calculated_delay - expected_delay)
self.progress("Stopped for %u seconds (want >=%u seconds)" %
(calculated_delay, delay_for_seconds))
if error > 2:
raise NotAchievedException("delay outside expectations")
def fly_nav_takeoff_delay_abstime(self):
"""make sure taking off at a specific time works"""
self.load_mission("copter_nav_delay_takeoff.txt")
self.change_mode("LOITER")
self.wait_ready_to_arm()
delay_item_seq = 2
delay_for_seconds = 77
self.reset_delay_item(delay_item_seq, delay_for_seconds)
reset_at = self.get_sim_time_cached()
self.arm_vehicle()
self.change_mode("AUTO")
self.set_rc(3, 1600)
# should not take off for about least 77 seconds
tstart = self.get_sim_time()
took_off = False
while self.armed():
now = self.get_sim_time_cached()
if now - tstart > 200:
# timeout
break
m = self.mav.recv_match(type='MISSION_CURRENT', blocking=True)
now = self.get_sim_time_cached()
self.progress("%s" % str(m))
if m.seq > delay_item_seq:
if not took_off:
took_off = True
delta_time = now - reset_at
if abs(delta_time - delay_for_seconds) > 2:
raise NotAchievedException((
"Did not take off on time "
"measured=%f want=%f" %
(delta_time, delay_for_seconds)))
if not took_off:
raise NotAchievedException("Did not take off")
def fly_zigzag_mode(self):
'''test zigzag mode'''
# set channel 8 for zigzag savewp and recentre it
self.set_parameter("RC8_OPTION", 61)
self.takeoff(alt_min=5, mode='LOITER')
ZIGZAG = 24
j = 0
slowdown_speed = 0.3 # because Copter takes a long time to actually stop
self.start_subtest("Conduct ZigZag test for all 4 directions")
while j < 4:
self.progress("## Align heading with the run-way (j=%d)##" % j)
self.set_rc(8, 1500)
self.set_rc(4, 1420)
self.wait_heading(352-j*90)
self.set_rc(4, 1500)
self.change_mode(ZIGZAG)
self.progress("## Record Point A ##")
self.set_rc(8, 1100) # record point A
self.set_rc(1, 1700) # fly side-way for 20m
self.wait_distance(20)
self.set_rc(1, 1500)
self.wait_groundspeed(0, slowdown_speed) # wait until the copter slows down
self.progress("## Record Point A ##")
self.set_rc(8, 1500) # pilot always have to cross mid position when changing for low to high position
self.set_rc(8, 1900) # record point B
i = 1
while i < 2:
self.start_subtest("Run zigzag A->B and B->A (i=%d)" % i)
self.progress("## fly forward for 10 meter ##")
self.set_rc(2, 1300)
self.wait_distance(10)
self.set_rc(2, 1500) # re-centre pitch rc control
self.wait_groundspeed(0, slowdown_speed) # wait until the copter slows down
self.set_rc(8, 1500) # switch to mid position
self.progress("## auto execute vector BA ##")
self.set_rc(8, 1100)
self.wait_distance(17) # wait for it to finish
self.wait_groundspeed(0, slowdown_speed) # wait until the copter slows down
self.progress("## fly forward for 10 meter ##")
self.set_rc(2, 1300) # fly forward for 10 meter
self.wait_distance(10)
self.set_rc(2, 1500) # re-centre pitch rc control
self.wait_groundspeed(0, slowdown_speed) # wait until the copter slows down
self.set_rc(8, 1500) # switch to mid position
self.progress("## auto execute vector AB ##")
self.set_rc(8, 1900)
self.wait_distance(17) # wait for it to finish
self.wait_groundspeed(0, slowdown_speed) # wait until the copter slows down
i = i + 1
# test the case when pilot switch to manual control during the auto flight
self.start_subtest("test the case when pilot switch to manual control during the auto flight")
self.progress("## fly forward for 10 meter ##")
self.set_rc(2, 1300) # fly forward for 10 meter
self.wait_distance(10)
self.set_rc(2, 1500) # re-centre pitch rc control
self.wait_groundspeed(0, 0.3) # wait until the copter slows down
self.set_rc(8, 1500) # switch to mid position
self.progress("## auto execute vector BA ##")
self.set_rc(8, 1100) # switch to low position, auto execute vector BA
self.wait_distance(8) # purposely switch to manual halfway
self.set_rc(8, 1500)
self.wait_groundspeed(0, slowdown_speed) # copter should slow down here
self.progress("## Manual control to fly forward ##")
self.set_rc(2, 1300) # manual control to fly forward
self.wait_distance(8)
self.set_rc(2, 1500) # re-centre pitch rc control
self.wait_groundspeed(0, slowdown_speed) # wait until the copter slows down
self.progress("## continue vector BA ##")
self.set_rc(8, 1100) # copter should continue mission here
self.wait_distance(8) # wait for it to finish rest of BA
self.wait_groundspeed(0, slowdown_speed) # wait until the copter slows down
self.set_rc(8, 1500) # switch to mid position
self.progress("## auto execute vector AB ##")
self.set_rc(8, 1900) # switch to execute AB again
self.wait_distance(17) # wait for it to finish
self.wait_groundspeed(0, slowdown_speed) # wait until the copter slows down
self.change_mode('LOITER')
j = j + 1
self.do_RTL()
def test_setting_modes_via_modeswitch(self):
self.context_push()
ex = None
try:
fltmode_ch = 5
self.set_parameter("FLTMODE_CH", fltmode_ch)
self.set_rc(fltmode_ch, 1000) # PWM for mode1
testmodes = [("FLTMODE1", 4, "GUIDED", 1165),
("FLTMODE2", 13, "SPORT", 1295),
("FLTMODE3", 6, "RTL", 1425),
("FLTMODE4", 7, "CIRCLE", 1555),
("FLTMODE5", 1, "ACRO", 1685),
("FLTMODE6", 17, "BRAKE", 1815),
]
for mode in testmodes:
(parm, parm_value, name, pwm) = mode
self.set_parameter(parm, parm_value)
for mode in reversed(testmodes):
(parm, parm_value, name, pwm) = mode
self.set_rc(fltmode_ch, pwm)
self.wait_mode(name)
for mode in testmodes:
(parm, parm_value, name, pwm) = mode
self.set_rc(fltmode_ch, pwm)
self.wait_mode(name)
for mode in reversed(testmodes):
(parm, parm_value, name, pwm) = mode
self.set_rc(fltmode_ch, pwm)
self.wait_mode(name)
except Exception as e:
self.print_exception_caught(e)
ex = e
self.context_pop()
if ex is not None:
raise ex
def test_setting_modes_via_auxswitch(self):
self.context_push()
ex = None
try:
fltmode_ch = int(self.get_parameter("FLTMODE_CH"))
self.set_rc(fltmode_ch, 1000)
self.wait_mode("CIRCLE")
self.set_rc(9, 1000)
self.set_rc(10, 1000)
self.set_parameters({
"RC9_OPTION": 18, # land
"RC10_OPTION": 55, # guided
})
self.set_rc(9, 1900)
self.wait_mode("LAND")
self.set_rc(10, 1900)
self.wait_mode("GUIDED")
self.set_rc(10, 1000) # this re-polls the mode switch
self.wait_mode("CIRCLE")
except Exception as e:
self.print_exception_caught(e)
ex = e
self.context_pop()
if ex is not None:
raise ex
def fly_guided_stop(self,
timeout=20,
groundspeed_tolerance=0.05,
climb_tolerance=0.01):
"""stop the vehicle moving in guided mode"""
self.progress("Stopping vehicle")
tstart = self.get_sim_time()
# send a position-control command
self.mav.mav.set_position_target_local_ned_send(
0, # timestamp
1, # target system_id
1, # target component id
mavutil.mavlink.MAV_FRAME_BODY_NED,
MAV_POS_TARGET_TYPE_MASK.POS_ONLY | MAV_POS_TARGET_TYPE_MASK.LAST_BYTE, # mask specifying use-only-x-y-z
0, # x
0, # y
0, # z
0, # vx
0, # vy
0, # vz
0, # afx
0, # afy
0, # afz
0, # yaw
0, # yawrate
)
while True:
if self.get_sim_time_cached() - tstart > timeout:
raise NotAchievedException("Vehicle did not stop")
m = self.mav.recv_match(type='VFR_HUD', blocking=True)
print("%s" % str(m))
if (m.groundspeed < groundspeed_tolerance and
m.climb < climb_tolerance):
break
def fly_guided_move_global_relative_alt(self, lat, lon, alt):
startpos = self.mav.recv_match(type='GLOBAL_POSITION_INT',
blocking=True)
self.mav.mav.set_position_target_global_int_send(
0, # timestamp
1, # target system_id
1, # target component id
mavutil.mavlink.MAV_FRAME_GLOBAL_RELATIVE_ALT_INT,
MAV_POS_TARGET_TYPE_MASK.POS_ONLY, # mask specifying use-only-lat-lon-alt
lat, # lat
lon, # lon
alt, # alt
0, # vx
0, # vy
0, # vz
0, # afx
0, # afy
0, # afz
0, # yaw
0, # yawrate
)
tstart = self.get_sim_time()
while True:
if self.get_sim_time_cached() - tstart > 200:
raise NotAchievedException("Did not move far enough")
# send a position-control command
pos = self.mav.recv_match(type='GLOBAL_POSITION_INT',
blocking=True)
delta = self.get_distance_int(startpos, pos)
self.progress("delta=%f (want >10)" % delta)
if delta > 10:
break
def fly_guided_move_local(self, x, y, z_up, timeout=100):
"""move the vehicle using MAVLINK_MSG_ID_SET_POSITION_TARGET_LOCAL_NED"""
startpos = self.mav.recv_match(type='LOCAL_POSITION_NED', blocking=True)
self.progress("startpos=%s" % str(startpos))
tstart = self.get_sim_time()
# send a position-control command
self.mav.mav.set_position_target_local_ned_send(
0, # timestamp
1, # target system_id
1, # target component id
mavutil.mavlink.MAV_FRAME_LOCAL_NED,
MAV_POS_TARGET_TYPE_MASK.POS_ONLY | MAV_POS_TARGET_TYPE_MASK.LAST_BYTE, # mask specifying use-only-x-y-z
x, # x
y, # y
-z_up,# z
0, # vx
0, # vy
0, # vz
0, # afx
0, # afy
0, # afz
0, # yaw
0, # yawrate
)
while True:
if self.get_sim_time_cached() - tstart > timeout:
raise NotAchievedException("Did not reach destination")
if self.distance_to_local_position((x, y, -z_up)) < 1:
break
def test_guided_local_position_target(self, x, y, z_up):
""" Check target position being received by vehicle """
# set POSITION_TARGET_LOCAL_NED message rate using SET_MESSAGE_INTERVAL
self.progress("Setting local target in NED: (%f, %f, %f)" % (x, y, -z_up))
self.progress("Setting rate to 1 Hz")
self.set_message_rate_hz(mavutil.mavlink.MAVLINK_MSG_ID_POSITION_TARGET_LOCAL_NED, 1)
# mask specifying use only xyz
target_typemask = MAV_POS_TARGET_TYPE_MASK.POS_ONLY
# set position target
self.mav.mav.set_position_target_local_ned_send(
0, # timestamp
1, # target system_id
1, # target component id
mavutil.mavlink.MAV_FRAME_LOCAL_NED,
target_typemask | MAV_POS_TARGET_TYPE_MASK.LAST_BYTE,
x, # x
y, # y
-z_up, # z
0, # vx
0, # vy
0, # vz
0, # afx
0, # afy
0, # afz
0, # yaw
0, # yawrate
)
m = self.mav.recv_match(type='POSITION_TARGET_LOCAL_NED', blocking=True, timeout=2)
self.progress("Received local target: %s" % str(m))
if not (m.type_mask == (target_typemask | MAV_POS_TARGET_TYPE_MASK.LAST_BYTE) or m.type_mask == target_typemask):
raise NotAchievedException("Did not receive proper mask: expected=%u or %u, got=%u" %
((target_typemask | MAV_POS_TARGET_TYPE_MASK.LAST_BYTE), target_typemask, m.type_mask))
if x - m.x > 0.1:
raise NotAchievedException("Did not receive proper target position x: wanted=%f got=%f" % (x, m.x))
if y - m.y > 0.1:
raise NotAchievedException("Did not receive proper target position y: wanted=%f got=%f" % (y, m.y))
if z_up - (-m.z) > 0.1:
raise NotAchievedException("Did not receive proper target position z: wanted=%f got=%f" % (z_up, -m.z))
def test_guided_local_velocity_target(self, vx, vy, vz_up, timeout=3):
" Check local target velocity being received by vehicle "
self.progress("Setting local NED velocity target: (%f, %f, %f)" % (vx, vy, -vz_up))
self.progress("Setting POSITION_TARGET_LOCAL_NED message rate to 10Hz")
self.set_message_rate_hz(mavutil.mavlink.MAVLINK_MSG_ID_POSITION_TARGET_LOCAL_NED, 10)
# mask specifying use only vx,vy,vz & accel. Even though we don't test acceltargets below currently
# a velocity only mask returns a velocity & accel mask
target_typemask = (MAV_POS_TARGET_TYPE_MASK.POS_IGNORE |
MAV_POS_TARGET_TYPE_MASK.YAW_IGNORE | MAV_POS_TARGET_TYPE_MASK.YAW_RATE_IGNORE)
# Drain old messages and ignore the ramp-up to the required target velocity
tstart = self.get_sim_time()
while self.get_sim_time_cached() - tstart < timeout:
# send velocity-control command
self.mav.mav.set_position_target_local_ned_send(
0, # timestamp
1, # target system_id
1, # target component id
mavutil.mavlink.MAV_FRAME_LOCAL_NED,
target_typemask | MAV_POS_TARGET_TYPE_MASK.LAST_BYTE,
0, # x
0, # y
0, # z
vx, # vx
vy, # vy
-vz_up, # vz
0, # afx
0, # afy
0, # afz
0, # yaw
0, # yawrate
)
m = self.mav.recv_match(type='POSITION_TARGET_LOCAL_NED', blocking=True, timeout=1)
if m is None:
raise NotAchievedException("Did not receive any message for 1 sec")
self.progress("Received local target: %s" % str(m))
# Check the last received message
if not (m.type_mask == (target_typemask | MAV_POS_TARGET_TYPE_MASK.LAST_BYTE) or m.type_mask == target_typemask):
raise NotAchievedException("Did not receive proper mask: expected=%u or %u, got=%u" %
((target_typemask | MAV_POS_TARGET_TYPE_MASK.LAST_BYTE), target_typemask, m.type_mask))
if vx - m.vx > 0.1:
raise NotAchievedException("Did not receive proper target velocity vx: wanted=%f got=%f" % (vx, m.vx))
if vy - m.vy > 0.1:
raise NotAchievedException("Did not receive proper target velocity vy: wanted=%f got=%f" % (vy, m.vy))
if vz_up - (-m.vz) > 0.1:
raise NotAchievedException("Did not receive proper target velocity vz: wanted=%f got=%f" % (vz_up, -m.vz))
self.progress("Received proper target velocity commands")
def test_position_target_message_mode(self):
" Ensure that POSITION_TARGET_LOCAL_NED messages are sent in Guided Mode only "
self.hover()
self.change_mode('LOITER')
self.progress("Setting POSITION_TARGET_LOCAL_NED message rate to 10Hz")
self.set_message_rate_hz(mavutil.mavlink.MAVLINK_MSG_ID_POSITION_TARGET_LOCAL_NED, 10)
tstart = self.get_sim_time()
while self.get_sim_time_cached() < tstart + 5:
m = self.mav.recv_match(type='POSITION_TARGET_LOCAL_NED', blocking=True, timeout=1)
if m is None:
continue
raise NotAchievedException("Received POSITION_TARGET message in LOITER mode: %s" % str(m))
self.progress("Did not receive any POSITION_TARGET_LOCAL_NED message in LOITER mode. Success")
def earth_to_body(self, vector):
r = mavextra.rotation(self.mav.messages["ATTITUDE"]).invert()
# print("r=%s" % str(r))
return r * vector
def loiter_to_ne(self, x, y, z, timeout=40):
'''loiter to x, y, z from origin (in metres), z is *up*'''
dest_ned = rotmat.Vector3(x, y, -z)
tstart = self.get_sim_time()
success_start = -1
while True:
now = self.get_sim_time_cached()
if now - tstart > timeout:
raise NotAchievedException("Did not loiter to ne!")
m_pos = self.mav.recv_match(type='LOCAL_POSITION_NED',
blocking=True)
pos_ned = rotmat.Vector3(m_pos.x, m_pos.y, m_pos.z)
# print("dest_ned=%s" % str(dest_ned))
# print("pos_ned=%s" % str(pos_ned))
delta_ef = dest_ned - pos_ned
# print("delta_ef=%s" % str(delta_ef))
# determine if we've successfully navigated to close to
# where we should be:
dist = math.sqrt(delta_ef.x * delta_ef.x + delta_ef.y * delta_ef.y)
dist_max = 0.15
self.progress("dist=%f want <%f" % (dist, dist_max))
if dist < dist_max:
# success! We've gotten within our target distance
if success_start == -1:
success_start = now
elif now - success_start > 10:
self.progress("Yay!")
break
else:
success_start = -1
delta_bf = self.earth_to_body(delta_ef)
# print("delta_bf=%s" % str(delta_bf))
angle_x = math.atan2(delta_bf.y, delta_bf.z)
angle_y = -math.atan2(delta_bf.x, delta_bf.z)
distance = math.sqrt(delta_bf.x * delta_bf.x +
delta_bf.y * delta_bf.y +
delta_bf.z * delta_bf.z)
# att = self.mav.messages["ATTITUDE"]
# print("r=%f p=%f y=%f" % (math.degrees(att.roll), math.degrees(att.pitch), math.degrees(att.yaw)))
# print("angle_x=%s angle_y=%s" % (str(math.degrees(angle_x)), str(math.degrees(angle_y))))
# print("distance=%s" % str(distance))
self.mav.mav.landing_target_send(
0, # time_usec
1, # target_num
mavutil.mavlink.MAV_FRAME_GLOBAL, # frame; AP ignores
angle_x, # angle x (radians)
angle_y, # angle y (radians)
distance, # distance to target
0.01, # size of target in radians, X-axis
0.01 # size of target in radians, Y-axis
)
def fly_payload_place_mission(self):
"""Test payload placing in auto."""
self.context_push()
ex = None
try:
self.set_analog_rangefinder_parameters()
self.set_parameters({
"GRIP_ENABLE": 1,
"GRIP_TYPE": 1,
"SIM_GRPS_ENABLE": 1,
"SIM_GRPS_PIN": 8,
"SERVO8_FUNCTION": 28,
"RC9_OPTION": 19,
})
self.reboot_sitl()
self.set_rc(9, 2000)
# load the mission:
self.load_mission("copter_payload_place.txt")
self.progress("Waiting for location")
self.mav.location()
self.zero_throttle()
self.change_mode('STABILIZE')
self.wait_ready_to_arm()
self.arm_vehicle()
self.change_mode('AUTO')
self.set_rc(3, 1500)
self.wait_text("Gripper load releas", timeout=90)
self.wait_disarmed()
except Exception as e:
self.print_exception_caught(e)
ex = e
self.context_pop()
self.reboot_sitl()
self.progress("All done")
if ex is not None:
raise ex
def fly_guided_change_submode(self):
""""Ensure we can move around in guided after a takeoff command."""
'''start by disabling GCS failsafe, otherwise we immediately disarm
due to (apparently) not receiving traffic from the GCS for
too long. This is probably a function of --speedup'''
self.set_parameters({
"FS_GCS_ENABLE": 0,
"DISARM_DELAY": 0, # until traffic problems are fixed
})
self.change_mode("GUIDED")
self.wait_ready_to_arm()
self.arm_vehicle()
self.user_takeoff(alt_min=10)
self.start_subtest("yaw through absolute angles using MAV_CMD_CONDITION_YAW")
self.guided_achieve_heading(45)
self.guided_achieve_heading(135)
self.start_subtest("move the vehicle using set_position_target_global_int")
# the following numbers are 5-degree-latitude and 5-degrees
# longitude - just so that we start to really move a lot.
self.fly_guided_move_global_relative_alt(5, 5, 10)
self.start_subtest("move the vehicle using MAVLINK_MSG_ID_SET_POSITION_TARGET_LOCAL_NED")
self.fly_guided_stop(groundspeed_tolerance=0.1)
self.fly_guided_move_local(5, 5, 10)
self.start_subtest("Check target position received by vehicle using SET_MESSAGE_INTERVAL")
self.test_guided_local_position_target(5, 5, 10)
self.test_guided_local_velocity_target(2, 2, 1)
self.test_position_target_message_mode()
self.do_RTL()
def test_gripper_mission(self):
self.context_push()
ex = None
try:
self.load_mission("copter-gripper-mission.txt")
self.change_mode('LOITER')
self.wait_ready_to_arm()
self.assert_vehicle_location_is_at_startup_location()
self.arm_vehicle()
self.change_mode('AUTO')
self.set_rc(3, 1500)
self.wait_statustext("Gripper Grabbed", timeout=60)
self.wait_statustext("Gripper Released", timeout=60)
except Exception as e:
self.print_exception_caught(e)
self.change_mode('LAND')
ex = e
self.context_pop()
self.wait_disarmed()
if ex is not None:
raise ex
def test_spline_last_waypoint(self):
self.context_push()
ex = None
try:
self.load_mission("copter-spline-last-waypoint.txt")
self.change_mode('LOITER')
self.wait_ready_to_arm()
self.arm_vehicle()
self.change_mode('AUTO')
self.set_rc(3, 1500)
self.wait_altitude(10, 3000, relative=True)
except Exception as e:
self.print_exception_caught(e)
ex = e
self.context_pop()
self.do_RTL()
self.wait_disarmed()
if ex is not None:
raise ex
def fly_manual_throttle_mode_change(self):
self.set_parameter("FS_GCS_ENABLE", 0) # avoid GUIDED instant disarm
self.change_mode("STABILIZE")
self.wait_ready_to_arm()
self.arm_vehicle()
self.change_mode("ACRO")
self.change_mode("STABILIZE")
self.change_mode("GUIDED")
self.set_rc(3, 1700)
self.watch_altitude_maintained(-1, 0.2) # should not take off in guided
self.run_cmd_do_set_mode(
"ACRO",
want_result=mavutil.mavlink.MAV_RESULT_FAILED)
self.run_cmd_do_set_mode(
"STABILIZE",
want_result=mavutil.mavlink.MAV_RESULT_FAILED)
self.run_cmd_do_set_mode(
"DRIFT",
want_result=mavutil.mavlink.MAV_RESULT_FAILED)
self.progress("Check setting an invalid mode")
self.run_cmd(
mavutil.mavlink.MAV_CMD_DO_SET_MODE,
mavutil.mavlink.MAV_MODE_FLAG_CUSTOM_MODE_ENABLED,
126,
0,
0,
0,
0,
0,
want_result=mavutil.mavlink.MAV_RESULT_FAILED,
timeout=1
)
self.set_rc(3, 1000)
self.run_cmd_do_set_mode("ACRO")
self.wait_disarmed()
def test_mount_pitch(self, despitch, despitch_tolerance, mount_mode, timeout=10, hold=0):
tstart = self.get_sim_time()
success_start = 0
while True:
now = self.get_sim_time_cached()
if now - tstart > timeout:
raise NotAchievedException("Mount pitch not achieved")
m = self.mav.recv_match(type='MOUNT_STATUS',
blocking=True,
timeout=5)
if m.mount_mode != mount_mode:
raise NotAchievedException("MAV_MOUNT_MODE Not: %s" % (mount_mode))
# self.progress("pitch=%f roll=%f yaw=%f" %
# (m.pointing_a, m.pointing_b, m.pointing_c))
mount_pitch = m.pointing_a/100.0 # centidegrees to degrees
if abs(despitch - mount_pitch) > despitch_tolerance:
self.progress("Mount pitch incorrect: got=%f want=%f (+/- %f)" %
(mount_pitch, despitch, despitch_tolerance))
success_start = 0
continue
self.progress("Mount pitch correct: %f degrees == %f" %
(mount_pitch, despitch))
if success_start == 0:
success_start = now
continue
if now - success_start > hold:
self.progress("Mount pitch achieved")
return
def do_pitch(self, pitch):
'''pitch aircraft in guided/angle mode'''
self.mav.mav.set_attitude_target_send(
0, # time_boot_ms
1, # target sysid
1, # target compid
0, # bitmask of things to ignore
mavextra.euler_to_quat([0, math.radians(pitch), 0]), # att
0, # roll rate (rad/s)
0, # pitch rate (rad/s)
0, # yaw rate (rad/s)
0.5) # thrust, 0 to 1, translated to a climb/descent rate
def setup_servo_mount(self, roll_servo=5, pitch_servo=6, yaw_servo=7):
'''configure a rpy servo mount; caller responsible for required rebooting'''
self.progress("Setting up servo mount")
self.set_parameters({
"MNT_TYPE": 1,
"SERVO%u_FUNCTION" % roll_servo: 8, # roll
"SERVO%u_FUNCTION" % pitch_servo: 7, # pitch
"SERVO%u_FUNCTION" % yaw_servo: 6, # yaw
})
def test_mount(self):
ex = None
self.context_push()
old_srcSystem = self.mav.mav.srcSystem
self.mav.mav.srcSystem = 250
self.set_parameter("DISARM_DELAY", 0)
try:
'''start by disabling GCS failsafe, otherwise we immediately disarm
due to (apparently) not receiving traffic from the GCS for
too long. This is probably a function of --speedup'''
self.set_parameter("FS_GCS_ENABLE", 0)
self.setup_servo_mount()
self.reboot_sitl() # to handle MNT_TYPE changing
# make sure we're getting mount status and gimbal reports
self.mav.recv_match(type='MOUNT_STATUS',
blocking=True,
timeout=5)
self.mav.recv_match(type='GIMBAL_REPORT',
blocking=True,
timeout=5)
# test pitch isn't stabilising:
m = self.mav.recv_match(type='MOUNT_STATUS',
blocking=True,
timeout=5)
if m.mount_mode != mavutil.mavlink.MAV_MOUNT_MODE_RC_TARGETING:
raise NotAchievedException("Mount_Mode: Default Not MAV_MOUNT_MODE_RC_TARGETING")
if m.pointing_a != 0 or m.pointing_b != 0 or m.pointing_c != 0:
raise NotAchievedException("Mount stabilising when not requested")
self.change_mode('GUIDED')
self.wait_ready_to_arm()
self.arm_vehicle()
self.user_takeoff()
despitch = 10
despitch_tolerance = 3
self.progress("Pitching vehicle")
self.do_pitch(despitch) # will time out!
self.wait_pitch(despitch, despitch_tolerance)
# check we haven't modified:
m = self.mav.recv_match(type='MOUNT_STATUS',
blocking=True,
timeout=5)
if m.mount_mode != mavutil.mavlink.MAV_MOUNT_MODE_RC_TARGETING:
raise NotAchievedException("Mount_Mode: changed when not requested")
if m.pointing_a != 0 or m.pointing_b != 0 or m.pointing_c != 0:
raise NotAchievedException("Mount stabilising when not requested")
self.progress("Enable pitch stabilization using MOUNT_CONFIGURE")
self.mav.mav.mount_configure_send(
1, # target system
1, # target component
mavutil.mavlink.MAV_MOUNT_MODE_RC_TARGETING,
0, # stab-roll
1, # stab-pitch
0)
self.do_pitch(despitch)
self.test_mount_pitch(-despitch, 1, mavutil.mavlink.MAV_MOUNT_MODE_RC_TARGETING)
self.progress("Disable pitch using MAV_CMD_DO_MOUNT_CONFIGURE")
self.do_pitch(despitch)
self.run_cmd(mavutil.mavlink.MAV_CMD_DO_MOUNT_CONFIGURE,
mavutil.mavlink.MAV_MOUNT_MODE_RC_TARGETING,
0,
0,
0,
0,
0,
0,
)
self.test_mount_pitch(0, 0, mavutil.mavlink.MAV_MOUNT_MODE_RC_TARGETING)
self.progress("Point somewhere using MOUNT_CONTROL (ANGLE)")
self.do_pitch(despitch)
self.run_cmd(mavutil.mavlink.MAV_CMD_DO_MOUNT_CONFIGURE,
mavutil.mavlink.MAV_MOUNT_MODE_MAVLINK_TARGETING,
0,
0,
0,
0,
0,
0,
)
self.mav.mav.mount_control_send(
1, # target system
1, # target component
20 * 100, # pitch
20 * 100, # roll (centidegrees)
0, # yaw
0 # save position
)
self.test_mount_pitch(20, 1, mavutil.mavlink.MAV_MOUNT_MODE_MAVLINK_TARGETING)
self.progress("Point somewhere using MOUNT_CONTROL (GPS)")
self.do_pitch(despitch)
self.run_cmd(mavutil.mavlink.MAV_CMD_DO_MOUNT_CONFIGURE,
mavutil.mavlink.MAV_MOUNT_MODE_GPS_POINT,
0,
0,
0,
0,
0,
0,
)
# Delay here to allow the attitude to command to timeout and level out the copter a bit
self.delay_sim_time(3)
start = self.mav.location()
self.progress("start=%s" % str(start))
(t_lat, t_lon) = mavextra.gps_offset(start.lat, start.lng, 10, 20)
t_alt = 0
self.progress("loc %f %f %f" % (start.lat, start.lng, start.alt))
self.progress("targetting %f %f %f" % (t_lat, t_lon, t_alt))
self.do_pitch(despitch)
self.mav.mav.mount_control_send(
1, # target system
1, # target component
int(t_lat * 1e7), # lat
int(t_lon * 1e7), # lon
t_alt * 100, # alt
0 # save position
)
self.test_mount_pitch(-52, 5, mavutil.mavlink.MAV_MOUNT_MODE_GPS_POINT)
# now test RC targetting
self.progress("Testing mount RC targetting")
# this is a one-off; ArduCopter *will* time out this directive!
self.progress("Levelling aircraft")
self.mav.mav.set_attitude_target_send(
0, # time_boot_ms
1, # target sysid
1, # target compid
0, # bitmask of things to ignore
mavextra.euler_to_quat([0, 0, 0]), # att
0, # roll rate (rad/s)
0, # pitch rate (rad/s)
0, # yaw rate (rad/s)
0.5) # thrust, 0 to 1, translated to a climb/descent rate
self.run_cmd(mavutil.mavlink.MAV_CMD_DO_MOUNT_CONFIGURE,
mavutil.mavlink.MAV_MOUNT_MODE_RC_TARGETING,
0,
0,
0,
0,
0,
0,
)
try:
self.context_push()
self.set_parameters({
'MNT_RC_IN_ROLL': 11,
'MNT_RC_IN_TILT': 12,
'MNT_RC_IN_PAN': 13,
})
self.progress("Testing RC angular control")
# default RC min=1100 max=1900
self.set_rc_from_map({
11: 1500,
12: 1500,
13: 1500,
})
self.test_mount_pitch(0, 1, mavutil.mavlink.MAV_MOUNT_MODE_RC_TARGETING)
self.progress("Testing RC input down 1/4 of its range in the output, should be down 1/4 range in output")
rc12_in = 1400
rc12_min = 1100 # default
rc12_max = 1900 # default
angmin_tilt = -45.0 # default
angmax_tilt = 45.0 # default
expected_pitch = (float(rc12_in-rc12_min)/float(rc12_max-rc12_min) * (angmax_tilt-angmin_tilt)) + angmin_tilt
self.progress("expected mount pitch: %f" % expected_pitch)
if expected_pitch != -11.25:
raise NotAchievedException("Calculation wrong - defaults changed?!")
self.set_rc(12, rc12_in)
self.test_mount_pitch(-11.25, 0.01, mavutil.mavlink.MAV_MOUNT_MODE_RC_TARGETING)
self.set_rc(12, 1800)
self.test_mount_pitch(33.75, 0.01, mavutil.mavlink.MAV_MOUNT_MODE_RC_TARGETING)
self.set_rc_from_map({
11: 1500,
12: 1500,
13: 1500,
})
try:
self.progress(
"Issue https://discuss.ardupilot.org/t/"
"gimbal-limits-with-storm32-backend-mavlink-not-applied-correctly/51438"
)
self.context_push()
self.set_parameters({
"RC12_MIN": 1000,
"RC12_MAX": 2000,
"MNT_ANGMIN_TIL": -9000,
"MNT_ANGMAX_TIL": 1000,
})
self.set_rc(12, 1000)
self.test_mount_pitch(-90.00, 0.01, mavutil.mavlink.MAV_MOUNT_MODE_RC_TARGETING)
self.set_rc(12, 2000)
self.test_mount_pitch(10.00, 0.01, mavutil.mavlink.MAV_MOUNT_MODE_RC_TARGETING)
self.set_rc(12, 1500)
self.test_mount_pitch(-40.00, 0.01, mavutil.mavlink.MAV_MOUNT_MODE_RC_TARGETING)
finally:
self.context_pop()
self.set_rc(12, 1500)
self.progress("Testing RC rate control")
self.set_parameter('MNT_JSTICK_SPD', 10)
self.test_mount_pitch(0, 1, mavutil.mavlink.MAV_MOUNT_MODE_RC_TARGETING)
self.set_rc(12, 1300)
self.test_mount_pitch(-5, 1, mavutil.mavlink.MAV_MOUNT_MODE_RC_TARGETING)
self.test_mount_pitch(-10, 1, mavutil.mavlink.MAV_MOUNT_MODE_RC_TARGETING)
self.test_mount_pitch(-15, 1, mavutil.mavlink.MAV_MOUNT_MODE_RC_TARGETING)
self.test_mount_pitch(-20, 1, mavutil.mavlink.MAV_MOUNT_MODE_RC_TARGETING)
self.set_rc(12, 1700)
self.test_mount_pitch(-15, 1, mavutil.mavlink.MAV_MOUNT_MODE_RC_TARGETING)
self.test_mount_pitch(-10, 1, mavutil.mavlink.MAV_MOUNT_MODE_RC_TARGETING)
self.test_mount_pitch(-5, 1, mavutil.mavlink.MAV_MOUNT_MODE_RC_TARGETING)
self.test_mount_pitch(0, 1, mavutil.mavlink.MAV_MOUNT_MODE_RC_TARGETING)
self.test_mount_pitch(5, 1, mavutil.mavlink.MAV_MOUNT_MODE_RC_TARGETING)
self.progress("Reverting to angle mode")
self.set_parameter('MNT_JSTICK_SPD', 0)
self.set_rc(12, 1500)
self.test_mount_pitch(0, 0.1, mavutil.mavlink.MAV_MOUNT_MODE_RC_TARGETING)
self.context_pop()
except Exception as e:
self.print_exception_caught(e)
self.context_pop()
raise e
self.progress("Testing mount ROI behaviour")
self.drain_mav_unparsed()
self.test_mount_pitch(0, 0.1, mavutil.mavlink.MAV_MOUNT_MODE_RC_TARGETING)
start = self.mav.location()
self.progress("start=%s" % str(start))
(roi_lat, roi_lon) = mavextra.gps_offset(start.lat,
start.lng,
10,
20)
roi_alt = 0
self.progress("Using MAV_CMD_DO_SET_ROI_LOCATION")
self.run_cmd(mavutil.mavlink.MAV_CMD_DO_SET_ROI_LOCATION,
0,
0,
0,
0,
roi_lat,
roi_lon,
roi_alt,
)
self.test_mount_pitch(-52, 5, mavutil.mavlink.MAV_MOUNT_MODE_GPS_POINT)
start = self.mav.location()
(roi_lat, roi_lon) = mavextra.gps_offset(start.lat,
start.lng,
-100,
-200)
roi_alt = 0
self.progress("Using MAV_CMD_DO_SET_ROI")
self.run_cmd(mavutil.mavlink.MAV_CMD_DO_SET_ROI,
0,
0,
0,
0,
roi_lat,
roi_lon,
roi_alt,
)
self.test_mount_pitch(-7.5, 1, mavutil.mavlink.MAV_MOUNT_MODE_GPS_POINT)
start = self.mav.location()
(roi_lat, roi_lon) = mavextra.gps_offset(start.lat,
start.lng,
-100,
-200)
roi_alt = 0
self.progress("Using MAV_CMD_DO_SET_ROI (COMMAND_INT)")
self.run_cmd_int(
mavutil.mavlink.MAV_CMD_DO_SET_ROI,
0,
0,
0,
0,
int(roi_lat*1e7),
int(roi_lon*1e7),
roi_alt,
frame=mavutil.mavlink.MAV_FRAME_GLOBAL_RELATIVE_ALT_INT,
)
self.test_mount_pitch(-7.5, 1, mavutil.mavlink.MAV_MOUNT_MODE_GPS_POINT)
self.progress("Using MAV_CMD_DO_SET_ROI (COMMAND_INT), absolute-alt-frame")
# this is pointing essentially straight down
self.run_cmd_int(
mavutil.mavlink.MAV_CMD_DO_SET_ROI,
0,
0,
0,
0,
int(roi_lat*1e7),
int(roi_lon*1e7),
roi_alt,
frame=mavutil.mavlink.MAV_FRAME_GLOBAL,
)
self.test_mount_pitch(-70, 1, mavutil.mavlink.MAV_MOUNT_MODE_GPS_POINT, hold=2)
self.run_cmd(mavutil.mavlink.MAV_CMD_DO_MOUNT_CONFIGURE,
mavutil.mavlink.MAV_MOUNT_MODE_NEUTRAL,
0,
0,
0,
0,
0,
0,
)
self.test_mount_pitch(0, 0.1, mavutil.mavlink.MAV_MOUNT_MODE_NEUTRAL)
self.progress("Testing mount roi-sysid behaviour")
self.test_mount_pitch(0, 0.1, mavutil.mavlink.MAV_MOUNT_MODE_NEUTRAL)
start = self.mav.location()
self.progress("start=%s" % str(start))
(roi_lat, roi_lon) = mavextra.gps_offset(start.lat,
start.lng,
10,
20)
roi_alt = 0
self.progress("Using MAV_CMD_DO_SET_ROI_SYSID")
self.run_cmd(mavutil.mavlink.MAV_CMD_DO_SET_ROI_SYSID,
250,
0,
0,
0,
0,
0,
0,
)
self.mav.mav.global_position_int_send(
0, # time boot ms
int(roi_lat * 1e7),
int(roi_lon * 1e7),
0 * 1000, # mm alt amsl
0 * 1000, # relalt mm UP!
0, # vx
0, # vy
0, # vz
0 # heading
)
self.test_mount_pitch(-89, 5, mavutil.mavlink.MAV_MOUNT_MODE_SYSID_TARGET, hold=2)
self.mav.mav.global_position_int_send(
0, # time boot ms
int(roi_lat * 1e7),
int(roi_lon * 1e7),
670 * 1000, # mm alt amsl
100 * 1000, # mm UP!
0, # vx
0, # vy
0, # vz
0 # heading
)
self.test_mount_pitch(68, 5, mavutil.mavlink.MAV_MOUNT_MODE_SYSID_TARGET, hold=2)
self.run_cmd(mavutil.mavlink.MAV_CMD_DO_MOUNT_CONFIGURE,
mavutil.mavlink.MAV_MOUNT_MODE_NEUTRAL,
0,
0,
0,
0,
0,
0,
)
self.test_mount_pitch(0, 0.1, mavutil.mavlink.MAV_MOUNT_MODE_NEUTRAL)
except Exception as e:
self.print_exception_caught(e)
ex = e
self.context_pop()
self.mav.mav.srcSystem = old_srcSystem
self.disarm_vehicle(force=True)
self.reboot_sitl() # to handle MNT_TYPE changing
if ex is not None:
raise ex
def MountYawVehicleForMountROI(self):
self.context_push()
self.set_parameter("SYSID_MYGCS", self.mav.source_system)
yaw_servo = 7
self.setup_servo_mount(yaw_servo=yaw_servo)
self.reboot_sitl() # to handle MNT_TYPE changing
self.progress("checking ArduCopter yaw-aircraft-for-roi")
ex = None
try:
self.takeoff(20, mode='GUIDED')
m = self.mav.recv_match(type='VFR_HUD', blocking=True)
self.progress("current heading %u" % m.heading)
self.set_parameter("SERVO%u_FUNCTION" % yaw_servo, 0) # yaw
self.progress("Waiting for check_servo_map to do its job")
self.delay_sim_time(5)
self.progress("Pointing North")
self.guided_achieve_heading(0)
self.delay_sim_time(5)
start = self.mav.location()
(roi_lat, roi_lon) = mavextra.gps_offset(start.lat,
start.lng,
-100,
-100)
roi_alt = 0
self.progress("Using MAV_CMD_DO_SET_ROI")
self.run_cmd(mavutil.mavlink.MAV_CMD_DO_SET_ROI,
0,
0,
0,
0,
roi_lat,
roi_lon,
roi_alt,
)
self.progress("Waiting for vehicle to point towards ROI")
self.wait_heading(225, timeout=600, minimum_duration=2)
# the following numbers are 1-degree-latitude and
# 0-degrees longitude - just so that we start to
# really move a lot.
there = mavutil.location(1, 0, 0, 0)
self.progress("Starting to move")
self.mav.mav.set_position_target_global_int_send(
0, # timestamp
1, # target system_id
1, # target component id
mavutil.mavlink.MAV_FRAME_GLOBAL_RELATIVE_ALT_INT,
MAV_POS_TARGET_TYPE_MASK.POS_ONLY | MAV_POS_TARGET_TYPE_MASK.LAST_BYTE, # mask specifying use-only-lat-lon-alt
there.lat, # lat
there.lng, # lon
there.alt, # alt
0, # vx
0, # vy
0, # vz
0, # afx
0, # afy
0, # afz
0, # yaw
0, # yawrate
)
self.progress("Starting to move changes the target")
bearing = self.bearing_to(there)
self.wait_heading(bearing, timeout=600, minimum_duration=2)
self.run_cmd(mavutil.mavlink.MAV_CMD_DO_SET_ROI,
0,
0,
0,
0,
roi_lat,
roi_lon,
roi_alt,
)
self.progress("Wait for vehicle to point sssse due to moving")
self.wait_heading(170, timeout=600, minimum_duration=1)
self.do_RTL()
except Exception as e:
self.print_exception_caught(e)
ex = e
self.context_pop()
if ex is not None:
raise ex
def fly_throw_mode(self):
# test boomerang mode:
self.progress("Throwing vehicle away")
self.set_parameters({
"THROW_NEXTMODE": 6,
"SIM_SHOVE_Z": -30,
"SIM_SHOVE_X": -20,
})
self.change_mode('THROW')
self.wait_ready_to_arm()
self.arm_vehicle()
try:
self.set_parameter("SIM_SHOVE_TIME", 500)
except ValueError:
# the shove resets this to zero
pass
tstart = self.get_sim_time()
self.wait_mode('RTL')
max_good_tdelta = 15
tdelta = self.get_sim_time() - tstart
self.progress("Vehicle in RTL")
self.wait_rtl_complete()
self.progress("Vehicle disarmed")
if tdelta > max_good_tdelta:
raise NotAchievedException("Took too long to enter RTL: %fs > %fs" %
(tdelta, max_good_tdelta))
self.progress("Vehicle returned")
def hover_and_check_matched_frequency_with_fft(self, dblevel=-15, minhz=200, maxhz=300, peakhz=None, reverse=None):
# find a motor peak
self.takeoff(10, mode="ALT_HOLD")
hover_time = 15
tstart = self.get_sim_time()
self.progress("Hovering for %u seconds" % hover_time)
while self.get_sim_time_cached() < tstart + hover_time:
self.mav.recv_match(type='ATTITUDE', blocking=True)
vfr_hud = self.mav.recv_match(type='VFR_HUD', blocking=True)
tend = self.get_sim_time()
self.do_RTL()
psd = self.mavfft_fttd(1, 0, tstart * 1.0e6, tend * 1.0e6)
# batch sampler defaults give 1024 fft and sample rate of 1kz so roughly 1hz/bin
freq = psd["F"][numpy.argmax(psd["X"][minhz:maxhz]) + minhz] * (1000. / 1024.)
peakdb = numpy.amax(psd["X"][minhz:maxhz])
if peakdb < dblevel or (peakhz is not None and abs(freq - peakhz) / peakhz > 0.05):
if reverse is not None:
self.progress("Did not detect a motor peak, found %fHz at %fdB" % (freq, peakdb))
else:
raise NotAchievedException("Did not detect a motor peak, found %fHz at %fdB" % (freq, peakdb))
else:
if reverse is not None:
raise NotAchievedException(
"Detected motor peak at %fHz, throttle %f%%, %fdB" %
(freq, vfr_hud.throttle, peakdb))
else:
self.progress("Detected motor peak at %fHz, throttle %f%%, %fdB" % (freq, vfr_hud.throttle, peakdb))
return freq, vfr_hud, peakdb
def fly_dynamic_notches(self):
"""Use dynamic harmonic notch to control motor noise."""
self.progress("Flying with dynamic notches")
self.context_push()
ex = None
try:
self.set_parameters({
"AHRS_EKF_TYPE": 10,
"INS_LOG_BAT_MASK": 3,
"INS_LOG_BAT_OPT": 0,
"INS_GYRO_FILTER": 100, # set the gyro filter high so we can observe behaviour
"LOG_BITMASK": 958,
"LOG_DISARMED": 0,
"SIM_VIB_MOT_MAX": 350,
"SIM_GYR1_RND": 20,
})
self.reboot_sitl()
self.takeoff(10, mode="ALT_HOLD")
# find a motor peak
freq, vfr_hud, peakdb = self.hover_and_check_matched_frequency_with_fft(-15, 200, 300)
# now add a dynamic notch and check that the peak is squashed
self.set_parameters({
"INS_LOG_BAT_OPT": 2,
"INS_HNTCH_ENABLE": 1,
"INS_HNTCH_FREQ": freq,
"INS_HNTCH_REF": vfr_hud.throttle/100.,
"INS_HNTCH_HMNCS": 5, # first and third harmonic
"INS_HNTCH_ATT": 50,
"INS_HNTCH_BW": freq/2,
})
self.reboot_sitl()
freq, vfr_hud, peakdb1 = self.hover_and_check_matched_frequency_with_fft(-10, 20, 350, reverse=True)
# now add double dynamic notches and check that the peak is squashed
self.set_parameter("INS_HNTCH_OPTS", 1)
self.reboot_sitl()
freq, vfr_hud, peakdb2 = self.hover_and_check_matched_frequency_with_fft(-15, 20, 350, reverse=True)
# double-notch should do better, but check for within 5%
if peakdb2 * 1.05 > peakdb1:
raise NotAchievedException(
"Double-notch peak was higher than single-notch peak %fdB > %fdB" %
(peakdb2, peakdb1))
except Exception as e:
self.print_exception_caught(e)
ex = e
self.context_pop()
if ex is not None:
raise ex
def fly_esc_telemetry_notches(self):
"""Use dynamic harmonic notch to control motor noise via ESC telemetry."""
self.progress("Flying with ESC telemetry driven dynamic notches")
self.set_rc_default()
self.set_parameters({
"AHRS_EKF_TYPE": 10,
"INS_LOG_BAT_MASK": 3,
"INS_LOG_BAT_OPT": 0,
"INS_GYRO_FILTER": 100, # set gyro filter high so we can observe behaviour
"LOG_BITMASK": 958,
"LOG_DISARMED": 0,
"SIM_VIB_MOT_MAX": 350,
"SIM_GYR1_RND": 20,
"SIM_ESC_TELEM": 1,
})
self.reboot_sitl()
self.takeoff(10, mode="ALT_HOLD")
# find a motor peak
freq, vfr_hud, peakdb = self.hover_and_check_matched_frequency_with_fft(-15, 200, 300)
# now add a dynamic notch and check that the peak is squashed
self.set_parameters({
"INS_LOG_BAT_OPT": 2,
"INS_HNTCH_ENABLE": 1,
"INS_HNTCH_FREQ": 80,
"INS_HNTCH_REF": 1.0,
"INS_HNTCH_HMNCS": 5, # first and third harmonic
"INS_HNTCH_ATT": 50,
"INS_HNTCH_BW": 40,
"INS_HNTCH_MODE": 3,
})
self.reboot_sitl()
freq, vfr_hud, peakdb1 = self.hover_and_check_matched_frequency_with_fft(-10, 20, 350, reverse=True)
# now add notch-per motor and check that the peak is squashed
self.set_parameter("INS_HNTCH_OPTS", 2)
self.reboot_sitl()
freq, vfr_hud, peakdb2 = self.hover_and_check_matched_frequency_with_fft(-15, 20, 350, reverse=True)
# notch-per-motor should do better, but check for within 5%
if peakdb2 * 1.05 > peakdb1:
raise NotAchievedException(
"Notch-per-motor peak was higher than single-notch peak %fdB > %fdB" %
(peakdb2, peakdb1))
# Now do it again for an octacopter
self.context_push()
ex = None
try:
self.progress("Flying Octacopter with ESC telemetry driven dynamic notches")
self.set_parameter("INS_HNTCH_OPTS", 0)
self.customise_SITL_commandline(
[],
defaults_filepath=','.join(self.model_defaults_filepath("octa")),
model="octa"
)
freq, vfr_hud, peakdb1 = self.hover_and_check_matched_frequency_with_fft(-10, 20, 350, reverse=True)
# now add notch-per motor and check that the peak is squashed
self.set_parameter("INS_HNTCH_HMNCS", 1)
self.set_parameter("INS_HNTCH_OPTS", 2)
self.reboot_sitl()
freq, vfr_hud, peakdb2 = self.hover_and_check_matched_frequency_with_fft(-15, 20, 350, reverse=True)
# notch-per-motor should do better, but check for within 5%
if peakdb2 * 1.05 > peakdb1:
raise NotAchievedException(
"Notch-per-motor peak was higher than single-notch peak %fdB > %fdB" %
(peakdb2, peakdb1))
except Exception as e:
self.print_exception_caught(e)
ex = e
self.context_pop()
self.reboot_sitl()
if ex is not None:
raise ex
def hover_and_check_matched_frequency(self, dblevel=-15, minhz=200, maxhz=300, fftLength=32, peakhz=None):
# find a motor peak
self.takeoff(10, mode="ALT_HOLD")
hover_time = 15
tstart = self.get_sim_time()
self.progress("Hovering for %u seconds" % hover_time)
while self.get_sim_time_cached() < tstart + hover_time:
self.mav.recv_match(type='ATTITUDE', blocking=True)
vfr_hud = self.mav.recv_match(type='VFR_HUD', blocking=True)
tend = self.get_sim_time()
self.do_RTL()
psd = self.mavfft_fttd(1, 0, tstart * 1.0e6, tend * 1.0e6)
# batch sampler defaults give 1024 fft and sample rate of 1kz so roughly 1hz/bin
scale = 1000. / 1024.
sminhz = int(minhz * scale)
smaxhz = int(maxhz * scale)
freq = psd["F"][numpy.argmax(psd["X"][sminhz:smaxhz]) + sminhz]
peakdb = numpy.amax(psd["X"][sminhz:smaxhz])
if peakdb < dblevel:
raise NotAchievedException("Did not detect a motor peak, found %fHz at %fdB" % (freq, peakdb))
elif peakhz is not None and abs(freq - peakhz) / peakhz > 0.05:
raise NotAchievedException("Did not detect a motor peak at %fHz, found %fHz at %fdB" % (peakhz, freq, peakdb))
else:
self.progress("Detected motor peak at %fHz, throttle %f%%, %fdB" % (freq, vfr_hud.throttle, peakdb))
# we have a peak make sure that the FFT detected something close
# logging is at 10Hz
mlog = self.dfreader_for_current_onboard_log()
# accuracy is determined by sample rate and fft length, given our use of quinn we could probably use half of this
freqDelta = 1000. / fftLength
pkAvg = freq
nmessages = 1
m = mlog.recv_match(
type='FTN1',
blocking=False,
condition="FTN1.TimeUS>%u and FTN1.TimeUS<%u" % (tstart * 1.0e6, tend * 1.0e6)
)
freqs = []
while m is not None:
nmessages = nmessages + 1
freqs.append(m.PkAvg)
m = mlog.recv_match(
type='FTN1',
blocking=False,
condition="FTN1.TimeUS>%u and FTN1.TimeUS<%u" % (tstart * 1.0e6, tend * 1.0e6)
)
# peak within resolution of FFT length
pkAvg = numpy.median(numpy.asarray(freqs))
self.progress("Detected motor peak at %fHz processing %d messages" % (pkAvg, nmessages))
# peak within 5%
if abs(pkAvg - freq) > freqDelta:
raise NotAchievedException("FFT did not detect a motor peak at %f, found %f, wanted %f" % (dblevel, pkAvg, freq))
return freq
def fly_gyro_fft_harmonic(self):
"""Use dynamic harmonic notch to control motor noise with harmonic matching of the first harmonic."""
# basic gyro sample rate test
self.progress("Flying with gyro FFT harmonic - Gyro sample rate")
self.context_push()
ex = None
# we are dealing with probabalistic scenarios involving threads, have two bites at the cherry
try:
self.start_subtest("Hover to calculate approximate hover frequency")
# magic tridge EKF type that dramatically speeds up the test
self.set_parameters({
"AHRS_EKF_TYPE": 10,
"EK2_ENABLE": 0,
"EK3_ENABLE": 0,
"INS_LOG_BAT_MASK": 3,
"INS_LOG_BAT_OPT": 0,
"INS_GYRO_FILTER": 100,
"INS_FAST_SAMPLE": 0,
"LOG_BITMASK": 958,
"LOG_DISARMED": 0,
"SIM_DRIFT_SPEED": 0,
"SIM_DRIFT_TIME": 0,
"FFT_THR_REF": self.get_parameter("MOT_THST_HOVER"),
"SIM_GYR1_RND": 20, # enable a noisy gyro
})
# motor peak enabling FFT will also enable the arming
# check, self-testing the functionality
self.set_parameters({
"FFT_ENABLE": 1,
"FFT_MINHZ": 50,
"FFT_MAXHZ": 450,
"FFT_SNR_REF": 10,
})
# Step 1: inject actual motor noise and use the FFT to track it
self.set_parameters({
"SIM_VIB_MOT_MAX": 250, # gives a motor peak at about 175Hz
"FFT_WINDOW_SIZE": 64,
"FFT_WINDOW_OLAP": 0.75,
})
self.reboot_sitl()
freq = self.hover_and_check_matched_frequency(-15, 100, 250, 64)
# Step 2: add a second harmonic and check the first is still tracked
self.start_subtest("Add a fixed frequency harmonic at twice the hover frequency "
"and check the right harmonic is found")
self.set_parameters({
"SIM_VIB_FREQ_X": freq * 2,
"SIM_VIB_FREQ_Y": freq * 2,
"SIM_VIB_FREQ_Z": freq * 2,
"SIM_VIB_MOT_MULT": 0.25, # halve the motor noise so that the higher harmonic dominates
})
self.reboot_sitl()
self.hover_and_check_matched_frequency(-15, 100, 250, 64, None)
# Step 3: switch harmonics mid flight and check for tracking
self.start_subtest("Switch harmonics mid flight and check the right harmonic is found")
self.set_parameter("FFT_HMNC_PEAK", 0)
self.reboot_sitl()
self.takeoff(10, mode="ALT_HOLD")
hover_time = 10
tstart = self.get_sim_time()
self.progress("Hovering for %u seconds" % hover_time)
while self.get_sim_time_cached() < tstart + hover_time:
self.mav.recv_match(type='ATTITUDE', blocking=True)
vfr_hud = self.mav.recv_match(type='VFR_HUD', blocking=True)
self.set_parameter("SIM_VIB_MOT_MULT", 5.0)
self.progress("Hovering for %u seconds" % hover_time)
while self.get_sim_time_cached() < tstart + hover_time:
self.mav.recv_match(type='ATTITUDE', blocking=True)
vfr_hud = self.mav.recv_match(type='VFR_HUD', blocking=True)
tend = self.get_sim_time()
self.do_RTL()
mlog = self.dfreader_for_current_onboard_log()
m = mlog.recv_match(
type='FTN1',
blocking=False,
condition="FTN1.TimeUS>%u and FTN1.TimeUS<%u" % (tstart * 1.0e6, tend * 1.0e6))
freqs = []
while m is not None:
freqs.append(m.PkAvg)
m = mlog.recv_match(
type='FTN1',
blocking=False,
condition="FTN1.TimeUS>%u and FTN1.TimeUS<%u" % (tstart * 1.0e6, tend * 1.0e6))
# peak within resolution of FFT length, the highest energy peak switched but our detection should not
pkAvg = numpy.median(numpy.asarray(freqs))
freqDelta = 1000. / self.get_parameter("FFT_WINDOW_SIZE")
if abs(pkAvg - freq) > freqDelta:
raise NotAchievedException("FFT did not detect a harmonic motor peak, found %f, wanted %f" % (pkAvg, freq))
# Step 4: dynamic harmonic
self.start_subtest("Enable dynamic harmonics and make sure both frequency peaks are attenuated")
# find a motor peak
freq, vfr_hud, peakdb = self.hover_and_check_matched_frequency_with_fft(-15, 100, 350)
# now add a dynamic notch and check that the peak is squashed
self.set_parameters({
"INS_LOG_BAT_OPT": 2,
"INS_HNTCH_ENABLE": 1,
"INS_HNTCH_HMNCS": 1,
"INS_HNTCH_MODE": 4,
"INS_HNTCH_FREQ": freq,
"INS_HNTCH_REF": vfr_hud.throttle/100.0,
"INS_HNTCH_ATT": 100,
"INS_HNTCH_BW": freq/2,
"INS_HNTCH_OPTS": 3,
})
self.reboot_sitl()
# 5db is far in excess of the attenuation that the double dynamic-harmonic notch is able
# to provide (-7dB on average), but without the notch the peak is around 20dB so still a safe test
self.hover_and_check_matched_frequency_with_fft(5, 100, 350, reverse=True)
self.set_parameters({
"SIM_VIB_FREQ_X": 0,
"SIM_VIB_FREQ_Y": 0,
"SIM_VIB_FREQ_Z": 0,
"SIM_VIB_MOT_MULT": 1.0,
})
# prevent update parameters from messing with the settings when we pop the context
self.set_parameter("FFT_ENABLE", 0)
self.reboot_sitl()
except Exception as e:
self.print_exception_caught(e)
ex = e
self.context_pop()
# need a final reboot because weird things happen to your
# vehicle state when switching back from EKF type 10!
self.reboot_sitl()
if ex is not None:
raise ex
def fly_gyro_fft(self):
"""Use dynamic harmonic notch to control motor noise."""
# basic gyro sample rate test
self.progress("Flying with gyro FFT - Gyro sample rate")
self.context_push()
ex = None
try:
# magic tridge EKF type that dramatically speeds up the test
self.set_parameters({
"AHRS_EKF_TYPE": 10,
"EK2_ENABLE": 0,
"EK3_ENABLE": 0,
"INS_LOG_BAT_MASK": 3,
"INS_LOG_BAT_OPT": 0,
"INS_GYRO_FILTER": 100,
"INS_FAST_SAMPLE": 0,
"LOG_BITMASK": 958,
"LOG_DISARMED": 0,
"SIM_DRIFT_SPEED": 0,
"SIM_DRIFT_TIME": 0,
"SIM_GYR1_RND": 20, # enable a noisy motor peak
})
# enabling FFT will also enable the arming check,
# self-testing the functionality
self.set_parameters({
"FFT_ENABLE": 1,
"FFT_MINHZ": 50,
"FFT_MAXHZ": 450,
"FFT_SNR_REF": 10,
"FFT_WINDOW_SIZE": 128,
"FFT_WINDOW_OLAP": 0.75,
"FFT_SAMPLE_MODE": 0,
})
# Step 1: inject a very precise noise peak at 250hz and make sure the in-flight fft
# can detect it really accurately. For a 128 FFT the frequency resolution is 8Hz so
# a 250Hz peak should be detectable within 5%
self.start_subtest("Inject noise at 250Hz and check the FFT can find the noise")
self.set_parameters({
"SIM_VIB_FREQ_X": 250,
"SIM_VIB_FREQ_Y": 250,
"SIM_VIB_FREQ_Z": 250,
})
self.reboot_sitl()
# find a motor peak
self.hover_and_check_matched_frequency(-15, 100, 350, 128, 250)
# Step 1b: run the same test with an FFT length of 256 which is needed to flush out a
# whole host of bugs related to uint8_t. This also tests very accurately the frequency resolution
self.set_parameter("FFT_WINDOW_SIZE", 256)
self.start_subtest("Inject noise at 250Hz and check the FFT can find the noise")
self.reboot_sitl()
# find a motor peak
self.hover_and_check_matched_frequency(-15, 100, 350, 256, 250)
self.set_parameter("FFT_WINDOW_SIZE", 128)
# Step 2: inject actual motor noise and use the standard length FFT to track it
self.start_subtest("Hover and check that the FFT can find the motor noise")
self.set_parameters({
"SIM_VIB_FREQ_X": 0,
"SIM_VIB_FREQ_Y": 0,
"SIM_VIB_FREQ_Z": 0,
"SIM_VIB_MOT_MAX": 250, # gives a motor peak at about 175Hz
"FFT_WINDOW_SIZE": 32,
"FFT_WINDOW_OLAP": 0.5,
})
self.reboot_sitl()
freq = self.hover_and_check_matched_frequency(-15, 100, 250, 32)
self.set_parameter("SIM_VIB_MOT_MULT", 1.)
# Step 3: add a FFT dynamic notch and check that the peak is squashed
self.start_subtest("Add a dynamic notch, hover and check that the noise peak is now gone")
self.set_parameters({
"INS_LOG_BAT_OPT": 2,
"INS_HNTCH_ENABLE": 1,
"INS_HNTCH_FREQ": freq,
"INS_HNTCH_REF": 1.0,
"INS_HNTCH_ATT": 50,
"INS_HNTCH_BW": freq/2,
"INS_HNTCH_MODE": 4,
})
self.reboot_sitl()
self.takeoff(10, mode="ALT_HOLD")
hover_time = 15
self.progress("Hovering for %u seconds" % hover_time)
tstart = self.get_sim_time()
while self.get_sim_time_cached() < tstart + hover_time:
self.mav.recv_match(type='ATTITUDE', blocking=True)
tend = self.get_sim_time()
# fly fast forrest!
self.set_rc(3, 1900)
self.set_rc(2, 1200)
self.wait_groundspeed(5, 1000)
self.set_rc(3, 1500)
self.set_rc(2, 1500)
self.do_RTL()
psd = self.mavfft_fttd(1, 0, tstart * 1.0e6, tend * 1.0e6)
# batch sampler defaults give 1024 fft and sample rate of 1kz so roughly 1hz/bin
scale = 1000. / 1024.
sminhz = int(100 * scale)
smaxhz = int(350 * scale)
freq = psd["F"][numpy.argmax(psd["X"][sminhz:smaxhz]) + sminhz]
peakdb = numpy.amax(psd["X"][sminhz:smaxhz])
if peakdb < 0:
self.progress("Did not detect a motor peak, found %fHz at %fdB" % (freq, peakdb))
else:
raise NotAchievedException("Detected %fHz motor peak at %fdB" % (freq, peakdb))
# Step 4: loop sample rate test with larger window
self.start_subtest("Hover and check that the FFT can find the motor noise when running at fast loop rate")
# we are limited to half the loop rate for frequency detection
self.set_parameters({
"FFT_MAXHZ": 185,
"INS_LOG_BAT_OPT": 0,
"SIM_VIB_MOT_MAX": 220,
"FFT_WINDOW_SIZE": 64,
"FFT_WINDOW_OLAP": 0.75,
"FFT_SAMPLE_MODE": 1,
})
self.reboot_sitl()
self.takeoff(10, mode="ALT_HOLD")
self.progress("Hovering for %u seconds" % hover_time)
tstart = self.get_sim_time()
while self.get_sim_time_cached() < tstart + hover_time:
self.mav.recv_match(type='ATTITUDE', blocking=True)
tend = self.get_sim_time()
self.do_RTL()
# prevent update parameters from messing with the settings when we pop the context
self.set_parameter("FFT_ENABLE", 0)
self.reboot_sitl()
except Exception as e:
self.print_exception_caught(e)
ex = e
self.context_pop()
# must reboot after we move away from EKF type 10 to EKF2 or EKF3
self.reboot_sitl()
if ex is not None:
raise ex
def fly_brake_mode(self):
# test brake mode
self.progress("Testing brake mode")
self.takeoff(10, mode="LOITER")
self.progress("Ensuring RC inputs have no effect in brake mode")
self.change_mode("STABILIZE")
self.set_rc(3, 1500)
self.set_rc(2, 1200)
self.wait_groundspeed(5, 1000)
self.change_mode("BRAKE")
self.wait_groundspeed(0, 1)
self.set_rc(2, 1500)
self.do_RTL()
self.progress("Ran brake mode")
def fly_guided_move_to(self, destination, timeout=30):
'''move to mavutil.location location; absolute altitude'''
tstart = self.get_sim_time()
self.mav.mav.set_position_target_global_int_send(
0, # timestamp
1, # target system_id
1, # target component id
mavutil.mavlink.MAV_FRAME_GLOBAL_INT,
MAV_POS_TARGET_TYPE_MASK.POS_ONLY | MAV_POS_TARGET_TYPE_MASK.LAST_BYTE, # mask specifying use-only-lat-lon-alt
int(destination.lat * 1e7), # lat
int(destination.lng * 1e7), # lon
destination.alt, # alt
0, # vx
0, # vy
0, # vz
0, # afx
0, # afy
0, # afz
0, # yaw
0, # yawrate
)
while True:
if self.get_sim_time() - tstart > timeout:
raise NotAchievedException()
delta = self.get_distance(self.mav.location(), destination)
self.progress("delta=%f (want <1)" % delta)
if delta < 1:
break
def test_altitude_types(self):
'''start by disabling GCS failsafe, otherwise we immediately disarm
due to (apparently) not receiving traffic from the GCS for
too long. This is probably a function of --speedup'''
'''this test flies the vehicle somewhere lower than were it started.
It then disarms. It then arms, which should reset home to the
new, lower altitude. This delta should be outside 1m but
within a few metres of the old one.
'''
# we must start mavproxy here as otherwise we can't get the
# terrain database tiles - this leads to random failures in
# CI!
mavproxy = self.start_mavproxy()
self.set_parameter("FS_GCS_ENABLE", 0)
self.change_mode('GUIDED')
self.wait_ready_to_arm()
self.arm_vehicle()
m = self.mav.recv_match(type='GLOBAL_POSITION_INT', blocking=True)
max_initial_home_alt_m = 500
if m.relative_alt > max_initial_home_alt_m:
raise NotAchievedException("Initial home alt too high (%fm > %fm)" %
(m.relative_alt*1000, max_initial_home_alt_m*1000))
orig_home_offset_mm = m.alt - m.relative_alt
self.user_takeoff(5)
self.progress("Flying to low position")
current_alt = self.mav.location().alt
# 10m delta low_position = mavutil.location(-35.358273, 149.169165, current_alt, 0)
low_position = mavutil.location(-35.36200016, 149.16415599, current_alt, 0)
self.fly_guided_move_to(low_position, timeout=240)
self.change_mode('LAND')
# expecting home to change when disarmed
self.wait_landed_and_disarmed()
# wait a while for home to move (it shouldn't):
self.delay_sim_time(10)
m = self.mav.recv_match(type='GLOBAL_POSITION_INT', blocking=True)
new_home_offset_mm = m.alt - m.relative_alt
home_offset_delta_mm = orig_home_offset_mm - new_home_offset_mm
self.progress("new home offset: %f delta=%f" %
(new_home_offset_mm, home_offset_delta_mm))
self.progress("gpi=%s" % str(m))
max_home_offset_delta_mm = 10
if home_offset_delta_mm > max_home_offset_delta_mm:
raise NotAchievedException("Large home offset delta: want<%f got=%f" %
(max_home_offset_delta_mm, home_offset_delta_mm))
self.progress("Ensuring home moves when we arm")
self.change_mode('GUIDED')
self.wait_ready_to_arm()
self.arm_vehicle()
m = self.mav.recv_match(type='GLOBAL_POSITION_INT', blocking=True)
post_arming_home_offset_mm = m.alt - m.relative_alt
self.progress("post-arming home offset: %f" % (post_arming_home_offset_mm))
self.progress("gpi=%s" % str(m))
min_post_arming_home_offset_delta_mm = -2500
max_post_arming_home_offset_delta_mm = -4000
delta_between_original_home_alt_offset_and_new_home_alt_offset_mm = post_arming_home_offset_mm - orig_home_offset_mm
self.progress("delta=%f-%f=%f" % (
post_arming_home_offset_mm,
orig_home_offset_mm,
delta_between_original_home_alt_offset_and_new_home_alt_offset_mm))
self.progress("Home moved %fm vertically" % (delta_between_original_home_alt_offset_and_new_home_alt_offset_mm/1000.0))
if delta_between_original_home_alt_offset_and_new_home_alt_offset_mm > min_post_arming_home_offset_delta_mm:
raise NotAchievedException(
"Home did not move vertically on arming: want<=%f got=%f" %
(min_post_arming_home_offset_delta_mm, delta_between_original_home_alt_offset_and_new_home_alt_offset_mm))
if delta_between_original_home_alt_offset_and_new_home_alt_offset_mm < max_post_arming_home_offset_delta_mm:
raise NotAchievedException(
"Home moved too far vertically on arming: want>=%f got=%f" %
(max_post_arming_home_offset_delta_mm, delta_between_original_home_alt_offset_and_new_home_alt_offset_mm))
self.wait_disarmed()
self.stop_mavproxy(mavproxy)
def fly_precision_companion(self):
"""Use Companion PrecLand backend precision messages to loiter."""
self.context_push()
ex = None
try:
self.set_parameter("PLND_ENABLED", 1)
# enable companion backend:
self.set_parameter("PLND_TYPE", 1)
self.set_analog_rangefinder_parameters()
# set up a channel switch to enable precision loiter:
self.set_parameter("RC7_OPTION", 39)
self.reboot_sitl()
self.progress("Waiting for location")
self.mav.location()
self.zero_throttle()
self.change_mode('STABILIZE')
self.wait_ready_to_arm()
# we should be doing precision loiter at this point
start = self.mav.recv_match(type='LOCAL_POSITION_NED',
blocking=True)
self.arm_vehicle()
self.set_rc(3, 1800)
alt_min = 10
self.wait_altitude(alt_min,
(alt_min + 5),
relative=True)
self.set_rc(3, 1500)
# move away a little
self.set_rc(2, 1550)
self.wait_distance(5, accuracy=1)
self.set_rc(2, 1500)
self.change_mode('LOITER')
# turn precision loiter on:
self.set_rc(7, 2000)
# try to drag aircraft to a position 5 metres north-east-east:
self.loiter_to_ne(start.x + 5, start.y + 10, start.z + 10)
self.loiter_to_ne(start.x + 5, start.y - 10, start.z + 10)
except Exception as e:
self.print_exception_caught(e)
ex = e
self.context_pop()
self.zero_throttle()
self.disarm_vehicle(force=True)
self.reboot_sitl()
self.progress("All done")
if ex is not None:
raise ex
def loiter_requires_position(self):
# ensure we can't switch to LOITER without position
self.progress("Ensure we can't enter LOITER without position")
self.context_push()
self.set_parameters({
"GPS_TYPE": 2,
"SIM_GPS_DISABLE": 1,
})
# if there is no GPS at all then we must direct EK3 to not use
# it at all. Otherwise it will never initialise, as it wants
# to calculate the lag and size its delay buffers accordingly.
self.set_parameters({
"EK3_SRC1_POSXY": 0,
"EK3_SRC1_VELZ": 0,
"EK3_SRC1_VELXY": 0,
})
self.reboot_sitl()
# check for expected EKF flags
ahrs_ekf_type = self.get_parameter("AHRS_EKF_TYPE")
expected_ekf_flags = (mavutil.mavlink.ESTIMATOR_ATTITUDE |
mavutil.mavlink.ESTIMATOR_VELOCITY_VERT |
mavutil.mavlink.ESTIMATOR_POS_VERT_ABS |
mavutil.mavlink.ESTIMATOR_CONST_POS_MODE)
if ahrs_ekf_type == 2:
expected_ekf_flags = expected_ekf_flags | mavutil.mavlink.ESTIMATOR_PRED_POS_HORIZ_REL
self.wait_ekf_flags(expected_ekf_flags, 0, timeout=120)
# arm in Stabilize and attempt to switch to Loiter
self.change_mode('STABILIZE')
self.arm_vehicle()
self.context_collect('STATUSTEXT')
self.run_cmd_do_set_mode(
"LOITER",
want_result=mavutil.mavlink.MAV_RESULT_FAILED)
self.wait_statustext("requires position", check_context=True)
self.disarm_vehicle()
self.context_pop()
self.reboot_sitl()
def test_arm_feature(self):
self.loiter_requires_position()
super(AutoTestCopter, self).test_arm_feature()
def test_parameter_checks(self):
self.test_parameter_checks_poscontrol("PSC")
def fly_poshold_takeoff(self):
"""ensure vehicle stays put until it is ready to fly"""
self.context_push()
ex = None
try:
self.set_parameter("PILOT_TKOFF_ALT", 700)
self.change_mode('POSHOLD')
self.set_rc(3, 1000)
self.wait_ready_to_arm()
self.arm_vehicle()
self.delay_sim_time(2)
# check we are still on the ground...
m = self.mav.recv_match(type='GLOBAL_POSITION_INT', blocking=True)
if abs(m.relative_alt) > 100:
raise NotAchievedException("Took off prematurely")
self.progress("Pushing throttle up")
self.set_rc(3, 1710)
self.delay_sim_time(0.5)
self.progress("Bringing back to hover throttle")
self.set_rc(3, 1500)
# make sure we haven't already reached alt:
m = self.mav.recv_match(type='GLOBAL_POSITION_INT', blocking=True)
max_initial_alt = 2000
if abs(m.relative_alt) > max_initial_alt:
raise NotAchievedException("Took off too fast (%f > %f" %
(abs(m.relative_alt), max_initial_alt))
self.progress("Monitoring takeoff-to-alt")
self.wait_altitude(6.9, 8, relative=True)
self.progress("Making sure we stop at our takeoff altitude")
tstart = self.get_sim_time()
while self.get_sim_time() - tstart < 5:
m = self.mav.recv_match(type='GLOBAL_POSITION_INT', blocking=True)
delta = abs(7000 - m.relative_alt)
self.progress("alt=%f delta=%f" % (m.relative_alt/1000,
delta/1000))
if delta > 1000:
raise NotAchievedException("Failed to maintain takeoff alt")
self.progress("takeoff OK")
except Exception as e:
self.print_exception_caught(e)
ex = e
self.land_and_disarm()
self.set_rc(8, 1000)
self.context_pop()
if ex is not None:
raise ex
def initial_mode(self):
return "STABILIZE"
def initial_mode_switch_mode(self):
return "STABILIZE"
def default_mode(self):
return "STABILIZE"
def rc_defaults(self):
ret = super(AutoTestCopter, self).rc_defaults()
ret[3] = 1000
ret[5] = 1800 # mode switch
return ret
def test_manual_control(self):
'''test manual_control mavlink message'''
self.set_parameter("SYSID_MYGCS", self.mav.source_system)
self.change_mode('STABILIZE')
self.takeoff(10)
tstart = self.get_sim_time_cached()
want_pitch_degrees = -12
while True:
if self.get_sim_time_cached() - tstart > 10:
raise AutoTestTimeoutException("Did not reach pitch")
self.progress("Sending pitch-forward")
self.mav.mav.manual_control_send(
1, # target system
500, # x (pitch)
32767, # y (roll)
32767, # z (thrust)
32767, # r (yaw)
0) # button mask
m = self.mav.recv_match(type='ATTITUDE', blocking=True, timeout=1)
print("m=%s" % str(m))
if m is None:
continue
p = math.degrees(m.pitch)
self.progress("pitch=%f want<=%f" % (p, want_pitch_degrees))
if p <= want_pitch_degrees:
break
self.mav.mav.manual_control_send(
1, # target system
32767, # x (pitch)
32767, # y (roll)
32767, # z (thrust)
32767, # r (yaw)
0) # button mask
self.do_RTL()
def check_avoidance_corners(self):
self.takeoff(10, mode="LOITER")
self.set_rc(2, 1400)
west_loc = mavutil.location(-35.363007,
149.164911,
0,
0)
self.wait_location(west_loc, accuracy=6)
north_loc = mavutil.location(-35.362908,
149.165051,
0,
0)
self.reach_heading_manual(0)
self.wait_location(north_loc, accuracy=6, timeout=200)
self.reach_heading_manual(90)
east_loc = mavutil.location(-35.363013,
149.165194,
0,
0)
self.wait_location(east_loc, accuracy=6)
self.reach_heading_manual(225)
self.wait_location(west_loc, accuracy=6, timeout=200)
self.set_rc(2, 1500)
self.do_RTL()
def OBSTACLE_DISTANCE_3D_test_angle(self, angle):
now = self.get_sim_time_cached()
distance = 15
right = distance * math.sin(math.radians(angle))
front = distance * math.cos(math.radians(angle))
down = 0
expected_distance_cm = distance * 100
# expected orientation
expected_orientation = int((angle+22.5)/45) % 8
self.progress("Angle %f expected orient %u" %
(angle, expected_orientation))
tstart = self.get_sim_time()
last_send = 0
while True:
now = self.get_sim_time_cached()
if now - tstart > 10:
raise NotAchievedException("Did not get correct angle back")
if now - last_send > 0.1:
self.progress("ang=%f sending front=%f right=%f" %
(angle, front, right))
self.mav.mav.obstacle_distance_3d_send(
int(now*1000), # time_boot_ms
mavutil.mavlink.MAV_DISTANCE_SENSOR_LASER,
mavutil.mavlink.MAV_FRAME_BODY_FRD,
65535,
front, # x (m)
right, # y (m)
down, # z (m)
0, # min_distance (m)
20 # max_distance (m)
)
last_send = now
m = self.mav.recv_match(type="DISTANCE_SENSOR",
blocking=True,
timeout=1)
if m is None:
continue
# self.progress("Got (%s)" % str(m))
if m.orientation != expected_orientation:
# self.progress("Wrong orientation (want=%u got=%u)" %
# (expected_orientation, m.orientation))
continue
if abs(m.current_distance - expected_distance_cm) > 1:
# self.progress("Wrong distance (want=%f got=%f)" %
# (expected_distance_cm, m.current_distance))
continue
self.progress("distance-at-angle good")
break
def OBSTACLE_DISTANCE_3D(self):
self.context_push()
ex = None
try:
self.set_parameters({
"SERIAL5_PROTOCOL": 1,
"PRX_TYPE": 2,
})
self.reboot_sitl()
for angle in range(0, 360):
self.OBSTACLE_DISTANCE_3D_test_angle(angle)
except Exception as e:
self.print_exception_caught(e)
ex = e
self.context_pop()
self.disarm_vehicle(force=True)
self.reboot_sitl()
if ex is not None:
raise ex
def fly_proximity_avoidance_test_corners(self):
self.start_subtest("Corners")
self.context_push()
ex = None
try:
self.load_fence("copter-avoidance-fence.txt")
self.set_parameters({
"FENCE_ENABLE": 1,
"PRX_TYPE": 10,
"RC10_OPTION": 40, # proximity-enable
})
self.reboot_sitl()
self.progress("Enabling proximity")
self.set_rc(10, 2000)
self.check_avoidance_corners()
except Exception as e:
self.print_exception_caught(e)
ex = e
self.context_pop()
self.clear_fence()
self.disarm_vehicle(force=True)
self.reboot_sitl()
if ex is not None:
raise ex
def fly_proximity_avoidance_test_alt_no_avoid(self):
self.start_subtest("Alt-no-avoid")
self.context_push()
ex = None
try:
self.set_parameters({
"PRX_TYPE": 2,
"AVOID_ALT_MIN": 10,
})
self.set_analog_rangefinder_parameters()
self.reboot_sitl()
tstart = self.get_sim_time()
self.change_mode('LOITER')
while True:
if self.armed():
break
if self.get_sim_time_cached() - tstart > 60:
raise AutoTestTimeoutException("Did not arm")
self.mav.mav.distance_sensor_send(
0, # time_boot_ms
10, # min_distance cm
500, # max_distance cm
400, # current_distance cm
mavutil.mavlink.MAV_DISTANCE_SENSOR_LASER, # type
26, # id
mavutil.mavlink.MAV_SENSOR_ROTATION_NONE, # orientation
255 # covariance
)
self.send_cmd(mavutil.mavlink.MAV_CMD_COMPONENT_ARM_DISARM,
1, # ARM
0,
0,
0,
0,
0,
0)
self.wait_heartbeat()
self.takeoff(15, mode='LOITER')
self.progress("Poking vehicle; should avoid")
def shove(a, b):
self.mav.mav.distance_sensor_send(
0, # time_boot_ms
10, # min_distance cm
500, # max_distance cm
20, # current_distance cm
mavutil.mavlink.MAV_DISTANCE_SENSOR_LASER, # type
21, # id
mavutil.mavlink.MAV_SENSOR_ROTATION_NONE, # orientation
255 # covariance
)
self.wait_speed_vector_bf(
Vector3(-0.4, 0.0, 0.0),
timeout=10,
called_function=shove,
)
self.change_alt(5)
tstart = self.get_sim_time()
while True:
if self.get_sim_time_cached() - tstart > 10:
break
vel = self.get_body_frame_velocity()
if vel.length() > 0.3:
raise NotAchievedException("Moved too much (%s)" %
(str(vel),))
shove(None, None)
except Exception as e:
self.progress("Caught exception: %s" %
self.get_exception_stacktrace(e))
ex = e
self.context_pop()
self.disarm_vehicle(force=True)
self.reboot_sitl()
if ex is not None:
raise ex
def fly_proximity_avoidance_test(self):
self.fly_proximity_avoidance_test_alt_no_avoid()
self.fly_proximity_avoidance_test_corners()
def fly_fence_avoidance_test(self):
self.context_push()
ex = None
try:
self.load_fence("copter-avoidance-fence.txt")
self.set_parameter("FENCE_ENABLE", 1)
self.check_avoidance_corners()
except Exception as e:
self.print_exception_caught(e)
ex = e
self.context_pop()
self.clear_fence()
self.disarm_vehicle(force=True)
if ex is not None:
raise ex
def global_position_int_for_location(self, loc, time_boot, heading=0):
return self.mav.mav.global_position_int_encode(
int(time_boot * 1000), # time_boot_ms
int(loc.lat * 1e7),
int(loc.lng * 1e7),
int(loc.alt * 1000), # alt in mm
20, # relative alt - urp.
vx=0,
vy=0,
vz=0,
hdg=heading
)
def fly_follow_mode(self):
foll_ofs_x = 30 # metres
self.set_parameters({
"FOLL_ENABLE": 1,
"FOLL_SYSID": self.mav.source_system,
"FOLL_OFS_X": -foll_ofs_x,
"FOLL_OFS_TYPE": 1, # relative to other vehicle heading
})
self.takeoff(10, mode="LOITER")
self.set_parameter("SIM_SPEEDUP", 1)
self.change_mode("FOLLOW")
new_loc = self.mav.location()
new_loc_offset_n = 20
new_loc_offset_e = 30
self.location_offset_ne(new_loc, new_loc_offset_n, new_loc_offset_e)
self.progress("new_loc: %s" % str(new_loc))
heading = 0
if self.mavproxy is not None:
self.mavproxy.send("map icon %f %f greenplane %f\n" %
(new_loc.lat, new_loc.lng, heading))
expected_loc = copy.copy(new_loc)
self.location_offset_ne(expected_loc, -foll_ofs_x, 0)
if self.mavproxy is not None:
self.mavproxy.send("map icon %f %f hoop\n" %
(expected_loc.lat, expected_loc.lng))
self.progress("expected_loc: %s" % str(expected_loc))
last_sent = 0
tstart = self.get_sim_time()
while True:
now = self.get_sim_time_cached()
if now - tstart > 60:
raise NotAchievedException("Did not FOLLOW")
if now - last_sent > 0.5:
gpi = self.global_position_int_for_location(new_loc,
now,
heading=heading)
gpi.pack(self.mav.mav)
self.mav.mav.send(gpi)
self.mav.recv_match(type='GLOBAL_POSITION_INT', blocking=True)
pos = self.mav.location()
delta = self.get_distance(expected_loc, pos)
max_delta = 3
self.progress("position delta=%f (want <%f)" % (delta, max_delta))
if delta < max_delta:
break
self.do_RTL()
def get_global_position_int(self, timeout=30):
tstart = self.get_sim_time()
while True:
if self.get_sim_time_cached() - tstart > timeout:
raise NotAchievedException("Did not get good global_position_int")
m = self.mav.recv_match(type='GLOBAL_POSITION_INT', blocking=True, timeout=1)
self.progress("GPI: %s" % str(m))
if m is None:
continue
if m.lat != 0 or m.lon != 0:
return m
def fly_beacon_position(self):
self.reboot_sitl()
self.wait_ready_to_arm(require_absolute=True)
old_pos = self.get_global_position_int()
print("old_pos=%s" % str(old_pos))
self.context_push()
ex = None
try:
self.set_parameters({
"BCN_TYPE": 10,
"BCN_LATITUDE": SITL_START_LOCATION.lat,
"BCN_LONGITUDE": SITL_START_LOCATION.lng,
"BCN_ALT": SITL_START_LOCATION.alt,
"BCN_ORIENT_YAW": 0,
"AVOID_ENABLE": 4,
"GPS_TYPE": 0,
"EK3_ENABLE": 1,
"EK3_SRC1_POSXY": 4, # Beacon
"EK3_SRC1_POSZ": 1, # Baro
"EK3_SRC1_VELXY": 0, # None
"EK3_SRC1_VELZ": 0, # None
"EK2_ENABLE": 0,
"AHRS_EKF_TYPE": 3,
})
self.reboot_sitl()
# turn off GPS arming checks. This may be considered a
# bug that we need to do this.
old_arming_check = int(self.get_parameter("ARMING_CHECK"))
if old_arming_check == 1:
old_arming_check = 1 ^ 25 - 1
new_arming_check = int(old_arming_check) & ~(1 << 3)
self.set_parameter("ARMING_CHECK", new_arming_check)
self.reboot_sitl()
# require_absolute=True infers a GPS is present
self.wait_ready_to_arm(require_absolute=False)
tstart = self.get_sim_time()
timeout = 20
while True:
if self.get_sim_time_cached() - tstart > timeout:
raise NotAchievedException("Did not get new position like old position")
self.progress("Fetching location")
new_pos = self.get_global_position_int()
pos_delta = self.get_distance_int(old_pos, new_pos)
max_delta = 1
self.progress("delta=%u want <= %u" % (pos_delta, max_delta))
if pos_delta <= max_delta:
break
self.progress("Moving to ensure location is tracked")
self.takeoff(10, mode="STABILIZE")
self.change_mode("CIRCLE")
tstart = self.get_sim_time()
max_delta = 0
max_allowed_delta = 10
while True:
if self.get_sim_time_cached() - tstart > timeout:
break
pos_delta = self.get_distance_int(self.sim_location_int(), self.get_global_position_int())
self.progress("pos_delta=%f max_delta=%f max_allowed_delta=%f" % (pos_delta, max_delta, max_allowed_delta))
if pos_delta > max_delta:
max_delta = pos_delta
if pos_delta > max_allowed_delta:
raise NotAchievedException("Vehicle location not tracking simulated location (%f > %f)" %
(pos_delta, max_allowed_delta))
self.progress("Tracked location just fine (max_delta=%f)" % max_delta)
self.change_mode("LOITER")
self.wait_groundspeed(0, 0.3, timeout=120)
self.land_and_disarm()
except Exception as e:
self.print_exception_caught(e)
ex = e
self.disarm_vehicle(force=True)
self.reboot_sitl()
self.context_pop()
self.reboot_sitl()
if ex is not None:
raise ex
def fly_beacon_avoidance_test(self):
self.context_push()
ex = None
try:
self.set_parameters({
"BCN_TYPE": 10,
"BCN_LATITUDE": int(SITL_START_LOCATION.lat),
"BCN_LONGITUDE": int(SITL_START_LOCATION.lng),
"BCN_ORIENT_YAW": 45,
"AVOID_ENABLE": 4,
})
self.reboot_sitl()
self.takeoff(10, mode="LOITER")
self.set_rc(2, 1400)
west_loc = mavutil.location(-35.362919, 149.165055, 0, 0)
self.wait_location(west_loc, accuracy=7)
self.reach_heading_manual(0)
north_loc = mavutil.location(-35.362881, 149.165103, 0, 0)
self.wait_location(north_loc, accuracy=7)
self.set_rc(2, 1500)
self.set_rc(1, 1600)
east_loc = mavutil.location(-35.362986, 149.165227, 0, 0)
self.wait_location(east_loc, accuracy=7)
self.set_rc(1, 1500)
self.set_rc(2, 1600)
south_loc = mavutil.location(-35.363025, 149.165182, 0, 0)
self.wait_location(south_loc, accuracy=7)
self.set_rc(2, 1500)
self.do_RTL()
except Exception as e:
self.print_exception_caught(e)
ex = e
self.context_pop()
self.clear_fence()
self.disarm_vehicle(force=True)
self.reboot_sitl()
if ex is not None:
raise ex
def fly_wind_baro_compensation(self):
self.context_push()
ex = None
try:
self.customise_SITL_commandline(
["--defaults", ','.join(self.model_defaults_filepath('Callisto'))],
model="octa-quad:@ROMFS/models/Callisto.json",
wipe=True,
)
wind_spd_truth = 8.0
wind_dir_truth = 90.0
self.set_parameters({
"EK3_ENABLE": 1,
"EK2_ENABLE": 0,
"AHRS_EKF_TYPE": 3,
"BARO1_WCF_ENABLE": 1.000000,
})
self.reboot_sitl()
self.set_parameters({
"EK3_DRAG_BCOEF_X": 361.000000,
"EK3_DRAG_BCOEF_Y": 361.000000,
"EK3_DRAG_MCOEF": 0.082000,
"BARO1_WCF_FWD": -0.300000,
"BARO1_WCF_BCK": -0.300000,
"BARO1_WCF_RGT": 0.300000,
"BARO1_WCF_LFT": 0.300000,
"SIM_BARO_WCF_FWD": -0.300000,
"SIM_BARO_WCF_BAK": -0.300000,
"SIM_BARO_WCF_RGT": 0.300000,
"SIM_BARO_WCF_LFT": 0.300000,
"SIM_WIND_DIR": wind_dir_truth,
"SIM_WIND_SPD": wind_spd_truth,
"SIM_WIND_T": 1.000000,
})
self.reboot_sitl()
# require_absolute=True infers a GPS is present
self.wait_ready_to_arm(require_absolute=False)
self.progress("Climb to 20m in LOITER and yaw spin for 30 seconds")
self.takeoff(10, mode="LOITER")
self.set_rc(4, 1400)
self.delay_sim_time(30)
# check wind esitmates
m = self.mav.recv_match(type='WIND', blocking=True)
speed_error = abs(m.speed - wind_spd_truth)
angle_error = abs(m.direction - wind_dir_truth)
if (speed_error > 1.0):
raise NotAchievedException("Wind speed incorrect - want %f +-1 got %f m/s" % (wind_spd_truth, m.speed))
if (angle_error > 15.0):
raise NotAchievedException(
"Wind direction incorrect - want %f +-15 got %f deg" %
(wind_dir_truth, m.direction))
self.progress("Wind estimate is good, now check height variation for 30 seconds")
# check height stability over another 30 seconds
z_min = 1E6
z_max = -1E6
tstart = self.get_sim_time()
while (self.get_sim_time() < tstart + 30):
m = self.mav.recv_match(type='LOCAL_POSITION_NED', blocking=True)
if (m.z > z_max):
z_max = m.z
if (m.z < z_min):
z_min = m.z
if (z_max-z_min > 0.5):
raise NotAchievedException("Height variation is excessive")
self.progress("Height variation is good")
self.set_rc(4, 1500)
self.land_and_disarm()
except Exception as e:
self.print_exception_caught(e)
ex = e
self.disarm_vehicle(force=True)
self.reboot_sitl()
self.context_pop()
self.reboot_sitl()
if ex is not None:
raise ex
def wait_generator_speed_and_state(self, rpm_min, rpm_max, want_state, timeout=240):
self.drain_mav()
tstart = self.get_sim_time()
while True:
if self.get_sim_time_cached() - tstart > timeout:
raise NotAchievedException("Did not move to state/speed")
m = self.mav.recv_match(type="GENERATOR_STATUS", blocking=True, timeout=10)
if m is None:
raise NotAchievedException("Did not get GENERATOR_STATUS")
if m.generator_speed < rpm_min:
self.progress("Too slow (%u<%u)" % (m.generator_speed, rpm_min))
continue
if m.generator_speed > rpm_max:
self.progress("Too fast (%u>%u)" % (m.generator_speed, rpm_max))
continue
if m.status != want_state:
self.progress("Wrong state (got=%u want=%u)" % (m.status, want_state))
break
self.progress("Got generator speed and state")
def test_richenpower(self):
self.set_parameters({
"SERIAL5_PROTOCOL": 30,
"SIM_RICH_ENABLE": 1,
"SERVO8_FUNCTION": 42,
"SIM_RICH_CTRL": 8,
"RC9_OPTION": 85,
"LOG_DISARMED": 1,
"BATT2_MONITOR": 17,
"GEN_TYPE": 3,
})
self.reboot_sitl()
self.set_rc(9, 1000) # remember this is a switch position - stop
self.customise_SITL_commandline(["--uartF=sim:richenpower"])
self.wait_statustext("requested state is not RUN", timeout=60)
self.set_message_rate_hz("GENERATOR_STATUS", 10)
self.drain_mav_unparsed()
self.wait_generator_speed_and_state(0, 0, mavutil.mavlink.MAV_GENERATOR_STATUS_FLAG_OFF)
messages = []
def my_message_hook(mav, m):
if m.get_type() != 'STATUSTEXT':
return
messages.append(m)
self.install_message_hook(my_message_hook)
try:
self.set_rc(9, 2000) # remember this is a switch position - run
finally:
self.remove_message_hook(my_message_hook)
if "Generator HIGH" not in [x.text for x in messages]:
self.wait_statustext("Generator HIGH", timeout=60)
self.set_rc(9, 1000) # remember this is a switch position - stop
self.wait_statustext("requested state is not RUN", timeout=200)
self.set_rc(9, 1500) # remember this is a switch position - idle
self.wait_generator_speed_and_state(3000, 8000, mavutil.mavlink.MAV_GENERATOR_STATUS_FLAG_IDLE)
self.set_rc(9, 2000) # remember this is a switch position - run
# self.wait_generator_speed_and_state(3000, 30000, mavutil.mavlink.MAV_GENERATOR_STATUS_FLAG_WARMING_UP)
self.wait_generator_speed_and_state(8000, 30000, mavutil.mavlink.MAV_GENERATOR_STATUS_FLAG_GENERATING)
bs = self.mav.recv_match(
type="BATTERY_STATUS",
condition="BATTERY_STATUS.id==1", # id is zero-indexed
timeout=1,
blocking=True
)
if bs is None:
raise NotAchievedException("Did not receive BATTERY_STATUS")
self.progress("Received battery status: %s" % str(bs))
want_bs_volt = 50000
if bs.voltages[0] != want_bs_volt:
raise NotAchievedException("Battery voltage not as expected (want=%f) got=(%f)" % (want_bs_volt, bs.voltages[0],))
self.progress("Moving *back* to idle")
self.set_rc(9, 1500) # remember this is a switch position - idle
self.wait_generator_speed_and_state(3000, 10000, mavutil.mavlink.MAV_GENERATOR_STATUS_FLAG_IDLE)
self.progress("Moving *back* to run")
self.set_rc(9, 2000) # remember this is a switch position - run
self.wait_generator_speed_and_state(8000, 30000, mavutil.mavlink.MAV_GENERATOR_STATUS_FLAG_GENERATING)
self.set_message_rate_hz("GENERATOR_STATUS", -1)
self.set_parameter("LOG_DISARMED", 0)
if not self.current_onboard_log_contains_message("GEN"):
raise NotAchievedException("Did not find expected GEN message")
def test_ie24(self):
self.context_push()
ex = None
try:
self.set_parameters({
"SERIAL5_PROTOCOL": 30,
"SERIAL5_BAUD": 115200,
"GEN_TYPE": 2,
"BATT2_MONITOR": 17,
"SIM_IE24_ENABLE": 1,
"LOG_DISARMED": 1,
})
self.customise_SITL_commandline(["--uartF=sim:ie24"])
self.wait_ready_to_arm()
self.arm_vehicle()
self.disarm_vehicle()
# Test for pre-arm check fail when state is not running
self.start_subtest("If you haven't taken off generator error should cause instant failsafe and disarm")
self.set_parameter("SIM_IE24_STATE", 8)
self.wait_statustext("Status not running", timeout=40)
self.try_arm(result=False,
expect_msg="Status not running")
self.set_parameter("SIM_IE24_STATE", 2) # Explicitly set state to running
# Test that error code does result in failsafe
self.start_subtest("If you haven't taken off generator error should cause instant failsafe and disarm")
self.change_mode("STABILIZE")
self.set_parameter("DISARM_DELAY", 0)
self.arm_vehicle()
self.set_parameter("SIM_IE24_ERROR", 30)
self.disarm_wait(timeout=1)
self.set_parameter("SIM_IE24_ERROR", 0)
self.set_parameter("DISARM_DELAY", 10)
except Exception as e:
self.print_exception_caught(e)
ex = e
self.context_pop()
if ex is not None:
raise ex
def test_aux_switch_options(self):
self.set_parameter("RC7_OPTION", 58) # clear waypoints
self.load_mission("copter_loiter_to_alt.txt")
self.set_rc(7, 1000)
self.assert_mission_count(5)
self.progress("Clear mission")
self.set_rc(7, 2000)
self.delay_sim_time(1) # allow switch to debounce
self.assert_mission_count(0)
self.set_rc(7, 1000)
self.set_parameter("RC7_OPTION", 24) # reset mission
self.delay_sim_time(2)
self.load_mission("copter_loiter_to_alt.txt")
set_wp = 4
self.set_current_waypoint(set_wp)
self.wait_current_waypoint(set_wp, timeout=10)
self.progress("Reset mission")
self.set_rc(7, 2000)
self.delay_sim_time(1)
self.drain_mav()
self.wait_current_waypoint(0, timeout=10)
self.set_rc(7, 1000)
def test_aux_functions_in_mission(self):
self.load_mission("aux_functions.txt")
self.change_mode('LOITER')
self.wait_ready_to_arm()
self.arm_vehicle()
self.change_mode('AUTO')
self.set_rc(3, 1500)
self.wait_mode('ALT_HOLD')
self.change_mode('AUTO')
self.wait_rtl_complete()
def fly_rangefinder_drivers_fly(self, rangefinders):
'''ensure rangefinder gives height-above-ground'''
self.change_mode('GUIDED')
self.wait_ready_to_arm()
self.arm_vehicle()
expected_alt = 5
self.user_takeoff(alt_min=expected_alt)
rf = self.mav.recv_match(type="RANGEFINDER", timeout=1, blocking=True)
if rf is None:
raise NotAchievedException("Did not receive rangefinder message")
gpi = self.mav.recv_match(type='GLOBAL_POSITION_INT', blocking=True, timeout=1)
if gpi is None:
raise NotAchievedException("Did not receive GLOBAL_POSITION_INT message")
if abs(rf.distance - gpi.relative_alt/1000.0) > 1:
raise NotAchievedException(
"rangefinder alt (%s) disagrees with global-position-int.relative_alt (%s)" %
(rf.distance, gpi.relative_alt/1000.0)
)
for i in range(0, len(rangefinders)):
name = rangefinders[i]
self.progress("i=%u (%s)" % (i, name))
ds = self.mav.recv_match(
type="DISTANCE_SENSOR",
timeout=2,
blocking=True,
condition="DISTANCE_SENSOR.id==%u" % i
)
if ds is None:
raise NotAchievedException("Did not receive DISTANCE_SENSOR message for id==%u (%s)" % (i, name))
self.progress("Got: %s" % str(ds))
if abs(ds.current_distance/100.0 - gpi.relative_alt/1000.0) > 1:
raise NotAchievedException(
"distance sensor.current_distance (%f) (%s) disagrees with global-position-int.relative_alt (%s)" %
(ds.current_distance/100.0, name, gpi.relative_alt/1000.0))
self.land_and_disarm()
self.progress("Ensure RFND messages in log")
if not self.current_onboard_log_contains_message("RFND"):
raise NotAchievedException("No RFND messages in log")
def fly_proximity_mavlink_distance_sensor(self):
self.start_subtest("Test mavlink proximity sensor using DISTANCE_SENSOR messages") # noqa
self.context_push()
ex = None
try:
self.set_parameter("SERIAL5_PROTOCOL", 1)
self.set_parameter("PRX_TYPE", 2) # mavlink
self.reboot_sitl()
self.progress("Should be unhealthy while we don't send messages")
self.assert_sensor_state(mavutil.mavlink.MAV_SYS_STATUS_SENSOR_PROXIMITY, True, True, False)
self.progress("Should be healthy while we're sending good messages")
tstart = self.get_sim_time()
while True:
if self.get_sim_time() - tstart > 5:
raise NotAchievedException("Sensor did not come good")
self.mav.mav.distance_sensor_send(
0, # time_boot_ms
10, # min_distance cm
50, # max_distance cm
20, # current_distance cm
mavutil.mavlink.MAV_DISTANCE_SENSOR_LASER, # type
21, # id
mavutil.mavlink.MAV_SENSOR_ROTATION_NONE, # orientation
255 # covariance
)
if self.sensor_has_state(mavutil.mavlink.MAV_SYS_STATUS_SENSOR_PROXIMITY, True, True, True):
self.progress("Sensor has good state")
break
self.delay_sim_time(0.1)
self.progress("Should be unhealthy again if we stop sending messages")
self.delay_sim_time(1)
self.assert_sensor_state(mavutil.mavlink.MAV_SYS_STATUS_SENSOR_PROXIMITY, True, True, False)
# now make sure we get echoed back the same sorts of things we send:
# distances are in cm
distance_map = {
mavutil.mavlink.MAV_SENSOR_ROTATION_NONE: 30,
mavutil.mavlink.MAV_SENSOR_ROTATION_YAW_45: 35,
mavutil.mavlink.MAV_SENSOR_ROTATION_YAW_90: 20,
mavutil.mavlink.MAV_SENSOR_ROTATION_YAW_135: 15,
mavutil.mavlink.MAV_SENSOR_ROTATION_YAW_180: 70,
mavutil.mavlink.MAV_SENSOR_ROTATION_YAW_225: 80,
mavutil.mavlink.MAV_SENSOR_ROTATION_YAW_270: 10,
mavutil.mavlink.MAV_SENSOR_ROTATION_YAW_315: 90,
}
wanted_distances = copy.copy(distance_map)
sensor_enum = mavutil.mavlink.enums["MAV_SENSOR_ORIENTATION"]
def my_message_hook(mav, m):
if m.get_type() != 'DISTANCE_SENSOR':
return
self.progress("Got (%s)" % str(m))
want = distance_map[m.orientation]
got = m.current_distance
# ArduPilot's floating point conversions make it imprecise:
delta = abs(want-got)
if delta > 1:
self.progress(
"Wrong distance (%s): want=%f got=%f" %
(sensor_enum[m.orientation].name, want, got))
return
if m.orientation not in wanted_distances:
return
self.progress(
"Correct distance (%s): want=%f got=%f" %
(sensor_enum[m.orientation].name, want, got))
del wanted_distances[m.orientation]
self.install_message_hook_context(my_message_hook)
tstart = self.get_sim_time()
while True:
if self.get_sim_time() - tstart > 5:
raise NotAchievedException("Sensor did not give right distances") # noqa
for (orient, dist) in distance_map.items():
self.mav.mav.distance_sensor_send(
0, # time_boot_ms
10, # min_distance cm
90, # max_distance cm
dist, # current_distance cm
mavutil.mavlink.MAV_DISTANCE_SENSOR_LASER, # type
21, # id
orient, # orientation
255 # covariance
)
self.wait_heartbeat()
if len(wanted_distances.keys()) == 0:
break
except Exception as e:
self.print_exception_caught(e)
ex = e
self.context_pop()
self.reboot_sitl()
if ex is not None:
raise ex
def fly_rangefinder_mavlink_distance_sensor(self):
self.start_subtest("Test mavlink rangefinder using DISTANCE_SENSOR messages")
self.context_push()
self.set_parameter('RTL_ALT_TYPE', 0)
ex = None
try:
self.set_parameter("SERIAL5_PROTOCOL", 1)
self.set_parameter("RNGFND1_TYPE", 10)
self.reboot_sitl()
self.set_parameter("RNGFND1_MAX_CM", 32767)
self.progress("Should be unhealthy while we don't send messages")
self.assert_sensor_state(mavutil.mavlink.MAV_SYS_STATUS_SENSOR_LASER_POSITION, True, True, False)
self.progress("Should be healthy while we're sending good messages")
tstart = self.get_sim_time()
while True:
if self.get_sim_time() - tstart > 5:
raise NotAchievedException("Sensor did not come good")
self.mav.mav.distance_sensor_send(
0, # time_boot_ms
10, # min_distance
50, # max_distance
20, # current_distance
mavutil.mavlink.MAV_DISTANCE_SENSOR_LASER, # type
21, # id
mavutil.mavlink.MAV_SENSOR_ROTATION_PITCH_270, # orientation
255 # covariance
)
if self.sensor_has_state(mavutil.mavlink.MAV_SYS_STATUS_SENSOR_LASER_POSITION, True, True, True):
self.progress("Sensor has good state")
break
self.delay_sim_time(0.1)
self.progress("Should be unhealthy again if we stop sending messages")
self.delay_sim_time(1)
self.assert_sensor_state(mavutil.mavlink.MAV_SYS_STATUS_SENSOR_LASER_POSITION, True, True, False)
self.progress("Landing gear should deploy with current_distance below min_distance")
self.change_mode('STABILIZE')
timeout = 60
tstart = self.get_sim_time()
while not self.sensor_has_state(mavutil.mavlink.MAV_SYS_STATUS_PREARM_CHECK, True, True, True):
if self.get_sim_time() - tstart > timeout:
raise NotAchievedException("Failed to become armable after %f seconds" % timeout)
self.mav.mav.distance_sensor_send(
0, # time_boot_ms
100, # min_distance (cm)
2500, # max_distance (cm)
200, # current_distance (cm)
mavutil.mavlink.MAV_DISTANCE_SENSOR_LASER, # type
21, # id
mavutil.mavlink.MAV_SENSOR_ROTATION_PITCH_270, # orientation
255 # covariance
)
self.arm_vehicle()
self.set_parameters({
"SERVO10_FUNCTION": 29,
"LGR_DEPLOY_ALT": 1,
"LGR_RETRACT_ALT": 10, # metres
})
self.delay_sim_time(1) # servo function maps only periodically updated
# self.send_debug_trap()
self.run_cmd(
mavutil.mavlink.MAV_CMD_AIRFRAME_CONFIGURATION,
0,
0, # deploy
0,
0,
0,
0,
0
)
self.context_collect("STATUSTEXT")
tstart = self.get_sim_time()
while True:
if self.get_sim_time_cached() - tstart > 5:
raise NotAchievedException("Retraction did not happen")
self.mav.mav.distance_sensor_send(
0, # time_boot_ms
100, # min_distance (cm)
6000, # max_distance (cm)
1500, # current_distance (cm)
mavutil.mavlink.MAV_DISTANCE_SENSOR_LASER, # type
21, # id
mavutil.mavlink.MAV_SENSOR_ROTATION_PITCH_270, # orientation
255 # covariance
)
self.delay_sim_time(0.1)
try:
self.wait_text("LandingGear: RETRACT", check_context=True, timeout=0.1)
except Exception:
continue
self.progress("Retracted")
break
# self.send_debug_trap()
while True:
if self.get_sim_time_cached() - tstart > 5:
raise NotAchievedException("Deployment did not happen")
self.progress("Sending distance-sensor message")
self.mav.mav.distance_sensor_send(
0, # time_boot_ms
300, # min_distance
500, # max_distance
250, # current_distance
mavutil.mavlink.MAV_DISTANCE_SENSOR_LASER, # type
21, # id
mavutil.mavlink.MAV_SENSOR_ROTATION_PITCH_270, # orientation
255 # covariance
)
try:
self.wait_text("LandingGear: DEPLOY", check_context=True, timeout=0.1)
except Exception:
continue
self.progress("Deployed")
break
self.disarm_vehicle()
except Exception as e:
self.print_exception_caught(e)
ex = e
self.context_pop()
self.reboot_sitl()
if ex is not None:
raise ex
def test_gsf(self):
'''test the Gaussian Sum filter'''
ex = None
self.context_push()
try:
self.set_parameter("EK2_ENABLE", 1)
self.reboot_sitl()
self.takeoff(20, mode='LOITER')
self.set_rc(2, 1400)
self.delay_sim_time(5)
self.set_rc(2, 1500)
self.progress("Path: %s" % self.current_onboard_log_filepath())
dfreader = self.dfreader_for_current_onboard_log()
self.do_RTL()
except Exception as e:
self.progress("Caught exception: %s" %
self.get_exception_stacktrace(e))
ex = e
self.context_pop()
self.reboot_sitl()
if ex is not None:
raise ex
# ensure log messages present
want = set(["XKY0", "XKY1", "NKY0", "NKY1"])
still_want = want
while len(still_want):
m = dfreader.recv_match(type=want)
if m is None:
raise NotAchievedException("Did not get %s" % want)
still_want.remove(m.get_type())
def fly_rangefinder_mavlink(self):
self.fly_rangefinder_mavlink_distance_sensor()
# explicit test for the mavlink driver as it doesn't play so nice:
self.set_parameters({
"SERIAL5_PROTOCOL": 1,
"RNGFND1_TYPE": 10,
})
self.customise_SITL_commandline(['--uartF=sim:rf_mavlink'])
self.change_mode('GUIDED')
self.wait_ready_to_arm()
self.arm_vehicle()
expected_alt = 5
self.user_takeoff(alt_min=expected_alt)
tstart = self.get_sim_time()
while True:
if self.get_sim_time() - tstart > 5:
raise NotAchievedException("Mavlink rangefinder not working")
rf = self.mav.recv_match(type="RANGEFINDER", timeout=1, blocking=True)
if rf is None:
raise NotAchievedException("Did not receive rangefinder message")
gpi = self.mav.recv_match(type='GLOBAL_POSITION_INT', blocking=True, timeout=1)
if gpi is None:
raise NotAchievedException("Did not receive GLOBAL_POSITION_INT message")
if abs(rf.distance - gpi.relative_alt/1000.0) > 1:
print("rangefinder alt (%s) disagrees with global-position-int.relative_alt (%s)" %
(rf.distance, gpi.relative_alt/1000.0))
continue
ds = self.mav.recv_match(
type="DISTANCE_SENSOR",
timeout=2,
blocking=True,
)
if ds is None:
raise NotAchievedException("Did not receive DISTANCE_SENSOR message")
self.progress("Got: %s" % str(ds))
if abs(ds.current_distance/100.0 - gpi.relative_alt/1000.0) > 1:
print(
"distance sensor.current_distance (%f) disagrees with global-position-int.relative_alt (%s)" %
(ds.current_distance/100.0, gpi.relative_alt/1000.0))
continue
break
self.progress("mavlink rangefinder OK")
self.land_and_disarm()
def fly_rangefinder_driver_maxbotix(self):
ex = None
try:
self.context_push()
self.start_subtest("No messages")
rf = self.mav.recv_match(type="DISTANCE_SENSOR", timeout=5, blocking=True)
if rf is not None:
raise NotAchievedException("Receiving DISTANCE_SENSOR when I shouldn't be")
self.start_subtest("Default address")
self.set_parameter("RNGFND1_TYPE", 2) # maxbotix
self.reboot_sitl()
self.do_timesync_roundtrip()
rf = self.mav.recv_match(type="DISTANCE_SENSOR", timeout=5, blocking=True)
self.progress("Got (%s)" % str(rf))
if rf is None:
raise NotAchievedException("Didn't receive DISTANCE_SENSOR when I should've")
self.start_subtest("Explicitly set to default address")
self.set_parameters({
"RNGFND1_TYPE": 2, # maxbotix
"RNGFND1_ADDR": 0x70,
})
self.reboot_sitl()
self.do_timesync_roundtrip()
rf = self.mav.recv_match(type="DISTANCE_SENSOR", timeout=5, blocking=True)
self.progress("Got (%s)" % str(rf))
if rf is None:
raise NotAchievedException("Didn't receive DISTANCE_SENSOR when I should've")
self.start_subtest("Explicitly set to non-default address")
self.set_parameter("RNGFND1_ADDR", 0x71)
self.reboot_sitl()
self.do_timesync_roundtrip()
rf = self.mav.recv_match(type="DISTANCE_SENSOR", timeout=5, blocking=True)
self.progress("Got (%s)" % str(rf))
if rf is None:
raise NotAchievedException("Didn't receive DISTANCE_SENSOR when I should've")
self.start_subtest("Two MaxBotix RangeFinders")
self.set_parameters({
"RNGFND1_TYPE": 2, # maxbotix
"RNGFND1_ADDR": 0x70,
"RNGFND1_MIN_CM": 150,
"RNGFND2_TYPE": 2, # maxbotix
"RNGFND2_ADDR": 0x71,
"RNGFND2_MIN_CM": 250,
})
self.reboot_sitl()
self.do_timesync_roundtrip()
for i in [0, 1]:
rf = self.mav.recv_match(
type="DISTANCE_SENSOR",
timeout=5,
blocking=True,
condition="DISTANCE_SENSOR.id==%u" % i
)
self.progress("Got id==%u (%s)" % (i, str(rf)))
if rf is None:
raise NotAchievedException("Didn't receive DISTANCE_SENSOR when I should've")
expected_dist = 150
if i == 1:
expected_dist = 250
if rf.min_distance != expected_dist:
raise NotAchievedException("Unexpected min_cm (want=%u got=%u)" %
(expected_dist, rf.min_distance))
self.context_pop()
except Exception as e:
self.print_exception_caught(e)
ex = e
self.reboot_sitl()
if ex is not None:
raise ex
def fly_rangefinder_drivers(self):
self.set_parameters({
"RTL_ALT": 500,
"RTL_ALT_TYPE": 1,
})
drivers = [
("lightwareserial", 8), # autodetected between this and -binary
("lightwareserial-binary", 8),
("USD1_v0", 11),
("USD1_v1", 11),
("leddarone", 12),
("maxsonarseriallv", 13),
("nmea", 17),
("wasp", 18),
("benewake_tf02", 19),
("blping", 23),
("benewake_tfmini", 20),
("lanbao", 26),
("benewake_tf03", 27),
("gyus42v2", 31),
]
while len(drivers):
do_drivers = drivers[0:3]
drivers = drivers[3:]
command_line_args = []
self.context_push()
for (offs, cmdline_argument, serial_num) in [(0, '--uartE', 4),
(1, '--uartF', 5),
(2, '--uartG', 6)]:
if len(do_drivers) > offs:
(sim_name, rngfnd_param_value) = do_drivers[offs]
command_line_args.append("%s=sim:%s" %
(cmdline_argument, sim_name))
serial_param_name = "SERIAL%u_PROTOCOL" % serial_num
self.set_parameters({
serial_param_name: 9, # rangefinder
"RNGFND%u_TYPE" % (offs+1): rngfnd_param_value,
})
self.customise_SITL_commandline(command_line_args)
self.fly_rangefinder_drivers_fly([x[0] for x in do_drivers])
self.context_pop()
self.fly_rangefinder_mavlink()
i2c_drivers = [
("maxbotixi2cxl", 2),
]
while len(i2c_drivers):
do_drivers = i2c_drivers[0:9]
i2c_drivers = i2c_drivers[9:]
count = 1
p = {}
for d in do_drivers:
(sim_name, rngfnd_param_value) = d
p["RNGFND%u_TYPE" % count] = rngfnd_param_value
count += 1
self.set_parameters(p)
self.reboot_sitl()
self.fly_rangefinder_drivers_fly([x[0] for x in do_drivers])
def fly_rangefinder_drivers_maxalt(self):
'''test max-height behaviour'''
# lightwareserial goes to 130m when out of range
self.set_parameters({
"SERIAL4_PROTOCOL": 9,
"RNGFND1_TYPE": 8,
"WPNAV_SPEED_UP": 1000, # cm/s
})
self.customise_SITL_commandline([
"--uartE=sim:lightwareserial",
])
self.takeoff(95, mode='GUIDED', timeout=240, max_err=0.5)
self.assert_rangefinder_distance_between(90, 100)
self.wait_rangefinder_distance(90, 100)
rf_bit = mavutil.mavlink.MAV_SYS_STATUS_SENSOR_LASER_POSITION
self.assert_sensor_state(rf_bit, present=True, enabled=True, healthy=True)
self.assert_distance_sensor_quality(100)
self.progress("Moving higher to be out of max rangefinder range")
self.fly_guided_move_local(0, 0, 150)
# sensor remains healthy even out-of-range
self.assert_sensor_state(rf_bit, present=True, enabled=True, healthy=True)
self.assert_distance_sensor_quality(1)
self.do_RTL()
def fly_ship_takeoff(self):
# test ship takeoff
self.wait_groundspeed(0, 2)
self.set_parameters({
"SIM_SHIP_ENABLE": 1,
"SIM_SHIP_SPEED": 10,
"SIM_SHIP_DSIZE": 2,
})
self.wait_ready_to_arm()
# we should be moving with the ship
self.wait_groundspeed(9, 11)
self.takeoff(10)
# above ship our speed drops to 0
self.wait_groundspeed(0, 2)
self.land_and_disarm()
# ship will have moved on, so we land on the water which isn't moving
self.wait_groundspeed(0, 2)
def test_parameter_validation(self):
# wait 10 seconds for initialisation
self.delay_sim_time(10)
self.progress("invalid; min must be less than max:")
self.set_parameters({
"MOT_PWM_MIN": 100,
"MOT_PWM_MAX": 50,
})
self.drain_mav()
self.assert_prearm_failure("Check MOT_PWM_MIN/MAX")
self.progress("invalid; min must be less than max (equal case):")
self.set_parameters({
"MOT_PWM_MIN": 100,
"MOT_PWM_MAX": 100,
})
self.drain_mav()
self.assert_prearm_failure("Check MOT_PWM_MIN/MAX")
def test_alt_estimate_prearm(self):
self.context_push()
ex = None
try:
# disable barometer so there is no altitude source
self.set_parameters({
"SIM_BARO_DISABLE": 1,
"SIM_BARO2_DISABL": 1,
})
self.wait_gps_disable(position_vertical=True)
# turn off arming checks (mandatory arming checks will still be run)
self.set_parameter("ARMING_CHECK", 0)
# delay 12 sec to allow EKF to lose altitude estimate
self.delay_sim_time(12)
self.change_mode("ALT_HOLD")
self.assert_prearm_failure("Need Alt Estimate")
# force arm vehicle in stabilize to bypass barometer pre-arm checks
self.change_mode("STABILIZE")
self.arm_vehicle()
self.set_rc(3, 1700)
try:
self.change_mode("ALT_HOLD", timeout=10)
except AutoTestTimeoutException:
self.progress("PASS not able to set mode without Position : %s" % "ALT_HOLD")
# check that mode change to ALT_HOLD has failed (it should)
if self.mode_is("ALT_HOLD"):
raise NotAchievedException("Changed to ALT_HOLD with no altitude estimate")
except Exception as e:
self.print_exception_caught(e)
ex = e
self.context_pop()
self.disarm_vehicle(force=True)
if ex is not None:
raise ex
def test_ekf_source(self):
self.context_push()
ex = None
try:
self.set_parameters({
"EK3_ENABLE": 1,
"AHRS_EKF_TYPE": 3,
})
self.wait_ready_to_arm()
self.start_subtest("bad yaw source")
self.set_parameter("EK3_SRC3_YAW", 17)
self.assert_prearm_failure("Check EK3_SRC3_YAW")
self.context_push()
self.start_subtest("missing required yaw source")
self.set_parameters({
"EK3_SRC3_YAW": 3, # External Yaw with Compass Fallback
"COMPASS_USE": 0,
"COMPASS_USE2": 0,
"COMPASS_USE3": 0,
})
self.assert_prearm_failure("EK3 sources require Compass")
self.context_pop()
except Exception as e:
self.disarm_vehicle(force=True)
self.print_exception_caught(e)
ex = e
self.context_pop()
if ex is not None:
raise ex
def test_replay_gps_bit(self):
self.set_parameters({
"LOG_REPLAY": 1,
"LOG_DISARMED": 1,
"EK3_ENABLE": 1,
"EK2_ENABLE": 1,
"AHRS_TRIM_X": 0.01,
"AHRS_TRIM_Y": -0.03,
"GPS_TYPE2": 1,
"GPS_POS1_X": 0.1,
"GPS_POS1_Y": 0.2,
"GPS_POS1_Z": 0.3,
"GPS_POS2_X": -0.1,
"GPS_POS2_Y": -0.02,
"GPS_POS2_Z": -0.31,
"INS_POS1_X": 0.12,
"INS_POS1_Y": 0.14,
"INS_POS1_Z": -0.02,
"INS_POS2_X": 0.07,
"INS_POS2_Y": 0.012,
"INS_POS2_Z": -0.06,
"RNGFND1_TYPE": 1,
"RNGFND1_PIN": 0,
"RNGFND1_SCALING": 30,
"RNGFND1_POS_X": 0.17,
"RNGFND1_POS_Y": -0.07,
"RNGFND1_POS_Z": -0.005,
"SIM_SONAR_SCALE": 30,
"SIM_GPS2_DISABLE": 0,
})
self.reboot_sitl()
current_log_filepath = self.current_onboard_log_filepath()
self.progress("Current log path: %s" % str(current_log_filepath))
self.change_mode("LOITER")
self.wait_ready_to_arm(require_absolute=True)
self.arm_vehicle()
self.takeoffAndMoveAway()
self.do_RTL()
self.reboot_sitl()
return current_log_filepath
def test_replay_beacon_bit(self):
self.set_parameters({
"LOG_REPLAY": 1,
"LOG_DISARMED": 1,
})
old_onboard_logs = sorted(self.log_list())
self.fly_beacon_position()
new_onboard_logs = sorted(self.log_list())
log_difference = [x for x in new_onboard_logs if x not in old_onboard_logs]
return log_difference[2]
def test_replay_optical_flow_bit(self):
self.set_parameters({
"LOG_REPLAY": 1,
"LOG_DISARMED": 1,
})
old_onboard_logs = sorted(self.log_list())
self.fly_optical_flow_limits()
new_onboard_logs = sorted(self.log_list())
log_difference = [x for x in new_onboard_logs if x not in old_onboard_logs]
print("log difference: %s" % str(log_difference))
return log_difference[0]
def test_gps_blending(self):
'''ensure we get dataflash log messages for blended instance'''
self.context_push()
ex = None
try:
# configure:
self.set_parameters({
"GPS_TYPE2": 1,
"SIM_GPS2_TYPE": 1,
"SIM_GPS2_DISABLE": 0,
"GPS_AUTO_SWITCH": 2,
})
self.reboot_sitl()
# ensure we're seeing the second GPS:
tstart = self.get_sim_time()
while True:
if self.get_sim_time_cached() - tstart > 60:
raise NotAchievedException("Did not get good GPS2_RAW message")
m = self.mav.recv_match(type='GPS2_RAW', blocking=True, timeout=1)
self.progress("%s" % str(m))
if m is None:
continue
if m.lat == 0:
continue
break
# create a log we can expect blended data to appear in:
self.change_mode('LOITER')
self.wait_ready_to_arm()
self.arm_vehicle()
self.delay_sim_time(5)
self.disarm_vehicle()
# inspect generated log for messages:
dfreader = self.dfreader_for_current_onboard_log()
wanted = set([0, 1, 2])
seen_primary_change = False
while True:
m = dfreader.recv_match(type=["GPS", "EV"]) # disarmed
if m is None:
break
mtype = m.get_type()
if mtype == 'GPS':
try:
wanted.remove(m.I)
except KeyError:
continue
elif mtype == 'EV':
if m.Id == 67: # GPS_PRIMARY_CHANGED
seen_primary_change = True
if len(wanted) == 0 and seen_primary_change:
break
if len(wanted):
raise NotAchievedException("Did not get all three GPS types")
if not seen_primary_change:
raise NotAchievedException("Did not see primary change")
except Exception as e:
self.progress("Caught exception: %s" %
self.get_exception_stacktrace(e))
ex = e
self.context_pop()
self.reboot_sitl()
if ex is not None:
raise ex
def test_callisto(self):
self.customise_SITL_commandline(
["--defaults", ','.join(self.model_defaults_filepath('Callisto')), ],
model="octa-quad:@ROMFS/models/Callisto.json",
wipe=True,
)
self.takeoff(10)
self.do_RTL()
def fly_each_frame(self):
vinfo = vehicleinfo.VehicleInfo()
copter_vinfo_options = vinfo.options[self.vehicleinfo_key()]
known_broken_frames = {
'heli-compound': "wrong binary, different takeoff regime",
'heli-dual': "wrong binary, different takeoff regime",
'heli': "wrong binary, different takeoff regime",
'heli-blade360': "wrong binary, different takeoff regime",
}
for frame in sorted(copter_vinfo_options["frames"].keys()):
self.start_subtest("Testing frame (%s)" % str(frame))
if frame in known_broken_frames:
self.progress("Actually, no I'm not - it is known-broken (%s)" %
(known_broken_frames[frame]))
continue
frame_bits = copter_vinfo_options["frames"][frame]
print("frame_bits: %s" % str(frame_bits))
if frame_bits.get("external", False):
self.progress("Actually, no I'm not - it is an external simulation")
continue
model = frame_bits.get("model", frame)
# the model string for Callisto has crap in it.... we
# should really have another entry in the vehicleinfo data
# to carry the path to the JSON.
actual_model = model.split(":")[0]
defaults = self.model_defaults_filepath(actual_model)
if type(defaults) != list:
defaults = [defaults]
self.customise_SITL_commandline(
["--defaults", ','.join(defaults), ],
model=model,
wipe=True,
)
# add a listener that verifies yaw looks good:
def verify_yaw(mav, m):
if m.get_type() != 'ATTITUDE':
return
yawspeed_thresh_rads = math.radians(10)
if m.yawspeed > yawspeed_thresh_rads:
raise NotAchievedException("Excessive yaw on takeoff: %f deg/s > %f deg/s (frame=%s)" %
(math.degrees(m.yawspeed), math.degrees(yawspeed_thresh_rads), frame))
self.install_message_hook(verify_yaw)
self.takeoff(10)
self.remove_message_hook(verify_yaw)
self.hover()
self.change_mode('ALT_HOLD')
self.delay_sim_time(1)
def verify_rollpitch(mav, m):
if m.get_type() != 'ATTITUDE':
return
pitch_thresh_rad = math.radians(2)
if m.pitch > pitch_thresh_rad:
raise NotAchievedException("Excessive pitch %f deg > %f deg" %
(math.degrees(m.pitch), math.degrees(pitch_thresh_rad)))
roll_thresh_rad = math.radians(2)
if m.roll > roll_thresh_rad:
raise NotAchievedException("Excessive roll %f deg > %f deg" %
(math.degrees(m.roll), math.degrees(roll_thresh_rad)))
self.install_message_hook(verify_rollpitch)
for i in range(5):
self.set_rc(4, 2000)
self.delay_sim_time(0.5)
self.set_rc(4, 1500)
self.delay_sim_time(5)
self.remove_message_hook(verify_rollpitch)
self.do_RTL()
def test_replay(self):
'''test replay correctness'''
self.progress("Building Replay")
util.build_SITL('tool/Replay', clean=False, configure=False)
bits = [
('GPS', self.test_replay_gps_bit),
('Beacon', self.test_replay_beacon_bit),
('OpticalFlow', self.test_replay_optical_flow_bit),
]
for (name, func) in bits:
self.start_subtest("%s" % name)
self.test_replay_bit(func)
def test_replay_bit(self, bit):
self.context_push()
current_log_filepath = bit()
self.progress("Running replay on (%s)" % current_log_filepath)
util.run_cmd(
['build/sitl/tool/Replay', current_log_filepath],
directory=util.topdir(),
checkfail=True,
show=True,
output=True,
)
self.context_pop()
replay_log_filepath = self.current_onboard_log_filepath()
self.progress("Replay log path: %s" % str(replay_log_filepath))
check_replay = util.load_local_module("Tools/Replay/check_replay.py")
ok = check_replay.check_log(replay_log_filepath, self.progress, verbose=True)
if not ok:
raise NotAchievedException("check_replay failed")
def DefaultIntervalsFromFiles(self):
ex = None
intervals_filepath = util.reltopdir("message-intervals-chan0.txt")
self.progress("Using filepath (%s)" % intervals_filepath)
try:
with open(intervals_filepath, "w") as f:
f.write("""30 50
28 100
29 200
""")
# other tests may have explicitly set rates, so wipe parameters:
def custom_stream_rate_setter():
for stream in mavutil.mavlink.MAV_DATA_STREAM_EXTRA3, mavutil.mavlink.MAV_DATA_STREAM_RC_CHANNELS:
self.set_streamrate(5, stream=stream)
self.customise_SITL_commandline(
[],
wipe=True,
set_streamrate_callback=custom_stream_rate_setter,
)
self.assert_message_rate_hz("ATTITUDE", 20)
self.assert_message_rate_hz("SCALED_PRESSURE", 5)
except Exception as e:
self.print_exception_caught(e)
ex = e
os.unlink(intervals_filepath)
self.reboot_sitl()
if ex is not None:
raise ex
def BaroDrivers(self):
sensors = [
("MS5611", 2),
]
for (name, bus) in sensors:
self.context_push()
if bus is not None:
self.set_parameter("BARO_EXT_BUS", bus)
self.set_parameter("BARO_PROBE_EXT", 1 << 2)
self.reboot_sitl()
self.wait_ready_to_arm()
self.arm_vehicle()
# insert listener to compare airspeeds:
messages = [None, None, None]
global count
count = 0
def check_pressure(mav, m):
global count
m_type = m.get_type()
count += 1
# if count > 500:
# if press_abs[0] is None or press_abs[1] is None:
# raise NotAchievedException("Not receiving messages")
if m_type == 'SCALED_PRESSURE3':
off = 2
elif m_type == 'SCALED_PRESSURE2':
off = 1
elif m_type == 'SCALED_PRESSURE':
off = 0
else:
return
messages[off] = m
if None in messages:
return
first = messages[0]
for msg in messages[1:]:
delta_press_abs = abs(first.press_abs - msg.press_abs)
if delta_press_abs > 0.5: # 50 Pa leeway
raise NotAchievedException("Press_Abs mismatch (press1=%s press2=%s)" % (first, msg))
delta_temperature = abs(first.temperature - msg.temperature)
if delta_temperature > 300: # that's 3-degrees leeway
raise NotAchievedException("Temperature mismatch (t1=%s t2=%s)" % (first, msg))
self.install_message_hook_context(check_pressure)
self.fly_mission("copter_mission.txt", strict=False)
if None in messages:
raise NotAchievedException("Missing a message")
self.context_pop()
self.reboot_sitl()
def test_copter_gps_zero(self):
# https://github.com/ArduPilot/ardupilot/issues/14236
self.progress("arm the vehicle and takeoff in Guided")
self.takeoff(20, mode='GUIDED')
self.progress("fly 50m North (or whatever)")
old_pos = self.mav.recv_match(type='GLOBAL_POSITION_INT', blocking=True)
self.fly_guided_move_global_relative_alt(50, 0, 20)
self.set_parameter('GPS_TYPE', 0)
self.drain_mav()
tstart = self.get_sim_time()
while True:
if self.get_sim_time_cached() - tstart > 30 and self.mode_is('LAND'):
self.progress("Bug not reproduced")
break
m = self.mav.recv_match(type='GLOBAL_POSITION_INT', blocking=True, timeout=1)
self.progress("Received (%s)" % str(m))
if m is None:
raise NotAchievedException("No GLOBAL_POSITION_INT?!")
pos_delta = self.get_distance_int(old_pos, m)
self.progress("Distance: %f" % pos_delta)
if pos_delta < 5:
raise NotAchievedException("Bug reproduced - returned to near origin")
self.wait_disarmed()
self.reboot_sitl()
def test_SMART_RTL(self):
self.context_push()
ex = None
try:
self.progress("arm the vehicle and takeoff in Guided")
self.takeoff(20, mode='GUIDED')
self.progress("fly around a bit (or whatever)")
locs = [
(50, 0, 20),
(-50, 50, 20),
(-50, 0, 20),
]
for (lat, lng, alt) in locs:
self.fly_guided_move_local(lat, lng, alt)
self.change_mode('SMART_RTL')
for (lat, lng, alt) in reversed(locs):
self.wait_distance_to_local_position(
(lat, lng, -alt),
0,
10,
timeout=60
)
self.wait_disarmed()
except Exception as e:
self.print_exception_caught(e)
ex = e
self.disarm_vehicle(force=True)
self.context_pop()
self.reboot_sitl()
if ex is not None:
raise ex
def get_ground_effect_duration_from_current_onboard_log(self, bit, ignore_multi=False):
'''returns a duration in seconds we were expecting to interact with
the ground. Will die if there's more than one such block of
time and ignore_multi is not set (will return first duration
otherwise)
'''
ret = []
dfreader = self.dfreader_for_current_onboard_log()
seen_expected_start_TimeUS = None
first = None
last = None
while True:
m = dfreader.recv_match(type="XKF4")
if m is None:
break
last = m
if first is None:
first = m
# self.progress("%s" % str(m))
expected = m.SS & (1 << bit)
if expected:
if seen_expected_start_TimeUS is None:
seen_expected_start_TimeUS = m.TimeUS
continue
else:
if seen_expected_start_TimeUS is not None:
duration = (m.TimeUS - seen_expected_start_TimeUS)/1000000.0
ret.append(duration)
seen_expected_start_TimeUS = None
if seen_expected_start_TimeUS is not None:
duration = (last.TimeUS - seen_expected_start_TimeUS)/1000000.0
ret.append(duration)
return ret
def get_takeoffexpected_durations_from_current_onboard_log(self, ignore_multi=False):
return self.get_ground_effect_duration_from_current_onboard_log(11, ignore_multi=ignore_multi)
def get_touchdownexpected_durations_from_current_onboard_log(self, ignore_multi=False):
return self.get_ground_effect_duration_from_current_onboard_log(12, ignore_multi=ignore_multi)
def ThrowDoubleDrop(self):
# test boomerang mode:
self.progress("Getting a lift to altitude")
self.set_parameters({
"SIM_SHOVE_Z": -11,
"THROW_TYPE": 1, # drop
"MOT_SPOOL_TIME": 2,
})
self.change_mode('THROW')
self.wait_ready_to_arm()
self.arm_vehicle()
try:
self.set_parameter("SIM_SHOVE_TIME", 30000)
except ValueError:
# the shove resets this to zero
pass
self.wait_altitude(100, 1000, timeout=100, relative=True)
self.context_collect('STATUSTEXT')
self.wait_statustext("throw detected - spooling motors", check_context=True, timeout=10)
self.wait_statustext("throttle is unlimited - uprighting", check_context=True)
self.wait_statustext("uprighted - controlling height", check_context=True)
self.wait_statustext("height achieved - controlling position", check_context=True)
self.progress("Waiting for still")
self.wait_speed_vector(Vector3(0, 0, 0))
self.change_mode('ALT_HOLD')
self.set_rc(3, 1000)
self.wait_disarmed(timeout=90)
self.zero_throttle()
self.progress("second flight")
self.upload_square_mission_items_around_location(self.poll_home_position())
self.set_parameters({
"THROW_NEXTMODE": 3, # auto
})
self.change_mode('THROW')
self.wait_ready_to_arm()
self.arm_vehicle()
try:
self.set_parameter("SIM_SHOVE_TIME", 30000)
except ValueError:
# the shove resets this to zero
pass
self.wait_altitude(100, 1000, timeout=100, relative=True)
self.wait_statustext("throw detected - spooling motors", check_context=True, timeout=10)
self.wait_statustext("throttle is unlimited - uprighting", check_context=True)
self.wait_statustext("uprighted - controlling height", check_context=True)
self.wait_statustext("height achieved - controlling position", check_context=True)
self.wait_mode('AUTO')
self.wait_disarmed(timeout=240)
def GroundEffectCompensation_takeOffExpected(self):
self.change_mode('ALT_HOLD')
self.set_parameter("LOG_FILE_DSRMROT", 1)
self.progress("Making sure we'll have a short log to look at")
self.wait_ready_to_arm()
self.arm_vehicle()
self.disarm_vehicle()
# arm the vehicle and let it disarm normally. This should
# yield a log where the EKF considers a takeoff imminent until
# disarm
self.start_subtest("Check ground effect compensation remains set in EKF while we're at idle on the ground")
self.arm_vehicle()
self.wait_disarmed()
durations = self.get_takeoffexpected_durations_from_current_onboard_log()
duration = durations[0]
want = 9
self.progress("takeoff-expected duration: %fs" % (duration,))
if duration < want: # assumes default 10-second DISARM_DELAY
raise NotAchievedException("Should have been expecting takeoff for longer than %fs (want>%f)" %
(duration, want))
self.start_subtest("takeoffExpected should be false very soon after we launch into the air")
self.takeoff(mode='ALT_HOLD', alt_min=5)
self.change_mode('LAND')
self.wait_disarmed()
durations = self.get_takeoffexpected_durations_from_current_onboard_log(ignore_multi=True)
self.progress("touchdown-durations: %s" % str(durations))
duration = durations[0]
self.progress("takeoff-expected-duration %f" % (duration,))
want_lt = 5
if duration >= want_lt:
raise NotAchievedException("Was expecting takeoff for longer than expected; got=%f want<=%f" %
(duration, want_lt))
def MAV_CMD_CONDITION_YAW_absolute(self):
self.start_subtest("absolute")
self.takeoff(20, mode='GUIDED')
m = self.mav.recv_match(type='VFR_HUD', blocking=True)
initial_heading = m.heading
self.progress("Ensuring initial heading is steady")
target = initial_heading
self.run_cmd(
mavutil.mavlink.MAV_CMD_CONDITION_YAW,
target, # target angle
10, # degrees/second
1, # -1 is counter-clockwise, 1 clockwise
0, # 1 for relative, 0 for absolute
0, # p5
0, # p6
0, # p7
)
self.wait_heading(target, minimum_duration=2, timeout=50)
degsecond = 2
def rate_watcher(mav, m):
if m.get_type() != 'ATTITUDE':
return
if abs(math.degrees(m.yawspeed)) > 5*degsecond:
raise NotAchievedException("Moved too fast (%f>%f)" %
(math.degrees(m.yawspeed), 5*degsecond))
self.install_message_hook_context(rate_watcher)
self.progress("Yaw CW 60 degrees")
target = initial_heading + 60
part_way_target = initial_heading + 10
self.run_cmd(
mavutil.mavlink.MAV_CMD_CONDITION_YAW,
target, # target angle
degsecond, # degrees/second
1, # -1 is counter-clockwise, 1 clockwise
0, # 1 for relative, 0 for absolute
0, # p5
0, # p6
0, # p7
)
self.wait_heading(part_way_target)
self.wait_heading(target, minimum_duration=2)
self.progress("Yaw CCW 60 degrees")
target = initial_heading
part_way_target = initial_heading + 30
self.run_cmd(
mavutil.mavlink.MAV_CMD_CONDITION_YAW,
target, # target angle
degsecond, # degrees/second
-1, # -1 is counter-clockwise, 1 clockwise
0, # 1 for relative, 0 for absolute
0, # p5
0, # p6
0, # p7
)
self.wait_heading(part_way_target)
self.wait_heading(target, minimum_duration=2)
self.do_RTL()
def MAV_CMD_CONDITION_YAW_relative(self):
pass
def MAV_CMD_CONDITION_YAW(self):
self.MAV_CMD_CONDITION_YAW_absolute()
self.MAV_CMD_CONDITION_YAW_relative()
def GroundEffectCompensation_touchDownExpected(self):
self.zero_throttle()
self.change_mode('ALT_HOLD')
self.set_parameter("LOG_FILE_DSRMROT", 1)
self.progress("Making sure we'll have a short log to look at")
self.wait_ready_to_arm()
self.arm_vehicle()
self.disarm_vehicle()
self.start_subtest("Make sure touchdown-expected duration is about right")
self.takeoff(20, mode='ALT_HOLD')
self.change_mode('LAND')
self.wait_disarmed()
durations = self.get_touchdownexpected_durations_from_current_onboard_log(ignore_multi=True)
self.progress("touchdown-durations: %s" % str(durations))
duration = durations[-1]
expected = 23 # this is the time in the final descent phase of LAND
if abs(duration - expected) > 5:
raise NotAchievedException("Was expecting roughly %fs of touchdown expected, got %f" % (expected, duration))
def upload_square_mission_items_around_location(self, loc):
alt = 20
loc.alt = alt
items = [
(mavutil.mavlink.MAV_CMD_NAV_TAKEOFF, 0, 0, alt)
]
for (ofs_n, ofs_e) in (20, 20), (20, -20), (-20, -20), (-20, 20), (20, 20):
items.append((mavutil.mavlink.MAV_CMD_NAV_WAYPOINT, ofs_n, ofs_e, alt))
items.append((mavutil.mavlink.MAV_CMD_NAV_RETURN_TO_LAUNCH, 0, 0, 0))
self.upload_simple_relhome_mission(items)
def RefindGPS(self):
# https://github.com/ArduPilot/ardupilot/issues/14236
self.progress("arm the vehicle and takeoff in Guided")
self.takeoff(20, mode='GUIDED')
self.progress("fly 50m North (or whatever)")
old_pos = self.mav.recv_match(type='GLOBAL_POSITION_INT', blocking=True)
self.fly_guided_move_global_relative_alt(50, 0, 20)
self.set_parameter('GPS_TYPE', 0)
self.drain_mav()
tstart = self.get_sim_time()
while True:
if self.get_sim_time_cached() - tstart > 30 and self.mode_is('LAND'):
self.progress("Bug not reproduced")
break
m = self.mav.recv_match(type='GLOBAL_POSITION_INT', blocking=True, timeout=1)
self.progress("Received (%s)" % str(m))
if m is None:
raise NotAchievedException("No GLOBAL_POSITION_INT?!")
pos_delta = self.get_distance_int(old_pos, m)
self.progress("Distance: %f" % pos_delta)
if pos_delta < 5:
raise NotAchievedException("Bug reproduced - returned to near origin")
self.set_parameter('GPS_TYPE', 1)
self.do_RTL()
def GPSForYaw(self):
self.context_push()
self.load_default_params_file("copter-gps-for-yaw.parm")
self.reboot_sitl()
ex = None
try:
self.wait_gps_fix_type_gte(6, message_type="GPS2_RAW", verbose=True)
m = self.assert_receive_message("GPS2_RAW")
self.progress(self.dump_message_verbose(m))
want = 27000
if abs(m.yaw - want) > 500:
raise NotAchievedException("Expected to get GPS-from-yaw (want %f got %f)" % (want, m.yaw))
self.wait_ready_to_arm()
except Exception as e:
self.print_exception_caught(e)
ex = e
self.context_pop()
self.reboot_sitl()
if ex is not None:
raise ex
def AP_Avoidance(self):
self.set_parameters({
"AVD_ENABLE": 1,
"ADSB_TYPE": 1, # mavlink
"AVD_F_ACTION": 2, # climb or descend
})
self.reboot_sitl()
self.wait_ready_to_arm()
here = self.mav.location()
self.context_push()
self.start_subtest("F_ALT_MIN zero - disabled, can't arm in face of threat")
self.set_parameters({
"AVD_F_ALT_MIN": 0,
})
self.wait_ready_to_arm()
self.test_adsb_send_threatening_adsb_message(here)
self.delay_sim_time(1)
self.try_arm(result=False,
expect_msg="ADSB threat detected")
self.wait_ready_to_arm(timeout=60)
self.context_pop()
self.start_subtest("F_ALT_MIN 16m relative - arm in face of threat")
self.context_push()
self.set_parameters({
"AVD_F_ALT_MIN": int(16 + here.alt),
})
self.wait_ready_to_arm()
self.test_adsb_send_threatening_adsb_message(here)
# self.delay_sim_time(1)
self.arm_vehicle()
self.disarm_vehicle()
self.context_pop()
def PAUSE_CONTINUE(self):
self.load_mission("copter_mission.txt", strict=False)
self.set_parameter("AUTO_OPTIONS", 3)
self.change_mode('AUTO')
self.wait_ready_to_arm()
self.arm_vehicle()
self.wait_waypoint(4, 4)
self.run_cmd(mavutil.mavlink.MAV_CMD_DO_PAUSE_CONTINUE,
0, # param1
0, # param2
0, # param3
0, # param4
0, # param5
0, # param6
0 # param7
)
self.wait_groundspeed(0, 1, minimum_duration=5)
self.run_cmd(mavutil.mavlink.MAV_CMD_DO_PAUSE_CONTINUE,
1, # param1
0, # param2
0, # param3
0, # param4
0, # param5
0, # param6
0 # param7
)
self.wait_groundspeed(5, 100)
self.wait_disarmed()
# a wrapper around all the 1A,1B,1C..etc tests for travis
def tests1(self):
ret = ([])
ret.extend(self.tests1a())
ret.extend(self.tests1b())
ret.extend(self.tests1c())
ret.extend(self.tests1d())
ret.extend(self.tests1e())
return ret
def ATTITUDE_FAST(self):
'''ensure that when ATTITDE_FAST is set we get many messages'''
self.context_push()
ex = None
try:
old = self.get_parameter('LOG_BITMASK')
new = int(old) | (1 << 0) # see defines.h
self.set_parameters({
"LOG_BITMASK": new,
"LOG_DISARMED": 1,
})
path = self.generate_rate_sample_log()
except Exception as e:
self.print_exception_caught(e)
ex = e
self.context_pop()
self.reboot_sitl()
if ex is not None:
raise ex
self.delay_sim_time(10) # NFI why this is required
self.check_dflog_message_rates(path, {
'ATT': 400,
})
def BaseLoggingRates(self):
'''ensure messages come out at specific rates'''
path = self.generate_rate_sample_log()
self.delay_sim_time(10) # NFI why this is required
self.check_dflog_message_rates(path, {
"ATT": 10,
"IMU": 25,
})
def FETtecESC_flight(self):
'''fly with servo outputs from FETtec ESC'''
self.start_subtest("FETtec ESC flight")
num_wp = self.load_mission("copter_mission.txt", strict=False)
self.fly_loaded_mission(num_wp)
def FETtecESC_esc_power_checks(self):
'''Make sure state machine copes with ESCs rebooting'''
self.start_subtest("FETtec ESC reboot")
self.wait_ready_to_arm()
self.context_collect('STATUSTEXT')
self.progress("Turning off an ESC off ")
mask = int(self.get_parameter("SIM_FTOWESC_POW"))
for mot_id_to_kill in 1, 2:
self.progress("Turning ESC=%u off" % mot_id_to_kill)
self.set_parameter("SIM_FTOWESC_POW", mask & ~(1 << mot_id_to_kill))
self.delay_sim_time(1)
self.assert_prearm_failure("are not running")
self.progress("Turning it back on")
self.set_parameter("SIM_FTOWESC_POW", mask)
self.wait_ready_to_arm()
self.progress("Turning ESC=%u off (again)" % mot_id_to_kill)
self.set_parameter("SIM_FTOWESC_POW", mask & ~(1 << mot_id_to_kill))
self.delay_sim_time(1)
self.assert_prearm_failure("are not running")
self.progress("Turning it back on")
self.set_parameter("SIM_FTOWESC_POW", mask)
self.wait_ready_to_arm()
self.progress("Turning all ESCs off")
self.set_parameter("SIM_FTOWESC_POW", 0)
self.delay_sim_time(1)
self.assert_prearm_failure("are not running")
self.progress("Turning them back on")
self.set_parameter("SIM_FTOWESC_POW", mask)
self.wait_ready_to_arm()
def fettec_assert_bad_mask(self, mask):
'''assert the mask is bad for fettec driver'''
self.start_subsubtest("Checking mask (%s) is bad" % (mask,))
self.context_push()
self.set_parameter("SERVO_FTW_MASK", mask)
self.reboot_sitl()
tstart = self.get_sim_time()
while True:
if self.get_sim_time_cached() - tstart > 20:
raise NotAchievedException("Expected mask to be only problem within 20 seconds")
try:
self.assert_prearm_failure("Invalid motor mask")
break
except NotAchievedException:
self.delay_sim_time(1)
self.context_pop()
self.reboot_sitl()
def fettec_assert_good_mask(self, mask):
'''assert the mask is bad for fettec driver'''
self.start_subsubtest("Checking mask (%s) is good" % (mask,))
self.context_push()
self.set_parameter("SERVO_FTW_MASK", mask)
self.reboot_sitl()
self.wait_ready_to_arm()
self.context_pop()
self.reboot_sitl()
def FETtecESC_safety_switch(self):
mot = self.find_first_set_bit(int(self.get_parameter("SERVO_FTW_MASK"))) + 1
self.wait_esc_telem_rpm(mot, 0, 0)
self.wait_ready_to_arm()
self.context_push()
self.set_parameter("DISARM_DELAY", 0)
self.arm_vehicle()
# we have to wait for a while for the arming tone to go out
# before the motors will spin:
self.wait_esc_telem_rpm(
esc=mot,
rpm_min=17640,
rpm_max=17640,
minimum_duration=2,
timeout=5,
)
self.set_safetyswitch_on()
self.wait_esc_telem_rpm(mot, 0, 0)
self.set_safetyswitch_off()
self.wait_esc_telem_rpm(
esc=mot,
rpm_min=17640,
rpm_max=17640,
minimum_duration=2,
timeout=5,
)
self.context_pop()
self.wait_disarmed()
def FETtecESC_btw_mask_checks(self):
'''ensure prearm checks work as expected'''
for bad_mask in [0b1000000000000, 0b10100000000000]:
self.fettec_assert_bad_mask(bad_mask)
for good_mask in [0b00001, 0b00101, 0b110000000000]:
self.fettec_assert_good_mask(good_mask)
def FETtecESC(self):
self.set_parameters({
"SERIAL5_PROTOCOL": 38,
"SERVO_FTW_MASK": 0b11101000,
"SIM_FTOWESC_ENA": 1,
"SERVO1_FUNCTION": 0,
"SERVO2_FUNCTION": 0,
"SERVO3_FUNCTION": 0,
"SERVO4_FUNCTION": 33,
"SERVO5_FUNCTION": 0,
"SERVO6_FUNCTION": 34,
"SERVO7_FUNCTION": 35,
"SERVO8_FUNCTION": 36,
})
self.customise_SITL_commandline(["--uartF=sim:fetteconewireesc"])
self.FETtecESC_safety_switch()
self.FETtecESC_esc_power_checks()
self.FETtecESC_btw_mask_checks()
self.FETtecESC_flight()
def PerfInfo(self):
self.set_parameter('SCHED_OPTIONS', 1) # enable gathering
# sometimes we need to trigger collection....
content = self.fetch_file_via_ftp("@SYS/tasks.txt")
self.delay_sim_time(5)
content = self.fetch_file_via_ftp("@SYS/tasks.txt")
self.progress("Got content (%s)" % str(content))
if "fast_loop" not in content:
raise NotAchievedException("Did not find fast_loop in content")
lines = content.split("\n")
if not lines[0].startswith("TasksV1"):
raise NotAchievedException("Expected TasksV1 as first line first not (%s)" % lines[0])
if not lines[1].startswith("fast_loop"):
raise NotAchievedException("Expected fast_loop first, not (%s)" % lines[1])
# last line is empty, so -2 here
if not lines[-2].startswith("AP_EFI::update"):
raise NotAchievedException("Expected EFI last not (%s)" % lines[-2])
def tests1a(self):
'''return list of all tests'''
ret = super(AutoTestCopter, self).tests() # about 5 mins and ~20 initial tests from autotest/common.py
ret.extend([
("NavDelayTakeoffAbsTime",
"Fly Nav Delay (takeoff)",
self.fly_nav_takeoff_delay_abstime), # 19s
("NavDelayAbsTime",
"Fly Nav Delay (AbsTime)",
self.fly_nav_delay_abstime), # 20s
("NavDelay",
"Fly Nav Delay",
self.fly_nav_delay), # 19s
("GuidedSubModeChange",
"Test submode change",
self.fly_guided_change_submode),
("MAV_CMD_CONDITION_YAW",
"Test response to MAV_CMD_CONDITION_YAW",
self.MAV_CMD_CONDITION_YAW),
("LoiterToAlt",
"Loiter-To-Alt",
self.fly_loiter_to_alt), # 25s
("PayLoadPlaceMission",
"Payload Place Mission",
self.fly_payload_place_mission), # 44s
("PrecisionLoiterCompanion",
"Precision Loiter (Companion)",
self.fly_precision_companion), # 29s
("PrecisionLandingSITL",
"Precision Landing drivers (SITL)",
self.fly_precision_landing_drivers), # 29s
("SetModesViaModeSwitch",
"Set modes via modeswitch",
self.test_setting_modes_via_modeswitch),
("SetModesViaAuxSwitch",
"Set modes via auxswitch",
self.test_setting_modes_via_auxswitch),
("AuxSwitchOptions",
"Test random aux mode options",
self.test_aux_switch_options),
("AuxFunctionsInMission",
"Test use of auxilliary functions in missions",
self.test_aux_functions_in_mission),
("AutoTune",
"Fly AUTOTUNE mode",
self.fly_autotune), # 73s
])
return ret
def tests1b(self):
'''return list of all tests'''
ret = ([
("ThrowMode", "Fly Throw Mode", self.fly_throw_mode),
("BrakeMode", "Fly Brake Mode", self.fly_brake_mode),
("RecordThenPlayMission",
"Use switches to toggle in mission, then fly it",
self.fly_square), # 27s
("ThrottleFailsafe",
"Test Throttle Failsafe",
self.fly_throttle_failsafe), # 173s
("GCSFailsafe",
"Test GCS Failsafe",
self.fly_gcs_failsafe), # 239s
# this group has the smallest runtime right now at around
# 5mins, so add more tests here, till its around
# 9-10mins, then make a new group
])
return ret
def tests1c(self):
'''return list of all tests'''
ret = ([
("BatteryFailsafe",
"Fly Battery Failsafe",
self.fly_battery_failsafe), # 164s
("VibrationFailsafe",
"Test Vibration Failsafe",
self.test_vibration_failsafe),
("StabilityPatch",
"Fly stability patch",
lambda: self.fly_stability_patch(30)), # 17s
("OBSTACLE_DISTANCE_3D",
"Test proximity avoidance slide behaviour in 3D",
self.OBSTACLE_DISTANCE_3D), # ??s
("AC_Avoidance_Proximity",
"Test proximity avoidance slide behaviour",
self.fly_proximity_avoidance_test), # 41s
("AC_Avoidance_Fence",
"Test fence avoidance slide behaviour",
self.fly_fence_avoidance_test),
("AC_Avoidance_Beacon",
"Test beacon avoidance slide behaviour",
self.fly_beacon_avoidance_test), # 28s
("BaroWindCorrection",
"Test wind estimation and baro position error compensation",
self.fly_wind_baro_compensation),
("SetpointGlobalPos",
"Test setpoint global position",
self.test_set_position_global_int),
("ThrowDoubleDrop",
"Test a more complicated drop-mode scenario",
self.ThrowDoubleDrop),
("SetpointGlobalVel",
"Test setpoint global velocity",
self.test_set_velocity_global_int),
("SplineTerrain",
"Test Splines and Terrain",
self.test_terrain_spline_mission),
])
return ret
def tests1d(self):
'''return list of all tests'''
ret = ([
("HorizontalFence",
"Test horizontal fence",
self.fly_fence_test), # 20s
("HorizontalAvoidFence",
"Test horizontal Avoidance fence",
self.fly_fence_avoid_test),
("MaxAltFence",
"Test Max Alt Fence",
self.fly_alt_max_fence_test), # 26s
("MinAltFence",
"Test Min Alt Fence",
self.fly_alt_min_fence_test), # 26s
("FenceFloorEnabledLanding",
"Test Landing with Fence floor enabled",
self.fly_fence_floor_enabled_landing),
("AutoTuneSwitch",
"Fly AUTOTUNE on a switch",
self.fly_autotune_switch), # 105s
("GPSGlitchLoiter",
"GPS Glitch Loiter Test",
self.fly_gps_glitch_loiter_test), # 30s
("GPSGlitchLoiter2",
"GPS Glitch Loiter Test2",
self.fly_gps_glitch_loiter_test2), # 30s
("GPSGlitchAuto",
"GPS Glitch Auto Test",
self.fly_gps_glitch_auto_test),
("ModeAltHold",
"Test AltHold Mode",
self.test_mode_ALT_HOLD),
("ModeLoiter",
"Test Loiter Mode",
self.loiter),
("SimpleMode",
"Fly in SIMPLE mode",
self.fly_simple),
("SuperSimpleCircle",
"Fly a circle in SUPER SIMPLE mode",
self.fly_super_simple), # 38s
("ModeCircle",
"Fly CIRCLE mode",
self.fly_circle), # 27s
("MagFail",
"Test magnetometer failure",
self.test_mag_fail),
("OpticalFlow",
"Test Optical Flow",
self.optical_flow),
("OpticalFlowLimits",
"Fly Optical Flow limits",
self.fly_optical_flow_limits), # 27s
("OpticalFlowCalibration",
"Fly Optical Flow calibration",
self.fly_optical_flow_calibration),
("MotorFail",
"Fly motor failure test",
self.fly_motor_fail),
("Flip",
"Fly Flip Mode",
self.fly_flip),
("CopterMission",
"Fly copter mission",
self.fly_auto_test), # 37s
("SplineLastWaypoint",
"Test Spline as last waypoint",
self.test_spline_last_waypoint),
("Gripper",
"Test gripper",
self.test_gripper), # 28s
("TestGripperMission",
"Test Gripper mission items",
self.test_gripper_mission),
("VisionPosition",
"Fly Vision Position",
self.fly_vision_position), # 24s
("ATTITUDE_FAST",
"Ensure ATTITUTDE_FAST logging works",
self.ATTITUDE_FAST),
("BaseLoggingRates",
"Ensure base logging rates as expected",
self.BaseLoggingRates),
("BodyFrameOdom",
"Fly Body Frame Odometry Code",
self.fly_body_frame_odom), # 24s
("GPSViconSwitching",
"Fly GPS and Vicon Switching",
self.fly_gps_vicon_switching),
])
return ret
def tests1e(self):
'''return list of all tests'''
ret = ([
("BeaconPosition",
"Fly Beacon Position",
self.fly_beacon_position), # 56s
("RTLSpeed",
"Fly RTL Speed",
self.fly_rtl_speed),
("Mount",
"Test Camera/Antenna Mount",
self.test_mount), # 74s
("MountYawVehicleForMountROI",
"Test Camera/Antenna Mount vehicle yawing for ROI",
self.MountYawVehicleForMountROI),
("Button",
"Test Buttons",
self.test_button),
("ShipTakeoff",
"Fly Simulated Ship Takeoff",
self.fly_ship_takeoff),
("RangeFinder",
"Test RangeFinder Basic Functionality",
self.test_rangefinder), # 23s
("BaroDrivers",
"Test Baro Drivers",
self.BaroDrivers),
("SurfaceTracking",
"Test Surface Tracking",
self.test_surface_tracking), # 45s
("Parachute",
"Test Parachute Functionality",
self.test_parachute),
("ParameterChecks",
"Test Arming Parameter Checks",
self.test_parameter_checks),
("ManualThrottleModeChange",
"Check manual throttle mode changes denied on high throttle",
self.fly_manual_throttle_mode_change),
("MANUAL_CONTROL",
"Test mavlink MANUAL_CONTROL",
self.test_manual_control),
("ZigZag",
"Fly ZigZag Mode",
self.fly_zigzag_mode), # 58s
("PosHoldTakeOff",
"Fly POSHOLD takeoff",
self.fly_poshold_takeoff),
("FOLLOW",
"Fly follow mode",
self.fly_follow_mode), # 80s
("RangeFinderDrivers",
"Test rangefinder drivers",
self.fly_rangefinder_drivers), # 62s
("RangeFinderDriversMaxAlt",
"Test rangefinder drivers - test max alt",
self.fly_rangefinder_drivers_maxalt), # 25s
("MaxBotixI2CXL",
"Test maxbotix rangefinder drivers",
self.fly_rangefinder_driver_maxbotix), # 62s
("MAVProximity",
"Test MAVLink proximity driver",
self.fly_proximity_mavlink_distance_sensor,
),
("ParameterValidation",
"Test parameters are checked for validity",
self.test_parameter_validation),
("AltTypes",
"Test Different Altitude Types",
self.test_altitude_types),
("PAUSE_CONTINUE",
"Test MAV_CMD_PAUSE_CONTINUE",
self.PAUSE_CONTINUE),
("RichenPower",
"Test RichenPower generator",
self.test_richenpower),
("IE24",
"Test IntelligentEnergy 2.4kWh generator",
self.test_ie24),
("LogUpload",
"Log upload",
self.log_upload),
])
return ret
# a wrapper around all the 2A,2B,2C..etc tests for travis
def tests2(self):
ret = ([])
ret.extend(self.tests2a())
ret.extend(self.tests2b())
return ret
def tests2a(self):
'''return list of all tests'''
ret = ([
# something about SITLCompassCalibration appears to fail
# this one, so we put it first:
("FixedYawCalibration",
"Test Fixed Yaw Calibration", # about 20 secs
self.test_fixed_yaw_calibration),
# we run this single 8min-and-40s test on its own, apart from
# requiring FixedYawCalibration right before it because without it, it fails to calibrate
("SITLCompassCalibration", # this autotest appears to interfere with FixedYawCalibration, no idea why.
"Test SITL onboard compass calibration",
self.test_mag_calibration),
])
return ret
def tests2b(self): # this block currently around 9.5mins here
'''return list of all tests'''
ret = ([
Test("MotorVibration",
"Fly motor vibration test",
self.fly_motor_vibration),
Test("DynamicNotches",
"Fly Dynamic Notches",
self.fly_dynamic_notches,
attempts=8),
Test("PositionWhenGPSIsZero",
"Ensure position doesn't zero when GPS lost",
self.test_copter_gps_zero),
Test("DynamicRpmNotches",
"Fly Dynamic Notches driven by ESC Telemetry",
self.fly_esc_telemetry_notches,
attempts=8),
Test("RefindGPS",
"Refind the GPS and attempt to RTL rather than continue to land",
self.RefindGPS),
Test("GyroFFT",
"Fly Gyro FFT",
self.fly_gyro_fft,
attempts=8),
Test("GyroFFTHarmonic",
"Fly Gyro FFT Harmonic Matching",
self.fly_gyro_fft_harmonic,
attempts=8),
Test("CompassReordering",
"Test Compass reordering when priorities are changed",
self.test_mag_reordering), # 40sec?
Test("CRSF",
"Test RC CRSF",
self.test_crsf), # 20secs ish
Test("MotorTest",
"Run Motor Tests",
self.test_motortest), # 20secs ish
Test("AltEstimation",
"Test that Alt Estimation is mandatory for ALT_HOLD",
self.test_alt_estimate_prearm), # 20secs ish
Test("EKFSource",
"Check EKF Source Prearms work",
self.test_ekf_source),
Test("GSF",
"Check GSF",
self.test_gsf),
Test("AP_Avoidance",
"ADSB-based avoidance",
self.AP_Avoidance),
Test("SMART_RTL",
"Check SMART_RTL",
self.test_SMART_RTL),
Test("FlyEachFrame",
"Fly each supported internal frame",
self.fly_each_frame),
Test("GPSBlending",
"Test GPS Blending",
self.test_gps_blending),
Test("DataFlash",
"Test DataFlash Block backend",
self.test_dataflash_sitl),
Test("DataFlashErase",
"Test DataFlash Block backend erase",
self.test_dataflash_erase),
Test("Callisto",
"Test Callisto",
self.test_callisto),
Test("PerfInfo",
"Test Scheduler PerfInfo output",
self.PerfInfo),
Test("Replay",
"Test Replay",
self.test_replay),
Test("FETtecESC",
"Test FETtecESC",
self.FETtecESC),
Test("GroundEffectCompensation_touchDownExpected",
"Test EKF's handling of touchdown-expected",
self.GroundEffectCompensation_touchDownExpected),
Test("GroundEffectCompensation_takeOffExpected",
"Test EKF's handling of takeoff-expected",
self.GroundEffectCompensation_takeOffExpected),
Test("WPNAV_SPEED",
"Change speed during misison",
self.WPNAV_SPEED),
Test("WPNAV_SPEED_UP",
"Change speed (up) during misison",
self.WPNAV_SPEED_UP),
Test("WPNAV_SPEED_DN",
"Change speed (down) during misison",
self.WPNAV_SPEED_DN),
Test("GPSForYaw",
"Moving baseline GPS yaw",
self.GPSForYaw),
("DefaultIntervalsFromFiles",
"Test setting default mavlink message intervals from files",
self.DefaultIntervalsFromFiles),
Test("GPSTypes",
"Test simulated GPS types",
self.GPSTypes),
Test("MultipleGPS",
"Test multi-GPS behaviour",
self.MultipleGPS),
Test("LogUpload",
"Log upload",
self.log_upload),
])
return ret
def testcan(self):
ret = ([
("CANGPSCopterMission",
"Fly copter mission",
self.fly_auto_test_using_can_gps),
])
return ret
def tests(self):
ret = []
ret.extend(self.tests1())
ret.extend(self.tests2())
return ret
def disabled_tests(self):
return {
"Parachute": "See https://github.com/ArduPilot/ardupilot/issues/4702",
"HorizontalAvoidFence": "See https://github.com/ArduPilot/ardupilot/issues/11525",
"AltEstimation": "See https://github.com/ArduPilot/ardupilot/issues/15191",
"GroundEffectCompensation_takeOffExpected": "Flapping",
"GroundEffectCompensation_touchDownExpected": "Flapping",
}
class AutoTestCopterTests1(AutoTestCopter):
def tests(self):
return self.tests1()
class AutoTestCopterTests1a(AutoTestCopter):
def tests(self):
return self.tests1a()
class AutoTestCopterTests1b(AutoTestCopter):
def tests(self):
return self.tests1b()
class AutoTestCopterTests1c(AutoTestCopter):
def tests(self):
return self.tests1c()
class AutoTestCopterTests1d(AutoTestCopter):
def tests(self):
return self.tests1d()
class AutoTestCopterTests1e(AutoTestCopter):
def tests(self):
return self.tests1e()
class AutoTestCopterTests2(AutoTestCopter):
def tests(self):
return self.tests2()
class AutoTestCopterTests2a(AutoTestCopter):
def tests(self):
return self.tests2a()
class AutoTestCopterTests2b(AutoTestCopter):
def tests(self):
return self.tests2b()
class AutoTestCAN(AutoTestCopter):
def tests(self):
return self.testcan()
|
samuelctabor/ardupilot
|
Tools/autotest/arducopter.py
|
Python
|
gpl-3.0
| 326,096
|
[
"Gaussian"
] |
225bccad737b23be470b0fa3d73d6fc548c4d8ec26bcf623d8831c2988e64cf2
|
#
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
import abc
import logging
import re
import sys
from io import IOBase
from logging import Handler, Logger, StreamHandler
from typing import IO, Optional
# 7-bit C1 ANSI escape sequences
ANSI_ESCAPE = re.compile(r'\x1B[@-_][0-?]*[ -/]*[@-~]')
def remove_escape_codes(text: str) -> str:
"""
Remove ANSI escapes codes from string. It's used to remove
"colors" from log messages.
"""
return ANSI_ESCAPE.sub("", text)
class LoggingMixin:
"""Convenience super-class to have a logger configured with the class name"""
_log: Optional[logging.Logger] = None
def __init__(self, context=None):
self._set_context(context)
@property
def log(self) -> Logger:
"""Returns a logger."""
if self._log is None:
self._log = logging.getLogger(self.__class__.__module__ + '.' + self.__class__.__name__)
return self._log
def _set_context(self, context):
if context is not None:
set_context(self.log, context)
class ExternalLoggingMixin:
"""Define a log handler based on an external service (e.g. ELK, StackDriver)."""
@property
@abc.abstractmethod
def log_name(self) -> str:
"""Return log name"""
@abc.abstractmethod
def get_external_log_url(self, task_instance, try_number) -> str:
"""Return the URL for log visualization in the external service."""
@property
@abc.abstractmethod
def supports_external_link(self) -> bool:
"""Return whether handler is able to support external links."""
# We have to ignore typing errors here because Python I/O classes are a mess, and they do not
# have the same type hierarchy defined as the `typing.IO` - they violate Liskov Substitution Principle
# While it is ok to make your class derive from IOBase (and its good thing to do as they provide
# base implementation for IO-implementing classes, it's impossible to make them work with
# IO generics (and apparently it has not even been intended)
# See more: https://giters.com/python/typeshed/issues/6077
class StreamLogWriter(IOBase, IO[str]): # type: ignore[misc]
"""Allows to redirect stdout and stderr to logger"""
encoding: None = None
def __init__(self, logger, level):
"""
:param log: The log level method to write to, ie. log.debug, log.warning
:return:
"""
self.logger = logger
self.level = level
self._buffer = ''
def close(self):
"""
Provide close method, for compatibility with the io.IOBase interface.
This is a no-op method.
"""
@property
def closed(self):
"""
Returns False to indicate that the stream is not closed, as it will be
open for the duration of Airflow's lifecycle.
For compatibility with the io.IOBase interface.
"""
return False
def _propagate_log(self, message):
"""Propagate message removing escape codes."""
self.logger.log(self.level, remove_escape_codes(message))
def write(self, message):
"""
Do whatever it takes to actually log the specified logging record
:param message: message to log
"""
if not message.endswith("\n"):
self._buffer += message
else:
self._buffer += message.rstrip()
self.flush()
def flush(self):
"""Ensure all logging output has been flushed"""
buf = self._buffer
if len(buf) > 0:
self._buffer = ''
self._propagate_log(buf)
def isatty(self):
"""
Returns False to indicate the fd is not connected to a tty(-like) device.
For compatibility reasons.
"""
return False
class RedirectStdHandler(StreamHandler):
"""
This class is like a StreamHandler using sys.stderr/stdout, but always uses
whatever sys.stderr/stderr is currently set to rather than the value of
sys.stderr/stdout at handler construction time.
"""
def __init__(self, stream):
if not isinstance(stream, str):
raise Exception(
"Cannot use file like objects. Use 'stdout' or 'stderr' as a str and without 'ext://'."
)
self._use_stderr = True
if 'stdout' in stream:
self._use_stderr = False
# StreamHandler tries to set self.stream
Handler.__init__(self)
@property
def stream(self):
"""Returns current stream."""
if self._use_stderr:
return sys.stderr
return sys.stdout
def set_context(logger, value):
"""
Walks the tree of loggers and tries to set the context for each handler
:param logger: logger
:param value: value to set
"""
_logger = logger
while _logger:
for handler in _logger.handlers:
# Not all handlers need to have context passed in so we ignore
# the error when handlers do not have set_context defined.
set_context = getattr(handler, 'set_context', None)
if set_context:
set_context(value)
if _logger.propagate is True:
_logger = _logger.parent
else:
_logger = None
|
bolkedebruin/airflow
|
airflow/utils/log/logging_mixin.py
|
Python
|
apache-2.0
| 6,012
|
[
"Elk"
] |
f37e7ee981d024ccc564a1e1438955fb4f1b8c5f0db4be55bc11abdf02270c7e
|
import numpy as np
import devito as dv
from devito.tools import as_tuple, as_list
from devito.builtins.utils import nbl_to_padsize, pad_outhalo
__all__ = ['assign', 'smooth', 'gaussian_smooth', 'initialize_function']
def assign(f, rhs=0, options=None, name='assign', **kwargs):
"""
Assign a list of RHSs to a list of Functions.
Parameters
----------
f : Function or list of Functions
The left-hand side of the assignment.
rhs : expr-like or list of expr-like, optional
The right-hand side of the assignment.
options : dict or list of dict, optional
Dictionary or list (of len(f)) of dictionaries containing optional arguments to
be passed to Eq.
name : str, optional
Name of the operator.
Examples
--------
>>> from devito import Grid, Function, assign
>>> grid = Grid(shape=(4, 4))
>>> f = Function(name='f', grid=grid, dtype=np.int32)
>>> g = Function(name='g', grid=grid, dtype=np.int32)
>>> h = Function(name='h', grid=grid, dtype=np.int32)
>>> functions = [f, g, h]
>>> scalars = [1, 2, 3]
>>> assign(functions, scalars)
>>> f.data
Data([[1, 1, 1, 1],
[1, 1, 1, 1],
[1, 1, 1, 1],
[1, 1, 1, 1]], dtype=int32)
>>> g.data
Data([[2, 2, 2, 2],
[2, 2, 2, 2],
[2, 2, 2, 2],
[2, 2, 2, 2]], dtype=int32)
>>> h.data
Data([[3, 3, 3, 3],
[3, 3, 3, 3],
[3, 3, 3, 3],
[3, 3, 3, 3]], dtype=int32)
"""
if not isinstance(rhs, list):
rhs = len(as_list(f))*[rhs, ]
eqs = []
if options:
for i, j, k in zip(as_list(f), rhs, options):
if k is not None:
eqs.append(dv.Eq(i, j, **k))
else:
eqs.append(dv.Eq(i, j))
else:
for i, j in zip(as_list(f), rhs):
eqs.append(dv.Eq(i, j))
dv.Operator(eqs, name=name, **kwargs)()
def smooth(f, g, axis=None):
"""
Smooth a Function through simple moving average.
Parameters
----------
f : Function
The left-hand side of the smoothing kernel, that is the smoothed Function.
g : Function
The right-hand side of the smoothing kernel, that is the Function being smoothed.
axis : Dimension or list of Dimensions, optional
The Dimension along which the smoothing operation is performed. Defaults
to ``f``'s innermost Dimension.
Notes
-----
More info about simple moving average available at: ::
https://en.wikipedia.org/wiki/Moving_average#Simple_moving_average
"""
if g.is_Constant:
# Return a scaled version of the input if it's a Constant
f.data[:] = .9 * g.data
else:
if axis is None:
axis = g.dimensions[-1]
dv.Operator(dv.Eq(f, g.avg(dims=axis)), name='smoother')()
def gaussian_smooth(f, sigma=1, truncate=4.0, mode='reflect'):
"""
Gaussian smooth function.
Parameters
----------
f : Function
The left-hand side of the smoothing kernel, that is the smoothed Function.
sigma : float, optional
Standard deviation. Default is 1.
truncate : float, optional
Truncate the filter at this many standard deviations. Default is 4.0.
mode : str, optional
The function initialisation mode. 'constant' and 'reflect' are
accepted. Default mode is 'reflect'.
"""
class ObjectiveDomain(dv.SubDomain):
name = 'objective_domain'
def __init__(self, lw):
super(ObjectiveDomain, self).__init__()
self.lw = lw
def define(self, dimensions):
return {d: ('middle', l, l) for d, l in zip(dimensions, self.lw)}
def create_gaussian_weights(sigma, lw):
weights = [w/w.sum() for w in (np.exp(-0.5/s**2*(np.linspace(-l, l, 2*l+1))**2)
for s, l in zip(sigma, lw))]
processed = []
for w in weights:
temp = list(w)
while len(temp) < 2*max(lw)+1:
temp.insert(0, 0)
temp.append(0)
processed.append(np.array(temp))
return as_tuple(processed)
def fset(f, g):
indices = [slice(l, -l, 1) for _, l in zip(g.dimensions, lw)]
slices = (slice(None, None, 1), )*g.ndim
if isinstance(f, np.ndarray):
f[slices] = g.data[tuple(indices)]
elif isinstance(f, dv.Function):
f.data[slices] = g.data[tuple(indices)]
else:
raise NotImplementedError
try:
# NOTE: required if input is an np.array
dtype = f.dtype.type
shape = f.shape
except AttributeError:
dtype = f.dtype
shape = f.shape_global
# TODO: Add s = 0 dim skip option
lw = tuple(int(truncate*float(s) + 0.5) for s in as_tuple(sigma))
if len(lw) == 1 and len(lw) < f.ndim:
lw = f.ndim*(lw[0], )
sigma = f.ndim*(as_tuple(sigma)[0], )
elif len(lw) == f.ndim:
sigma = as_tuple(sigma)
else:
raise ValueError("`sigma` must be an integer or a tuple of length" +
" `f.ndim`.")
# Create the padded grid:
objective_domain = ObjectiveDomain(lw)
shape_padded = tuple([np.array(s) + 2*l for s, l in zip(shape, lw)])
grid = dv.Grid(shape=shape_padded, subdomains=objective_domain)
f_c = dv.Function(name='f_c', grid=grid, space_order=2*max(lw),
coefficients='symbolic', dtype=dtype)
f_o = dv.Function(name='f_o', grid=grid, dtype=dtype)
weights = create_gaussian_weights(sigma, lw)
mapper = {}
for d, l, w in zip(f_c.dimensions, lw, weights):
lhs = []
rhs = []
options = []
lhs.append(f_o)
rhs.append(dv.generic_derivative(f_c, d, 2*l, 1))
coeffs = dv.Coefficient(1, f_c, d, w)
options.append({'coefficients': dv.Substitutions(coeffs),
'subdomain': grid.subdomains['objective_domain']})
lhs.append(f_c)
rhs.append(f_o)
options.append({'subdomain': grid.subdomains['objective_domain']})
mapper[d] = {'lhs': lhs, 'rhs': rhs, 'options': options}
# Note: generally not enough parallelism to be performant on a gpu device
# TODO: Add openacc support for CPUs and set platform = 'cpu64'
initialize_function(f_c, f, lw, mapper=mapper, mode='reflect', name='smooth')
fset(f, f_c)
return f
def initialize_function(function, data, nbl, mapper=None, mode='constant',
name=None, pad_halo=True, **kwargs):
"""
Initialize a Function with the given ``data``. ``data``
does *not* include the ``nbl`` outer/boundary layers; these are added via padding
by this function.
Parameters
----------
function : Function
The initialised object.
data : ndarray or Function
The data used for initialisation.
nbl : int or tuple of int or tuple of tuple of int
Number of outer layers (such as absorbing layers for boundary damping).
mapper : dict, optional
Dictionary containing, for each dimension of `function`, a sub-dictionary
containing the following keys:
1) 'lhs': List of additional expressions to be added to the LHS expressions list.
2) 'rhs': List of additional expressions to be added to the RHS expressions list.
3) 'options': Options pertaining to the additional equations that will be
constructed.
mode : str, optional
The function initialisation mode. 'constant' and 'reflect' are
accepted.
name : str, optional
The name assigned to the operator.
pad_halo : bool, optional
Whether to also pad the outer halo.
Examples
--------
In the following example the `'interior'` of a function is set to one plus
the value on the boundary.
>>> import numpy as np
>>> from devito import Grid, SubDomain, Function, initialize_function
Create the computational domain:
>>> grid = Grid(shape=(6, 6))
>>> x, y = grid.dimensions
Create the Function we wish to set along with the data to set it:
>>> f = Function(name='f', grid=grid, dtype=np.int32)
>>> data = np.full((4, 4), 2, dtype=np.int32)
Now create the additional expressions and options required to set the value of
the interior region to one greater than the boundary value. Note that the equation
is specified on the second (final) grid dimension so that additional equation is
executed after padding is complete.
>>> lhs = f
>>> rhs = f+1
>>> options = {'subdomain': grid.subdomains['interior']}
>>> mapper = {}
>>> mapper[y] = {'lhs': lhs, 'rhs': rhs, 'options': options}
Call the initialize_function routine:
>>> initialize_function(f, data, 1, mapper=mapper)
>>> f.data
Data([[2, 2, 2, 2, 2, 2],
[2, 3, 3, 3, 3, 2],
[2, 3, 3, 3, 3, 2],
[2, 3, 3, 3, 3, 2],
[2, 3, 3, 3, 3, 2],
[2, 2, 2, 2, 2, 2]], dtype=int32)
"""
name = name or 'pad_%s' % function.name
if isinstance(function, dv.TimeFunction):
raise NotImplementedError("TimeFunctions are not currently supported.")
if nbl == 0:
if isinstance(data, dv.Function):
function.data[:] = data.data[:]
else:
function.data[:] = data[:]
if pad_halo:
pad_outhalo(function)
return
nbl = nbl_to_padsize(nbl, function.ndim)
slices = tuple([slice(nl, -nr) for _, (nl, nr) in zip(range(function.grid.dim),
as_tuple(nbl))])
if isinstance(data, dv.Function):
function.data[slices] = data.data[:]
else:
function.data[slices] = data
lhs = []
rhs = []
options = []
if mode == 'reflect' and function.grid.distributor.is_parallel:
# Check that HALO size is appropriate
halo = function.halo
local_size = function.shape
def buff(i, j):
return [(i + k - 2*max(max(nbl))) for k in j]
b = [min(l) for l in (w for w in (buff(i, j) for i, j in zip(local_size, halo)))]
if any(np.array(b) < 0):
raise ValueError("Function `%s` halo is not sufficiently thick." % function)
for d, (nl, nr) in zip(function.space_dimensions, as_tuple(nbl)):
dim_l = dv.SubDimension.left(name='abc_%s_l' % d.name, parent=d, thickness=nl)
dim_r = dv.SubDimension.right(name='abc_%s_r' % d.name, parent=d, thickness=nr)
if mode == 'constant':
subsl = nl
subsr = d.symbolic_max - nr
elif mode == 'reflect':
subsl = 2*nl - 1 - dim_l
subsr = 2*(d.symbolic_max - nr) + 1 - dim_r
else:
raise ValueError("Mode not available")
lhs.append(function.subs({d: dim_l}))
lhs.append(function.subs({d: dim_r}))
rhs.append(function.subs({d: subsl}))
rhs.append(function.subs({d: subsr}))
options.extend([None, None])
if mapper and d in mapper.keys():
exprs = mapper[d]
lhs_extra = exprs['lhs']
rhs_extra = exprs['rhs']
lhs.extend(as_list(lhs_extra))
rhs.extend(as_list(rhs_extra))
options_extra = exprs.get('options', len(as_list(lhs_extra))*[None, ])
if isinstance(options_extra, list):
options.extend(options_extra)
else:
options.extend([options_extra])
if all(options is None for i in options):
options = None
assign(lhs, rhs, options=options, name=name, **kwargs)
if pad_halo:
pad_outhalo(function)
|
opesci/devito
|
devito/builtins/initializers.py
|
Python
|
mit
| 11,728
|
[
"Gaussian"
] |
6d641bf87638855f3404e182c7a8fce118cf42cf3c91bd9c7216b79fac6cddf6
|
"""HandleImport transformation takes care of importing user-defined modules."""
from pythran.passmanager import Transformation
from pythran.tables import cxx_keywords, MODULES, pythran_ward
from pythran.syntax import PythranSyntaxError
import ast
import importlib
import inspect
import logging
logger = logging.getLogger('pythran')
def add_filename_field(node, filename):
for descendant in ast.walk(node):
descendant.filename = filename
def mangle_imported_function_name(module_name, func_name):
"""Mangling naming scheme for imported functions."""
return pythran_ward + "imported__" + module_name + "_" + func_name
def is_builtin_function(func_name):
"""Test if a function is a builtin (like len(), map(), ...)."""
return (func_name in MODULES["__builtin__"] or
(func_name in cxx_keywords and
func_name + "_" in MODULES["__builtin__"]))
def is_builtin_module_name(module_name):
"""Test if a module is a builtin module (numpy, math, ...)."""
module_name = module_name.split(".")[0]
return (module_name in MODULES or
(module_name in cxx_keywords and module_name + "_" in MODULES))
def is_builtin_module(module):
"""Test if a module is a builtin module (numpy, math, ...)."""
return is_builtin_module_name(module.name)
def filter_builtinIn_import(import_node):
"""Filter out import list to keep only builtin modules."""
import_node.names = filter(is_builtin_module, import_node.names)
# Remove the import statement if no builtin module were present.
return import_node if import_node.names else None
class ImportFunction(ast.NodeTransformer):
"""
AST transformer that operates on a function that we need to import.
It visits each call inside the function and recursively import the
callees. The call site is modified to call the new imported function,
using name mangling.
"""
def __init__(self, registry, module, func_name):
self.registry = registry
self.module = module
self.func_name = func_name
self.nested_functions = dict()
def visit_FunctionDef(self, func_node):
"""Keep track of nested Function."""
self.nested_functions[func_node.name] = func_node
self.generic_visit(func_node)
return func_node
def visit_Import(self, import_node):
"""
Track local import.
This is "wrong" because we add these import like if they were global.
"""
for alias in import_node.names:
asname = alias.asname or alias.name
self.module.imported_modules[asname] = alias.name
return filter_builtinIn_import(import_node)
def visit_ImportFrom(self, importfrom_node):
"""
Track local import.
This is "wrong" because we add these import like if they were global.
"""
module_name = importfrom_node.module
for alias in importfrom_node.names:
func_name = alias.name
asname = alias.asname or func_name
self.module.imported_functions[asname] = (module_name,
func_name,
None)
if is_builtin_module_name(module_name):
return importfrom_node
def visit_Call(self, call_node):
"""Find any non-builtin and non-nested function call to pull the callee
as part of the import.
"""
self.generic_visit(call_node)
if isinstance(call_node.func, ast.Name):
# Direct call, resolve in the current module.
# Note: the function is not necessarily locally defined, it could
# be imported in the form "from bar import foo"
func_name = call_node.func.id
if func_name in self.nested_functions:
# Don't need to do anything in this case, nested function are
# implicitly imported with the current function
return call_node
# Import the function now, imply a recursion to import the callee
mangled_name = self.module.call_function(self.registry,
func_name)
# Patch the call site, replacing with the mangle name
call_node.func.id = mangled_name
elif (isinstance(call_node.func, ast.Attribute) and
isinstance(call_node.func.value, ast.Name)):
# This is a call in the form of something.function()
module_alias = call_node.func.value.id
func_name = call_node.func.attr
if module_alias not in self.module.imported_modules:
# This might be an import error, but it can also be that
# "something" in something.function() is not a module, for
# instance: list.append(...)
return call_node
module_name = self.module.imported_modules[module_alias]
module = self.registry.import_module(module_name)
# In case it a builtin module, add import with the correct alias
if isinstance(module, BuiltinModule):
self.module.dependent_modules[module_alias] = module_name
# Import the function from the module now, triggers a recursion
mangled_name = module.import_function(self.registry, func_name)
# Patch witch mangled name, force it for the main module as we want
# to tranform calls from main_module.foo() to simply foo()
if module.to_be_mangled or module.is_main_module:
# Patch the call, replace with the mangle name
call_node.func = ast.Name(id=mangled_name, ctx=ast.Load())
return call_node
class ImportedModule(object):
"""
Represent a user-defined imported module.
It offer an interface to import a function from this module, handling
automatically the import of all callees in the function.
"""
def __init__(self, name, module=None):
"""Parameters are the name for the module (mandatory), and the
ast.Module node (optional) in the case the current module is the main
one. This differentiation is needed to avoid mangling function name for
functions defined in the main module.
"""
self.is_main_module = True
self.node = module
if self.node is None:
# Not main module, parse now the imported module
self.is_main_module = False
imported_module = importlib.import_module(name)
self.node = ast.parse(inspect.getsource(imported_module))
assert isinstance(self.node, ast.Module)
# Recursively add filename information to all nodes, for debug msg
add_filename_field(self.node, name + ".py")
# Mangle function imported, unless it is the main module
self.to_be_mangled = not self.is_main_module
self.name = name
# Functions defined in this module and imported by another one.
# This dict is used at the end of the process to gather functions to be
# prepend at the beginning of the main pythran module
self.exported_functions = dict()
self.dependent_modules = dict()
# Top-level function declared in this module
self.functions = dict()
# Functions imported as "from somemodule import func as func_alias"
self.imported_functions = dict()
# Regular module import. Keys are alias and values are module names
self.imported_modules = dict()
# Collect top-level functions and imports
for decl in self.node.body:
if isinstance(decl, ast.FunctionDef): # regular functions
self.functions[decl.name] = decl
elif isinstance(decl, ast.Import): # Module import
for alias in decl.names:
asname = alias.asname or alias.name
self.imported_modules[asname] = alias.name
elif isinstance(decl, ast.ImportFrom): # Function import
module_name = decl.module
for alias in decl.names:
func_name = alias.name
asname = alias.asname or func_name
self.imported_functions[asname] = (module_name, func_name,
None)
elif isinstance(decl, ast.Assign):
# FIXME : We ignore import of globals
pass
else:
raise PythranSyntaxError('Unpythranizable module: %s' % name)
def call_function(self, registry, func_name):
"""Direct function call from another function of the current module,
try to find if it was imported from another module in the form of
"from module_name import foo", if it was not it has to be locally
defined.
Return the mangled name to be used at call site.
"""
if func_name in self.imported_functions:
module_name, realName, decl = self.imported_functions[func_name]
if not decl: # first time we call this function, import it.
decl = registry.import_module(module_name). \
call_function(registry, realName)
# Cache the fact that it has been imported now
self.imported_functions[func_name] = (module_name, realName,
decl)
if not registry.import_module(module_name).to_be_mangled:
# No mangling in the main module, nor in builtins
return realName
return mangle_imported_function_name(module_name, realName)
# Function not imported, hopefully it was locally defined, delegate!
return self.import_function(registry, func_name)
def import_function(self, registry, func_name):
"""
Called to import a function locally defined in this module.
Return the mangled name to be used at call site.
"""
if func_name in self.exported_functions: # Caching: already registered
return self.exported_functions[func_name].name
# Function is not defined locally, maybe it is an alias, like
# c = math.cos
# c()
# Just give up here and hope for the best!
if func_name not in self.functions:
return func_name
func = self.functions[func_name]
# Mangle function's name here so that module1.foo() and
# module2.foo() don't conflict
if self.to_be_mangled:
# No mangling in the main module
func.name = mangle_imported_function_name(self.name, func_name)
# Cache the processed function
self.exported_functions[func_name] = func
# Recursively visit the function to handle any callees
ImportFunction(registry, self, func.name).visit(func)
return func.name
class BuiltinModule(object):
"""
Represent a builtin module.
it offer the same interface as ImportedModule class, but do not try to
validate function imported from here.
"""
def __init__(self, name):
self.name = name
self.is_main_module = False
self.to_be_mangled = False
# For builtins module, exported_functions is only used to keep
# ImportFrom nodes, see call_function()
self.exported_functions = dict()
self.dependent_modules = dict()
def call_function(self, _, func_name):
# There was a direct call to a function from this builtin. It means it
# was imported in the caller module in the form: from builtin import
# foo. We need to add such node to be imported
importFrom = ast.ImportFrom(module=self.name,
names=[ast.alias(name=func_name,
asname=None)],
level=0) # FIXME what is level?
self.exported_functions[func_name] = importFrom
return func_name
def import_function(self, _, func_name):
# We could check if the function is supported by Pythran here...
return func_name
class ImportRegistry(object):
"""
Keep track of already imported modules.
It avoid duplication in case of diamond or reflective import. It keeps a
single ImportedModule() instance per module. Import has to use the
canonical name (not the aliased one).
"""
def __init__(self):
self.modules = dict() # List of modules already imported
def import_module(self, name):
"""Keep track of imported modules. Pythran-supported builtin modules
are handled using a dummy BuiltinModule() type, while user-defined
modules rely on ImportedModule() to provide an interface to import
function at call site
"""
if name in self.modules: # Caching
return self.modules[name]
if is_builtin_module_name(name):
mod = BuiltinModule(name)
else:
mod = ImportedModule(name)
self.modules[name] = mod
return mod
def generate_ImportList(self):
"""List of imported functions to be added to the main module. """
import_list = []
for mod in self.modules.values():
if mod.is_main_module:
# don't need to import anything from the main module
continue
for alias, module_name in mod.dependent_modules.items():
import_node = ast.Import(names=[ast.alias(name=module_name,
asname=alias)])
import_list.append(import_node)
# Here we import the function itself (FunctionDef node)
# In case of builtin module, it is an ImportFrom node.
import_list += mod.exported_functions.values()
return import_list
class HandleImport(Transformation):
"""This pass handle user-defined import, mangling name for function from
other modules and include them in the current module, patching all call
site accordingly.
"""
def __init__(self):
super(HandleImport, self).__init__()
self.registry = ImportRegistry()
def visit_Module(self, module):
"""Entry point for the module."""
# Do not use registry.import_module because this is the main module and
# ImportedModule takes an extra parameter in this case
self.module = ImportedModule(self.passmanager.module_name, module)
self.registry.modules[self.passmanager.module_name] = self.module
self.generic_visit(module)
# Patch module body: prepend all imported function and import nodes
imported = self.registry.generate_ImportList()
external_modules_name = [f for f in self.module.imported_modules
if not is_builtin_module_name(f)]
if not imported and external_modules_name:
# We can't raise an exception as it may just be an unused import.
# FIXME : To improve this, we have to handle aliasing so that we
# can know sys.stdout is not an attribute of class but a function
# call from a module even when the function is not defined (.so
# file for example)
logger.warn("Module : '" + "', '".join(external_modules_name) +
"' is imported but not used or can't be imported by "
"Pythran.")
module.body = imported + module.body
self.update |= bool(imported)
return module
@staticmethod
def visit_Import(import_node):
"""Filter out import node to keep only builtin modules."""
return filter_builtinIn_import(import_node)
@staticmethod
def visit_ImportFrom(import_node):
"""Filter out import node to keep only builtin modules."""
module_name = import_node.module
if is_builtin_module_name(module_name):
return import_node
def visit_FunctionDef(self, func):
"""Trigger dependent import for this function's body."""
self.module.call_function(self.registry, func.name)
return func
|
pbrunet/pythran
|
pythran/transformations/handle_import.py
|
Python
|
bsd-3-clause
| 16,323
|
[
"VisIt"
] |
7e7700e5bbd5124affaa67fcb2cdfffae298d7be99a80b53d6c35c143a9db43e
|
# -*- coding: iso-8859-1 -*-
"""
MoinMoin - convert content in 1.6.0alpha (rev 1844: 58ebb64243cc) wiki markup to 1.6.0 style
by using a modified 1.6.0alpha parser as translator.
PLEASE NOTE: most moin users will never need to execute this code,
because it is just for users of 1.6.0alpha version,
that used modified link markup, but was never released.
The 1.5.x/1.6.x releases use a different link markup than 1.6.0a.
@copyright: 2007 MoinMoin:JohannesBerg,
2007-2009 MoinMoin:ThomasWaldmann
@license: GNU GPL, see COPYING for details.
"""
import re
from MoinMoin import i18n
i18n.wikiLanguages = lambda: {}
from MoinMoin import config, macro, wikiutil
from MoinMoin.action import AttachFile
from MoinMoin.Page import Page
from MoinMoin.support.python_compatibility import rsplit
import wikiutil160a
from text_moin160a_wiki import Parser
QUOTE_CHARS = u"'\""
def convert_wiki(request, pagename, intext, renames):
""" Convert content written in wiki markup """
noeol = False
if not intext.endswith('\r\n'):
intext += '\r\n'
noeol = True
c = Converter(request, pagename, intext, renames)
result = request.redirectedOutput(c.convert, request)
if noeol and result.endswith('\r\n'):
result = result[:-2]
return result
STONEAGE_IMAGELINK = False # True for ImageLink(target,image), False for ImageLink(image,target)
# copied from moin 1.6.0 macro/ImageLink.py (to be safe in case we remove ImageLink some day)
# ... and slightly modified/refactored for our needs here.
# hint: using parse_quoted_separated from wikiutil does NOT work here, because we do not have
# quoted urls when they contain a '=' char in the 1.5 data input.
def explore_args(args):
""" explore args for positional and keyword parameters """
if args:
args = args.split(',')
args = [arg.strip() for arg in args]
else:
args = []
kw_count = 0
kw = {} # keyword args
pp = [] # positional parameters
kwAllowed = ('width', 'height', 'alt')
for arg in args:
if '=' in arg:
key, value = arg.split('=', 1)
key_lowerstr = str(key.lower())
# avoid that urls with "=" are interpreted as keyword
if key_lowerstr in kwAllowed:
kw_count += 1
kw[key_lowerstr] = value
elif not kw_count and '://' in arg:
# assuming that this is the image
pp.append(arg)
else:
pp.append(arg)
if STONEAGE_IMAGELINK and len(pp) >= 2:
pp[0], pp[1] = pp[1], pp[0]
return pp, kw
class Converter(Parser):
def __init__(self, request, pagename, raw, renames):
self.pagename = pagename
self.raw = raw
self.renames = renames
self.request = request
self._ = None
self.in_pre = 0
self.formatting_rules = self.formatting_rules % {'macronames': u'|'.join(['ImageLink', ] + macro.getNames(self.request.cfg))}
# no change
def return_word(self, word):
return word
_emph_repl = return_word
_emph_ibb_repl = return_word
_emph_ibi_repl = return_word
_emph_ib_or_bi_repl = return_word
_u_repl = return_word
_strike_repl = return_word
_sup_repl = return_word
_sub_repl = return_word
_small_repl = return_word
_big_repl = return_word
_tt_repl = return_word
_tt_bt_repl = return_word
_remark_repl = return_word
_table_repl = return_word
_tableZ_repl = return_word
_rule_repl = return_word
_smiley_repl = return_word
_smileyA_repl = return_word
_ent_repl = return_word
_ent_numeric_repl = return_word
_ent_symbolic_repl = return_word
_heading_repl = return_word
_email_repl = return_word
_notword_repl = return_word
_indent_repl = return_word
_li_none_repl = return_word
_li_repl = return_word
_ol_repl = return_word
_dl_repl = return_word
_comment_repl = return_word
# translate pagenames using pagename translation map
def _replace(self, key):
""" replace a item_name if it is in the renames dict
key is either a 2-tuple ('PAGE', pagename)
or a 3-tuple ('FILE', pagename, filename)
"""
current_page = self.pagename
item_type, page_name, file_name = (key + (None, ))[:3]
abs_page_name = wikiutil.AbsPageName(current_page, page_name)
if item_type == 'PAGE':
key = (item_type, abs_page_name)
new_name = self.renames.get(key)
if new_name is None:
# we don't have an entry in rename map - apply the same magic
# to the page name as 1.5 did (" " -> "_") and try again:
abs_magic_name = abs_page_name.replace(u' ', u'_')
key = (item_type, abs_magic_name)
new_name = self.renames.get(key)
if new_name is None:
# we didn't find it under the magic name either -
# that means we do not rename it!
new_name = page_name
if new_name != page_name and abs_page_name != page_name:
# we have to fix the (absolute) new_name to be a relative name (as it was before)
new_name = wikiutil.RelPageName(current_page, new_name)
elif item_type == 'FILE':
key = (item_type, abs_page_name, file_name)
new_name = self.renames.get(key)
if new_name is None:
# we don't have an entry in rename map - apply the same magic
# to the page name as 1.5 did (" " -> "_") and try again:
abs_magic_name = abs_page_name.replace(u' ', u'_')
key = (item_type, abs_magic_name, file_name)
new_name = self.renames.get(key)
if new_name is None:
# we didn't find it under the magic name either -
# that means we do not rename it!
new_name = file_name
return new_name
def _replace_target(self, target):
target_and_anchor = rsplit(target, '#', 1)
if len(target_and_anchor) > 1:
target, anchor = target_and_anchor
target = self._replace(('PAGE', target))
return '%s#%s' % (target, anchor)
else:
target = self._replace(('PAGE', target))
return target
# markup conversion
def _macro_repl(self, word):
# we use [[...]] for links now, macros will be <<...>>
macro_rule = ur"""
\[\[
(?P<macro_name>\w+)
(\((?P<macro_args>.*?)\))?
\]\]
"""
word = unicode(word) # XXX why is word not unicode before???
m = re.match(macro_rule, word, re.X|re.U)
macro_name = m.group('macro_name')
macro_args = m.group('macro_args')
if macro_name == 'ImageLink':
fixed, kw = explore_args(macro_args)
#print "macro_args=%r" % macro_args
#print "fixed=%r, kw=%r" % (fixed, kw)
image, target = (fixed + ['', ''])[:2]
if image is None:
image = ''
if target is None:
target = ''
if '://' not in image:
# if it is not a URL, it is meant as attachment
image = u'attachment:%s' % image
if not target:
target = image
elif target.startswith('inline:'):
target = 'attachment:' + target[7:] # we don't support inline:
elif target.startswith('wiki:'):
target = target[5:] # drop wiki:
image_attrs = []
alt = kw.get('alt') or ''
width = kw.get('width')
if width is not None:
image_attrs.append(u"width=%s" % width)
height = kw.get('height')
if height is not None:
image_attrs.append(u"height=%s" % height)
image_attrs = u", ".join(image_attrs)
if image_attrs:
image_attrs = u'|' + image_attrs
if alt or image_attrs:
alt = u'|' + alt
result = u'[[%s|{{%s%s%s}}]]' % (target, image, alt, image_attrs)
else:
if macro_args:
macro_args = u"(%s)" % macro_args
else:
macro_args = u''
result = u"<<%s%s>>" % (macro_name, macro_args)
# XXX later check whether some to be renamed pagename is used as macro param
return result
def _word_repl(self, word, text=None):
"""Handle WikiNames."""
if not text:
if wikiutil.isStrictWikiname(word):
return word
else:
return '[[%s]]' % word
else: # internal use:
return '[[%s|%s]]' % (word, text)
def _wikiname_bracket_repl(self, text):
"""Handle special-char wikinames with link text, like:
["Jim O'Brian" Jim's home page] or ['Hello "world"!' a page with doublequotes]
"""
word = text[1:-1] # strip brackets
first_char = word[0]
if first_char in QUOTE_CHARS:
# split on closing quote
target, linktext = word[1:].split(first_char, 1)
else: # not quoted
# split on whitespace
target, linktext = word.split(None, 1)
if target:
target = self._replace(('PAGE', target))
linktext = linktext.strip()
if linktext and linktext != target:
return '[[%s|%s]]' % (target, linktext)
else:
return '[[%s]]' % target
else:
return text
def _interwiki_repl(self, word):
"""Handle InterWiki links."""
wikitag, wikiurl, wikitail, wikitag_bad = wikiutil.resolve_wiki(self.request, word)
if wikitag_bad:
return word
else:
return self.interwiki("wiki:" + word)
def interwiki(self, target_and_text, **kw):
scheme, rest = target_and_text.split(':', 1)
wikiname, pagename, text = wikiutil160a.split_wiki(rest)
#if (pagename.startswith(wikiutil.CHILD_PREFIX) or # fancy link to subpage [wiki:/SubPage text]
# Page(self.request, pagename).exists()): # fancy link to local page [wiki:LocalPage text]
# # XXX OtherWiki:FooPage markup -> checks for local FooPage -sense???
# pagename = wikiutil.url_unquote(pagename)
# pagename = self._replace_target(pagename)
# return '[[%s%s]]' % (pagename, text)
if wikiname in ('Self', self.request.cfg.interwikiname, ''): # [wiki:Self:LocalPage text] or [:LocalPage:text]
orig_pagename = pagename
pagename = wikiutil.url_unquote(pagename)
pagename = self._replace_target(pagename)
camelcase = wikiutil.isStrictWikiname(pagename)
if camelcase and (not text or text == orig_pagename):
return pagename # optimize special case
else:
if text:
text = '|' + text
return '[[%s%s]]' % (pagename, text)
wikitag, wikiurl, wikitail, wikitag_bad = wikiutil.resolve_wiki(self.request, wikiname+':')
if wikitag_bad: # likely we got some /InterWiki as wikitail, we don't want that!
pagename = wikiutil.url_unquote(pagename)
pagename = self._replace_target(pagename)
wikitail = pagename
else: # good
wikitail = wikiutil.url_unquote(pagename)
# link to self?
if wikiutil.isPicture(wikitail):
return '{{%s:%s%s}}' % (wikitag, wikitail, text)
else:
if ' ' not in wikitail and not text:
return '%s:%s' % (wikitag, wikitail)
else:
if text:
text = '|' + text
return '[[%s:%s%s]]' % (wikitag, wikitail, text)
def attachment(self, target_and_text, **kw):
""" This gets called on attachment URLs """
_ = self._
scheme, fname, text = wikiutil160a.split_wiki(target_and_text)
pagename, fname = AttachFile.absoluteName(fname, self.pagename)
from_this_page = pagename == self.pagename
fname = self._replace(('FILE', pagename, fname))
#fname = wikiutil.url_unquote(fname)
#fname = self._replace(('FILE', pagename, fname))
pagename = self._replace(('PAGE', pagename))
if from_this_page:
name = fname
else:
name = "%s/%s" % (pagename, fname)
fn_txt = name
if text:
fn_txt += '|' + text
if scheme == 'drawing':
return "{{drawing:%s}}" % fn_txt
# check for image, and possibly return IMG tag (images are always inlined)
if not kw.get('pretty_url', 0) and wikiutil.isPicture(fname):
return "{{attachment:%s}}" % fn_txt
# inline the attachment
if scheme == 'inline':
return '{{attachment:%s}}' % fn_txt
return '[[attachment:%s]]' % fn_txt
def _url_repl(self, word):
"""Handle literal URLs including inline images."""
scheme = word.split(":", 1)[0]
if scheme == 'wiki':
return self.interwiki(word)
if scheme in self.attachment_schemas:
return '%s' % self.attachment(word)
if wikiutil.isPicture(word): # magic will go away in 1.6!
return '{{%s}}' % word # new markup for inline images
else:
return word
def _url_bracket_repl(self, word):
"""Handle bracketed URLs."""
word = word[1:-1] # strip brackets
# Local extended link? [:page name:link text] XXX DEPRECATED
if word[0] == ':':
words = word[1:].split(':', 1)
link, text = (words + ['', ''])[:2]
if link.strip() == text.strip():
text = ''
link = self._replace_target(link)
if text:
text = '|' + text
return '[[%s%s]]' % (link, text)
scheme_and_rest = word.split(":", 1)
if len(scheme_and_rest) == 1: # no scheme
# Traditional split on space
words = word.split(None, 1)
if words[0].startswith('#'): # anchor link
link, text = (words + ['', ''])[:2]
if link.strip() == text.strip():
text = ''
if text:
text = '|' + text
return '[[%s%s]]' % (link, text)
else:
scheme = scheme_and_rest[0]
if scheme == "wiki":
return self.interwiki(word, pretty_url=1)
if scheme in self.attachment_schemas:
m = self.attachment(word)
if scheme == 'attachment':
# with url_bracket markup, 1.6.0a parser does not embed pictures, but link!
return '[[%s]]' % m[2:-2]
else:
# drawing and inline
return m
words = word.split(None, 1)
if len(words) == 1:
words = words * 2
target, text = words
if wikiutil.isPicture(text) and re.match(self.url_rule, text):
return '[[%s|{{%s}}]]' % (target, text)
else:
if target == text:
return '[[%s]]' % target
else:
return '[[%s|%s]]' % (target, text)
def _parser_repl(self, word):
self.in_pre = 'no_parser'
return word
def _pre_repl(self, word):
w = word.strip()
if w == '{{{' and not self.in_pre:
self.in_pre = 'no_parser'
elif w == '}}}' and self.in_pre:
self.in_pre = None
return word
def scan(self, scan_re, line):
""" Scans one line - append text before match, invoke replace() with match, and add text after match. """
result = []
lastpos = 0
for match in scan_re.finditer(line):
# Add text before the match
if lastpos < match.start():
result.append(line[lastpos:match.start()])
# Replace match with markup
result.append(self.replace(match))
lastpos = match.end()
# Add remainder of the line
result.append(line[lastpos:])
return u''.join(result)
def replace(self, match):
""" Replace match using type name """
result = []
for _type, hit in match.groupdict().items():
if hit is not None and not _type in ["hmarker", ]:
# Get replace method and replace hit
replace = getattr(self, '_' + _type + '_repl')
# print _type, hit
result.append(replace(hit))
return ''.join(result)
else:
# We should never get here
import pprint
raise Exception("Can't handle match %r\n%s\n%s" % (
match,
pprint.pformat(match.groupdict()),
pprint.pformat(match.groups()),
))
return ""
def convert(self, request):
""" For each line, scan through looking for magic
strings, outputting verbatim any intervening text.
"""
self.request = request
# prepare regex patterns
rules = self.formatting_rules.replace('\n', '|')
if self.request.cfg.bang_meta:
rules = ur'(?P<notword>!%(word_rule)s)|%(rules)s' % {
'word_rule': self.word_rule,
'rules': rules,
}
pre_rules = r'''(?P<pre>\}\}\})'''
pre_scan_re = re.compile(pre_rules, re.UNICODE)
scan_re = re.compile(rules, re.UNICODE)
eol_re = re.compile(r'\r?\n', re.UNICODE)
rawtext = self.raw
# remove last item because it's guaranteed to be empty
self.lines = eol_re.split(rawtext)[:-1]
self.in_processing_instructions = True
# Main loop
for line in self.lines:
# ignore processing instructions
if self.in_processing_instructions:
found = False
for pi in ("##", "#format", "#refresh", "#redirect", "#deprecated",
"#pragma", "#form", "#acl", "#language"):
if line.lower().startswith(pi):
self.request.write(line + '\r\n')
found = True
break
if not found:
self.in_processing_instructions = False
else:
continue # do not parse this line
if not line.strip():
self.request.write(line + '\r\n')
else:
# Scan line, format and write
scanning_re = self.in_pre and pre_scan_re or scan_re
formatted_line = self.scan(scanning_re, line)
self.request.write(formatted_line + '\r\n')
|
RealTimeWeb/wikisite
|
MoinMoin/script/migration/_conv160a_wiki.py
|
Python
|
apache-2.0
| 19,189
|
[
"Brian"
] |
bc1f8dda94485f05e694cbc44496aa59c65da11319e0defc029df69f7c5bf16a
|
import os
import json
import requests
import multiprocessing
cwd = os.path.dirname(os.path.realpath(__file__))
num_requests = 3
key = ''
headers = {'Cache-Control': 'no-cache'}
post_url = ''
def get_code(url):
# Try loaing the site in 1 second
try:
requests.get(url, timeout=1, headers=headers, verify=False)
return 1
except:
pass
# Try loaing the site in 3 seconds
try:
requests.get(url, timeout=5, headers=headers, verify=False)
return 3
except:
pass
# Try loaing the site in 12 seconds
try:
requests.get(url, timeout=12, headers=headers, verify=False)
return 10
except:
return 30
def check(site):
code = 0
for i in xrange(num_requests):
code += get_code(site['url'])
params = {'name': site['name'], 'key': key}
if 3 <= code <= 5:
print '%s|GREEN' % site['name']
params['status'] = 'GREEN'
requests.post(post_url, params=params)
elif 6 <= code <= 30:
print '%s|AMBER' % site['name']
params['status'] = 'AMBER'
requests.post(post_url, params=params)
elif code > 30:
print '%s|RED' % site['name']
params['status'] = 'RED'
requests.post(post_url, params=params)
if __name__ == '__main__':
# Load up the JSON file
file_path = os.path.join(cwd, 'banks.json')
banks = json.loads(open(file_path).read())
# Create a list of banks to check
bank_list = []
for bank, meta in banks.iteritems():
bank_list.append({
'name': bank,
'url': meta['url']
})
# Process the files, determine canidates for clustering
pool = multiprocessing.Pool(processes=2)
pool.map(check, bank_list)
|
cloughrm/HTTP-Uptime-Monitor
|
status.py
|
Python
|
gpl-2.0
| 1,764
|
[
"Amber"
] |
aed0f0a724ef1bf00aed5d16b5cfb8396496630017ac9c60040740567819c791
|
import hashlib
import itsdangerous
import rollbar
from boto3.session import Session
from django.conf import settings
from django.http import HttpResponseBadRequest
from django.utils.translation import ugettext
from .signatures import signer
from .helpers import render
CONFIRMATION_PARAM = '__ctx'
def _send_mail(to, subject, body, email_format='Text'):
if settings.DEBUG:
print((to, subject, body))
session = Session(aws_access_key_id=settings.SES_ACCESS_ID,
aws_secret_access_key=settings.SES_SECRET_KEY,
region_name='us-east-1')
conn = session.client('ses')
resp = conn.send_email(
Source=settings.SENDER_EMAIL,
Destination={'ToAddresses': [to]},
Message={
'Subject': {
'Data': subject,
},
'Body': {
email_format: {
'Data': body,
},
},
},
ReplyToAddresses=[settings.SUPPORT_EMAIL],
ReturnPath=settings.ADMINS[0][1]
)
if not resp.get('MessageId'):
rollbar.report_message('Got bad response from SES: %s' % repr(resp), 'error')
def send_confirmation_email(user, subject, description, url, email=None):
email = email or user.email
signed_url = get_signed_url(url)
body = ugettext('''{description}
To confirm this request, visit the link below.
https://pinecast.com{url}
''').format(description=description, url=signed_url)
return send_notification_email(user, subject, body, email)
def send_notification_email(user, subject, description, email=None):
email = email or user.email
body = ugettext('''{greeting}
{description}
Thanks,
The Pinecast Team
''').format(
description=description,
greeting='Hey Pinecaster,' if user else 'Hi there,')
return _send_mail(email, subject, body)
def send_anon_confirmation_email(to, subject, body, url):
signed_url = get_signed_url(url)
constructed_body = ugettext('{body}\n\n{url}').format(
body=body,
url=signed_url if signed_url.startswith('http') else 'https://pinecast.com%s' % url
)
return _send_mail(to, subject, constructed_body)
def validate_confirmation(req, max_age=settings.EMAIL_CONFIRMATION_MAX_AGE):
full_path = req.get_full_path()
if CONFIRMATION_PARAM not in full_path:
rollbar.report_message('Confirmation URL without param (%s): %s' % (CONFIRMATION_PARAM, full_path), 'warning')
return False
param_loc = full_path.index(CONFIRMATION_PARAM)
trimmed_path = full_path[:param_loc - 1]
signed = req.GET.get(CONFIRMATION_PARAM)
try:
signature = signer.unsign(signed, max_age=max_age).decode('utf-8')
hashed_path = hashlib.sha1(trimmed_path.encode('utf-8')).hexdigest()
success = hashed_path == signature
if not success:
rollbar.report_message(
'Failed confirmation with mismatched hashes: %s != %s (via %s)' % (
signature, hashed_path, trimmed_path),
'warning')
return success
except itsdangerous.BadTimeSignature as e:
rollbar.report_message('Failed confirmation with bad time signature: %s' % str(e), 'warning')
return False
def request_must_be_confirmed(view):
def wrap(*args, **kwargs):
if not validate_confirmation(args[0]):
return get_expired_page(args[0])
return view(*args, **kwargs)
return wrap
def get_signed_url(url):
orig_url = url
prefix = ''
if '://' in url:
if url.startswith('https://'):
url = url[8:]
elif url.startswith('http://'):
url = url[7:]
if '/' not in url:
url = '/'
else:
url = url[url.find('/'):]
prefix = orig_url[:len(orig_url) - len(url)]
print((prefix, url, orig_url))
if not url.startswith('/'):
url = '/%s' % url
if '?' in url:
signed_url = '%s&' % url
else:
signed_url = '%s?' % url
token = hashlib.sha1(url.encode('utf-8')).hexdigest()
signed_url += '%s=%s' % (CONFIRMATION_PARAM, signer.sign(token).decode('utf-8'))
return prefix + signed_url
def get_expired_page(req):
return HttpResponseBadRequest(render(req, 'bad_signature.html'))
|
Pinecast/pinecast
|
pinecast/email.py
|
Python
|
apache-2.0
| 4,330
|
[
"VisIt"
] |
11df6239b31c0ac26346f7ab9309ca541c7c7f2316ff15901cf3c8012be0a457
|
# Copyright 2017-2020 The GPflow Contributors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import itertools
from functools import reduce
from typing import Type, Union
import tensorflow as tf
from .. import kernels
from .. import mean_functions as mfn
from ..inducing_variables import InducingPoints
from ..probability_distributions import DiagonalGaussian, Gaussian, MarkovGaussian
from . import dispatch
from .expectations import expectation
NoneType: Type[None] = type(None)
@dispatch.expectation.register(Gaussian, kernels.Sum, NoneType, NoneType, NoneType)
def _expectation_gaussian_sum(
p: Gaussian, kernel: kernels.Sum, _: None, __: None, ___: None, nghp: None = None
) -> tf.Tensor:
r"""
Compute the expectation:
<\Sum_i diag(Ki_{X, X})>_p(X)
- \Sum_i Ki_{.,.} :: Sum kernel
:return: N
"""
exps = [expectation(p, k, nghp=nghp) for k in kernel.kernels]
return reduce(tf.add, exps)
@dispatch.expectation.register(Gaussian, kernels.Sum, InducingPoints, NoneType, NoneType)
def _expectation_gaussian_sum_inducingpoints(
p: Gaussian,
kernel: kernels.Sum,
inducing_variable: InducingPoints,
_: None,
__: None,
nghp: None = None,
) -> tf.Tensor:
r"""
Compute the expectation:
<\Sum_i Ki_{X, Z}>_p(X)
- \Sum_i Ki_{.,.} :: Sum kernel
:return: NxM
"""
exps = [expectation(p, (k, inducing_variable), nghp=nghp) for k in kernel.kernels]
return reduce(tf.add, exps)
@dispatch.expectation.register(
Gaussian, (mfn.Linear, mfn.Identity, mfn.Constant), NoneType, kernels.Sum, InducingPoints
)
def _expectation_gaussian_linear__sum_inducingpoints(
p: Gaussian,
mean: Union[mfn.Linear, mfn.Identity, mfn.Constant],
_: None,
kernel: kernels.Sum,
inducing_variable: InducingPoints,
nghp: None = None,
) -> tf.Tensor:
r"""
Compute the expectation:
expectation[n] = <m(x_n)^T (\Sum_i Ki_{x_n, Z})>_p(x_n)
- \Sum_i Ki_{.,.} :: Sum kernel
:return: NxQxM
"""
exps = [expectation(p, mean, (k, inducing_variable), nghp=nghp) for k in kernel.kernels]
return reduce(tf.add, exps)
@dispatch.expectation.register(MarkovGaussian, mfn.Identity, NoneType, kernels.Sum, InducingPoints)
def _expectation_markov__sum_inducingpoints(
p: MarkovGaussian,
mean: mfn.Identity,
_: None,
kernel: kernels.Sum,
inducing_variable: InducingPoints,
nghp: None = None,
) -> tf.Tensor:
r"""
Compute the expectation:
expectation[n] = <x_{n+1} (\Sum_i Ki_{x_n, Z})>_p(x_{n:n+1})
- \Sum_i Ki_{.,.} :: Sum kernel
:return: NxDxM
"""
exps = [expectation(p, mean, (k, inducing_variable), nghp=nghp) for k in kernel.kernels]
return reduce(tf.add, exps)
@dispatch.expectation.register(
(Gaussian, DiagonalGaussian), kernels.Sum, InducingPoints, kernels.Sum, InducingPoints
)
def _expectation_gaussian_sum_inducingpoints__sum_inducingpoints(
p: Union[Gaussian, DiagonalGaussian],
kern1: kernels.Sum,
feat1: InducingPoints,
kern2: kernels.Sum,
feat2: InducingPoints,
nghp: None = None,
) -> tf.Tensor:
r"""
Compute the expectation:
expectation[n] = <(\Sum_i K1_i_{Z1, x_n}) (\Sum_j K2_j_{x_n, Z2})>_p(x_n)
- \Sum_i K1_i_{.,.}, \Sum_j K2_j_{.,.} :: Sum kernels
:return: NxM1xM2
"""
crossexps = []
if kern1 == kern2 and feat1 == feat2: # avoid duplicate computation by using transposes
for i, k1 in enumerate(kern1.kernels):
crossexps.append(expectation(p, (k1, feat1), (k1, feat1), nghp=nghp))
for k2 in kern1.kernels[:i]:
eKK = expectation(p, (k1, feat1), (k2, feat2), nghp=nghp)
eKK += tf.linalg.adjoint(eKK)
crossexps.append(eKK)
else:
for k1, k2 in itertools.product(kern1.kernels, kern2.kernels):
crossexps.append(expectation(p, (k1, feat1), (k2, feat2), nghp=nghp))
return reduce(tf.add, crossexps)
|
GPflow/GPflow
|
gpflow/expectations/sums.py
|
Python
|
apache-2.0
| 4,488
|
[
"Gaussian"
] |
04509f87f210a29ea2f294589d7418cdad204351f957de0a668e632e326c1735
|
#!/usr/bin/env python3
#* This file is part of the MOOSE framework
#* https://www.mooseframework.org
#*
#* All rights reserved, see COPYRIGHT for full restrictions
#* https://github.com/idaholab/moose/blob/master/COPYRIGHT
#*
#* Licensed under LGPL 2.1, please see LICENSE for details
#* https://www.gnu.org/licenses/lgpl-2.1.html
from .Input import OutputNames
from .PythonConsoleWidget import PythonConsoleWidget
from .ExodusViewer.ExodusViewer import ExodusViewer
from .PostprocessorViewer.PostprocessorViewer import PostprocessorViewer
from .utils import WidgetUtils
from .BasePeacockMainWindow import BasePeacockMainWindow
import mooseutils
from .PostprocessorViewer.VectorPostprocessorViewer import VectorPostprocessorViewer
from .Input.InputFileEditorWithMesh import InputFileEditorWithMesh
from .Execute.ExecuteTabPlugin import ExecuteTabPlugin
import os
class PeacockMainWindow(BasePeacockMainWindow):
"""
Main Peacock window.
This includes all the various tabs as well as some menus
"""
PLUGINS = [InputFileEditorWithMesh, ExecuteTabPlugin, ExodusViewer, PostprocessorViewer, VectorPostprocessorViewer]
def __init__(self, **kwds):
super(PeacockMainWindow, self).__init__(plugins=self.PLUGINS, **kwds)
self.setObjectName("PeacockMainWindow")
self.setWindowTitle("Peacock")
self.console = PythonConsoleWidget()
self.exe_path = ""
self.input_file_path = ""
self.tab_plugin.ExecuteTabPlugin.executableInfoChanged.connect(self._executableChanged)
self.tab_plugin.ExecuteTabPlugin.startJob.connect(self._startJob)
self.tab_plugin.ExecuteTabPlugin.needInputFile.connect(self.tab_plugin.InputFileEditorWithMesh.InputFileEditorPlugin.writeInputFile)
self.tab_plugin.InputFileEditorWithMesh.inputFileChanged.connect(self._inputFileChanged)
self.tab_plugin.ExecuteTabPlugin.ExecuteOptionsPlugin.workingDirChanged.connect(self.tab_plugin.InputFileEditorWithMesh.onWorkingDirChanged)
self.tab_plugin.ExecuteTabPlugin.ExecuteOptionsPlugin.useTestObjectsChanged.connect(self.tab_plugin.InputFileEditorWithMesh.onUseTestObjectsChanged)
self.setPythonVariable('main_window', self)
self.setPythonVariable('tabs', self.tab_plugin)
self.setup()
@staticmethod
def commandLineArgs(parser):
BasePeacockMainWindow.commandLineArgs(parser, PeacockMainWindow.PLUGINS)
def initialize(self, options):
curr_dir = ""
if options.working_dir:
curr_dir = os.path.abspath(options.working_dir)
super(PeacockMainWindow, self).initialize(options)
if options.working_dir:
# if the input file is set then it will change directory to where
# it exists. We need to honor the command line switch for the working dir.
self.tab_plugin.ExecuteTabPlugin.ExecuteOptionsPlugin.setWorkingDir(curr_dir)
self._setTitle()
def _showConsole(self):
"""
Toggles showing the python console widget
"""
if self.console.isVisible():
self.console.hide()
else:
self.console.show()
def setPythonVariable(self, name, value):
"""
This just passes on the arguments to the python console.
This is used to add objects to the python console.
Input:
name: name of the variable
value: value of the variable
"""
self.console.setVariable(name, value)
def _executableChanged(self, app_info):
"""
Slot called when the executable has changed.
"""
self.setPythonVariable("app_info", app_info)
self.exe_path = app_info.path
self._setTitle()
def _inputFileChanged(self, input_filename):
"""
Slot for when the input file has changed.
Note that comes from the input tab widget so we don't
need to update it.
Input:
input_filename: Name of the new input_filename
"""
self.input_file_path = input_filename
full_filename = os.path.abspath(input_filename)
new_dir = os.path.dirname(full_filename)
self.tab_plugin.ExecuteTabPlugin.ExecuteOptionsPlugin.setWorkingDir(new_dir)
self.tab_plugin.ExecuteTabPlugin.ExecuteRunnerPlugin.setInputFile(full_filename)
self._setTitle()
def setTab(self, tabName):
"""
Set the selected tab by name.
Normally you select by index or QWidget.
Input:
tabname: str: Title of the tab to be selected.
"""
for idx in range(self.tab_plugin.count()):
if self.tab_plugin.tabText(idx) == tabName:
self.tab_plugin.setCurrentIndex(idx)
return
def _setTitle(self):
"""
Sets the title of the window.
"""
title = "Peacock"
if self.exe_path:
title += " : executable - %s" % os.path.abspath(self.exe_path)
if self.input_file_path:
title += " : input file - %s" % os.path.abspath(self.input_file_path)
self.setWindowTitle(title)
def _startJob(self, csv, inputfile, t):
"""
This gets called when a job has started on the execute tab
Input:
csv[bool]: Whether CSV output has been requested
inputfile[str]: Path of the input file that will be used
t[float]: Time at which job started
"""
tree = self.tab_plugin.InputFileEditorWithMesh.InputFileEditorPlugin.tree
output_files = OutputNames.getOutputFiles(tree, inputfile)
if output_files:
mooseutils.mooseMessage("Exodus filenames: %s" % output_files)
self.tab_plugin.ExodusViewer.onStartJob(csv, inputfile, t)
self.tab_plugin.ExodusViewer.onSetFilenames(output_files)
if csv or OutputNames.csvEnabled(tree):
pp_files = OutputNames.getPostprocessorFiles(tree, inputfile)
if pp_files:
mooseutils.mooseMessage("Postprocessor filenames: %s" % pp_files)
self.tab_plugin.PostprocessorViewer.onStartJob(csv, inputfile, t)
self.tab_plugin.PostprocessorViewer.onSetFilenames(pp_files)
vpp_files = OutputNames.getVectorPostprocessorFiles(tree, inputfile)
if vpp_files:
mooseutils.mooseMessage("VectorPostprocessor filenames: %s" % vpp_files)
self.tab_plugin.VectorPostprocessorViewer.onSetFilenames(vpp_files)
def _addMenus(self):
"""
Internal method to allow plugins to add menus to the main menu bar.
"""
super(PeacockMainWindow, self)._addMenus()
menubar = self.menuBar()
debug_menu = menubar.addMenu("Debug")
WidgetUtils.addAction(debug_menu, "Show Python Console", self._showConsole, "Ctrl+P", True)
if __name__ == "__main__":
from PyQt5.QtWidgets import QApplication
import argparse, sys
app = QApplication(sys.argv)
parser = argparse.ArgumentParser()
PeacockMainWindow.commandLineArgs(parser)
main = PeacockMainWindow()
main.show()
main.initialize(parser.parse_args())
sys.exit(app.exec_())
|
nuclear-wizard/moose
|
python/peacock/PeacockMainWindow.py
|
Python
|
lgpl-2.1
| 7,195
|
[
"MOOSE"
] |
b20d97d5c0710afaf8e55e694827abcf3dae3cd6217a5825783d906374195371
|
#!/usr/bin/env python3
#* This file is part of the MOOSE framework
#* https://www.mooseframework.org
#*
#* All rights reserved, see COPYRIGHT for full restrictions
#* https://github.com/idaholab/moose/blob/master/COPYRIGHT
#*
#* Licensed under LGPL 2.1, please see LICENSE for details
#* https://www.gnu.org/licenses/lgpl-2.1.html
import os
import sys
import re
import glob
import tarfile
if sys.version_info[0] == 3:
import enum
import urllib.request
import urllib.error
else:
import urllib2
import collections
import logging
DEFAULT_JOBS_CACHE = os.path.join(os.getenv('HOME'), '.local', 'share', 'civet', 'jobs')
DEFAULT_CIVET_SITE = 'https://civet.inl.gov'
DEFAULT_CIVET_REPO = 'idaholab/moose'
TEST_RE = re.compile(r'^(?:\[(?P<time>.+?)s\])?' # Optional test time
r' *(?P<status>[A-Z]+?)' # Test status (e.g., OK)
r' +(?P<test>.*?)' # Test name
r'(?: +(?P<reason>.*?))?' # reason FAILED (FAILED (ERRORMSG))
r'(?: *\[(?P<caveats>.*?)\])?$', # Test caveats (e.g., [min_cpus=1])
flags=re.MULTILINE)
JOB_RE = re.compile(r'id=\"job_(?P<job>\d+)\"')
RECIPE_RE = re.compile(r'results_(?P<number>\d+)_(?P<job>.*)/(?P<recipe>.*)')
RUN_TESTS_START_RE = re.compile(r'^.+?run_tests.+?$', flags=re.MULTILINE)
RUN_TESTS_END_RE = re.compile(r'^-{5,}$', flags=re.MULTILINE)
RESULT_FILENAME_RE = re.compile(r'results_(?P<number>[0-9]+)_(?P<recipe>.*)\.tar\.gz')
Test = collections.namedtuple('Test', 'recipe status caveats reason time url')
Job = collections.namedtuple('Job', 'number filename status url')
if sys.version_info[0] == 3:
class JobFileStatus(enum.Enum):
"""Status flag for Job file downloads"""
CACHE = 0
LOCAL = 1
DOWNLOAD = 2
FAIL = 3
else:
class JobFileStatus(object):
"""Status flag for Job file downloads"""
CACHE = 0
LOCAL = 1
DOWNLOAD = 2
FAIL = 3
def _get_local_civet_jobs(location, logger=None):
"""
Get a list of Job objects for the supplied directory; this searches for tar.gz files with the
name as: results_<JOB>_*.tar.gz.
"""
jobs = set()
for filename in glob.glob(os.path.join(location, 'results_*.tar.gz')):
match = RESULT_FILENAME_RE.search(filename)
if match:
jobs.add(Job(int(match.group('number')), filename, JobFileStatus.LOCAL, None))
return sorted(jobs, key=lambda j: j.number)
def _get_remote_civet_jobs(hashes, site, repo, cache=DEFAULT_JOBS_CACHE, logger=None):
"""
Get a list of Job objects for the supplied git SHA1 strings.
"""
jobs = set()
for sha1 in hashes:
url = '{}/sha_events/{}/{}'.format(site, repo, sha1)
if sys.version_info[0] == 3:
pid = urllib.request.urlopen(url)
else:
pid = urllib2.urlopen(url)
page = pid.read().decode('utf8')
for match in JOB_RE.finditer(page):
job = jobs.add(_download_job(int(match.group('job')), site, cache, logger))
return sorted(jobs, key=lambda j: j.number)
def _download_job(job, site, cache, logger):
"""
Download, if it doesn't already exist, the raw data file from CIVET testing given a Job object.
"""
if not os.path.isdir(cache):
os.makedirs(cache)
url = '{}/job_results/{}'.format(site, job)
filename = '{}/results_{}.tar.gz'.format(cache, job)
status = None
if os.path.isfile(filename):
if logger:
logger.debug('Using cached results for job %s', job)
status = JobFileStatus.CACHE
else:
try:
if sys.version_info[0] == 3:
response = urllib.request.urlopen(url)
else:
response = urllib2.urlopen(url)
if response.code == 200:
if logger:
logger.debug('Downloading results for job %s', job)
with open(filename, 'wb') as fid:
fid.write(response.read())
status = JobFileStatus.DOWNLOAD
except urllib.error.HTTPError:
if logger:
logger.warning('Failed to download results for job %s: %s', job, url)
status = JobFileStatus.FAIL
return Job(job, filename, status, site)
def _update_database_from_job(job, database, possible):
"""
Update the test result database given a Job object.
"""
if job.status == JobFileStatus.FAIL:
return
tar = tarfile.open(job.filename, 'r:gz')
for member in tar.getmembers():
match = RECIPE_RE.search(member.name)
recipe = match.group('recipe')
number = int(match.group('number'))
f = tar.extractfile(member)
if f is not None:
content = f.read().decode('utf8')
begin = RUN_TESTS_START_RE.search(content)
if begin is None:
continue
end = RUN_TESTS_END_RE.search(content)
if end is not None:
_process_results(database, job, recipe, content[begin.end():end.start()], possible)
def _process_results(database, job, recipe, content, possible):
"""
Extract results from run_tests and update the database.
"""
for match in TEST_RE.finditer(content):
caveats = match.group('caveats')
reason = match.group('reason')
if caveats is not None:
caveats = caveats.split(',')
time = match.group('time')
if time is not None:
time = float(time)
tname = match.group('test').split(':')[-1]
status = match.group('status')
if (possible is None) or (status in possible):
url = job.url if job.url is not None else job.filename
database[tname][job.number].append(Test(recipe, status, caveats, reason, time, url))
def get_civet_results(local=list(),
hashes=list(),
sites=[(DEFAULT_CIVET_SITE, DEFAULT_CIVET_REPO)],
possible=None,
cache=DEFAULT_JOBS_CACHE, logger=None):
database = collections.defaultdict(lambda: collections.defaultdict(list))
for loc in local:
jobs = _get_local_civet_jobs(loc, logger=logger)
for job in jobs:
_update_database_from_job(job, database, possible)
for site, repo in sites:
jobs = _get_remote_civet_jobs(hashes, site, repo, cache=cache, logger=logger)
for job in jobs:
_update_database_from_job(job, database, possible)
return database
if __name__ == '__main__':
#database = get_civet_results(hashes=['681ba2f4274dc8465bb2a54e1353cfa24765a5c1',
# 'febe3476040fe6af1df1d67e8cc8c04c4760afb6'])
database = get_civet_results(sites=[],
local=['/Users/slauae/projects/moose/python/MooseDocs/test/content/civet'])
|
nuclear-wizard/moose
|
python/mooseutils/civet_results.py
|
Python
|
lgpl-2.1
| 6,960
|
[
"MOOSE"
] |
c316a66b675d7ad695918d2aa7edf99059bd6dbc31c31afaf2d280978e578036
|
# -*- coding: utf-8 -*-
"""Unit tests for functions calling bowtie externally."""
from pathlib2 import Path
import pytest
from imfusion.external import star
# pylint: disable=no-self-use,redefined-outer-name
class TestStarIndex(object):
"""Unit tests for the star_index function."""
def test_call(self, mocker, tmpdir):
"""Tests example call."""
mock_run = mocker.patch.object(star, 'run_command')
output_dir = Path(str(tmpdir / 'out'))
star.star_index(
Path('reference.fa'),
gtf_path=Path('reference.gtf'),
output_dir=output_dir,
overhang=50)
mock_run.assert_called_once_with(
args=[
'STAR', '--runMode', 'genomeGenerate', '--genomeDir',
str(output_dir), '--genomeFastaFiles', 'reference.fa',
'--sjdbGTFfile', 'reference.gtf', '--sjdbOverhang', '50',
'--runThreadN', '1'
],
log_path=None)
@pytest.fixture
def star_align_kws(tmpdir):
"""Example kws for star_align."""
output_dir = Path(str(tmpdir / 'out'))
return {
'fastq_path': Path('sample.R1.fastq.gz'),
'index_path': Path('index'),
'output_dir': output_dir
}
class TestStarAlign(object):
"""Unit tests for the star_align function."""
def test_basic_call(self, mocker, star_align_kws):
"""Tests example call."""
mock_run = mocker.patch.object(star, 'run_command')
star.star_align(**star_align_kws)
mock_run.assert_called_once_with(
args=[
'STAR', '--genomeDir', 'index', '--outFileNamePrefix',
str(star_align_kws['output_dir']) + '/', '--readFilesIn',
'sample.R1.fastq.gz', '--readFilesCommand', 'gunzip', '-c'
],
log_path=None)
def test_basic_without_gzip(self, mocker, star_align_kws):
"""Tests example without gzipped input."""
mock_run = mocker.patch.object(star, 'run_command')
star_align_kws['fastq_path'] = Path('sample.R1.fastq')
star.star_align(**star_align_kws)
mock_run.assert_called_once_with(
args=[
'STAR', '--genomeDir', 'index', '--outFileNamePrefix',
str(star_align_kws['output_dir']) + '/', '--readFilesIn',
'sample.R1.fastq'
],
log_path=None)
def test_paired_end(self, mocker, star_align_kws):
"""Tests example call with paired-end data."""
mock_run = mocker.patch.object(star, 'run_command')
star_align_kws['fastq2_path'] = 'sample.R2.fastq.gz'
star.star_align(**star_align_kws)
mock_run.assert_called_once_with(
args=[
'STAR', '--genomeDir', 'index', '--outFileNamePrefix',
str(star_align_kws['output_dir']) + '/', '--readFilesIn',
'sample.R1.fastq.gz', 'sample.R2.fastq.gz',
'--readFilesCommand', 'gunzip', '-c'
],
log_path=None)
def test_extra_arguments(self, mocker, star_align_kws):
"""Tests example call with extra arguments."""
mock_run = mocker.patch.object(star, 'run_command')
star_align_kws['extra_args'] = {'--outSAMtype': 'Unsorted'}
star.star_align(**star_align_kws)
mock_run.assert_called_once_with(
args=[
'STAR', '--genomeDir', 'index', '--outFileNamePrefix',
str(star_align_kws['output_dir']) + '/', '--readFilesIn',
'sample.R1.fastq.gz', '--outSAMtype', 'Unsorted',
'--readFilesCommand', 'gunzip', '-c'
],
log_path=None)
def test_multiple_threads(self, mocker, star_align_kws):
"""Tests example call with extra arguments."""
mock_run = mocker.patch.object(star, 'run_command')
star_align_kws['threads'] = 5
star.star_align(**star_align_kws)
mock_run.assert_called_once_with(
args=[
'STAR', '--genomeDir', 'index', '--outFileNamePrefix',
str(star_align_kws['output_dir']) + '/', '--readFilesIn',
'sample.R1.fastq.gz', '--readFilesCommand', 'gunzip', '-c',
'--runThreadN', '5'
],
log_path=None)
|
NKI-CCB/imfusion
|
tests/imfusion/external/test_ext_star.py
|
Python
|
mit
| 4,343
|
[
"Bowtie"
] |
5b60400c02c0084710395aebe4dca8ae124c64ae509b9906cd87a89e1b4ea812
|
import numpy
import scipy.stats.kde as kde
import scipy.ndimage as ndimage
def viterbi(p_observations_given_state, p_transition, p_initial):
"""Given an HMM and set of observations, identify the most likely state
sequence to have generated the observations using the Viterbi algorithm.
This implements a generalization of the Viterbi algorithm where the
transition probabilities may be specified in such a way as to change from
observation to observation. (Formally, this could be modeled as a HMM with
a new set of states for each observation, but that is more complex.) This
allows for modeling of processes like lifespan where age can modify the
probability of state transition (e.g. death).
Paramters:
(Let N be the number of observations and S the number of states.)
p_observations_given_state: Array of shape (N, S), where element [t, s]
is the probability of the observation at time t assuming the system
was in fact in state s.
p_transition: Array of shape (S, S), where element [si, sj] is the
probability of transitioning from state si to state sj.
Alternately, array of shape (N-1, S, S) where [t, si, sj] is the
probability of transition from state si to state sj between time t
and time t+1.
Note that in either case, p_transition must sum to 1 across the sj's.
p_initial: List of length S giving the proability of starting out in each
state. Must sum to 1.
Returns: list of length N giving the index of each state at each time, for
the most likely path through the states.
"""
p_observations_given_state = numpy.asarray(p_observations_given_state)
p_transition = numpy.asarray(p_transition)
p_initial = numpy.asarray(p_initial)
N, S = p_observations_given_state.shape
assert p_transition.shape in {(S, S), (N-1, S, S)}
if p_transition.shape == (S, S):
p_transition = numpy.array([p_transition for i in range(N-1)])
assert numpy.allclose(numpy.sum(p_transition, axis=2), 1)
assert p_initial.shape == (S,)
assert numpy.allclose(numpy.sum(p_initial), 1)
# convert all probabilities to log probabilities so we can sum instead of
# multiplying, which better controls numerical error.
err = numpy.seterr(divide='ignore') # allow log(0) to go to -inf, as desired
lp_observations_given_state = numpy.log(p_observations_given_state)
lp_transition = numpy.log(p_transition)
lp_initial = numpy.log(p_initial)
numpy.seterr(**err)
states = numpy.arange(S)
# path[i] always contains the maximum likelihood sequence of states ending at state i
path = [[i] for i in states]
# lp_state contains the current log probability of being in the state given the sequence
# of observations thus far considered.
lp_state = lp_observations_given_state[0] + lp_initial
for lp_obs, lp_trans in zip(lp_observations_given_state[1:], lp_transition):
# For each observation after the first timepoint, construct an (S, S)
# shape array where [si, sj] contains the log probability of going from
# state si to state sj between time t and t+1.
# Assume we know for each state si prob(si at time t), the probability
# of being in that state at that time, then we can calculate the probability
# of being in any given state sj at time t+1:
# prob(transition from si at time t to sj at time t+1) = prob(si at t) *
# prob(si->sj between t and t+1) *
# prob(observation at t+1 given state sj)
# prob(j at time t+1) = max_i(prob(i at time t -> j at time t+1))
#
# Thus we merely need to keep updating our estimates for the probability
# of being in each state at each time, and keep a list of the path that
# lead to each state.
#
# The actual code in use is 100% equivalent to the code below; however it
# is rather more efficient.
#
# lp_transition_t = numpy.zeros((s, s), dtype=float)
# new_path = []
# lp_state = []
# for s_to in states:
# best_from_lp = -numpy.inf
# for s_from in states:
# lp_transition_t[s_from, s_to] = lp_state[s_from] + lp_trans[s_from, s_to] + lp_obs[s_to]
# if lp_transition_t[s_from, s_to] > best_from_lp:
# best_from = s_from
# best_from_lp = lp_transition_t[s_from, s_to]
# lp_state.append(best_from_lp)
# new_path.append(path[best_from] + [s_to])
# path = new_path
lp_transition_t = lp_state[:,numpy.newaxis] + lp_trans + lp_obs[numpy.newaxis,:]
best_from = numpy.argmax(lp_transition_t, axis=0)
path = [path[s_from]+[s_to] for s_to, s_from in enumerate(best_from)]
lp_state = lp_transition_t[best_from, states]
last_state = numpy.argmax(lp_state)
return numpy.array(path[last_state])
class ObservationProbabilityEstimator:
def __init__(self, state_observations, continuous=True, pseudocount=1):
"""Given a set of observations known to belong to different states,
construct an object that will estimate the probability that new observations
belong to each state (i.e. the p_observations_given_state matrix)
Parameters:
state_observations: list of length S containing an array of observation
data for each state.
continuous: if True, the observation data is assumed to be continuous.
If false, the data will be treated as categorical observations from
0 to to the maximum value seen across any observation.
pseudocount: if data are treated as categorical, add the specified
pseudocount to each category, to prevent zero-probability estimates.
"""
self.continuous = continuous
state_observations = [numpy.asarray(so) for so in state_observations]
if continuous:
self.state_distributions = [kde.gaussian_kde(so) for so in state_observations]
else:
max_val = max(so.max() for so in state_observations)
state_counts = [numpy.bincount(so, minlength=max_val) + pseudocount]
self.state_distributions = [sc / sc.sum() for sc in state_counts]
def __call__(self, observations):
"""Estimate the p_observations_given_state matrix for a set of observations.
If observations is a list/array of length N, returns an array of shape
(N, S), where element [t, s] is the probability of the observation at
time t assuming the system was in fact in state s.
"""
observations = numpy.asarray(observations)
if self.continuous:
state_probabilities = [kde(observations) for kde in self.state_distributions]
else:
state_probabilities = [hist[observations] for hist in self.state_distributions]
return numpy.transpose(state_probabilities)
def estimate_hmm_params(state_sequences, pseudocount=1, moving=True, time_sigma=1):
"""Given a set of state sequences, estimate the initial and transition
probabilities for each state (i.e. the p_initial and p_transition matrices
needed for HMM inference).
Parameters:
state_sequences: array of shape (n,t) with timecourses of state
assignments for n different sequences of measurements, each of
length t.
pseudocount: add specified pseudocount to each count (of initial state
or transition probabilities), to keep any probability from being
estimated as zero.
moving: if True, the returned p_transition will be of shape (n-1, s, s),
where n is as above and s is the number of states. This matrix will
contain the probability of transitions at each observation time.
If False, p_transition is of shape (s, s), and contains the grand
transition probabilities over all times.
time_sigma: if moving is True, smooth the probability distributions by
a gaussian moving average with their neighbors with the specified
sigma. To disable, set time_sigma to 0.
Returns: p_initial, p_transition
"""
state_sequences = numpy.asarray(state_sequences)
n, t = state_sequences.shape
s = state_sequences.max() + 1 # number of states
initial_counts = numpy.bincount(state_sequences[:,0], minlength=s) + pseudocount
p_initial = initial_counts / (n + s*pseudocount)
p_transition = []
for i in range(t-1):
from_states = state_sequences[:, i]
to_states = state_sequences[:, i+1]
p_trans = []
for from_s in range(s):
from_mask = (from_states == from_s)
tos = to_states[from_mask]
p_trans.append(numpy.bincount(tos, minlength=s))
p_transition.append(p_trans)
p_transition = numpy.array(p_transition) # shape (n-1, s, s)
if not moving:
p_transition = p_transition.sum(axis=0) # shape (s, s)
p_transition += pseudocount
denom = p_transition.sum(axis=-1) # shape (n-1, s) or (s,)
denom[denom == 0] = 1 # avoid 0/0 cases. Just set them to probability = 0 by converting to 0/1
p_transition = p_transition / denom[...,numpy.newaxis]
if moving and time_sigma:
p_transition = ndimage.gaussian_filter1d(p_transition, time_sigma, axis=0, mode='nearest')
return p_initial, p_transition
|
zpincus/zplib
|
zplib/scalar_stats/hmm.py
|
Python
|
mit
| 9,561
|
[
"Gaussian"
] |
2985be5a584f38d8006f61333325a3e39d956a5abfd202457797cfc3478d0cdb
|
'''upgrade to numpy 1.8.1
instal pyper # bridge to R
install numexpr # http://code.google.com/p/numexpr/downloads/detail?name=numexpr-2.1.win32-py2.7.exe
install pytables aka tables 3.1.1 # http://www.lfd.uci.edu/~gohlke/pythonlibs/
easy_install pandas
# IN R do this to install rhdf5:
> source("http://bioconductor.org/biocLite.R")
> biocLite("rhdf5")
Usage:
# convert RData file to HDF5 format
RdataToHDF5('smart_efficiency/RData/resultBasics.RData','basics')
basics = pd.read_hdf('smart_efficiency/RData/resultBasics.RData.h5','basics')
'''
from __future__ import absolute_import
from __future__ import print_function
import pyper
import pandas as pd
from six.moves import map
from six.moves import zip
def RdataToHDF5(fileName,variableName,path=None):
r = pyper.R()
if path is not None:
r["setwd('%s')" % path]
r['load("%s")' % fileName]
r['library(rhdf5)']
try:
r['h5createFile("%s.h5")' % fileName]
except pyper.RError:
pass # typically this is because the file already exists
# TODO: determine if something else went wrong
r['h5write(%s, "%s.h5","%s")' % (variableName,fileName,variableName)]
def loadHDF5(fileName,variableName):
return pd.read_hdf(fileName,variableName)
if __name__ == "__main__":
import numpy as np
print('Testing pandasTools')
print('Using R to convert RData into HDF5 data')
f = 'RData/resultBasics.RData'
var = 'basics'
#RdataToHDF5(f,var)
print('Loading hdf5 data into python DataFrame (via Pandas)')
basics = loadHDF5('%s.h5' % f,var)
zipCounts = basics.groupby('zip5').size()
zipMeans = basics.groupby('zip5').mean()
zd = zipCounts.to_dict()
zdd = dict(list(zip(list(map(int,list(zd.keys()))),list(map(int,list(zd.values()))))))
#zd = zipCounts.to_dict()
print((zdd[94611]))
#print(dir(basics))
|
ConvergenceDA/visdom-web
|
test/pandasTools.py
|
Python
|
mit
| 1,802
|
[
"Bioconductor"
] |
ae695988e8f2285efafca6f4b700f764fb7efcaf01b840aa8570ca4cb8a81baf
|
# Copyright (c) 2016, the GPyOpt Authors
# Licensed under the BSD 3-clause license (see LICENSE.txt)
from .base import AcquisitionBase
from ..util.general import get_quantiles
class AcquisitionLCB(AcquisitionBase):
"""
GP-Lower Confidence Bound acquisition function with constant exploration weight.
See:
Gaussian Process Optimization in the Bandit Setting: No Regret and Experimental Design
Srinivas et al., Proc. International Conference on Machine Learning (ICML), 2010
:param model: GPyOpt class of model
:param space: GPyOpt class of domain
:param optimizer: optimizer of the acquisition. Should be a GPyOpt optimizer
:param cost_withGradients: function
:param jitter: positive value to make the acquisition more explorative
.. Note:: does not allow to be used with cost
"""
analytical_gradient_prediction = True
def __init__(self, model, space, optimizer=None, cost_withGradients=None, exploration_weight=2):
self.optimizer = optimizer
super(AcquisitionLCB, self).__init__(model, space, optimizer)
self.exploration_weight = exploration_weight
if cost_withGradients is not None:
print('The set cost function is ignored! LCB acquisition does not make sense with cost.')
def _compute_acq(self, x):
"""
Computes the GP-Lower Confidence Bound
"""
m, s = self.model.predict(x)
f_acqu = -m + self.exploration_weight * s
return f_acqu
def _compute_acq_withGradients(self, x):
"""
Computes the GP-Lower Confidence Bound and its derivative
"""
m, s, dmdx, dsdx = self.model.predict_withGradients(x)
f_acqu = -m + self.exploration_weight * s
df_acqu = -dmdx + self.exploration_weight * dsdx
return f_acqu, df_acqu
|
SheffieldML/GPyOpt
|
GPyOpt/acquisitions/LCB.py
|
Python
|
bsd-3-clause
| 1,851
|
[
"Gaussian"
] |
b7bb1613cb19d546a3203134792454cfc0508c6bf9b2567e67f56ca8718f10e7
|
""" SummarizeLogsAgent module
This agents scans all the log tables ( SiteLog, ResourceLog and NodeLog ) on the
ResourceStatusDB and summarizes them. The results are stored on the History
tables (SiteHistory, ResourceHistory and NodeHistory) and the Log tables
cleared.
In order to summarize the logs, all entries with no changes on the Status or
TokenOwner column for a given ( Name, StatusType ) tuple are discarded.
The agent also adds a little prevention to avoid messing the summaries if the
agent is restarted / killed abruptly. Please, please, please, DO NOT DO IT !
"""
__RCSID__ = '$Id$'
from DIRAC import S_OK
from DIRAC.Core.Base.AgentModule import AgentModule
from DIRAC.ResourceStatusSystem.Client.ResourceStatusClient import ResourceStatusClient
AGENT_NAME = 'ResourceStatus/SummarizeLogsAgent'
class SummarizeLogsAgent(AgentModule):
""" SummarizeLogsAgent as extension of AgentModule.
"""
def __init__(self, *args, **kwargs):
""" Constructor.
"""
AgentModule.__init__(self, *args, **kwargs)
self.rsClient = None
def initialize(self):
""" Standard initialize.
:return: S_OK
"""
self.rsClient = ResourceStatusClient()
return S_OK()
def execute(self):
""" execute ( main method )
The execute method runs over the three families of tables ( Site, Resource and
Node ) performing identical operations. First, selects all logs for a given
family ( and keeps track of which one is the last row ID ). It summarizes the
logs and finally, deletes the logs from the database.
:return: S_OK
"""
# loop over the tables
for element in ('Site', 'Resource', 'Node'):
self.log.info('Summarizing %s' % element)
# get all logs to be summarized
selectLogElements = self._summarizeLogs(element)
if not selectLogElements['OK']:
self.log.error(selectLogElements['Message'])
continue
lastID, logElements = selectLogElements['Value']
# logElements is a dictionary of key-value pairs as follows:
# ( name, statusType ) : list( logs )
for key, logs in logElements.iteritems():
sumResult = self._registerLogs(element, key, logs)
if not sumResult['OK']:
self.log.error(sumResult['Message'])
continue
if lastID is not None:
self.log.info('Deleting %sLog till ID %s' % (element, lastID))
deleteResult = self.rsClient.deleteStatusElement(element, 'Log',
meta={'older': ('ID', lastID)})
if not deleteResult['OK']:
self.log.error(deleteResult['Message'])
continue
return S_OK()
#.............................................................................
def _summarizeLogs(self, element):
""" given an element, selects all logs in table <element>Log.
:Parameters:
**element** - `string`
name of the table family ( either Site, Resource or Node )
:return: S_OK( lastID, listOfLogs ) / S_ERROR
"""
selectResults = self.rsClient.selectStatusElement(element, 'Log')
if not selectResults['OK']:
return selectResults
selectedItems = {}
latestID = None
if not selectResults['Value']:
return S_OK((latestID, selectedItems))
selectColumns = selectResults['Columns']
selectResults = selectResults['Value']
if selectResults:
latestID = dict(zip(selectColumns, selectResults[-1]))['ID']
for selectResult in selectResults:
elementDict = dict(zip(selectColumns, selectResult))
key = (elementDict['Name'], elementDict['StatusType'])
if key not in selectedItems:
selectedItems[key] = [elementDict]
else:
lastStatus = selectedItems[key][-1]['Status']
lastToken = selectedItems[key][-1]['TokenOwner']
# If there are no changes on the Status or the TokenOwner with respect
# the previous one, discards the log.
if lastStatus != elementDict['Status'] or lastToken != elementDict['TokenOwner']:
selectedItems[key].append(elementDict)
return S_OK((latestID, selectedItems))
def _registerLogs(self, element, key, logs):
""" Given an element, a key - which is a tuple ( <name>, <statusType> )
and a list of dictionaries, this method inserts them on the <element>History
table. Before inserting them, checks whether the first one is or is not on
the <element>History table. If it is, it is not inserted.
:Parameters:
**element** - `string`
name of the table family ( either Site, Resource and Node )
**key** - `tuple`
tuple with the name of the element and the statusType
**logs** - `list`
list of dictionaries containing the logs
:return: S_OK / S_ERROR
"""
if not logs:
return S_OK()
# Undo key
name, statusType = key
selectedRes = self.rsClient.selectStatusElement(element, 'History', name,
statusType,
meta={'columns': ['Status', 'TokenOwner'],
'limit': 1,
'order': ('DateEffective', 'desc')})
if not selectedRes['OK']:
return selectedRes
selectedRes = selectedRes['Value']
if not selectedRes:
return S_OK()
# We want from the <element>History table the last Status, and TokenOwner
lastStatus, lastToken = None, None
if selectedRes:
try:
lastStatus = selectedRes[0][0]
lastToken = selectedRes[0][1]
except IndexError:
pass
# If the first of the selected items has a different status than the latest
# on the history, we keep it, otherwise we remove it.
if logs[0]['Status'] == lastStatus and logs[0]['TokenOwner'] == lastToken:
logs.pop(0)
if logs:
self.log.info('%s ( %s ):' % (name, statusType))
self.log.debug(logs)
for selectedItemDict in logs:
res = self.__logToHistoryTable(element, selectedItemDict)
if not res['OK']:
return res
return S_OK()
def __logToHistoryTable(self, element, elementDict):
""" Given an element and a dictionary with all the arguments, this method
inserts a new entry on the <element>History table
:Parameters:
**element** - `string`
name of the table family ( either Site, Resource and Node )
**elementDict** - `dict`
dictionary returned from the DB to be inserted on the History table
:return: S_OK / S_ERROR
"""
name = elementDict.get('Name')
statusType = elementDict.get('StatusType')
status = elementDict.get('Status')
elementType = elementDict.get('ElementType')
reason = elementDict.get('Reason')
dateEffective = elementDict.get('DateEffective')
lastCheckTime = elementDict.get('LastCheckTime')
tokenOwner = elementDict.get('TokenOwner')
tokenExpiration = elementDict.get('TokenExpiration')
self.log.info(' %s %s %s %s' % (status, dateEffective, tokenOwner, reason))
return self.rsClient.insertStatusElement(element, 'History', name, statusType,
status, elementType, reason,
dateEffective, lastCheckTime,
tokenOwner, tokenExpiration)
|
arrabito/DIRAC
|
ResourceStatusSystem/Agent/SummarizeLogsAgent.py
|
Python
|
gpl-3.0
| 7,460
|
[
"DIRAC"
] |
793cf82d4e4c6b18490dd6317e46d62005b0e27b3f9fff7be17d12348d12e627
|
from sqlobject import *
from sqlobject.converters import sqlrepr
from sqlobject.sqlbuilder import RLIKE, AND, OR, INNERJOINOn
from turbogears import identity, config
from datetime import datetime
import time
from string import strip
import IPy
from mirrormanager.lib import uniqueify, append_value_to_cache
from mirrormanager.categorymap import categorymap
IPy.check_addr_prefixlen = 0
from turbogears.database import PackageHub
hub = PackageHub("mirrormanager")
__connection__ = hub
UnicodeColKeyLength=None
_dburi = config.get('sqlobject.dburi', '')
if 'mysql://' in _dburi:
UnicodeColKeyLength=255
class SiteToSite(SQLObject):
class sqlmeta:
cacheValues = False
upstream_site = ForeignKey('Site')
downstream_site = ForeignKey('Site')
idx = DatabaseIndex('upstream_site', 'downstream_site', unique=True)
username = UnicodeCol(default=None, length=UnicodeColKeyLength)
password = UnicodeCol(default=None)
username_idx = DatabaseIndex('upstream_site', 'username', unique=True)
def my_site(self):
return self.upstream_site
class Site(SQLObject):
class sqlmeta:
cacheValues = False
name = UnicodeCol(alternateID=True, length=UnicodeColKeyLength)
password = UnicodeCol(default=None)
orgUrl = UnicodeCol(default=None)
private = BoolCol(default=False)
admin_active = BoolCol(default=True)
user_active = BoolCol(default=True)
createdAt = DateTimeCol(default=datetime.utcnow())
createdBy = UnicodeCol(default=None)
# allow all sites to pull from me
allSitesCanPullFromMe = BoolCol(default=False)
downstreamComments = UnicodeCol(default=None)
emailOnDrop = BoolCol(default=False)
emailOnAdd = BoolCol(default=False)
admins = MultipleJoin('SiteAdmin')
hosts = MultipleJoin('Host')
def destroySelf(self):
"""Cascade the delete operation"""
for h in self.hosts:
h.destroySelf()
for a in self.admins:
a.destroySelf()
for s in SiteToSite.select(OR(SiteToSite.q.upstream_siteID == self.id,
SiteToSite.q.downstream_siteID == self.id)):
s.destroySelf()
SQLObject.destroySelf(self)
def _get_downstream_sites(self):
if self.allSitesCanPullFromMe:
return [s for s in Site.select() if s != self]
else:
return [s2s.downstream_site for s2s in SiteToSite.selectBy(upstream_site=self)]
def _get_upstream_sites(self):
open_upstreams = [s for s in Site.select() if s != self and s.allSitesCanPullFromMe]
chosen_upstreams = [s2s.upstream_site for s2s in SiteToSite.selectBy(downstream_site=self)]
result = uniqueify(open_upstreams + chosen_upstreams)
return result
def add_downstream_site(self, site):
if site is not None:
SiteToSite(upstream_site=self, downstream_site=site)
def del_downstream_site(self, site):
for s in SiteToSite.selectBy(upstream_site=self, downstream_site=site):
s.destroySelf()
def is_siteadmin_byname(self, name):
for a in self.admins:
if a.username == name:
return True
return False
def is_siteadmin(self, identity):
admin_group = config.get('mirrormanager.admin_group', 'sysadmin')
if identity.in_group(admin_group):
return True
return self.is_siteadmin_byname(identity.current.user_name)
def is_downstream_siteadmin_byname(self, name):
for d in self.downstream_sites:
for a in d.admins:
if a.username == name:
return True
return False
def is_downstream_siteadmin(self, identity):
"""If you are a sysadmin of one of my immediate downstream sites,
you can see some of my site details, but you can't edit them.
"""
return self.is_downstream_siteadmin_byname(identity.current.user_name)
class SiteAdmin(SQLObject):
class sqlmeta:
cacheValues = False
username = UnicodeCol()
site = ForeignKey('Site')
def my_site(self):
return self.site
def user_sites(identity):
result = []
sites = Site.select(join=INNERJOINOn(Site, SiteAdmin, AND(SiteAdmin.q.siteID == Site.q.id,
SiteAdmin.q.username == identity.current.user_name)))
return list(sites)
class HostCategory(SQLObject):
class sqlmeta:
cacheValues = False
host = ForeignKey('Host')
category = ForeignKey('Category')
hcindex = DatabaseIndex('host', 'category', unique=True)
always_up2date = BoolCol(default=False)
dirs = MultipleJoin('HostCategoryDir', orderBy='path')
urls = MultipleJoin('HostCategoryUrl')
def destroySelf(self):
"""Cascade the delete operation"""
for b in self.urls:
b.destroySelf()
for d in self.dirs:
d.destroySelf()
SQLObject.destroySelf(self)
def my_site(self):
return self.host.my_site()
class HostCategoryDir(SQLObject):
class sqlmeta:
cacheValues = False
host_category = ForeignKey('HostCategory')
# subset of the path starting below HostCategory.path
path = UnicodeCol(length=UnicodeColKeyLength)
directory = ForeignKey('Directory')
hcdindex = DatabaseIndex('host_category', 'path', unique=True)
up2date = BoolCol(default=True)
class HostCategoryUrl(SQLObject):
class sqlmeta:
cacheValues = False
host_category = ForeignKey('HostCategory')
url = UnicodeCol(alternateID=True, length=UnicodeColKeyLength)
private = BoolCol(default=False)
def my_site(self):
return self.host_category.my_site()
class Host(SQLObject):
class sqlmeta:
cacheValues = False
name = UnicodeCol(length=UnicodeColKeyLength)
site = ForeignKey('Site')
idx = DatabaseIndex('site', 'name', unique=True)
robot_email = UnicodeCol(default=None)
admin_active = BoolCol(default=True)
user_active = BoolCol(default=True)
country = StringCol(default=None)
bandwidth_int = IntCol(default=100, notNull=True)
comment = UnicodeCol(default=None)
_config = PickleCol(default=None)
lastCheckedIn = DateTimeCol(default=None)
lastCrawled = DateTimeCol(default=None)
private = BoolCol(default=False)
internet2 = BoolCol(default=False)
internet2_clients = BoolCol(default=False)
asn = IntCol(default=None)
asn_clients = BoolCol(default=True)
max_connections = IntCol(default=1, notNone=True, unsigned=True)
last_crawl_duration = BigIntCol(default=0)
countries_allowed = MultipleJoin('HostCountryAllowed')
netblocks = MultipleJoin('HostNetblock', orderBy='netblock')
acl_ips = MultipleJoin('HostAclIp', orderBy='ip')
categories = MultipleJoin('HostCategory')
exclusive_dirs = MultipleJoin('DirectoryExclusiveHost')
locations = SQLRelatedJoin('Location')
countries = SQLRelatedJoin('Country')
peer_asns = MultipleJoin('HostPeerAsn')
def destroySelf(self):
"""Cascade the delete operation"""
s = [self.countries_allowed,
self.netblocks,
self.acl_ips,
self.categories]
for a in s:
for b in a:
b.destroySelf()
for ed in self.exclusive_dirs:
ed.destroySelf()
for l in self.locations:
self.removeLocation(l)
SQLObject.destroySelf(self)
def _uploaded_config(self, config):
message = ''
def _config_categories(config):
noncategories = ['version', 'global', 'site', 'host', 'stats']
if config is not None:
return [key for key in config.keys() if key not in noncategories]
else:
return []
def compare_dir(hcdir, files):
if hcdir.directory is None or hcdir.directory.files is None:
raise SQLObjectNotFound
dfiles = hcdir.directory.files
if len(dfiles) == 0 and len(files) == 0:
return True
for fname, fdata in dfiles.iteritems():
if fname not in files:
return False
if fdata['size'] != files[fname]:
return False
return True
# handle the optional arguments
if config['host'].has_key('user_active'):
if config['host']['user_active'] in ['true', '1', 't', 'y', 'yes']:
self.user_active = True
else:
self.user_active = False
# fill in the host category data (HostCategory and HostCategoryURL)
# the category names in the config have been lowercased
# so we have to find the matching mixed-case category name.
cats = {}
for c in Category.select():
cats[c.name.lower()] = c.id
for c in _config_categories(config):
if c not in cats:
continue
category = Category.get(cats[c])
hc = HostCategory.selectBy(host=self, category=category)
if hc.count() > 0:
hc = hc[0]
else:
# don't let report_mirror create HostCategories
# it must be done through the web UI
continue
marked_up2date = 0
deleted = 0
added = 0
# and now one HostCategoryDir for each dir in the dirtree
if config[c].has_key('dirtree'):
for dirname,files in config[c]['dirtree'].iteritems():
d = strip(dirname, '/')
hcdir = HostCategoryDir.selectBy(host_category = hc, path=d)
if hcdir.count() > 0:
hcdir = hcdir[0]
# this is evil, but it avoids stat()s on the client side and a lot of data uploading
is_up2date = True
marked_up2date += 1
if hcdir.up2date != is_up2date:
hcdir.up2date = is_up2date
hcdir.sync()
else:
if len(d) > 0:
dname = "%s/%s" % (hc.category.topdir.name, d)
else:
dname = hc.category.topdir.name
# Don't create an entry for a directory the database doesn't know about
try:
dir = Directory.byName(dname)
hcdir = HostCategoryDir(host_category=hc, path=d, directory=dir)
added += 1
except:
pass
for d in HostCategoryDir.selectBy(host_category=hc):
if d.path not in config[c]['dirtree'].keys():
d.destroySelf()
deleted += 1
message += "Category %s directories updated: %s added: %s deleted %s\n" % (category.name, marked_up2date, added, deleted)
hc.sync()
return message
def is_admin_active(self):
return self.admin_active and self.site.admin_active
def is_active(self):
return self.admin_active and self.user_active and self.site.user_active
def is_private(self):
return self.private or self.site.private
def _get_config(self):
return self._config
def _set_config(self, config):
# really, we don't store the config anymore
self._config = None
self.lastCheckedIn = datetime.utcnow()
def checkin(self, config):
message = self._uploaded_config(config)
self.config = config
self.sync()
return message
def has_category(self, cname):
return HostCategory.selectBy(host=self, category=Category.byName(cname)).count() > 0
def has_category_dir(self, category, dir):
if len(dir)==0:
return True
sr = HostCategory.select(join=INNERJOINOn(HostCategory, HostCategoryDir,
AND(HostCategory.q.hostID == self.id,
HostCategory.q.categoryID == category.id,
HostCategory.q.id == HostCategoryDir.q.host_categoryID,
HostCategoryDir.q.path == dir)),
limit=1)
return sr.count() > 0
def directory_urls(self, directory, category):
"""Given what we know about the host and the categories it carries
return the URLs by which we can get at it (whether or not it's actually present can be determined later."""
result = []
for hc in self.categories:
if category != hc.category:
continue
dirname = directory.name[(len(category.topdir.name)+1):]
for hcu in self.category_urls(category.name):
fullurl = '%s/%s' % (hcu, dirname)
result.append((fullurl, self.country))
return result
def my_site(self):
return self.site
def set_not_up2date(self):
for hc in self.categories:
for hcd in hc.dirs:
hcd.up2date=False
hcd.sync()
class PubliclistHostCategory:
class sqlmeta:
cacheValues = False
def __init__(self, name):
self.name = name
self.http_url = None
self.ftp_url = None
self.rsync_url = None
def numurls(self):
i=0
if self.http_url is not None: i=i+1
if self.ftp_url is not None: i=i+1
if self.rsync_url is not None: i=i+1
return i
def add_url(self, url):
if url.startswith('http:'):
self.http_url = url
elif url.startswith('ftp:'):
self.ftp_url = url
elif url.startswith('rsync:'):
self.rsync_url = url
class PubliclistHost:
class sqlmeta:
cacheValues = False
def __init__(self, hostinfo):
self.id = hostinfo[0]
self.country = hostinfo[1]
self.name = hostinfo[2]
self.bandwidth_int = hostinfo[3]
self.comment = hostinfo[4]
self.internet2 = hostinfo[5]
self.site_url = hostinfo[6]
self.site_name = hostinfo[7]
self.categories = {}
def __cmp__(self, other):
"""comparison based on country, so we can sort().
First sort on country, ascending order.
Second sort on bandwidth_int, decending order.
"""
a = self.country
b = other.country
if a is None:
a = 'ZZ'
if b is None:
b = 'ZZ'
rc = cmp(a.upper(), b.upper())
if rc == 0:
rc = -cmp(self.bandwidth_int, other.bandwidth_int)
return rc
def add_category(self, name, url):
if name in self.categories:
c = self.categories[name]
else:
c = PubliclistHostCategory(name)
self.categories[name] = c
c.add_url(url)
def trim_categories(self, keepcategories):
k = self.categories.keys()
for c in k:
if c not in keepcategories:
del self.categories[c]
def _publiclist_sql_to_list(sqlresult, valid_categories):
hosts = {}
for info in sqlresult:
if info[0] not in hosts:
hosts[info[0]] = PubliclistHost(info)
hosts[info[0]].add_category(info[8], info[9])
hkeys = hosts.keys()
for h in hkeys:
hosts[h].trim_categories(valid_categories)
ckeys = hosts[h].categories.keys()
for c in ckeys:
if hosts[h].categories[c].numurls() == 0:
del hosts[h].categories[c]
if len(hosts[h].categories) == 0:
del hosts[h]
# turn the dict values into a list
l = sorted(hosts.values())
return l
def _publiclist_hosts(product=None, re=None):
class MY_RLIKE(RLIKE):
def __sqlrepr__(self, db):
return "(%s %s (%s))" % (
self.string, self._get_op(db), sqlrepr(self.expr, db))
def _rlike(pattern, string):
# there's probably a beter way to get this, but this works...
_dburi = config.get('sqlobject.dburi', 'sqlite://')
dbtype = _dburi.strip('notrans_').split(':')[0]
return MY_RLIKE(pattern, string).__sqlrepr__(dbtype) + " "
sql1_filter = ''
sql2_filter = ''
sql_common = "SELECT host.id, host.country, host.name AS host_name, host.bandwidth_int, host.comment, host.internet2, "
sql_common += "site.org_url, site.name AS site_name, category.name AS category_name, host_category_url.url "
sql_common += "FROM category, host_category, host, site, host_category_url "
# join conditions
sql_common += "WHERE "
sql_common += "host_category.category_id = category.id AND "
sql_common += "host_category.host_id = host.id AND "
sql_common += "host_category_url.host_category_id = host_category.id AND "
if product is not None:
sql_common += "category.product_id = %s AND " % product.id
sql_common += "host.site_id = site.id "
# select conditions
# up2date, active, not private
sql_common += 'AND host.user_active AND site.user_active '
sql_common += 'AND host.admin_active AND site.admin_active '
sql_common += 'AND NOT host.private '
sql_common += 'AND NOT site.private '
sql_common += 'AND NOT host_category_url.private '
sql_common += 'AND category.publiclist '
if re is not None:
sql1_filter = "AND " + _rlike(re, 'host_category_dir.path')
sql2_filter = "AND " + _rlike(re, 'directory.name')
sql1_subselect = '('
sql1_subselect += 'SELECT 1 from host_category_dir '
sql1_subselect += 'WHERE host_category_dir.host_category_id = host_category.id '
sql1_subselect += 'AND host_category_dir.up2date '
sql1_subselect += sql1_filter
sql1_subselect += 'LIMIT 1 '
sql1_subselect += ') '
sql2_subselect = '('
sql2_subselect += 'SELECT 1 from category_directory, directory '
sql2_subselect += 'WHERE category_directory.directory_id = directory.id '
sql2_subselect += 'AND category_directory.category_id = category.id '
sql2_subselect += 'AND host_category.always_up2date '
sql2_subselect += sql2_filter
sql2_subselect += 'LIMIT 1 '
sql2_subselect += ') '
sql = sql_common + 'AND ( EXISTS ' + sql1_subselect + 'OR EXISTS ' + sql2_subselect + ') '
result = Directory._connection.queryAll(sql)
return result
def publiclist_hosts(productname=None, vername=None, archname=None):
""" has a category of product, and an hcd that matches version """
product = None
if productname is not None:
try:
product = Product.byName(productname)
except SQLObjectNotFound:
return []
if vername is not None and archname is not None:
desiredPath = '(^|/)%s/.*%s/' % (vername, archname)
elif vername is not None:
desiredPath = '(^|/)%s/' % vername
else:
desiredPath = None
sqlresult = _publiclist_hosts(product=product, re=desiredPath)
valid_categories = categorymap(productname, vername)
return _publiclist_sql_to_list(sqlresult, valid_categories)
class HostAclIp(SQLObject):
class sqlmeta:
cacheValues = False
host = ForeignKey('Host')
ip = UnicodeCol()
def my_site(self):
return self.host.my_site()
def _rsync_acl_list(internet2_only, public_only):
sql = "SELECT host_acl_ip.ip "
sql += "FROM host, site, host_acl_ip "
# join conditions
sql += "WHERE "
sql += "host.site_id = site.id AND "
sql += "host_acl_ip.host_id = host.id "
# select conditions
# admin_active
sql += 'AND host.admin_active AND site.admin_active '
if internet2_only:
sql += 'AND host.internet2 '
if public_only:
sql += 'AND NOT host.private '
sql += 'AND NOT site.private '
result = Directory._connection.queryAll(sql)
return result
def rsync_acl_list(internet2_only=False,public_only=False):
result = _rsync_acl_list(internet2_only, public_only)
return [t[0] for t in result]
class HostCountryAllowed(SQLObject):
class sqlmeta:
cacheValues = False
host = ForeignKey('Host')
country = StringCol(notNone=True)
def my_site(self):
return self.host.my_site()
class HostNetblock(SQLObject):
class sqlmeta:
cacheValues = False
host = ForeignKey('Host')
netblock = StringCol()
name = UnicodeCol()
def my_site(self):
return self.host.my_site()
class HostPeerAsn(SQLObject):
class sqlmeta:
cacheValues = False
host = ForeignKey('Host')
asn = IntCol(notNone=True)
name = UnicodeCol()
idx = DatabaseIndex('host', 'asn', unique=True)
class HostStats(SQLObject):
class sqlmeta:
cacheValues = False
host = ForeignKey('Host')
_timestamp = DateTimeCol(default=datetime.utcnow())
type = UnicodeCol(default=None)
data = PickleCol(default=None)
class Arch(SQLObject):
class sqlmeta:
cacheValues = False
name = UnicodeCol(alternateID=True, length=UnicodeColKeyLength)
publiclist = BoolCol(default=True)
primaryArch = BoolCol(default=True)
def publiclist_arches():
return list(Arch.selectBy(publiclist=True).orderBy(['-primaryArch', 'name']))
# e.g. 'fedora' and 'epel'
class Product(SQLObject):
class sqlmeta:
cacheValues = False
name = UnicodeCol(alternateID=True, length=UnicodeColKeyLength)
publiclist = BoolCol(default=True)
versions = MultipleJoin('Version', orderBy=['-sortorder', '-id'])
categories = MultipleJoin('Category')
def destroySelf(self):
for v in self.versions:
v.destroySelf()
for c in self.categories:
c.destroySelf()
SQLObject.destroySelf(self)
@staticmethod
def selectFieldOptions():
return [(p.id, p.name) for p in Product.select().orderBy('name')]
class Version(SQLObject):
class sqlmeta:
cacheValues = False
name = UnicodeCol(length=UnicodeColKeyLength)
product = ForeignKey('Product')
isTest = BoolCol(default=False)
display = BoolCol(default=True)
display_name = UnicodeCol(default=None)
ordered_mirrorlist = BoolCol(default=True)
sortorder = IntCol(default=0, notNone=True)
codename = UnicodeCol(default=None)
idx = DatabaseIndex('name', 'productID', unique=True)
def setup_directory_category_cache():
cache = {}
sql = 'SELECT category_id, directory_id FROM category_directory ORDER BY directory_id'
result = Directory._connection.queryAll(sql)
for (cid, did) in result:
append_value_to_cache(cache, did, cid)
return cache
class Directory(SQLObject):
class sqlmeta:
cacheValues = False
# Full path
# e.g. pub/epel
# e.g. pub/fedora/linux
name = UnicodeCol(alternateID=True, length=UnicodeColKeyLength)
files = PickleCol(default={}, length=2**24)
readable = BoolCol(default=True)
ctime = BigIntCol(default=0)
categories = RelatedJoin('Category')
repositories = MultipleJoin('Repository') # zero or one repository, set if this dir contains a yum repo
host_category_dirs = MultipleJoin('HostCategoryDir')
fileDetails = MultipleJoin('FileDetail', orderBy=['filename', '-timestamp'])
exclusive_hosts = MultipleJoin('DirectoryExclusiveHost')
def destroySelf(self):
for c in self.categories:
self.removeCategory(c)
for r in self.repositories:
r.destroySelf()
# don't destroy a whole category if only deleting a directory
for hcd in self.host_category_dirs:
hcd.destroySelf()
for fd in self.fileDetails:
fd.destroySelf()
for eh in self.exclusive_hosts:
eh.destroySelf()
SQLObject.destroySelf(self)
file_details_cache = dict()
@staticmethod
def ageFileDetails():
Directory._fill_file_details_cache()
Directory._age_file_details()
@staticmethod
def _fill_file_details_cache():
sql = 'SELECT id, directory_id, filename, timestamp from file_detail ORDER BY directory_id, filename, -timestamp'
result = FileDetail._connection.queryAll(sql)
cache = dict()
for (id, directory_id, filename, timestamp) in result:
k = (directory_id, filename)
v = dict(file_detail_id=id, timestamp=timestamp)
append_value_to_cache(cache, k, v)
Directory.file_details_cache = cache
@staticmethod
def _age_file_details():
"""For each file, keep at least 1 FileDetail entry.
Remove the second-most recent entry if the most recent entry is older than
max_propogation_days. This gives mirrors time to pick up the
most recent change.
Remove any others that are more than max_stale_days old."""
t = int(time.time())
max_stale = config.get('mirrormanager.max_stale_days', 3)
max_propogation = config.get('mirrormanager.max_propogation_days', 2)
stale = t - (60*60*24*max_stale)
propogation = t - (60*60*24*max_propogation)
for k, fds in Directory.file_details_cache.iteritems():
(directory_id, filename) = k
if len(fds) > 1:
start=2
# second-most recent only if most recent has had time to propogate
if fds[0]['timestamp'] < propogation:
start=1
# all others
for f in fds[start:]:
if f['timestamp'] < stale:
FileDetail.get(f['file_detail_id']).destroySelf()
class Category(SQLObject):
class sqlmeta:
cacheValues = False
# Top-level mirroring
# e.g. 'Fedora Linux', 'Fedora Archive'
name = UnicodeCol(alternateID=True, length=UnicodeColKeyLength)
product = ForeignKey('Product')
canonicalhost = UnicodeCol(default='http://download.fedora.redhat.com')
topdir = ForeignKey('Directory', default=None)
publiclist = BoolCol(default=True)
GeoDNSDomain = UnicodeCol(default=None)
directories = RelatedJoin('Directory', orderBy='name') # all the directories that are part of this category
repositories = MultipleJoin('Repository')
hostCategories = MultipleJoin('HostCategory')
def destroySelf(self):
for hc in self.hostCategories:
hc.destroySelf()
SQLObject.destroySelf(self)
def directories_newer_than(self, since):
result = []
for d in self.directories:
if d.ctime > since:
result.append(d.name)
return result
@staticmethod
def lookupCategory(s):
s = s.lower()
for c in Category.select():
cname = c.name.lower()
if cname == s:
return c
return None
def rsyncFilter(categories_requested, since):
"""
@categories_requested: a list of category names
@since: timestamp
"""
def _rsyncFilter(categorySearch, since):
sql = ''
sql += "SELECT directory.name "
sql += "FROM category, directory, category_directory "
sql += "WHERE "
# join conditions
sql += "category_directory.category_id = category.id AND "
sql += "category_directory.directory_id = directory.id AND "
# select conditions
sql += "category.id IN %s AND " % categorySearch
sql += "directory.ctime > %d " % (since)
result = Directory._connection.queryAll(sql)
return result
def _list_to_inclause(categoryList):
s = '( '
for i in xrange(len(categoryList)):
s += '%d' % (categoryList[i])
if i < len(categoryList)-1:
s += ', '
s += ' )'
return s
try:
since = int(since)
except:
return []
categoryList = []
for i in xrange(len(categories_requested)):
c = Category.lookupCategory(categories_requested[i])
if c is None:
continue
categoryList.append(c.id)
if len(categoryList) == 0:
return []
categorySearch = _list_to_inclause(categoryList)
sqlresult = _rsyncFilter(categorySearch, since)
# un-tuplelize it
result = [d[0] for d in sqlresult]
return result
class Repository(SQLObject):
class sqlmeta:
cacheValues = False
name = UnicodeCol(alternateID=True, length=UnicodeColKeyLength)
prefix = UnicodeCol(default=None, length=UnicodeColKeyLength)
category = ForeignKey('Category')
version = ForeignKey('Version')
arch = ForeignKey('Arch')
directory = ForeignKey('Directory')
disabled = BoolCol(default=False)
idx = DatabaseIndex('prefix', 'arch', unique=True)
class FileDetail(SQLObject):
class sqlmeta:
cacheValues = False
directory = ForeignKey('Directory', notNone=True)
filename = UnicodeCol(notNone=True)
timestamp = BigIntCol(default=None)
size = BigIntCol(default=None)
sha1 = UnicodeCol(default=None)
md5 = UnicodeCol(default=None)
sha256 = UnicodeCol(default=None)
sha512 = UnicodeCol(default=None)
fileGroups = SQLRelatedJoin('FileGroup')
class RepositoryRedirect(SQLObject):
class sqlmeta:
cacheValues = False
""" Uses strings to allow for effective named aliases, and for repos that may not exist yet """
fromRepo = UnicodeCol(alternateID=True, length=UnicodeColKeyLength)
toRepo = UnicodeCol(default=None, length=UnicodeColKeyLength)
idx = DatabaseIndex('fromRepo', 'toRepo', unique=True)
class CountryContinentRedirect(SQLObject):
class sqlmeta:
cacheValues = False
country = UnicodeCol(alternateID=True, notNone=True, length=UnicodeColKeyLength)
continent = UnicodeCol(notNone=True)
def _set_country(self, country):
self._SO_set_country(country.upper())
def _set_continent(self, continent):
self._SO_set_continent(continent.upper())
class EmbargoedCountry(SQLObject):
class sqlmeta:
cacheValues = False
country_code = StringCol(notNone=True)
class DirectoryExclusiveHost(SQLObject):
class sqlmeta:
cacheValues = False
directory = ForeignKey('Directory')
host = ForeignKey('Host')
idx = DatabaseIndex('directory', 'host', unique=True)
def mirror_admins(public_only=True):
sql = 'SELECT DISTINCT site_admin.username '
sql += 'FROM site, host, site_admin '
sql += 'WHERE host.site_id = site.id '
sql += 'AND site_admin.site_id = site.id '
if public:
sql += 'AND site.public AND host.public '
sql += 'ORDER BY site_admin.username '
qresult = Directory._connection.queryAll(sql)
result = [x[0] for x in qresult]
return result
def _host_siteadmins(url):
sql = 'SELECT DISTINCT site_admin.username FROM '
sql += 'host_category_url, host_category, host, site, site_admin WHERE '
# join conditions
sql += 'host_category_url.host_category_id = host_category.id AND '
sql += 'host_category.host_id = host.id AND '
sql += 'host.site_id = site.id AND '
sql += 'site_admin.site_id = site.id AND '
# query conditions
sql += "host_category_url.url = '" + url + "'"
qresult = Directory._connection.queryAll(sql)
result = [x[0] for x in qresult]
return result
from urlparse import urlsplit
def host_siteadmins(host):
found = False
for hcurl in HostCategoryUrl.select():
scheme, netloc, path, query, fragment = urlsplit(hcurl.url)
if host == netloc:
found=True
break
if not found:
return []
return _host_siteadmins(hcurl.url)
class Location(SQLObject):
"""For grouping hosts, perhaps across Site boundaries. User queries may request
hosts from a particular Location (such as an Amazon region), which will be returned
first in the mirror list. """
class sqlmeta:
cacheValues = False
name = UnicodeCol(alternateID=True, length=UnicodeColKeyLength)
hosts = SQLRelatedJoin('Host')
def destroySelf(self):
"""Cascade the delete operation"""
for h in self.hosts:
self.removeHost(h)
SQLObject.destroySelf(self)
# manual creation of the RelatedJoin table so we can guarantee uniqueness
class HostLocation(SQLObject):
class sqlmeta:
table = 'host_location'
host = ForeignKey('Host')
location = ForeignKey('Location')
hlidx = DatabaseIndex('host', 'location', unique=True)
class FileGroup(SQLObject):
class sqlmeta:
cacheValues = False
name = UnicodeCol(alternateID=True, length=UnicodeColKeyLength)
files = SQLRelatedJoin('FileDetail')
# manual creation of the RelatedJoin table because we're adding it to the schema
# and SO then requires us to create it ourselves
class FileDetailFileGroup(SQLObject):
class sqlmeta:
table = 'file_detail_file_group'
file_detail = ForeignKey('FileDetail')
file_group = ForeignKey('FileGroup')
class Country(SQLObject):
code = UnicodeCol(alternateID=True, length=UnicodeColKeyLength)
hosts = SQLRelatedJoin('Host')
class HostCountry(SQLObject):
class sqlmeta:
table = 'host_country'
host = ForeignKey('Host')
country = ForeignKey('Country')
hlidx = DatabaseIndex('host', 'country', unique=True)
class NetblockCountry(SQLObject):
class sqlmeta:
cacheValues = False
netblock = UnicodeCol(alternateID=True, notNone=True, length=UnicodeColKeyLength)
country = UnicodeCol(notNone=True)
def _set_country(self, country):
self._SO_set_country(country.upper())
###############################################################
# These classes are only used if you're not using the
# Fedora Account System or some other backend that provides
# Identity management
class Visit(SQLObject):
class sqlmeta:
table = "visit"
visit_key = StringCol(length=40, alternateID=True,
alternateMethodName="by_visit_key")
created = DateTimeCol(default=datetime.now)
expiry = DateTimeCol()
def lookup_visit(cls, visit_key):
try:
return cls.by_visit_key(visit_key)
except SQLObjectNotFound:
return None
lookup_visit = classmethod(lookup_visit)
class VisitIdentity(SQLObject):
visit_key = StringCol(length=40, alternateID=True,
alternateMethodName="by_visit_key")
user_id = IntCol()
class Group(SQLObject):
"""
An ultra-simple group definition.
"""
# names like "Group", "Order" and "User" are reserved words in SQL
# so we set the name to something safe for SQL
class sqlmeta:
table = "tg_group"
group_name = UnicodeCol(length=16, alternateID=True,
alternateMethodName="by_group_name")
display_name = UnicodeCol(length=255)
created = DateTimeCol(default=datetime.now)
# collection of all users belonging to this group
users = RelatedJoin("User", intermediateTable="user_group",
joinColumn="group_id", otherColumn="user_id")
# collection of all permissions for this group
permissions = RelatedJoin("Permission", joinColumn="group_id",
intermediateTable="group_permission",
otherColumn="permission_id")
class User(SQLObject):
"""
Reasonably basic User definition. Probably would want additional attributes.
"""
# names like "Group", "Order" and "User" are reserved words in SQL
# so we set the name to something safe for SQL
class sqlmeta:
table = "tg_user"
user_name = UnicodeCol(length=UnicodeColKeyLength, alternateID=True,
alternateMethodName="by_user_name")
email_address = UnicodeCol(length=255, alternateID=True,
alternateMethodName="by_email_address")
display_name = UnicodeCol(length=255)
password = UnicodeCol(length=40)
created = DateTimeCol(default=datetime.now)
# groups this user belongs to
groups = RelatedJoin("Group", intermediateTable="user_group",
joinColumn="user_id", otherColumn="group_id")
def _get_permissions(self):
perms = set()
for g in self.groups:
perms = perms | set(g.permissions)
return perms
def _set_password(self, cleartext_password):
"Runs cleartext_password through the hash algorithm before saving."
hash = identity.encrypt_password(cleartext_password)
self._SO_set_password(hash)
def set_password_raw(self, password):
"Saves the password as-is to the database."
self._SO_set_password(password)
class Permission(SQLObject):
permission_name = UnicodeCol(length=16, alternateID=True,
alternateMethodName="by_permission_name")
description = UnicodeCol(length=255)
groups = RelatedJoin("Group",
intermediateTable="group_permission",
joinColumn="permission_id",
otherColumn="group_id")
|
docent-net/mirrormanager
|
server/mirrormanager/model.py
|
Python
|
gpl-2.0
| 37,615
|
[
"VisIt"
] |
bdd01dc5264f0dc92c7c34fa6145fc9522f3b9aa28ec7a3beea5dabc31897bfd
|
# Look at sdf_example.py in the examples/ directory for more detail
from sdfpy import load_sdf
from thingking import loadtxt
import vtk
import numpy as np
# Load N-body particles from a = 1.0 dataset. Particles have positions with
# units of proper kpc, and velocities with units of km/s.
particles = load_sdf("../data/ds14_scivis_0128_e4_dt04_1.0000")
xx, yy, zz = particles['x'], particles['y'], particles['z']
n = 5000
pts = [ (xx[i], yy[i], zz[i]) for i in range(n) ]
points = vtk.vtkPoints()
for pt in pts:
points.InsertNextPoint(pt)
grid = vtk.vtkUnstructuredGrid()
grid.SetPoints(points)
sphere = vtk.vtkSphereSource()
sphere.SetRadius(50.0)
glyph = vtk.vtkGlyph3D()
glyph.SetInput(grid)
glyph.SetSource(sphere.GetOutput())
mapper = vtk.vtkPolyDataMapper()
mapper.SetInput(glyph.GetOutput())
actor = vtk.vtkActor()
actor.SetMapper(mapper)
ren = vtk.vtkRenderer()
ren.AddActor(actor)
renWin = vtk.vtkRenderWindow()
renWin.AddRenderer(ren)
iren = vtk.vtkRenderWindowInteractor()
iren.SetRenderWindow(renWin)
iren.Start()
|
ryanpbrewster/SciVis-2015
|
examples/displayParticleGlyphs.py
|
Python
|
mit
| 1,043
|
[
"VTK"
] |
05a10212c8eff9dc464c0aacfac3f6c828be784a784882e109d32971bfa5b9fa
|
#!/usr/bin/env python
########################################################################
# File : dirac-configure
# Author : Ricardo Graciani
########################################################################
"""
Main script to write dirac.cfg for a new DIRAC installation and initial download of CAs and CRLs
if necessary.
To be used by VO specific scripts to configure new DIRAC installations
There are 2 mandatory arguments:
-S --Setup=<setup> To define the DIRAC setup for the current installation
-C --ConfigurationServer=<server>|-W --Gateway To define the reference Configuration Servers/Gateway
for the current installation
others are optional
-I --IncludeAllServers To include all Configuration Servers
(by default only those in -C option are included)
-n --SiteName=<sitename> To define the DIRAC Site Name for the installation
-N --CEName=<cename> To determine the DIRAC Site Name from the CE Name
-V --VO=<vo> To define the VO for the installation
-U --UseServerCertificate To use Server Certificate for all clients
-H --SkipCAChecks To skip check of CAs for all clients
-D --SkipCADownload To skip download of CAs
-M --SkipVOMSDownload To skip download of VOMS info
-v --UseVersionsDir Use versions directory
(This option will properly define RootPath and InstancePath)
-A --Architecture=<architecture> To define /LocalSite/Architecture=<architecture>
-L --LocalSE=<localse> To define /LocalSite/LocalSE=<localse>
-F --ForceUpdate Forces the update of cfg file (i.e. dirac.cfg),
even if it does already exists (use with care)
-O --Output define output configuration file
Other arguments will take proper defaults if not defined.
Additionally all options can all be passed inside a .cfg file passed as argument.
The following options are recognized::
Setup
ConfigurationServer
IncludeAllServers
Gateway
SiteName
CEName
VirtualOrganization
UseServerCertificate
SkipCAChecks
SkipCADownload
UseVersionsDir
Architecture
LocalSE
LogLevel
As in any other script command line option take precedence over .cfg files passed as arguments.
The combination of both is written into the installed dirac.cfg.
Notice: It will not overwrite exiting info in current dirac.cfg if it exists.
Example: dirac-configure -d
-S LHCb-Development
-C 'dips://lhcbprod.pic.es:9135/Configuration/Server'
-W 'dips://lhcbprod.pic.es:9135'
--SkipCAChecks
"""
import sys
import os
import DIRAC
from DIRAC.Core.Utilities.File import mkDir
from DIRAC.Core.Base import Script
from DIRAC.Core.Security.ProxyInfo import getProxyInfo
from DIRAC.ConfigurationSystem.Client.Helpers import cfgInstallPath, cfgPath, Registry
from DIRAC.Core.Utilities.SiteSEMapping import getSEsForSite
__RCSID__ = "$Id$"
logLevel = None
setup = None
configurationServer = None
includeAllServers = False
gatewayServer = None
siteName = None
useServerCert = False
skipCAChecks = False
skipCADownload = False
useVersionsDir = False
architecture = None
localSE = None
ceName = None
vo = None
update = False
outputFile = ''
skipVOMSDownload = False
extensions = ''
def setGateway(optionValue):
global gatewayServer
gatewayServer = optionValue
setServer(gatewayServer + '/Configuration/Server')
DIRAC.gConfig.setOptionValue(cfgInstallPath('Gateway'), gatewayServer)
return DIRAC.S_OK()
def setOutput(optionValue):
global outputFile
outputFile = optionValue
return DIRAC.S_OK()
def setServer(optionValue):
global configurationServer
configurationServer = optionValue
DIRAC.gConfig.setOptionValue('/DIRAC/Configuration/Servers', configurationServer)
DIRAC.gConfig.setOptionValue(cfgInstallPath('ConfigurationServer'), configurationServer)
return DIRAC.S_OK()
def setAllServers(optionValue):
global includeAllServers
includeAllServers = True
def setSetup(optionValue):
global setup
setup = optionValue
DIRAC.gConfig.setOptionValue('/DIRAC/Setup', setup)
DIRAC.gConfig.setOptionValue(cfgInstallPath('Setup'), setup)
return DIRAC.S_OK()
def setSiteName(optionValue):
global siteName
siteName = optionValue
Script.localCfg.addDefaultEntry('/LocalSite/Site', siteName)
DIRAC.__siteName = False
DIRAC.gConfig.setOptionValue(cfgInstallPath('SiteName'), siteName)
return DIRAC.S_OK()
def setCEName(optionValue):
global ceName
ceName = optionValue
DIRAC.gConfig.setOptionValue(cfgInstallPath('CEName'), ceName)
return DIRAC.S_OK()
def setServerCert(optionValue):
global useServerCert
useServerCert = True
DIRAC.gConfig.setOptionValue(cfgInstallPath('UseServerCertificate'), useServerCert)
return DIRAC.S_OK()
def setSkipCAChecks(optionValue):
global skipCAChecks
skipCAChecks = True
DIRAC.gConfig.setOptionValue(cfgInstallPath('SkipCAChecks'), skipCAChecks)
return DIRAC.S_OK()
def setSkipCADownload(optionValue):
global skipCADownload
skipCADownload = True
DIRAC.gConfig.setOptionValue(cfgInstallPath('SkipCADownload'), skipCADownload)
return DIRAC.S_OK()
def setSkipVOMSDownload(optionValue):
global skipVOMSDownload
skipVOMSDownload = True
DIRAC.gConfig.setOptionValue(cfgInstallPath('SkipVOMSDownload'), skipVOMSDownload)
return DIRAC.S_OK()
def setUseVersionsDir(optionValue):
global useVersionsDir
useVersionsDir = True
DIRAC.gConfig.setOptionValue(cfgInstallPath('UseVersionsDir'), useVersionsDir)
return DIRAC.S_OK()
def setArchitecture(optionValue):
global architecture
architecture = optionValue
Script.localCfg.addDefaultEntry('/LocalSite/Architecture', architecture)
DIRAC.gConfig.setOptionValue(cfgInstallPath('Architecture'), architecture)
return DIRAC.S_OK()
def setLocalSE(optionValue):
global localSE
localSE = optionValue
Script.localCfg.addDefaultEntry('/LocalSite/LocalSE', localSE)
DIRAC.gConfig.setOptionValue(cfgInstallPath('LocalSE'), localSE)
return DIRAC.S_OK()
def setVO(optionValue):
global vo
vo = optionValue
Script.localCfg.addDefaultEntry('/DIRAC/VirtualOrganization', vo)
DIRAC.gConfig.setOptionValue(cfgInstallPath('VirtualOrganization'), vo)
return DIRAC.S_OK()
def forceUpdate(optionValue):
global update
update = True
return DIRAC.S_OK()
def setExtensions(optionValue):
global extensions
extensions = optionValue
DIRAC.gConfig.setOptionValue('/DIRAC/Extensions', extensions)
DIRAC.gConfig.setOptionValue(cfgInstallPath('Extensions'), extensions)
return DIRAC.S_OK()
Script.disableCS()
Script.registerSwitch("S:", "Setup=", "Set <setup> as DIRAC setup", setSetup)
Script.registerSwitch("e:", "Extensions=", "Set <extensions> as DIRAC extensions", setExtensions)
Script.registerSwitch("C:", "ConfigurationServer=", "Set <server> as DIRAC configuration server", setServer)
Script.registerSwitch("I", "IncludeAllServers", "include all Configuration Servers", setAllServers)
Script.registerSwitch("n:", "SiteName=", "Set <sitename> as DIRAC Site Name", setSiteName)
Script.registerSwitch("N:", "CEName=", "Determiner <sitename> from <cename>", setCEName)
Script.registerSwitch("V:", "VO=", "Set the VO name", setVO)
Script.registerSwitch("W:", "gateway=", "Configure <gateway> as DIRAC Gateway for the site", setGateway)
Script.registerSwitch("U", "UseServerCertificate", "Configure to use Server Certificate", setServerCert)
Script.registerSwitch("H", "SkipCAChecks", "Configure to skip check of CAs", setSkipCAChecks)
Script.registerSwitch("D", "SkipCADownload", "Configure to skip download of CAs", setSkipCADownload)
Script.registerSwitch("M", "SkipVOMSDownload", "Configure to skip download of VOMS info", setSkipVOMSDownload)
Script.registerSwitch("v", "UseVersionsDir", "Use versions directory", setUseVersionsDir)
Script.registerSwitch("A:", "Architecture=", "Configure /Architecture=<architecture>", setArchitecture)
Script.registerSwitch("L:", "LocalSE=", "Configure LocalSite/LocalSE=<localse>", setLocalSE)
Script.registerSwitch(
"F",
"ForceUpdate",
"Force Update of cfg file (i.e. dirac.cfg) (otherwise nothing happens if dirac.cfg already exists)",
forceUpdate)
Script.registerSwitch("O:", "output=", "output configuration file", setOutput)
Script.setUsageMessage('\n'.join([__doc__.split('\n')[1],
'\nUsage:',
' %s [option|cfgfile] ...\n' % Script.scriptName]))
Script.parseCommandLine(ignoreErrors=True)
args = Script.getExtraCLICFGFiles()
if not logLevel:
logLevel = DIRAC.gConfig.getValue(cfgInstallPath('LogLevel'), '')
if logLevel:
DIRAC.gLogger.setLevel(logLevel)
else:
DIRAC.gConfig.setOptionValue(cfgInstallPath('LogLevel'), logLevel)
if not gatewayServer:
newGatewayServer = DIRAC.gConfig.getValue(cfgInstallPath('Gateway'), '')
if newGatewayServer:
setGateway(newGatewayServer)
if not configurationServer:
newConfigurationServer = DIRAC.gConfig.getValue(cfgInstallPath('ConfigurationServer'), '')
if newConfigurationServer:
setServer(newConfigurationServer)
if not includeAllServers:
newIncludeAllServer = DIRAC.gConfig.getValue(cfgInstallPath('IncludeAllServers'), False)
if newIncludeAllServer:
setAllServers(True)
if not setup:
newSetup = DIRAC.gConfig.getValue(cfgInstallPath('Setup'), '')
if newSetup:
setSetup(newSetup)
if not siteName:
newSiteName = DIRAC.gConfig.getValue(cfgInstallPath('SiteName'), '')
if newSiteName:
setSiteName(newSiteName)
if not ceName:
newCEName = DIRAC.gConfig.getValue(cfgInstallPath('CEName'), '')
if newCEName:
setCEName(newCEName)
if not useServerCert:
newUserServerCert = DIRAC.gConfig.getValue(cfgInstallPath('UseServerCertificate'), False)
if newUserServerCert:
setServerCert(newUserServerCert)
if not skipCAChecks:
newSkipCAChecks = DIRAC.gConfig.getValue(cfgInstallPath('SkipCAChecks'), False)
if newSkipCAChecks:
setSkipCAChecks(newSkipCAChecks)
if not skipCADownload:
newSkipCADownload = DIRAC.gConfig.getValue(cfgInstallPath('SkipCADownload'), False)
if newSkipCADownload:
setSkipCADownload(newSkipCADownload)
if not useVersionsDir:
newUseVersionsDir = DIRAC.gConfig.getValue(cfgInstallPath('UseVersionsDir'), False)
if newUseVersionsDir:
setUseVersionsDir(newUseVersionsDir)
# Set proper Defaults in configuration (even if they will be properly overwrite by gComponentInstaller
instancePath = os.path.dirname(os.path.dirname(DIRAC.rootPath))
rootPath = os.path.join(instancePath, 'pro')
DIRAC.gConfig.setOptionValue(cfgInstallPath('InstancePath'), instancePath)
DIRAC.gConfig.setOptionValue(cfgInstallPath('RootPath'), rootPath)
if not architecture:
newArchitecture = DIRAC.gConfig.getValue(cfgInstallPath('Architecture'), '')
if newArchitecture:
setArchitecture(newArchitecture)
if not vo:
newVO = DIRAC.gConfig.getValue(cfgInstallPath('VirtualOrganization'), '')
if newVO:
setVO(newVO)
if not extensions:
newExtensions = DIRAC.gConfig.getValue(cfgInstallPath('Extensions'), '')
if newExtensions:
setExtensions(newExtensions)
DIRAC.gLogger.notice('Executing: %s ' % (' '.join(sys.argv)))
DIRAC.gLogger.notice('Checking DIRAC installation at "%s"' % DIRAC.rootPath)
if update:
if outputFile:
DIRAC.gLogger.notice('Will update the output file %s' % outputFile)
else:
DIRAC.gLogger.notice('Will update %s' % DIRAC.gConfig.diracConfigFilePath)
if setup:
DIRAC.gLogger.verbose('/DIRAC/Setup =', setup)
if vo:
DIRAC.gLogger.verbose('/DIRAC/VirtualOrganization =', vo)
if configurationServer:
DIRAC.gLogger.verbose('/DIRAC/Configuration/Servers =', configurationServer)
if siteName:
DIRAC.gLogger.verbose('/LocalSite/Site =', siteName)
if architecture:
DIRAC.gLogger.verbose('/LocalSite/Architecture =', architecture)
if localSE:
DIRAC.gLogger.verbose('/LocalSite/localSE =', localSE)
if not useServerCert:
DIRAC.gLogger.verbose('/DIRAC/Security/UseServerCertificate =', 'no')
# Being sure it was not there before
Script.localCfg.deleteOption('/DIRAC/Security/UseServerCertificate')
Script.localCfg.addDefaultEntry('/DIRAC/Security/UseServerCertificate', 'no')
else:
DIRAC.gLogger.verbose('/DIRAC/Security/UseServerCertificate =', 'yes')
# Being sure it was not there before
Script.localCfg.deleteOption('/DIRAC/Security/UseServerCertificate')
Script.localCfg.addDefaultEntry('/DIRAC/Security/UseServerCertificate', 'yes')
host = DIRAC.gConfig.getValue(cfgInstallPath("Host"), "")
if host:
DIRAC.gConfig.setOptionValue(cfgPath("DIRAC", "Hostname"), host)
if skipCAChecks:
DIRAC.gLogger.verbose('/DIRAC/Security/SkipCAChecks =', 'yes')
# Being sure it was not there before
Script.localCfg.deleteOption('/DIRAC/Security/SkipCAChecks')
Script.localCfg.addDefaultEntry('/DIRAC/Security/SkipCAChecks', 'yes')
else:
# Necessary to allow initial download of CA's
if not skipCADownload:
DIRAC.gConfig.setOptionValue('/DIRAC/Security/SkipCAChecks', 'yes')
if not skipCADownload:
Script.enableCS()
try:
dirName = os.path.join(DIRAC.rootPath, 'etc', 'grid-security', 'certificates')
mkDir(dirName)
except BaseException:
DIRAC.gLogger.exception()
DIRAC.gLogger.fatal('Fail to create directory:', dirName)
DIRAC.exit(-1)
try:
from DIRAC.FrameworkSystem.Client.BundleDeliveryClient import BundleDeliveryClient
bdc = BundleDeliveryClient()
result = bdc.syncCAs()
if result['OK']:
result = bdc.syncCRLs()
except BaseException:
DIRAC.gLogger.exception('Could not import BundleDeliveryClient')
pass
if not skipCAChecks:
Script.localCfg.deleteOption('/DIRAC/Security/SkipCAChecks')
if ceName or siteName:
# This is used in the pilot context, we should have a proxy, or a certificate, and access to CS
if useServerCert:
# Being sure it was not there before
Script.localCfg.deleteOption('/DIRAC/Security/UseServerCertificate')
Script.localCfg.addDefaultEntry('/DIRAC/Security/UseServerCertificate', 'yes')
Script.enableCS()
# Get the site resource section
gridSections = DIRAC.gConfig.getSections('/Resources/Sites/')
if not gridSections['OK']:
DIRAC.gLogger.warn('Could not get grid sections list')
grids = []
else:
grids = gridSections['Value']
# try to get siteName from ceName or Local SE from siteName using Remote Configuration
for grid in grids:
siteSections = DIRAC.gConfig.getSections('/Resources/Sites/%s/' % grid)
if not siteSections['OK']:
DIRAC.gLogger.warn('Could not get %s site list' % grid)
sites = []
else:
sites = siteSections['Value']
if not siteName:
if ceName:
for site in sites:
siteCEs = DIRAC.gConfig.getValue('/Resources/Sites/%s/%s/CE' % (grid, site), [])
if ceName in siteCEs:
siteName = site
break
if siteName:
DIRAC.gLogger.notice('Setting /LocalSite/Site = %s' % siteName)
Script.localCfg.addDefaultEntry('/LocalSite/Site', siteName)
DIRAC.__siteName = False
if ceName:
DIRAC.gLogger.notice('Setting /LocalSite/GridCE = %s' % ceName)
Script.localCfg.addDefaultEntry('/LocalSite/GridCE', ceName)
if not localSE and siteName in sites:
localSE = getSEsForSite(siteName)
if localSE['OK'] and localSE['Value']:
localSE = ','.join(localSE['Value'])
DIRAC.gLogger.notice('Setting /LocalSite/LocalSE =', localSE)
Script.localCfg.addDefaultEntry('/LocalSite/LocalSE', localSE)
break
if gatewayServer:
DIRAC.gLogger.verbose('/DIRAC/Gateways/%s =' % DIRAC.siteName(), gatewayServer)
Script.localCfg.addDefaultEntry('/DIRAC/Gateways/%s' % DIRAC.siteName(), gatewayServer)
# Create the local cfg if it is not yet there
if not outputFile:
outputFile = DIRAC.gConfig.diracConfigFilePath
outputFile = os.path.abspath(outputFile)
if not os.path.exists(outputFile):
configDir = os.path.dirname(outputFile)
mkDir(configDir)
update = True
DIRAC.gConfig.dumpLocalCFGToFile(outputFile)
# We need user proxy or server certificate to continue
if not useServerCert:
Script.enableCS()
result = getProxyInfo()
if not result['OK']:
DIRAC.gLogger.notice('Configuration is not completed because no user proxy is available')
DIRAC.gLogger.notice('Create one using dirac-proxy-init and execute again with -F option')
sys.exit(1)
else:
Script.localCfg.deleteOption('/DIRAC/Security/UseServerCertificate')
# When using Server Certs CA's will be checked, the flag only disables initial download
# this will be replaced by the use of SkipCADownload
Script.localCfg.deleteOption('/DIRAC/Security/UseServerCertificate')
Script.localCfg.addDefaultEntry('/DIRAC/Security/UseServerCertificate', 'yes')
Script.enableCS()
if includeAllServers:
DIRAC.gConfig.setOptionValue('/DIRAC/Configuration/Servers', ','.join(DIRAC.gConfig.getServersList()))
DIRAC.gLogger.verbose('/DIRAC/Configuration/Servers =', ','.join(DIRAC.gConfig.getServersList()))
if useServerCert:
# always removing before dumping
Script.localCfg.deleteOption('/DIRAC/Security/UseServerCertificate')
Script.localCfg.deleteOption('/DIRAC/Security/SkipCAChecks')
Script.localCfg.deleteOption('/DIRAC/Security/SkipVOMSDownload')
if update:
DIRAC.gConfig.dumpLocalCFGToFile(outputFile)
# ## LAST PART: do the vomsdir/vomses magic
# This has to be done for all VOs in the installation
if skipVOMSDownload:
# We stop here
sys.exit(0)
result = Registry.getVOMSServerInfo()
if not result['OK']:
sys.exit(1)
error = ''
vomsDict = result['Value']
for vo in vomsDict:
voName = vomsDict[vo]['VOMSName']
vomsDirPath = os.path.join(DIRAC.rootPath, 'etc', 'grid-security', 'vomsdir', voName)
vomsesDirPath = os.path.join(DIRAC.rootPath, 'etc', 'grid-security', 'vomses')
for path in (vomsDirPath, vomsesDirPath):
mkDir(path)
vomsesLines = []
for vomsHost in vomsDict[vo].get('Servers', {}):
hostFilePath = os.path.join(vomsDirPath, "%s.lsc" % vomsHost)
try:
DN = vomsDict[vo]['Servers'][vomsHost]['DN']
CA = vomsDict[vo]['Servers'][vomsHost]['CA']
port = vomsDict[vo]['Servers'][vomsHost]['Port']
if not DN or not CA or not port:
DIRAC.gLogger.error('DN = %s' % DN)
DIRAC.gLogger.error('CA = %s' % CA)
DIRAC.gLogger.error('Port = %s' % port)
DIRAC.gLogger.error('Missing Parameter for %s' % vomsHost)
continue
with open(hostFilePath, "wb") as fd:
fd.write("%s\n%s\n" % (DN, CA))
vomsesLines.append('"%s" "%s" "%s" "%s" "%s" "24"' % (voName, vomsHost, port, DN, voName))
DIRAC.gLogger.notice("Created vomsdir file %s" % hostFilePath)
except Exception:
DIRAC.gLogger.exception("Could not generate vomsdir file for host", vomsHost)
error = "Could not generate vomsdir file for VO %s, host %s" % (voName, vomsHost)
try:
vomsesFilePath = os.path.join(vomsesDirPath, voName)
with open(vomsesFilePath, "wb") as fd:
fd.write("%s\n" % "\n".join(vomsesLines))
DIRAC.gLogger.notice("Created vomses file %s" % vomsesFilePath)
except Exception:
DIRAC.gLogger.exception("Could not generate vomses file")
error = "Could not generate vomses file for VO %s" % voName
if useServerCert:
Script.localCfg.deleteOption('/DIRAC/Security/UseServerCertificate')
# When using Server Certs CA's will be checked, the flag only disables initial download
# this will be replaced by the use of SkipCADownload
Script.localCfg.deleteOption('/DIRAC/Security/SkipCAChecks')
if error:
sys.exit(1)
sys.exit(0)
|
fstagni/DIRAC
|
Core/scripts/dirac-configure.py
|
Python
|
gpl-3.0
| 20,249
|
[
"DIRAC"
] |
fd4fc3304df1191169742cf2408eae0b4a2f33ef12a9368705be47b3fdf382bb
|
"""Importers for bookmarks"""
import json
import os
import random
import string
import time
import transaction
from datetime import datetime
from dateutil import parser as dateparser
from BeautifulSoup import BeautifulSoup
from lxml import etree
from lxml.etree import XMLSyntaxError
from bookie.lib.urlhash import generate_hash
from bookie.models import (
BmarkMgr,
DBSession,
InvalidBookmark,
)
IMPORTED = u"importer"
COMMIT_SIZE = 25
def store_import_file(storage_dir, username, files):
# save the file off to the temp storage
out_dir = "{storage_dir}/{randdir}".format(
storage_dir=storage_dir,
randdir=random.choice(string.letters),
)
# make sure the directory exists
# we create it with parents as well just in case
if not os.path.isdir(out_dir):
os.makedirs(out_dir)
out_fname = "{0}/{1}.{2}".format(
out_dir, username, files.filename)
out = open(out_fname, 'w')
out.write(files.file.read())
out.close()
return out_fname
class Importer(object):
"""The actual factory object we use for handling imports"""
def __init__(self, import_io, username=None):
"""work on getting an importer instance"""
self.file_handle = import_io
self.username = username
# we need to get our list of hashes to make sure we check for dupes
self.hash_list = set([b[0] for b in
BmarkMgr.hash_list(username=username)])
def __new__(cls, *args, **kwargs):
"""Overriding new we return a subclass based on the file content"""
if DelImporter.can_handle(args[0]):
return super(Importer, cls).__new__(DelImporter)
if DelXMLImporter.can_handle(args[0]):
return super(Importer, cls).__new__(DelXMLImporter)
if GBookmarkImporter.can_handle(args[0]):
return super(Importer, cls).__new__(GBookmarkImporter)
if FBookmarkImporter.can_handle(args[0]):
return super(Importer, cls).__new__(FBookmarkImporter)
return super(Importer, cls).__new__(Importer)
@staticmethod
def can_handle(file_io):
"""This is meant to be implemented in subclasses"""
raise NotImplementedError("Please implement this in your importer")
def process(self, fulltext=None):
"""Meant to be implemented in subclasses"""
raise NotImplementedError("Please implement this in your importer")
def save_bookmark(self, url, desc, ext, tags, dt=None, is_private=False):
"""Save the bookmark to the db
:param url: bookmark url
:param desc: one line description
:param ext: extended description/notes
:param tags: The string of tags to store with this bmark
:param mark: Instance of Bmark that we're storing to db
"""
# If a bookmark has the tag "private" then we ignore it to prevent
# leaking user data.
if tags and 'private' in tags.lower().split(' '):
return None
check_hash = generate_hash(url)
# We should make sure that this url isn't already bookmarked before
# adding it...if the hash matches, you must skip!
if check_hash not in self.hash_list:
bmark = BmarkMgr.store(
url,
self.username,
desc,
ext,
tags,
dt=dt,
inserted_by=IMPORTED,
is_private=is_private,
)
# Add this hash to the list so that we can skip dupes in the
# same import set.
self.hash_list.add(check_hash)
return bmark
# If we don't store a bookmark then just return None back to the
# importer.
return None
class DelImporter(Importer):
"""Process a delicious html file"""
@staticmethod
def _is_delicious_format(soup, can_handle, delicious_doctype):
"""A check for if this import files is a delicious format compat file
Very fragile currently, it makes sure the first line is the doctype.
Any blank lines before it will cause it to fail
"""
if (soup.contents and
soup.contents[0] == delicious_doctype and
not soup.find('h3')):
can_handle = True
return can_handle
@staticmethod
def can_handle(file_io):
"""Check if this file is a google bookmarks format file
In order to check the file we have to read it and check it's content
type.
Google Bookmarks and Delicious both have the same content type, but
they use different formats. We use the fact that Google Bookmarks
uses <h3> tags and Delicious does not in order to differentiate these
two formats.
"""
delicious_doctype = u'DOCTYPE NETSCAPE-Bookmark-file-1'
soup = BeautifulSoup(file_io)
can_handle = False
can_handle = DelImporter._is_delicious_format(soup,
can_handle,
delicious_doctype)
# make sure we reset the file_io object so that we can use it again
file_io.seek(0)
return can_handle
def process(self):
"""Given a file, process it"""
soup = BeautifulSoup(self.file_handle)
count = 0
ids = []
for tag in soup.findAll('dt'):
if 'javascript:' in str(tag):
continue
# if we have a dd as next sibling, get it's content
if tag.nextSibling and tag.nextSibling.name == 'dd':
extended = tag.nextSibling.text
else:
extended = u""
link = tag.a
is_private = False
if link.has_key('private'): # noqa
is_private = True
import_add_date = float(link['add_date'])
if import_add_date > 9999999999:
# Remove microseconds from the timestamp
import_add_date = import_add_date / 1000
add_date = datetime.fromtimestamp(import_add_date)
try:
bmark = self.save_bookmark(
unicode(link['href']),
unicode(link.text),
unicode(extended),
u" ".join(unicode(link.get('tags', '')).split(u',')),
dt=add_date,
is_private=is_private)
count = count + 1
DBSession.flush()
except InvalidBookmark:
bmark = None
if bmark:
ids.append(bmark.bid)
if count % COMMIT_SIZE == 0:
transaction.commit()
# Commit any that are left since the last commit performed.
transaction.commit()
from bookie.bcelery import tasks
# For each bookmark in this set that we saved, sign up to
# fetch its content.
for bid in ids:
tasks.fetch_bmark_content.delay(bid)
# Start a new transaction for the next grouping.
transaction.begin()
class DelXMLImporter(Importer):
"""Process a delicious xml export file"""
@staticmethod
def _is_delicious_format(parsed, can_handle):
"""A check for if this import files is a delicious xml format compat
The root xml element will be 'posts' if this is the case.
"""
if parsed.docinfo and parsed.docinfo.root_name == 'posts':
can_handle = True
return can_handle
@staticmethod
def can_handle(file_io):
"""Check if this file is a google bookmarks format file
In order to check the file we have to read it and check it's content
type.
Google Bookmarks and Delicious both have the same content type, but
they use different formats. We use the fact that Google Bookmarks
uses <h3> tags and Delicious does not in order to differentiate these
two formats.
"""
try:
file_io.seek(0)
parsed = etree.parse(file_io)
except XMLSyntaxError:
# IF etree can't parse it, it's not our file.
return False
can_handle = False
can_handle = DelXMLImporter._is_delicious_format(parsed,
can_handle)
# make sure we reset the file_io object so that we can use it again
return can_handle
def process(self):
"""Given a file, process it"""
if self.file_handle.closed:
self.file_handle = open(self.file_handle.name)
self.file_handle.seek(0)
parsed = etree.parse(self.file_handle)
count = 0
ids = []
for post in parsed.findall('post'):
if 'javascript:' in post.get('href'):
continue
add_date = dateparser.parse(post.get('time'))
if post.get('private') == "no":
is_private = False
elif post.get('private') == "yes":
is_private = True
try:
bmark = self.save_bookmark(
unicode(post.get('href')),
unicode(post.get('description')),
unicode(post.get('extended')),
unicode(post.get('tag')),
dt=add_date,
is_private=is_private)
count = count + 1
if bmark:
bmark.stored = bmark.stored.replace(tzinfo=None)
DBSession.flush()
except InvalidBookmark:
bmark = None
if bmark:
ids.append(bmark.bid)
if count % COMMIT_SIZE == 0:
transaction.commit()
# Commit any that are left since the last commit performed.
transaction.commit()
from bookie.bcelery import tasks
# For each bookmark in this set that we saved, sign up to
# fetch its content.
for bid in ids:
tasks.fetch_bmark_content.delay(bid)
# Start a new transaction for the next grouping.
transaction.begin()
class GBookmarkImporter(Importer):
"""Process a Google Bookmark export html file"""
@staticmethod
def _is_google_format(soup, gbookmark_doctype, can_handle):
"""Verify that this import file is in the google export format
Google only puts one tag at a time and needs to be looped through to
get them all. See the sample files in the test_importer directory
"""
if (soup.contents and
soup.contents[0] == gbookmark_doctype and
soup.find('h3')):
can_handle = True
return can_handle
@staticmethod
def can_handle(file_io):
"""Check if this file is a google bookmarks format file
In order to check the file we have to read it and check it's content
type
Google Bookmarks and Delicious both have the same content type, but
they use different formats. We use the fact that Google Bookmarks
uses <h3> tags and Delicious does not in order to differentiate these
two formats.
"""
if (file_io.closed):
file_io = open(file_io.name)
file_io.seek(0)
soup = BeautifulSoup(file_io)
can_handle = False
gbookmark_doctype = "DOCTYPE NETSCAPE-Bookmark-file-1"
can_handle = GBookmarkImporter._is_google_format(soup,
gbookmark_doctype,
can_handle)
# make sure we reset the file_io object so that we can use it again
file_io.seek(0)
return can_handle
def process(self):
"""Process an html google bookmarks export and import them into bookie
The export format is a tag as a heading, with urls that have that tag
under that heading. If a url has N tags, it will appear N times, once
under each heading.
"""
count = 0
if (self.file_handle.closed):
self.file_handle = open(self.file_handle.name)
soup = BeautifulSoup(self.file_handle)
if not soup.contents[0] == "DOCTYPE NETSCAPE-Bookmark-file-1":
raise Exception("File is not a google bookmarks file")
urls = dict() # url:url_metadata
# we don't want to just import all the available urls, since each url
# occurs once per tag. loop through and aggregate the tags for each url
for tag in soup.findAll('h3'):
links = tag.findNextSibling('dl')
if links is not None:
links = links.findAll("a")
for link in links:
url = link["href"]
if url.startswith('javascript:'):
continue
tag_text = tag.text.replace(" ", "-")
if url in urls:
urls[url]['tags'].append(tag_text)
else:
tags = [tag_text] if tag_text != 'Unlabeled' else []
# get extended description
has_extended = (
link.parent.nextSibling and
link.parent.nextSibling.name == 'dd')
if has_extended:
extended = link.parent.nextSibling.text
else:
extended = ""
# Must use has_key here due to the link coming from
# the parser and it's not a true dict.
if link.has_key('add_date'): # noqa
if int(link['add_date']) < 9999999999:
timestamp_added = int(link['add_date'])
else:
timestamp_added = float(link['add_date']) / 1e6
else:
link['add_date'] = time.time()
urls[url] = {
'description': link.text,
'tags': tags,
'extended': extended,
'date_added': datetime.fromtimestamp(
timestamp_added),
}
# save the bookmarks
ids = []
for url, metadata in urls.items():
try:
bmark = self.save_bookmark(
unicode(url),
unicode(metadata['description']),
unicode(metadata['extended']),
u" ".join(metadata['tags']),
dt=metadata['date_added'])
DBSession.flush()
except InvalidBookmark:
bmark = None
if bmark:
ids.append(bmark.bid)
if count % COMMIT_SIZE == 0:
transaction.commit()
# Start a new transaction for the next grouping.
transaction.begin()
# Commit any that are left since the last commit performed.
transaction.commit()
from bookie.bcelery import tasks
# For each bookmark in this set that we saved, sign up to
# fetch its content.
for bid in ids:
tasks.fetch_bmark_content.delay(bid)
class FBookmarkImporter(Importer):
"""Process a FireFox backup export json file"""
MOZ_CONTAINER = "text/x-moz-place-container"
@staticmethod
def _is_firefox_format(json, can_handle):
"""Verify that this import file is in the firefox backup
export format
Firefox json file has a variable "type" which is equal to
"text/x-moz-place-container"
"""
if json['type'] == FBookmarkImporter.MOZ_CONTAINER:
can_handle = True
return can_handle
@staticmethod
def can_handle(file_io):
"""Check if this file is a Firefox bookmarks format file
In order to check the file we have to read it and check it's content
has a variable "type" which is equal to "text/x-moz-place-container"
"""
if (file_io.closed):
file_io = open(file_io.name)
file_io.seek(0)
can_handle = False
try:
backup_json = json.load(file_io)
except:
file_io.seek(0)
return can_handle
can_handle = FBookmarkImporter._is_firefox_format(backup_json,
can_handle)
# make sure we reset the file_io object so that we can use it again
file_io.seek(0)
return can_handle
def bmap_add(self, bmark, bmap):
if bmark["uri"] not in bmap:
bmap[bmark["uri"]] = bmark
def process(self):
"""Process an json firefox bookmarks export and import them into bookie
"""
MOZ_PLACE = "text/x-moz-place"
UNWANTED_SCHEME = ("data", "place", "javascript")
count = 0
if (self.file_handle.closed):
self.file_handle = open(self.file_handle.name)
content = self.file_handle.read().decode("UTF-8")
# HACK: Firefox' JSON writer leaves a trailing comma
# HACK: at the end of the array, which no parser accepts
if content.endswith(u"}]},]}"):
content = content[:-6] + u"}]}]}"
root = json.loads(content)
# make a dictionary of unique bookmarks
bmap = {}
# check if uri of child starts with "data", "place", "javascript"
def is_good(child):
return not child["uri"].split(":", 1)[0] in UNWANTED_SCHEME
# find toplevel subfolders and tag folders
folders = []
tagfolders = []
for child in root["children"]:
if child.get("root") == "tagsFolder":
tagfolders.extend(child["children"])
elif child.get("root"):
folders.append(child)
# visit all subfolders recursively
visited = set()
while folders:
next = folders.pop()
if next["id"] in visited:
continue
for child in next["children"]:
if child["type"] == self.MOZ_CONTAINER:
folders.append(child)
tagfolders.append(child)
elif child["type"] == MOZ_PLACE and \
child.get("uri") and \
is_good(child):
self.bmap_add(child, bmap)
visited.add(next["id"])
# visit all tag folders
for tag in tagfolders:
for bmark in tag["children"]:
if bmark["type"] == MOZ_PLACE and \
bmark.get("uri") and \
is_good(bmark):
self.bmap_add(bmark, bmap)
if "tags" not in bmap[bmark["uri"]]:
bmap[bmark["uri"]]["tags"] = []
bmap[bmark["uri"]]["tags"].append(
tag["title"].replace(" ", "-"))
# save the bookmarks
# annos has the information about the url like name, flags, expires,
# value, type etc
ids = []
for url, metadata in bmap.items():
if metadata.get('annos') is not None:
if metadata.get('annos')[0].get('value') is None:
metadata['annos'][0]['value'] = ''
else:
metadata['annos'] = [{}]
metadata['annos'][0]['value'] = ''
if metadata.get('tags') is None:
metadata['tags'] = ''
try:
bookmark = self.save_bookmark(
unicode(url),
unicode(metadata['title']),
unicode(metadata['annos'][0]['value']),
u" ".join(metadata['tags']),
dt=datetime.fromtimestamp(
metadata['dateAdded']/1e6))
DBSession.flush()
except InvalidBookmark:
bookmark = None
if bookmark:
ids.append(bookmark.bid)
if count % COMMIT_SIZE == 0:
transaction.commit()
# Start a new transaction for the next grouping.
transaction.begin()
# Commit any that are left since the last commit performed.
transaction.commit()
from bookie.bcelery import tasks
# For each bookmark in this set that we saved, sign up to
# fetch its content.
for bid in ids:
tasks.fetch_bmark_content.delay(bid)
|
charany1/Bookie
|
bookie/lib/importer.py
|
Python
|
agpl-3.0
| 20,851
|
[
"VisIt"
] |
f091eca57452bb4c99110cd7607bd9adda95fba90796c4ff3320bde6a19725c5
|
# -*- coding: utf-8 -*-
"""
Created on Sun Dec 03 21:54:41 2017
@author: TUNTUNGAN
"""
from datetime import timedelta,datetime
import numpy as np
import re
import os.path
from scipy import signal
import pandas as pd
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
def step_removal_process(data,threshold,comp):
#Smooth the data using a median filter to remove spikes and the Savitzky-Golay running average filter
Binterp = data.interpolate(method = 'linear')
medfiltB = signal.medfilt(Binterp.values[:], 3);
vAvgResampB = signal.savgol_filter(medfiltB,17,1);
diffB = np.diff(vAvgResampB)
steps = [i for i,v in enumerate(abs(diffB)) if v > threshold]
if np.array(steps).size:
breakpoints = [i for i,v in enumerate(np.diff(steps)) if v > 1]
print('Number of ',comp,' breakpoints: '+str(len(breakpoints)))
#Go through each break point and sum up the accumulated change
breakpoints = [-1]+breakpoints+[len(steps)-1] # put a zero at the start for each of looping and the final point
for i in range(0,len(breakpoints)-1):
st = breakpoints[i]+1; en = breakpoints[i+1]
#Extend the edges of the step detection back and forward a few
#points and check you haven't gone over the edge of the time-series
stp=steps[st]-2 if steps[st]>3 else steps[st]
enp=steps[en]+2 if steps[en]<(len(diffB)-3) else steps[en]
#Compute the change in the field across the step by cumulatively
#summing up the differences from point-to-point
change = np.cumsum(diffB[stp:enp+1])
#Now remove it from the time series starting at the revelant point
vAvgResampB[stp:enp+1] = vAvgResampB[stp:enp+1] - change
vAvgResampB[enp+1:-1] = vAvgResampB[enp+1:-1] - change[-1]
return vAvgResampB
def step_removal(date1,threshold,namefolderlemi,namefolder_out):
#Define data
tahun1 = int((date1-timedelta(days=1)).year)
bulan1 = int((date1-timedelta(days=1)).month)
tanggal1 = int((date1-timedelta(days=1)).day)
tahun2 = int(date1.year)
bulan2 = int(date1.month)
tanggal2 = int(date1.day)
hh=np.zeros(1440)
dd=np.zeros(1440)
zz=np.zeros(1440)
ff=np.zeros(1440)
xx=np.zeros(1440)
yy=np.zeros(1440)
h_mean=np.zeros(1440)
d_mean=np.zeros(1440)
z_mean=np.zeros(1440)
f_mean=np.zeros(1440)
x_mean=np.zeros(1440)
y_mean=np.zeros(1440)
#Koefisien Gaussian filter
gaussFilter=[0.00045933,0.00054772,0.00065055,0.00076964,0.00090693,
0.00106449,0.00124449,0.00144918,0.00168089,0.00194194,0.00223468,
0.0025614,0.0029243,0.00332543,0.00376666,0.00424959,0.00477552,
0.00534535,0.00595955,0.00661811,0.00732042,0.0080653,0.0088509,
0.00967467,0.01053338,0.01142303,0.01233892,0.01327563,0.01422707,
0.01518651,0.01614667,0.01709976,0.01803763,0.01895183,0.01983377,
0.0206748,0.02146643,0.02220039,0.02286881,0.02346437,0.0239804,
0.02441104,0.02475132,0.02499727,0.02514602,0.0251958,0.02514602,
0.02499727,0.02475132,0.02441104,0.0239804,0.02346437,0.02286881,
0.02220039,0.02146643,0.0206748,0.01983377,0.01895183,0.01803763,
0.01709976,0.01614667,0.01518651,0.01422707,0.01327563,0.01233892,
0.01142303,0.01053338,0.00967467,0.0088509,0.0080653,0.00732042,
0.00661811,0.00595955,0.00534535,0.00477552,0.00424959,0.00376666,
0.00332543,0.0029243,0.0025614,0.00223468,0.00194194,0.00168089,
0.00144918,0.00124449,0.00106449,0.00090693,0.00076964,0.00065055,
0.00054772,0.00045933]
#Parameter Stasiun
with open('station.ini') as f_init:
content_init = f_init.readlines()
datasta = list(np.tile(np.nan,len(content_init)))
for i in range(0,len(content_init)):
datasta[i] = re.split('\=|\n',content_init[i])
#Import data Lemi
filename1 = '%4.0f\\%02.0f\\%4.0f %02.0f %02.0f 00 00 00.txt' % (tahun1,bulan1,tahun1,bulan1,tanggal1)
filename2 = '%4.0f\\%02.0f\\%4.0f %02.0f %02.0f 00 00 00.txt' % (tahun2,bulan2,tahun2,bulan2,tanggal2)
try:
# if os.path.isfile(namefolderlemi + '/' + filename1)==True and os.path.isfile(namefolderlemi + '/' + filename2)==True:
with open(namefolderlemi + '/' + filename1) as f_lemi1:
content1 = f_lemi1.readlines()
dates1 = list(np.tile(np.nan,len(content1)))
for i in range(0,len(content1)):
data1 = re.split('\s+',content1[i])
Bx1 = float(data1[6]) #+ 41300
By1 = float(data1[7])
Bz1 = float(data1[8]) #- 7100
dates1[i] = list((data1[0]+'-'+data1[1]+'-'+data1[2]+' '+data1[3]+':'+data1[4]+':'+data1[5],Bx1,By1,Bz1))
datadates1 = pd.DataFrame(dates1,columns=['dt', 'Bx', 'By', 'Bz'])
except:
print('File '+filename1+' not exist')
try:
with open(namefolderlemi + '/' + filename2) as f_lemi2:
content2 = f_lemi2.readlines()
dates2 = list(np.tile(np.nan,len(content2)))
for i in range(0,len(content2)):
data2 = re.split('\s+',content2[i])
Bx2 = float(data2[6]) #+ 41300
By2 = float(data2[7])
Bz2 = float(data2[8]) #- 7100
dates2[i] = list((data2[0]+'-'+data2[1]+'-'+data2[2]+' '+data2[3]+':'+data2[4]+':'+data2[5],Bx2,By2,Bz2))
datadates2 = pd.DataFrame(dates2,columns=['dt', 'Bx', 'By', 'Bz'])
except:
print('File '+filename2+' not exist' )
timefull = pd.date_range(date1-timedelta(days=1), periods=172800, freq='s')
timeadd = pd.concat([datadates1,datadates2], ignore_index=True)
timeadd.index = pd.DatetimeIndex(timeadd.dt)
datafull = timeadd.reindex(timefull)
#Now look for steps and remove them ...
#Threshold is how large in nT/sample do you want to consider a step? it is important to set this correctly
#Removing step
vAvgResampX = step_removal_process(datafull.Bx,threshold,'X')
vAvgResampY = step_removal_process(datafull.By,threshold,'Y')
vAvgResampZ = step_removal_process(datafull.Bz,threshold,'Z')
#Smooth the data using a median filter to remove final spikes
finalX = signal.medfilt(vAvgResampX, 3)
finalY = signal.medfilt(vAvgResampY, 3)
finalZ = signal.medfilt(vAvgResampZ, 3)
finalF = np.sqrt((finalX**2)+(finalY**2)+(finalZ**2))
finalH = np.sqrt(finalX**2+finalY**2)
finalD = 60*np.degrees(np.arcsin(finalY/finalH))
#1 Minute mean value using gaussian filter
gaussFilter=gaussFilter/np.sum(gaussFilter)
for i in range(0,1440):
H_conv=np.convolve(finalH[86354+(60*i):86445+(60*i)],gaussFilter)
D_conv=np.convolve(finalD[86354+(60*i):86445+(60*i)],gaussFilter)
Z_conv=np.convolve(finalZ[86354+(60*i):86445+(60*i)],gaussFilter)
F_conv=np.convolve(finalF[86354+(60*i):86445+(60*i)],gaussFilter)
X_conv=np.convolve(finalX[86354+(60*i):86445+(60*i)],gaussFilter)
Y_conv=np.convolve(finalY[86354+(60*i):86445+(60*i)],gaussFilter)
hh[i]=H_conv[90]
dd[i]=D_conv[90]
zz[i]=Z_conv[90]
ff[i]=F_conv[90]
xx[i]=X_conv[90]
yy[i]=Y_conv[90]
#Hitung rata-rata satu menit
for k in range(0,1440):
if np.isnan(hh[k])==True:
h_mean[k]=99999.00
else:
h_mean[k]=hh[k]
if np.isnan(dd[k])==True:
d_mean[k]=99999.00
else:
d_mean[k]=dd[k]
if np.isnan(zz[k])==True:
z_mean[k]=99999.00
else:
z_mean[k]=zz[k]
if np.isnan(ff[k])==True:
f_mean[k]=99999.00
else:
f_mean[k]=ff[k]
if np.isnan(xx[k])==True:
x_mean[k]=99999.00
else:
x_mean[k]=xx[k]
if np.isnan(yy[k])==True:
y_mean[k]=99999.00
else:
y_mean[k]=yy[k]
#Menyimpan file output
fileout = 'TUN'+str(date1.year)+str(date1.month).zfill(2)+str(date1.day).zfill(2)+'pmin'+'.min'
namefolder = namefolder_out
f_iaga = open(namefolder + '/' + fileout, 'w')
f_iaga.write(' Format IAGA-2002 |\n')
f_iaga.write(' Source of Data BMKG |\n')
f_iaga.write(' Station Name %-45s|\n'%datasta[1][1])
f_iaga.write(' IAGA Code %-45s|\n'%datasta[2][1])
f_iaga.write(' Geodetic Latitude %-45s|\n'%datasta[8][1])
f_iaga.write(' Geodetic Longitude %-45s|\n'%datasta[9][1])
f_iaga.write(' Elevation %-45s|\n'%datasta[5][1])
f_iaga.write(' Reported DHZF |\n')
f_iaga.write(' Sensor Orientation XYZ |\n')
f_iaga.write(' Digital Sampling 1 second |\n')
f_iaga.write(' Data Interval Type Filtered 1-minute (00:15-01:45) |\n')
f_iaga.write(' Data Type provisional |\n')
f_iaga.write(' #F=sqrt((Bx^2)+(By^2)+(Bz^2)),H=sqrt(Bx^2+By^2),D=60*asind(By/H) |\n')
f_iaga.write('DATE TIME DOY TUND TUNH TUNZ TUNF |\n')
for j in range(0,1440):
body_iaga = '%s %9.2f %9.2f %9.2f %9.2f\n' %((datetime(year=int(date1.year),month=int(date1.month),
day=int(date1.day))+timedelta(minutes=j)).strftime("%Y-%m-%d %H:%M:00.000 %j"),
d_mean[j],h_mean[j],z_mean[j],f_mean[j])
f_iaga.write(body_iaga)
f_iaga.close()
print(fileout+' has been created')
print('Creating graphic, please wait...')
#PLOT GRAFIK
t=pd.date_range(date1.strftime('%d-%B-%Y 00:00'),date1.strftime('%d-%B-%Y 23:59'),freq="1min")
plt.rcParams['axes.linewidth'] = 0.3
xfmt = mdates.DateFormatter('%H:%M')
fig, axs = plt.subplots(3, 2, sharex=True)
fig.subplots_adjust(hspace=0)
fig.suptitle(str.upper(date1.strftime('%d %B %Y')), fontsize=16, fontweight='bold', color='k')
fig.set_size_inches(12.5, 8.5, forward=True)
#PLOT Sebelum
dataX = datafull.Bx[86400:172800]
dataY = datafull.By[86400:172800]
dataZ = datafull.Bz[86400:172800]
#X Sebelum
axs[0,0].plot(dataX, linewidth=1, color='r')
axs[0,0].grid(b=True, which='major', color='c', linestyle=':', linewidth=0.5)
axs[0,0].set_ylabel('X COMPONENT\n (nT)', fontsize=10)
axs[0,0].set_title('SEBELUM', fontsize=12, fontweight='bold', color='r')
#Y Sebelum
axs[1,0].plot(dataY, linewidth=1, color='g')
axs[1,0].grid(b=True, which='major', color='c', linestyle=':', linewidth=0.5)
axs[1,0].set_ylabel('Y COMPONENT\n (nT)', fontsize=10)
#Z Sebelum
axs[2,0].plot(dataZ, linewidth=1, color='b')
axs[2,0].grid(b=True, which='major', color='c', linestyle=':', linewidth=0.5)
axs[2,0].set_ylabel('Z COMPONENT\n (nT)', fontsize=10)
axs[2,0].set_xlabel('Time', fontsize=10)
#PLOT Sesudah
#X Sesudah
axs[0,1].plot(t, x_mean, linewidth=1, color='r')
axs[0,1].grid(b=True, which='major', color='c', linestyle=':', linewidth=0.5)
axs[0,1].set_title('SESUDAH', fontsize=12, fontweight='bold', color='r')
axs[0,1].set_ylabel('X COMPONENT\n (nT)', fontsize=10)
axs[0,1].yaxis.set_label_position("right")
axs[0,1].yaxis.tick_right()
#Y Sesudah
axs[1,1].plot(t, y_mean, linewidth=1, color='g')
axs[1,1].grid(b=True, which='major', color='c', linestyle=':', linewidth=0.5)
axs[1,1].set_ylabel('Y COMPONENT\n (nT)', fontsize=10)
axs[1,1].yaxis.set_label_position("right")
axs[1,1].yaxis.tick_right()
#Z Sesudah
axs[2,1].plot(t, z_mean, linewidth=1, color='b')
axs[2,1].grid(b=True, which='major', color='c', linestyle=':', linewidth=0.5)
axs[2,1].set_ylabel('Z COMPONENT\n (nT)', fontsize=10)
axs[2,1].yaxis.set_label_position("right")
axs[2,1].yaxis.tick_right()
axs[2,1].set_xlabel('Time', fontsize=10)
axs[2,1].xaxis.set_major_formatter(xfmt)
axs[2,1].set_xlim(min(t),max(t))
plt.show()
print('Finish\n')
|
ragabhumi/MRDP
|
step_remove.py
|
Python
|
gpl-3.0
| 12,400
|
[
"Gaussian"
] |
7a08fd1ce5dda859a69ae64680456a55c2779b902c698041acb349abe76b794f
|
#!/usr/bin/env python3
#* This file is part of the MOOSE framework
#* https://www.mooseframework.org
#*
#* All rights reserved, see COPYRIGHT for full restrictions
#* https://github.com/idaholab/moose/blob/master/COPYRIGHT
#*
#* Licensed under LGPL 2.1, please see LICENSE for details
#* https://www.gnu.org/licenses/lgpl-2.1.html
import os, re, math, sys, argparse
from decimal import Decimal
class CSVTools:
def __init__(self):
self.__num_errors = 0
self.__msg = []
def addError(self, f, message):
"""Add error message and increment the error count"""
self.__msg.append('In file ' + os.path.basename(f.name) + ': ' + message)
self.__num_errors += 1
return self.__msg
def addMessage(self, message):
"""Add a message to be printed before exit"""
self.__msg.append(message)
def getMessages(self):
"""Return stored messages"""
return self.__msg
def getNumErrors(self):
"""Return number of errors"""
return self.__num_errors
def convertToTable(self, files):
"""Convert text to a map of column names to column values"""
table_pair = []
for f in files:
f.seek(0)
text = f.read()
text = re.sub( r'\n\s*\n', '\n', text).strip()
# Exceptions occur if you try to parse a .e file
try:
lines = text.split('\n')
headers = [x.strip() for x in lines.pop(0).split(',')]
table = {}
for header in headers:
table[header] = []
for row in lines:
vals = row.split(',')
if len(headers) != len(vals):
self.addError(f, "Number of columns ("+str(len(vals))+") not the same as number of column names ("+str(len(headers))+") in row "+repr(row))
break
for header, val in zip(headers,vals):
try:
table[header].append(float(val))
except:
# ignore strings
table[header].append(0)
except Exception as e:
self.addError(f, "Exception parsing file: "+str(e.args))
return {}
table_pair.append(table)
return table_pair
def getParamValues(self, param, param_line):
""" return a list of discovered values for param """
return re.findall(param + "\s+([0-9e.\-\+]+)", param_line)
def parseComparisonFile(self, config_file):
""" Walk through comparison file and populate/return a dictionary as best we can """
# A set of known paramater naming conventions. The comparison file can have these set, and we will use them.
zero_params = set(['floor', 'abs_zero', 'absolute'])
tolerance_params = set(['relative', 'rel_tol'])
custom_params = {'RELATIVE' : 0.0, 'ZERO' : 0.0, 'FIELDS' : {} }
config_file.seek(0)
for a_line in config_file:
s_line = a_line.strip()
words = set(a_line.split())
# Ignore this line if commented, is the 'time steps' header, or contains logical nots
if s_line and \
(s_line.startswith("#") \
or s_line.lower().find('time steps') == 0 \
or s_line[0] == "!"):
continue
field_key = re.findall(r'^\s+(\S+)', a_line)
if field_key:
custom_params['FIELDS'][field_key[0]] = {}
# Capture invalid/empty paramater key values
try:
# Possible global header containing floor params
if not re.match(r'^\s', a_line) and words.intersection(zero_params):
custom_params['ZERO'] = self.getParamValues(words.intersection(zero_params).pop(), a_line)[0]
# Possible global header containing tolerance params
if not re.match(r'^\s', a_line) and words.intersection(tolerance_params):
custom_params['RELATIVE'] = self.getParamValues(words.intersection(tolerance_params).pop(), a_line)[0]
# Possible field containing floor params
if field_key and words.intersection(zero_params):
custom_params['FIELDS'][field_key[0]]['ZERO'] = self.getParamValues(words.intersection(zero_params).pop(), a_line)[0]
# Possible field containing tolerance params
if field_key and words.intersection(tolerance_params):
custom_params['FIELDS'][field_key[0]]['RELATIVE'] = self.getParamValues(words.intersection(tolerance_params).pop(), a_line)[0]
except IndexError:
self.addError(config_file, "Error parsing comparison file on line: \n%s" % (a_line))
return custom_params
class CSVSummary(CSVTools):
def __init__(self, args):
CSVTools.__init__(self)
self.files = args.summary
self.abs_zero = float(args.abs_zero)
self.rel_tol = float(args.relative_tolerance)
def __enter__(self):
return self
def __exit__(self, exc_type, exc_value, traceback):
for a_file in self.files:
a_file.close()
def _getMinMax(field_list):
""" return the minimum and maximum values in the list along with the row id they were discovered on """
return
def summary(self):
""" Parse the CSV file and generate a summary """
table1 = self.convertToTable(self.files)[0]
if self.getNumErrors():
return self.getMessages()
formatted_messages = ['GLOBAL VARIABLES relative %s floor %s' % (self.rel_tol, self.abs_zero) ]
field_len = []
value_len = []
for field, value in table1.items():
field_len.append(len(field))
value_len.append(len("# min: %.3e @ t%d" % (Decimal(min(value)), value.index(min(value)))))
field_justify = max(field_len) + 10
value_justify = max(value_len) + 5
# Generate a 'TIME STEPS' summary line if a time field does not exist. This is to maintain compliance with an exodiff summary
if 'time' not in [x.lower() for x in table1.keys()]:
value_count = len(table1[table1.keys()[0]]) - 1
formatted_messages.insert(0, 'TIME STEPS relative 1 floor 0 # min: 0 @ t0 max: %d @ t%d\n' % (value_count, value_count))
for field, value in table1.items():
if field.lower() == 'time':
# Tolerance for time steps will be the same for value tolerances for now (future csvdiff capability will separate this tolerance)
formatted_messages.insert(0, 'TIME STEPS relative %s floor %s # min: %d @ t%d max: %d @ t%d\n' % \
( self.rel_tol, self.abs_zero, min(value), value.index(min(value)), max(value), value.index(max(value))))
formatted_messages.append('%s%s%s# min: %.3e @ t%d%smax: %.3e @ t%d' % \
(" "*4,
field,
" "*((field_justify - len(field)) + 10),
Decimal(min(value)), value.index(min(value)),
" "*((value_justify - len("# min: %.3e @ t%d" % (Decimal(min(value)), value.index(min(value))))) + 5),
Decimal(max(value)), value.index(max(value))))
self.addMessage('\n'.join(formatted_messages))
return self.getMessages()
class CSVDiffer(CSVTools):
def __init__(self, args):
CSVTools.__init__(self)
self.files = args.csv_file
self.config = args.comparison_file
self.abs_zero = float(args.abs_zero)
self.rel_tol = float(args.relative_tolerance)
self.custom_columns = args.custom_columns
self.custom_rel_err = args.custom_rel_err
self.custom_abs_zero = args.custom_abs_zero
self.__only_compare_custom = False
def __enter__(self):
return self
def __exit__(self, exc_type, exc_value, traceback):
for a_file in self.files:
a_file.close()
if self.config:
self.config.close()
# diff the files added to the system and return a message of differences
# This method should only be called once. If it called again you must
# manually clear messages by calling clearDiff
def diff(self):
abs_zero = self.abs_zero
rel_tol = self.rel_tol
# Setup custom values based on supplied config file. Override any information
# in self.custom_colums (indeed, verifyArgs will not allow both --custom and
# --config to be used together anyway)
if self.config:
self.__only_compare_custom = True
custom_params = self.parseComparisonFile(self.config)
abs_zero = custom_params.get('ZERO', abs_zero)
rel_tol = custom_params.get('RELATIVE', rel_tol)
if self.getNumErrors():
return self.getMessages()
self.custom_columns = []
self.custom_rel_err = []
self.custom_abs_zero = []
for field_id, value in custom_params['FIELDS'].items():
self.custom_columns.append(field_id)
self.custom_abs_zero.append(value.get('ZERO', abs_zero))
self.custom_rel_err.append(value.get('RELATIVE', rel_tol))
# Setup data structures for holding customized relative tolerance and absolute
# zero values and flag for checking variable names
rel_err_map = {}
abs_zero_map = {}
found_column = {}
if self.custom_columns:
for i in range(0, len(self.custom_columns)):
rel_err_map[self.custom_columns[i]] = float(self.custom_rel_err[i])
abs_zero_map[self.custom_columns[i]] = float(self.custom_abs_zero[i])
found_column[self.custom_columns[i]] = False
# use this value to skip the rest of the tests when we've found an error
# the order of the tests is most general to most specific, so if a general
# one fails then the more specific ones will probably not only fail, but
# crash the program because it's looking in a column that doesn't exist
(table1, table2) = self.convertToTable(self.files)
# Make sure header names are the same (also makes sure # cols is the same)
# This way it reports what column is missing, not just # cols is different
keys1 = table1.keys()
keys2 = table2.keys()
(large,small) = (keys1,keys2)
# check if custom tolerances used, column name exists in one of
# the CSV files
if self.custom_columns and self.__only_compare_custom:
# For the rest of the comparison, we only care about custom columns
keys1 = self.custom_columns
for key in self.custom_columns:
if key not in small or key not in large:
self.addError(self.files[0], "Header '" + key + "' is missing")
elif len(keys1) < len(keys2):
(large,small) = (keys2,keys1)
for key in large:
if key not in small:
self.addError(self.files[0], "Header '" + key + "' is missing")
elif len(keys1) > len(keys2):
for key in large:
if key not in small:
self.addError(self.files[1], "Header '" + key + "' is missing")
else:
for key in keys1:
found_column[key] = True
if self.getNumErrors():
return self.getMessages()
# now check that each column is the same length
for key in keys1:
if len(table1[key]) != len(table2[key]):
self.addError(self.files[0], "Columns with header '" + key + "' aren't the same length")
# assume all columns are the same length, so don't report the other errors
break
if self.getNumErrors():
return self.getMessages()
# now check all the values in the table
for key in keys1:
for val1, val2 in zip( table1[key], table2[key] ):
# if customized tolerances specified use them otherwise
# use the default
if self.custom_columns:
try:
abs_zero = abs_zero_map[key]
except:
abs_zero = self.abs_zero
if abs(val1) < abs_zero:
val1 = 0
if abs(val2) < abs_zero:
val2 = 0
# disallow nan in the gold file
if math.isnan(val1):
self.addError(self.files[0], "The values in column \"" + key.strip() + "\" contain NaN")
# disallow inf in the gold file
if math.isinf(val1):
self.addError(self.files[0], "The values in column \"" + key.strip() + "\" contain Inf")
# if they're both exactly zero (due to the threshold above) then they're equal so pass this test
if val1 == 0 and val2 == 0:
continue
rel_diff = 0
if max( abs(val1), abs(val2) ) > 0:
rel_diff = abs( ( val1 - val2 ) / max( abs(val1), abs(val2) ) )
# if customized tolerances specified use them otherwise
# use the default
if self.custom_columns:
try:
rel_tol = rel_err_map[key]
except:
rel_tol = self.rel_tol
if rel_diff > rel_tol:
self.addError(self.files[1], "The values in column \"%s\" don't match @ t%d\n\trelative diff: %.3e ~ %.3e = %.3e (%.3e)" % (key.strip(),
table2[key].index(val2),
val1,
val2,
rel_diff,
Decimal(rel_diff)))
# assume all other vals in this column are wrong too, so don't report them
break
# Loop over variable names to check if any are missing from all the
# CSV files being compared
if self.custom_columns and not self.__only_compare_custom:
for mykey2 in self.custom_columns:
if not found_column[mykey2]:
self.addError(self.files[0], "all CSV files Variable '" + mykey2 + "' in custom_columns is missing" )
return self.getMessages()
def verifyArgs(args):
problems = []
if not args.csv_file and not args.summary:
problems.append('No input files given')
elif len(args.csv_file) != 2 and not args.summary:
problems.append('Specify two files to compare')
elif args.csv_file and args.summary:
problems.append('Incorrect positional arguments, or you are trying to perform a diff and show a summary (can only do one or the other)')
elif args.summary and args.comparison_file:
print('Ignoring request to use config file while being asked to display a summary\n')
# Check if all custom args are populated correctly
unify_custom_args = [x for x in [args.custom_columns, args.custom_abs_zero, args.custom_rel_err] if x != None]
if unify_custom_args and len(unify_custom_args) != 3:
problems.append('When using any --custom-* option, you must use all three')
elif unify_custom_args:
if len(set([len(x) for x in unify_custom_args])) > 1:
problems.append('All --custom-* options need to contain the same number of space separated items')
if unify_custom_args and args.comparison_file:
problems.append('When supplying a config file (--comparison-file|-c), you can not use any --custom-* args')
for a_problem in problems:
print(a_problem)
if problems:
sys.exit(1)
return args
def parseArgs(args=None):
parser = argparse.ArgumentParser(description='Tool for testing differences between two CSV files')
parser.add_argument('csv_file', nargs='*', type=argparse.FileType('r'))
parser.add_argument('--summary', '-s', nargs=1, type=argparse.FileType('r'), metavar='csv_file', help='Produce a summary in csvdiff input format')
parser.add_argument('--comparison-file', '-c', type=argparse.FileType('r'), metavar='comparison_file', help='Use comparison configuration file (can be generated using --summary|-s)')
parser.add_argument('--ignore-fields', '-i', nargs='+', metavar='id', help='Ignore specified space-separated field IDs')
parser.add_argument('--diff-fields', '-f', nargs='+', metavar='id', help='Perform diff tests only on space-separated field IDs')
parser.add_argument('--abs-zero', metavar='absolute zero', default='1e-11', help='Value representing an absolute zero (default: 1e-11)')
parser.add_argument('--relative-tolerance', metavar='tolerance', default='5.5e-6', help='Value representing the acceptable tolerance between comparisons (default: 5.5e-6)')
parser.add_argument('--custom-columns', nargs='+', metavar='field', help='Space separated list of custom field IDs to compare')
parser.add_argument('--custom-abs-zero', nargs='+', metavar='exponential', help='Space separated list of corresponding exponential absolute zero values for --custom-colums')
parser.add_argument('--custom-rel-err', nargs='+', metavar='exponential', help='Space separated list of corresponding acceptable exponential tolerance values for --custom-colums')
return verifyArgs(parser.parse_args(args))
if __name__ == '__main__':
args = parseArgs()
if args.summary:
with CSVSummary(args) as csv_summary:
messages = csv_summary.summary()
errors = csv_summary.getNumErrors()
else:
with CSVDiffer(args) as csv_differ:
messages = csv_differ.diff()
errors = csv_differ.getNumErrors()
for a_message in messages:
print(a_message)
if not errors and not args.summary:
print("Files are the same")
if errors:
sys.exit(1)
|
nuclear-wizard/moose
|
python/mooseutils/csvdiff.py
|
Python
|
lgpl-2.1
| 18,912
|
[
"MOOSE"
] |
3b3bd5a8f351abd84e6312f693ea20dae762bee7aeeeee1c1517c494acbb57b9
|
from django.db import models
from django.core.mail import send_mail
from django.core.urlresolvers import reverse
import os
import urllib
import uuid
# Create your models here.
class Subscriber(models.Model):
email = models.EmailField(max_length=254)
active = models.BooleanField(default=False)
confirm_key = models.UUIDField(primary_key=False, default=uuid.uuid4)
subscribe_date = models.DateField(auto_now_add=True)
def confirm_url(self, hostname, secure = False):
return "{host}{path}?{params}".format(
host = hostname,
path = reverse('register_user'),
params = urllib.urlencode({'k': self.confirm_key})
)
def send_subscribe_confirm_email(self):
hostname = os.environ.get('BASE_IRI', 'http://www.ospc.org')
print(self.email)
send_mail(subject="Thank you for joining the conversation on American tax policy",
message = """Welcome!
Thank you for registering with ospc.org. This is the best way to stay up to date on
the latest news from the Open Source Policy Center. We also invite you to beta test
the TaxBrain webapp.
Please visit {url} to confirm your subscription""".format(url = self.confirm_url(hostname)),
from_email = "Open Source Policy Center <mailing@ospc.org>",
recipient_list = [self.email])
|
nolanzandi/webapp-public
|
webapp/apps/register/models.py
|
Python
|
mit
| 1,396
|
[
"VisIt"
] |
6444d84f911ee444d82403bb90a4ab303f474cab16d8d4f93c868aa8a007f630
|
import logging
import math
from galaxy.model.item_attrs import RuntimeException, UsesAnnotations, UsesItemRatings
from galaxy.util import sanitize_text
from galaxy.util.json import loads, dumps
from galaxy.util.odict import odict
from galaxy.web.framework import decorators
from galaxy.web.framework import url_for
from galaxy.web.framework.helpers import iff
from sqlalchemy.sql.expression import and_, func, or_
log = logging.getLogger( __name__ )
class Grid( object ):
"""
Specifies the content and format of a grid (data table).
"""
title = ""
exposed = True
model_class = None
show_item_checkboxes = False
template = "grid_base.mako"
async_template = "grid_base_async.mako"
use_async = False
use_hide_message = True
global_actions = []
columns = []
operations = []
standard_filters = []
# Any columns that are filterable (either standard or advanced) should have a default value set in the default filter.
default_filter = {}
default_sort_key = None
preserve_state = False
use_paging = False
num_rows_per_page = 25
num_page_links = 10
# Set preference names.
cur_filter_pref_name = ".filter"
cur_sort_key_pref_name = ".sort_key"
pass_through_operations = {}
legend = None
info_text = None
def __init__( self ):
# Determine if any multiple row operations are defined
self.has_multiple_item_operations = False
for operation in self.operations:
if operation.allow_multiple:
self.has_multiple_item_operations = True
break
# If a column does not have a model class, set the column's model class
# to be the grid's model class.
for column in self.columns:
if not column.model_class:
column.model_class = self.model_class
def __call__( self, trans, **kwargs ):
# Get basics.
# FIXME: pretty sure this is only here to pass along, can likely be eliminated
status = kwargs.get( 'status', None )
message = kwargs.get( 'message', None )
# Build a base filter and sort key that is the combination of the saved state and defaults.
# Saved state takes preference over defaults.
base_filter = {}
if self.default_filter:
# default_filter is a dictionary that provides a default set of filters based on the grid's columns.
base_filter = self.default_filter.copy()
base_sort_key = self.default_sort_key
if self.preserve_state:
pref_name = unicode( self.__class__.__name__ + self.cur_filter_pref_name )
if pref_name in trans.get_user().preferences:
saved_filter = loads( trans.get_user().preferences[pref_name] )
base_filter.update( saved_filter )
pref_name = unicode( self.__class__.__name__ + self.cur_sort_key_pref_name )
if pref_name in trans.get_user().preferences:
base_sort_key = loads( trans.get_user().preferences[pref_name] )
# Build initial query
query = self.build_initial_query( trans, **kwargs )
query = self.apply_query_filter( trans, query, **kwargs )
# Maintain sort state in generated urls
extra_url_args = {}
# Determine whether use_default_filter flag is set.
use_default_filter_str = kwargs.get( 'use_default_filter' )
use_default_filter = False
if use_default_filter_str:
use_default_filter = ( use_default_filter_str.lower() == 'true' )
# Process filtering arguments to (a) build a query that represents the filter and (b) build a
# dictionary that denotes the current filter.
cur_filter_dict = {}
for column in self.columns:
if column.key:
# Get the filter criterion for the column. Precedence is (a) if using default filter, only look there; otherwise,
# (b) look in kwargs; and (c) look in base filter.
column_filter = None
if use_default_filter:
if self.default_filter:
column_filter = self.default_filter.get( column.key )
elif "f-" + column.model_class.__name__ + ".%s" % column.key in kwargs:
# Queries that include table joins cannot guarantee unique column names. This problem is
# handled by setting the column_filter value to <TableName>.<ColumnName>.
column_filter = kwargs.get( "f-" + column.model_class.__name__ + ".%s" % column.key )
elif "f-" + column.key in kwargs:
column_filter = kwargs.get( "f-" + column.key )
elif column.key in base_filter:
column_filter = base_filter.get( column.key )
# Method (1) combines a mix of strings and lists of strings into a single string and (2) attempts to de-jsonify all strings.
def loads_recurse(item):
decoded_list = []
if isinstance( item, basestring):
try:
# Not clear what we're decoding, so recurse to ensure that we catch everything.
decoded_item = loads( item )
if isinstance( decoded_item, list):
decoded_list = loads_recurse( decoded_item )
else:
decoded_list = [ unicode( decoded_item ) ]
except ValueError:
decoded_list = [ unicode ( item ) ]
elif isinstance( item, list):
for element in item:
a_list = loads_recurse( element )
decoded_list = decoded_list + a_list
return decoded_list
# If column filter found, apply it.
if column_filter is not None:
# TextColumns may have a mix of json and strings.
if isinstance( column, TextColumn ):
column_filter = loads_recurse( column_filter )
if len( column_filter ) == 1:
column_filter = column_filter[0]
# Interpret ',' as a separator for multiple terms.
if isinstance( column_filter, basestring ) and column_filter.find(',') != -1:
column_filter = column_filter.split(',')
# Check if filter is empty
if isinstance( column_filter, list ):
# Remove empty strings from filter list
column_filter = [x for x in column_filter if x != '']
if len(column_filter) == 0:
continue;
elif isinstance(column_filter, basestring):
# If filter criterion is empty, do nothing.
if column_filter == '':
continue
# Update query.
query = column.filter( trans, trans.user, query, column_filter )
# Upate current filter dict.
# Column filters are rendered in various places, sanitize them all here.
cur_filter_dict[ column.key ] = sanitize_text(column_filter)
# Carry filter along to newly generated urls; make sure filter is a string so
# that we can encode to UTF-8 and thus handle user input to filters.
if isinstance( column_filter, list ):
# Filter is a list; process each item.
for filter in column_filter:
if not isinstance( filter, basestring ):
filter = unicode( filter ).encode("utf-8")
extra_url_args[ "f-" + column.key ] = dumps( column_filter )
else:
# Process singleton filter.
if not isinstance( column_filter, basestring ):
column_filter = unicode(column_filter)
extra_url_args[ "f-" + column.key ] = column_filter.encode("utf-8")
# Process sort arguments.
sort_key = None
if 'sort' in kwargs:
sort_key = kwargs['sort']
elif base_sort_key:
sort_key = base_sort_key
if sort_key:
ascending = not( sort_key.startswith( "-" ) )
# Queries that include table joins cannot guarantee unique column names. This problem is
# handled by setting the column_filter value to <TableName>.<ColumnName>.
table_name = None
if sort_key.find( '.' ) > -1:
a_list = sort_key.split( '.' )
if ascending:
table_name = a_list[0]
else:
table_name = a_list[0][1:]
column_name = a_list[1]
elif ascending:
column_name = sort_key
else:
column_name = sort_key[1:]
# Sort key is a column key.
for column in self.columns:
if column.key and column.key.find( '.' ) > -1:
column_key = column.key.split( '.' )[1]
else:
column_key = column.key
if ( table_name is None or table_name == column.model_class.__name__ ) and column_key == column_name:
query = column.sort( trans, query, ascending, column_name=column_name )
break
extra_url_args['sort'] = sort_key
# There might be a current row
current_item = self.get_current_item( trans, **kwargs )
# Process page number.
if self.use_paging:
if 'page' in kwargs:
if kwargs['page'] == 'all':
page_num = 0
else:
page_num = int( kwargs['page'] )
else:
page_num = 1
if page_num == 0:
# Show all rows in page.
total_num_rows = query.count()
page_num = 1
num_pages = 1
else:
# Show a limited number of rows. Before modifying query, get the total number of rows that query
# returns so that the total number of pages can be computed.
total_num_rows = query.count()
query = query.limit( self.num_rows_per_page ).offset( ( page_num-1 ) * self.num_rows_per_page )
num_pages = int ( math.ceil( float( total_num_rows ) / self.num_rows_per_page ) )
else:
# Defaults.
page_num = 1
num_pages = 1
# There are some places in grid templates where it's useful for a grid
# to have its current filter.
self.cur_filter_dict = cur_filter_dict
# Preserve grid state: save current filter and sort key.
if self.preserve_state:
pref_name = unicode( self.__class__.__name__ + self.cur_filter_pref_name )
trans.get_user().preferences[pref_name] = unicode( dumps( cur_filter_dict ) )
if sort_key:
pref_name = unicode( self.__class__.__name__ + self.cur_sort_key_pref_name )
trans.get_user().preferences[pref_name] = unicode( dumps( sort_key ) )
trans.sa_session.flush()
# Log grid view.
context = unicode( self.__class__.__name__ )
params = cur_filter_dict.copy()
params['sort'] = sort_key
params['async'] = ( 'async' in kwargs )
#TODO:??
# commenting this out; when this fn calls session.add( action ) and session.flush the query from this fn
# is effectively 'wiped' out. Nate believes it has something to do with our use of session( autocommit=True )
# in mapping.py. If you change that to False, the log_action doesn't affect the query
# Below, I'm rendering the template first (that uses query), then calling log_action, then returning the page
#trans.log_action( trans.get_user(), unicode( "grid.view" ), context, params )
# Render grid.
def url( *args, **kwargs ):
# Only include sort/filter arguments if not linking to another
# page. This is a bit of a hack.
if 'action' in kwargs:
new_kwargs = dict()
else:
new_kwargs = dict( extra_url_args )
# Extend new_kwargs with first argument if found
if len(args) > 0:
new_kwargs.update( args[0] )
new_kwargs.update( kwargs )
# We need to encode item ids
if 'id' in new_kwargs:
id = new_kwargs[ 'id' ]
if isinstance( id, list ):
new_kwargs[ 'id' ] = [ trans.security.encode_id( i ) for i in id ]
else:
new_kwargs[ 'id' ] = trans.security.encode_id( id )
#The url_for invocation *must* include a controller and action.
if 'controller' not in new_kwargs:
new_kwargs['controller'] = trans.controller
if 'action' not in new_kwargs:
new_kwargs['action'] = trans.action
return url_for( **new_kwargs)
self.use_panels = ( kwargs.get( 'use_panels', False ) in [ True, 'True', 'true' ] )
self.advanced_search = ( kwargs.get( 'advanced_search', False ) in [ True, 'True', 'true' ] )
async_request = ( ( self.use_async ) and ( kwargs.get( 'async', False ) in [ True, 'True', 'true'] ) )
# Currently, filling the template returns a str object; this requires decoding the string into a
# unicode object within mako templates. What probably should be done is to return the template as
# utf-8 unicode; however, this would require encoding the object as utf-8 before returning the grid
# results via a controller method, which is require substantial changes. Hence, for now, return grid
# as str.
page = trans.fill_template( iff( async_request, self.async_template, self.template ),
grid=self,
query=query,
cur_page_num = page_num,
num_pages = num_pages,
num_page_links = self.num_page_links,
default_filter_dict=self.default_filter,
cur_filter_dict=cur_filter_dict,
sort_key=sort_key,
current_item=current_item,
ids = kwargs.get( 'id', [] ),
url = url,
status = status,
message = message,
info_text=self.info_text,
use_panels=self.use_panels,
use_hide_message=self.use_hide_message,
advanced_search=self.advanced_search,
show_item_checkboxes = ( self.show_item_checkboxes or
kwargs.get( 'show_item_checkboxes', '' ) in [ 'True', 'true' ] ),
# Pass back kwargs so that grid template can set and use args without
# grid explicitly having to pass them.
kwargs=kwargs )
trans.log_action( trans.get_user(), unicode( "grid.view" ), context, params )
return page
def get_ids( self, **kwargs ):
id = []
if 'id' in kwargs:
id = kwargs['id']
# Coerce ids to list
if not isinstance( id, list ):
id = id.split( "," )
# Ensure ids are integers
try:
id = map( int, id )
except:
decorators.error( "Invalid id" )
return id
# ---- Override these ----------------------------------------------------
def handle_operation( self, trans, operation, ids, **kwargs ):
pass
def get_current_item( self, trans, **kwargs ):
return None
def build_initial_query( self, trans, **kwargs ):
return trans.sa_session.query( self.model_class )
def apply_query_filter( self, trans, query, **kwargs ):
# Applies a database filter that holds for all items in the grid.
# (gvk) Is this method necessary? Why not simply build the entire query,
# including applying filters in the build_initial_query() method?
return query
class GridColumn( object ):
def __init__( self, label, key=None, model_class=None, method=None, format=None, \
link=None, attach_popup=False, visible=True, nowrap=False, \
# Valid values for filterable are ['standard', 'advanced', None]
filterable=None, sortable=True, label_id_prefix=None, inbound=False ):
"""Create a grid column."""
self.label = label
self.key = key
self.model_class = model_class
self.method = method
self.format = format
self.link = link
self.inbound = inbound
self.nowrap = nowrap
self.attach_popup = attach_popup
self.visible = visible
self.filterable = filterable
# Column must have a key to be sortable.
self.sortable = ( self.key is not None and sortable )
self.label_id_prefix = label_id_prefix or ''
def get_value( self, trans, grid, item ):
if self.method:
value = getattr( grid, self.method )( trans, item )
elif self.key:
value = getattr( item, self.key )
else:
value = None
if self.format:
value = self.format( value )
return value
def get_link( self, trans, grid, item ):
if self.link and self.link( item ):
return self.link( item )
return None
def filter( self, trans, user, query, column_filter ):
""" Modify query to reflect the column filter. """
if column_filter == "All":
pass
if column_filter == "True":
query = query.filter_by( **{ self.key: True } )
elif column_filter == "False":
query = query.filter_by( **{ self.key: False } )
return query
def get_accepted_filters( self ):
""" Returns a list of accepted filters for this column. """
accepted_filters_vals = [ "False", "True", "All" ]
accepted_filters = []
for val in accepted_filters_vals:
args = { self.key: val }
accepted_filters.append( GridColumnFilter( val, args) )
return accepted_filters
def sort( self, trans, query, ascending, column_name=None ):
"""Sort query using this column."""
if column_name is None:
column_name = self.key
if ascending:
query = query.order_by( self.model_class.table.c.get( column_name ).asc() )
else:
query = query.order_by( self.model_class.table.c.get( column_name ).desc() )
return query
class ReverseSortColumn( GridColumn ):
""" Column that reverses sorting; this is useful when the natural sort is descending. """
def sort( self, trans, query, ascending, column_name=None ):
return GridColumn.sort( self, trans, query, (not ascending), column_name=column_name )
class TextColumn( GridColumn ):
""" Generic column that employs freetext and, hence, supports freetext, case-independent filtering. """
def filter( self, trans, user, query, column_filter ):
""" Modify query to filter using free text, case independence. """
if column_filter == "All":
pass
elif column_filter:
query = query.filter( self.get_filter( trans, user, column_filter ) )
return query
def get_filter( self, trans, user, column_filter ):
""" Returns a SQLAlchemy criterion derived from column_filter. """
if isinstance( column_filter, basestring ):
return self.get_single_filter( user, column_filter )
elif isinstance( column_filter, list ):
clause_list = []
for filter in column_filter:
clause_list.append( self.get_single_filter( user, filter ) )
return and_( *clause_list )
def get_single_filter( self, user, a_filter ):
"""
Returns a SQLAlchemy criterion derived for a single filter. Single filter
is the most basic filter--usually a string--and cannot be a list.
"""
# Queries that include table joins cannot guarantee that table column names will be
# unique, so check to see if a_filter is of type <TableName>.<ColumnName>.
if self.key.find( '.' ) > -1:
a_key = self.key.split( '.' )[1]
else:
a_key = self.key
model_class_key_field = getattr( self.model_class, a_key )
return func.lower( model_class_key_field ).like( "%" + a_filter.lower() + "%" )
def sort( self, trans, query, ascending, column_name=None ):
"""Sort column using case-insensitive alphabetical sorting."""
if column_name is None:
column_name = self.key
if ascending:
query = query.order_by( func.lower( self.model_class.table.c.get( column_name ) ).asc() )
else:
query = query.order_by( func.lower( self.model_class.table.c.get( column_name ) ).desc() )
return query
class DateTimeColumn( TextColumn ):
def sort( self, trans, query, ascending, column_name=None ):
"""Sort query using this column."""
return GridColumn.sort( self, trans, query, ascending, column_name=column_name )
class BooleanColumn( TextColumn ):
def sort( self, trans, query, ascending, column_name=None ):
"""Sort query using this column."""
return GridColumn.sort( self, trans, query, ascending, column_name=column_name )
def get_single_filter( self, user, a_filter ):
if self.key.find( '.' ) > -1:
a_key = self.key.split( '.' )[1]
else:
a_key = self.key
model_class_key_field = getattr( self.model_class, a_key )
return model_class_key_field == a_filter
class IntegerColumn( TextColumn ):
"""
Integer column that employs freetext, but checks that the text is an integer,
so support filtering on integer values.
IMPORTANT NOTE: grids that use this column type should not include the column
in the cols_to_filter list of MulticolFilterColumn ( i.e., searching on this
column type should not be performed in the grid's standard search - it won't
throw exceptions, but it also will not find what you're looking for ). Grids
that search on this column should use 'filterable="advanced"' so that searching
is only performed in the advanced search component, restricting the search to
the specific column.
This is useful for searching on object ids or other integer columns. See the
JobIdColumn column in the SpecifiedDateListGrid class in the jobs controller of
the reports webapp for an example.
"""
def get_single_filter( self, user, a_filter ):
model_class_key_field = getattr( self.model_class, self.key )
assert int( a_filter ), "The search entry must be an integer"
return model_class_key_field == int( a_filter )
def sort( self, trans, query, ascending, column_name=None ):
"""Sort query using this column."""
return GridColumn.sort( self, trans, query, ascending, column_name=column_name )
class CommunityRatingColumn( GridColumn, UsesItemRatings ):
""" Column that displays community ratings for an item. """
def get_value( self, trans, grid, item ):
ave_item_rating, num_ratings = self.get_ave_item_rating_data( trans.sa_session, item, webapp_model=trans.model )
return trans.fill_template( "tool_shed_rating.mako",
ave_item_rating=ave_item_rating,
num_ratings=num_ratings,
item_id=trans.security.encode_id( item.id ) )
def sort( self, trans, query, ascending, column_name=None ):
def get_foreign_key( source_class, target_class ):
""" Returns foreign key in source class that references target class. """
target_fk = None
for fk in source_class.table.foreign_keys:
if fk.references( target_class.table ):
target_fk = fk
break
if not target_fk:
raise RuntimeException( "No foreign key found between objects: %s, %s" % source_class.table, target_class.table )
return target_fk
# Get the columns that connect item's table and item's rating association table.
item_rating_assoc_class = getattr( trans.model, '%sRatingAssociation' % self.model_class.__name__ )
foreign_key = get_foreign_key( item_rating_assoc_class, self.model_class )
fk_col = foreign_key.parent
referent_col = foreign_key.get_referent( self.model_class.table )
# Do sorting using a subquery.
# Subquery to get average rating for each item.
ave_rating_subquery = trans.sa_session.query( fk_col, \
func.avg( item_rating_assoc_class.table.c.rating ).label('avg_rating') ) \
.group_by( fk_col ) \
.subquery()
# Integrate subquery into main query.
query = query.outerjoin( (ave_rating_subquery, referent_col==ave_rating_subquery.columns[fk_col.name]) )
# Sort using subquery results; use coalesce to avoid null values.
if not ascending: # TODO: for now, reverse sorting b/c first sort is ascending, and that should be the natural sort.
query = query.order_by( func.coalesce( ave_rating_subquery.c.avg_rating, 0 ).asc() )
else:
query = query.order_by( func.coalesce( ave_rating_subquery.c.avg_rating, 0 ).desc() )
return query
class OwnerAnnotationColumn( TextColumn, UsesAnnotations ):
""" Column that displays and filters item owner's annotations. """
def __init__( self, col_name, key, model_class=None, model_annotation_association_class=None, filterable=None ):
GridColumn.__init__( self, col_name, key=key, model_class=model_class, filterable=filterable )
self.sortable = False
self.model_annotation_association_class = model_annotation_association_class
def get_value( self, trans, grid, item ):
""" Returns first 150 characters of annotation. """
annotation = self.get_item_annotation_str( trans.sa_session, item.user, item )
if annotation:
ann_snippet = annotation[:155]
if len( annotation ) > 155:
ann_snippet = ann_snippet[ :ann_snippet.rfind(' ') ]
ann_snippet += "..."
else:
ann_snippet = ""
return ann_snippet
def get_single_filter( self, user, a_filter ):
""" Filter by annotation and annotation owner. """
return self.model_class.annotations.any(
and_( func.lower( self.model_annotation_association_class.annotation ).like( "%" + a_filter.lower() + "%" ),
# TODO: not sure why, to filter by owner's annotations, we have to do this rather than
# 'self.model_class.user==self.model_annotation_association_class.user'
self.model_annotation_association_class.table.c.user_id==self.model_class.table.c.user_id ) )
class CommunityTagsColumn( TextColumn ):
""" Column that supports community tags. """
def __init__( self, col_name, key, model_class=None, model_tag_association_class=None, filterable=None, grid_name=None ):
GridColumn.__init__( self, col_name, key=key, model_class=model_class, nowrap=True, filterable=filterable, sortable=False )
self.model_tag_association_class = model_tag_association_class
# Column-specific attributes.
self.grid_name = grid_name
def get_value( self, trans, grid, item ):
return trans.fill_template( "/tagging_common.mako", tag_type="community", trans=trans, user=trans.get_user(), tagged_item=item, elt_context=self.grid_name,
in_form=True, input_size="20", tag_click_fn="add_tag_to_grid_filter", use_toggle_link=True )
def filter( self, trans, user, query, column_filter ):
""" Modify query to filter model_class by tag. Multiple filters are ANDed. """
if column_filter == "All":
pass
elif column_filter:
query = query.filter( self.get_filter( trans, user, column_filter ) )
return query
def get_filter( self, trans, user, column_filter ):
# Parse filter to extract multiple tags.
if isinstance( column_filter, list ):
# Collapse list of tags into a single string; this is redundant but effective. TODO: fix this by iterating over tags.
column_filter = ",".join( column_filter )
raw_tags = trans.app.tag_handler.parse_tags( column_filter.encode( "utf-8" ) )
clause_list = []
for name, value in raw_tags.items():
if name:
# Filter by all tags.
clause_list.append( self.model_class.tags.any( func.lower( self.model_tag_association_class.user_tname ).like( "%" + name.lower() + "%" ) ) )
if value:
# Filter by all values.
clause_list.append( self.model_class.tags.any( func.lower( self.model_tag_association_class.user_value ).like( "%" + value.lower() + "%" ) ) )
return and_( *clause_list )
class IndividualTagsColumn( CommunityTagsColumn ):
""" Column that supports individual tags. """
def get_value( self, trans, grid, item ):
return trans.fill_template( "/tagging_common.mako",
tag_type="individual",
user=trans.user,
tagged_item=item,
elt_context=self.grid_name,
in_form=True,
input_size="20",
tag_click_fn="add_tag_to_grid_filter",
use_toggle_link=True )
def get_filter( self, trans, user, column_filter ):
# Parse filter to extract multiple tags.
if isinstance( column_filter, list ):
# Collapse list of tags into a single string; this is redundant but effective. TODO: fix this by iterating over tags.
column_filter = ",".join( column_filter )
raw_tags = trans.app.tag_handler.parse_tags( column_filter.encode( "utf-8" ) )
clause_list = []
for name, value in raw_tags.items():
if name:
# Filter by individual's tag names.
clause_list.append( self.model_class.tags.any( and_( func.lower( self.model_tag_association_class.user_tname ).like( "%" + name.lower() + "%" ), self.model_tag_association_class.user == user ) ) )
if value:
# Filter by individual's tag values.
clause_list.append( self.model_class.tags.any( and_( func.lower( self.model_tag_association_class.user_value ).like( "%" + value.lower() + "%" ), self.model_tag_association_class.user == user ) ) )
return and_( *clause_list )
class MulticolFilterColumn( TextColumn ):
""" Column that performs multicolumn filtering. """
def __init__( self, col_name, cols_to_filter, key, visible, filterable="default" ):
GridColumn.__init__( self, col_name, key=key, visible=visible, filterable=filterable)
self.cols_to_filter = cols_to_filter
def filter( self, trans, user, query, column_filter ):
""" Modify query to filter model_class by tag. Multiple filters are ANDed. """
if column_filter == "All":
return query
if isinstance( column_filter, list):
clause_list = []
for filter in column_filter:
part_clause_list = []
for column in self.cols_to_filter:
part_clause_list.append( column.get_filter( trans, user, filter ) )
clause_list.append( or_( *part_clause_list ) )
complete_filter = and_( *clause_list )
else:
clause_list = []
for column in self.cols_to_filter:
clause_list.append( column.get_filter( trans, user, column_filter ) )
complete_filter = or_( *clause_list )
return query.filter( complete_filter )
class OwnerColumn( TextColumn ):
""" Column that lists item's owner. """
def get_value( self, trans, grid, item ):
return item.user.username
def sort( self, trans, query, ascending, column_name=None ):
""" Sort column using case-insensitive alphabetical sorting on item's username. """
if ascending:
query = query.order_by( func.lower ( self.model_class.username ).asc() )
else:
query = query.order_by( func.lower( self.model_class.username ).desc() )
return query
class PublicURLColumn( TextColumn ):
""" Column displays item's public URL based on username and slug. """
def get_link( self, trans, grid, item ):
if item.user.username and item.slug:
return dict( action='display_by_username_and_slug', username=item.user.username, slug=item.slug )
elif not item.user.username:
# TODO: provide link to set username.
return None
elif not item.user.slug:
# TODO: provide link to set slug.
return None
class DeletedColumn( GridColumn ):
""" Column that tracks and filters for items with deleted attribute. """
def get_accepted_filters( self ):
""" Returns a list of accepted filters for this column. """
accepted_filter_labels_and_vals = { "active" : "False", "deleted" : "True", "all": "All" }
accepted_filters = []
for label, val in accepted_filter_labels_and_vals.items():
args = { self.key: val }
accepted_filters.append( GridColumnFilter( label, args) )
return accepted_filters
def filter( self, trans, user, query, column_filter ):
"""Modify query to filter self.model_class by state."""
if column_filter == "All":
pass
elif column_filter in [ "True", "False" ]:
query = query.filter( self.model_class.deleted == ( column_filter == "True" ) )
return query
class StateColumn( GridColumn ):
"""
Column that tracks and filters for items with state attribute.
IMPORTANT NOTE: self.model_class must have a states Bunch or dict if
this column type is used in the grid.
"""
def get_value( self, trans, grid, item ):
return item.state
def filter( self, trans, user, query, column_filter ):
"""Modify query to filter self.model_class by state."""
if column_filter == "All":
pass
elif column_filter in [ v for k, v in self.model_class.states.items() ]:
query = query.filter( self.model_class.state == column_filter )
return query
def get_accepted_filters( self ):
"""Returns a list of accepted filters for this column."""
all = GridColumnFilter( 'all', { self.key : 'All' } )
accepted_filters = [ all ]
for k, v in self.model_class.states.items():
args = { self.key: v }
accepted_filters.append( GridColumnFilter( v, args) )
return accepted_filters
class SharingStatusColumn( GridColumn ):
""" Grid column to indicate sharing status. """
def get_value( self, trans, grid, item ):
# Delete items cannot be shared.
if item.deleted:
return ""
# Build a list of sharing for this item.
sharing_statuses = []
if item.users_shared_with:
sharing_statuses.append( "Shared" )
if item.importable:
sharing_statuses.append( "Accessible" )
if item.published:
sharing_statuses.append( "Published" )
return ", ".join( sharing_statuses )
def get_link( self, trans, grid, item ):
if not item.deleted and ( item.users_shared_with or item.importable or item.published ):
return dict( operation="share or publish", id=item.id )
return None
def filter( self, trans, user, query, column_filter ):
""" Modify query to filter histories by sharing status. """
if column_filter == "All":
pass
elif column_filter:
if column_filter == "private":
query = query.filter( self.model_class.users_shared_with == None )
query = query.filter( self.model_class.importable == False )
elif column_filter == "shared":
query = query.filter( self.model_class.users_shared_with != None )
elif column_filter == "accessible":
query = query.filter( self.model_class.importable == True )
elif column_filter == "published":
query = query.filter( self.model_class.published == True )
return query
def get_accepted_filters( self ):
""" Returns a list of accepted filters for this column. """
accepted_filter_labels_and_vals = odict()
accepted_filter_labels_and_vals["private"] = "private"
accepted_filter_labels_and_vals["shared"] = "shared"
accepted_filter_labels_and_vals["accessible"] = "accessible"
accepted_filter_labels_and_vals["published"] = "published"
accepted_filter_labels_and_vals["all"] = "All"
accepted_filters = []
for label, val in accepted_filter_labels_and_vals.items():
args = { self.key: val }
accepted_filters.append( GridColumnFilter( label, args) )
return accepted_filters
class GridOperation( object ):
def __init__( self, label, key=None, condition=None, allow_multiple=True, allow_popup=True,
target=None, url_args=None, async_compatible=False, confirm=None,
global_operation=None, inbound=False ):
self.label = label
self.key = key
self.allow_multiple = allow_multiple
self.allow_popup = allow_popup
self.condition = condition
self.target = target
self.url_args = url_args
self.async_compatible = async_compatible
self.inbound = inbound
# if 'confirm' is set, then ask before completing the operation
self.confirm = confirm
# specify a general operation that acts on the full grid
# this should be a function returning a dictionary with parameters
# to pass to the URL, similar to GridColumn links:
# global_operation=(lambda: dict(operation="download")
self.global_operation = global_operation
def get_url_args( self, item ):
if self.url_args:
if hasattr( self.url_args, '__call__' ):
url_args = self.url_args( item )
else:
url_args = dict( self.url_args )
url_args['id'] = item.id
return url_args
else:
return dict( operation=self.label, id=item.id )
def allowed( self, item ):
if self.condition:
return bool(self.condition( item ))
else:
return True
class DisplayByUsernameAndSlugGridOperation( GridOperation ):
""" Operation to display an item by username and slug. """
def get_url_args( self, item ):
return { 'action' : 'display_by_username_and_slug', 'username' : item.user.username, 'slug' : item.slug }
class GridAction( object ):
def __init__( self, label=None, url_args=None, inbound=False ):
self.label = label
self.url_args = url_args
self.inbound = inbound
class GridColumnFilter( object ):
def __init__( self, label, args=None ):
self.label = label
self.args = args
def get_url_args( self ):
rval = {}
for k, v in self.args.items():
rval[ "f-" + k ] = v
return rval
|
mikel-egana-aranguren/SADI-Galaxy-Docker
|
galaxy-dist/lib/galaxy/web/framework/helpers/grids.py
|
Python
|
gpl-3.0
| 41,060
|
[
"Galaxy"
] |
f02d57e45f80f086f6811a3df3efd762a3a57b163265447e6d9c5a0805a76253
|
"""
Author: Remy D <remyd@civx.us>
Ralph Bean <rbean@redhat.com>
Mike Nolan <me@michael-nolan.com>
License: AGPLv3+
"""
import ConfigParser
import feedparser
import json
import urllib2
import re
from flask import Flask
from flask.ext.mako import MakoTemplates, render_template
from flask import redirect, url_for, request
from evernote.api.client import EvernoteClient
from evernote.edam.notestore.ttypes import NoteFilter, NotesMetadataResultSpec
from evernote.edam.type.ttypes import NoteSortOrder
app = Flask(__name__)
app.template_folder = "templates"
mako = MakoTemplates(app)
config = ConfigParser.ConfigParser()
config.read('config.ini')
consumer_key = config.get('evernote', 'consumer_key', 0)
consumer_secret = config.get('evernote', 'consumer_secret', 0)
dev_token = config.get('evernote', 'dev_token', 0).strip("'")
@app.route('/')
def index():
client = EvernoteClient(token=dev_token)
userStore = client.get_user_store()
user = userStore.getUser()
username = user.username
return render_template('index.mak', name='mako', username=username)
@app.route('/getbooks')
def getbooks():
client = EvernoteClient(token=dev_token)
noteStore = client.get_note_store()
notebooks = noteStore.listNotebooks(dev_token)
for n in notebooks:
print n.name
return "cool"
@app.route('/getevernote')
def getevernote():
client = EvernoteClient(token=dev_token)
updated_filter = NoteFilter(order=NoteSortOrder.UPDATED)
offset = 0
max_notes = 10
result_spec = NotesMetadataResultSpec(includeTitle=True)
note_store = client.get_note_store()
result_list = note_store.findNotesMetadata(
dev_token,
updated_filter,
offset,
max_notes,
result_spec)
notes = {"timeline": {
"headline": "Evernote to Timeline.js",
"type": "default",
"text": "Automatic Tweets, Wikipedia, Youtube",
"startDate": "2014,8,26",
"date": [],
}}
for note in result_list.notes:
content = note_store.getNoteContent(dev_token, note.guid)
content_list = content.split(',', 3)
media = False
if (":wikipedia:" in content or ":twitter:" in content or
":youtube:" in content):
media = True
note_json = {
"startDate": content_list[1].replace('-', ','),
"endDate": content_list[2].replace('-', ','),
"headline": note.title,
"text": content_list[3]
}
if media:
m = re.search('.+:\w+:\s([\w:/\.]+).*', content)
asset = {
"media": m.group(1)
}
note_json['asset'] = asset
notes['timeline']['date'].append(note_json)
return json.dumps(notes)
@app.route('/postevernote')
def postevernote():
'''
An example script using the EvernoteClient to post new notes.
Source:
https://github.com/evernote/evernote-sdk-python/tree/master/sample/client
'''
#
# A simple Evernote API demo script that lists all notebooks in the user's
# account and creates a simple test note in the default notebook.
#
# Before running this sample, you must fill in your Evernote developer
# token.
#
# To run (Unix):
# export PYTHONPATH=../../lib; python EDAMTest.py
#
import hashlib
import binascii
import evernote.edam.userstore.constants as UserStoreConstants
import evernote.edam.type.ttypes as Types
from evernote.api.client import EvernoteClient
# Real applications authenticate with Evernote using OAuth, but for the
# purpose of exploring the API, you can get a developer token that allows
# you to access your own Evernote account. To get a developer token, visit
# https://sandbox.evernote.com/api/DeveloperToken.action
auth_token = dev_token
if auth_token == "your developer token":
print "Please fill in your developer token"
print "To get a developer token, visit " \
"https://sandbox.evernote.com/api/DeveloperToken.action"
exit(1)
# Initial development is performed on our sandbox server. To use the
# production service, change sandbox=False and replace your
# developer token above with a token from
# https://www.evernote.com/api/DeveloperToken.action
client = EvernoteClient(token=auth_token, sandbox=True)
user_store = client.get_user_store()
version_ok = user_store.checkVersion(
"Evernote EDAMTest (Python)",
UserStoreConstants.EDAM_VERSION_MAJOR,
UserStoreConstants.EDAM_VERSION_MINOR
)
print "Is my Evernote API version up to date? ", str(version_ok)
print ""
if not version_ok:
exit(1)
note_store = client.get_note_store()
# List all of the notebooks in the user's account
notebooks = note_store.listNotebooks()
print "Found ", len(notebooks), " notebooks:"
for notebook in notebooks:
print " * ", notebook.name
print
print "Creating a new note in the default notebook"
print
# To create a new note, simply create a new Note object and fill in
# attributes such as the note's title.
note = Types.Note()
note.title = "Test note from EDAMTest.py"
# To include an attachment such as an image in a note, first create a
# Resource for the attachment. At a minimum, the Resource contains the
# binary attachment data, an MD5 hash of the binary data, and the
# attachment MIME type. It can also include attributes such as filename
# and location.
image = open('static/img/enlogo.png', 'rb').read()
md5 = hashlib.md5()
md5.update(image)
hash = md5.digest()
data = Types.Data()
data.size = len(image)
data.bodyHash = hash
data.body = image
resource = Types.Resource()
resource.mime = 'image/png'
resource.data = data
# Now, add the new Resource to the note's list of resources
note.resources = [resource]
# To display the Resource as part of the note's content, include an
# <en-media> tag in the note's ENML content. The en-media tag identifies
# the corresponding Resource using the MD5 hash.
hash_hex = binascii.hexlify(hash)
# The content of an Evernote note is represented using Evernote Markup
# Language (ENML). The full ENML specification can be found in the Evernote
# API Overview at
# http://dev.evernote.com/documentation/cloud/chapters/ENML.php
note.content = '<?xml version="1.0" encoding="UTF-8"?>'
note.content += '<!DOCTYPE en-note SYSTEM ' \
'"http://xml.evernote.com/pub/enml2.dtd">'
note.content += '<en-note>Here is the Evernote logo:<br/>'
note.content += '<en-media type="image/png" hash="' + hash_hex + '"/>'
note.content += '</en-note>'
# Finally, send the new note to Evernote using the createNote method
# The new Note object that is returned will contain server-generated
# attributes such as the new note's unique GUID.
created_note = note_store.createNote(note)
status = "Successfully created a new note with GUID: " + created_note.guid
print status
return status
@app.route('/about')
def about():
return render_template('about.mak', name='mako')
@app.route('/feed')
def feed():
query = request.args.get('q').lower()
request_type = request.args.get('type').lower()
if request_type == 'news':
google_news_rss_url = "https://news.google.com/news/feeds?q=" + "{0}".format(query) + "&output=rss"
feed = feedparser.parse(google_news_rss_url).entries
return render_template('feed.mak', request_type=request_type,
name='mako', feed=feed)
elif request_type == 'bills':
bills_response = urllib2.urlopen(
"http://congress.api.sunlightfoundation.com/bills/search?query="
+ "{0}".format(query) + "&apikey=9b21768d77c648a39ba9b9e77cda089c")
feed = json.loads(bills_response.read().decode(
bills_response.info().getparam('charset') or 'utf-8'))['results']
return render_template('feed.mak', request_type=request_type,
name='mako', feed=feed)
@app.route('/timeline')
def timeline():
return render_template('timeline.mak', name='mako')
@app.route('/story')
def story():
return render_template('story.mak', name='mako')
# return redirect(url_for('static', filename='img/preso.svg'))
@app.route('/slides')
def slides():
return redirect(url_for('static', filename='img/preso.svg'))
|
FOSSRIT/everline
|
run.py
|
Python
|
agpl-3.0
| 8,576
|
[
"VisIt"
] |
3e5bc52b88b53b32b1ed3626169b6ab962143b19f10eb2189adb9ed13d1f81e1
|
## Alarm Server
## Supporting Envisalink 2DS/3
##
## This code is under the terms of the GPL v3 license.
import ctypes
c_uint16 = ctypes.c_uint16
class IconLED_Bitfield( ctypes.LittleEndianStructure ):
_fields_ = [
("alarm", c_uint16, 1 ),
("alarm_in_memory", c_uint16, 1 ),
("armed_away", c_uint16, 1 ),
("ac_present", c_uint16, 1 ),
("bypass", c_uint16, 1 ),
("chime", c_uint16, 1 ),
("not_used1", c_uint16, 1 ),
("armed_zero_entry_delay", c_uint16, 1 ),
("alarm_fire_zone", c_uint16, 1 ),
("system_trouble", c_uint16, 1 ),
("not_used2", c_uint16, 1 ),
("not_used3", c_uint16, 1 ),
("ready", c_uint16, 1 ),
("fire", c_uint16, 1 ),
("low_battery", c_uint16, 1 ),
("armed_stay", c_uint16, 1 )
]
class IconLED_Flags( ctypes.Union ):
_fields_ = [
("b", IconLED_Bitfield ),
("asShort", c_uint16 )
]
_anonymous_ = ("b")
evl_Commands = {
'KeepAlive' : '00',
'ChangeDefaultPartition' : '01',
'DumpZoneTimers' : '02',
'PartitionKeypress' : '03'
}
evl_PanicTypes = {
'Fire' : 'A',
'Ambulance' : 'B',
'Police' : 'C'
}
evl_ResponseTypes = {
'Login:' : {'name' : 'Login Prompt', 'description' : 'Sent During Session Login Only.', 'handler' : 'login'},
'OK' : {'name' : 'Login Success', 'description' : 'Send During Session Login Only, successful login', 'handler' : 'login_success'},
'FAILED' : {'name' : 'Login Failure', 'description' : 'Sent During Session Login Only, password not accepted', 'handler' : 'login_failure'},
'Timed Out!' : {'name' : 'Login Interaction Timed Out', 'description' : 'Sent during Session Login Only, socket connection is then closed', 'handler' : 'login_timeout'},
'%00' : {'name' : 'Virtual Keypad Update', 'description' : 'The panel wants to update the state of the keypad','handler' : 'keypad_update'},
'%01' : {'type' : 'zone', 'name' : 'Zone State Change', 'description' : 'A zone change-of-state has occurred', 'handler' : 'zone_state_change'},
'%02' : {'type' : 'partition', 'name' : 'Partition State Change', 'description' : 'A partition change-of-state has occured', 'handler' : 'partition_state_change'},
'%03' : {'type' : 'system', 'name' : 'Realtime CID Event', 'description' : 'A system event has happened that is signaled to either the Envisalerts servers or the central monitoring station', 'handler' : 'realtime_cid_event'},
'%FF' : {'name' : 'Envisalink Zone Timer Dump', 'description' : 'This command contains the raw zone timers used inside the Envisalink. The dump is a 256 character packed HEX string representing 64 UINT16 (little endian) zone timers. Zone timers count down from 0xFFFF (zone is open) to 0x0000 (zone is closed too long ago to remember). Each ''tick'' of the zone time is actually 5 seconds so a zone timer of 0xFFFE means ''5 seconds ago''. Remember, the zone timers are LITTLE ENDIAN so the above example would be transmitted as FEFF.', 'handler' : 'zone_timer_dump'},
'^00' : {'type' : 'envisalink', 'name': 'Poll', 'description' : 'Envisalink poll', 'handler' : 'poll_response'},
'^01' : {'type' : 'envisalink', 'name': 'Change Default Partition', 'description': 'Change the partition which keystrokes are sent to when using the virtual keypad.', 'handler' : 'command_response'},
'^02' : {'type' : 'envisalink', 'name': 'Dump Zone Timers', 'description' : 'This command contains the raw zone timers used inside the Envisalink. The dump is a 256 character packed HEX string representing 64 UINT16 (little endian) zone timers. Zone timers count down from 0xFFFF (zone is open) to 0x0000 (zone is closed too long ago to remember). Each ''tick'' of the zone time is actually 5 seconds so a zone timer of 0xFFFE means ''5 seconds ago''. Remember, the zone timers are LITTLE ENDIAN so the above example would be transmitted as FEFF.','handler' : 'command_response'},
'^03' : {'type' : 'envisalink', 'name': 'Keypress to Specific Partition', 'description' : 'This will send a keystroke to the panel from an arbitrary partition. Use this if you don''t want to change the TPI default partition.' ,'handler' : 'command_response'},
'^0C' : {'type' : 'envisalink', 'name': 'Response for Invalid Command', 'description' : 'This response is returned when an invalid command number is passed to Envisalink', 'handler': 'command_response'}
}
evl_TPI_Response_Codes = {
'00' : 'Command Accepted',
'01' : 'Receive Buffer Overrun (a command is received while another is still being processed)',
'02' : 'Unknown Command',
'03' : 'Syntax Error. Data appended to the command is incorrect in some fashion',
'04' : 'Receive Buffer Overflow',
'05' : 'Receive State Machine Timeout (command not completed within 3 seconds)'
}
evl_Partition_Status_Codes = {
'00' : {'name' : 'NOT_USED', 'description' : 'Partition is not used or doesn''t exist'},
'01' : {'name' : 'READY', 'description' : 'Ready', 'pluginhandler' : 'disarmed'},
'02' : {'name' : 'READY_BYPASS', 'description' : 'Ready to Arm (Zones are Bypasses)', 'pluginhandler' : 'disarmed'},
'03' : {'name' : 'NOT_READY', 'description' : 'Not Ready', 'pluginhandler' : 'disarmed'},
'04' : {'name' : 'ARMED_STAY', 'description' : 'Armed in Stay Mode', 'pluginhandler' : 'armedHome'},
'05' : {'name' : 'ARMED_AWAY', 'description' : 'Armed in Away Mode', 'pluginhandler' : 'armedAway'},
'06' : {'name' : 'ARMED_MAX', 'description' : 'Armed in Away Mode', 'pluginhandler' : 'armedInstant'},
'07' : {'name' : 'EXIT_ENTRY_DELAY', 'description' : 'Entry or Exit Delay'},
'08' : {'name' : 'IN_ALARM', 'description' : 'Partition is in Alarm', 'pluginhandler' : 'alarmTriggered'},
'09' : {'name' : 'ALARM_IN_MEMORY', 'description' : 'Alarm Has Occurred (Alarm in Memory)', 'pluginhandler' : 'alarmCleared'}
}
evl_Virtual_Keypad_How_To_Beep = {
'00' : 'off',
'01' : 'beep 1 time',
'02' : 'beep 2 times',
'03' : 'beep 3 times',
'04' : 'continous fast beep',
'05' : 'continuous slow beep'
}
evl_CID_Qualifiers = {
1 : 'New Event or Opening',
3 : 'New Restore or Closing',
6 : 'Previously Reported Condition Still Present'
}
evl_CID_Events = {
100 : {
"label" : "Medical Alert",
"type" : "zone",
},
101 : {
"label" : "Personal Emergency",
"type" : "zone",
},
102 : {
"label" : "Failure to Report In",
"type" : "zone",
},
110 : {
"label" : "Fire Alarm",
"type" : "zone",
},
111 : {
"label" : "Smoke Alarm",
"type" : "zone",
},
112 : {
"label" : "Combustion Detected Alarm",
"type" : "zone",
},
113 : {
"label" : "Water Flood Alarm",
"type" : "zone",
},
114 : {
"label" : "Excessive Heat Alarm",
"type" : "zone",
},
115 : {
"label" : "Fire Alarm Pulled",
"type" : "zone",
},
116 : {
"label" : "Duct Alarm",
"type" : "zone",
},
117 : {
"label" : "Flame Detected",
"type" : "zone",
},
118 : {
"label" : "Near Alarm",
"type" : "zone",
},
120 : {
"label" : "Panic Alarm",
"type" : "zone",
},
121 : {
"label" : "Duress Alarm",
"type" : "user",
},
122 : {
"label" : "Alarm, 24-hour Silent",
"type" : "zone",
},
123 : {
"label" : "Alarm, 24-hour Audible",
"type" : "zone",
},
124 : {
"label" : "Duress - Access granted",
"type" : "zone",
},
125 : {
"label" : "Duress - Egress granted",
"type" : "zone",
},
130 : {
"label" : "Burgalry in Progress",
"type" : "zone",
},
131 : {
"label" : "Alarm, Perimeter",
"type" : "zone",
},
132 : {
"label" : "Alarm, Interior",
"type" : "zone",
},
133 : {
"label" : "24 Hour (Safe)",
"type" : "zone",
},
134 : {
"label" : "Alarm, Entry/Exit",
"type" : "zone",
},
135 : {
"label" : "Alarm, Day/Night",
"type" : "zone",
},
136 : {
"label" : "Alarm, Outdoor",
"type" : "zone",
},
137 : {
"label" : "Alarm, Tamper",
"type" : "zone",
},
138 : {
"label" : "Near Alarm",
"type" : "zone",
},
139 : {
"label" : "Intrusion Verifier",
"type" : "zone",
},
140 : {
"label" : "Alarm, General Alarm",
"type" : "zone",
},
141 : {
"label" : "Alarm, Polling Loop Open",
"type" : "zone",
},
142 : {
"label" : "Alarm, Polling Loop Short",
"type" : "zone",
},
143 : {
"label" : "Alarm, Expansion Module",
"type" : "zone",
},
144 : {
"label" : "Alarm, Sensor Tamper",
"type" : "zone",
},
145 : {
"label" : "Alarm, Expansion Module Tamper",
"type" : "zone",
},
146 : {
"label" : "Silent Burglary",
"type" : "zone",
},
147 : {
"label" : "Sensor Supervision failure",
"type" : "zone",
},
150 : {
"label" : "Alarm, 24-Hour Auxiliary",
"type" : "zone",
},
151 : {
"label" : "Alarm, Gas detected",
"type" : "zone",
},
152 : {
"label" : "Alarm, Refrigeration",
"type" : "zone",
},
153 : {
"label" : "Alarm, Loss of heat",
"type" : "zone",
},
154 : {
"label" : "Alarm, Water leakage",
"type" : "zone",
},
155 : {
"label" : "Alarm, foil break",
"type" : "zone",
},
156 : {
"label" : "Day trouble",
"type" : "zone",
},
157 : {
"label" : "Low bottled gas level",
"type" : "zone",
},
158 : {
"label" : "Alarm, High temperature",
"type" : "zone",
},
159 : {
"label" : "Alarm, Low temperature",
"type" : "zone",
},
161 : {
"label" : "Alarm, Loss of air flow",
"type" : "zone",
},
162 : {
"label" : "Alarm, Carbon Monoxide Detected",
"type" : "zone",
},
163 : {
"label" : "Alarm, Tank Level",
"type" : "zone",
},
300 : {
"label" : "System Trouble",
"type" : "zone",
},
301 : {
"label" : "AC Power",
"type" : "zone",
},
302 : {
"label" : "Low System Battery/Battery Test Fail",
"type" : "zone",
},
303 : {
"label" : "RAM Checksum Bad",
"type" : "zone",
},
304 : {
"label" : "ROM Checksum Bad",
"type" : "zone",
},
305 : {
"label" : "System Reset",
"type" : "zone",
},
306 : {
"label" : "Panel programming changed",
"type" : "zone",
},
307 : {
"label" : "Self-test failure",
"type" : "zone",
},
308 : {
"label" : "System shutdown",
"type" : "zone",
},
309 : {
"label" : "Battery test failure",
"type" : "zone",
},
310 : {
"label" : "Ground fault",
"type" : "zone",
},
311 : {
"label" : "Battery Missing/Dead",
"type" : "zone",
},
312 : {
"label" : "Power Supply Overcurrent",
"type" : "zone",
},
313 : {
"label" : "Engineer Reset",
"type" : "user",
},
321 : {
"label" : "Bell/Siren Trouble",
"type" : "zone",
},
333 : {
"label" : "Trouble or Tamper Expansion Module",
"type" : "zone",
},
341 : {
"label" : "Trouble, ECP Cover Tamper",
"type" : "zone",
},
344 : {
"label" : "RF Receiver Jam",
"type" : "zone",
},
351 : {
"label" : "Telco Line Fault",
"type" : "zone",
},
353 : {
"label" : "Long Range Radio Trouble",
"type" : "zone",
},
373 : {
"label" : "Fire Loop Trouble",
"type" : "zone",
},
374 : {
"label" : "Exit Error Alarm",
"type" : "zone",
},
380 : {
"label" : "Global Trouble, Trouble Day/Night",
"type" : "zone",
},
381 : {
"label" : "RF Supervision Trouble",
"type" : "zone",
},
382 : {
"label" : "Supervision Auxillary Wire Zone",
"type" : "zone",
},
383 : {
"label" : "RF Sensor Tamper",
"type" : "zone",
},
384 : {
"label" : "RF Sensor Low Battery",
"type" : "zone",
},
393 : {
"label" : "Clean Me",
"type" : "zone",
},
401 : {
"label" : "AWAY/MAX",
"type" : "user",
},
403 : {
"label" : "Scheduled Arming",
"type" : "user",
},
406 : {
"label" : "Cancel by User",
"type" : "user",
},
407 : {
"label" : "Remote Arm/Disarm (Downloading)",
"type" : "user",
},
408 : {
"label" : "Quick AWAY/MAX",
"type" : "user",
},
409 : {
"label" : "AWAY/MAX Keyswitch",
"type" : "user",
},
411 : {
"label" : "Callback Requested",
"type" : "user",
},
412 : {
"label" : "Success-Download/Access",
"type" : "user",
},
413 : {
"label" : "Unsuccessful Access",
"type" : "user",
},
414 : {
"label" : "System Shutdown",
"type" : "user",
},
415 : {
"label" : "Dialer Shutdown",
"type" : "user",
},
416 : {
"label" : "Successful Upload",
"type" : "user",
},
421 : {
"label" : "Access Denied",
"type" : "user",
},
422 : {
"label" : "Access Granted",
"type" : "user",
},
423 : {
"label" : "PANIC Forced Access",
"type" : "zone",
},
424 : {
"label" : "Egress Denied",
"type" : "user",
},
425 : {
"label" : "Egress Granted",
"type" : "user",
},
426 : {
"label" : "Access Door Propped Open",
"type" : "zone",
},
427 : {
"label" : "Access Point DSM Trouble",
"type" : "zone",
},
428 : {
"label" : "Access Point RTE Trouble",
"type" : "zone",
},
429 : {
"label" : "Access Program Mode Entry",
"type" : "user",
},
430 : {
"label" : "Access Program Mode Exit",
"type" : "user",
},
431 : {
"label" : "Access Threat Level Change",
"type" : "user",
},
432 : {
"label" : "Access Relay/Triger Failure",
"type" : "zone",
},
433 : {
"label" : "Access RTE Shunt",
"type" : "zone",
},
434 : {
"label" : "Access DSM Shunt",
"type" : "zone",
},
441 : {
"label" : "STAY/INSTANT",
"type" : "user",
},
442 : {
"label" : "STAY/INSTANT Keyswitch",
"type" : "user",
},
570 : {
"label" : "Zone Bypass",
"type" : "zone",
},
574 : {
"label" : "Group Bypass",
"type" : "user"
},
601 : {
"label" : "Operator Initiated Dialer Test",
"type" : "user",
},
602 : {
"label" : "Periodic Test",
"type" : "zone",
},
606 : {
"label" : "AAV to follow",
"type" : "zone",
},
607 : {
"label" : "Walk Test",
"type" : "user",
},
623 : {
"label" : "Event Log 80% Full",
"type" : "zone",
},
625 : {
"label" : "Real-Time Clock Changed",
"type" : "user",
},
627 : {
"label" : "Program Mode Entry",
"type" : "zone",
},
628 : {
"label" : "Program Mode Exit",
"type" : "zone",
},
629 : {
"label" : "1-1/3 Day No Event",
"type" : "zone",
},
642 : {
"label" : "Latch Key",
"type" : "user",
},
}
|
jnimmo/pyenvisalink
|
pyenvisalink/honeywell_envisalinkdefs.py
|
Python
|
mit
| 15,602
|
[
"FEFF"
] |
e94d04ab767b5f1684ed56f53a5242a5423c30e7414e27bdc9a9cd294b985c1e
|
from __future__ import unicode_literals
import re
from .common import InfoExtractor
class NhkVodIE(InfoExtractor):
_VALID_URL = r'https?://www3\.nhk\.or\.jp/nhkworld/(?P<lang>[a-z]{2})/ondemand/(?P<type>video|audio)/(?P<id>\d{7}|[a-z]+-\d{8}-\d+)'
# Content available only for a limited period of time. Visit
# https://www3.nhk.or.jp/nhkworld/en/ondemand/ for working samples.
_TESTS = [{
# clip
'url': 'https://www3.nhk.or.jp/nhkworld/en/ondemand/video/9999011/',
'md5': '256a1be14f48d960a7e61e2532d95ec3',
'info_dict': {
'id': 'a95j5iza',
'ext': 'mp4',
'title': "Dining with the Chef - Chef Saito's Family recipe: MENCHI-KATSU",
'description': 'md5:5aee4a9f9d81c26281862382103b0ea5',
'timestamp': 1565965194,
'upload_date': '20190816',
},
}, {
'url': 'https://www3.nhk.or.jp/nhkworld/en/ondemand/video/2015173/',
'only_matching': True,
}, {
'url': 'https://www3.nhk.or.jp/nhkworld/en/ondemand/audio/plugin-20190404-1/',
'only_matching': True,
}, {
'url': 'https://www3.nhk.or.jp/nhkworld/fr/ondemand/audio/plugin-20190404-1/',
'only_matching': True,
}]
_API_URL_TEMPLATE = 'https://api.nhk.or.jp/nhkworld/%sod%slist/v7/episode/%s/%s/all%s.json'
def _real_extract(self, url):
lang, m_type, episode_id = re.match(self._VALID_URL, url).groups()
if episode_id.isdigit():
episode_id = episode_id[:4] + '-' + episode_id[4:]
is_video = m_type == 'video'
episode = self._download_json(
self._API_URL_TEMPLATE % (
'v' if is_video else 'r',
'clip' if episode_id[:4] == '9999' else 'esd',
episode_id, lang, '/all' if is_video else ''),
episode_id, query={'apikey': 'EJfK8jdS57GqlupFgAfAAwr573q01y6k'})['data']['episodes'][0]
title = episode.get('sub_title_clean') or episode['sub_title']
def get_clean_field(key):
return episode.get(key + '_clean') or episode.get(key)
series = get_clean_field('title')
thumbnails = []
for s, w, h in [('', 640, 360), ('_l', 1280, 720)]:
img_path = episode.get('image' + s)
if not img_path:
continue
thumbnails.append({
'id': '%dp' % h,
'height': h,
'width': w,
'url': 'https://www3.nhk.or.jp' + img_path,
})
info = {
'id': episode_id + '-' + lang,
'title': '%s - %s' % (series, title) if series and title else title,
'description': get_clean_field('description'),
'thumbnails': thumbnails,
'series': series,
'episode': title,
}
if is_video:
info.update({
'_type': 'url_transparent',
'ie_key': 'Piksel',
'url': 'https://player.piksel.com/v/refid/nhkworld/prefid/' + episode['vod_id'],
})
else:
audio = episode['audio']
audio_path = audio['audio']
info['formats'] = self._extract_m3u8_formats(
'https://nhks-vh.akamaihd.net/i%s/master.m3u8' % audio_path,
episode_id, 'm4a', m3u8_id='hls', fatal=False)
for proto in ('rtmpt', 'rtmp'):
info['formats'].append({
'ext': 'flv',
'format_id': proto,
'url': '%s://flv.nhk.or.jp/ondemand/mp4:flv%s' % (proto, audio_path),
'vcodec': 'none',
})
for f in info['formats']:
f['language'] = lang
return info
|
hakatashi/youtube-dl
|
youtube_dl/extractor/nhk.py
|
Python
|
unlicense
| 3,776
|
[
"VisIt"
] |
f03ae6723245e9a0960799d7138d1a041eccb954193214b6f70b9c8a253f2f5f
|
import ast
__author__ = 'Mathias Claus Jensen'
__maintainer__ = 'Mathias Claus Jensen'
__all__ = ['TransformVisitor']
ATOMIC_SOURCES = ['SQLSource', 'CSVSource', 'TypedCSVSource']
WRAPPERS = ['ConnectionWrapper']
class TransformVisitor(ast.NodeVisitor):
"""
Class responsible for making changes to an AST so that it can be run
with other connections
"""
def __init__(self, sources_ids, dw_id):
"""
:param: source_ids: names of the replacement sources
:param: dw_id: name of the replacement dw connection
"""
self.source_ids = sources_ids
self.dw_id = dw_id
self.counter = 0
self.dw_flag = False
def __get_id(self):
"""
Goes through a single iteration of the keys of the source_ids.
"""
if self.counter == len(self.source_ids):
raise StopIteration('There are no more mappings to use')
else:
id = self.source_ids[self.counter]
self.counter += 1
return id
def __replace_connection(self, id, node):
"""
Replace name of connection with user-defined id
:param id: Name to replace with
:param node: A call node
"""
newnode = ast.Name(id=id, ctx=ast.Load())
if len(node.args) != 0: # Conn given as positional arg
node.args[0] = newnode
else: # Conn given by keyword i.e. "connection = x"
for keyword in node.keywords:
if keyword.arg == 'connection'\
or keyword.arg == 'f'\
or keyword.arg == 'csvfile':
keyword.value = newnode
# Call to fill in line number and indentation information for the new
# node and its children.
ast.fix_missing_locations(node)
def __find_call_name(self, node):
"""
Function that finds the name of a call node
:param node: The call node, who's name we will find.
:return: The name of the call node
"""
name = None
if hasattr(node.func, 'id'): # SQLSource() type call
name = node.func.id
elif hasattr(node.func, 'attr'): # pygrametl.SQLSource() type call.
name = node.func.attr # Occurs when we don't import with
# "From".
else:
raise NotImplementedError('Cannot get the name of ' + str(node))
return name
def visit_Call(self, node):
"""
The visit of a call node.
Ignores all calls except for those we need to modify.
:param node: A call node
"""
name = self.__find_call_name(node)
if name in ATOMIC_SOURCES:
id = self.__get_id()
self.__replace_connection(id, node)
elif name in WRAPPERS:
if self.dw_flag:
raise Exception('There is more than one wrapper in this '
'program')
else:
id = self.dw_id
self.__replace_connection(id, node)
self.dw_flag = True
def start(self, node):
"""
We start the visitor.
:param node: the root of an AST.
"""
self.counter = 0
self.visit(node)
|
Betaboxguugi/P6
|
code/framework/reinterpreter/transform_visitor.py
|
Python
|
gpl-3.0
| 3,321
|
[
"VisIt"
] |
c1115b0bc77f8f72b0b2e28a9500303075b68cd1547a5f07987d7b86bbb5eefc
|
import pandas as pd
from sklearn.ensemble import RandomForestRegressor
from sklearn.ensemble import BaggingRegressor
from sklearn.ensemble import ExtraTreesRegressor
from sklearn.ensemble import AdaBoostRegressor
from sklearn.ensemble import GradientBoostingRegressor
from sklearn.ensemble import RandomTreesEmbedding
from sklearn.neural_network import MLPRegressor
from sklearn.linear_model import ElasticNet
from sklearn.gaussian_process import GaussianProcessRegressor
from sklearn.multioutput import MultiOutputRegressor
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import LabelEncoder
from sklearn.preprocessing import Imputer
from sklearn import metrics
import numpy as np
def get_multioutput_regressor(base_estimator):
multi = MultiOutputRegressor(base_estimator)
return multi
def get_gaussian_process_regressor():
gp = GaussianProcessRegressor()
return [gp],['Gaussian Process']
def get_mlp_regressor(num_hidden_units=51):
mlp = MLPRegressor(hidden_layer_sizes=num_hidden_units)
return [mlp],['Multi-Layer Perceptron']
def get_ensemble_models():
rf = RandomForestRegressor(n_estimators=51,min_samples_leaf=5,min_samples_split=3,random_state=42)
bag = BaggingRegressor(n_estimators=51,random_state=42)
extra = ExtraTreesRegressor(n_estimators=71,random_state=42)
ada = AdaBoostRegressor(random_state=42)
grad = GradientBoostingRegressor(n_estimators=101,random_state=42)
classifier_list = [rf,bag,extra,ada,grad]
classifier_name_list = ['Random Forests','Bagging','Extra Trees','AdaBoost','Gradient Boost']
return classifier_list, classifier_name_list
def get_linear_model():
elastic_net = ElasticNet()
return [elastic_net],['Elastic Net']
def print_evaluation_metrics(trained_model,trained_model_name,X_test,y_test):
print '--------- For Model : ', trained_model_name ,' ---------\n'
print "R2 Score : ", trained_model.score(X_test,y_test)
print "---------------------------------------\n"
def remove_nan_columns(dataframe):
for column in dataframe.columns:
if dataframe[column].isnull().sum() > 0.25*len(dataframe):
del dataframe[column]
return dataframe
filename = 'train.csv'
train_frame = pd.read_csv(filename)
train_frame = remove_nan_columns(train_frame)
output_values = train_frame[['Ret_PlusOne','Ret_PlusTwo']]
output_values = Imputer().fit_transform(output_values.values)
train_values = Imputer().fit_transform(train_frame.values)
X_train,X_test,y_train,y_test = train_test_split(train_values,output_values,test_size=0.2,random_state=42)
regressor_list, regressor_name_list = get_ensemble_models()
for regressor, regressor_name in zip(regressor_list,regressor_name_list):
multi_reg = get_multioutput_regressor(regressor)
multi_reg.fit(X_train,y_train)
print_evaluation_metrics(multi_reg,regressor_name,X_test,y_test)
|
rupakc/Kaggle-Compendium
|
Winton Stock Market Challenge/stock-baseline.py
|
Python
|
mit
| 2,904
|
[
"Gaussian"
] |
5b01cb2ed2f42657ba1bebc72c24b9e05574b0ec578fdeae197900eebb9616b1
|
"""
This module provides the generic functionality of tracing code by
modifying its AST. Eventually this will become a separate package.
This is similar to the standard library module bdb, while birdseye
itself would correspond to pdb.
Most of the work is in TreeTracerBase.
"""
import ast
import inspect
import sys
from collections import namedtuple, defaultdict
from copy import deepcopy
from functools import partial, update_wrapper, wraps
from itertools import takewhile
from types import FrameType, TracebackType, CodeType, FunctionType
from uuid import uuid4
from birdseye.utils import PY3, Type, is_lambda, lru_cache, read_source_file, is_ipython_cell, \
is_future_import, PYPY
# noinspection PyUnreachableCode
if False:
from typing import List, Dict, Any, Optional, Tuple, Iterator, Callable, Union
Loop = Union[ast.For, ast.While, ast.comprehension]
class TracedFile(object):
"""
An instance of this class corresponds to a single .py file.
It contains some useful data in the following attributes:
- filename: name of the source file
- source: textual contents of the file
- root: root of the original Abstract Syntax Tree (AST) of the source,
where the nodes of this tree have an additional handy attribute:
- parent: parent of the node, so this node is a child node of its parent
- tracer: instance of TreeTracerBase
- code: executable code object compiled from the modified AST
"""
is_ipython_cell = False
def __init__(self, tracer, source, filename, flags):
# type: (TreeTracerBase, str, str, int) -> None
# Here the source code is parsed, modified, and compiled
self.root = compile(source, filename, 'exec', ast.PyCF_ONLY_AST | flags, dont_inherit=True) # type: ast.Module
self.nodes = [] # type: List[ast.AST]
self.set_basic_node_attributes()
new_root = tracer.parse_extra(self.root, source, filename)
if new_root is not None:
self.root = new_root
self.set_basic_node_attributes()
self.set_enter_call_nodes()
self.trace_methods = {
f: "_treetrace_hidden_" + uuid4().hex
for f in [
TreeTracerBase._treetrace_hidden_with_stmt,
TreeTracerBase._treetrace_hidden_before_expr,
TreeTracerBase._treetrace_hidden_after_expr,
]
}
new_root = deepcopy(self.root)
new_root = _NodeVisitor(self).visit(new_root)
self.code = compile(new_root, filename, "exec", dont_inherit=True, flags=flags) # type: CodeType
self.tracer = tracer
self.source = source
self.filename = filename
def set_basic_node_attributes(self):
self.nodes = [] # type: List[ast.AST]
for node in ast.walk(self.root): # type: ast.AST
for child in ast.iter_child_nodes(node):
child.parent = node
node._tree_index = len(self.nodes)
self.nodes.append(node)
# Mark __future__ imports and anything before (i.e. module docstrings)
# to be ignored by the AST transformer
for i, stmt in enumerate(self.root.body):
if is_future_import(stmt):
for s in self.root.body[:i + 1]:
for node in ast.walk(s):
node._visit_ignore = True
def set_enter_call_nodes(self):
for node in self.nodes:
if isinstance(node, (ast.Module, ast.FunctionDef)):
for stmt in node.body:
if not is_future_import(stmt):
stmt._enter_call_node = True
break
class FrameInfo(object):
"""
Contains extra data about an execution frame.
Can be obtained from the stack attribute of a TreeTracerBase instance
"""
def __init__(self):
# Stack of statements currently being executed
self.statement_stack = [] # type: List[ast.stmt]
# Stack of expression nodes within the above statement that
# the interpreter is planning on evaluating, or has just evaluated
# in the case of the last element of the list. For example, given
# the expression f(g(x)), the stack would be [f, g, x] before and just
# after evaluating x, since function arguments are evaluated before the
# actual function call.
self.expression_stack = [] # type: List[ast.expr]
# Mapping from the expression node to its most recent value
# in the corresponding frame
self.expression_values = {} # type: Dict[ast.expr, Any]
# Node where the frame has explicitly returned
# There may be parent nodes such as enclosing loops that still need to finish executing
self.return_node = None # type: Optional[ast.Return]
# Most recent exception raised in the frame
self.exc_value = None # type: Optional[BaseException]
# Some of the attributes of the classes below are unused for now and are
# intended for future use, possibly by other debuggers
# Argument of TreeTracerBase.enter_call
EnterCallInfo = namedtuple('EnterCallInfo', 'call_node enter_node caller_frame current_frame')
# Argument of TreeTracerBase.exit_call
ExitCallInfo = namedtuple('ExitCallInfo', 'call_node return_node caller_frame current_frame '
'return_value exc_value exc_tb')
# see TreeTracerBase.after_expr
ChangeValue = namedtuple('ChangeValue', 'value')
class TreeTracerBase(object):
"""
Create a subclass of this class with one or more of the 'hooks'
(methods which are empty in this class) overridden to take a custom action
in the given situation. Then decorate functions with an instance of this class
to trace them.
"""
def __init__(self):
# Mapping from frames of execution being traced to FrameInfo objects
# for extra metadata.
self.stack = {} # type: Dict[FrameType, FrameInfo]
self.main_to_secondary_frames = defaultdict(list)
self.secondary_to_main_frames = {}
@lru_cache()
def compile(self, source, filename, flags=0):
# type: (str, str, int) -> TracedFile
return TracedFile(self, source, filename, flags)
def _trace_methods_dict(self, traced_file):
# type: (TracedFile) -> Dict[str, Callable]
return {
name: partial(f, self, traced_file)
for f, name in traced_file.trace_methods.items()
}
def trace_function(self, func):
# type: (FunctionType) -> FunctionType
"""
Returns a version of the passed function with the AST modified to
trigger the tracing hooks.
"""
if not isinstance(func, FunctionType):
raise ValueError('You can only trace user-defined functions. '
'The birdseye decorator must be applied first, '
'at the bottom of the list.')
try:
if inspect.iscoroutinefunction(func) or inspect.isasyncgenfunction(func):
raise ValueError('You cannot trace async functions')
except AttributeError:
pass
if is_lambda(func):
raise ValueError('You cannot trace lambdas')
filename = inspect.getsourcefile(func) # type: str
if is_ipython_cell(filename):
# noinspection PyPackageRequirements
from IPython import get_ipython
import linecache
flags = get_ipython().compile.flags
source = ''.join(linecache.cache[filename][2])
else:
source = read_source_file(filename)
flags = 0
# We compile the entire file instead of just the function source
# because it can contain context which affects the function code,
# e.g. enclosing functions and classes or __future__ imports
traced_file = self.compile(source, filename, flags)
if func.__dict__:
raise ValueError('The birdseye decorator must be applied first, '
'at the bottom of the list.')
# Then we have to recursively search through the newly compiled
# code to find the code we actually want corresponding to this function
code_options = [] # type: List[CodeType]
def find_code(root_code):
# type: (CodeType) -> None
for const in root_code.co_consts: # type: CodeType
if not inspect.iscode(const):
continue
matches = (const.co_firstlineno == func.__code__.co_firstlineno and
const.co_name == func.__code__.co_name)
if matches:
code_options.append(const)
find_code(const)
find_code(traced_file.code)
if len(code_options) > 1:
# Currently lambdas aren't allowed anyway, but should be in the future
assert is_lambda(func)
raise ValueError("Failed to trace lambda. Convert the function to a def.")
new_func_code = code_options[0] # type: CodeType
# Give the new function access to the hooks
# We have to use the original __globals__ and not a copy
# because it's the actual module namespace that may get updated by other code
func.__globals__.update(self._trace_methods_dict(traced_file))
# http://stackoverflow.com/a/13503277/2482744
# noinspection PyArgumentList
new_func = FunctionType(new_func_code, func.__globals__, func.__name__, func.__defaults__, func.__closure__)
update_wrapper(new_func, func) # type: FunctionType
if PY3:
new_func.__kwdefaults__ = getattr(func, '__kwdefaults__', None)
new_func.traced_file = traced_file
return new_func
def __call__(self, func=None, optional=False):
# type: (FunctionType, bool) -> Callable
"""
Decorator which returns a (possibly optionally) traced function.
This decorator can be called with or without arguments.
Typically it is called without arguments, in which case it returns
a traced function.
If optional=True, it returns a function similar to the original
but with an additional optional parameter trace_call, default False.
If trace_call is false, the underlying untraced function is used.
If true, the traced version is used.
"""
if inspect.isclass(func):
raise TypeError('Decorating classes is no longer supported')
if func:
# The decorator has been called without arguments/parentheses,
# e.g.
# @eye
# def ...
return self.trace_function(func)
# The decorator has been called with arguments/parentheses,
# e.g.
# @eye(...)
# def ...
# We must return a decorator
if not optional:
return self.trace_function
def decorator(actual_func):
traced = self.trace_function(actual_func)
@wraps(actual_func)
def wrapper(*args, **kwargs):
trace_call = kwargs.pop('trace_call', False)
if trace_call:
f = traced
else:
f = actual_func
return f(*args, **kwargs)
return wrapper
return decorator
def _main_frame(self, node):
# type: (ast.AST) -> Optional[FrameType]
frame = sys._getframe(2 + PYPY)
result = self.secondary_to_main_frames.get(frame)
if result:
return result
original_frame = frame
# Generator expressions are not attached to the original frame
# They may or may not run within that frame
# Don't cache a main frame for them or any frame within
in_genexpr = False
while frame.f_code.co_name in ('<listcomp>', '<dictcomp>', '<setcomp>', '<genexpr>'):
if frame.f_code.co_name == '<genexpr>':
in_genexpr = True
# If not currently called from the frame which defined it...
if frame.f_code not in frame.f_back.f_code.co_consts:
return None
frame = frame.f_back
for node in ancestors(node):
if isinstance(node, (ast.FunctionDef, ast.Lambda)):
break
if isinstance(node, ast.ClassDef):
frame = frame.f_back
if frame.f_code.co_name == '<lambda>':
return None
if not in_genexpr:
self.secondary_to_main_frames[original_frame] = frame
self.main_to_secondary_frames[frame].append(original_frame)
return frame
def _treetrace_hidden_with_stmt(self, traced_file, _tree_index):
# type: (TracedFile, int) -> _StmtContext
"""
Called directly from the modified code.
Every statement in the original code becomes:
with _treetrace_hidden_with_stmt(...):
<statement>
"""
node = traced_file.nodes[_tree_index]
assert isinstance(node, ast.stmt)
frame = self._main_frame(node)
return _StmtContext(self, node, frame)
def _treetrace_hidden_before_expr(self, traced_file, _tree_index):
# type: (TracedFile, int) -> ast.expr
"""
Called directly from the modified code before an expression is
evaluated.
"""
node = traced_file.nodes[_tree_index]
assert isinstance(node, ast.expr)
frame = self._main_frame(node)
if frame is None:
return node
frame_info = self.stack[frame]
frame_info.expression_stack.append(node)
self.before_expr(node, frame)
return node
def _treetrace_hidden_after_expr(self, _, node, value):
# type: (TracedFile, ast.expr, Any) -> Any
"""
Called directly from the modified code after an expression is
evaluated.
"""
frame = self._main_frame(node)
if frame is None:
return value
result = self._after_expr(node, frame, value, None, None)
if result is not None:
assert isinstance(result, ChangeValue), "after_expr must return None or an instance of ChangeValue"
value = result.value
return value
def _after_expr(self, node, frame, value, exc_value, exc_tb):
frame_info = self.stack[frame]
frame_info.expression_stack.pop()
frame_info.expression_values[node] = value
return self.after_expr(node, frame, value, exc_value, exc_tb)
def _enter_call(self, enter_node, current_frame):
# type: (ast.AST, FrameType) -> None
caller_frame, call_node = self._get_caller_stuff(current_frame)
self.stack[current_frame] = FrameInfo()
self.enter_call(EnterCallInfo(call_node, enter_node, caller_frame, current_frame))
def _get_caller_stuff(self, frame):
# type: (FrameType) -> Tuple[FrameType, Optional[Union[ast.expr, ast.stmt]]]
caller_frame = frame.f_back
call_node = None
main_frame = self.secondary_to_main_frames.get(caller_frame)
if main_frame:
caller_frame = main_frame
frame_info = self.stack[caller_frame]
expression_stack = frame_info.expression_stack
if expression_stack:
call_node = expression_stack[-1]
else:
call_node = frame_info.statement_stack[-1] # type: ignore
return caller_frame, call_node
# The methods below are hooks meant to be overridden in subclasses to take custom actions
def before_expr(self, node, frame):
# type: (ast.expr, FrameType) -> None
"""
Called right before the expression corresponding to `node` is evaluated
within `frame`.
"""
def after_expr(self, node, frame, value, exc_value, exc_tb):
# type: (ast.expr, FrameType, Any, Optional[BaseException], Optional[TracebackType]) -> Optional[ChangeValue]
"""
Called right after the expression corresponding to `node` is evaluated
within `frame`. `value` is the value of the expression, if it succeeded.
If the evaluation raised an exception, exc_value will be the exception object
and exc_tb the traceback.
Return `ChangeValue(x)` to change the value of the expression as
seen by the rest of the program from `value` to `x`.
"""
def before_stmt(self, node, frame):
# type: (ast.stmt, FrameType) -> None
"""
Called right before the statement corresponding to `node` is executed
within `frame`.
"""
def after_stmt(self, node, frame, exc_value, exc_traceback, exc_node):
# type: (ast.stmt, FrameType, Optional[BaseException], Optional[TracebackType], Optional[ast.AST]) -> Optional[bool]
"""
Called right after the statement corresponding to `node` is executed
within `frame`.
If the statement raised an exception, exc_value will be the exception object,
exc_tb the traceback, and exc_node the node where the exception was raised
(either this statement or an expression within).
Returning True will suppress any exception raised (as with __exit__ in general).
"""
def enter_call(self, enter_info):
# type: (EnterCallInfo) -> None
"""
Called before a function call begins executing. For typical `def` functions,
this is called before the `before_stmt` for to the first statement in the function.
"""
def exit_call(self, exit_info):
# type: (ExitCallInfo) -> None
"""
Called after a function call finishes executing. For typical `def` functions,
this is called after the `after_stmt` for to the last statement to execute.
"""
def parse_extra(self, root, source, filename):
# type: (ast.Module, str, str) -> Optional[ast.Module]
"""
Called before the AST (root) is modified to let subclasses make additional changes first.
"""
class _NodeVisitor(ast.NodeTransformer):
"""
This does the AST modifications that call the hooks.
"""
def __init__(self, traced_file):
self.traced_file = traced_file
def generic_visit(self, node):
# type: (ast.AST) -> ast.AST
if not getattr(node, '_visit_ignore', False):
if (isinstance(node, ast.expr) and
not (hasattr(node, "ctx") and not isinstance(node.ctx, ast.Load)) and
not isinstance(node, (getattr(ast, 'Starred', ()), ast.Slice))):
return self.visit_expr(node)
if isinstance(node, ast.stmt):
return self.visit_stmt(node)
return super(_NodeVisitor, self).generic_visit(node)
def visit_expr(self, node):
# type: (ast.expr) -> ast.Call
"""
each expression e gets wrapped like this:
_treetrace_hidden_after_expr(_treetrace_hidden_before_expr(_tree_index), e)
where the _treetrace_* functions are the corresponding methods with the
TreeTracerBase and traced_file arguments already filled in (see _trace_methods_dict)
"""
before_marker = self._create_simple_marker_call(node, TreeTracerBase._treetrace_hidden_before_expr)
ast.copy_location(before_marker, node)
after_marker = ast.Call(
func=ast.Name(
id=self.traced_file.trace_methods[
TreeTracerBase._treetrace_hidden_after_expr
],
ctx=ast.Load(),
),
args=[
before_marker,
super(_NodeVisitor, self).generic_visit(node),
],
keywords=[],
)
ast.copy_location(after_marker, node)
ast.fix_missing_locations(after_marker)
return after_marker
def visit_stmt(self, node):
# type: (ast.stmt) -> ast.With
"""
Every statement in the original code becomes:
with _treetrace_hidden_with_stmt(_tree_index):
<statement>
where the _treetrace_hidden_with_stmt function is the the corresponding method with the
TreeTracerBase and traced_file arguments already filled in (see _trace_methods_dict)
"""
context_expr = self._create_simple_marker_call(
super(_NodeVisitor, self).generic_visit(node),
TreeTracerBase._treetrace_hidden_with_stmt)
if PY3:
wrapped = ast.With(
items=[ast.withitem(context_expr=context_expr)],
body=[node],
)
else:
wrapped = ast.With(
context_expr=context_expr,
body=[node],
)
ast.copy_location(wrapped, node)
ast.fix_missing_locations(wrapped)
return wrapped
def _create_simple_marker_call(self, node, func):
# type: (ast.AST, Callable) -> ast.Call
"""
Returns a Call node representing `func(node._tree_index)`
where node._tree_index is a numerical literal which allows the node object
to be retrieved later through the nodes attribute of a TracedFile.
"""
return ast.Call(
func=ast.Name(id=self.traced_file.trace_methods[func], ctx=ast.Load()),
args=[ast.Num(node._tree_index)],
keywords=[],
)
class _StmtContext(object):
__slots__ = ('tracer', 'node', 'frame')
def __init__(self, tracer, node, frame):
# type: (TreeTracerBase, ast.stmt, FrameType) -> None
self.tracer = tracer
self.node = node
self.frame = frame
def __enter__(self):
tracer = self.tracer
node = self.node
frame = self.frame
if getattr(node, '_enter_call_node', False):
tracer._enter_call(node, frame)
frame_info = tracer.stack[frame]
frame_info.expression_stack = []
frame_info.statement_stack.append(node)
tracer.before_stmt(node, frame)
def __exit__(self, exc_type, exc_val, exc_tb):
# type: (Type[Exception], Exception, TracebackType) -> bool
node = self.node
tracer = self.tracer
frame = self.frame
frame_info = tracer.stack[frame]
frame_info.statement_stack.pop()
exc_node = None # type: Optional[Union[ast.expr, ast.stmt]]
if exc_val and exc_val is not frame_info.exc_value:
exc_node = node
frame_info.exc_value = exc_val
# Call the after_expr hook if the exception was raised by an expression
expression_stack = frame_info.expression_stack
if expression_stack:
exc_node = expression_stack[-1]
tracer._after_expr(exc_node, frame, None, exc_val, exc_tb)
result = tracer.after_stmt(node, frame, exc_val, exc_tb, exc_node)
if isinstance(node, ast.Return):
frame_info.return_node = node
parent = node.parent # type: ast.AST
return_node = frame_info.return_node
exiting = (isinstance(parent, (ast.FunctionDef, ast.Module)) and
(node is parent.body[-1] or
exc_val or
return_node))
if exiting:
caller_frame, call_node = tracer._get_caller_stuff(frame)
return_value = None
if return_node and return_node.value and not exc_val:
return_value = frame_info.expression_values[return_node.value]
tracer.exit_call(ExitCallInfo(call_node,
return_node,
caller_frame,
frame,
return_value,
exc_val,
exc_tb
))
del tracer.stack[frame]
for secondary_frame in self.tracer.main_to_secondary_frames.pop(frame):
del self.tracer.secondary_to_main_frames[secondary_frame]
return result
def ancestors(node):
# type: (ast.AST) -> Iterator[ast.AST]
while True:
try:
node = node.parent
except AttributeError:
break
yield node
def loops(node):
# type: (ast.AST) -> Tuple[Loop, ...]
"""
Return all the 'enclosing loops' of a node, up to the innermost class or
function definition. This also includes the 'for in' clauses in list/dict/set/generator
comprehensions. So for example, in this code:
for x in ...:
def foo():
while True:
print([z for y in ...])
The loops enclosing the node 'z' are 'while True' and 'for y in ...', in that order.
"""
result = []
while True:
try:
parent = node.parent
except AttributeError:
break
if isinstance(parent, ast.FunctionDef):
break
is_containing_loop = (((isinstance(parent, ast.For) and parent.iter is not node or
isinstance(parent, ast.While))
and node not in parent.orelse) or
(isinstance(parent, ast.comprehension) and node in parent.ifs))
if is_containing_loop:
result.append(parent)
elif isinstance(parent, (ast.ListComp,
ast.GeneratorExp,
ast.DictComp,
ast.SetComp)):
generators = parent.generators
if node in generators:
generators = list(takewhile(lambda n: n != node, generators))
result.extend(reversed(generators))
node = parent
result.reverse()
return tuple(result)
|
alexmojaki/birdseye
|
birdseye/tracer.py
|
Python
|
mit
| 26,076
|
[
"VisIt"
] |
db555262a013f922a8d60c5618f424dc20999149b142a499d065705af0c749b3
|
"""
:mod: DataManager
.. module: DataManager
:synopsis: DataManager links the functionalities of StorageElement and FileCatalog.
This module consists of DataManager and related classes.
"""
# # imports
from datetime import datetime, timedelta
import fnmatch
import os
import time
import errno
# # from DIRAC
import DIRAC
from DIRAC import S_OK, S_ERROR, gLogger, gConfig
from DIRAC.Core.Utilities import DErrno
from DIRAC.Core.Utilities.Adler import fileAdler, compareAdler
from DIRAC.Core.Utilities.File import makeGuid, getSize
from DIRAC.Core.Utilities.List import randomize, breakListIntoChunks
from DIRAC.Core.Utilities.ReturnValues import returnSingleResult
from DIRAC.Core.Security.ProxyInfo import getProxyInfo
from DIRAC.ConfigurationSystem.Client.Helpers.Operations import Operations
from DIRAC.AccountingSystem.Client.DataStoreClient import gDataStoreClient
from DIRAC.AccountingSystem.Client.Types.DataOperation import DataOperation
from DIRAC.DataManagementSystem.Utilities.DMSHelpers import DMSHelpers
from DIRAC.Resources.Catalog.FileCatalog import FileCatalog
from DIRAC.Resources.Storage.StorageElement import StorageElement
from DIRAC.ResourceStatusSystem.Client.ResourceStatus import ResourceStatus
# # RSCID
__RCSID__ = "$Id$"
def _isOlderThan(stringTime, days):
""" Check if a time stamp is older than a given number of days """
timeDelta = timedelta(days=days)
maxCTime = datetime.utcnow() - timeDelta
# st = time.strptime( stringTime, "%a %b %d %H:%M:%S %Y" )
# cTimeStruct = datetime( st[0], st[1], st[2], st[3], st[4], st[5], st[6], None )
cTimeStruct = stringTime
if cTimeStruct < maxCTime:
return True
return False
def _initialiseAccountingObject(operation, se, files):
""" create accouting record """
accountingDict = {}
accountingDict['OperationType'] = operation
result = getProxyInfo()
if not result['OK']:
userName = 'system'
else:
userName = result['Value'].get('username', 'unknown')
accountingDict['User'] = userName
accountingDict['Protocol'] = 'DataManager'
accountingDict['RegistrationTime'] = 0.0
accountingDict['RegistrationOK'] = 0
accountingDict['RegistrationTotal'] = 0
accountingDict['Destination'] = se
accountingDict['TransferTotal'] = files
accountingDict['TransferOK'] = files
accountingDict['TransferSize'] = files
accountingDict['TransferTime'] = 0.0
accountingDict['FinalStatus'] = 'Successful'
accountingDict['Source'] = DIRAC.siteName()
oDataOperation = DataOperation()
oDataOperation.setValuesFromDict(accountingDict)
return oDataOperation
class DataManager(object):
"""
.. class:: DataManager
A DataManager is taking all the actions that impact or require the FileCatalog and the StorageElement together
"""
def __init__(self, catalogs=None, masterCatalogOnly=False, vo=False):
""" c'tor
:param self: self reference
:param catalogs: the list of catalog in which to perform the operations. This
list will be ignored if masterCatalogOnly is set to True
:param masterCatalogOnly: if set to True, the operations will be performed only on the master catalog.
The catalogs parameter will be ignored.
:param vo: the VO for which the DataManager is created, get VO from the current proxy if not specified
"""
self.log = gLogger.getSubLogger(self.__class__.__name__, True)
self.voName = vo
if catalogs is None:
catalogs = []
catalogsToUse = FileCatalog(vo=self.voName).getMasterCatalogNames()[
'Value'] if masterCatalogOnly else catalogs
self.fileCatalog = FileCatalog(catalogs=catalogsToUse, vo=self.voName)
self.accountingClient = None
self.resourceStatus = ResourceStatus()
self.ignoreMissingInFC = Operations(vo=self.voName).getValue(
'DataManagement/IgnoreMissingInFC', False)
self.useCatalogPFN = Operations(vo=self.voName).getValue(
'DataManagement/UseCatalogPFN', True)
self.dmsHelper = DMSHelpers(vo=vo)
self.registrationProtocol = self.dmsHelper.getRegistrationProtocols()
self.thirdPartyProtocols = self.dmsHelper.getThirdPartyProtocols()
def setAccountingClient(self, client):
""" Set Accounting Client instance
"""
self.accountingClient = client
def __hasAccess(self, opType, path):
""" Check if we have permission to execute given operation on the given file (if exists) or its directory
"""
if isinstance(path, basestring):
paths = [path]
else:
paths = list(path)
res = self.fileCatalog.hasAccess(paths, opType)
if not res['OK']:
return res
result = {'Successful': list(), 'Failed': list()}
for path in paths:
isAllowed = res['Value']['Successful'].get(path, False)
if isAllowed:
result['Successful'].append(path)
else:
result['Failed'].append(path)
return S_OK(result)
##########################################################################
#
# These are the bulk removal methods
#
def cleanLogicalDirectory(self, lfnDir):
""" Clean the logical directory from the catalog and storage
"""
log = self.log.getSubLogger('cleanLogicalDirectory')
if isinstance(lfnDir, basestring):
lfnDir = [lfnDir]
retDict = {"Successful": {}, "Failed": {}}
for folder in lfnDir:
res = self.__cleanDirectory(folder)
if not res['OK']:
log.debug("Failed to clean directory.", "%s %s" %
(folder, res['Message']))
retDict["Failed"][folder] = res['Message']
else:
log.debug("Successfully removed directory.", folder)
retDict["Successful"][folder] = res['Value']
return S_OK(retDict)
def __cleanDirectory(self, folder):
""" delete all files from directory :folder: in FileCatalog and StorageElement
:param self: self reference
:param str folder: directory name
"""
log = self.log.getSubLogger('__cleanDirectory')
res = self.__hasAccess('removeDirectory', folder)
if not res['OK']:
return res
if folder not in res['Value']['Successful']:
errStr = "Write access not permitted for this credential."
log.debug(errStr, folder)
return S_ERROR(errStr)
res = self.__getCatalogDirectoryContents([folder], includeDirectories=True)
if not res['OK']:
return res
# create a list of folders so that empty folders are also deleted
listOfFolders = []
areDirs = self.fileCatalog.isDirectory(res['Value'])
if not areDirs['OK']:
return areDirs
listOfFolders = [aDir for aDir in areDirs['Value']['Successful'] if areDirs['Value']['Successful'][aDir]]
for lfn in listOfFolders:
res['Value'].pop(lfn)
res = self.removeFile(res['Value'])
if not res['OK']:
return res
for lfn, reason in res['Value']['Failed'].iteritems():
log.error("Failed to remove file found in the catalog",
"%s %s" % (lfn, reason))
res = returnSingleResult(self.removeFile(['%s/dirac_directory' % folder]))
if not res['OK']:
if not DErrno.cmpError(res, errno.ENOENT):
log.warn('Failed to delete dirac_directory placeholder file')
storageElements = gConfig.getValue(
'Resources/StorageElementGroups/SE_Cleaning_List', [])
failed = False
for storageElement in sorted(storageElements):
res = self.__removeStorageDirectory(folder, storageElement)
if not res['OK']:
failed = True
if failed:
return S_ERROR("Failed to clean storage directory at all SEs")
for aFolder in sorted(listOfFolders, reverse=True):
res = returnSingleResult(self.fileCatalog.removeDirectory(aFolder, recursive=True))
log.verbose('Removed folder', '%s: %s' % (aFolder, res))
if not res['OK']:
return res
res = returnSingleResult(
self.fileCatalog.removeDirectory(folder, recursive=True))
if not res['OK']:
return res
return S_OK()
def __removeStorageDirectory(self, directory, storageElement):
""" delete SE directory
:param self: self reference
:param str directory: folder to be removed
:param str storageElement: DIRAC SE name
"""
se = StorageElement(storageElement, vo=self.voName)
res = returnSingleResult(se.exists(directory))
log = self.log.getSubLogger('__removeStorageDirectory')
if not res['OK']:
log.debug("Failed to obtain existance of directory", res['Message'])
return res
exists = res['Value']
if not exists:
log.debug("The directory %s does not exist at %s " %
(directory, storageElement))
return S_OK()
res = returnSingleResult(se.removeDirectory(directory, recursive=True))
if not res['OK']:
log.debug("Failed to remove storage directory", res['Message'])
return res
log.debug("Successfully removed %d files from %s at %s" % (res['Value']['FilesRemoved'],
directory,
storageElement))
return S_OK()
def __getCatalogDirectoryContents(self, directories, includeDirectories=False):
""" ls recursively all files in directories
:param self: self reference
:param list directories: folder names
:param bool includeDirectories: if True includes directories in the return dictionary
:return: S_OK with dict of LFNs and their attribute dictionary
"""
log = self.log.getSubLogger('__getCatalogDirectoryContents')
log.debug('Obtaining the catalog contents for %d directories:' %
len(directories))
activeDirs = directories
allFiles = {}
while len(activeDirs) > 0:
currentDir = activeDirs[0]
res = returnSingleResult(
self.fileCatalog.listDirectory(currentDir, verbose=True))
activeDirs.remove(currentDir)
if not res['OK']:
log.debug("Problem getting the %s directory content" %
currentDir, res['Message'])
else:
dirContents = res['Value']
activeDirs.extend(dirContents['SubDirs'])
allFiles.update(dirContents['Files'])
if includeDirectories:
allFiles.update(dirContents['SubDirs'])
log.debug("Found %d files" % len(allFiles))
return S_OK(allFiles)
def getReplicasFromDirectory(self, directory):
""" get all replicas from a given directory
:param self: self reference
:param mixed directory: list of directories or one directory
"""
if isinstance(directory, basestring):
directories = [directory]
else:
directories = directory
res = self.__getCatalogDirectoryContents(directories)
if not res['OK']:
return res
allReplicas = dict((lfn, metadata['Replicas'])
for lfn, metadata in res['Value'].iteritems())
return S_OK(allReplicas)
def getFilesFromDirectory(self, directory, days=0, wildcard='*'):
""" get all files from :directory: older than :days: days matching to :wildcard:
:param self: self reference
:param mixed directory: list of directories or directory name
:param int days: ctime days
:param str wildcard: pattern to match
"""
if isinstance(directory, basestring):
directories = [directory]
else:
directories = directory
log = self.log.getSubLogger('getFilesFromDirectory')
log.debug("Obtaining the files older than %d days in %d directories:" %
(days, len(directories)))
for folder in directories:
log.debug(folder)
activeDirs = directories
allFiles = []
while len(activeDirs) > 0:
currentDir = activeDirs[0]
# We only need the metadata (verbose) if a limit date is given
res = returnSingleResult(
self.fileCatalog.listDirectory(currentDir, verbose=(days != 0)))
activeDirs.remove(currentDir)
if not res['OK']:
log.debug("Error retrieving directory contents", "%s %s" %
(currentDir, res['Message']))
else:
dirContents = res['Value']
subdirs = dirContents['SubDirs']
files = dirContents['Files']
log.debug("%s: %d files, %d sub-directories" %
(currentDir, len(files), len(subdirs)))
for subdir in subdirs:
if (not days) or _isOlderThan(subdirs[subdir]['CreationDate'], days):
if subdir[0] != '/':
subdir = currentDir + '/' + subdir
activeDirs.append(subdir)
for fileName in files:
fileInfo = files[fileName]
fileInfo = fileInfo.get('Metadata', fileInfo)
if (not days) or not fileInfo.get('CreationDate') or _isOlderThan(fileInfo['CreationDate'], days):
if wildcard == '*' or fnmatch.fnmatch(fileName, wildcard):
fileName = fileInfo.get('LFN', fileName)
allFiles.append(fileName)
return S_OK(allFiles)
##########################################################################
#
# These are the data transfer methods
#
def getFile(self, lfn, destinationDir='', sourceSE=None):
""" Get a local copy of a LFN from Storage Elements.
'lfn' is the logical file name for the desired file
"""
log = self.log.getSubLogger('getFile')
fileMetadata = {}
if isinstance(lfn, list):
lfns = lfn
elif isinstance(lfn, basestring):
lfns = [lfn]
else:
errStr = "Supplied lfn must be string or list of strings."
log.debug(errStr)
return S_ERROR(errStr)
log.debug("Attempting to get %s files." % len(lfns))
res = self.getActiveReplicas(lfns, getUrl=False)
if not res['OK']:
return res
failed = res['Value']['Failed']
lfnReplicas = res['Value']['Successful']
# If some files have replicas, check their metadata
if lfnReplicas:
res = self.fileCatalog.getFileMetadata(lfnReplicas.keys())
if not res['OK']:
return res
failed.update(res['Value']['Failed'])
fileMetadata = res['Value']['Successful']
successful = {}
for lfn in fileMetadata:
res = self.__getFile(
lfn, lfnReplicas[lfn], fileMetadata[lfn], destinationDir, sourceSE=sourceSE)
if not res['OK']:
failed[lfn] = res['Message']
else:
successful[lfn] = res['Value']
return S_OK({'Successful': successful, 'Failed': failed})
def __getFile(self, lfn, replicas, metadata, destinationDir, sourceSE=None):
"""
Method actually doing the job to get a file from storage
"""
log = self.log.getSubLogger('__getFile')
if not replicas:
errStr = "No accessible replicas found"
log.debug(errStr)
return S_ERROR(errStr)
# Determine the best replicas
errTuple = ("No SE", "found")
if sourceSE is None:
sortedSEs = self._getSEProximity(replicas)
else:
if sourceSE not in replicas:
return S_ERROR('No replica at %s' % sourceSE)
else:
sortedSEs = [sourceSE]
for storageElementName in sortedSEs:
se = StorageElement(storageElementName, vo=self.voName)
res = returnSingleResult(se.getFile(
lfn, localPath=os.path.realpath(destinationDir)))
if not res['OK']:
errTuple = ("Error getting file from storage:", "%s from %s, %s" %
(lfn, storageElementName, res['Message']))
errToReturn = res
else:
localFile = os.path.realpath(os.path.join(
destinationDir, os.path.basename(lfn)))
localAdler = fileAdler(localFile)
if metadata['Size'] != res['Value']:
errTuple = ("Mismatch of sizes:", "downloaded = %d, catalog = %d" %
(res['Value'], metadata['Size']))
errToReturn = S_ERROR(DErrno.EFILESIZE, errTuple[1])
elif (metadata['Checksum']) and (not compareAdler(metadata['Checksum'], localAdler)):
errTuple = ("Mismatch of checksums:", "downloaded = %s, catalog = %s" %
(localAdler, metadata['Checksum']))
errToReturn = S_ERROR(DErrno.EBADCKS, errTuple[1])
else:
return S_OK(localFile)
# If we are here, there was an error, log it debug level
log.debug(errTuple[0], errTuple[1])
log.verbose("Failed to get local copy from any replicas:",
"\n%s %s" % errTuple)
return errToReturn
def _getSEProximity(self, replicas):
""" get SE proximity """
siteName = DIRAC.siteName()
self.__filterTapeSEs(replicas)
localSEs = [se for se in self.dmsHelper.getSEsAtSite(
siteName).get('Value', []) if se in replicas]
countrySEs = []
countryCode = str(siteName).split('.')[-1]
res = self.dmsHelper.getSEsAtCountry(countryCode)
if res['OK']:
countrySEs = [se for se in res['Value']
if se in replicas and se not in localSEs]
sortedSEs = randomize(localSEs) + randomize(countrySEs)
sortedSEs += randomize(se for se in replicas if se not in sortedSEs)
return sortedSEs
def putAndRegister(self, lfn, fileName, diracSE, guid=None, path=None,
checksum=None, overwrite=False):
""" Put a local file to a Storage Element and register in the File Catalogues
'lfn' is the file LFN
'file' is the full path to the local file
'diracSE' is the Storage Element to which to put the file
'guid' is the guid with which the file is to be registered (if not provided will be generated)
'path' is the path on the storage where the file will be put (if not provided the LFN will be used)
'overwrite' removes file from the file catalogue and SE before attempting upload
"""
res = self.__hasAccess('addFile', lfn)
if not res['OK']:
return res
log = self.log.getSubLogger('putAndRegister')
if lfn not in res['Value']['Successful']:
errStr = "Write access not permitted for this credential."
log.debug(errStr, lfn)
return S_ERROR(errStr)
# Check that the local file exists
if not os.path.exists(fileName):
errStr = "Supplied file does not exist."
log.debug(errStr, fileName)
return S_ERROR(errStr)
# If the path is not provided then use the LFN path
if not path:
path = os.path.dirname(lfn)
# Obtain the size of the local file
size = getSize(fileName)
if size == 0:
errStr = "Supplied file is zero size."
log.debug(errStr, fileName)
return S_ERROR(errStr)
# If the GUID is not given, generate it here
if not guid:
guid = makeGuid(fileName)
if not checksum:
log.debug("Checksum information not provided. Calculating adler32.")
checksum = fileAdler(fileName)
# Make another try
if not checksum:
log.debug("Checksum calculation failed, try again")
checksum = fileAdler(fileName)
if checksum:
log.debug("Checksum calculated to be %s." % checksum)
else:
return S_ERROR(DErrno.EBADCKS, "Unable to calculate checksum")
res = self.fileCatalog.exists({lfn: guid})
if not res['OK']:
errStr = "Completely failed to determine existence of destination LFN."
log.debug(errStr, lfn)
return res
if lfn not in res['Value']['Successful']:
errStr = "Failed to determine existence of destination LFN."
log.debug(errStr, lfn)
return S_ERROR(errStr)
if res['Value']['Successful'][lfn]:
if res['Value']['Successful'][lfn] == lfn:
if overwrite:
resRm = self.removeFile(lfn, force=True)
if not resRm['OK']:
errStr = "Failed to prepare file for overwrite"
log.debug(errStr, lfn)
return resRm
if lfn not in resRm['Value']['Successful']:
errStr = "Failed to either delete file or LFN"
log.debug(errStr, lfn)
return S_ERROR("%s %s" % (errStr, lfn))
else:
errStr = "The supplied LFN already exists in the File Catalog."
log.debug(errStr, lfn)
return S_ERROR("%s %s" % (errStr, res['Value']['Successful'][lfn]))
else:
# If the returned LFN is different, this is the name of a file
# with the same GUID
errStr = "This file GUID already exists for another file"
log.debug(errStr, res['Value']['Successful'][lfn])
return S_ERROR("%s %s" % (errStr, res['Value']['Successful'][lfn]))
##########################################################
# Instantiate the destination storage element here.
storageElement = StorageElement(diracSE, vo=self.voName)
res = storageElement.isValid()
if not res['OK']:
errStr = "The storage element is not currently valid."
log.verbose(errStr, "%s %s" % (diracSE, res['Message']))
return S_ERROR("%s %s" % (errStr, res['Message']))
fileDict = {lfn: fileName}
successful = {}
failed = {}
##########################################################
# Perform the put here.
oDataOperation = _initialiseAccountingObject('putAndRegister', diracSE, 1)
oDataOperation.setStartTime()
oDataOperation.setValueByKey('TransferSize', size)
startTime = time.time()
res = returnSingleResult(storageElement.putFile(fileDict))
putTime = time.time() - startTime
oDataOperation.setValueByKey('TransferTime', putTime)
if not res['OK']:
# We don't consider it a failure if the SE is not valid
if not DErrno.cmpError(res, errno.EACCES):
oDataOperation.setValueByKey('TransferOK', 0)
oDataOperation.setValueByKey('FinalStatus', 'Failed')
oDataOperation.setEndTime()
gDataStoreClient.addRegister(oDataOperation)
gDataStoreClient.commit()
startTime = time.time()
log.debug('putAndRegister: Sending accounting took %.1f seconds' %
(time.time() - startTime))
errStr = "Failed to put file to Storage Element."
log.debug(errStr, "%s: %s" % (fileName, res['Message']))
return S_ERROR("%s %s" % (errStr, res['Message']))
successful[lfn] = {'put': putTime}
###########################################################
# Perform the registration here
destinationSE = storageElement.storageElementName()
res = returnSingleResult(storageElement.getURL(
lfn, protocol=self.registrationProtocol))
if not res['OK']:
errStr = "Failed to generate destination PFN."
log.debug(errStr, res['Message'])
return S_ERROR("%s %s" % (errStr, res['Message']))
destUrl = res['Value']
oDataOperation.setValueByKey('RegistrationTotal', 1)
fileTuple = (lfn, destUrl, size, destinationSE, guid, checksum)
registerDict = {'LFN': lfn, 'PFN': destUrl, 'Size': size,
'TargetSE': destinationSE, 'GUID': guid, 'Addler': checksum}
startTime = time.time()
res = self.registerFile(fileTuple)
registerTime = time.time() - startTime
oDataOperation.setValueByKey('RegistrationTime', registerTime)
if not res['OK']:
errStr = "Completely failed to register file."
log.debug(errStr, res['Message'])
failed[lfn] = {'register': registerDict}
oDataOperation.setValueByKey('FinalStatus', 'Failed')
elif lfn in res['Value']['Failed']:
errStr = "Failed to register file."
log.debug(errStr, "%s %s" % (lfn, res['Value']['Failed'][lfn]))
oDataOperation.setValueByKey('FinalStatus', 'Failed')
failed[lfn] = {'register': registerDict}
else:
successful[lfn]['register'] = registerTime
oDataOperation.setValueByKey('RegistrationOK', 1)
oDataOperation.setEndTime()
gDataStoreClient.addRegister(oDataOperation)
startTime = time.time()
gDataStoreClient.commit()
log.debug('Sending accounting took %.1f seconds' %
(time.time() - startTime))
return S_OK({'Successful': successful, 'Failed': failed})
def replicateAndRegister(self, lfn, destSE, sourceSE='', destPath='', localCache='', catalog=''):
""" Replicate a LFN to a destination SE and register the replica.
'lfn' is the LFN to be replicated
'destSE' is the Storage Element the file should be replicated to
'sourceSE' is the source for the file replication (where not specified all replicas will be attempted)
'destPath' is the path on the destination storage element, if to be different from LHCb convention
'localCache' is the local file system location to be used as a temporary cache
"""
log = self.log.getSubLogger('replicateAndRegister')
successful = {}
failed = {}
log.debug("Attempting to replicate %s to %s." % (lfn, destSE))
startReplication = time.time()
res = self.__replicate(lfn, destSE, sourceSE, destPath, localCache)
replicationTime = time.time() - startReplication
if not res['OK']:
errStr = "Completely failed to replicate file."
log.debug(errStr, res['Message'])
return S_ERROR("%s %s" % (errStr, res['Message']))
if not res['Value']:
# The file was already present at the destination SE
log.debug("%s already present at %s." % (lfn, destSE))
successful[lfn] = {'replicate': 0, 'register': 0}
resDict = {'Successful': successful, 'Failed': failed}
return S_OK(resDict)
successful[lfn] = {'replicate': replicationTime}
destPfn = res['Value']['DestPfn']
destSE = res['Value']['DestSE']
log.debug("Attempting to register %s at %s." % (destPfn, destSE))
replicaTuple = (lfn, destPfn, destSE)
startRegistration = time.time()
res = self.registerReplica(replicaTuple, catalog=catalog)
registrationTime = time.time() - startRegistration
if not res['OK']:
# Need to return to the client that the file was replicated but not
# registered
errStr = "Completely failed to register replica."
log.debug(errStr, res['Message'])
failed[lfn] = {'Registration': {
'LFN': lfn, 'TargetSE': destSE, 'PFN': destPfn}}
else:
if lfn in res['Value']['Successful']:
log.debug("Successfully registered replica.")
successful[lfn]['register'] = registrationTime
else:
errStr = "Failed to register replica."
log.debug(errStr, res['Value']['Failed'][lfn])
failed[lfn] = {'Registration': {
'LFN': lfn, 'TargetSE': destSE, 'PFN': destPfn}}
return S_OK({'Successful': successful, 'Failed': failed})
def replicate(self, lfn, destSE, sourceSE='', destPath='', localCache=''):
""" Replicate a LFN to a destination SE and register the replica.
'lfn' is the LFN to be replicated
'destSE' is the Storage Element the file should be replicated to
'sourceSE' is the source for the file replication (where not specified all replicas will be attempted)
'destPath' is the path on the destination storage element, if to be different from LHCb convention
'localCache' is the local file system location to be used as a temporary cache
"""
log = self.log.getSubLogger('replicate')
log.debug("Attempting to replicate %s to %s." % (lfn, destSE))
res = self.__replicate(lfn, destSE, sourceSE, destPath, localCache)
if not res['OK']:
errStr = "Replication failed."
log.debug(errStr, "%s %s" % (lfn, destSE))
return res
if not res['Value']:
# The file was already present at the destination SE
log.debug("%s already present at %s." % (lfn, destSE))
return res
return S_OK(lfn)
def __getSERealName(self, storageName):
""" get the base name of an SE possibly defined as an alias"""
rootConfigPath = '/Resources/StorageElements'
configPath = '%s/%s' % (rootConfigPath, storageName)
res = gConfig.getOptions(configPath)
if not res['OK']:
errStr = "Failed to get storage options"
return S_ERROR(errStr)
if not res['Value']:
errStr = "Supplied storage doesn't exist."
return S_ERROR(errStr)
if 'Alias' in res['Value']:
configPath += '/Alias'
aliasName = gConfig.getValue(configPath)
result = self.__getSERealName(aliasName)
if not result['OK']:
return result
resolvedName = result['Value']
else:
resolvedName = storageName
return S_OK(resolvedName)
def __isSEInList(self, seName, seList):
""" Check whether an SE is in a list of SEs... All could be aliases """
seSet = set()
for se in seList:
res = self.__getSERealName(se)
if res['OK']:
seSet.add(res['Value'])
return self.__getSERealName(seName).get('Value') in seSet
def __replicate(self, lfn, destSEName, sourceSEName='', destPath='', localCache=''):
""" Replicate a LFN to a destination SE.
'lfn' is the LFN to be replicated
'destSE' is the Storage Element the file should be replicated to
'sourceSE' is the source for the file replication (where not specified all replicas will be attempted)
'destPath' is the path on the destination storage element, if to be different from LHCb convention
'localCache' if cannot do third party transfer, we do get and put through this local directory
"""
log = self.log.getSubLogger('__replicate', True)
###########################################################
# Check that we have write permissions to this directory.
res = self.__hasAccess('addReplica', lfn)
if not res['OK']:
return res
if lfn not in res['Value']['Successful']:
errStr = "__replicate: Write access not permitted for this credential."
log.debug(errStr, lfn)
return S_ERROR(errStr)
# Check that the destination storage element is sane and resolve its name
log.debug("Verifying destination StorageElement validity (%s)." %
(destSEName))
destStorageElement = StorageElement(destSEName, vo=self.voName)
res = destStorageElement.isValid()
if not res['OK']:
errStr = "The storage element is not currently valid."
log.verbose(errStr, "%s %s" % (destSEName, res['Message']))
return S_ERROR("%s %s" % (errStr, res['Message']))
# Get the real name of the SE
destSEName = destStorageElement.storageElementName()
###########################################################
# Check whether the destination storage element is banned
log.verbose(
"Determining whether %s ( destination ) is Write-banned." % destSEName)
if not destStorageElement.status()['Write']:
infoStr = "Supplied destination Storage Element is not currently allowed for Write."
log.debug(infoStr, destSEName)
return S_ERROR(infoStr)
# Get the LFN replicas from the file catalog
log.debug("Attempting to obtain replicas for %s." % (lfn))
res = returnSingleResult(self.getReplicas(lfn, getUrl=False))
if not res['OK']:
errStr = "Failed to get replicas for LFN."
log.debug(errStr, "%s %s" % (lfn, res['Message']))
return S_ERROR("%s %s" % (errStr, res['Message']))
log.debug("Successfully obtained replicas for LFN.")
lfnReplicas = res['Value']
###########################################################
# If the file catalog size is zero fail the transfer
log.debug("Attempting to obtain size for %s." % lfn)
res = returnSingleResult(self.fileCatalog.getFileSize(lfn))
if not res['OK']:
errStr = "Failed to get size for LFN."
log.debug(errStr, "%s %s" % (lfn, res['Message']))
return S_ERROR("%s %s" % (errStr, res['Message']))
catalogSize = res['Value']
if catalogSize == 0:
errStr = "Registered file size is 0."
log.debug(errStr, lfn)
return S_ERROR(errStr)
log.debug("File size determined to be %s." % catalogSize)
###########################################################
# If the LFN already exists at the destination we have nothing to do
if self.__isSEInList(destSEName, lfnReplicas):
log.debug("__replicate: LFN is already registered at %s." % destSEName)
return S_OK()
###########################################################
# If the source is specified, check that it is in the replicas
if sourceSEName:
log.debug("Determining whether source Storage Element specified is sane.")
if sourceSEName not in lfnReplicas:
errStr = "LFN does not exist at supplied source SE."
log.error(errStr, "%s %s" % (lfn, sourceSEName))
return S_ERROR(errStr)
# If sourceSE is specified, then we consider this one only, otherwise
# we consider them all
possibleSourceSEs = [sourceSEName] if sourceSEName else lfnReplicas
# We sort the possibileSourceSEs with the SEs that are on the same site than the destination first
# reverse = True because True > False
possibleSourceSEs = sorted(possibleSourceSEs,
key=lambda x: self.dmsHelper.isSameSiteSE(
x, destSEName).get('Value', False),
reverse=True)
# In case we manage to find SEs that would work as a source, but we can't negotiate a protocol
# we will do a get and put using one of this sane SE
possibleIntermediateSEs = []
# Take into account the destination path
if destPath:
destPath = '%s/%s' % (destPath, os.path.basename(lfn))
else:
destPath = lfn
for candidateSEName in possibleSourceSEs:
log.debug("Consider %s as a source" % candidateSEName)
# Check that the candidate is active
if not self.__checkSEStatus(candidateSEName, status='Read'):
log.debug("%s is currently not allowed as a source." % candidateSEName)
continue
else:
log.debug("%s is available for use." % candidateSEName)
candidateSE = StorageElement(candidateSEName, vo=self.voName)
# Check that the SE is valid
res = candidateSE.isValid()
if not res['OK']:
log.verbose("The storage element is not currently valid.",
"%s %s" % (candidateSEName, res['Message']))
continue
else:
log.debug("The storage is currently valid", candidateSEName)
# Check that the file size corresponds to the one in the FC
res = returnSingleResult(candidateSE.getFileSize(lfn))
if not res['OK']:
log.debug("could not get fileSize on %s" %
candidateSEName, res['Message'])
continue
seFileSize = res['Value']
if seFileSize != catalogSize:
log.debug("Catalog size and physical file size mismatch.",
"%s %s" % (catalogSize, seFileSize))
continue
else:
log.debug("Catalog size and physical size match")
res = destStorageElement.negociateProtocolWithOtherSE(
candidateSE, protocols=self.thirdPartyProtocols)
if not res['OK']:
log.debug("Error negotiating replication protocol", res['Message'])
continue
replicationProtocols = res['Value']
if not replicationProtocols:
possibleIntermediateSEs.append(candidateSE)
log.debug("No protocol suitable for replication found")
continue
log.debug('Found common protocols', replicationProtocols)
# THIS WOULD NOT WORK IF PROTO == file !!
# Why did I write that comment ?!
# We try the protocols one by one
# That obviously assumes that there is an overlap and not only
# a compatibility between the output protocols of the source
# and the input protocols of the destination.
# But that is the only way to make sure we are not replicating
# over ourselves.
for compatibleProtocol in replicationProtocols:
# Compare the urls to make sure we are not overwriting
res = returnSingleResult(candidateSE.getURL(
lfn, protocol=compatibleProtocol))
if not res['OK']:
log.debug("Cannot get sourceURL", res['Message'])
continue
sourceURL = res['Value']
destURL = ''
res = returnSingleResult(destStorageElement.getURL(
destPath, protocol=compatibleProtocol))
if not res['OK']:
# for some protocols, in particular srm
# you might get an error because the file does not exist
# which is exactly what we want
# in that case, we just keep going with the comparison
# since destURL will be an empty string
if not DErrno.cmpError(res, errno.ENOENT):
log.debug("Cannot get destURL", res['Message'])
continue
else:
log.debug("File does not exist: Expected error for TargetSE !!")
destURL = res['Value']
if sourceURL == destURL:
log.debug("Same source and destination, give up")
continue
# Attempt the transfer
res = returnSingleResult(destStorageElement.replicateFile({destPath: sourceURL},
sourceSize=catalogSize,
inputProtocol=compatibleProtocol))
if not res['OK']:
log.debug("Replication failed", "%s from %s to %s." %
(lfn, candidateSEName, destSEName))
continue
log.debug("Replication successful.", res['Value'])
res = returnSingleResult(destStorageElement.getURL(
destPath, protocol=self.registrationProtocol))
if not res['OK']:
log.debug('Error getting the registration URL', res['Message'])
# it's maybe pointless to try the other candidateSEs...
continue
registrationURL = res['Value']
return S_OK({'DestSE': destSEName, 'DestPfn': registrationURL})
# If we are here, that means that we could not make a third party transfer.
# Check if we have some sane SEs from which we could do a get/put
localDir = os.path.realpath(localCache if localCache else '.')
localFile = os.path.join(localDir, os.path.basename(lfn))
log.debug("Will try intermediate transfer from %s sources" %
len(possibleIntermediateSEs))
for candidateSE in possibleIntermediateSEs:
res = returnSingleResult(candidateSE.getFile(lfn, localPath=localDir))
if not res['OK']:
log.debug('Error getting the file from %s' %
candidateSE.name, res['Message'])
continue
res = returnSingleResult(
destStorageElement.putFile({destPath: localFile}))
# Remove the local file whatever happened
try:
os.remove(localFile)
except OSError as e:
log.error('Error removing local file', '%s %s' % (localFile, e))
if not res['OK']:
log.debug('Error putting file coming from %s' %
candidateSE.name, res['Message'])
# if the put is the problem, it's maybe pointless to try the other
# candidateSEs...
continue
# get URL with default protocol to return it
res = returnSingleResult(destStorageElement.getURL(
destPath, protocol=self.registrationProtocol))
if not res['OK']:
log.debug('Error getting the registration URL', res['Message'])
# it's maybe pointless to try the other candidateSEs...
continue
registrationURL = res['Value']
return S_OK({'DestSE': destSEName, 'DestPfn': registrationURL})
# If here, we are really doomed
errStr = "Failed to replicate with all sources."
log.debug(errStr, lfn)
return S_ERROR(errStr)
###################################################################
#
# These are the file catalog write methods
#
def registerFile(self, fileTuple, catalog=''):
""" Register a file or a list of files
:param self: self reference
:param tuple fileTuple: (lfn, physicalFile, fileSize, storageElementName, fileGuid, checksum )
:param str catalog: catalog name
"""
log = self.log.getSubLogger('registerFile')
if isinstance(fileTuple, (list, set)):
fileTuples = fileTuple
elif isinstance(fileTuple, tuple):
fileTuples = [fileTuple]
for fileTuple in fileTuples:
if not isinstance(fileTuple, tuple):
errStr = "Supplied file info must be tuple or list of tuples."
log.debug(errStr)
return S_ERROR(errStr)
if not fileTuples:
return S_OK({'Successful': [], 'Failed': {}})
log.debug("Attempting to register %s files." % len(fileTuples))
res = self.__registerFile(fileTuples, catalog)
if not res['OK']:
errStr = "Completely failed to register files."
log.debug(errStr, res['Message'])
return res
return res
def __registerFile(self, fileTuples, catalog):
""" register file to catalog """
fileDict = {}
for lfn, physicalFile, fileSize, storageElementName, fileGuid, checksum in fileTuples:
fileDict[lfn] = {'PFN': physicalFile,
'Size': fileSize,
'SE': storageElementName,
'GUID': fileGuid,
'Checksum': checksum}
if catalog:
fileCatalog = FileCatalog(catalog, vo=self.voName)
if not fileCatalog.isOK():
return S_ERROR("Can't get FileCatalog %s" % catalog)
else:
fileCatalog = self.fileCatalog
res = fileCatalog.addFile(fileDict)
if not res['OK']:
errStr = "Completely failed to register files."
self.log.getSubLogger('__registerFile').debug(errStr, res['Message'])
return res
def registerReplica(self, replicaTuple, catalog=''):
""" Register a replica (or list of) supplied in the replicaTuples.
'replicaTuple' is a tuple or list of tuples of the form (lfn,pfn,se)
"""
log = self.log.getSubLogger('registerReplica')
if isinstance(replicaTuple, (list, set)):
replicaTuples = replicaTuple
elif isinstance(replicaTuple, tuple):
replicaTuples = [replicaTuple]
for replicaTuple in replicaTuples:
if not isinstance(replicaTuple, tuple):
errStr = "Supplied file info must be tuple or list of tuples."
log.debug(errStr)
return S_ERROR(errStr)
if not replicaTuples:
return S_OK({'Successful': [], 'Failed': {}})
log.debug("Attempting to register %s replicas." % len(replicaTuples))
res = self.__registerReplica(replicaTuples, catalog)
if not res['OK']:
errStr = "Completely failed to register replicas."
log.debug(errStr, res['Message'])
return res
return res
def __registerReplica(self, replicaTuples, catalog):
""" register replica to catalogue """
log = self.log.getSubLogger('__registerReplica')
seDict = {}
for lfn, url, storageElementName in replicaTuples:
seDict.setdefault(storageElementName, []).append((lfn, url))
failed = {}
replicaTuples = []
for storageElementName, replicaTuple in seDict.iteritems():
destStorageElement = StorageElement(storageElementName, vo=self.voName)
res = destStorageElement.isValid()
if not res['OK']:
errStr = "The storage element is not currently valid."
log.verbose(errStr, "%s %s" % (storageElementName, res['Message']))
for lfn, url in replicaTuple:
failed[lfn] = errStr
else:
storageElementName = destStorageElement.storageElementName()
for lfn, url in replicaTuple:
res = returnSingleResult(destStorageElement.getURL(
lfn, protocol=self.registrationProtocol))
if not res['OK']:
failed[lfn] = res['Message']
else:
replicaTuple = (lfn, res['Value'], storageElementName, False)
replicaTuples.append(replicaTuple)
log.debug("Successfully resolved %s replicas for registration." %
len(replicaTuples))
# HACK!
replicaDict = {}
for lfn, url, se, _master in replicaTuples:
replicaDict[lfn] = {'SE': se, 'PFN': url}
if catalog:
fileCatalog = FileCatalog(catalog, vo=self.voName)
res = fileCatalog.addReplica(replicaDict)
else:
res = self.fileCatalog.addReplica(replicaDict)
if not res['OK']:
errStr = "Completely failed to register replicas."
log.debug(errStr, res['Message'])
return S_ERROR("%s %s" % (errStr, res['Message']))
failed.update(res['Value']['Failed'])
successful = res['Value']['Successful']
resDict = {'Successful': successful, 'Failed': failed}
return S_OK(resDict)
###################################################################
#
# These are the removal methods for physical and catalogue removal
#
def removeFile(self, lfn, force=None):
""" Remove the file (all replicas) from Storage Elements and file catalogue
'lfn' is the file to be removed
"""
log = self.log.getSubLogger('removeFile')
if not lfn:
return S_OK({'Successful': {}, 'Failed': {}})
if force is None:
force = self.ignoreMissingInFC
if isinstance(lfn, (list, dict, set, tuple)):
lfns = list(lfn)
else:
lfns = [lfn]
for lfn in lfns:
if not isinstance(lfn, basestring):
errStr = "Supplied lfns must be string or list of strings."
log.debug(errStr)
return S_ERROR(errStr)
successful = {}
failed = {}
if not lfns:
return S_OK({'Successful': successful, 'Failed': failed})
# First check if the file exists in the FC
res = self.fileCatalog.exists(lfns)
if not res['OK']:
return res
success = res['Value']['Successful']
lfns = [lfn for lfn in success if success[lfn]]
if force:
# Files that don't exist are removed successfully
successful = dict.fromkeys(
(lfn for lfn in success if not success[lfn]), True)
else:
failed = dict.fromkeys(
(lfn for lfn in success if not success[lfn]), 'No such file or directory')
# Check that we have write permissions to this directory and to the file.
if lfns:
res = self.__hasAccess('removeFile', lfns)
if not res['OK']:
return res
if res['Value']['Failed']:
errStr = "Write access not permitted for this credential."
log.debug(errStr, 'for %d files' % len(res['Value']['Failed']))
failed.update(dict.fromkeys(res['Value']['Failed'], errStr))
lfns = res['Value']['Successful']
if lfns:
log.debug(
"Attempting to remove %d files from Storage and Catalogue. Get replicas first" % len(lfns))
res = self.fileCatalog.getReplicas(lfns, allStatus=True)
if not res['OK']:
errStr = "DataManager.removeFile: Completely failed to get replicas for lfns."
log.debug(errStr, res['Message'])
return res
lfnDict = res['Value']['Successful']
for lfn, reason in res['Value']['Failed'].iteritems():
# Ignore files missing in FC if force is set
if reason == 'No such file or directory' and force:
successful[lfn] = True
elif reason == 'File has zero replicas':
lfnDict[lfn] = {}
else:
failed[lfn] = reason
res = self.__removeFile(lfnDict)
if not res['OK']:
# This can never happen
return res
failed.update(res['Value']['Failed'])
successful.update(res['Value']['Successful'])
gDataStoreClient.commit()
return S_OK({'Successful': successful, 'Failed': failed})
def __removeFile(self, lfnDict):
""" remove file """
storageElementDict = {}
# # sorted and reversed
for lfn, repDict in sorted(lfnDict.items(), reverse=True):
for se in repDict:
storageElementDict.setdefault(se, []).append(lfn)
failed = {}
successful = {}
for storageElementName in sorted(storageElementDict):
lfns = storageElementDict[storageElementName]
res = self.__removeReplica(storageElementName, lfns, replicaDict=lfnDict)
if not res['OK']:
errStr = res['Message']
for lfn in lfns:
failed[lfn] = failed.setdefault(lfn, '') + " %s" % errStr
else:
for lfn, errStr in res['Value']['Failed'].iteritems():
failed[lfn] = failed.setdefault(lfn, '') + " %s" % errStr
completelyRemovedFiles = set(lfnDict) - set(failed)
if completelyRemovedFiles:
res = self.fileCatalog.removeFile(list(completelyRemovedFiles))
if not res['OK']:
failed.update(dict.fromkeys(completelyRemovedFiles,
"Failed to remove file from the catalog: %s" % res['Message']))
else:
failed.update(res['Value']['Failed'])
successful = res['Value']['Successful']
return S_OK({'Successful': successful, 'Failed': failed})
def removeReplica(self, storageElementName, lfn):
""" Remove replica at the supplied Storage Element from Storage Element then file catalogue
'storageElementName' is the storage where the file is to be removed
'lfn' is the file to be removed
"""
log = self.log.getSubLogger('removeReplica')
if isinstance(lfn, (list, dict, set, tuple)):
lfns = set(lfn)
else:
lfns = set([lfn])
for lfn in lfns:
if not isinstance(lfn, basestring):
errStr = "Supplied lfns must be string or list of strings."
log.debug(errStr)
return S_ERROR(errStr)
successful = {}
failed = {}
if not lfns:
return S_OK({'Successful': successful, 'Failed': failed})
# Check that we have write permissions to this file.
res = self.__hasAccess('removeReplica', lfns)
if not res['OK']:
log.debug('Error in __verifyWritePermisison', res['Message'])
return res
if res['Value']['Failed']:
errStr = "Write access not permitted for this credential."
log.debug(errStr, 'for %d files' % len(res['Value']['Failed']))
failed.update(dict.fromkeys(res['Value']['Failed'], errStr))
lfns -= set(res['Value']['Failed'])
if not lfns:
log.debug('Permission denied for all files')
else:
log.debug("Will remove %s lfns at %s." % (len(lfns), storageElementName))
res = self.fileCatalog.getReplicas(list(lfns), allStatus=True)
if not res['OK']:
errStr = "Completely failed to get replicas for lfns."
log.debug(errStr, res['Message'])
return res
failed.update(res['Value']['Failed'])
replicaDict = res['Value']['Successful']
lfnsToRemove = set()
for lfn, repDict in replicaDict.iteritems():
if storageElementName not in repDict:
# The file doesn't exist at the storage element so don't have to
# remove it
successful[lfn] = True
elif len(repDict) == 1:
# The file has only a single replica so don't remove
log.debug("The replica you are trying to remove is the only one.",
"%s @ %s" % (lfn, storageElementName))
failed[lfn] = "Failed to remove sole replica"
else:
lfnsToRemove.add(lfn)
if lfnsToRemove:
res = self.__removeReplica(
storageElementName, lfnsToRemove, replicaDict=replicaDict)
if not res['OK']:
log.debug("Failed in __removeReplica", res['Message'])
return res
failed.update(res['Value']['Failed'])
successful.update(res['Value']['Successful'])
gDataStoreClient.commit()
return S_OK({'Successful': successful, 'Failed': failed})
def __removeReplica(self, storageElementName, lfns, replicaDict=None):
""" remove replica
Remove the replica from the storageElement, and then from the catalog
:param storageElementName : The name of the storage Element
:param lfns : list of lfn we want to remove
:param replicaDict : cache of fc.getReplicas(lfns) : { lfn { se : catalog url } }
"""
log = self.log.getSubLogger('__removeReplica')
failed = {}
successful = {}
replicaDict = replicaDict if replicaDict else {}
lfnsToRemove = set()
for lfn in lfns:
res = self.__hasAccess('removeReplica', lfn)
if not res['OK']:
log.debug('Error in __verifyWritePermission', res['Message'])
return res
if lfn not in res['Value']['Successful']:
errStr = "Write access not permitted for this credential."
log.debug(errStr, lfn)
failed[lfn] = errStr
else:
lfnsToRemove.add(lfn)
# Remove physical replicas first
res = self.__removePhysicalReplica(
storageElementName, lfnsToRemove, replicaDict=replicaDict)
if not res['OK']:
errStr = "Failed to remove physical replicas."
log.debug(errStr, res['Message'])
return res
failed.update(res['Value']['Failed'])
# Here we use the FC PFN...
replicaTuples = [(lfn, replicaDict[lfn][storageElementName], storageElementName)
for lfn in res['Value']['Successful']]
if replicaTuples:
res = self.__removeCatalogReplica(replicaTuples)
if not res['OK']:
errStr = "Completely failed to remove physical files."
log.debug(errStr, res['Message'])
failed.update(dict.fromkeys(
(lfn for lfn, _pfn, _se in replicaTuples), res['Message']))
successful = {}
else:
failed.update(res['Value']['Failed'])
successful = res['Value']['Successful']
return S_OK({'Successful': successful, 'Failed': failed})
def removeReplicaFromCatalog(self, storageElementName, lfn):
""" remove :lfn: replica from :storageElementName: SE
:param self: self reference
:param str storageElementName: SE name
:param mixed lfn: a single LFN or list of LFNs
"""
# FIXME: this method is dangerous ans should eventually be removed as well
# as the script dirac-dms-remove-catalog-replicas
log = self.log.getSubLogger('removeReplicaFromCatalog')
# Remove replica from the file catalog 'lfn' are the file
# to be removed 'storageElementName' is the storage where the file is to
# be removed
if isinstance(lfn, (list, dict, set, tuple)):
lfns = list(lfn)
else:
lfns = [lfn]
for lfn in lfns:
if not isinstance(lfn, basestring):
errStr = "Supplied lfns must be string or list of strings."
log.debug(errStr)
return S_ERROR(errStr)
successful = {}
failed = {}
if not lfns:
return S_OK({'Successful': successful, 'Failed': failed})
log.debug("Will remove catalogue entry for %s lfns at %s." %
(len(lfns), storageElementName))
res = self.fileCatalog.getReplicas(lfns, allStatus=True)
if not res['OK']:
errStr = "Completely failed to get replicas for lfns."
log.debug(errStr, res['Message'])
return res
failed = {}
successful = {}
for lfn, reason in res['Value']['Failed'].iteritems():
if reason in ('No such file or directory', 'File has zero replicas'):
successful[lfn] = True
else:
failed[lfn] = reason
replicaTuples = []
for lfn, repDict in res['Value']['Successful'].iteritems():
if storageElementName not in repDict:
# The file doesn't exist at the storage element so don't have to remove
# it
successful[lfn] = True
else:
replicaTuples.append(
(lfn, repDict[storageElementName], storageElementName))
log.debug("Resolved %s pfns for catalog removal at %s." % (len(replicaTuples),
storageElementName))
res = self.__removeCatalogReplica(replicaTuples)
failed.update(res['Value']['Failed'])
successful.update(res['Value']['Successful'])
resDict = {'Successful': successful, 'Failed': failed}
return S_OK(resDict)
def __removeCatalogReplica(self, replicaTuples):
""" remove replica form catalogue
:param replicaTuples : list of (lfn, catalogPFN, se)
"""
log = self.log.getSubLogger('__removeCatalogReplica')
oDataOperation = _initialiseAccountingObject(
'removeCatalogReplica', '', len(replicaTuples))
oDataOperation.setStartTime()
start = time.time()
# HACK!
replicaDict = {}
for lfn, pfn, se in replicaTuples:
replicaDict[lfn] = {'SE': se, 'PFN': pfn}
res = self.fileCatalog.removeReplica(replicaDict)
oDataOperation.setEndTime()
oDataOperation.setValueByKey('RegistrationTime', time.time() - start)
if not res['OK']:
oDataOperation.setValueByKey('RegistrationOK', 0)
oDataOperation.setValueByKey('FinalStatus', 'Failed')
gDataStoreClient.addRegister(oDataOperation)
errStr = "Completely failed to remove replica: "
log.debug(errStr, res['Message'])
return S_ERROR("%s %s" % (errStr, res['Message']))
success = res['Value']['Successful']
failed = res['Value']['Failed']
for lfn, error in failed.items():
# Ignore error if file doesn't exist
# This assumes all catalogs return an error as { catalog : error }
for catalog, err in error.items():
if 'no such file' in err.lower():
success.setdefault(lfn, {}).update({catalog: True})
error.pop(catalog)
if not failed[lfn]:
failed.pop(lfn)
else:
log.error("Failed to remove replica.", "%s %s" % (lfn, error))
# Only for logging information
if success:
log.debug("Removed %d replicas" % len(success))
for lfn in success:
log.debug("Successfully removed replica.", lfn)
oDataOperation.setValueByKey('RegistrationOK', len(success))
gDataStoreClient.addRegister(oDataOperation)
return res
def __removePhysicalReplica(self, storageElementName, lfnsToRemove, replicaDict=None):
""" remove replica from storage element
:param storageElementName : name of the storage Element
:param lfnsToRemove : set of lfn to removes
:param replicaDict : cache of fc.getReplicas, to be passed to the SE
"""
log = self.log.getSubLogger('__removePhysicalReplica')
log.debug("Attempting to remove %s pfns at %s." %
(len(lfnsToRemove), storageElementName))
storageElement = StorageElement(storageElementName, vo=self.voName)
res = storageElement.isValid()
if not res['OK']:
errStr = "The storage element is not currently valid."
log.verbose(errStr, "%s %s" % (storageElementName, res['Message']))
return S_ERROR("%s %s" % (errStr, res['Message']))
oDataOperation = _initialiseAccountingObject('removePhysicalReplica',
storageElementName,
len(lfnsToRemove))
oDataOperation.setStartTime()
start = time.time()
lfnsToRemove = list(lfnsToRemove)
ret = storageElement.getFileSize(lfnsToRemove, replicaDict=replicaDict)
deletedSizes = ret.get('Value', {}).get('Successful', {})
res = storageElement.removeFile(lfnsToRemove, replicaDict=replicaDict)
oDataOperation.setEndTime()
oDataOperation.setValueByKey('TransferTime', time.time() - start)
if not res['OK']:
oDataOperation.setValueByKey('TransferOK', 0)
oDataOperation.setValueByKey('FinalStatus', 'Failed')
gDataStoreClient.addRegister(oDataOperation)
log.debug("Failed to remove replicas.", res['Message'])
else:
for lfn, value in res['Value']['Failed'].items():
if 'No such file or directory' in value:
res['Value']['Successful'][lfn] = lfn
res['Value']['Failed'].pop(lfn)
for lfn in res['Value']['Successful']:
res['Value']['Successful'][lfn] = True
deletedSize = sum(deletedSizes.get(lfn, 0)
for lfn in res['Value']['Successful'])
oDataOperation.setValueByKey('TransferSize', deletedSize)
oDataOperation.setValueByKey(
'TransferOK', len(res['Value']['Successful']))
gDataStoreClient.addRegister(oDataOperation)
infoStr = "Successfully issued accounting removal request."
log.debug(infoStr)
return res
#########################################################################
#
# File transfer methods
#
def put(self, lfn, fileName, diracSE, path=None):
""" Put a local file to a Storage Element
:param self: self reference
:param str lfn: LFN
:param str fileName: the full path to the local file
:param str diracSE: the Storage Element to which to put the file
:param str path: the path on the storage where the file will be put (if not provided the LFN will be used)
"""
log = self.log.getSubLogger('put')
# Check that the local file exists
if not os.path.exists(fileName):
errStr = "Supplied file does not exist."
log.debug(errStr, fileName)
return S_ERROR(errStr)
# If the path is not provided then use the LFN path
if not path:
path = os.path.dirname(lfn)
# Obtain the size of the local file
size = getSize(fileName)
if size == 0:
errStr = "Supplied file is zero size."
log.debug(errStr, fileName)
return S_ERROR(errStr)
##########################################################
# Instantiate the destination storage element here.
storageElement = StorageElement(diracSE, vo=self.voName)
res = storageElement.isValid()
if not res['OK']:
errStr = "The storage element is not currently valid."
log.verbose(errStr, "%s %s" % (diracSE, res['Message']))
return S_ERROR("%s %s" % (errStr, res['Message']))
fileDict = {lfn: fileName}
successful = {}
failed = {}
##########################################################
# Perform the put here.
startTime = time.time()
res = returnSingleResult(storageElement.putFile(fileDict))
putTime = time.time() - startTime
if not res['OK']:
errStr = "Failed to put file to Storage Element."
failed[lfn] = res['Message']
log.debug(errStr, "%s: %s" % (fileName, res['Message']))
else:
log.debug("Put file to storage in %s seconds." % putTime)
successful[lfn] = res['Value']
resDict = {'Successful': successful, 'Failed': failed}
return S_OK(resDict)
#########################################################################
#
# File catalog methods
#
def getActiveReplicas(self, lfns, getUrl=True, diskOnly=False, preferDisk=False):
""" Get all the replicas for the SEs which are in Active status for reading.
"""
return self.getReplicas(lfns, allStatus=False, getUrl=getUrl, diskOnly=diskOnly,
preferDisk=preferDisk, active=True)
def __filterTapeReplicas(self, replicaDict, diskOnly=False):
"""
Check a replica dictionary for disk replicas:
If there is a disk replica, removetape replicas, else keep all
The input argument is modified
"""
seList = set(
se for ses in replicaDict['Successful'].itervalues() for se in ses)
# Get a cache of SE statuses for long list of replicas
seStatus = dict((se,
(self.__checkSEStatus(se, status='DiskSE'),
self.__checkSEStatus(se, status='TapeSE'))) for se in seList)
# Beware, there is a del below
for lfn, replicas in replicaDict['Successful'].items():
self.__filterTapeSEs(replicas, diskOnly=diskOnly, seStatus=seStatus)
# If diskOnly, one may not have any replica in the end, set Failed
if diskOnly and not replicas:
del replicaDict['Successful'][lfn]
replicaDict['Failed'][lfn] = 'No disk replicas'
return
def __filterReplicasForJobs(self, replicaDict):
""" Remove the SEs that are not to be used for jobs, and archive SEs if there are others
The input argument is modified
"""
seList = set(
se for ses in replicaDict['Successful'].itervalues() for se in ses)
# Get a cache of SE statuses for long list of replicas
seStatus = dict((se, (self.dmsHelper.isSEForJobs(
se), self.dmsHelper.isSEArchive(se))) for se in seList)
# Beware, there is a del below
for lfn, replicas in replicaDict['Successful'].items():
otherThanArchive = set(se for se in replicas if not seStatus[se][1])
for se in replicas.keys():
# Remove the SE if it should not be used for jobs or if it is an
# archive and there are other SEs
if not seStatus[se][0] or (otherThanArchive and seStatus[se][1]):
replicas.pop(se)
# If in the end there is no replica, set Failed
if not replicas:
del replicaDict['Successful'][lfn]
replicaDict['Failed'][lfn] = 'No replicas for jobs'
return
def __filterTapeSEs(self, replicas, diskOnly=False, seStatus=None):
""" Remove the tape SEs as soon as there is one disk SE or diskOnly is requested
The input argument is modified
"""
# Build the SE status cache if not existing
if seStatus is None:
seStatus = dict((se,
(self.__checkSEStatus(se, status='DiskSE'),
self.__checkSEStatus(se, status='TapeSE'))) for se in replicas)
for se in replicas: # There is a del below but we then return!
# First find a disk replica, otherwise do nothing unless diskOnly is set
if diskOnly or seStatus[se][0]:
# There is one disk replica, remove tape replicas and exit loop
for se in replicas.keys(): # Beware: there is a pop below
if seStatus[se][1]:
replicas.pop(se)
return
return
def checkActiveReplicas(self, replicaDict):
"""
Check a replica dictionary for active replicas, and verify input structure first
"""
if not isinstance(replicaDict, dict):
return S_ERROR('Wrong argument type %s, expected a dictionary' % type(replicaDict))
for key in ['Successful', 'Failed']:
if key not in replicaDict:
return S_ERROR('Missing key "%s" in replica dictionary' % key)
if not isinstance(replicaDict[key], dict):
return S_ERROR('Wrong argument type %s, expected a dictionary' % type(replicaDict[key]))
activeDict = {'Successful': {}, 'Failed': replicaDict['Failed'].copy()}
for lfn, replicas in replicaDict['Successful'].iteritems():
if not isinstance(replicas, dict):
activeDict['Failed'][lfn] = 'Wrong replica info'
else:
activeDict['Successful'][lfn] = replicas.copy()
self.__filterActiveReplicas(activeDict)
return S_OK(activeDict)
def __filterActiveReplicas(self, replicaDict):
"""
Check a replica dictionary for active replicas
The input dict is modified, no returned value
"""
seList = set(
se for ses in replicaDict['Successful'].itervalues() for se in ses)
# Get a cache of SE statuses for long list of replicas
seStatus = dict((se, self.__checkSEStatus(se, status='Read'))
for se in seList)
for replicas in replicaDict['Successful'].itervalues():
for se in replicas.keys(): # Beware: there is a pop below
if not seStatus[se]:
replicas.pop(se)
return
def __checkSEStatus(self, se, status='Read'):
""" returns the value of a certain SE status flag (access or other) """
return StorageElement(se, vo=self.voName).status().get(status, False)
def getReplicas(self, lfns, allStatus=True, getUrl=True, diskOnly=False, preferDisk=False, active=False):
""" get replicas from catalogue and filter if requested
Warning: all filters are independent, hence active and preferDisk should be set if using forJobs
"""
catalogReplicas = {}
failed = {}
for lfnChunk in breakListIntoChunks(lfns, 1000):
res = self.fileCatalog.getReplicas(lfnChunk, allStatus=allStatus)
if res['OK']:
catalogReplicas.update(res['Value']['Successful'])
failed.update(res['Value']['Failed'])
else:
return res
if not getUrl:
for lfn in catalogReplicas:
catalogReplicas[lfn] = dict.fromkeys(catalogReplicas[lfn], True)
elif not self.useCatalogPFN:
if res['OK']:
se_lfn = {}
# We group the query to getURL by storage element to gain in speed
for lfn in catalogReplicas:
for se in catalogReplicas[lfn]:
se_lfn.setdefault(se, []).append(lfn)
for se in se_lfn:
seObj = StorageElement(se, vo=self.voName)
succPfn = seObj.getURL(se_lfn[se],
protocol=self.registrationProtocol).get('Value', {}).get('Successful', {})
for lfn in succPfn:
# catalogReplicas still points res["value"]["Successful"] so res
# will be updated
catalogReplicas[lfn][se] = succPfn[lfn]
result = {'Successful': catalogReplicas, 'Failed': failed}
if active:
self.__filterActiveReplicas(result)
if diskOnly or preferDisk:
self.__filterTapeReplicas(result, diskOnly=diskOnly)
return S_OK(result)
def getReplicasForJobs(self, lfns, allStatus=False, getUrl=True, diskOnly=False):
""" get replicas useful for jobs
"""
# Call getReplicas with no filter and enforce filters in this method
result = self.getReplicas(lfns, allStatus=allStatus, getUrl=getUrl)
if not result['OK']:
return result
replicaDict = result['Value']
# For jobs replicas must be active
self.__filterActiveReplicas(replicaDict)
# For jobs, give preference to disk replicas but not only
self.__filterTapeReplicas(replicaDict, diskOnly=diskOnly)
# don't use SEs excluded for jobs (e.g. Failover)
self.__filterReplicasForJobs(replicaDict)
return S_OK(replicaDict)
# 3
# Methods from the catalogToStorage. It would all work with the direct call to the SE, but this checks
# first if the replica is known to the catalog
def __executeIfReplicaExists(self, storageElementName, lfn, method, **kwargs):
""" a simple wrapper that allows replica querying then perform the StorageElement operation
:param self: self reference
:param str storageElementName: DIRAC SE name
:param mixed lfn: a LFN str, list of LFNs or dict with LFNs as keys
"""
log = self.log.getSubLogger('__executeIfReplicaExists')
# # default value
kwargs = kwargs if kwargs else {}
# # get replicas for lfn
res = FileCatalog(vo=self.voName).getReplicas(lfn)
if not res["OK"]:
errStr = "Completely failed to get replicas for LFNs."
log.debug(errStr, res["Message"])
return res
# # returned dict, get failed replicase
retDict = {"Failed": res["Value"]["Failed"],
"Successful": {}}
# # print errors
for lfn, reason in retDict["Failed"].iteritems():
log.error("_callReplicaSEFcn: Failed to get replicas for file.",
"%s %s" % (lfn, reason))
# # good replicas
lfnReplicas = res["Value"]["Successful"]
# # store PFN to LFN mapping
lfnList = []
for lfn, replicas in lfnReplicas.iteritems():
if storageElementName in replicas:
lfnList.append(lfn)
else:
errStr = "File hasn't got replica at supplied Storage Element."
log.error(errStr, "%s %s" % (lfn, storageElementName))
retDict["Failed"][lfn] = errStr
if 'replicaDict' not in kwargs:
kwargs['replicaDict'] = lfnReplicas
# # call StorageElement function at least
se = StorageElement(storageElementName, vo=self.voName)
fcn = getattr(se, method)
res = fcn(lfnList, **kwargs)
# # check result
if not res["OK"]:
errStr = "Failed to execute %s StorageElement method." % method
log.error(errStr, res["Message"])
return res
# # filter out failed and successful
retDict["Successful"].update(res["Value"]["Successful"])
retDict["Failed"].update(res["Value"]["Failed"])
return S_OK(retDict)
def getReplicaIsFile(self, lfn, storageElementName):
""" determine whether the supplied lfns are files at the supplied StorageElement
:param self: self reference
:param mixed lfn: LFN string, list if LFNs or dict with LFNs as keys
:param str storageElementName: DIRAC SE name
:param bool singleFile: execute for the first LFN only
"""
return self.__executeIfReplicaExists(storageElementName, lfn, "isFile")
def getReplicaSize(self, lfn, storageElementName):
""" get the size of files for the lfns at the supplied StorageElement
:param self: self reference
:param mixed lfn: LFN string, list if LFNs or dict with LFNs as keys
:param str storageElementName: DIRAC SE name
:param bool singleFile: execute for the first LFN only
"""
return self.__executeIfReplicaExists(storageElementName, lfn, "getFileSize")
def getReplicaAccessUrl(self, lfn, storageElementName, protocol=False):
""" get the access url for lfns at the supplied StorageElement
:param self: self reference
:param mixed lfn: LFN string, list if LFNs or dict with LFNs as keys
:param str storageElementName: DIRAC SE name
:param bool singleFile: execute for the first LFN only
"""
return self.__executeIfReplicaExists(storageElementName, lfn, "getURL", protocol=protocol)
def getReplicaMetadata(self, lfn, storageElementName):
""" get the file metadata for lfns at the supplied StorageElement
:param self: self reference
:param mixed lfn: LFN string, list if LFNs or dict with LFNs as keys
:param str storageElementName: DIRAC SE name
:param bool singleFile: execute for the first LFN only
"""
return self.__executeIfReplicaExists(storageElementName, lfn, "getFileMetadata")
def prestageReplica(self, lfn, storageElementName, lifetime=86400):
""" issue a prestage requests for the lfns at the supplied StorageElement
:param self: self reference
:param mixed lfn: LFN string, list if LFNs or dict with LFNs as keys
:param str storageElementName: DIRAC SE name
:param int lifetime: 24h in seconds
:param bool singleFile: execute for the first LFN only
"""
return self.__executeIfReplicaExists(storageElementName, lfn,
"prestageFile", lifetime=lifetime)
def pinReplica(self, lfn, storageElementName, lifetime=86400):
""" pin the lfns at the supplied StorageElement
:param self: self reference
:param mixed lfn: LFN string, list if LFNs or dict with LFNs as keys
:param str storageElementName: DIRAC SE name
:param int lifetime: 24h in seconds
:param bool singleFile: execute for the first LFN only
"""
return self.__executeIfReplicaExists(storageElementName, lfn,
"pinFile", lifetime=lifetime)
def releaseReplica(self, lfn, storageElementName):
""" release pins for the lfns at the supplied StorageElement
:param self: self reference
:param mixed lfn: LFN string, list if LFNs or dict with LFNs as keys
:param str storageElementName: DIRAC SE name
:param bool singleFile: execute for the first LFN only
"""
return self.__executeIfReplicaExists(storageElementName, lfn, "releaseFile")
def getReplica(self, lfn, storageElementName, localPath=False):
""" copy replicas from DIRAC SE to local directory
:param self: self reference
:param mixed lfn: LFN string, list if LFNs or dict with LFNs as keys
:param str storageElementName: DIRAC SE name
:param mixed localPath: path in the local file system, if False, os.getcwd() will be used
:param bool singleFile: execute for the first LFN only
"""
return self.__executeIfReplicaExists(storageElementName, lfn,
"getFile", localPath=localPath)
|
andresailer/DIRAC
|
DataManagementSystem/Client/DataManager.py
|
Python
|
gpl-3.0
| 75,470
|
[
"DIRAC"
] |
8c4767a42a6a12d1814081c1b957251de7fe4ce38e6206e1886bb90303cc0888
|
# Copyright (C) 2018
# Max Planck Institute for Polymer Research
#
# This file is part of ESPResSo++.
#
# ESPResSo++ 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.
#
# ESPResSo++ 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, see <http://www.gnu.org/licenses/>.
r"""
****************************************
espressopp.interaction.TabulatedSubEnsDihedral
****************************************
Calculates energies and forces for a dihedral tabulated potential.
In the tabulated potential file, angles should be in radians, and
the file should cover the range -pi radians to +pi radians (-180 to
+180 degrees).
Note that this class has only been tested for symmetric tabulated
potentials.
.. function:: espressopp.interaction.TabulatedSubEnsDihedral(itype, filename)
:param itype: The interpolation type: 1 - linear, 2 - akima spline, 3 - cubic spline
:param filename: The tabulated potential filename.
:type itype: int
:type filename: str
.. function:: espressopp.interaction.FixedQuadrupleListTabulatedSubEnsDihedral(system, fql, potential)
:param system: The Espresso++ system object.
:param fql: The FixedQuadrupleList.
:param potential: The potential.
:type system: espressopp.System
:type fql: espressopp.FixedQuadrupleList
:type potential: espressopp.interaction.Potential
.. function:: espressopp.interaction.FixedQuadrupleListTabulatedSubEnsDihedral.setPotential(potential)
:param potential: The potential object.
:type potential: espressopp.interaction.Potential
.. function:: espressopp.interaction.FixedQuadrupleListTypesTabulatedSubEnsDihedral(system, fql)
:param system: The Espresso++ system object.
:type system: espressopp.System
:param ftl: The FixedQuadrupleList list.
:type ftl: espressopp.FixedQuadrupleList
.. function:: espressopp.interaction.FixedQuadrupleListTypesTabulatedSubEnsDihedral(system, ftl)
:param system: The Espresso++ system object.
:type system: espressopp.System
:param ftl: The FixedQuadruple list.
:type ftl: espressopp.FixedQuadrupleList
.. function:: espressopp.interaction.FixedQuadrupleListTypesTabulatedSubEnsDihedral.setPotential(type1, type2, type3, type4, potential)
Defines dihedral potential for interaction between particles of types type1-type2-type3-type4.
:param type1: Type of particle 1.
:type type1: int
:param type2: Type of particle 2.
:type type2: int
:param type3: Type of particle 3.
:type type3: int
:param type4: Type of particle 4.
:type type4: int
:param potential: The potential to set up.
:type potential: espressopp.interaction.DihedralPotential
"""
from espressopp import pmi
from espressopp.esutil import *
from espressopp.interaction.DihedralPotential import *
from espressopp.interaction.Interaction import *
from _espressopp import interaction_TabulatedSubEnsDihedral, \
interaction_FixedQuadrupleListTabulatedSubEnsDihedral, \
interaction_FixedQuadrupleListTypesTabulatedSubEnsDihedral
class TabulatedSubEnsDihedralLocal(DihedralPotentialLocal, interaction_TabulatedSubEnsDihedral):
def __init__(self):
if not (pmi._PMIComm and pmi._PMIComm.isActive()) or pmi._MPIcomm.rank in pmi._PMIComm.getMPIcpugroup():
cxxinit(self, interaction_TabulatedSubEnsDihedral)
class FixedQuadrupleListTabulatedSubEnsDihedralLocal(InteractionLocal, interaction_FixedQuadrupleListTabulatedSubEnsDihedral):
def __init__(self, system, fql, potential):
if not (pmi._PMIComm and pmi._PMIComm.isActive()) or pmi._MPIcomm.rank in pmi._PMIComm.getMPIcpugroup():
cxxinit(self, interaction_FixedQuadrupleListTabulatedSubEnsDihedral, system, fql, potential)
def setPotential(self, potential):
if not (pmi._PMIComm and pmi._PMIComm.isActive()) or pmi._MPIcomm.rank in pmi._PMIComm.getMPIcpugroup():
self.cxxclass.setPotential(self, potential)
class FixedQuadrupleListTypesTabulatedSubEnsDihedralLocal(InteractionLocal, interaction_FixedQuadrupleListTypesTabulatedSubEnsDihedral):
def __init__(self, system, fql):
if pmi.workerIsActive():
cxxinit(self, interaction_FixedQuadrupleListTypesTabulatedSubEnsDihedral, system, fql)
def setPotential(self, type1, type2, type3, type4, potential):
if pmi.workerIsActive():
self.cxxclass.setPotential(self, type1, type2, type3, type4, potential)
def getPotential(self, type1, type2, type3, type4):
if pmi.workerIsActive():
return self.cxxclass.getPotential(self, type1, type2, type3, type4)
def setFixedQuadrupleList(self, fixedlist):
if pmi.workerIsActive():
self.cxxclass.setFixedQuadrupleList(self, fixedlist)
def getFixedQuadrupleList(self):
if pmi.workerIsActive():
return self.cxxclass.getFixedQuadrupleList(self)
if pmi.isController:
class TabulatedSubEnsDihedral(DihedralPotential):
'The TabulatedSubEnsDihedral potential.'
pmiproxydefs = dict(
cls = 'espressopp.interaction.TabulatedSubEnsDihedralLocal',
pmicall = ['weight_get', 'weight_set',
'alpha_get', 'alpha_set', 'targetProb_get', 'targetProb_set',
'colVarSd_get', 'colVarSd_set',
'dimension_get', 'filenames_get', 'filename_get',
'filename_set', 'addInteraction', 'colVarRefs_get',
'colVarRef_get']
)
class FixedQuadrupleListTabulatedSubEnsDihedral(Interaction, metaclass=pmi.Proxy):
pmiproxydefs = dict(
cls = 'espressopp.interaction.FixedQuadrupleListTabulatedSubEnsDihedralLocal',
pmicall = ['setPotential', 'getFixedQuadrupleList']
)
class FixedQuadrupleListTypesTabulatedSubEnsDihedral(Interaction, metaclass=pmi.Proxy):
pmiproxydefs = dict(
cls = 'espressopp.interaction.FixedQuadrupleListTypesTabulatedSubEnsDihedralLocal',
pmicall = ['setPotential','getPotential','setFixedQuadrupleList','getFixedQuadrupleList']
)
|
espressopp/espressopp
|
src/interaction/TabulatedSubEnsDihedral.py
|
Python
|
gpl-3.0
| 6,904
|
[
"ESPResSo"
] |
37b53882936376b49f227f58828ebc05d8cec78e4b9777cea1e53b45d8aa3965
|
#!/usr/bin/env python
import sys
import unittest
import vtk
from PyQt5 import QtWidgets
from peacock.ExodusViewer.plugins.MediaControlPlugin import main
from peacock.utils import Testing
class TestMediaControlPlugin(Testing.PeacockImageTestCase):
"""
Testing for MeshControl widget.
"""
qapp = QtWidgets.QApplication(sys.argv)
def setUp(self):
"""
Creates a window attached to BlockControls widget.
"""
# The file to open
self._filename = Testing.get_chigger_input('mug_blocks_out.e')
self._widget, self._window = main(size=[600,600])
self._window.onFileChanged(self._filename)
self._window.onResultOptionsChanged({'variable':'diffused'})
self._window.onWindowRequiresUpdate()
camera = vtk.vtkCamera()
camera.SetViewUp(-0.7786, 0.2277, 0.5847)
camera.SetPosition(9.2960, -0.4218, 12.6685)
camera.SetFocalPoint(0.0000, 0.0000, 0.1250)
self._window.onCameraChanged(camera)
def testInitial(self):
"""
Test the initial result.
"""
self.assertTrue(self._widget.MediaControlPlugin.BeginButton.isEnabled())
self.assertTrue(self._widget.MediaControlPlugin.BackwardButton.isEnabled())
self.assertTrue(self._widget.MediaControlPlugin.PlayButton.isEnabled())
self.assertFalse(self._widget.MediaControlPlugin.PauseButton.isVisible())
self.assertFalse(self._widget.MediaControlPlugin.ForwardButton.isEnabled())
self.assertFalse(self._widget.MediaControlPlugin.EndButton.isEnabled())
self.assertTrue(self._widget.MediaControlPlugin.TimeStepDisplay.isEnabled())
self.assertTrue(self._widget.MediaControlPlugin.TimeDisplay.isEnabled())
self.assertEqual(self._widget.MediaControlPlugin.TimeStepDisplay.text(), '20')
self.assertEqual(self._widget.MediaControlPlugin.TimeDisplay.text(), '2.0')
self.assertEqual(self._widget.MediaControlPlugin.TimeSlider.value(), 20)
self.assertImage('testInitial.png')
def testBeginButton(self):
"""
Test that the begin button works.
"""
self._widget.MediaControlPlugin.BeginButton.clicked.emit(True)
self.assertFalse(self._widget.MediaControlPlugin.BeginButton.isEnabled())
self.assertFalse(self._widget.MediaControlPlugin.BackwardButton.isEnabled())
self.assertTrue(self._widget.MediaControlPlugin.ForwardButton.isEnabled())
self.assertTrue(self._widget.MediaControlPlugin.EndButton.isEnabled())
self.assertEqual(self._widget.MediaControlPlugin.TimeStepDisplay.text(), '0')
self.assertEqual(self._widget.MediaControlPlugin.TimeDisplay.text(), '0.0')
self.assertEqual(self._widget.MediaControlPlugin.TimeSlider.value(), 0)
self.assertImage('testBeginButton.png')
def testBackwardButton(self):
"""
Test that the back button works.
"""
# Click button 10 times
for i in range(10):
self._widget.MediaControlPlugin.BackwardButton.clicked.emit(True)
self.assertTrue(self._widget.MediaControlPlugin.BeginButton.isEnabled())
self.assertTrue(self._widget.MediaControlPlugin.BackwardButton.isEnabled())
self.assertTrue(self._widget.MediaControlPlugin.ForwardButton.isEnabled())
self.assertTrue(self._widget.MediaControlPlugin.EndButton.isEnabled())
self.assertEqual(self._widget.MediaControlPlugin.TimeStepDisplay.text(), '10')
self.assertEqual(self._widget.MediaControlPlugin.TimeDisplay.text(), '1.0')
self.assertEqual(self._widget.MediaControlPlugin.TimeSlider.value(), 10)
self.assertImage('testBackwardButton.png')
def testPlayButton(self):
"""
Test that play button works.
"""
# Go to timestep 10
self._widget.MediaControlPlugin.TimeStepDisplay.setText('10')
self._widget.MediaControlPlugin.TimeStepDisplay.editingFinished.emit()
# Test the pressing the play button the pause button appears and the other controls are disabled
self._widget.MediaControlPlugin.PlayButton.clicked.emit(True)
self.assertTrue(self._widget.MediaControlPlugin.PauseButton.isVisible())
self.assertFalse(self._widget.MediaControlPlugin.PlayButton.isVisible())
self.assertFalse(self._widget.MediaControlPlugin.BeginButton.isEnabled())
self.assertFalse(self._widget.MediaControlPlugin.BackwardButton.isEnabled())
self.assertFalse(self._widget.MediaControlPlugin.ForwardButton.isEnabled())
self.assertFalse(self._widget.MediaControlPlugin.EndButton.isEnabled())
self.assertFalse(self._widget.MediaControlPlugin.TimeStepDisplay.isEnabled())
self.assertFalse(self._widget.MediaControlPlugin.TimeDisplay.isEnabled())
self.assertFalse(self._widget.MediaControlPlugin.TimeSlider.isEnabled())
# The play button uses a timer, which doesn't work in the testing framework, so fake it
for i in range(10):
self._widget.MediaControlPlugin.Timer.timeout.emit()
self.assertImage('testPlayButton.png')
def testForwardButton(self):
"""
Test that forward button is working.
"""
# Go to the beginning and advance 5 steps
self._widget.MediaControlPlugin.BeginButton.clicked.emit(True)
for i in range(5):
self._widget.MediaControlPlugin.ForwardButton.clicked.emit(True)
self.assertTrue(self._widget.MediaControlPlugin.BeginButton.isEnabled())
self.assertTrue(self._widget.MediaControlPlugin.BackwardButton.isEnabled())
self.assertTrue(self._widget.MediaControlPlugin.ForwardButton.isEnabled())
self.assertTrue(self._widget.MediaControlPlugin.EndButton.isEnabled())
self.assertEqual(self._widget.MediaControlPlugin.TimeStepDisplay.text(), '5')
self.assertEqual(self._widget.MediaControlPlugin.TimeDisplay.text(), '0.5')
self.assertEqual(self._widget.MediaControlPlugin.TimeSlider.value(), 5)
self.assertImage('testForwardButton.png')
def testEndButton(self):
"""
Test that end button is working.
"""
# Go to the beginning and advance 5 steps
self._widget.MediaControlPlugin.BeginButton.clicked.emit(True)
self._widget.MediaControlPlugin.EndButton.clicked.emit(True)
self.assertTrue(self._widget.MediaControlPlugin.BeginButton.isEnabled())
self.assertTrue(self._widget.MediaControlPlugin.BackwardButton.isEnabled())
self.assertFalse(self._widget.MediaControlPlugin.ForwardButton.isEnabled())
self.assertFalse(self._widget.MediaControlPlugin.EndButton.isEnabled())
self.assertEqual(self._widget.MediaControlPlugin.TimeStepDisplay.text(), '20')
self.assertEqual(self._widget.MediaControlPlugin.TimeDisplay.text(), '2.0')
self.assertEqual(self._widget.MediaControlPlugin.TimeSlider.value(), 20)
self.assertImage('testInitial.png')
def testTimeStepEdit(self):
"""
Test that timestep can be set manually.
"""
# Test in-bounds value (although not an exact value)
self._widget.MediaControlPlugin.TimeStepDisplay.setText('12.1')
self._widget.MediaControlPlugin.TimeStepDisplay.editingFinished.emit()
self.assertEqual(self._widget.MediaControlPlugin.TimeStepDisplay.text(), '12')
self.assertEqual(self._widget.MediaControlPlugin.TimeDisplay.text(), '1.2')
self.assertEqual(self._widget.MediaControlPlugin.TimeSlider.value(), 12)
self.assertImage('testTimeStepEdit.png')
# Test -1 timestep
self._widget.MediaControlPlugin.TimeStepDisplay.setText('-1')
self._widget.MediaControlPlugin.TimeStepDisplay.editingFinished.emit()
self.assertEqual(self._widget.MediaControlPlugin.TimeStepDisplay.text(), '20')
self.assertEqual(self._widget.MediaControlPlugin.TimeDisplay.text(), '2.0')
self.assertEqual(self._widget.MediaControlPlugin.TimeSlider.value(), 20)
# Test over range timestep
self._widget.MediaControlPlugin.TimeStepDisplay.setText('500')
self._widget.MediaControlPlugin.TimeStepDisplay.editingFinished.emit()
self.assertEqual(self._widget.MediaControlPlugin.TimeStepDisplay.text(), '20')
self.assertEqual(self._widget.MediaControlPlugin.TimeDisplay.text(), '2.0')
self.assertEqual(self._widget.MediaControlPlugin.TimeSlider.value(), 20)
# Test under range timestep
self._widget.MediaControlPlugin.TimeStepDisplay.setText('-999')
self._widget.MediaControlPlugin.TimeStepDisplay.editingFinished.emit()
self.assertEqual(self._widget.MediaControlPlugin.TimeStepDisplay.text(), '0')
self.assertEqual(self._widget.MediaControlPlugin.TimeDisplay.text(), '0.0')
self.assertEqual(self._widget.MediaControlPlugin.TimeSlider.value(), 0)
def testTimeEdit(self):
"""
Test the time edit box.
"""
# Test in-bounds value (although not an exact value)
self._widget.MediaControlPlugin.TimeDisplay.setText('0.619')
self._widget.MediaControlPlugin.TimeDisplay.editingFinished.emit()
self.assertEqual(self._widget.MediaControlPlugin.TimeStepDisplay.text(), '6')
self.assertEqual(self._widget.MediaControlPlugin.TimeDisplay.text(), '0.6')
self.assertEqual(self._widget.MediaControlPlugin.TimeSlider.value(), 6)
self.assertImage('testTimeEdit.png')
# Test over range timestep
self._widget.MediaControlPlugin.TimeDisplay.setText('500')
self._widget.MediaControlPlugin.TimeDisplay.editingFinished.emit()
self.assertEqual(self._widget.MediaControlPlugin.TimeStepDisplay.text(), '20')
self.assertEqual(self._widget.MediaControlPlugin.TimeDisplay.text(), '2.0')
self.assertEqual(self._widget.MediaControlPlugin.TimeSlider.value(), 20)
# Test under range timestep
self._widget.MediaControlPlugin.TimeDisplay.setText('-999')
self._widget.MediaControlPlugin.TimeDisplay.editingFinished.emit()
self.assertEqual(self._widget.MediaControlPlugin.TimeStepDisplay.text(), '0')
self.assertEqual(self._widget.MediaControlPlugin.TimeDisplay.text(), '0.0')
self.assertEqual(self._widget.MediaControlPlugin.TimeSlider.value(), 0)
def testTimeSlider(self):
"""
Test that time slider is working.
"""
self._widget.MediaControlPlugin.TimeSlider.setValue(4)
self._widget.MediaControlPlugin.TimeSlider.sliderReleased.emit()
self.assertEqual(self._widget.MediaControlPlugin.TimeStepDisplay.text(), '4')
self.assertEqual(self._widget.MediaControlPlugin.TimeDisplay.text(), '0.4')
self.assertEqual(self._widget.MediaControlPlugin.TimeSlider.value(), 4)
self.assertImage('testTimeSlider.png')
def testMeshOnly(self):
"""
Test that mesh only disables media controls.
"""
filename = Testing.get_chigger_input('mesh_only.e')
self._window.onFileChanged(filename)
#self.assertFalse(self._widget.MediaControlPlugin.isEnabled())
self.assertImage('testMeshOnly.png')
def testPlayDisable(self):
"""
Tests that play button disables other plugins.
"""
# Set the time so there is something to play
self._widget.MediaControlPlugin.TimeStepDisplay.setText('10')
self._widget.MediaControlPlugin.TimeStepDisplay.editingFinished.emit()
# Other plugins should still be enabled
self.assertTrue(self._widget.ClipPlugin.isEnabled())
# Test the pressing the play button the pause button appears and the other plugins are disabled
self._widget.MediaControlPlugin.PlayButton.clicked.emit(True)
self.assertFalse(self._widget.ClipPlugin.isEnabled())
# The play button uses a timer, which doesn't work in the testing framework, so fake it
for i in range(10):
self.assertFalse(self._widget.ClipPlugin.isEnabled())
self._widget.MediaControlPlugin.Timer.timeout.emit()
self.assertImage('testPlayButton.png')
# Test that stop re-enables
self._widget.MediaControlPlugin.stop()
self.assertTrue(self._widget.ClipPlugin.isEnabled())
if __name__ == '__main__':
unittest.main(module=__name__, verbosity=2)
|
Chuban/moose
|
python/peacock/tests/exodus_tab/test_MediaControlPlugin.py
|
Python
|
lgpl-2.1
| 12,428
|
[
"VTK"
] |
788f6df5426b607c68b005649189a953a1a115ac4ad6923ac08bf3460bb47782
|
import os
from visitor.Visitor import Visitor
from data.Category import Category
from data.Test import Test
class FileExplorer(Visitor):
@staticmethod
def visit(obj):
if isinstance(obj, Category):
FileExplorer.visit_category(obj)
@staticmethod
def visit_category(obj: Category):
for directory in os.listdir(obj.path):
path = os.path.join(obj.path, directory)
if os.path.isdir(os.path.join(path, "_test")):
obj.add_test(Test(path, directory, obj.depth + 1, obj))
elif os.path.isdir(path):
obj.add_category(Category(path, directory, obj.depth + 1, obj))
|
Sildra/PyTester
|
PyTester/visitor/FileExplorer.py
|
Python
|
apache-2.0
| 668
|
[
"VisIt"
] |
2c8cd944bc7cb744fc68ccc9314826bafb0af1326a290316bd72cddb655e0e1c
|
"""Mayavi/traits GUI for averaging two sets of KIT marker points."""
# Authors: Christian Brodbeck <christianbrodbeck@nyu.edu>
#
# License: BSD-3-Clause
import os
import sys
import numpy as np
from mayavi.tools.mlab_scene_model import MlabSceneModel
from pyface.api import confirm, error, FileDialog, OK, YES
from traits.api import (HasTraits, HasPrivateTraits, on_trait_change,
cached_property, Instance, Property, Array, Bool,
Button, Enum, File, Float, List, Str, ArrayOrNone)
from traitsui.api import View, Item, HGroup, VGroup, CheckListEditor
from traitsui.menu import Action, CancelButton
from ..transforms import apply_trans, rotation, translation
from ..coreg import fit_matched_points
from ..io.kit import read_mrk
from ..io._digitization import _write_dig_points
from ._viewer import PointObject
from ._backend import _get_pyface_backend
if _get_pyface_backend() == 'wx':
mrk_wildcard = [
'Supported Files (*.sqd, *.mrk, *.txt, *.pickled)|*.sqd;*.mrk;*.txt;*.pickled', # noqa:E501
'Sqd marker file (*.sqd;*.mrk)|*.sqd;*.mrk',
'Text marker file (*.txt)|*.txt',
'Pickled markers (*.pickled)|*.pickled']
mrk_out_wildcard = ["Tab separated values file (*.txt)|*.txt"]
else:
if sys.platform in ('win32', 'linux2'):
# on Windows and Ubuntu, multiple wildcards does not seem to work
mrk_wildcard = ["*.sqd", "*.mrk", "*.txt", "*.pickled"]
else:
mrk_wildcard = ["*.sqd;*.mrk;*.txt;*.pickled"]
mrk_out_wildcard = "*.txt"
out_ext = '.txt'
use_editor_v = CheckListEditor(cols=1, values=[(i, str(i)) for i in range(5)])
use_editor_h = CheckListEditor(cols=5, values=[(i, str(i)) for i in range(5)])
mrk_view_editable = View(
VGroup('file',
Item('name', show_label=False, style='readonly'),
HGroup(
Item('use', editor=use_editor_v, enabled_when="enabled",
style='custom'),
'points',
),
HGroup(Item('clear', enabled_when="can_save", show_label=False),
Item('save_as', enabled_when="can_save",
show_label=False)),
))
mrk_view_basic = View(
VGroup('file',
Item('name', show_label=False, style='readonly'),
Item('use', editor=use_editor_h, enabled_when="enabled",
style='custom'),
HGroup(Item('clear', enabled_when="can_save", show_label=False),
Item('edit', show_label=False),
Item('switch_left_right', label="Switch Left/Right",
show_label=False),
Item('reorder', show_label=False),
Item('save_as', enabled_when="can_save",
show_label=False)),
))
mrk_view_edit = View(VGroup('points'))
class ReorderDialog(HasPrivateTraits):
"""Dialog for reordering marker points."""
order = Str("0 1 2 3 4")
index = Property(List, depends_on='order')
is_ok = Property(Bool, depends_on='order')
view = View(
Item('order', label='New order (five space delimited numbers)'),
buttons=[CancelButton, Action(name='OK', enabled_when='is_ok')])
def _get_index(self):
try:
return [int(i) for i in self.order.split()]
except ValueError:
return []
def _get_is_ok(self):
return sorted(self.index) == [0, 1, 2, 3, 4]
class MarkerPoints(HasPrivateTraits):
"""Represent 5 marker points."""
points = Array(float, (5, 3))
can_save = Property(depends_on='points')
save_as = Button()
view = View(VGroup('points',
Item('save_as', enabled_when='can_save')))
@cached_property
def _get_can_save(self):
return np.any(self.points)
def _save_as_fired(self):
dlg = FileDialog(action="save as", wildcard=mrk_out_wildcard,
default_filename=self.name,
default_directory=self.dir)
dlg.open()
if dlg.return_code != OK:
return
path, ext = os.path.splitext(dlg.path)
if not path.endswith(out_ext) and len(ext) != 0:
ValueError("The extension '%s' is not supported." % ext)
path = path + out_ext
if os.path.exists(path):
answer = confirm(None, "The file %r already exists. Should it "
"be replaced?", "Overwrite File?")
if answer != YES:
return
self.save(path)
def save(self, path):
"""Save the marker points.
Parameters
----------
path : str
Path to the file to write. The kind of file to write is determined
based on the extension: '.txt' for tab separated text file,
'.pickled' for pickled file.
"""
_write_dig_points(path, self.points)
class MarkerPointSource(MarkerPoints): # noqa: D401
"""MarkerPoints subclass for source files."""
file = File(filter=mrk_wildcard, exists=True)
name = Property(Str, depends_on='file')
dir = Property(Str, depends_on='file')
use = List(list(range(5)), desc="Which points to use for the interpolated "
"marker.")
enabled = Property(Bool, depends_on=['points', 'use'])
clear = Button(desc="Clear the current marker data")
edit = Button(desc="Edit the marker coordinates manually")
switch_left_right = Button(
desc="Switch left and right marker points; this is intended to "
"correct for markers that were attached in the wrong order")
reorder = Button(desc="Change the order of the marker points")
view = mrk_view_basic
@cached_property
def _get_enabled(self):
return np.any(self.points)
@cached_property
def _get_dir(self):
if self.file:
return os.path.dirname(self.file)
@cached_property
def _get_name(self):
if self.file:
return os.path.basename(self.file)
@on_trait_change('file')
def load(self, fname):
if not fname:
self.reset_traits(['points'])
return
try:
pts = read_mrk(fname)
except Exception as err:
error(None, str(err), "Error Reading mrk")
self.reset_traits(['points'])
else:
self.points = pts
def _clear_fired(self):
self.reset_traits(['file', 'points', 'use'])
def _edit_fired(self):
self.edit_traits(view=mrk_view_edit)
def _reorder_fired(self):
dlg = ReorderDialog()
ui = dlg.edit_traits(kind='modal')
if not ui.result: # user pressed cancel
return
self.points = self.points[dlg.index]
def _switch_left_right_fired(self):
self.points = self.points[[1, 0, 2, 4, 3]]
class MarkerPointDest(MarkerPoints): # noqa: D401
"""MarkerPoints subclass that serves for derived points."""
src1 = Instance(MarkerPointSource)
src2 = Instance(MarkerPointSource)
name = Property(Str, depends_on='src1.name,src2.name')
dir = Property(Str, depends_on='src1.dir,src2.dir')
points = Property(ArrayOrNone(float, (5, 3)),
depends_on=['method', 'src1.points', 'src1.use',
'src2.points', 'src2.use'])
enabled = Property(Bool, depends_on=['points'])
method = Enum('Transform', 'Average', desc="Transform: estimate a rotation"
"/translation from mrk1 to mrk2; Average: use the average "
"of the mrk1 and mrk2 coordinates for each point.")
view = View(VGroup(Item('method', style='custom'),
Item('save_as', enabled_when='can_save',
show_label=False)))
@cached_property
def _get_dir(self):
return self.src1.dir
@cached_property
def _get_name(self):
n1 = self.src1.name
n2 = self.src2.name
if not n1:
if n2:
return n2
else:
return ''
elif not n2:
return n1
if n1 == n2:
return n1
i = 0
l1 = len(n1) - 1
l2 = len(n1) - 2
while n1[i] == n2[i]:
if i == l1:
return n1
elif i == l2:
return n2
i += 1
return n1[:i]
@cached_property
def _get_enabled(self):
return np.any(self.points)
@cached_property
def _get_points(self):
# in case only one or no source is enabled
if not (self.src1 and self.src1.enabled):
if (self.src2 and self.src2.enabled):
return self.src2.points
else:
return np.zeros((5, 3))
elif not (self.src2 and self.src2.enabled):
return self.src1.points
# Average method
if self.method == 'Average':
if len(np.union1d(self.src1.use, self.src2.use)) < 5:
error(None, "Need at least one source for each point.",
"Marker Average Error")
return np.zeros((5, 3))
pts = (self.src1.points + self.src2.points) / 2.
for i in np.setdiff1d(self.src1.use, self.src2.use):
pts[i] = self.src1.points[i]
for i in np.setdiff1d(self.src2.use, self.src1.use):
pts[i] = self.src2.points[i]
return pts
# Transform method
idx = np.intersect1d(np.array(self.src1.use),
np.array(self.src2.use), assume_unique=True)
if len(idx) < 3:
error(None, "Need at least three shared points for trans"
"formation.", "Marker Interpolation Error")
return np.zeros((5, 3))
src_pts = self.src1.points[idx]
tgt_pts = self.src2.points[idx]
est = fit_matched_points(src_pts, tgt_pts, out='params')
rot = np.array(est[:3]) / 2.
tra = np.array(est[3:]) / 2.
if len(self.src1.use) == 5:
trans = np.dot(translation(*tra), rotation(*rot))
pts = apply_trans(trans, self.src1.points)
elif len(self.src2.use) == 5:
trans = np.dot(translation(* -tra), rotation(* -rot))
pts = apply_trans(trans, self.src2.points)
else:
trans1 = np.dot(translation(*tra), rotation(*rot))
pts = apply_trans(trans1, self.src1.points)
trans2 = np.dot(translation(* -tra), rotation(* -rot))
for i in np.setdiff1d(self.src2.use, self.src1.use):
pts[i] = apply_trans(trans2, self.src2.points[i])
return pts
class CombineMarkersModel(HasPrivateTraits):
"""Combine markers model."""
mrk1_file = Instance(File)
mrk2_file = Instance(File)
mrk1 = Instance(MarkerPointSource)
mrk2 = Instance(MarkerPointSource)
mrk3 = Instance(MarkerPointDest)
clear = Button(desc="Clear the current marker data")
# stats
distance = Property(Str, depends_on=['mrk1.points', 'mrk2.points'])
def _clear_fired(self):
self.mrk1.clear = True
self.mrk2.clear = True
self.mrk3.reset_traits(['method'])
def _mrk1_default(self):
return MarkerPointSource()
def _mrk1_file_default(self):
return self.mrk1.trait('file')
def _mrk2_default(self):
return MarkerPointSource()
def _mrk2_file_default(self):
return self.mrk2.trait('file')
def _mrk3_default(self):
return MarkerPointDest(src1=self.mrk1, src2=self.mrk2)
@cached_property
def _get_distance(self):
if (self.mrk1 is None or self.mrk2 is None or
(not np.any(self.mrk1.points)) or
(not np.any(self.mrk2.points))):
return ""
ds = np.sqrt(np.sum((self.mrk1.points - self.mrk2.points) ** 2, 1))
desc = '\t'.join('%.1f mm' % (d * 1000) for d in ds)
return desc
class CombineMarkersPanel(HasTraits): # noqa: D401
"""Has two marker points sources and interpolates to a third one."""
model = Instance(CombineMarkersModel, ())
# model references for UI
mrk1 = Instance(MarkerPointSource)
mrk2 = Instance(MarkerPointSource)
mrk3 = Instance(MarkerPointDest)
distance = Str
# Visualization
scene = Instance(MlabSceneModel)
scale = Float(5e-3)
mrk1_obj = Instance(PointObject)
mrk2_obj = Instance(PointObject)
mrk3_obj = Instance(PointObject)
trans = Array()
view = View(VGroup(VGroup(Item('mrk1', style='custom'),
Item('mrk1_obj', style='custom'),
show_labels=False,
label="Source Marker 1", show_border=True),
VGroup(Item('mrk2', style='custom'),
Item('mrk2_obj', style='custom'),
show_labels=False,
label="Source Marker 2", show_border=True),
VGroup(Item('distance', style='readonly'),
label='Stats', show_border=True),
VGroup(Item('mrk3', style='custom'),
Item('mrk3_obj', style='custom'),
show_labels=False,
label="New Marker", show_border=True),
))
def _mrk1_default(self):
return self.model.mrk1
def _mrk2_default(self):
return self.model.mrk2
def _mrk3_default(self):
return self.model.mrk3
def __init__(self, *args, **kwargs): # noqa: D102
super(CombineMarkersPanel, self).__init__(*args, **kwargs)
self.model.sync_trait('distance', self, 'distance', mutual=False)
self.mrk1_obj = PointObject(scene=self.scene,
color=(0.608, 0.216, 0.216),
point_scale=self.scale)
self.model.mrk1.sync_trait(
'enabled', self.mrk1_obj, 'visible', mutual=False)
self.mrk2_obj = PointObject(scene=self.scene,
color=(0.216, 0.608, 0.216),
point_scale=self.scale)
self.model.mrk2.sync_trait(
'enabled', self.mrk2_obj, 'visible', mutual=False)
self.mrk3_obj = PointObject(scene=self.scene,
color=(0.588, 0.784, 1.),
point_scale=self.scale)
self.model.mrk3.sync_trait(
'enabled', self.mrk3_obj, 'visible', mutual=False)
@on_trait_change('model:mrk1:points,trans')
def _update_mrk1(self):
if self.mrk1_obj is not None:
self.mrk1_obj.points = apply_trans(self.trans,
self.model.mrk1.points)
@on_trait_change('model:mrk2:points,trans')
def _update_mrk2(self):
if self.mrk2_obj is not None:
self.mrk2_obj.points = apply_trans(self.trans,
self.model.mrk2.points)
@on_trait_change('model:mrk3:points,trans')
def _update_mrk3(self):
if self.mrk3_obj is not None:
self.mrk3_obj.points = apply_trans(self.trans,
self.model.mrk3.points)
|
pravsripad/mne-python
|
mne/gui/_marker_gui.py
|
Python
|
bsd-3-clause
| 15,406
|
[
"Mayavi"
] |
8d6a3a04cbeb5eec7d88e04ec5a8eeb98b2a5f939793e206dc7fb6f993ab78cf
|
# Copyright 2014-2018 The PySCF Developers. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from __future__ import print_function, division
import os,unittest,numpy as np
from pyscf.nao import bse_iter
class KnowValues(unittest.TestCase):
def test_bse_iter_nonin(self):
""" Compute polarization with LDA TDDFT """
from timeit import default_timer as timer
dname = os.path.dirname(os.path.abspath(__file__))
bse = bse_iter(label='water', cd=dname, iter_broadening=1e-2, xc_code='RPA', verbosity=0)
omegas = np.linspace(0.0,2.0,500)+1j*bse.eps
pxx = np.zeros(len(omegas))
for iw,omega in enumerate(omegas):
for ixyz in range(1):
vab = bse.apply_l0(bse.dip_ab[ixyz], omega)
pxx[iw] = pxx[iw] - (vab.imag*bse.dip_ab[ixyz].reshape(-1)).sum()
data = np.array([omegas.real*27.2114, pxx])
np.savetxt('water.bse_iter_rpa.omega.nonin.pxx.txt', data.T, fmt=['%f','%f'])
data_ref = np.loadtxt(dname+'/water.bse_iter_rpa.omega.nonin.pxx.txt-ref')
#print(' bse.l0_ncalls ', bse.l0_ncalls)
self.assertTrue(np.allclose(data_ref,data.T, rtol=1.0, atol=1e-05))
if __name__ == "__main__": unittest.main()
|
gkc1000/pyscf
|
pyscf/nao/test/test_0035_bse_nonin_nao.py
|
Python
|
apache-2.0
| 1,705
|
[
"PySCF"
] |
fe9f333ab73facd5353705c490bdbc058094055c4b2879f15cbd4b10885ee615
|
'''WeenieBot's Setup!'''
import json
import subprocess
import time
import sys
with open("settings.json", 'w+') as outfile:
outfile.write(json.dumps({}))
with open("settings.json", "r") as infile:
settings = json.loads(infile.read())
print('Welcome to WeenieBot\'s setup!\nIf you need any help just refer to the in-depth setup guide at:\nhttps://github.com/Beefywhale/WeenieBot/wiki/WeenieBot\'s-In-depth-setup\n')
install_depend = input('Install Python dependencies? [Y/N]')
if install_depend.lower() in ['yes', 'y']:
sys.stdout.write('Installing Python packages')
sys.stdout.flush()
time.sleep(0.5)
sys.stdout.write('.')
sys.stdout.flush()
time.sleep(0.5)
sys.stdout.write('.')
sys.stdout.flush()
time.sleep(0.5)
sys.stdout.write('.')
sys.stdout.flush()
time.sleep(0.2)
subprocess.run("python -m pip install -U -r requirements.txt", shell=True, check=True)
else:
print('Not installing dependencies!')
token = input('\nBot\'s Token: ')
settings['token'] = str(token)
with open("settings.json", 'w+') as outfile:
outfile.write(json.dumps(settings))
client_id = input('\nClient ID: ')
print('Visit this link to add the bot to your server!\nhttps://discordapp.com/oauth2/authorize?client_id={}&scope=bot&permissions=0'.format(client_id))
print('\n\nThats all! bot setup is complete!')
|
Beefywhale/WeenieBot
|
setup.py
|
Python
|
mit
| 1,308
|
[
"VisIt"
] |
4bccb143edf55d47dcfaaa3043100b8d0afe0ae2852761f64ca80a3cff0f9485
|
# -*- coding: utf-8 -*-
"""Various text used throughout the website, e.g. status messages, errors, etc.
"""
# Status Messages
#################
# NOTE: in status messages, newlines are not preserved, so triple-quotes strings
# are ok
# Status message shown at settings page on first login
# (upon clicking primary email confirmation link)
WELCOME_MESSAGE = ('Welcome to the OSF! Please update the following settings. If you need assistance '
'in getting started, please visit the <a href="/getting-started/">Getting Started</a> page.')
REGISTRATION_SUCCESS = '''Registration successful. Please check {email} to confirm your email address.'''
# Shown if registration is turned off in website.settings
REGISTRATION_UNAVAILABLE = 'Registration currently unavailable.'
ALREADY_REGISTERED = '''The email <em>{email}</em> has already been registered.'''
# Shown if user tries to login with an email that is not yet confirmed
UNCONFIRMED = ('This login email has been registered but not confirmed. Please check your email (and spam folder).'
' <a href="/resend/">Click here</a> to resend your confirmation email.')
# Shown if the user's account is disabled
DISABLED = '''
Log-in failed: Deactivated account.
'''
# Shown on incorrect password attempt
LOGIN_FAILED = '''
Log-in failed. Please try again or reset your password.
'''
# Shown if incorrect 2fa verification is entered at login
TWO_FACTOR_FAILED = '''
You entered an incorrect verification code. Please try again.
'''
# Shown at login page if user tries to access a resource that requires auth
MUST_LOGIN = '''
You must log in to access this resource.
'''
# Shown on logout
LOGOUT = '''
You have successfully logged out.
'''
EMAIL_NOT_FOUND = '''
<strong>{email}</strong> was not found in our records.
'''
# Shown after an unregistered user claims an account and is redirected to the
# settings page
CLAIMED_CONTRIBUTOR = ('<strong>Welcome to the OSF!</strong> Edit your display name below and then check your '
'<a href="/dashboard/">dashboard</a> to see projects to which you have been added as a '
'contributor by someone else.')
# Error Pages
# ###########
# Shown at error page if an expired/revokes email confirmation link is clicked
LINK_EXPIRED = 'This confirmation link has expired. Please <a href="/login/">log in</a> to continue.'
# Node Actions
BEFORE_REGISTER_HAS_POINTERS = (
'This {category} contains links to other projects. Links will be copied '
'into your registration, but the projects that they link to will not be '
'registered. If you wish to register the linked projects, you must fork '
'them from the original project before registering.'
)
BEFORE_FORK_HAS_POINTERS = (
'This {category} contains links to other projects. Links will be copied '
'into your fork, but the projects that they link to will not be forked. '
'If you wish to fork the linked projects, they need to be forked from the '
'original project.'
)
REGISTRATION_INFO = '''
<p>Registration creates a frozen version of the project that can never be edited
or deleted. You can register your project by selecting a registration form, entering
information about your project, and then confirming. You will be
able to continue editing the original project, however, and the frozen version with
time stamps will always be linked to the original.</p>
<ul>
<li>A registration takes the same privacy settings as the project, e.g. a public project results in a public registration.</li>
<li>Before initiating a registration, make sure that the project is in the
state that you wish to freeze. Consider turning links into forks.</li>
<li>Start by selecting a registration form from the list below. You can
hit your browser's back button if the selected form is not
appropriate for your use.</li>
</ul>
'''
BEFORE_REGISTRATION_INFO = '''
Registration cannot be undone, and the archived content and files cannot be
deleted after registration. Please be sure the project is complete and
comprehensive for what you wish to register.
'''
# Nodes: forking, templating, linking
LINK_ACTION = 'Link to this Project'
LINK_DESCRIPTION = """
<p>Linking to this project will reference it in another project, without
creating a copy. The link will always point to the most up-to-date version.</p>
"""
TEMPLATE_ACTION = 'Copy Project Structure'
TEMPLATE_DESCRIPTION = """
<p>This option will create a new project, using this project as a template.
The new project will be structured in the same way, but contain no data.</p>
"""
FORK_ACTION = 'Fork this Project'
FORK_DESCRIPTION = """
<p>Fork this project if you plan to build upon it in your own work.
The new project will be an exact duplicate of this project's current state,
with you as the only contributor.</p>
"""
TEMPLATE_DROPDOWN_HELP = """Start typing to search. Selecting project as
template will duplicate its structure in the new project without importing the
content of that project."""
TEMPLATED_FROM_PREFIX = "Templated from "
# MFR Error handling
ERROR_PREFIX = "Unable to render. <a href='?action=download'>Download</a> file to view it."
SUPPORT = "Contact support@osf.io for further assistance."
# Custom Error Messages w/ support
STATA_VERSION_ERROR = 'Version of given Stata file is not 104, 105, 108, 113 (Stata 8/9), 114 (Stata 10/11) or 115 (Stata 12)<p>{0}</p>'.format(SUPPORT)
BLANK_OR_CORRUPT_TABLE_ERROR = 'Is this a valid instance of this file type?<p>{0}</p>'.format(SUPPORT)
|
kushG/osf.io
|
website/language.py
|
Python
|
apache-2.0
| 5,549
|
[
"VisIt"
] |
24720641d45b1a06683f42bc09aa1dd9b8d2f59ff178b79f305116de9fc2479c
|
import os
import sys
import time
import platform
from math import log
import numpy as np
import ase
from ase.units import Bohr, Hartree
from ase.data import chemical_symbols
from ase.version import version as ase_version
import gpaw
import _gpaw
from gpaw.version import version
from gpaw.utilities import devnull
from gpaw.utilities.memory import maxrss
from gpaw import dry_run, extra_parameters
def initialize_text_stream(txt, rank, old_txt=None):
"""Set the stream for text output.
If `txt` is not a stream-object, then it must be one of:
* None: Throw output away.
* '-': Use standard-output (``sys.stdout``).
* A filename: Open a new file.
"""
firsttime = (old_txt is None)
if txt is None or rank != 0:
return devnull, firsttime
elif txt == '-':
return sys.stdout, firsttime
elif isinstance(txt, str):
if isinstance(old_txt, file) and old_txt.name == txt:
return old_txt, firsttime
else:
if not firsttime:
# We want every file to start with the logo, so
# that the ase.io.read() function will recognize
# it as a GPAW text file.
firsttime = True
# Open the file line buffered.
return open(txt, 'w', 1), firsttime
else:
assert hasattr(txt, 'write'), 'Not a stream object!'
return txt, firsttime
return old_txt, firsttime
class PAWTextOutput:
"""Class for handling all text output."""
def __init__(self):
self.txt = None
def set_text(self, txt, verbose=True):
"""Set the stream for text output.
If `txt` is not a stream-object, then it must be one of:
* None: Throw output away.
* '-': Use standard-output (``sys.stdout``).
* A filename: Open a new file.
"""
self.verbose = verbose
self.txt, firsttime = initialize_text_stream(txt, self.wfs.world.rank,
self.txt)
if firsttime:
self.print_logo()
def text(self, *args, **kwargs):
self.txt.write(kwargs.get('sep', ' ').join([str(arg)
for arg in args]) +
kwargs.get('end', '\n'))
def print_logo(self):
self.text()
self.text(' ___ ___ ___ _ _ _ ')
self.text(' | | |_ | | | | ')
self.text(' | | | | | . | | | | ')
self.text(' |__ | _|___|_____| ', version)
self.text(' |___|_| ')
self.text()
uname = platform.uname()
self.text('User: ', os.getenv('USER', '???') + '@' + uname[1])
self.text('Date: ', time.asctime())
self.text('Arch: ', uname[4])
self.text('Pid: ', os.getpid())
self.text('gpaw: ', os.path.dirname(gpaw.__file__))
# Find C-code:
c = getattr(_gpaw, '__file__', None)
if not c:
c = sys.executable
self.text('_gpaw:', os.path.normpath(c))
self.text('ase: %s (version %s)' %
(os.path.dirname(ase.__file__), ase_version))
self.text('numpy: %s (version %s)' %
(os.path.dirname(np.__file__), np.version.version))
try:
import scipy as sp
self.text('scipy: %s (version %s)' %
(os.path.dirname(sp.__file__), sp.version.version))
# Explicitly deleting SciPy seems to remove garbage collection
# problem of unknown cause
del sp
except ImportError:
self.text('scipy: Not available')
self.text('units: Angstrom and eV')
self.text('cores:', self.wfs.world.size)
if gpaw.debug:
self.text('DEBUG MODE')
if extra_parameters:
self.text('Extra parameters:', extra_parameters)
def print_cell_and_parameters(self):
self.plot_atoms(self.atoms)
self.print_unit_cell(self.atoms.get_positions() / Bohr)
self.print_parameters()
def print_unit_cell(self, pos_ac):
self.text()
self.text('Unit Cell:')
self.text(' Periodic X Y Z' +
' Points Spacing')
self.text(' -----------------------------------------------' +
'---------------------')
gd = self.wfs.gd
h_c = gd.get_grid_spacings()
pbc_c = self.atoms.pbc
for c in range(3):
self.text(' %d. axis: %s %10.6f %10.6f %10.6f %3d %8.4f'
% ((c + 1, ['no ', 'yes'][int(pbc_c[c])]) +
tuple(Bohr * gd.cell_cv[c]) +
(gd.N_c[c], Bohr * h_c[c])))
self.text()
def print_positions(self):
t = self.text
t()
t('Positions:')
symbols = self.atoms.get_chemical_symbols()
for a, pos_c in enumerate(self.atoms.get_positions()):
symbol = symbols[a]
t('%3d %-2s %9.4f %9.4f %9.4f' % ((a, symbol) + tuple(pos_c)))
t()
def print_parameters(self):
t = self.text
p = self.input_parameters
# Write PAW setup information in order of appearance:
ids = set()
for id in self.wfs.setups.id_a:
if id in ids:
continue
ids.add(id)
setup = self.wfs.setups.setups[id]
setup.print_info(self.text)
basis_descr = setup.get_basis_description()
t(basis_descr)
t()
t('Using the %s Exchange-Correlation Functional.'
% self.hamiltonian.xc.name)
if self.wfs.nspins == 2:
t('Spin-Polarized Calculation.')
t('Magnetic Moment: (%.6f, %.6f, %.6f)' %
tuple(self.density.magmom_av.sum(0)), end='')
if self.occupations.fixmagmom:
t('(fixed)')
else:
t()
else:
t('Spin-Paired Calculation')
t('Total Charge: %.6f' % p['charge'])
t('Fermi Temperature: %.6f' % (self.occupations.width * Hartree))
self.wfs.summary(self.txt)
if p.mode == 'lcao':
eigensolver = 'lcao (direct)'
else:
eigensolver = self.wfs.eigensolver
t('Eigensolver: %s' % eigensolver)
self.hamiltonian.summary(self.txt)
t('Reference Energy: %.6f' % (self.wfs.setups.Eref * Hartree))
t()
nibzkpts = self.wfs.nibzkpts
# Print parallelization details
t('Total number of cores used: %d' % self.wfs.world.size)
if self.wfs.kpt_comm.size > 1: # kpt/spin parallization
if self.wfs.nspins == 2 and nibzkpts == 1:
t('Parallelization over spin')
elif self.wfs.nspins == 2:
t('Parallelization over k-points and spin: %d' %
self.wfs.kpt_comm.size)
else:
t('Parallelization over k-points: %d' %
self.wfs.kpt_comm.size)
if self.wfs.gd.comm.size > 1: # domain parallelization
t('Domain Decomposition: %d x %d x %d' %
tuple(self.wfs.gd.parsize_c))
if self.wfs.bd.comm.size > 1: # band parallelization
t('Parallelization over states: %d'
% self.wfs.bd.comm.size)
if p['mode'] == 'lcao':
general_diagonalizer_layout = self.wfs.ksl.get_description()
t('Diagonalizer layout: ' + general_diagonalizer_layout)
elif p['mode'] == 'fd':
if self.wfs.diagksl.buffer_size is not None:
t('MatrixOperator buffer_size (KiB): %d'
% self.wfs.diagksl.buffer_size)
else:
t('MatrixOperator buffer_size: default value or \n' +
' %s see value of nblock in input file' % (26 * ' '))
diagonalizer_layout = self.wfs.diagksl.get_description()
t('Diagonalizer layout: ' + diagonalizer_layout)
orthonormalizer_layout = self.wfs.orthoksl.get_description()
t('Orthonormalizer layout: ' + orthonormalizer_layout)
t()
self.wfs.symmetry.print_symmetries(t)
t(self.wfs.kd.description)
t(('%d k-point%s in the Irreducible Part of the Brillouin Zone') %
(nibzkpts, ' s'[1:nibzkpts]))
if nibzkpts < 100:
t()
t(' k-points in crystal coordinates weights')
for k in range(nibzkpts):
t(' %12.8f %12.8f %12.8f %10.6f' %
(self.wfs.kd.ibzk_kc[k][0], self.wfs.kd.ibzk_kc[k][1],
self.wfs.kd.ibzk_kc[k][2], self.wfs.kd.weight_k[k]))
t()
if self.scf.fixdensity > self.scf.maxiter:
t('Fixing the initial density')
else:
mixer = self.density.mixer
t('Mixer Type: %s' % mixer.__class__.__name__)
t('Linear Mixing Parameter: %g' % mixer.beta)
t('Mixing with %d Old Densities' % mixer.nmaxold)
if mixer.weight == 1:
t('No Damping of Long Wave Oscillations')
else:
t('Damping of Long Wave Oscillations: %g' % mixer.weight)
cc = p['convergence']
t()
t('Convergence Criteria:')
t('Total Energy Change: %g eV / electron' %
(cc['energy']))
t('Integral of Absolute Density Change: %g electrons' %
cc['density'])
t('Integral of Absolute Eigenstate Change: %g eV^2' %
cc['eigenstates'])
t('Number of Atoms: %d' % len(self.wfs.setups))
t('Number of Atomic Orbitals: %d' % self.wfs.setups.nao)
if self.nbands_parallelization_adjustment != 0:
t('Adjusting Number of Bands by %+d to Match Parallelization'
% self.nbands_parallelization_adjustment)
t('Number of Bands in Calculation: %i' % self.wfs.bd.nbands)
t('Bands to Converge: ', end='')
if cc['bands'] == 'occupied':
t('Occupied States Only')
elif cc['bands'] == 'all':
t('All')
else:
t('%d Lowest Bands' % cc['bands'])
t('Number of Valence Electrons: %g'
% (self.wfs.setups.nvalence - p.charge))
def print_converged(self, iter):
t = self.text
t('------------------------------------')
t('Converged After %d Iterations.' % iter)
t()
self.print_all_information()
def print_all_information(self):
t = self.text
if len(self.atoms) == 1:
t('Energy Contributions Relative to Reference Atom:', end='')
else:
t('Energy Contributions Relative to Reference Atoms:', end='')
t('(reference = %.6f)' % (self.wfs.setups.Eref * Hartree))
t('-------------------------')
energies = [('Kinetic: ', self.hamiltonian.Ekin),
('Potential: ', self.hamiltonian.Epot),
('External: ', self.hamiltonian.Eext),
('XC: ', self.hamiltonian.Exc),
('Entropy (-ST):', -self.hamiltonian.S),
('Local: ', self.hamiltonian.Ebar)]
for name, e in energies:
t('%-14s %+11.6f' % (name, Hartree * e))
t('-------------------------')
t('Free Energy: %+11.6f' % (Hartree * self.hamiltonian.Etot))
t('Zero Kelvin: %+11.6f' % (Hartree * (self.hamiltonian.Etot +
0.5 * self.hamiltonian.S)))
t()
self.occupations.print_fermi_level(self.txt)
self.print_eigenvalues()
self.hamiltonian.xc.summary(self.txt)
t()
try:
dipole = self.get_dipole_moment()
except NotImplementedError:
pass
else:
if self.density.charge == 0:
t('Dipole Moment: %s' % dipole)
else:
t('Center of Charge: %s' % (dipole / abs(self.density.charge)))
try:
c = self.hamiltonian.poisson.corrector.c
epsF = self.occupations.fermilevel
except AttributeError:
pass
else:
wf_a = -epsF * Hartree - dipole[c]
wf_b = -epsF * Hartree + dipole[c]
t('Dipole-corrected work function: %f, %f' % (wf_a, wf_b))
if self.wfs.nspins == 2:
t()
magmom = self.occupations.magmom
t('Total Magnetic Moment: %f' % magmom)
try:
# XXX This doesn't always work, HGH, SIC, ...
sc = self.density.get_spin_contamination(self.atoms,
int(magmom < 0))
t('Spin contamination: %f electrons' % sc)
except (TypeError, AttributeError):
pass
t('Local Magnetic Moments:')
for a, mom in enumerate(self.get_magnetic_moments()):
t(a, mom)
t()
elif not self.wfs.collinear:
self.txt.write('Local Magnetic Moments:\n')
for a, mom_v in enumerate(self.get_magnetic_moments()):
self.txt.write('%4d (%.3f, %.3f, %.3f)\n' %
(a, mom_v[0], mom_v[1], mom_v[2]))
def print_iteration(self, iter):
# Output from each iteration:
t = self.text
nvalence = self.wfs.setups.nvalence - self.input_parameters.charge
if nvalence > 0:
eigerr = self.scf.eigenstates_error * Hartree**2 / nvalence
else:
eigerr = 0.0
if self.verbose != 0:
T = time.localtime()
t()
t('------------------------------------')
t('iter: %d %d:%02d:%02d' % (iter, T[3], T[4], T[5]))
t()
t('Poisson Solver Converged in %d Iterations' %
self.hamiltonian.npoisson)
t('Fermi Level Found in %d Iterations' % self.occupations.niter)
t('Error in Wave Functions: %.13f' % eigerr)
t()
self.print_all_information()
else:
if iter == 1:
header = """\
log10-error: Total Iterations:
Time WFS Density Energy Fermi Poisson"""
if self.wfs.nspins == 2:
header += ' MagMom'
t(header)
T = time.localtime()
if eigerr == 0.0:
eigerr = ''
else:
eigerr = '%+.2f' % (log(eigerr) / log(10))
denserr = self.density.mixer.get_charge_sloshing()
if denserr is None or denserr == 0 or nvalence == 0:
denserr = ''
else:
denserr = '%+.2f' % (log(denserr / nvalence) / log(10))
niterocc = self.occupations.niter
if niterocc == -1:
niterocc = ''
else:
niterocc = '%d' % niterocc
if self.hamiltonian.npoisson == 0:
niterpoisson = ''
else:
niterpoisson = str(self.hamiltonian.npoisson)
t('iter: %3d %02d:%02d:%02d %6s %6s %11.6f %-5s %-7s' %
(iter,
T[3], T[4], T[5],
eigerr,
denserr,
Hartree * (self.hamiltonian.Etot + 0.5 * self.hamiltonian.S),
niterocc,
niterpoisson), end='')
if self.wfs.nspins == 2:
t(' %+.4f' % self.occupations.magmom)
else:
t()
self.txt.flush()
def print_forces(self):
if self.forces.F_av is None:
return
t = self.text
t()
t('Forces in eV/Ang:')
c = Hartree / Bohr
symbols = self.atoms.get_chemical_symbols()
for a, symbol in enumerate(symbols):
t('%3d %-2s %10.5f %10.5f %10.5f' %
((a, symbol) + tuple(self.forces.F_av[a] * c)))
def print_eigenvalues(self):
"""Print eigenvalues and occupation numbers."""
self.text(eigenvalue_string(self))
def plot_atoms(self, atoms):
self.text(plot(atoms))
def __del__(self):
"""Destructor: Write timing output before closing."""
if not hasattr(self, 'txt') or self.txt is None:
return
if not dry_run:
mr = maxrss()
if mr > 0:
if mr < 1024.0**3:
self.text('Memory usage: %.2f MB' % (mr / 1024.0**2))
else:
self.text('Memory usage: %.2f GB' % (mr / 1024.0**3))
self.timer.write(self.txt)
def eigenvalue_string(paw, comment=None):
"""
Write eigenvalues and occupation numbers into a string.
The parameter comment can be used to comment out non-numers,
for example to escape it for gnuplot.
"""
if not comment:
comment = ' '
if len(paw.wfs.ibzk_kc) > 1:
# not implemented yet:
return ''
s = ''
if paw.wfs.nspins == 1:
s += comment + 'Band Eigenvalues Occupancy\n'
eps_n = paw.get_eigenvalues(kpt=0, spin=0)
f_n = paw.get_occupation_numbers(kpt=0, spin=0)
if paw.wfs.world.rank == 0:
for n in range(paw.wfs.bd.nbands):
s += ('%4d %10.5f %10.5f\n' % (n, eps_n[n], f_n[n]))
else:
s += comment + ' Up Down\n'
s += comment + 'Band Eigenvalues Occupancy Eigenvalues Occupancy\n'
epsa_n = paw.get_eigenvalues(kpt=0, spin=0, broadcast=False)
epsb_n = paw.get_eigenvalues(kpt=0, spin=1, broadcast=False)
fa_n = paw.get_occupation_numbers(kpt=0, spin=0, broadcast=False)
fb_n = paw.get_occupation_numbers(kpt=0, spin=1, broadcast=False)
if paw.wfs.world.rank == 0:
for n in range(paw.wfs.bd.nbands):
s += (' %4d %11.5f %9.5f %11.5f %9.5f\n' %
(n, epsa_n[n], fa_n[n], epsb_n[n], fb_n[n]))
return s
def plot(atoms):
"""Ascii-art plot of the atoms."""
## y
## |
## .-- x
## /
## z
cell_cv = atoms.get_cell()
if (cell_cv - np.diag(cell_cv.diagonal())).any():
atoms = atoms.copy()
atoms.cell = [1, 1, 1]
atoms.center(vacuum=2.0)
cell_cv = atoms.get_cell()
plot_box = False
else:
plot_box = True
cell = np.diagonal(cell_cv) / Bohr
positions = atoms.get_positions() / Bohr
numbers = atoms.get_atomic_numbers()
s = 1.3
nx, ny, nz = n = (s * cell * (1.0, 0.25, 0.5) + 0.5).astype(int)
sx, sy, sz = n / cell
grid = Grid(nx + ny + 4, nz + ny + 1)
positions = (positions % cell + cell) % cell
ij = np.dot(positions, [(sx, 0), (sy, sy), (0, sz)])
ij = np.around(ij).astype(int)
for a, Z in enumerate(numbers):
symbol = chemical_symbols[Z]
i, j = ij[a]
depth = positions[a, 1]
for n, c in enumerate(symbol):
grid.put(c, i + n + 1, j, depth)
if plot_box:
k = 0
for i, j in [(1, 0), (1 + nx, 0)]:
grid.put('*', i, j)
grid.put('.', i + ny, j + ny)
if k == 0:
grid.put('*', i, j + nz)
grid.put('.', i + ny, j + nz + ny)
for y in range(1, ny):
grid.put('/', i + y, j + y, y / sy)
if k == 0:
grid.put('/', i + y, j + y + nz, y / sy)
for z in range(1, nz):
if k == 0:
grid.put('|', i, j + z)
grid.put('|', i + ny, j + z + ny)
k = 1
for i, j in [(1, 0), (1, nz)]:
for x in range(1, nx):
if k == 1:
grid.put('-', i + x, j)
grid.put('-', i + x + ny, j + ny)
k = 0
return '\n'.join([''.join([chr(x) for x in line])
for line in np.transpose(grid.grid)[::-1]])
class Grid:
def __init__(self, i, j):
self.grid = np.zeros((i, j), np.int8)
self.grid[:] = ord(' ')
self.depth = np.zeros((i, j))
self.depth[:] = 1e10
def put(self, c, i, j, depth=1e9):
if depth < self.depth[i, j]:
self.grid[i, j] = ord(c)
self.depth[i, j] = depth
|
robwarm/gpaw-symm
|
gpaw/output.py
|
Python
|
gpl-3.0
| 20,573
|
[
"ASE",
"CRYSTAL",
"GPAW"
] |
4ff740f0a79bf92dab2570e32c06f2476739311d3d79db41d6dbfdc795f0d204
|
#
# Copyright 2018 Analytics Zoo Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
from unittest import TestCase
import numpy as np
import pytest
import mxnet as mx
from zoo.orca.learn.mxnet import Estimator, create_config
np.random.seed(1337) # for reproducibility
def get_train_data_iter(config, kv):
train_data = np.random.rand(200, 30)
train_label = np.random.randint(0, 10, (200,))
train = mx.io.NDArrayIter({"input": train_data}, {"label": train_label},
batch_size=config["batch_size"], shuffle=True)
return train
def get_test_data_iter(config, kv):
test_data = np.random.rand(80, 30)
test_label = np.random.randint(0, 10, (80,))
test = mx.io.NDArrayIter({"input": test_data}, {"label": test_label},
batch_size=config["batch_size"], shuffle=True)
return test
def get_model(config):
input_data = mx.symbol.Variable('input')
y_true = mx.symbol.Variable('label')
fc1 = mx.symbol.FullyConnected(data=input_data, num_hidden=20, name='fc1')
fc2 = mx.symbol.FullyConnected(data=fc1, num_hidden=10, name='fc2')
output = mx.symbol.SoftmaxOutput(data=fc2, label=y_true, name='output')
mod = mx.mod.Module(symbol=output,
data_names=['input'],
label_names=['label'],
context=mx.cpu())
return mod
def get_metrics(config):
return 'accuracy'
class TestMXNetSymbol(TestCase):
def test_symbol(self):
config = create_config(log_interval=2, seed=42)
estimator = Estimator.from_mxnet(config=config, model_creator=get_model,
validation_metrics_creator=get_metrics,
eval_metrics_creator=get_metrics)
estimator.fit(get_train_data_iter, validation_data=get_test_data_iter,
epochs=2, batch_size=16)
estimator.shutdown()
if __name__ == "__main__":
pytest.main([__file__])
|
intel-analytics/analytics-zoo
|
pyzoo/test/zoo/orca/learn/ray/mxnet/test_mxnet_symbol.py
|
Python
|
apache-2.0
| 2,514
|
[
"ORCA"
] |
504c81493161dbc2b7085985e7c5b1030b5204a6af110cd4582d5e2081ed890d
|
#!/galaxy/home/mgehrin/hiclib/bin/python
"""
Read a maf file and print the regions covered to a set of bed files (one for
each sequence source referenced in the maf). Only blocks with a positive
percent identity are written out.
TODO: Can this be generalized to be made more useful?
usage: %prog bed_outfile_prefix < maf
"""
from __future__ import division
import psyco_full
import bx.align.maf
import sys
def block_pid( comp1, comp2 ):
match = 0
total = 0
t1 = comp1.text.lower()
t2 = comp2.text.lower()
for i in range( 0, len(t1) ):
a, b = t1[i], t2[i]
if a == '-' or b == '-':
continue
elif a == b:
match += 1
total += 1
if total == 0: return None
return ( match / total )
def main():
out_prefix = sys.argv[1]
print out_prefix
out_files = dict()
for block in bx.align.maf.Reader( sys.stdin ):
ref_comp = block.components[0]
ref_chrom = ref_comp.src.split('.')[1]
for comp in block.components[1:]:
comp_species, comp_chrom = comp.src.split('.')[:2]
if comp_species not in out_files:
f = open( "%s%s.bed" % ( out_prefix, comp_species ), "w" )
out_files[comp_species] = f
pid = block_pid( ref_comp, comp )
if pid:
out_files[comp_species].write( "%s\t%d\t%d\t%s:%d-%d,%s\t%f\n" %
( ref_chrom, ref_comp.forward_strand_start, ref_comp.forward_strand_end, \
comp_chrom, comp.start, comp.end, comp.strand, pid ) )
for f in out_files.values():
f.close()
if __name__ == "__main__": main()
|
bxlab/HiFive_Paper
|
Scripts/HiCLib/bx-python-0.7.1/build/scripts-2.7/maf_covered_regions.py
|
Python
|
bsd-3-clause
| 1,700
|
[
"Galaxy"
] |
53dcf83ffb37ba8d344852c2533b70b8cfc17db96a71e6517fea9f2314b98a91
|
#!/usr/bin/python
import argparse, sys, re, random, os, gzip
from multiprocessing import Pool, Lock, cpu_count, Queue
from subprocess import Popen, PIPE
import SimulationBasics
from VCFBasics import VCF
from SequenceBasics import read_fasta_into_hash
from TranscriptomeBasics import Transcriptome
from GenePredBasics import GenePredEntry
from RangeBasics import Bed,Locus,Loci
from FASTQPrecomputedProfileBasics import default_illumina_1_9 as default_illumina, default_pacbio_ccs95, default_pacbio_subreads
import FASTQBasics
write_lock = Lock()
gcounter = 0
shand1 = None #handles for writing out short reads
shand2 = None
emissions_reports = []
def main():
parser = argparse.ArgumentParser(description="Create a simulated RNA-seq dataset")
group0 = parser.add_mutually_exclusive_group(required=True)
group0.add_argument('--load_biallelic_transcriptome',help="SERIALIZED BIALLELIC TRANSCRIOTOME EMITTER FILE to load up and use instead of all other file inputs")
group0.add_argument('--inputs',nargs=3,help="<reference_genome> <phased_VCF> <transcripts_genepred>")
#parser.add_argument('reference_genome',help="The reference genome.")
#parser.add_argument('phased_VCF',help="A phased VCF file. If you are simulating the genomes that step can make on of these for you.")
#parser.add_argument('transcripts_genepred',help="A genepred file describing the transcripts. Each transcript name must be unique.")
group = parser.add_mutually_exclusive_group()
group.add_argument('--uniform_expression',action='store_true',help="Uniform distribution of transcript expression")
group.add_argument('--isoform_expression',help="The transcript expression in TSV format <Transcript name> tab <Expression>")
group.add_argument('--cufflinks_isoform_expression',help="The expression of the isoforms or - for a uniform distribution of transcript expression")
group2 = parser.add_mutually_exclusive_group()
group2.add_argument('--ASE_identical',type=float,help="The ASE for the transcriptome, every isoform will have the same allele preference.")
group2.add_argument('--ASE_isoform_random',action='store_true',help="The ASE will be random for every isoform.")
group2.add_argument('--ASE_locus_random',action='store_true',help="The ASE will be randomly assigned for each locus")
parser.add_argument('--short_read_count',type=int,default=10000,help="INT number of short reads")
parser.add_argument('--short_read_length',type=int,default=101,help="INT length of the short reads")
parser.add_argument('--long_read_ccs_count',type=int,default=4000,help="INT default number of long reads")
parser.add_argument('--long_read_subread_count',type=int,default=4000,help="INT default number of long reads")
parser.add_argument('--no_errors',action='store_true',help="Do not simulate errors in reads")
parser.add_argument('--threads',type=int,default=cpu_count(),help="Number of threads defaults to cpu_count()")
parser.add_argument('--locus_by_gene_name',action='store_true',help="Faster than the complete calculation for overlapping loci.")
parser.add_argument('--seed',type=int,help="seed to make transcriptome and rho creation deterministic. Reads are still random, its just the transcriptome and rho that become determinisitic.")
group3 = parser.add_mutually_exclusive_group(required=True)
group3.add_argument('--output',help="Directory name for output")
group3.add_argument('--save_biallelic_transcriptome',help="FILENAME output the biallelic transcriptome used to this file and then exit")
parser.add_argument('--starting_read_multiplier',type=int,default=0,help="Used if outputting different reads from object, and you want them number differently give each different set values 0, 1, 2, etc...")
args = parser.parse_args()
fq_prof_illumina = None
fq_prof_pacbio_ccs95 = None
fq_prof_pacbio_subreads = None
if not args.no_errors:
fq_prof_illumina = default_illumina()
fq_prof_pacbio_ccs95 = default_pacbio_ccs95()
fq_prof_pacbio_subreads = default_pacbio_subreads()
rbe = None
if not args.load_biallelic_transcriptome:
# we need to establish the emitter based on some known data
rbe = load_from_inputs(args)
else:
rbe = SimulationBasics.RandomBiallelicTranscriptomeEmitter()
inf = open(args.load_biallelic_transcriptome)
sline = inf.readline().rstrip()
inf.close()
rbe.read_serialized(sline)
if args.save_biallelic_transcriptome:
ofser = open(args.save_biallelic_transcriptome,'w')
ofser.write(rbe.get_serialized())
ofser.close()
return #exiting here
# Lets prepare to output now
args.output = args.output.rstrip('/')
if not os.path.exists(args.output):
os.makedirs(args.output)
ofser = open(args.output+"/RandomBiallelicTranscriptomeEmitter.serialized",'w')
ofser.write(rbe.get_serialized())
ofser.close()
rbe.set_gaussian_fragmentation_default_hiseq()
#rbe_ser = rbe.get_serialized()
sys.stderr.write("Sequencing short reads\n")
global shand1
shand1 = gzip.open(args.output+"/SR_1.fq.gz",'wb')
global shand2
shand2 = gzip.open(args.output+"/SR_2.fq.gz",'wb')
z = 0
buffer_full_size = 5000
buffer = []
if args.threads > 1:
p = Pool(processes=args.threads)
for i in range(args.short_read_count*args.starting_read_multiplier,args.short_read_count*(args.starting_read_multiplier+1)):
z = i+1
buffer.append(z)
if buffer_full_size <= len(buffer):
vals = buffer[:]
buffer = []
if args.threads > 1:
p.apply_async(process_short_read_buffer,args=(rbe,vals,args),callback=write_short_reads)
else:
oval = process_short_read_buffer(rbe,vals,args)
write_short_reads(oval)
if len(buffer) > 0:
vals = buffer[:]
buffer = []
if args.threads > 1:
p.apply_async(process_short_read_buffer,args=(rbe,vals,args),callback=write_short_reads)
else:
oval = process_short_read_buffer(rbe,vals,args)
write_short_reads(oval)
if args.threads > 1:
p.close()
p.join()
sys.stderr.write("\nFinished sequencing short reads\n")
shand1.close()
shand2.close()
global emissions_reports
for i in range(0,len(emissions_reports)): emissions_reports[i]= emissions_reports[i].get()
sr_report = combine_reports(emissions_reports)
rbe.emissions_report = {} # initialize so we don't accidentally overwrite
# Now lets print out some of the emission details
of = open(args.output+"/SR_report.txt",'w')
for name in sorted(rbe.name2locus.keys()):
express = 1
if rbe.transcriptome1.expression:
express = rbe.transcriptome1.expression.get_expression(name)
if name in sr_report:
of.write(name +"\t"+rbe.gene_names[name]+"\t"+str(rbe.name2locus[name])+"\t"+str(express)+"\t"+str(rbe.transcriptome1_rho[name])+"\t"+str(sr_report[name][0])+"\t"+str(sr_report[name][1])+"\n")
else:
of.write(name +"\t"+rbe.gene_names[name]+"\t"+str(rbe.name2locus[name])+"\t"+str(express)+"\t"+str(rbe.transcriptome1_rho[name])+"\t"+str(0)+"\t"+str(0)+"\n")
of.close()
rbe.emissions_report = {}
emissions_reports = []
# Now lets create the long read set
rbe.set_gaussian_fragmentation_default_pacbio()
#rbe_ser = rbe.get_serialized()
sys.stderr.write("Sequencing long ccs reads\n")
shand1 = gzip.open(args.output+"/LR_ccs95.fq.gz",'wb')
buffer_full_size = 500
buffer = []
if args.threads > 1:
p = Pool(processes=args.threads)
for i in range(args.starting_read_multiplier*args.long_read_ccs_count,(args.starting_read_multiplier+1)*args.long_read_ccs_count):
z = i+1
buffer.append(z)
if buffer_full_size <= len(buffer):
vals = buffer[:]
buffer = []
if args.threads > 1:
p.apply_async(process_long_ccs_read_buffer,args=(rbe,vals,args),callback=write_long_reads)
else:
oval = process_long_ccs_read_buffer(rbe,vals,args)
write_long_reads(oval)
if len(buffer) > 0:
vals = buffer[:]
buffer = []
if args.threads > 1:
p.apply_async(process_long_ccs_read_buffer,args=(rbe,vals,args),callback=write_long_reads)
else:
oval = process_long_ccs_read_buffer(rbe,vals,args)
write_long_reads(oval)
if args.threads > 1:
p.close()
p.join()
sys.stderr.write("\nFinished sequencing long reads\n")
shand1.close()
for i in range(0,len(emissions_reports)): emissions_reports[i]= emissions_reports[i].get()
lr_ccs_report = combine_reports(emissions_reports)
rbe.emissions_report = {} # initialize so we don't accidentally overwrite
# Now lets print out some of the emission details
of = open(args.output+"/LR_ccs95_report.txt",'w')
for name in sorted(rbe.name2locus.keys()):
express = 1
if rbe.transcriptome1.expression:
express = rbe.transcriptome1.expression.get_expression(name)
if name in lr_ccs_report:
of.write(name +"\t"+rbe.gene_names[name]+"\t"+str(rbe.name2locus[name])+"\t"+str(express)+"\t"+str(rbe.transcriptome1_rho[name])+"\t"+str(lr_ccs_report[name][0])+"\t"+str(lr_ccs_report[name][1])+"\n")
else:
of.write(name +"\t"+rbe.gene_names[name]+"\t"+str(rbe.name2locus[name])+"\t"+str(express)+"\t"+str(rbe.transcriptome1_rho[name])+"\t"+str(0)+"\t"+str(0)+"\n")
of.close()
rbe.emissions_report = {}
emissions_reports = []
# Now lets create the long subread read set
rbe.set_gaussian_fragmentation_default_pacbio()
#rbe_ser = rbe.get_serialized()
sys.stderr.write("Sequencing long subreads\n")
shand1 = gzip.open(args.output+"/LR_subreads.fq.gz",'wb')
buffer_full_size = 500
buffer = []
if args.threads > 1:
p = Pool(processes=args.threads)
for i in range(args.long_read_subread_count*args.starting_read_multiplier,(args.starting_read_multiplier+1)*args.long_read_subread_count):
z = i+1
buffer.append(z)
if buffer_full_size <= len(buffer):
vals = buffer[:]
buffer = []
if args.threads > 1:
p.apply_async(process_long_sub_read_buffer,args=(rbe,vals,args),callback=write_long_reads)
else:
oval = process_long_sub_read_buffer(rbe,vals,args)
write_long_reads(oval)
if len(buffer) > 0:
vals = buffer[:]
buffer = []
if args.threads > 1:
p.apply_async(process_long_sub_read_buffer,args=(rbe,vals,args),callback=write_long_reads)
else:
oval = process_long_sub_read_buffer(rbe,vals,args)
write_long_reads(oval)
if args.threads > 1:
p.close()
p.join()
sys.stderr.write("\nFinished sequencing long reads\n")
shand1.close()
for i in range(0,len(emissions_reports)): emissions_reports[i]= emissions_reports[i].get()
lr_sub_report = combine_reports(emissions_reports)
rbe.emissions_report = {} # initialize so we don't accidentally overwrite
# Now lets print out some of the emission details
of = open(args.output+"/LR_subreads_report.txt",'w')
for name in sorted(rbe.name2locus.keys()):
express = 1
if rbe.transcriptome1.expression:
express = rbe.transcriptome1.expression.get_expression(name)
if name in lr_sub_report:
of.write(name +"\t"+rbe.gene_names[name]+"\t"+str(rbe.name2locus[name])+"\t"+str(express)+"\t"+str(rbe.transcriptome1_rho[name])+"\t"+str(lr_sub_report[name][0])+"\t"+str(lr_sub_report[name][1])+"\n")
else:
of.write(name +"\t"+rbe.gene_names[name]+"\t"+str(rbe.name2locus[name])+"\t"+str(express)+"\t"+str(rbe.transcriptome1_rho[name])+"\t"+str(0)+"\t"+str(0)+"\n")
of.close()
combo_report = combine_reports([sr_report,lr_ccs_report,lr_sub_report])
of = open(args.output+"/LR_SR_combo_report.txt",'w')
for name in sorted(rbe.name2locus.keys()):
express = 1
if rbe.transcriptome1.expression:
express = rbe.transcriptome1.expression.get_expression(name)
if name in combo_report:
of.write(name +"\t"+rbe.gene_names[name]+"\t"+str(rbe.name2locus[name])+"\t"+str(express)+"\t"+str(rbe.transcriptome1_rho[name])+"\t"+str(combo_report[name][0])+"\t"+str(combo_report[name][1])+"\n")
else:
of.write(name +"\t"+rbe.gene_names[name]+"\t"+str(rbe.name2locus[name])+"\t"+str(express)+"\t"+str(rbe.transcriptome1_rho[name])+"\t"+str(0)+"\t"+str(0)+"\n")
of.close()
def combine_reports(reports):
c = {}
for report in reports:
for e in report:
if e not in c: c[e] = [0,0]
c[e][0] += report[e][0]
c[e][1] += report[e][1]
return c
def process_short_read_buffer(rbe,buffer,args):
#rbe = SimulationBasics.RandomBiallelicTranscriptomeEmitter()
#rbe.read_serialized(rbe_ser)
fq_prof_illumina = default_illumina()
read1 = ''
read2 = ''
zend = 0
for z in buffer:
[name,l1,r1] = rbe.emit_paired_short_read(args.short_read_length)
zend = z
read1 += "@SRSIM"+str(z)+"\n"
if args.no_errors:
read1 += l1+"\n"
read1 += "+\n"
read1 += len(l1)*'I'+"\n"
else:
l1perm = fq_prof_illumina.create_fastq_and_permute_sequence(l1)
read1 += l1perm['seq']+"\n"
read1 += "+\n"
read1 += l1perm['qual']+"\n"
read2 += "@SRSIM"+str(z)+"\n"
if args.no_errors:
read2 += r1+"\n"
read2 += "+\n"
read2 += len(r1)*'I'+"\n"
else:
r1perm = fq_prof_illumina.create_fastq_and_permute_sequence(r1)
read2 += r1perm['seq']+"\n"
read2 += "+\n"
read2 += r1perm['qual']+"\n"
return [read1,read2,len(buffer),rbe.emissions_report]
def process_long_ccs_read_buffer(rbe,buffer,args):
#rbe = SimulationBasics.RandomBiallelicTranscriptomeEmitter()
#rbe.read_serialized(rbe_ser)
fq_prof_pacbio_ccs95 = default_pacbio_ccs95()
read1 = ''
zend = 0
for z in buffer:
[name,seq] = rbe.emit_long_read()
g = 'm150101_010101_11111_c111111111111111111_s1_p0/'+str(z)+'/ccs'
zend = z
read1 += "@"+g+"\n"
if args.no_errors:
read1 += seq+"\n"
read1 += "+\n"
read1 += len(seq)*'I'+"\n"
else:
seqperm = fq_prof_pacbio_ccs95.create_fastq_and_permute_sequence(seq)
read1 += seqperm['seq']+"\n"
read1 += "+\n"
read1 += seqperm['qual']+"\n"
return [read1,len(buffer),rbe.emissions_report]
def process_long_sub_read_buffer(rbe,buffer,args):
#rbe = SimulationBasics.RandomBiallelicTranscriptomeEmitter()
#rbe.read_serialized(rbe_ser)
fq_prof_pacbio_subreads = default_pacbio_subreads()
read1 = ''
zend = 0
for z in buffer:
[name,seq] = rbe.emit_long_read()
g = 'm150102_010102_11112_c111111111111111112_s1_p0/'+str(z)+'/0_'+str(len(seq)-1)
zend = z
read1 += "@"+g+"\n"
if args.no_errors:
read1 += seq+"\n"
read1 += "+\n"
read1 += len(seq)*'I'+"\n"
else:
seqperm = fq_prof_pacbio_subreads.create_fastq_and_permute_sequence(seq)
read1 += seqperm['seq']+"\n"
read1 += "+\n"
read1 += seqperm['qual']+"\n"
return [read1,len(buffer),rbe.emissions_report]
def write_short_reads(vals):
[read1,read2,zsize,emissions_report] = vals
global write_lock
global gcounter
write_lock.acquire()
global shand1
global shand2
global emissions_reports
gcounter += zsize
sys.stderr.write(str(gcounter)+"\r")
shand1.write(read1)
shand2.write(read2)
eq = Queue()
eq.put(emissions_report)
emissions_reports.append(eq)
write_lock.release()
return
def write_long_reads(vals):
[read1,zsize,emissions_report] = vals
global write_lock
global gcounter
write_lock.acquire()
global shand1
global emissions_reports
gcounter += zsize
sys.stderr.write(str(gcounter)+"\r")
shand1.write(read1)
eq = Queue()
eq.put(emissions_report)
emissions_reports.append(eq)
write_lock.release()
return
# Pre:
# Take the allele info for one chromosome,
# Take one chromosome sequence string
# Take the left or right 0 or 1 position or the phased allele
# Take the chromosome name
# Post:
# Reutrn a number of changes made, the chromosome name, and the chromosome sequence
def adjust_reference_genome(ainfo,refchrom,lrpos,chrom_name):
reflist = list(refchrom)
counter = 0
for pos in sorted(ainfo):
if reflist[pos-1].upper() != ainfo[pos][lrpos].upper():
counter += 1
reflist[pos-1] = ainfo[pos][lrpos]
return [counter,chrom_name,''.join(reflist)]
def get_loci(transcripts_genepred):
loci = Loci()
loci.verbose= True
with open(transcripts_genepred) as inf:
for line in inf:
if line[0]=='#': continue
gpd = GenePredEntry(line.rstrip())
rng = Bed(gpd.value('chrom'),gpd.value('txStart'),gpd.value('txEnd'))
rng.set_payload(gpd.value('name'))
loc1 = Locus()
loc1.add_member(rng)
loci.add_locus(loc1)
sys.stderr.write("Organizing genepred data into overlapping loci\n")
sys.stderr.write("Started with "+str(len(loci.loci))+" loci\n")
loci.update_loci()
sys.stderr.write("Ended with "+str(len(loci.loci))+" loci\n")
m = 0
locus2name = {}
name2locus = {}
for locus in loci.loci:
m+=1
for member in locus.members:
name = member.get_payload()
if m not in locus2name: locus2name[m] = set()
locus2name[m].add(name)
name2locus[name] = m
return [locus2name,name2locus]
def load_from_inputs(args):
#Read in the VCF file
sys.stderr.write("Reading in the VCF file\n")
alleles = {}
#with open(args.phased_VCF) as inf:
with open(args.inputs[1]) as inf:
for line in inf:
vcf = VCF(line)
if not vcf.is_snp(): continue
g = vcf.get_phased_genotype()
if not g: continue
if vcf.value('chrom') not in alleles:
alleles[vcf.value('chrom')] = {}
if vcf.value('pos') in alleles[vcf.value('chrom')]:
sys.stderr.write("WARNING: seeing the same position twice.\n"+line.rstrip()+"\n")
alleles[vcf.value('chrom')][vcf.value('pos')] = g # set our left and right
sys.stderr.write("Reading in the reference genome\n")
#ref = read_fasta_into_hash(args.reference_genome)
ref = read_fasta_into_hash(args.inputs[0])
res1 = []
res2 = []
p = None
sys.stderr.write("Introducing VCF changes to reference sequences\n")
# Pretty memory intesnive to so don't go with all possible threads
if args.threads > 1: p = Pool(processes=max(1,int(args.threads/4)))
for chrom in ref:
# handle the case where there is no allele information
if chrom not in alleles:
r1q = Queue()
r1q.put([0,chrom,ref[chrom]])
res1.append(r1q)
r2q = Queue()
r2q.put([0,chrom,ref[chrom]])
res2.append(r2q)
elif args.threads > 1:
res1.append(p.apply_async(adjust_reference_genome,args=(alleles[chrom],ref[chrom],0,chrom)))
res2.append(p.apply_async(adjust_reference_genome,args=(alleles[chrom],ref[chrom],1,chrom)))
else:
r1q = Queue()
r1q.put(adjust_reference_genome(alleles[chrom],ref[chrom],0,chrom))
res1.append(r1q)
r2q = Queue()
r2q.put(adjust_reference_genome(alleles[chrom],ref[chrom],1,chrom))
res2.append(r2q)
if args.threads > 1:
p.close()
p.join()
# now we can fill reference 1 with all our new sequences
ref1 = {}
c1 = 0
for i in range(0,len(res1)):
res = res1[i].get()
c1 += res[0]
ref1[res[1]]=res[2]
# now we can fill reference 2 with all our new sequences
ref2 = {}
c2 = 0
for i in range(0,len(res2)):
res = res2[i].get()
c2 += res[0]
ref2[res[1]]=res[2]
sys.stderr.write("Made "+str(c1)+"|"+str(c2)+" changes to the reference\n")
# Now ref1 and ref2 have are the diploid sources of the transcriptome
gpdnames = {}
txn1 = Transcriptome()
txn2 = Transcriptome()
txn1.set_reference_genome_dictionary(ref1)
txn2.set_reference_genome_dictionary(ref2)
#with open(args.transcripts_genepred) as inf:
with open(args.inputs[2]) as inf:
for line in inf:
if line[0]=='#': continue
txn1.add_genepred_line(line.rstrip())
txn2.add_genepred_line(line.rstrip())
gpd = GenePredEntry(line.rstrip())
gpdnames[gpd.value('name')] = gpd.value('gene_name')
# The transcriptomes are set but we dont' really need the references anymore
# Empty our big memory things
txn1.ref_hash = None
txn2.ref_hash = None
for chrom in ref1.keys(): del ref1[chrom]
for chrom in ref2.keys(): del ref2[chrom]
for chrom in ref.keys(): del ref[chrom]
if not args.locus_by_gene_name:
#[locus2name,name2locus] = get_loci(args.transcripts_genepred)
[locus2name,name2locus] = get_loci(args.inputs[2])
else: # set locus by gene name
sys.stderr.write("Organizing loci by gene name\n")
locus2name = {}
name2locus = {}
numname = {}
m = 0
for name in sorted(gpdnames):
gene = gpdnames[name]
if gene not in numname:
m+=1
numname[gene] = m
num = numname[gene]
if num not in locus2name:
locus2name[num] = set()
locus2name[num].add(name)
name2locus[name] = num
sys.stderr.write("Ended with "+str(len(locus2name.keys()))+" loci\n")
if args.isoform_expression:
sys.stderr.write("Reading expression from a TSV\n")
with open(args.isoform_expression) as inf:
line1 = inf.readline()
for line in inf:
f = line.rstrip().split("\t")
txn1.add_expression(f[0],float(f[1]))
txn2.add_expression(f[0],float(f[1]))
elif args.cufflinks_isoform_expression:
sys.stderr.write("Using cufflinks expression\n")
cuffz = 0
with open(args.cufflinks_isoform_expression) as inf:
line1 = inf.readline()
for line in inf:
cuffz +=1
sys.stderr.write(str(cuffz)+" cufflinks entries processed\r")
f = line.rstrip().split("\t")
txn1.add_expression_no_update(f[0],float(f[9]))
txn2.add_expression_no_update(f[0],float(f[9]))
txn1.update_expression()
txn2.update_expression()
sys.stderr.write("\n")
elif args.uniform_expression:
sys.stderr.write("Using uniform expression model\n")
else:
sys.stderr.write("Warning isoform expression not sepcified, using uniform expression model.\n")
# Now we have the transcriptomes set
rhos = {} # The ASE of allele 1 (the left side)
randos = {}
if args.seed:
random.seed(args.seed)
for z in locus2name: randos[z] = random.random()
sys.stderr.write("Setting rho for each transcript\n")
# Lets set rho for ASE for each transcript
for tname in sorted(txn1.transcripts):
if args.ASE_identical or args.ASE_identical == 0:
rhos[tname] = float(args.ASE_identical)
elif args.ASE_isoform_random:
rhos[tname] = random.random()
else: # we must be on locus random
rhos[tname] = randos[name2locus[tname]]
#Now our dataset is set up
rbe = SimulationBasics.RandomBiallelicTranscriptomeEmitter(txn1,txn2)
rbe.gene_names = gpdnames
rbe.name2locus = name2locus
rbe.set_transcriptome1_rho(rhos)
return rbe
if __name__=="__main__":
main()
|
jason-weirather/py-seq-tools
|
seqtools/cli/legacy/simulate_biallelic_transcriptome.py
|
Python
|
apache-2.0
| 22,656
|
[
"ASE"
] |
8027b3633d268ec7df97231d4c93c834a7811eece114643f7775cbb142ac1cdc
|
#!/usr/bin/env python3
#* This file is part of the MOOSE framework
#* https://www.mooseframework.org
#*
#* All rights reserved, see COPYRIGHT for full restrictions
#* https://github.com/idaholab/moose/blob/master/COPYRIGHT
#*
#* Licensed under LGPL 2.1, please see LICENSE for details
#* https://www.gnu.org/licenses/lgpl-2.1.html
import os
import argparse
import shutil
class Clobber(object):
"""
Class to cleanup compile artifacts.
This does not honor the METHOD environment variable.
It removes compile artifacts for all of them.
This can be called from a top level application so
we ignore the following directories:
moose (ignore a possible MOOSE submodule)
.git (don't accidentally delete any of git's metadata)
.svn (don't accidentally delete any of svn's metadata)
"""
def __init__(self, top_dir, verbose, dry_run):
self.top_dir = top_dir
self.verbose = verbose
self.dry_run = dry_run
def message(self, msg):
if self.verbose:
if self.dry_run:
print("DRY RUN: " + msg)
else:
print(msg)
def ignore_dir(self, root, subdirs, to_ignore):
"""
Ignores a directory by removing it from the subdirs list
"""
if to_ignore in subdirs:
self.message("Ignoring %s" % os.path.join(root, to_ignore))
subdirs.remove(to_ignore)
def remove_dir(self, root, subdirs, to_remove):
"""
Removes a directory in the filesystem.
"""
if to_remove in subdirs:
dir_path = os.path.join(root, to_remove)
self.message("Removing directory %s" % dir_path)
subdirs.remove(to_remove)
if not self.dry_run:
try:
shutil.rmtree(dir_path)
except Exception as e:
print("Failed to remove path: %s\nError: %s" % (dir_path, e))
def clobber(self):
"""
Walks the directories and removes unwanted files and directories.
"""
self.message("Clobbering in %s" % self.top_dir)
remove_file_ext = ("~",
".o",
".lo",
".la",
".dylib",
".a",
"-opt",
"-dbg",
"-oprof",
"-devel",
".d",
".pyc",
".plugin",
".mod",
".gcda",
".gcno",
".gcov",
".gch",
)
for root, subdirs, files in os.walk(self.top_dir, topdown=True):
self.ignore_dir(root, subdirs, "moose")
self.ignore_dir(root, subdirs, ".git")
self.ignore_dir(root, subdirs, ".svn")
self.remove_dir(root, subdirs, ".libs")
self.remove_dir(root, subdirs, ".jitcache")
for f in files:
if f.endswith(remove_file_ext) or ".so" in f:
fpath = os.path.join(root, f)
self.message("Removing file %s" % fpath)
if not self.dry_run:
try:
os.unlink(fpath)
except Exception as e:
print("Failed to remove file: %s\nError: %s" % (fpath, e))
for d in subdirs[:]:
if d.endswith(".dSYM"):
self.remove_dir(root, subdirs, d)
if __name__ == "__main__":
parser = argparse.ArgumentParser(description='Remove compile artifacts.')
parser.add_argument('-v', action='store_true', dest='verbose', help='Print what is happening.')
parser.add_argument('-n', action='store_true', dest='dry_run', help="Dry run. Don't actually remove anything.")
parser.add_argument('top_directory', help='Top directory to start with.')
parsed = parser.parse_args()
c = Clobber(parsed.top_directory, parsed.verbose, parsed.dry_run)
c.clobber()
|
nuclear-wizard/moose
|
scripts/clobber.py
|
Python
|
lgpl-2.1
| 4,034
|
[
"MOOSE"
] |
543f8b5903de2718424e576911200b7af9ee39fb0f6cfb870cb2f74abce28df1
|
# Copyright 2015 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
"""Tests for Python ops defined in image_grad.py."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import numpy as np
from tensorflow.python.eager import backprop
from tensorflow.python.framework import constant_op
from tensorflow.python.framework import test_util
from tensorflow.python.ops import gradient_checker
from tensorflow.python.ops import gradients_impl
from tensorflow.python.ops import image_ops
from tensorflow.python.platform import test
@test_util.for_all_test_methods(test_util.disable_xla,
'align_corners=False not supported by XLA')
class ResizeNearestNeighborOpTest(test.TestCase):
TYPES = [np.float32, np.float64]
def testShapeIsCorrectAfterOp(self):
in_shape = [1, 2, 2, 1]
out_shape = [1, 4, 6, 1]
for nptype in self.TYPES:
x = np.arange(0, 4).reshape(in_shape).astype(nptype)
with self.cached_session(use_gpu=True):
input_tensor = constant_op.constant(x, shape=in_shape)
resize_out = image_ops.resize_nearest_neighbor(input_tensor,
out_shape[1:3])
self.assertEqual(out_shape, list(resize_out.get_shape()))
resize_out = self.evaluate(resize_out)
self.assertEqual(out_shape, list(resize_out.shape))
@test_util.run_deprecated_v1
def testGradFromResizeToLargerInBothDims(self):
in_shape = [1, 2, 3, 1]
out_shape = [1, 4, 6, 1]
for nptype in self.TYPES:
x = np.arange(0, 6).reshape(in_shape).astype(nptype)
with self.cached_session(use_gpu=True):
input_tensor = constant_op.constant(x, shape=in_shape)
resize_out = image_ops.resize_nearest_neighbor(input_tensor,
out_shape[1:3])
err = gradient_checker.compute_gradient_error(
input_tensor, in_shape, resize_out, out_shape, x_init_value=x)
self.assertLess(err, 1e-3)
@test_util.run_deprecated_v1
def testGradFromResizeToSmallerInBothDims(self):
in_shape = [1, 4, 6, 1]
out_shape = [1, 2, 3, 1]
for nptype in self.TYPES:
x = np.arange(0, 24).reshape(in_shape).astype(nptype)
with self.cached_session(use_gpu=True):
input_tensor = constant_op.constant(x, shape=in_shape)
resize_out = image_ops.resize_nearest_neighbor(input_tensor,
out_shape[1:3])
err = gradient_checker.compute_gradient_error(
input_tensor, in_shape, resize_out, out_shape, x_init_value=x)
self.assertLess(err, 1e-3)
@test_util.run_deprecated_v1
def testCompareGpuVsCpu(self):
in_shape = [1, 4, 6, 3]
out_shape = [1, 8, 16, 3]
for nptype in self.TYPES:
x = np.arange(0, np.prod(in_shape)).reshape(in_shape).astype(nptype)
for align_corners in [True, False]:
with self.cached_session(use_gpu=False):
input_tensor = constant_op.constant(x, shape=in_shape)
resize_out = image_ops.resize_nearest_neighbor(
input_tensor, out_shape[1:3], align_corners=align_corners)
grad_cpu = gradient_checker.compute_gradient(
input_tensor, in_shape, resize_out, out_shape, x_init_value=x)
with self.cached_session(use_gpu=True):
input_tensor = constant_op.constant(x, shape=in_shape)
resize_out = image_ops.resize_nearest_neighbor(
input_tensor, out_shape[1:3], align_corners=align_corners)
grad_gpu = gradient_checker.compute_gradient(
input_tensor, in_shape, resize_out, out_shape, x_init_value=x)
self.assertAllClose(grad_cpu, grad_gpu, rtol=1e-5, atol=1e-5)
class ResizeBilinearOpTest(test.TestCase):
def testShapeIsCorrectAfterOp(self):
in_shape = [1, 2, 2, 1]
out_shape = [1, 4, 6, 1]
x = np.arange(0, 4).reshape(in_shape).astype(np.float32)
with self.cached_session():
input_tensor = constant_op.constant(x, shape=in_shape)
resize_out = image_ops.resize_bilinear(input_tensor, out_shape[1:3])
self.assertEqual(out_shape, list(resize_out.get_shape()))
resize_out = self.evaluate(resize_out)
self.assertEqual(out_shape, list(resize_out.shape))
@test_util.run_deprecated_v1
def testGradFromResizeToLargerInBothDims(self):
in_shape = [1, 2, 3, 1]
out_shape = [1, 4, 6, 1]
x = np.arange(0, 6).reshape(in_shape).astype(np.float32)
with self.cached_session():
input_tensor = constant_op.constant(x, shape=in_shape)
resize_out = image_ops.resize_bilinear(input_tensor, out_shape[1:3])
err = gradient_checker.compute_gradient_error(
input_tensor, in_shape, resize_out, out_shape, x_init_value=x)
self.assertLess(err, 1e-3)
@test_util.run_deprecated_v1
def testGradFromResizeToSmallerInBothDims(self):
in_shape = [1, 4, 6, 1]
out_shape = [1, 2, 3, 1]
x = np.arange(0, 24).reshape(in_shape).astype(np.float32)
with self.cached_session():
input_tensor = constant_op.constant(x, shape=in_shape)
resize_out = image_ops.resize_bilinear(input_tensor, out_shape[1:3])
err = gradient_checker.compute_gradient_error(
input_tensor, in_shape, resize_out, out_shape, x_init_value=x)
self.assertLess(err, 1e-3)
@test_util.run_deprecated_v1
def testCompareGpuVsCpu(self):
in_shape = [2, 4, 6, 3]
out_shape = [2, 8, 16, 3]
size = np.prod(in_shape)
x = 1.0 / size * np.arange(0, size).reshape(in_shape).astype(np.float32)
# Align corners will be deprecated for tf2.0 and the false version is not
# supported by XLA.
align_corner_options = [True
] if test_util.is_xla_enabled() else [True, False]
for align_corners in align_corner_options:
grad = {}
for use_gpu in [False, True]:
with self.cached_session(use_gpu=use_gpu):
input_tensor = constant_op.constant(x, shape=in_shape)
resized_tensor = image_ops.resize_bilinear(
input_tensor, out_shape[1:3], align_corners=align_corners)
grad[use_gpu] = gradient_checker.compute_gradient(
input_tensor, in_shape, resized_tensor, out_shape, x_init_value=x)
self.assertAllClose(grad[False], grad[True], rtol=1e-4, atol=1e-4)
@test_util.run_deprecated_v1
def testTypes(self):
in_shape = [1, 4, 6, 1]
out_shape = [1, 2, 3, 1]
x = np.arange(0, 24).reshape(in_shape)
with self.cached_session() as sess:
for dtype in [np.float16, np.float32, np.float64]:
input_tensor = constant_op.constant(x.astype(dtype), shape=in_shape)
resize_out = image_ops.resize_bilinear(input_tensor, out_shape[1:3])
grad = sess.run(gradients_impl.gradients(resize_out, input_tensor))[0]
self.assertAllEqual(in_shape, grad.shape)
# Not using gradient_checker.compute_gradient as I didn't work out
# the changes required to compensate for the lower precision of
# float16 when computing the numeric jacobian.
# Instead, we just test the theoretical jacobian.
self.assertAllEqual([[[[1.], [0.], [1.], [0.], [1.], [0.]], [[0.], [
0.
], [0.], [0.], [0.], [0.]], [[1.], [0.], [1.], [0.], [1.], [0.]],
[[0.], [0.], [0.], [0.], [0.], [0.]]]], grad)
class ResizeBicubicOpTest(test.TestCase):
def testShapeIsCorrectAfterOp(self):
in_shape = [1, 2, 2, 1]
out_shape = [1, 4, 6, 1]
x = np.arange(0, 4).reshape(in_shape).astype(np.float32)
for align_corners in [True, False]:
with self.cached_session():
input_tensor = constant_op.constant(x, shape=in_shape)
resize_out = image_ops.resize_bicubic(input_tensor, out_shape[1:3],
align_corners=align_corners)
self.assertEqual(out_shape, list(resize_out.get_shape()))
resize_out = self.evaluate(resize_out)
self.assertEqual(out_shape, list(resize_out.shape))
@test_util.run_deprecated_v1
def testGradFromResizeToLargerInBothDims(self):
in_shape = [1, 2, 3, 1]
out_shape = [1, 4, 6, 1]
x = np.arange(0, 6).reshape(in_shape).astype(np.float32)
for align_corners in [True, False]:
with self.cached_session():
input_tensor = constant_op.constant(x, shape=in_shape)
resize_out = image_ops.resize_bicubic(input_tensor, out_shape[1:3],
align_corners=align_corners)
err = gradient_checker.compute_gradient_error(
input_tensor, in_shape, resize_out, out_shape, x_init_value=x)
self.assertLess(err, 1e-3)
@test_util.run_deprecated_v1
def testGradFromResizeToSmallerInBothDims(self):
in_shape = [1, 4, 6, 1]
out_shape = [1, 2, 3, 1]
x = np.arange(0, 24).reshape(in_shape).astype(np.float32)
for align_corners in [True, False]:
with self.cached_session():
input_tensor = constant_op.constant(x, shape=in_shape)
resize_out = image_ops.resize_bicubic(input_tensor, out_shape[1:3],
align_corners=align_corners)
err = gradient_checker.compute_gradient_error(
input_tensor, in_shape, resize_out, out_shape, x_init_value=x)
self.assertLess(err, 1e-3)
@test_util.run_deprecated_v1
def testGradOnUnsupportedType(self):
in_shape = [1, 4, 6, 1]
out_shape = [1, 2, 3, 1]
x = np.arange(0, 24).reshape(in_shape).astype(np.uint8)
with self.cached_session():
input_tensor = constant_op.constant(x, shape=in_shape)
resize_out = image_ops.resize_bicubic(input_tensor, out_shape[1:3])
grad = gradients_impl.gradients(input_tensor, [resize_out])
self.assertEqual([None], grad)
class ScaleAndTranslateOpTest(test.TestCase):
@test_util.run_deprecated_v1
def testGrads(self):
in_shape = [1, 2, 3, 1]
out_shape = [1, 4, 6, 1]
x = np.arange(0, 6).reshape(in_shape).astype(np.float32)
kernel_types = [
'lanczos1', 'lanczos3', 'lanczos5', 'gaussian', 'box', 'triangle',
'keyscubic', 'mitchellcubic'
]
scales = [(1.0, 1.0), (0.37, 0.47), (2.1, 2.1)]
translations = [(0.0, 0.0), (3.14, 1.19), (2.1, 3.1), (100.0, 200.0)]
for scale in scales:
for translation in translations:
for kernel_type in kernel_types:
for antialias in [True, False]:
with self.cached_session():
input_tensor = constant_op.constant(x, shape=in_shape)
scale_and_translate_out = image_ops.scale_and_translate(
input_tensor,
out_shape[1:3],
scale=constant_op.constant(scale),
translation=constant_op.constant(translation),
kernel_type=kernel_type,
antialias=antialias)
err = gradient_checker.compute_gradient_error(
input_tensor,
in_shape,
scale_and_translate_out,
out_shape,
x_init_value=x)
self.assertLess(err, 1e-3)
def testIdentityGrads(self):
"""Tests that Gradients for 1.0 scale should be ones for some kernels."""
in_shape = [1, 2, 3, 1]
out_shape = [1, 4, 6, 1]
x = np.arange(0, 6).reshape(in_shape).astype(np.float32)
kernel_types = ['lanczos1', 'lanczos3', 'lanczos5', 'triangle', 'keyscubic']
scale = (1.0, 1.0)
translation = (0.0, 0.0)
antialias = True
for kernel_type in kernel_types:
with self.cached_session():
input_tensor = constant_op.constant(x, shape=in_shape)
with backprop.GradientTape() as tape:
tape.watch(input_tensor)
scale_and_translate_out = image_ops.scale_and_translate(
input_tensor,
out_shape[1:3],
scale=constant_op.constant(scale),
translation=constant_op.constant(translation),
kernel_type=kernel_type,
antialias=antialias)
grad = tape.gradient(scale_and_translate_out, input_tensor)[0]
grad_v = self.evaluate(grad)
self.assertAllClose(np.ones_like(grad_v), grad_v)
class CropAndResizeOpTest(test.TestCase):
def testShapeIsCorrectAfterOp(self):
batch = 2
image_height = 3
image_width = 4
crop_height = 4
crop_width = 5
depth = 2
num_boxes = 2
image_shape = [batch, image_height, image_width, depth]
crop_size = [crop_height, crop_width]
crops_shape = [num_boxes, crop_height, crop_width, depth]
image = np.arange(0, batch * image_height * image_width *
depth).reshape(image_shape).astype(np.float32)
boxes = np.array([[0, 0, 1, 1], [.1, .2, .7, .8]], dtype=np.float32)
box_ind = np.array([0, 1], dtype=np.int32)
with self.session(use_gpu=True) as sess:
crops = image_ops.crop_and_resize(
constant_op.constant(
image, shape=image_shape),
constant_op.constant(
boxes, shape=[num_boxes, 4]),
constant_op.constant(
box_ind, shape=[num_boxes]),
constant_op.constant(
crop_size, shape=[2]))
self.assertEqual(crops_shape, list(crops.get_shape()))
crops = self.evaluate(crops)
self.assertEqual(crops_shape, list(crops.shape))
def _randomUniformAvoidAnchors(self, low, high, anchors, radius, num_samples):
"""Generate samples that are far enough from a set of anchor points.
We generate uniform samples in [low, high], then reject those that are less
than radius away from any point in anchors. We stop after we have accepted
num_samples samples.
Args:
low: The lower end of the interval.
high: The upper end of the interval.
anchors: A list of length num_crops with anchor points to avoid.
radius: Distance threshold for the samples from the anchors.
num_samples: How many samples to produce.
Returns:
samples: A list of length num_samples with the accepted samples.
"""
self.assertTrue(low < high)
self.assertTrue(radius >= 0)
num_anchors = len(anchors)
# Make sure that at least half of the interval is not forbidden.
self.assertTrue(2 * radius * num_anchors < 0.5 * (high - low))
anchors = np.reshape(anchors, num_anchors)
samples = []
while len(samples) < num_samples:
sample = np.random.uniform(low, high)
if np.all(np.fabs(sample - anchors) > radius):
samples.append(sample)
return samples
@test_util.run_deprecated_v1
def testGradRandomBoxes(self):
"""Test that the gradient is correct for randomly generated boxes.
The mapping is piecewise differentiable with respect to the box coordinates.
The points where the function is not differentiable are those which are
mapped to image pixels, i.e., the normalized y coordinates in
np.linspace(0, 1, image_height) and normalized x coordinates in
np.linspace(0, 1, image_width). Make sure that the box coordinates are
sufficiently far away from those rectangular grid centers that are points of
discontinuity, so that the finite difference Jacobian is close to the
computed one.
"""
np.random.seed(1) # Make it reproducible.
delta = 1e-3
radius = 2 * delta
low, high = -0.5, 1.5 # Also covers the case of extrapolation.
image_height = 4
for image_width in range(1, 3):
for crop_height in range(1, 3):
for crop_width in range(2, 4):
for depth in range(1, 3):
for num_boxes in range(1, 3):
batch = num_boxes
image_shape = [batch, image_height, image_width, depth]
crop_size = [crop_height, crop_width]
crops_shape = [num_boxes, crop_height, crop_width, depth]
boxes_shape = [num_boxes, 4]
image = np.arange(0, batch * image_height * image_width *
depth).reshape(image_shape).astype(np.float32)
boxes = []
for _ in range(num_boxes):
# pylint: disable=unbalanced-tuple-unpacking
y1, y2 = self._randomUniformAvoidAnchors(
low, high, np.linspace(0, 1, image_height), radius, 2)
x1, x2 = self._randomUniformAvoidAnchors(
low, high, np.linspace(0, 1, image_width), radius, 2)
# pylint: enable=unbalanced-tuple-unpacking
boxes.append([y1, x1, y2, x2])
boxes = np.array(boxes, dtype=np.float32)
box_ind = np.arange(batch, dtype=np.int32)
with self.cached_session(use_gpu=True):
image_tensor = constant_op.constant(image, shape=image_shape)
boxes_tensor = constant_op.constant(boxes, shape=[num_boxes, 4])
box_ind_tensor = constant_op.constant(
box_ind, shape=[num_boxes])
crops = image_ops.crop_and_resize(
image_tensor,
boxes_tensor,
box_ind_tensor,
constant_op.constant(
crop_size, shape=[2]))
err = gradient_checker.compute_gradient_error(
[image_tensor, boxes_tensor], [image_shape, boxes_shape],
crops,
crops_shape,
delta=delta,
x_init_value=[image, boxes])
self.assertLess(err, 2e-3)
if __name__ == "__main__":
test.main()
|
ghchinoy/tensorflow
|
tensorflow/python/ops/image_grad_test.py
|
Python
|
apache-2.0
| 18,282
|
[
"Gaussian"
] |
8ba4a34a26c459eb546cb074903432e1b265acc0323ab8b7fd0f26731ea37029
|
"""
Converting the 'parse-tree' output of pyparsing to a SPARQL Algebra expression
http://www.w3.org/TR/sparql11-query/#sparqlQuery
"""
import functools
import operator
import collections
from rdflib import Literal, Variable, URIRef, BNode
from rdflib.plugins.sparql.sparql import Prologue, Query
from rdflib.plugins.sparql.parserutils import CompValue, Expr
from rdflib.plugins.sparql.operators import (
and_, TrueFilter, simplify as simplifyFilters)
from rdflib.paths import (
InvPath, AlternativePath, SequencePath, MulPath, NegatedPath)
from pyparsing import ParseResults
# ---------------------------
# Some convenience methods
def OrderBy(p, expr):
return CompValue('OrderBy', p=p, expr=expr)
def ToMultiSet(p):
return CompValue('ToMultiSet', p=p)
def Union(p1, p2):
return CompValue('Union', p1=p1, p2=p2)
def Join(p1, p2):
return CompValue('Join', p1=p1, p2=p2)
def Minus(p1, p2):
return CompValue('Minus', p1=p1, p2=p2)
def Graph(term, graph):
return CompValue('Graph', term=term, p=graph)
def BGP(triples=None):
return CompValue('BGP', triples=triples or [])
def LeftJoin(p1, p2, expr):
return CompValue('LeftJoin', p1=p1, p2=p2, expr=expr)
def Filter(expr, p):
return CompValue('Filter', expr=expr, p=p)
def Extend(p, expr, var):
return CompValue('Extend', p=p, expr=expr, var=var)
def Values(res):
return CompValue('values', res=res)
def Project(p, PV):
return CompValue('Project', p=p, PV=PV)
def Group(p, expr=None):
return CompValue('Group', p=p, expr=expr)
def _knownTerms(triple, varsknown, varscount):
return (len(filter(None, (x not in varsknown and
isinstance(
x, (Variable, BNode)) for x in triple))),
-sum(varscount.get(x, 0) for x in triple),
not isinstance(triple[2], Literal),
)
def reorderTriples(l):
"""
Reorder triple patterns so that we execute the
ones with most bindings first
"""
def _addvar(term, varsknown):
if isinstance(term, (Variable, BNode)):
varsknown.add(term)
l = [(None, x) for x in l]
varsknown = set()
varscount = collections.defaultdict(int)
for t in l:
for c in t[1]:
if isinstance(c, (Variable, BNode)):
varscount[c] += 1
i = 0
# Done in steps, sort by number of bound terms
# the top block of patterns with the most bound terms is kept
# the rest is resorted based on the vars bound after the first
# block is evaluated
# we sort by decorate/undecorate, since we need the value of the sort keys
while i < len(l):
l[i:] = sorted((_knownTerms(x[
1], varsknown, varscount), x[1]) for x in l[i:])
t = l[i][0][0] # top block has this many terms bound
j = 0
while i+j < len(l) and l[i+j][0][0] == t:
for c in l[i+j][1]:
_addvar(c, varsknown)
j += 1
i += 1
return [x[1] for x in l]
def triples(l):
l = reduce(lambda x, y: x + y, l)
if (len(l) % 3) != 0:
raise Exception('these aint triples')
return reorderTriples((l[x], l[x + 1], l[x + 2])
for x in range(0, len(l), 3))
def translatePName(p, prologue):
"""
Expand prefixed/relative URIs
"""
if isinstance(p, CompValue):
if p.name == 'pname':
return prologue.absolutize(p)
if p.name == 'literal':
return Literal(p.string, lang=p.lang,
datatype=prologue.absolutize(p.datatype))
elif isinstance(p, URIRef):
return prologue.absolutize(p)
def translatePath(p):
"""
Translate PropertyPath expressions
"""
if isinstance(p, CompValue):
if p.name == 'PathAlternative':
if len(p.part) == 1:
return p.part[0]
else:
return AlternativePath(*p.part)
elif p.name == 'PathSequence':
if len(p.part) == 1:
return p.part[0]
else:
return SequencePath(*p.part)
elif p.name == 'PathElt':
if not p.mod:
return p.part
else:
if isinstance(p.part, list):
if len(p.part) != 1:
raise Exception('Denkfehler!')
return MulPath(p.part[0], p.mod)
else:
return MulPath(p.part, p.mod)
elif p.name == 'PathEltOrInverse':
if isinstance(p.part, list):
if len(p.part) != 1:
raise Exception('Denkfehler!')
return InvPath(p.part[0])
else:
return InvPath(p.part)
elif p.name == 'PathNegatedPropertySet':
if isinstance(p.part, list):
return NegatedPath(AlternativePath(*p.part))
else:
return NegatedPath(p.part)
def translateExists(e):
"""
Translate the graph pattern used by EXISTS and NOT EXISTS
http://www.w3.org/TR/sparql11-query/#sparqlCollectFilters
"""
def _c(n):
if isinstance(n, CompValue):
if n.name in ('Builtin_EXISTS', 'Builtin_NOTEXISTS'):
n.graph = translateGroupGraphPattern(n.graph)
e = traverse(e, visitPost=_c)
return e
def collectAndRemoveFilters(parts):
"""
FILTER expressions apply to the whole group graph pattern in which
they appear.
http://www.w3.org/TR/sparql11-query/#sparqlCollectFilters
"""
filters = []
i = 0
while i < len(parts):
p = parts[i]
if p.name == 'Filter':
filters.append(translateExists(p.expr))
parts.pop(i)
else:
i += 1
if filters:
return and_(*filters)
return None
def translateGroupOrUnionGraphPattern(graphPattern):
A = None
for g in graphPattern.graph:
g = translateGroupGraphPattern(g)
if not A:
A = g
else:
A = Union(A, g)
return A
def translateGraphGraphPattern(graphPattern):
return Graph(graphPattern.term,
translateGroupGraphPattern(graphPattern.graph))
def translateInlineData(graphPattern):
return ToMultiSet(translateValues(graphPattern))
def translateGroupGraphPattern(graphPattern):
"""
http://www.w3.org/TR/sparql11-query/#convertGraphPattern
"""
if graphPattern.name == 'SubSelect':
return ToMultiSet(translate(graphPattern)[0])
if not graphPattern.part:
graphPattern.part = [] # empty { }
filters = collectAndRemoveFilters(graphPattern.part)
g = []
for p in graphPattern.part:
if p.name == 'TriplesBlock':
# merge adjacent TripleBlocks
if not (g and g[-1].name == 'BGP'):
g.append(BGP())
g[-1]["triples"] += triples(p.triples)
else:
g.append(p)
G = BGP()
for p in g:
if p.name == 'OptionalGraphPattern':
A = translateGroupGraphPattern(p.graph)
if A.name == 'Filter':
G = LeftJoin(G, A.p, A.expr)
else:
G = LeftJoin(G, A, TrueFilter)
elif p.name == 'MinusGraphPattern':
G = Minus(p1=G, p2=translateGroupGraphPattern(p.graph))
elif p.name == 'GroupOrUnionGraphPattern':
G = Join(p1=G, p2=translateGroupOrUnionGraphPattern(p))
elif p.name == 'GraphGraphPattern':
G = Join(p1=G, p2=translateGraphGraphPattern(p))
elif p.name == 'InlineData':
G = Join(p1=G, p2=translateInlineData(p))
elif p.name == 'ServiceGraphPattern':
G = Join(p1=G, p2=p)
elif p.name in ('BGP', 'Extend'):
G = Join(p1=G, p2=p)
elif p.name == 'Bind':
G = Extend(G, p.expr, p.var)
else:
raise Exception('Unknown part in GroupGraphPattern: %s - %s' %
(type(p), p.name))
if filters:
G = Filter(expr=filters, p=G)
return G
class StopTraversal(Exception):
def __init__(self, rv):
self.rv = rv
def _traverse(e, visitPre=lambda n: None, visitPost=lambda n: None):
"""
Traverse a parse-tree, visit each node
if visit functions return a value, replace current node
"""
_e = visitPre(e)
if _e is not None:
return _e
if e is None:
return None
if isinstance(e, (list, ParseResults)):
return [_traverse(x, visitPre, visitPost) for x in e]
elif isinstance(e, tuple):
return tuple([_traverse(x, visitPre, visitPost) for x in e])
elif isinstance(e, CompValue):
for k, val in e.iteritems():
e[k] = _traverse(val, visitPre, visitPost)
_e = visitPost(e)
if _e is not None:
return _e
return e
def _traverseAgg(e, visitor=lambda n, v: None):
"""
Traverse a parse-tree, visit each node
if visit functions return a value, replace current node
"""
res = []
if isinstance(e, (list, ParseResults, tuple)):
res = [_traverseAgg(x, visitor) for x in e]
elif isinstance(e, CompValue):
for k, val in e.iteritems():
if val != None:
res.append(_traverseAgg(val, visitor))
return visitor(e, res)
def traverse(
tree, visitPre=lambda n: None,
visitPost=lambda n: None, complete=None):
"""
Traverse tree, visit each node with visit function
visit function may raise StopTraversal to stop traversal
if complete!=None, it is returned on complete traversal,
otherwise the transformed tree is returned
"""
try:
r = _traverse(tree, visitPre, visitPost)
if complete is not None:
return complete
return r
except StopTraversal, st:
return st.rv
def _hasAggregate(x):
"""
Traverse parse(sub)Tree
return true if any aggregates are used
"""
if isinstance(x, CompValue):
if x.name.startswith('Aggregate_'):
raise StopTraversal(True)
def _aggs(e, A):
"""
Collect Aggregates in A
replaces aggregates with variable references
"""
# TODO: nested Aggregates?
if isinstance(e, CompValue) and e.name.startswith('Aggregate_'):
A.append(e)
aggvar = Variable('__agg_%d__' % len(A))
e["res"] = aggvar
return aggvar
def _findVars(x, res):
"""
Find all variables in a tree
"""
if isinstance(x, Variable):
res.add(x)
if isinstance(x, CompValue):
if x.name == "Bind":
res.add(x.var)
return x # stop recursion and finding vars in the expr
elif x.name == 'SubSelect':
if x.projection:
res.update(v.var or v.evar for v in x.projection)
return x
def _addVars(x, children):
# import pdb; pdb.set_trace()
if isinstance(x, Variable):
return set([x])
elif isinstance(x, CompValue):
x["_vars"] = set(reduce(operator.or_, children, set()))
if x.name == "Bind":
return set([x.var])
elif x.name == 'SubSelect':
if x.projection:
s = set(v.var or v.evar for v in x.projection)
else:
s = set()
return s
return reduce(operator.or_, children, set())
def _sample(e, v=None):
"""
For each unaggregated variable V in expr
Replace V with Sample(V)
"""
if isinstance(e, CompValue) and e.name.startswith("Aggregate_"):
return e # do not replace vars in aggregates
if isinstance(e, Variable) and v != e:
return CompValue('Aggregate_Sample', vars=e)
def _simplifyFilters(e):
if isinstance(e, Expr):
return simplifyFilters(e)
def translateAggregates(q, M):
E = []
A = []
# collect/replace aggs in :
# select expr as ?var
if q.projection:
for v in q.projection:
if v.evar:
v.expr = traverse(v.expr, functools.partial(_sample, v=v.evar))
v.expr = traverse(v.expr, functools.partial(_aggs, A=A))
# having clause
if traverse(q.having, _hasAggregate, complete=False):
q.having = traverse(q.having, _sample)
traverse(q.having, functools.partial(_aggs, A=A))
# order by
if traverse(q.orderby, _hasAggregate, complete=False):
q.orderby = traverse(q.orderby, _sample)
traverse(q.orderby, functools.partial(_aggs, A=A))
# sample all other select vars
# TODO: only allowed for vars in group-by?
if q.projection:
for v in q.projection:
if v.var:
rv = Variable('__agg_%d__' % (len(A) + 1))
A.append(CompValue('Aggregate_Sample', vars=v.var, res=rv))
E.append((rv, v.var))
return CompValue('AggregateJoin', A=A, p=M), E
def translateValues(v):
# if len(v.var)!=len(v.value):
# raise Exception("Unmatched vars and values in ValueClause: "+str(v))
res = []
if not v.var:
return res
if not v.value:
return res
if not isinstance(v.value[0], list):
for val in v.value:
res.append({v.var[0]: val})
else:
for vals in v.value:
res.append(dict(zip(v.var, vals)))
return Values(res)
def translate(q):
"""
http://www.w3.org/TR/sparql11-query/#convertSolMod
"""
_traverse(q, _simplifyFilters)
q.where = traverse(q.where, visitPost=translatePath)
# TODO: Var scope test
VS = set()
traverse(q.where, functools.partial(_findVars, res=VS))
# all query types have a where part
M = translateGroupGraphPattern(q.where)
aggregate = False
if q.groupby:
conditions = []
# convert "GROUP BY (?expr as ?var)" to an Extend
for c in q.groupby.condition:
if isinstance(c, CompValue) and c.name == 'GroupAs':
M = Extend(M, c.expr, c.var)
c = c.var
conditions.append(c)
M = Group(p=M, expr=conditions)
aggregate = True
elif traverse(q.having, _hasAggregate, complete=False) or \
traverse(q.orderby, _hasAggregate, complete=False) or \
any(traverse(x.expr, _hasAggregate, complete=False)
for x in q.projection or [] if x.evar):
# if any aggregate is used, implicit group by
M = Group(p=M)
aggregate = True
if aggregate:
M, E = translateAggregates(q, M)
else:
E = []
# HAVING
if q.having:
M = Filter(expr=and_(*q.having.condition), p=M)
# VALUES
if q.valuesClause:
M = Join(p1=M, p2=ToMultiSet(translateValues(q.valuesClause)))
if not q.projection:
# select *
PV = list(VS)
else:
PV = list()
for v in q.projection:
if v.var:
if v not in PV:
PV.append(v.var)
elif v.evar:
if v not in PV:
PV.append(v.evar)
E.append((v.expr, v.evar))
else:
raise Exception("I expected a var or evar here!")
for e, v in E:
M = Extend(M, e, v)
# ORDER BY
if q.orderby:
M = OrderBy(M, [CompValue('OrderCondition', expr=c.expr,
order=c.order) for c in q.orderby.condition])
# PROJECT
M = Project(M, PV)
if q.modifier:
if q.modifier == 'DISTINCT':
M = CompValue('Distinct', p=M)
elif q.modifier == 'REDUCED':
M = CompValue('Reduced', p=M)
if q.limitoffset:
offset = 0
if q.limitoffset.offset != None:
offset = q.limitoffset.offset.toPython()
if q.limitoffset.limit != None:
M = CompValue('Slice', p=M, start=offset,
length=q.limitoffset.limit.toPython())
else:
M = CompValue('Slice', p=M, start=offset)
return M, PV
def simplify(n):
"""Remove joins to empty BGPs"""
if isinstance(n, CompValue):
if n.name == 'Join':
if n.p1.name == 'BGP' and len(n.p1.triples) == 0:
return n.p2
if n.p2.name == 'BGP' and len(n.p2.triples) == 0:
return n.p1
elif n.name == 'BGP':
n["triples"] = reorderTriples(n.triples)
return n
def analyse(n, children):
if isinstance(n, CompValue):
if n.name == 'Join':
n["lazy"] = all(children)
return False
elif n.name in ('Slice', 'Distinct'):
return False
else:
return all(children)
else:
return True
def translatePrologue(p, base, initNs=None, prologue=None):
if prologue is None:
prologue = Prologue()
prologue.base = ""
if base:
prologue.base = base
if initNs:
for k, v in initNs.iteritems():
prologue.bind(k, v)
for x in p:
if x.name == 'Base':
prologue.base = x.iri
elif x.name == 'PrefixDecl':
prologue.bind(x.prefix, prologue.absolutize(x.iri))
return prologue
def translateQuads(quads):
if quads.triples:
alltriples = triples(quads.triples)
else:
alltriples = []
allquads = collections.defaultdict(list)
if quads.quadsNotTriples:
for q in quads.quadsNotTriples:
if q.triples:
allquads[q.term] += triples(q.triples)
return alltriples, allquads
def translateUpdate1(u, prologue):
if u.name in ('Load', 'Clear', 'Drop', 'Create'):
pass # no translation needed
elif u.name in ('Add', 'Move', 'Copy'):
pass
elif u.name in ('InsertData', 'DeleteData', 'DeleteWhere'):
t, q = translateQuads(u.quads)
u["quads"] = q
u["triples"] = t
if u.name in ('DeleteWhere', 'DeleteData'):
pass # TODO: check for bnodes in triples
elif u.name == 'Modify':
if u.delete:
u.delete["triples"], u.delete[
"quads"] = translateQuads(u.delete.quads)
if u.insert:
u.insert["triples"], u.insert[
"quads"] = translateQuads(u.insert.quads)
u["where"] = translateGroupGraphPattern(u.where)
else:
raise Exception('Unknown type of update operation: %s' % u)
u.prologue = prologue
return u
def translateUpdate(q, base=None, initNs=None):
"""
Returns a list of SPARQL Update Algebra expressions
"""
res = []
prologue = None
if not q.request:
return res
for p, u in zip(q.prologue, q.request):
prologue = translatePrologue(p, base, initNs, prologue)
# absolutize/resolve prefixes
u = traverse(
u, visitPost=functools.partial(translatePName, prologue=prologue))
u = _traverse(u, _simplifyFilters)
u = traverse(u, visitPost=translatePath)
res.append(translateUpdate1(u, prologue))
return res
def translateQuery(q, base=None, initNs=None):
"""
Translate a query-parsetree to a SPARQL Algebra Expression
Return a rdflib.plugins.sparql.sparql.Query object
"""
# We get in: (prologue, query)
prologue = translatePrologue(q[0], base, initNs)
# absolutize/resolve prefixes
q[1] = traverse(
q[1], visitPost=functools.partial(translatePName, prologue=prologue))
P, PV = translate(q[1])
datasetClause = q[1].datasetClause
if q[1].name == 'ConstructQuery':
template = triples(q[1].template) if q[1].template else None
res = CompValue(q[1].name, p=P,
template=template,
datasetClause=datasetClause)
else:
res = CompValue(q[1].name, p=P, datasetClause=datasetClause, PV=PV)
res = traverse(res, visitPost=simplify)
_traverseAgg(res, visitor=analyse)
_traverseAgg(res, _addVars)
return Query(prologue, res)
def pprintAlgebra(q):
def pp(p, ind=" "):
# if isinstance(p, list):
# print "[ "
# for x in p: pp(x,ind)
# print "%s ]"%ind
# return
if not isinstance(p, CompValue):
print p
return
print "%s(" % (p.name, )
for k in p:
print "%s%s =" % (ind, k,),
pp(p[k], ind + " ")
print "%s)" % ind
try:
pp(q.algebra)
except AttributeError:
# it's update, just a list
for x in q:
pp(x)
if __name__ == '__main__':
import sys
from rdflib.plugins.sparql import parser
import os.path
if os.path.exists(sys.argv[1]):
q = file(sys.argv[1])
else:
q = sys.argv[1]
pq = parser.parseQuery(q)
print pq
tq = translateQuery(pq)
print pprintAlgebra(tq)
|
dbs/rdflib
|
rdflib/plugins/sparql/algebra.py
|
Python
|
bsd-3-clause
| 20,961
|
[
"VisIt"
] |
f284ddcfc72e33526448abf2f6914deebb4af72d4414a39f1e287640a8d84233
|
#
# Copyright 2016 The BigDL Authors.
#
# 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 shutil
from unittest import TestCase
import numpy as np
import pytest
import tensorflow as tf
from bigdl.dllib.nncontext import init_nncontext
from bigdl.orca.data import XShards
import bigdl.orca.data.pandas
from bigdl.orca.learn.tf2 import Estimator
from bigdl.orca.ray import RayContext
import ray
NUM_TRAIN_SAMPLES = 1000
NUM_TEST_SAMPLES = 400
import os
resource_path = os.path.join(
os.path.realpath(os.path.dirname(__file__)), "../../../resources")
def linear_dataset(a=2, size=1000):
x = np.random.rand(size)
y = x / 2
x = x.reshape((-1, 1))
y = y.reshape((-1, 1))
return x, y
def create_train_datasets(config, batch_size):
import tensorflow as tf
x_train, y_train = linear_dataset(size=NUM_TRAIN_SAMPLES)
train_dataset = tf.data.Dataset.from_tensor_slices((x_train, y_train))
train_dataset = train_dataset.shuffle(NUM_TRAIN_SAMPLES).batch(
batch_size)
return train_dataset
def create_test_dataset(config, batch_size):
import tensorflow as tf
x_test, y_test = linear_dataset(size=NUM_TEST_SAMPLES)
test_dataset = tf.data.Dataset.from_tensor_slices((x_test, y_test))
test_dataset = test_dataset.batch(batch_size)
return test_dataset
def simple_model(config):
import tensorflow as tf
model = tf.keras.models.Sequential([tf.keras.layers.Dense(10, input_shape=(1,)),
tf.keras.layers.Dense(1)])
return model
def compile_args(config):
import tensorflow as tf
if "lr" in config:
lr = config["lr"]
else:
lr = 1e-3
args = {
"optimizer": tf.keras.optimizers.SGD(lr),
"loss": "mean_squared_error",
"metrics": ["mean_squared_error"]
}
return args
def model_creator(config):
model = simple_model(config)
model.compile(**compile_args(config))
return model
def identity_model_creator(config):
model = tf.keras.models.Sequential([
tf.keras.layers.InputLayer(input_shape=(1)),
tf.keras.layers.Lambda(lambda x: tf.identity(x))
])
model.compile()
return model
def create_auto_shard_datasets(config, batch_size):
import tensorflow as tf
data_path = os.path.join(resource_path, "orca/learn/test_auto_shard/*.csv")
dataset = tf.data.Dataset.list_files(data_path)
dataset = dataset.interleave(lambda x: tf.data.TextLineDataset(x))
dataset = dataset.map(lambda x: tf.strings.to_number(x))
dataset = dataset.map(lambda x: (x, x))
dataset = dataset.batch(batch_size)
return dataset
def create_auto_shard_model(config):
import tensorflow as tf
model = tf.keras.models.Sequential([
tf.keras.layers.Lambda(lambda x: tf.identity(x))
])
return model
def create_auto_shard_compile_args(config):
import tensorflow as tf
def loss_func(y1, y2):
return tf.abs(y1[0] - y1[1]) + tf.abs(y2[0] - y2[1])
args = {
"optimizer": tf.keras.optimizers.SGD(lr=0.0),
"loss": loss_func,
}
return args
def auto_shard_model_creator(config):
model = create_auto_shard_model(config)
model.compile(**create_auto_shard_compile_args(config))
return model
class LRChecker(tf.keras.callbacks.Callback):
def __init__(self, *args):
super(LRChecker, self).__init__(*args)
self.warmup_lr = [0.16, 0.22, 0.28, 0.34, 0.4]
def on_epoch_end(self, epoch, logs=None):
current_lr = tf.keras.backend.get_value(self.model.optimizer.lr)
print("epoch {} current lr is {}".format(epoch, current_lr))
if epoch < 5:
assert abs(current_lr - self.warmup_lr[epoch]) < 1e-5
elif 5 <= epoch < 10:
assert abs(current_lr - 0.4) < 1e-5
elif 10 <= epoch < 15:
assert abs(current_lr - 0.04) < 1e-5
elif 15 <= epoch < 20:
assert abs(current_lr - 0.004) < 1e-5
else:
assert abs(current_lr - 0.0004) < 1e-5
class TestTFRayEstimator(TestCase):
def impl_test_fit_and_evaluate(self, backend):
import tensorflow as tf
ray_ctx = RayContext.get()
batch_size = 32
global_batch_size = batch_size * ray_ctx.num_ray_nodes
if backend == "horovod":
trainer = Estimator.from_keras(
model_creator=simple_model,
compile_args_creator=compile_args,
verbose=True,
config=None,
backend=backend)
else:
trainer = Estimator.from_keras(model_creator=model_creator,
verbose=True,
config=None,
backend=backend,
workers_per_node=2)
# model baseline performance
start_stats = trainer.evaluate(create_test_dataset, batch_size=global_batch_size,
num_steps=NUM_TEST_SAMPLES // global_batch_size)
print(start_stats)
def scheduler(epoch):
if epoch < 2:
return 0.001
else:
return 0.001 * tf.math.exp(0.1 * (2 - epoch))
scheduler = tf.keras.callbacks.LearningRateScheduler(scheduler, verbose=1)
# train for 2 epochs
trainer.fit(create_train_datasets, epochs=2, batch_size=global_batch_size,
steps_per_epoch=10, callbacks=[scheduler])
trainer.fit(create_train_datasets, epochs=2, batch_size=global_batch_size,
steps_per_epoch=10, callbacks=[scheduler])
# model performance after training (should improve)
end_stats = trainer.evaluate(create_test_dataset, batch_size=global_batch_size,
num_steps=NUM_TEST_SAMPLES // global_batch_size)
print(end_stats)
# sanity check that training worked
dloss = end_stats["validation_loss"] - start_stats["validation_loss"]
dmse = (end_stats["validation_mean_squared_error"] -
start_stats["validation_mean_squared_error"])
print(f"dLoss: {dloss}, dMSE: {dmse}")
assert dloss < 0 and dmse < 0, "training sanity check failed. loss increased!"
def test_fit_and_evaluate_tf(self):
self.impl_test_fit_and_evaluate(backend="tf2")
def test_fit_and_evaluate_horovod(self):
self.impl_test_fit_and_evaluate(backend="horovod")
def test_auto_shard_tf(self):
# file 1 contains all 0s, file 2 contains all 1s
# If shard by files, then each model will
# see the same records in the same batch.
# If shard by records, then each batch
# will have different records.
# The loss func is constructed such that
# the former case will return 0, and the latter
# case will return non-zero.
ray_ctx = RayContext.get()
trainer = Estimator.from_keras(
model_creator=auto_shard_model_creator,
verbose=True,
backend="tf2", workers_per_node=2)
stats = trainer.fit(create_auto_shard_datasets, epochs=1, batch_size=4, steps_per_epoch=2)
assert stats["train_loss"] == 0.0
def test_auto_shard_horovod(self):
# file 1 contains all 0s, file 2 contains all 1s
# If shard by files, then each model will
# see the same records in the same batch.
# If shard by records, then each batch
# will have different records.
# The loss func is constructed such that
# the former case will return 0, and the latter
# case will return non-zero.
ray_ctx = RayContext.get()
trainer = Estimator.from_keras(
model_creator=create_auto_shard_model,
compile_args_creator=create_auto_shard_compile_args,
verbose=True,
backend="horovod", workers_per_node=2)
stats = trainer.fit(create_auto_shard_datasets, epochs=1, batch_size=4, steps_per_epoch=2)
assert stats["train_loss"] == 0.0
# this needs horovod >= 0.19.2
def test_horovod_learning_rate_schedule(self):
import horovod
major, minor, patch = horovod.__version__.split(".")
larger_major = int(major) > 0
larger_minor = int(major) == 0 and int(minor) > 19
larger_patch = int(major) == 0 and int(minor) == 19 and int(patch) >= 2
if larger_major or larger_minor or larger_patch:
ray_ctx = RayContext.get()
batch_size = 32
workers_per_node = 4
global_batch_size = batch_size * workers_per_node
config = {
"lr": 0.8
}
trainer = Estimator.from_keras(
model_creator=simple_model,
compile_args_creator=compile_args,
verbose=True,
config=config,
backend="horovod", workers_per_node=workers_per_node)
import horovod.tensorflow.keras as hvd
callbacks = [
hvd.callbacks.LearningRateWarmupCallback(warmup_epochs=5, initial_lr=0.4,
verbose=True),
hvd.callbacks.LearningRateScheduleCallback(start_epoch=5, end_epoch=10,
multiplier=1., initial_lr=0.4),
hvd.callbacks.LearningRateScheduleCallback(start_epoch=10, end_epoch=15,
multiplier=1e-1, initial_lr=0.4),
hvd.callbacks.LearningRateScheduleCallback(start_epoch=15, end_epoch=20,
multiplier=1e-2, initial_lr=0.4),
hvd.callbacks.LearningRateScheduleCallback(start_epoch=20, multiplier=1e-3,
initial_lr=0.4),
LRChecker()
]
for i in range(30):
trainer.fit(create_train_datasets, epochs=1, batch_size=global_batch_size,
callbacks=callbacks)
else:
# skip tests in horovod lower version
pass
def test_sparkxshards(self):
train_data_shard = XShards.partition({"x": np.random.randn(100, 1),
"y": np.random.randint(0, 1, size=(100))})
config = {
"lr": 0.8
}
trainer = Estimator.from_keras(
model_creator=model_creator,
verbose=True,
config=config,
workers_per_node=2)
trainer.fit(train_data_shard, epochs=1, batch_size=4, steps_per_epoch=25)
trainer.evaluate(train_data_shard, batch_size=4, num_steps=25)
def test_dataframe(self):
sc = init_nncontext()
rdd = sc.range(0, 10)
from pyspark.sql import SparkSession
spark = SparkSession(sc)
from pyspark.ml.linalg import DenseVector
df = rdd.map(lambda x: (DenseVector(np.random.randn(1,).astype(np.float)),
int(np.random.randint(0, 1, size=())))).toDF(["feature", "label"])
config = {
"lr": 0.8
}
trainer = Estimator.from_keras(
model_creator=model_creator,
verbose=True,
config=config,
workers_per_node=2)
trainer.fit(df, epochs=1, batch_size=4, steps_per_epoch=25,
feature_cols=["feature"],
label_cols=["label"])
trainer.evaluate(df, batch_size=4, num_steps=25, feature_cols=["feature"],
label_cols=["label"])
trainer.predict(df, feature_cols=["feature"]).collect()
def test_dataframe_with_empty_partition(self):
from bigdl.orca import OrcaContext
sc = OrcaContext.get_spark_context()
rdd = sc.range(0, 10)
rdd_with_empty = rdd.repartition(4).\
mapPartitionsWithIndex(lambda idx, part: [] if idx == 0 else part)
from pyspark.sql import SparkSession
spark = SparkSession(sc)
from pyspark.ml.linalg import DenseVector
df = rdd_with_empty.map(lambda x: (DenseVector(np.random.randn(1,).astype(np.float)),
int(np.random.randint(0, 1, size=()))))\
.toDF(["feature", "label"])
config = {
"lr": 0.8
}
trainer = Estimator.from_keras(
model_creator=model_creator,
verbose=True,
config=config,
workers_per_node=2)
trainer.fit(df, epochs=1, batch_size=4, steps_per_epoch=25,
feature_cols=["feature"],
label_cols=["label"])
trainer.evaluate(df, batch_size=4, num_steps=25, feature_cols=["feature"],
label_cols=["label"])
trainer.predict(df, feature_cols=["feature"]).collect()
def test_pandas_dataframe(self):
def model_creator(config):
import tensorflow as tf
input1 = tf.keras.layers.Input(shape=(1,))
input2 = tf.keras.layers.Input(shape=(1,))
concatenation = tf.concat([input1, input2], axis=-1)
outputs = tf.keras.layers.Dense(units=1, activation='softmax')(concatenation)
model = tf.keras.Model(inputs=[input1, input2], outputs=outputs)
model.compile(**compile_args(config))
return model
file_path = os.path.join(resource_path, "orca/learn/ncf2.csv")
train_data_shard = bigdl.orca.data.pandas.read_csv(file_path)
config = {
"lr": 0.8
}
trainer = Estimator.from_keras(
model_creator=model_creator,
verbose=True,
config=config,
workers_per_node=1)
trainer.fit(train_data_shard, epochs=1, batch_size=4, steps_per_epoch=25,
feature_cols=["user", "item"],
label_cols=["label"])
trainer.evaluate(train_data_shard, batch_size=4, num_steps=25,
feature_cols=["user", "item"], label_cols=["label"])
trainer.predict(train_data_shard, feature_cols=["user", "item"]).collect()
def test_dataframe_shard_size(self):
from bigdl.orca import OrcaContext
OrcaContext._shard_size = 3
sc = init_nncontext()
rdd = sc.range(0, 10)
from pyspark.sql import SparkSession
spark = SparkSession(sc)
from pyspark.ml.linalg import DenseVector
df = rdd.map(lambda x: (DenseVector(np.random.randn(1,).astype(np.float)),
int(np.random.randint(0, 1, size=())))).toDF(["feature", "label"])
config = {
"lr": 0.8
}
trainer = Estimator.from_keras(
model_creator=model_creator,
verbose=True,
config=config,
workers_per_node=2)
trainer.fit(df, epochs=1, batch_size=4, steps_per_epoch=25,
feature_cols=["feature"],
label_cols=["label"])
trainer.evaluate(df, batch_size=4, num_steps=25, feature_cols=["feature"],
label_cols=["label"])
trainer.predict(df, feature_cols=["feature"]).collect()
OrcaContext._shard_size = None
def test_partition_num_less_than_workers(self):
sc = init_nncontext()
rdd = sc.range(200, numSlices=1)
assert rdd.getNumPartitions() == 1
from pyspark.sql import SparkSession
spark = SparkSession(sc)
from pyspark.ml.linalg import DenseVector
df = rdd.map(lambda x: (DenseVector(np.random.randn(1,).astype(np.float)),
int(np.random.randint(0, 1, size=())))).toDF(["feature", "label"])
config = {
"lr": 0.8
}
trainer = Estimator.from_keras(
model_creator=model_creator,
verbose=True,
config=config,
workers_per_node=2)
assert df.rdd.getNumPartitions() < trainer.num_workers
trainer.fit(df, epochs=1, batch_size=4, steps_per_epoch=25,
validation_data=df, validation_steps=1,
feature_cols=["feature"],
label_cols=["label"])
trainer.evaluate(df, batch_size=4, num_steps=25, feature_cols=["feature"],
label_cols=["label"])
trainer.predict(df, feature_cols=["feature"]).collect()
def test_num_part_data_diff_val_data(self):
sc = init_nncontext()
rdd = sc.range(200, numSlices=10)
val_rdd = sc.range(60, numSlices=8)
from pyspark.sql import SparkSession
spark = SparkSession(sc)
from pyspark.ml.linalg import DenseVector
df = rdd.map(lambda x: (DenseVector(np.random.randn(1,).astype(np.float)),
int(np.random.randint(0, 1, size=())))).toDF(["feature", "label"])
val_df = val_rdd.map(lambda x: (DenseVector(np.random.randn(1,).astype(np.float)),
int(np.random.randint(0, 1, size=()))))\
.toDF(["feature", "label"])
config = {
"lr": 0.8
}
trainer = Estimator.from_keras(
model_creator=model_creator,
verbose=True,
config=config,
workers_per_node=2)
assert df.rdd.getNumPartitions() > trainer.num_workers
assert df.rdd.getNumPartitions() != val_df.rdd.getNumPartitions()
trainer.fit(df, epochs=1, batch_size=4, steps_per_epoch=25,
validation_data=val_df, validation_steps=1,
feature_cols=["feature"],
label_cols=["label"])
def test_dataframe_predict(self):
sc = init_nncontext()
rdd = sc.parallelize(range(20))
df = rdd.map(lambda x: ([float(x)] * 5,
[int(np.random.randint(0, 2, size=()))])
).toDF(["feature", "label"])
estimator = Estimator.from_keras(
model_creator=identity_model_creator,
verbose=True,
config={},
workers_per_node=2)
result = estimator.predict(df, batch_size=4,
feature_cols=["feature"])
expr = "sum(cast(feature <> to_array(prediction) as int)) as error"
assert result.selectExpr(expr).first()["error"] == 0
def test_sparkxshards_with_inbalanced_data(self):
train_data_shard = XShards.partition({"x": np.random.randn(100, 1),
"y": np.random.randint(0, 1, size=(100))})
def random_pad(data):
import numpy as np
import random
times = random.randint(1, 10)
data["x"] = np.concatenate([data["x"]] * times)
data["y"] = np.concatenate([data["y"]] * times)
return data
train_data_shard = train_data_shard.transform_shard(random_pad)
config = {
"lr": 0.8
}
trainer = Estimator.from_keras(
model_creator=model_creator,
verbose=True,
config=config,
workers_per_node=2)
trainer.fit(train_data_shard, epochs=1, batch_size=4, steps_per_epoch=25)
trainer.evaluate(train_data_shard, batch_size=4, num_steps=25)
def test_predict_xshards(self):
train_data_shard = XShards.partition({"x": np.random.randn(100, 1),
"y": np.random.randint(0, 1, size=(100,))})
expected = train_data_shard.collect()
expected = [shard["x"] for shard in expected]
for x in expected:
print(x.shape)
expected = np.concatenate(expected)
config = {
}
trainer = Estimator.from_keras(
model_creator=identity_model_creator,
verbose=True,
config=config,
workers_per_node=2)
result_shards = trainer.predict(train_data_shard, batch_size=10).collect()
result = [shard["prediction"] for shard in result_shards]
expected_result = [shard["x"] for shard in result_shards]
result = np.concatenate(result)
assert np.allclose(expected, result)
def test_save_and_load(self):
def model_creator(config):
import tensorflow as tf
model = tf.keras.Sequential([
tf.keras.layers.Conv2D(64, kernel_size=(3, 3), strides=(1, 1), activation='relu',
padding='valid'),
tf.keras.layers.BatchNormalization(),
tf.keras.layers.MaxPooling2D(pool_size=(2, 2), strides=(2, 2), padding='valid'),
tf.keras.layers.Conv2D(64, kernel_size=(3, 3), strides=(1, 1), activation='relu',
padding='valid'),
tf.keras.layers.MaxPooling2D(pool_size=(2, 2), strides=(2, 2), padding='valid'),
tf.keras.layers.Flatten(),
tf.keras.layers.Dense(10, activation='softmax')]
)
model.compile(optimizer=tf.keras.optimizers.RMSprop(),
loss='sparse_categorical_crossentropy',
metrics=['accuracy'])
return model
def train_data_creator(config, batch_size):
dataset = tf.data.Dataset.from_tensor_slices((np.random.randn(100, 28, 28, 3),
np.random.randint(0, 10, (100, 1))))
dataset = dataset.repeat()
dataset = dataset.shuffle(1000)
dataset = dataset.batch(batch_size)
return dataset
batch_size = 320
try:
est = Estimator.from_keras(model_creator=model_creator, workers_per_node=2)
history = est.fit(train_data_creator,
epochs=1,
batch_size=batch_size,
steps_per_epoch=5)
print("start saving")
est.save("/tmp/cifar10_keras.ckpt")
est.load("/tmp/cifar10_keras.ckpt")
print("save success")
finally:
os.remove("/tmp/cifar10_keras.ckpt")
def test_string_input(self):
def model_creator(config):
import tensorflow as tf
vectorize_layer = tf.keras.layers.experimental.preprocessing.TextVectorization(
max_tokens=10, output_mode='int', output_sequence_length=4)
model = tf.keras.models.Sequential()
model.add(tf.keras.Input(shape=(1,), dtype=tf.string))
model.add(vectorize_layer)
return model
from bigdl.orca import OrcaContext
from pyspark.sql.types import StructType, StructField, StringType
spark = OrcaContext.get_spark_session()
schema = StructType([StructField("input", StringType(), True)])
input_data = [["foo qux bar"], ["qux baz"]]
input_df = spark.createDataFrame(input_data, schema)
estimator = Estimator.from_keras(model_creator=model_creator)
output_df = estimator.predict(input_df, batch_size=1, feature_cols=["input"])
output = output_df.collect()
print(output)
def test_array_string_input(self):
def model_creator(config):
import tensorflow as tf
model = tf.keras.models.Sequential([
tf.keras.Input(shape=(None,), dtype=tf.string),
tf.keras.layers.experimental.preprocessing.StringLookup(
vocabulary=config["vocabulary"]
)
])
return model
import itertools
from bigdl.orca import OrcaContext
from pyspark.sql.types import StructType, StructField, StringType, IntegerType, ArrayType
spark = OrcaContext.get_spark_session()
schema = StructType([
StructField("id", IntegerType(), True),
StructField("input", ArrayType(StringType(), True), True)
])
input_data = [(0, ["foo", "qux", "bar"]), (1, ["qux", "baz", "baz"])]
input_df = spark.createDataFrame(input_data, schema)
string_data = [row["input"] for row in input_df.select("input").distinct().collect()]
vocabulary = list(set(itertools.chain(*string_data)))
config = {"vocabulary": vocabulary}
estimator = Estimator.from_keras(model_creator=model_creator, config=config)
output_df = estimator.predict(input_df, batch_size=1, feature_cols=["input"])
output = output_df.collect()
print(output)
if __name__ == "__main__":
pytest.main([__file__])
|
intel-analytics/BigDL
|
python/orca/test/bigdl/orca/learn/ray/tf/test_tf_ray_estimator.py
|
Python
|
apache-2.0
| 25,326
|
[
"ORCA"
] |
dc1ce54805722915f8fc696bf6c482b7661ba673b2cfc9ca7fd2bb18a43dd7a6
|
# modified mexican hat wavelet test.py
# spectral analysis for RADAR and WRF patterns
# NO plotting - just saving the results: LOG-response spectra for each sigma and max-LOG response numerical spectra
# pre-convolved with a gaussian filter of sigma=10
import os, shutil
import time, datetime
import pickle
import numpy as np
from scipy import signal, ndimage
import matplotlib.pyplot as plt
from armor import defaultParameters as dp
from armor import pattern
from armor import objects4 as ob
#from armor import misc as ms
dbz = pattern.DBZ
kongreywrf = ob.kongreywrf
kongreywrf.fix()
kongrey = ob.kongrey
monsoon = ob.monsoon
monsoon.list= [v for v in monsoon.list if '20120612' in v.dataTime] #fix
march2014 = ob.march2014
march2014wrf11 = ob.march2014wrf11
march2014wrf12 = ob.march2014wrf12
march2014wrf = ob.march2014wrf
march2014wrf.fix()
################################################################################
# hack
#kongrey.list = [v for v in kongrey.list if v.dataTime>="20130828.2320"]
################################################################################
# parameters
sigmaPreprocessing = 20 # sigma for preprocessing, 2014-05-15
testName = "modifiedMexicanHatTest15_march2014_sigmaPreprocessing" + str(sigmaPreprocessing)
sigmas = [1, 2, 4, 5, 8 ,10 ,16, 20, 32, 40, 64, 80, 128, 160, 256,]
dbzstreams = [march2014]
sigmaPower=0
scaleSpacePower=0 #2014-05-14
testScriptsFolder = dp.root + 'python/armor/tests/'
timeString = str(int(time.time()))
outputFolder = dp.root + 'labLogs/%d-%d-%d-%s/' % \
(time.localtime().tm_year, time.localtime().tm_mon, time.localtime().tm_mday, testName)
if not os.path.exists(outputFolder):
os.makedirs(outputFolder)
shutil.copyfile(testScriptsFolder+testName+".py", outputFolder+ timeString + testName+".py")
# end parameters
################################################################################
summaryFile = open(outputFolder + timeString + "summary.txt", 'a')
for ds in dbzstreams:
summaryFile.write("\n===============================================================\n\n\n")
streamMean = 0.
dbzCount = 0
#hack
#streamMean = np.array([135992.57472004235, 47133.59049120619, 16685.039217734946, 11814.043851969862, 5621.567482638702, 3943.2774923729303, 1920.246102887001, 1399.7855335686243, 760.055614122099, 575.3654495432361, 322.26668666562375, 243.49842951291757, 120.54647935045809, 79.05741086463254, 26.38971066782135])
#dbzCount = 140
for a in ds:
print "-------------------------------------------------"
print testName
print
print a.name
a.load()
a.setThreshold(0)
a.saveImage(imagePath=outputFolder+a.name+".png")
L = []
a.responseImages = [] #2014-05-02
#for sigma in [1, 2, 4, 8 ,16, 32, 64, 128, 256, 512]:
for sigma in sigmas:
print "sigma:", sigma
a.load()
a.setThreshold(0)
arr0 = a.matrix
#####################################################################
arr0 = ndimage.filters.gaussian_filter(arr0, sigma=sigmaPreprocessing) # <-- 2014-05-15
#####################################################################
#arr1 = signal.convolve2d(arr0, mask_i, mode='same', boundary='fill')
#arr1 = ndimage.filters.gaussian_laplace(arr0, sigma=sigma, mode="constant", cval=0.0) #2014-05-07
#arr1 = ndimage.filters.gaussian_laplace(arr0, sigma=sigma, mode="constant", cval=0.0) * sigma**2 #2014-04-29
arr1 = ndimage.filters.gaussian_laplace(arr0, sigma=sigma, mode="constant", cval=0.0) * sigma**scaleSpacePower #2014-05-14
a1 = dbz(matrix=arr1.real, name=a.name + "_" + testName + "_sigma" + str(sigma))
L.append({ 'sigma' : sigma,
'a1' : a1,
'abssum1': abs(a1.matrix).sum(),
'sum1' : a1.matrix.sum(),
})
print "abs sum", abs(a1.matrix.sum())
#a1.show()
#a2.show()
plt.close()
#a1.histogram(display=False, outputPath=outputFolder+a1.name+"_histogram.png")
###############################################################################
# computing the spectrum, i.e. sigma for which the LOG has max response
# 2014-05-02
a.responseImages.append({'sigma' : sigma,
'matrix' : arr1 * sigma**2,
})
pickle.dump(a.responseImages, open(outputFolder+a.name+"responseImagesList.pydump",'w'))
a_LOGspec = dbz(name= a.name + "Laplacian-of-Gaussian_numerical_spectrum",
imagePath=outputFolder+a1.name+"_LOGspec.png",
outputPath = outputFolder+a1.name+"_LOGspec.dat",
cmap = 'jet',
)
a.responseImages = np.dstack([v['matrix'] for v in a.responseImages])
#print 'shape:', a.responseImages.shape #debug
a.responseMax = a.responseImages.max(axis=2) # the deepest dimension
a_LOGspec.matrix = np.zeros(a.matrix.shape)
for count, sigma in enumerate(sigmas):
a_LOGspec.matrix += sigma * (a.responseMax == a.responseImages[:,:,count])
a_LOGspec.vmin = a_LOGspec.matrix.min()
a_LOGspec.vmax = a_LOGspec.matrix.max()
print "saving to:", a_LOGspec.imagePath
#a_LOGspec.saveImage()
print a_LOGspec.outputPath
#a_LOGspec.saveMatrix()
#a_LOGspec.histogram(display=False, outputPath=outputFolder+a1.name+"_LOGspec_histogram.png")
pickle.dump(a_LOGspec, open(outputFolder+ a_LOGspec.name + ".pydump","w"))
# end computing the sigma for which the LOG has max response
# 2014-05-02
##############################################################################
#pickle.dump(L, open(outputFolder+ a.name +'_test_results.pydump','w')) # no need to dump if test is easy
sigmas = np.array([v['sigma'] for v in L])
y1 = [v['abssum1'] for v in L]
plt.close()
plt.plot(sigmas,y1)
plt.title(a1.name+ '\n absolute values against sigma')
plt.savefig(outputFolder+a1.name+"-spectrum-histogram.png")
plt.close()
# now update the mean
streamMeanUpdate = np.array([v['abssum1'] for v in L])
dbzCount += 1
streamMean = 1.* ((streamMean*(dbzCount -1)) + streamMeanUpdate ) / dbzCount
print "Stream Count and Mean so far:", dbzCount, streamMean
# now save the mean and the plot
summaryText = '\n---------------------------------------\n'
summaryText += str(int(time.time())) + '\n'
summaryText += "dbzStream Name: " + ds.name + '\n'
summaryText += "dbzCount:\t" + str(dbzCount) + '\n'
summaryText +="sigma=\t\t" + str(sigmas.tolist()) + '\n'
summaryText += "streamMean=\t" + str(streamMean.tolist()) +'\n'
print summaryText
print "saving..."
# release the memory
a.matrix = np.array([0])
summaryFile.write(summaryText)
plt.close()
plt.plot(sigmas, streamMean* (sigmas**sigmaPower))
plt.title(ds.name + '- average laplacian-of-gaussian numerical spectrum\n' +\
'for ' +str(dbzCount) + ' DBZ patterns\n' +\
'suppressed by a factor of sigma^' + str(sigmaPower) )
plt.savefig(outputFolder + ds.name + "_average_LoG_numerical_spectrum.png")
plt.close()
summaryFile.close()
|
yaukwankiu/armor
|
tests/modifiedMexicanHatTest15_march2014_sigmaPreprocessing20.py
|
Python
|
cc0-1.0
| 7,833
|
[
"Gaussian"
] |
84afd4822ebf7fc765d3bb4d5d270e54f0e369559b54524fd74be2740060ccf8
|
# This file is generated by /afs/bx.psu.edu/home/nate/galaxy/py27/scripts/scramble/build/py2.7-linux-x86_64-ucs4/numpy/scramble.py
# It contains system_info results at the time of building this package.
__all__ = ["get_info","show"]
blas_info={}
lapack_info={}
atlas_threads_info={}
blas_src_info={}
blas_opt_info={}
lapack_src_info={}
atlas_blas_threads_info={}
lapack_opt_info={}
atlas_info={}
lapack_mkl_info={}
blas_mkl_info={}
atlas_blas_info={}
mkl_info={}
def get_info(name):
g = globals()
return g.get(name, g.get(name + "_info", {}))
def show():
for name,info_dict in globals().items():
if name[0] == "_" or type(info_dict) is not type({}): continue
print(name + ":")
if not info_dict:
print(" NOT AVAILABLE")
for k,v in info_dict.items():
v = str(v)
if k == "sources" and len(v) > 200:
v = v[:60] + " ...\n... " + v[-60:]
print(" %s = %s" % (k,v))
|
mikel-egana-aranguren/SADI-Galaxy-Docker
|
galaxy-dist/eggs/numpy-1.6.0-py2.7-linux-x86_64-ucs4.egg/numpy/distutils/__config__.py
|
Python
|
gpl-3.0
| 977
|
[
"Galaxy"
] |
0d4cc6a7d25cbda7bdad50424900f040e4c63a3eac8537cc70409720fa06f822
|
#
# MuPIF: Multi-Physics Integration Framework
# Copyright (C) 2010-2015 Borek Patzak
#
# Czech Technical University, Faculty of Civil Engineering,
# Department of Structural Mechanics, 166 29 Prague, Czech Republic
#
# This library 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 2.1 of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this library; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor,
# Boston, MA 02110-1301 USA
#
from __future__ import annotations
from . import cell
from . import bbox
from . import apierror
from . import mupifobject
from .dataid import DataID
from . import cellgeometrytype
from . import mesh
from . import mupifquantity
from .units import Quantity, Unit
import meshio
import sys
import pydantic
import typing
from numpy import array, arange, random, zeros
import numpy
import numpy as np
import copy
import Pyro5
from enum import IntEnum
import pydantic
import pickle
import logging
from .units import Unit
log = logging.getLogger()
# debug flag
debug = 0
class FieldType(IntEnum):
"""
Represent the supported values of FieldType, i.e. FT_vertexBased or FT_cellBased.
"""
FT_vertexBased = 1
FT_cellBased = 2
@Pyro5.api.expose
class Field(mupifquantity.MupifQuantity):
"""
Representation of field. Field is a scalar, vector, or tensorial
quantity defined on a spatial domain. The field, however is assumed
to be fixed at certain time. The field can be evaluated in any spatial point
belonging to underlying domain.
Derived classes will implement fields defined on common discretizations,
like fields defined on structured/unstructured FE meshes, FD grids, etc.
.. automethod:: __init__
.. automethod:: _evaluate
"""
#: Instance of a Mesh class representing the underlying discretization.
mesh: mesh.Mesh
#: Field type (displacement, strain, temperature ...)
fieldID: DataID
#: Time associated with field values
# (setting the default here results in pydatic trying __bool__ on Quantity, resulting in astropy warning... hence, leave it without the default)
time: Quantity
#: whether the field is vertex-based or cell-based
fieldType: FieldType = FieldType.FT_vertexBased
def __init__(self, **kw):
super().__init__(**kw) # this calls the real ctor
# fix zero values
if 1:
if len(self.quantity) == 0:
if self.fieldType == FieldType.FT_vertexBased:
ncomp = self.mesh.getNumberOfVertices()
else:
ncomp = self.mesh.getNumberOfCells()
self.quantity = Quantity(value=np.zeros((ncomp, self.valueType.getNumberOfComponents())), unit=self.quantity.unit)
# add some extra metadata
self.updateMetadata({
'Units': self.getUnit().to_string(),
'Type': 'mupif.field.Field',
'Type_ID': str(self.fieldID),
'FieldType': str(self.fieldType),
'ValueType': str(self.valueType)
})
def setRecord(self, componentID, value):
"""
Sets the value associated with a given component (vertex or cell).
:param int componentID: An identifier of a component: vertexID or cellID
:param tuple value: Value to be set for a given component, should have the same units as receiver
"""
self.quantity.value[componentID] = value
def getRecord(self, componentID):
"""Return value in one point (cell, vertex or similar)"""
return self.quantity.value[componentID]
def getRecordQuantity(self, componentID):
"""Return value in one point (cell, vertex or similar)"""
return self.quantity[componentID]
def getRecordSize(self):
"""
Return the number of scalars per value, depending on :obj:`valueType` passed when constructing the instance.
:return: number of scalars (1,3,9 respectively for scalar, vector, tensor)
:rtype: int
"""
return self.valueType.getNumberOfComponents()
def getMesh(self):
"""
Obtain mesh.
:return: Returns a mesh of underlying discretization
:rtype: mesh.Mesh
"""
return self.mesh
def getFieldID(self):
"""
Returns DataID, e.g. FID_Displacement, FID_Temperature.
:return: Returns field ID
:rtype: DataID
"""
return self.fieldID
def getFieldIDName(self):
"""
Returns name of the field.
:return: Returns fieldID name
:rtype: string
"""
return self.fieldID.name
def getFieldType(self):
"""
Returns receiver field type (values specified as vertex or cell values)
:return: Returns fieldType id
:rtype: FieldType
"""
return self.fieldType
def getTime(self):
"""
Get time of the field.
:return: Time of field data
:rtype: units.Quantity
"""
return self.time
@pydantic.validate_arguments
def evaluate(self,
positions: typing.Union[
typing.List[typing.Tuple[float, float, float]], # list of 3d coords
typing.List[typing.Tuple[float, float]], # list of 2d coords
typing.Tuple[float, float, float], # single 3d coords
typing.Tuple[float, float] # single 2d coord
],
eps: float = 0.0):
"""
Evaluates the receiver at given spatial position(s).
:param positions: 1D/2D/3D position vectors
:type positions: tuple, a list of tuples
:param float eps: Optional tolerance for probing whether the point belongs to a cell (should really not be used)
:return: field value(s)
:rtype: units.Quantity with given value or tuple of values
"""
# test if positions is a list of positions
if isinstance(positions, list):
ans = []
for pos in positions:
ans.append(self._evaluate(pos, eps))
return Quantity(value=ans, unit=self.getUnit())
else:
# single position passed
return Quantity(value=self._evaluate(positions, eps), unit=self.getUnit())
def _evaluate(self, position, eps):
"""
Evaluates the receiver at a single spatial position.
:param tuple position: 1D/2D/3D position vector
:param float eps: Optional tolerance
:return: field value
:rtype: tuple of doubles
.. note:: This method has some issues related to https://sourceforge.net/p/mupif/tickets/22/ .
"""
cells = self.mesh.getCellLocalizer().getItemsInBBox(bbox.BBox([c-eps for c in position], [c+eps for c in position]))
# answer=None
if len(cells):
if self.fieldType == FieldType.FT_vertexBased:
for icell in cells:
try:
if icell.containsPoint(position):
if debug:
log.debug(icell.getVertices())
try:
answer = icell.interpolate(position, [self.value[i.number] for i in icell.getVertices()])
except IndexError:
log.error('Field::evaluate failed, inconsistent data at cell %d' % icell.label)
raise
return answer
except ZeroDivisionError:
print('ZeroDivisionError?')
log.debug(icell.number)
log.debug(position)
icell.debug = 1
log.debug(icell.containsPoint(position), icell.glob2loc(position))
log.error('Field::evaluate - no source cell found for position %s' % str(position))
for icell in cells:
log.debug(icell.number)
log.debug(icell.containsPoint(position))
log.debug(icell.glob2loc(position))
else: # if (self.fieldType == FieldType.FT_vertexBased):
# in case of cell based fields do compute average of cell values containing point
# this typically happens when point is on the shared edge or vertex
count = 0
for icell in cells:
if icell.containsPoint(position):
if debug:
log.debug(icell.getVertices())
try:
tmp = self.value[icell.number]
if count == 0:
answer = list(tmp)
else:
for i in answer:
answer = [x+y for x in answer for y in tmp]
count += 1
except IndexError:
log.error('Field::evaluate failed, inconsistent data at cell %d' % icell.label)
log.error(icell.getVertices())
raise
# end loop over icells
if count == 0:
log.error('Field::evaluate - no source cell found for position %s', str(position))
# for icell in cells:
# log.debug(icell.number, icell.containsPoint(position), icell.glob2loc(position))
else:
answer = [x/count for x in answer]
return answer
else:
# no source cell found
log.error('Field::evaluate - no source cell found for position ' + str(position))
raise ValueError('Field::evaluate - no source cell found for position ' + str(position))
def getVertexValue(self, vertexID):
"""
Returns the value associated with a given vertex.
:param int vertexID: Vertex identifier
:return: The value
:rtype: units.Quantity
"""
if self.fieldType == FieldType.FT_vertexBased:
return Quantity(value=self.getRecord(vertexID), unit=self.getUnit())
else:
raise TypeError('Attempt to acces vertex value of cell based field, use evaluate instead')
def getCellValue(self, cellID):
"""
Returns the value associated with a given cell.
:param int cellID: Cell identifier
:return: The value
:rtype: units.Quantity
"""
if self.fieldType == FieldType.FT_cellBased:
return Quantity(value=self.getRecord(cellID), unit=self.getUnit())
else:
raise TypeError('Attempt to acces cell value of vertex based field, use evaluate instead')
def merge(self, field):
"""
Merges the receiver with given field together. Both fields should be on different parts of the domain (can also overlap), but should refer to same underlying discretization, otherwise unpredictable results can occur.
:param Field field: given field to merge with.
"""
# first merge meshes
mesh = copy.deepcopy(self.mesh)
mesh.merge(field.mesh)
log.debug(mesh)
# merge the field values
# some type checking first
if self.fieldType != field.fieldType:
raise TypeError("Field::merge: fieldType of receiver and parameter is different")
if self.unit != field.unit:
raise ValueError('fields have different units (merge is currently not unit-aware; this limitation will be remove with astropy.units)')
if self.fieldType == FieldType.FT_vertexBased:
vv = np.zeros_like(self.value, shape=(mesh.getNumberOfVertices(), self.getRecordSize()))
for f in self, field:
for v in range(f.mesh.getNumberOfVertices()):
vv[mesh.vertexLabel2Number(f.mesh.getVertex(v).label)] = f.getRecord(v)
else:
vv = np.zeros_like(self.value, shape=(mesh.getNumberOfCells(), self.getRecordSize()))
for f in self, field:
for v in range(f.mesh.getNumberOfCells()):
vv[mesh.cellLabel2Number(f.mesh.giveCell(v).label)] = f.getRecord(v)
self.mesh = mesh
self.value = vv
def getMartixForTensor(self, values):
"""
Reshape values to a list with 3x3 arrays. Usable for VTK export.
:param list values: List containing tuples of 9 values, e.g. [(1,2,3,4,5,6,7,8,9), (1,2,3,4,5,6,7,8,9), ...]
:return: List containing 3x3 matrices for each tensor
:rtype: list
"""
tensor = []
for i in values:
tensor.append(numpy.reshape(i, (3, 3)))
return tensor
def plot2D(self, plane="xy", title=None, fieldComponent=0, warpField=None, warpScale=0., fileName=None, show=0, colorbar='horizontal'):
"""
Plots and/or saves 2D image using a matplotlib library. Works for structured and unstructured 2D/3D fields. 2D/3D fields need to define plane. This method gives only basic viewing options, for aesthetic and more elaborated output use e.g. VTK field export with
postprocessors such as ParaView or Mayavi. Idea from https://docs.scipy.org/doc/scipy/reference/tutorial/interpolate.html#id1
:param str plane: what plane to extract from field, valid values are 'xy', 'xz', 'yz'
:param int fieldComponent: component of the field
:param bool vertex: if vertices shoud be plot as points
:param str colorBar: color bar details. Valid values '' for no colorbar, 'vertical' or 'horizontal'
:param str title: title
:param str fileName: if nonempty, a filename is written to the disk, usually png, pdf, ps, eps and svg are supported
:param bool show: if the plot should be showed
:param tuple figsize: size of canvas in inches. Affects only showing a figure. Image to a file adjust one side automatically.
:param Field warpField: vector field to wrap geometry
:param float warpScale: warping scale
:return: handle to matplotlib figure
"""
import numpy as np
import math
from scipy.interpolate import griddata
import matplotlib
import matplotlib.pyplot as plt
if 0:
try:
matplotlib.use('TkAgg') # Qt4Agg gives an empty, black window
except ImportError as e:
log.error('Skipping field2Image2D due to missing modules: %s' % e)
return None
# raise
if self.fieldType != FieldType.FT_vertexBased:
raise apierror.APIError('Only FieldType.FT_vertexBased is now supported')
mesh = self.getMesh()
numVertices = mesh.getNumberOfVertices()
indX = 0
indY = 0
elev = 0
if plane == 'xy':
indX = 0
indY = 1
elev = 2
elif plane == 'xz':
indX = 0
indY = 2
elev = 1
elif plane == 'yz':
indX = 1
indY = 2
elev = 0
# find eligible vertex points and values
vx = []
vy = []
vertexValue = []
for i in range(0, numVertices):
coords = mesh.getVertex(i).getCoordinates()
if warpField:
# coords+=warpField.evaluate(coords).getValue()*warpScale
warpVec = (warpScale * s for s in warpField.evaluate(coords).getValue())
coords = tuple(map(lambda x, y: x + y, coords, warpVec))
# print(coords)
value = self.getRecord(i)[fieldComponent]
vx.append(coords[indX])
vy.append(coords[indY])
vertexValue.append(value)
if len(vx) == 0:
log.info('No valid vertex points found, putting zeros on domain 1 x 1')
for i in range(5):
vx.append(i % 2)
vy.append(i/4.)
vertexValue.append(0)
# for i in range (0, len(vertexPoints)):
# print (vertexPoints[i], vertexValue[i])
# v = np.array(vertexPoints)
# vertexValueArr = np.array(vertexValue)
xMin = min(vx)
xMax = max(vx)
yMin = min(vy)
yMax = max(vy)
# print(xMin, xMax, yMin, yMax)
# Create the Triangulation; no triangles so Delaunay triangulation created.
triang = matplotlib.tri.Triangulation(vx, vy)
# pcolor plot.
plt.figure()
plt.gca().set_aspect('equal')
plt.tricontourf(triang, vertexValue)
if colorbar:
plt.colorbar(orientation=colorbar)
plt.tricontour(triang, vertexValue, colors='k')
plt.scatter(vx, vy, marker='o', c='k', s=1, zorder=10)
if title:
plt.title(title)
if fileName:
plt.savefig(fileName, bbox_inches='tight')
# if show:
# matPlotFig.canvas.draw()
# return plt
def field2Image2DBlock(self):
"""
Block an open window from matPlotLib. Waits until closed.
"""
import matplotlib.pyplot as plt
plt.ioff()
plt.show(block=True)
def toHdf5(self, fileName, group='component1/part1'):
r"""
Dump field to HDF5, in a simple format suitable for interoperability (TODO: document).
:param str fileName: HDF5 file
:param str group: HDF5 group the data will be saved under.
The HDF hierarchy is like this::
group
|
+--- mesh_01 {hash=25aa0aa04457}
| +--- [vertex_coords]
| +--- [cell_types]
| \--- [cell_vertices]
+--- mesh_02 {hash=17809e2b86ea}
| +--- [vertex_coords]
| +--- [cell_types]
| \--- [cell_vertices]
+--- ...
+--- field_01
| +--- -> mesh_01
| \--- [vertex_values]
+--- field_02
| +--- -> mesh_01
| \--- [vertex_values]
+--- field_03
| +--- -> mesh_02
| \--- [cell_values]
\--- ...
where ``plain`` names are HDF (sub)groups, ``[bracketed]`` names are datasets, ``{name=value}`` are HDF attributes, ``->`` prefix indicated HDF5 hardlink (transparent to the user); numerical suffixes (``_01``, ...) are auto-allocated. Mesh objects are hardlinked using HDF5 hardlinks if an identical mesh is already stored in the group, based on hexdigest of its full data.
.. note:: This method has not been tested yet. The format is subject to future changes.
"""
import h5py
hdf = h5py.File(fileName, 'a', libver='latest')
if group not in hdf:
gg = hdf.create_group(group)
else:
gg = hdf[group]
# raise IOError('Path "%s" is already used in "%s".'%(path,fileName))
def lowestUnused(trsf, predicate, start=1):
"""
Find the lowest unused index, where *predicate* is used to test for existence, and *trsf* transforms
integer (starting at *start* and incremented until unused value is found) to whatever predicate accepts
as argument. Lowest transformed value is returned.
"""
import itertools
for i in itertools.count(start=start):
t = trsf(i)
if not predicate(t):
return t
# save mesh (not saved if there already)
newgrp = lowestUnused(trsf=lambda i: 'mesh_%02d' % i, predicate=lambda t: t in gg)
mh5 = self.getMesh().asHdf5Object(parentgroup=gg, newgroup=newgrp)
if len(self.value) > 0:
fieldGrp = hdf.create_group(lowestUnused(trsf=lambda i, group=group: group+'/field_%02d' % i, predicate=lambda t: t in hdf))
fieldGrp['mesh'] = mh5
fieldGrp.attrs['fieldID'] = self.fieldID
fieldGrp.attrs['valueType'] = self.valueType
# string/bytes may not contain NULL when stored as string in HDF5
# see http://docs.h5py.org/en/2.3/strings.html
# that's why we cast to opaque type "void" and uncast using tostring before unpickling
fieldGrp.attrs['unit'] = numpy.void(pickle.dumps(self.getUnit()))
fieldGrp.attrs['time'] = numpy.void(pickle.dumps(self.time))
if self.fieldType == FieldType.FT_vertexBased:
val = numpy.empty(shape=(self.getMesh().getNumberOfVertices(), self.getRecordSize()), dtype=numpy.float64)
for vert in range(self.getMesh().getNumberOfVertices()):
val[vert] = self.getVertexValue(vert).getValue()
fieldGrp['vertex_values'] = val
elif self.fieldType == FieldType.FT_cellBased:
# raise NotImplementedError("Saving cell-based fields to HDF5 is not yet implemented.")
val = numpy.empty(shape=(self.getMesh().getNumberOfCells(), self.getRecordSize()), dtype=numpy.float64)
for cell in range(self.getMesh().getNumberOfCells()):
val[cell] = self.getCellValue(cell)
fieldGrp['cell_values'] = val
else:
raise RuntimeError("Unknown fieldType %d." % self.fieldType)
hdf.close() # necessary for windows
@staticmethod
def makeFromHdf5(fileName, group='component1/part1'):
"""
Restore Fields from HDF5 file.
:param str fileName: HDF5 file
:param str group: HDF5 group the data will be read from (IOError is raised if the group does not exist).
:return: list of new :obj:`Field` instances
:rtype: [Field,Field,...]
.. note:: This method has not been tested yet.
"""
import h5py
hdf = h5py.File(fileName, 'r', libver='latest')
grp = hdf[group]
# load mesh and field data from HDF5
meshObjs = [obj for name, obj in grp.items() if name.startswith('mesh_')]
fieldObjs = [obj for name, obj in grp.items() if name.startswith('field_')]
# construct all meshes as mupif objects
meshes = [mesh.Mesh.makeFromHdf5Object(meshObj) for meshObj in meshObjs]
# construct all fields as mupif objects
ret = []
for f in fieldObjs:
if 'vertex_values' in f:
fieldType, values = FieldType.FT_vertexBased, numpy.array(f['vertex_values'])
elif 'cell_values' in f:
fieldType, values = FieldType.FT_cellBased, numpy.array(f['cell_values'])
else:
raise ValueError("HDF5/mupif format error: unable to determine field type.")
fieldID, valueType, unit, time = DataID(f.attrs['fieldID']), f.attrs['valueType'], f.attrs['unit'].tobytes(), f.attrs['time'].tobytes()
if unit == '':
unit = None # special case, handled at saving time
else:
unit = pickle.loads(unit)
if time == '':
time = None # special case, handled at saving time
else:
time = pickle.loads(time)
meshIndex = meshObjs.index(f['mesh']) # find which mesh object this field refers to
ret.append(Field(mesh=meshes[meshIndex], fieldID=fieldID, unit=unit, time=time, valueType=valueType, value=values.tolist(), fieldType=fieldType))
hdf.close() # necessary for windows
return ret
def toMeshioMesh(self):
return Field.manyToMeshioMesh([self])
@staticmethod
# @pydantic.validate_arguments(config=dict(arbitrary_types_allowed=True))
def manyToMeshioMesh(
fields: typing.Sequence[Field]
) -> typing.List[Field]:
import meshio
if len(fields) == 0:
raise ValueError('fields must not be enpty.')
if len(set([f.getMesh() for f in fields])) != 1:
raise RuntimeError('All fields must share the same mupif.Mesh.')
msh = fields[0].getMesh()
points = msh.getVertices()
cell_data, point_data = {}, {}
# defined here: https://github.com/nschloe/meshio/blob/6a1b8c4c3db24ea788a8cac00e46c7f9d562e4d0/meshio/_common.py#L189
points, cells_list = msh.toMeshioPointsCells()
for f in fields:
assert f.getFieldType() in (FieldType.FT_vertexBased, FieldType.FT_cellBased)
ptData = (f.getFieldType() == FieldType.FT_vertexBased)
rows = (msh.getNumberOfVertices() if ptData else msh.getNumberOfCells())
cols = f.getRecordSize()
# sys.stderr.write(f'each record has {cols} components\n')
# dta=np.ndarray((rows,cols),dtype='float32')
dta=np.array([f.getRecord(row) for row in range(rows)])
(point_data if ptData else cell_data)[f.getFieldIDName()] = (dta if ptData else dta.T)
# print(f.getFieldIDName())
# print('Is point data?',ptData)
# print(f.getFieldIDName(),dta.shape)
return meshio.Mesh(points, cells_list, point_data, cell_data)
def makeFromMeshioMesh(
input: typing.Union[str,meshio.Mesh], # could also be buffer, is that useful?
unit: dict[str, Unit], # maps field name to Unit
time: Quantity = Quantity(value=0, unit='s')
) -> typing.List[Field]:
if isinstance(input, str):
input = meshio.read(input)
msh = mesh.Mesh.makeFromMeshioPointsCells(input.points, input.cells)
ret = []
for data, fieldType in (input.point_data, FieldType.FT_vertexBased), (input.cell_data, FieldType.FT_cellBased):
for fname, values in data.items():
# reshape scalar array saved as 1D
if len(values.shape) == 1:
values = np.reshape(values, (-1, 1))
ret.append(Field(
mesh=msh,
fieldID=DataID[fname],
unit=unit.get(fname,None),
time=time,
valueType=mupifquantity.ValueType.fromNumberOfComponents(values.shape[1]),
value=values.tolist(),
fieldType=fieldType
))
return ret
@staticmethod
def fromMeshioMesh(m): raise NotImplementedError('maybe later')
def _sum(self, other, sign1, sign2):
"""
Should return a new instance. As deep copy is expensive,
this operation should be avoided. Better to modify the field values.
"""
raise TypeError('Not supported')
def inUnitsOf(self, *units):
"""
Should return a new instance. As deep copy is expensive,
this operation should be avoided. Better to use convertToUnits method
performing in place conversion.
"""
raise TypeError('Not supported')
|
mupif/mupif
|
mupif/field.py
|
Python
|
lgpl-3.0
| 27,647
|
[
"Mayavi",
"ParaView",
"VTK"
] |
9ec16d92d4f2e74969fbf39adad6f5d6b370413dbf31b9466d0cfe795bc3f8fd
|
#!/usr/bin/python
# encoding: utf-8
'''
Licensed under a 3-clause BSD license.
'''
from __future__ import print_function, division
import os
# Flask imports
from flask import Flask, Blueprint, send_from_directory, request
import flask_jsglue as jsg
# Marvin imports
from brain.utils.general.general import getDbMachine
from marvin import config, log, marvindb
from marvin.web.web_utils import updateGlobalSession, check_access, configFeatures
from marvin.web.jinja_filters import jinjablue
from marvin.web.error_handlers import errors
from marvin.web.extensions import jsglue, flags, sentry, limiter, profiler, cache, login_manager, jwt
from marvin.web.settings import ProdConfig, DevConfig, CustomConfig
# Web Views
from marvin.web.controllers.index import index
from marvin.web.controllers.galaxy import galaxy
from marvin.web.controllers.search import search
from marvin.web.controllers.plate import plate
from marvin.web.controllers.images import images
from marvin.web.controllers.users import users
# API Views
from marvin.api.base import BaseView
from marvin.api.cube import CubeView
from marvin.api.maps import MapsView
from marvin.api.modelcube import ModelCubeView
from marvin.api.plate import PlateView
from marvin.api.rss import RSSView
# from marvin.api.spaxel import SpaxelView
from marvin.api.query import QueryView
from marvin.api.general import GeneralRequestsView
# ================================================================================
def create_app(debug=False, local=False, object_config=None):
# ----------------------------------
# Create App
marvin_base = os.environ.get('MARVIN_BASE', 'marvin')
app = Flask(__name__, static_url_path='/{0}/static'.format(marvin_base))
api = Blueprint("api", __name__, url_prefix='/{0}/api'.format(marvin_base))
app.debug = debug
# Add Marvin Logger
app.logger.addHandler(log)
# Turn on debug stuff in config
if app.debug is True:
sentry = None
config.use_sentry = False
config.add_github_message = False
# Find which connection to make
connection = getDbMachine()
local = (connection == 'local') or local
# ----------------------------------
# Set some other variables
config._inapp = True
url_prefix = '/marvin' if local else '/{0}'.format(marvin_base)
# ----------------------------------
# Load the appropriate Flask configuration object for debug or production
if not object_config:
if app.debug or local:
app.logger.info('Loading Development Config!')
object_config = type('Config', (DevConfig, CustomConfig), dict())
else:
app.logger.info('Loading Production Config!')
object_config = type('Config', (ProdConfig, CustomConfig), dict())
app.config.from_object(object_config)
# ------------------------------------------
# Add lib directory as a new static path
@app.route('/{0}/lib/<path:filename>'.format(marvin_base))
def lib(filename):
return send_from_directory(app.config["LIB_PATH"], filename)
# Register global session update before every request
@app.before_request
def global_update():
''' updates the global session / config '''
pass
# # check login/access status
# check_access()
# # update the version/release info in the session
# updateGlobalSession()
# ----------------------------------
# Registration
register_extensions(app, app_base=marvin_base)
register_api(app, api)
register_blueprints(app, url_prefix=url_prefix)
return app
# ================================================================================
def register_api(app, api):
''' Register the Flask API routes used '''
CubeView.register(api)
MapsView.register(api)
ModelCubeView.register(api)
PlateView.register(api)
RSSView.register(api)
# SpaxelView.register(api)
GeneralRequestsView.register(api)
QueryView.register(api)
# set the API rate limiting
limiter.limit("400/minute")(api)
# register the API blueprint
app.register_blueprint(api)
def register_extensions(app, app_base=None):
''' Register the Flask extensions used '''
jsg.JSGLUE_JS_PATH = '/{0}/jsglue.js'.format(app_base)
jsglue.init_app(app)
flags.init_app(app)
configFeatures(app)
cache.init_app(app, config=app.config)
limiter.init_app(app)
for handler in app.logger.handlers:
limiter.logger.addHandler(handler)
if app.config['RATELIMIT_ENABLED'] is False:
limiter.enabled = False
if app.config['USE_SENTRY']:
sentry.init_app(app)
# Initialize the Flask-Profiler ; see results at localhost:portnumber/app_base/flask-profiler
if app.config['USE_PROFILER']:
try:
profiler.init_app(app)
except Exception as e:
pass
# Initialize the Login Manager and JWT
login_manager.init_app(app)
login_manager.session_protection = "strong"
jwt.init_app(app)
def register_blueprints(app, url_prefix=None):
''' Register the Flask Blueprints used '''
app.register_blueprint(index, url_prefix=url_prefix)
app.register_blueprint(galaxy, url_prefix=url_prefix)
app.register_blueprint(search, url_prefix=url_prefix)
app.register_blueprint(plate, url_prefix=url_prefix)
app.register_blueprint(images, url_prefix=url_prefix)
app.register_blueprint(users, url_prefix=url_prefix)
app.register_blueprint(jinjablue)
app.register_blueprint(errors)
@login_manager.user_loader
def load_user(pk):
return marvindb.session.query(marvindb.datadb.User).get(int(pk))
|
albireox/marvin
|
python/marvin/web/__init__.py
|
Python
|
bsd-3-clause
| 5,684
|
[
"Galaxy"
] |
1aa4aab9250527e3c57c266fead2989f82911e59ec2492612578092303edd376
|
from veidt.elsie.preprocessing import Preprocessing
from pymatgen.core.spectrum import Spectrum
import numpy as np
import unittest
from copy import deepcopy
class PreprocessingTest(unittest.TestCase):
def setUp(self):
self.x_range = np.linspace(-np.pi, np.pi, 201)
self.spectrum = Spectrum(self.x_range, np.sin(self.x_range))
def test_derivative(self):
deri_preprocessing = Preprocessing(deepcopy(self.spectrum))
deri_preprocessing.first_derivative()
self.assertTrue(np.allclose(deri_preprocessing.spectrum.y, np.cos(self.x_range)[:-1], atol=2e-2))
deri_2nd_pre = Preprocessing(deepcopy(self.spectrum))
deri_2nd_pre.second_derivative()
self.assertTrue(np.allclose(deri_2nd_pre.spectrum.y, np.negative(np.sin(self.x_range))[:-2], atol=3.5e-2))
def test_weighted_derivative(self):
deri_preprocessing = Preprocessing(Spectrum(self.x_range, 2 * self.x_range))
deri_preprocessing.weighted_first_derivative()
self.assertTrue(np.allclose(deri_preprocessing.spectrum.y, 4 * self.x_range[:-1]))
deri_preprocessing = Preprocessing(Spectrum(self.x_range, 2 * self.x_range))
deri_preprocessing.weighted_second_derivative()
self.assertTrue(np.allclose(deri_preprocessing.spectrum.y, 0))
def test_normalization(self):
normal_pre = Preprocessing(Spectrum(self.x_range, np.abs(np.sin(self.x_range))))
normal_pre.intensity_normalize()
self.assertAlmostEqual(np.sum(normal_pre.spectrum.y), 1)
normal_max = Preprocessing(Spectrum(self.x_range, np.abs(np.sin(self.x_range))))
normal_max.maximum_intensity_norm()
self.assertEqual(max(normal_max.spectrum.y), 1)
vector_norm = Preprocessing(Spectrum(self.x_range, np.abs(np.sin(self.x_range))))
vector_norm.vector_norm_normalize()
self.assertTrue(np.allclose(vector_norm.spectrum.y.sum() * np.linalg.norm(np.abs(np.sin(self.x_range))),
np.abs(np.sin(self.x_range)).sum()))
area_norm = Preprocessing(Spectrum(self.x_range, np.abs(np.sin(self.x_range))))
area_norm.area_normalize()
self.assertTrue(np.allclose(np.trapz(area_norm.spectrum.y, area_norm.spectrum.x), 1))
def test_spec_preprocessing(self):
x_range = np.linspace(0, np.pi / 2, 100)
to_compare = np.cos(x_range)[:-1]
to_compare /= to_compare.sum()
spec_preprocessing = Preprocessing(Spectrum(x_range, np.sin(x_range)))
spec_preprocessing.spectrum_process(('1st_der', 'intnorm'))
self.assertAlmostEqual(spec_preprocessing.spectrum.y.sum(), 1)
self.assertTrue(np.allclose(spec_preprocessing.spectrum.y, to_compare, atol=1.5e-4))
def test_property(self):
spec_preprocessing = Preprocessing(self.spectrum)
self.assertTrue(set(spec_preprocessing.preprocessing_method) == set(
['first_derivative', 'second_derivative', 'vector_norm_normalize', 'maximum_intensity_norm',
'area_normalize',
'snv_norm', 'square_root_squashing', 'sigmoid_squashing', 'weighted_first_derivative',
'weighted_second_derivative', 'intensity_normalize']))
|
materialsvirtuallab/veidt
|
veidt/elsie/tests/test_preprocessing.py
|
Python
|
bsd-3-clause
| 3,214
|
[
"pymatgen"
] |
cb407ce1e45de2899686e86a21f7b5c04bee609e8d837775073e018f60ce6e59
|
from enum import Enum
"""
Adds an Enum for MIME_TYPE and LINKED_DATA_RESOURCE_DEFINING_NETCDF for use
in Schema.org and DCAT outputs
"""
class BaldDistributionEnum(Enum):
MIME_TYPE = "application/x-netcdf"
LINKED_DATA_RESOURCE_DEFINING_NETCDF = "http://vocab.nerc.ac.uk/collection/M01/current/NC/"
|
binary-array-ld/bald
|
lib/bald/distribution.py
|
Python
|
bsd-3-clause
| 307
|
[
"NetCDF"
] |
86500c01d3fe773e5f5286210481684492b5aa4d998d5b8dd8de3d3313433e90
|
"""
This is the file for diverse helper functions.
Copyright 2015 Markus Oberweger, ICG,
Graz University of Technology <oberweger@icg.tugraz.at>
This file is part of DeepPrior.
DeepPrior 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.
DeepPrior 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 DeepPrior. If not, see <http://www.gnu.org/licenses/>.
"""
import numpy
__author__ = "Markus Oberweger <oberweger@icg.tugraz.at>"
__copyright__ = "Copyright 2015, ICG, Graz University of Technology, Austria"
__credits__ = ["Markus Oberweger"]
__license__ = "GPL"
__version__ = "1.0"
__maintainer__ = "Markus Oberweger"
__email__ = "oberweger@icg.tugraz.at"
__status__ = "Development"
def ReLU(x):
"""
Rectified linear unit
:param x: input value
:return: max(x, 0)
"""
import theano.tensor as T
return T.nnet.relu(x, 0)
def LeakyReLU(a=0.33):
"""
Leaky rectified linear unit with different scale
:param a: scale
:return: max(x, a*x)
"""
import theano.tensor as T
def inner(x):
return T.nnet.relu(x, a)
return inner
def InvReLU(x):
"""
Rectified linear unit
:param x: input value
:return: max(x,0)
"""
import theano.tensor as T
x *= -1.
return T.switch(x < 0, 0, x)
def TruncLin(x):
"""
Truncated linear unit
:param x: input value
:return: max(min(x,1),-1)
"""
import theano.tensor as T
return T.switch(x < -1, -1, T.switch(x > 1, 1, x))
def TruncReLU(x):
"""
Truncated rectified linear unit
:param x: input value
:return: max(min(x,1),0)
"""
import theano.tensor as T
return T.switch(x < 0, 0, T.switch(x > 1, 1, x))
def SlopeLin(slope):
"""
Linear unit with different slopes
:param slope: slope of negative quadrant
:return: x if x > 0 else x/slope
"""
import theano.tensor as T
def inner(x):
return T.switch(T.gt(x, 0), x, T.true_div(x, slope))
return inner
def SlopeLinInv(slope):
"""
Truncated linear unit
:param slope: slope of negative quadrant
:return: x if x > 0 else x*slope
"""
import theano.tensor as T
def inner(x):
return T.switch(T.gt(x, 0), x, T.mul(x, slope))
return inner
def SlopeLin2(x, slope):
"""
Linear unit with different slopes
:param slope: slope of negative quadrant
:return: x if x > 0 else x/slope
"""
import theano.tensor as T
return T.switch(T.gt(x, 0), x, T.true_div(x, slope))
def huber(delta):
"""
Huber loss, robust at 0
:param delta: delta parameter
:return: loss value
"""
import theano.tensor as T
def inner(target, output):
d = target - output
a = .5 * d**2
b = delta * (T.abs_(d) - delta / 2.)
l = T.switch(T.abs_(d) <= delta, a, b)
return l
return inner
def cartesian(arrays, out=None):
"""
Generate a cartesian product of input arrays.
Parameters
----------
arrays : list of array-like
1-D arrays to form the cartesian product of.
out : ndarray
Array to place the cartesian product in.
Returns
-------
out : ndarray
2-D array of shape (M, len(arrays)) containing cartesian products
formed of input arrays.
Examples
--------
>>> cartesian(([1, 2, 3], [4, 5], [6, 7]))
array([[1, 4, 6],
[1, 4, 7],
[1, 5, 6],
[1, 5, 7],
[2, 4, 6],
[2, 4, 7],
[2, 5, 6],
[2, 5, 7],
[3, 4, 6],
[3, 4, 7],
[3, 5, 6],
[3, 5, 7]])
"""
# https://stackoverflow.com/questions/1208118/using-numpy-to-build-an-array-of-all-combinations-of-two-arrays
arrays = [numpy.asarray(x) for x in arrays]
dtype = arrays[0].dtype
n = numpy.prod([x.size for x in arrays])
if out is None:
out = numpy.zeros([n, len(arrays)], dtype=dtype)
m = n / arrays[0].size
out[:, 0] = numpy.repeat(arrays[0], m)
if arrays[1:]:
cartesian(arrays[1:], out=out[0:m, 1:])
for j in xrange(1, arrays[0].size):
out[j*m:(j+1)*m, 1:] = out[0:m, 1:]
return out
def shuffle_many_inplace(arrays, random_state=None):
"""
Shuffle given list of array consistently along first dimension
:param arrays: list of arrays
:param random_state: random state or seed
:return: None
"""
if random_state is None:
rng = numpy.random.mtrand._rand
elif isinstance(random_state, numpy.random.RandomState):
rng = random_state
else:
raise ValueError("random_state must be None or numpy RandomState")
assert all(i.shape[0] == arrays[0].shape[0] for i in arrays[1:])
# Fisher-Yates Shuffle
for oi in reversed(range(1, arrays[0].shape[0])):
ni = rng.randint(oi+1)
for a in arrays:
a[[oi, ni]] = a[[ni, oi]]
def gaussian_kernel(kernel_shape, sigma=None):
"""
Get 2D Gaussian kernel
:param kernel_shape: kernel size
:param sigma: sigma of Gaussian distribution
:return: 2D Gaussian kernel
"""
kern = numpy.zeros((kernel_shape, kernel_shape), dtype='float32')
# get sigma from kernel size
if sigma is None:
sigma = 0.3*((kernel_shape-1.)*0.5 - 1.) + 0.8
def gauss(x, y, s):
Z = 2. * numpy.pi * s ** 2.
return 1. / Z * numpy.exp(-(x ** 2. + y ** 2.) / (2. * s ** 2.))
mid = numpy.floor(kernel_shape / 2.)
for i in xrange(0, kernel_shape):
for j in xrange(0, kernel_shape):
kern[i, j] = gauss(i - mid, j - mid, sigma)
return kern / kern.sum()
|
moberweger/deep-prior
|
src/util/helpers.py
|
Python
|
gpl-3.0
| 6,072
|
[
"Gaussian"
] |
ede9244901deef938b9674d2b746c5f9e7783e50cca81d81fb65b33dea1d1ec2
|
"""
This file contains a few demo functions for easily showing some nice examples
in hermes and also showing that things work.
"""
def demo_layer(lib="mayavi"):
"""
Shows off the example 22-layer.
It adaptively refines things and shows the final solution and a convergence
graph.
"""
from hermes2d import (Mesh, MeshView, H1Shapeset, PrecalcShapeset, H1Space,
WeakForm, Solution, DummySolver, LinSystem, ScalarView, RefSystem,
H1Adapt, H1ProjBasedSelector, CandList,
set_verbose)
from hermes2d.examples.c22 import set_bc, set_forms
set_verbose(False)
def calc(threshold=0.3, strategy=0, h_only=False, error_tol=1,
interactive_plotting=False, show_mesh=False, show_graph=True):
mesh = Mesh()
mesh.create([
[0, 0],
[1, 0],
[1, 1],
[0, 1],
], [
[2, 3, 0, 1, 0],
], [
[0, 1, 1],
[1, 2, 1],
[2, 3, 1],
[3, 0, 1],
], [])
mesh.refine_all_elements()
shapeset = H1Shapeset()
pss = PrecalcShapeset(shapeset)
space = H1Space(mesh, shapeset)
set_bc(space)
space.set_uniform_order(1)
wf = WeakForm(1)
set_forms(wf)
sln = Solution()
rsln = Solution()
solver = DummySolver()
selector = H1ProjBasedSelector(CandList.HP_ANISO, 1.0, -1, shapeset)
view = ScalarView("Solution")
iter = 0
graph = []
while 1:
space.assign_dofs()
sys = LinSystem(wf, solver)
sys.set_spaces(space)
sys.set_pss(pss)
sys.assemble()
sys.solve_system(sln)
dofs = sys.get_matrix().shape[0]
if interactive_plotting:
view.show(sln, lib=lib, notebook=True,
filename="a%02d.png" % iter)
rsys = RefSystem(sys)
rsys.assemble()
rsys.solve_system(rsln)
hp = H1Adapt([space])
hp.set_solutions([sln], [rsln])
err_est = hp.calc_error() * 100
err_est = hp.calc_error(sln, rsln)*100
print "iter=%02d, err_est=%5.2f%%, DOFS=%d" % (iter, err_est, dofs)
graph.append([dofs, err_est])
if err_est < error_tol:
break
hp.adapt(selector, threshold, strategy)
iter += 1
if not interactive_plotting:
view.show(sln, lib=lib, notebook=True)
if show_mesh:
mview = MeshView("Mesh")
mview.show(mesh, lib="mpl", notebook=True, filename="b.png")
if show_graph:
from numpy import array
graph = array(graph)
import pylab
pylab.clf()
pylab.plot(graph[:, 0], graph[:, 1], "ko", label="error estimate")
pylab.plot(graph[:, 0], graph[:, 1], "k-")
pylab.title("Error Convergence for the Inner Layer Problem")
pylab.legend()
pylab.xlabel("Degrees of Freedom")
pylab.ylabel("Error [%]")
pylab.yscale("log")
pylab.grid()
pylab.savefig("graph.png")
calc()
|
certik/hermes2d
|
python/hermes2d/demos.py
|
Python
|
gpl-2.0
| 3,220
|
[
"Mayavi"
] |
eec5e800e65aadc56017dd481f2d30cecebb6347ee0b02791b8d5f4a844d9b5e
|
"""
Implement -f aka looponfailing for py.test.
NOTE that we try to avoid loading and depending on application modules
within the controlling process (the one that starts repeatedly test
processes) otherwise changes to source code can crash
the controlling process which should best never happen.
"""
import py
import pytest
import sys
import execnet
def pytest_addoption(parser):
group = parser.getgroup("xdist", "distributed and subprocess testing")
group._addoption(
'-f', '--looponfail',
action="store_true", dest="looponfail", default=False,
help="run tests in subprocess, wait for modified files "
"and re-run failing test set until all pass.")
def pytest_cmdline_main(config):
if config.getoption("looponfail"):
usepdb = config.getoption('usepdb') # a core option
if usepdb:
raise pytest.UsageError(
"--pdb incompatible with --looponfail.")
looponfail_main(config)
return 2 # looponfail only can get stop with ctrl-C anyway
def looponfail_main(config):
remotecontrol = RemoteControl(config)
rootdirs = config.getini("looponfailroots")
statrecorder = StatRecorder(rootdirs)
try:
while 1:
remotecontrol.loop_once()
if not remotecontrol.failures and remotecontrol.wasfailing:
# the last failures passed, let's immediately rerun all
continue
repr_pytest_looponfailinfo(
failreports=remotecontrol.failures,
rootdirs=rootdirs)
statrecorder.waitonchange(checkinterval=2.0)
except KeyboardInterrupt:
print()
class RemoteControl(object):
def __init__(self, config):
self.config = config
self.failures = []
def trace(self, *args):
if self.config.option.debug:
msg = " ".join([str(x) for x in args])
py.builtin.print_("RemoteControl:", msg)
def initgateway(self):
return execnet.makegateway("popen")
def setup(self, out=None):
if out is None:
out = py.io.TerminalWriter()
if hasattr(self, 'gateway'):
raise ValueError("already have gateway %r" % self.gateway)
self.trace("setting up slave session")
self.gateway = self.initgateway()
self.channel = channel = self.gateway.remote_exec(
init_slave_session,
args=self.config.args,
option_dict=vars(self.config.option),
)
remote_outchannel = channel.receive()
def write(s):
out._file.write(s)
out._file.flush()
remote_outchannel.setcallback(write)
def ensure_teardown(self):
if hasattr(self, 'channel'):
if not self.channel.isclosed():
self.trace("closing", self.channel)
self.channel.close()
del self.channel
if hasattr(self, 'gateway'):
self.trace("exiting", self.gateway)
self.gateway.exit()
del self.gateway
def runsession(self):
try:
self.trace("sending", self.failures)
self.channel.send(self.failures)
try:
return self.channel.receive()
except self.channel.RemoteError:
e = sys.exc_info()[1]
self.trace("ERROR", e)
raise
finally:
self.ensure_teardown()
def loop_once(self):
self.setup()
self.wasfailing = self.failures and len(self.failures)
result = self.runsession()
failures, reports, collection_failed = result
if collection_failed:
pass # "Collection failed, keeping previous failure set"
else:
uniq_failures = []
for failure in failures:
if failure not in uniq_failures:
uniq_failures.append(failure)
self.failures = uniq_failures
def repr_pytest_looponfailinfo(failreports, rootdirs):
tr = py.io.TerminalWriter()
if failreports:
tr.sep("#", "LOOPONFAILING", bold=True)
for report in failreports:
if report:
tr.line(report, red=True)
tr.sep("#", "waiting for changes", bold=True)
for rootdir in rootdirs:
tr.line("### Watching: %s" % (rootdir,), bold=True)
def init_slave_session(channel, args, option_dict):
import os
import sys
outchannel = channel.gateway.newchannel()
sys.stdout = sys.stderr = outchannel.makefile('w')
channel.send(outchannel)
# prune sys.path to not contain relative paths
newpaths = []
for p in sys.path:
if p:
if not os.path.isabs(p):
p = os.path.abspath(p)
newpaths.append(p)
sys.path[:] = newpaths
# fullwidth, hasmarkup = channel.receive()
from _pytest.config import Config
config = Config.fromdictargs(option_dict, list(args))
config.args = args
from xdist.looponfail import SlaveFailSession
SlaveFailSession(config, channel).main()
class SlaveFailSession:
def __init__(self, config, channel):
self.config = config
self.channel = channel
self.recorded_failures = []
self.collection_failed = False
config.pluginmanager.register(self)
config.option.looponfail = False
config.option.usepdb = False
def DEBUG(self, *args):
if self.config.option.debug:
print(" ".join(map(str, args)))
def pytest_collection(self, session):
self.session = session
self.trails = self.current_command
hook = self.session.ihook
try:
items = session.perform_collect(self.trails or None)
except pytest.UsageError:
items = session.perform_collect(None)
hook.pytest_collection_modifyitems(
session=session, config=session.config, items=items)
hook.pytest_collection_finish(session=session)
return True
def pytest_runtest_logreport(self, report):
if report.failed:
self.recorded_failures.append(report)
def pytest_collectreport(self, report):
if report.failed:
self.recorded_failures.append(report)
self.collection_failed = True
def main(self):
self.DEBUG("SLAVE: received configuration, waiting for command trails")
try:
command = self.channel.receive()
except KeyboardInterrupt:
return # in the slave we can't do much about this
self.DEBUG("received", command)
self.current_command = command
self.config.hook.pytest_cmdline_main(config=self.config)
trails, failreports = [], []
for rep in self.recorded_failures:
trails.append(rep.nodeid)
loc = rep.longrepr
loc = str(getattr(loc, 'reprcrash', loc))
failreports.append(loc)
self.channel.send((trails, failreports, self.collection_failed))
class StatRecorder:
def __init__(self, rootdirlist):
self.rootdirlist = rootdirlist
self.statcache = {}
self.check() # snapshot state
def fil(self, p):
return p.check(file=1, dotfile=0) and p.ext != ".pyc"
def rec(self, p):
return p.check(dotfile=0)
def waitonchange(self, checkinterval=1.0):
while 1:
changed = self.check()
if changed:
return
py.std.time.sleep(checkinterval)
def check(self, removepycfiles=True): # noqa, too complex
changed = False
statcache = self.statcache
newstat = {}
for rootdir in self.rootdirlist:
for path in rootdir.visit(self.fil, self.rec):
oldstat = statcache.pop(path, None)
try:
newstat[path] = curstat = path.stat()
except py.error.ENOENT:
if oldstat:
changed = True
else:
if oldstat:
if oldstat.mtime != curstat.mtime or \
oldstat.size != curstat.size:
changed = True
py.builtin.print_("# MODIFIED", path)
if removepycfiles and path.ext == ".py":
pycfile = path + "c"
if pycfile.check():
pycfile.remove()
else:
changed = True
if statcache:
changed = True
self.statcache = newstat
return changed
|
vicky2135/lucious
|
oscar/lib/python2.7/site-packages/xdist/looponfail.py
|
Python
|
bsd-3-clause
| 8,713
|
[
"VisIt"
] |
f1042583e47531d8e27216b8779e5e387128b3f4ba8a9a2e09b1146ec501ca6b
|
###########################################################################
#
# This program is part of Zenoss Core, an open source monitoring platform.
# Copyright (C) 2007, 2009 Zenoss Inc.
#
# 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.
#
# For complete information please visit: http://www.zenoss.com/oss/
#
###########################################################################
__doc__ = """OlsonNewDeviceMap
Try to determine OS and hardware manufacturer information based on
the SNMP description (sysDescr).
Olson devices don't support MIB-2 properly so interface not created automatically.
This is solved here.
"""
import re
from Products.DataCollector.plugins.CollectorPlugin import SnmpPlugin, GetMap
from Products.DataCollector.plugins.DataMaps import ObjectMap,RelationshipMap, MultiArgs
from Products.DataCollector.EnterpriseOIDs import EnterpriseOIDs
class OlsonNewDeviceMap(SnmpPlugin):
"""
Record basic hardware/software information based on the snmpDscr OID.
Note that this doesn't work with Olson devices if .0 on end of OID
"""
maptype = "OlsonNewDeviceMap"
snmpGetMap = GetMap({
'.1.3.6.1.2.1.1.1' : 'snmpDescr',
'.1.3.6.1.2.1.1.2' : 'snmpOid',
'.1.3.6.1.2.1.1.5' : 'snmpSysName',
'.1.3.6.1.4.1.17933.1.1.1' : 'setHWProductKey',
'.1.3.6.1.4.1.17933.1.1.4' : '_macAddr',
'.1.3.6.1.4.1.17933.1.1.6' : '_ipAddr',
})
osregex = (
# Olson 9016-V01 PDU
re.compile(r'^(Olson) (\S+) (\S+)'), # Olson
#GENERIC unix
re.compile(r'(\S+) \S+ (\S+)'), # unix
)
def olsonInterface(self, manageIp, macaddr):
om = ObjectMap({}, compname = "os",
modname = "Products.ZenModel.IpInterface")
om.id = self.prepId("eth0")
om.title = om.id
om.interfaceName = om.id
om.description = "Manually Kludged"
om.type = "manual"
om.speed = 10000000
om.mtu = 1500
om.ifindex = "1"
om.adminStatus = 1
om.operStatus = 1
om.monitor = False
om.setIpAddresses = [manageIp, ]
om.macaddress = macaddr
# om.lockFromDeletion()
# om.lockFromUpdates()
return RelationshipMap(relname = "interfaces", compname = "os",
modname = "Products.ZenModel.IpInterface",
objmaps = [om,])
def process(self, device, results, log):
"""
Collect SNMP information from this device
"""
log.info('Processing %s for device %s', self.name(), device.id)
getdata, tabledata = results
if not getdata:
log.warn("Unable to retrieve getdata from %s", device.id)
log.warn("Does snmpwalk -v1 -c community %s 1.3.6.1.2.1.1 work?",
device.id)
return
log.debug("%s getdata = %s", device.id, getdata)
maps = []
om = self.objectMap(getdata)
if om.snmpDescr:
descr = re.sub("\s", " ", om.snmpDescr)
for regex in self.osregex:
m = regex.search(descr)
if m:
groups = m.groups()
if groups[0] == 'Olson':
om.setOSProductKey = MultiArgs(" ".join(groups[0:3])
, 'Olson')
else:
om.setOSProductKey = " ".join(groups)
log.debug("OSProductKey=%s", om.setOSProductKey)
break
maps.append(om)
# Create an interface for the device if ipAddr and macAddr were supplied by Olson MIB
if device.manageIp:
if om._ipAddr and om._macAddr:
maps.append(self.olsonInterface(om._ipAddr, om._macAddr))
return maps
|
jcurry/ZenPacks.ZenSystems.olsonPower
|
ZenPacks/ZenSystems/olsonPower/modeler/plugins/OlsonNewDeviceMap.py
|
Python
|
gpl-2.0
| 4,058
|
[
"VisIt"
] |
3ba121612c802b3d284459f4376da82074ef2ba7a6820a058d82ef66707b99a3
|
# -*- coding: utf-8 -*-
#
# brunel_alpha_nest.py
#
# This file is part of NEST.
#
# Copyright (C) 2004 The NEST Initiative
#
# NEST is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 2 of the License, or
# (at your option) any later version.
#
# NEST 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 NEST. If not, see <http://www.gnu.org/licenses/>.
"""Random balanced network (alpha synapses) connected with NEST
------------------------------------------------------------------
This script simulates an excitatory and an inhibitory population on
the basis of the network used in [1]_.
In contrast to ``brunel-alpha-numpy.py``, this variant uses NEST's builtin
connection routines to draw the random connections instead of NumPy.
When connecting the network customary synapse models are used, which
allow for querying the number of created synapses. Using spike
detectors the average firing rates of the neurons in the populations
are established. The building as well as the simulation time of the
network are recorded.
References
~~~~~~~~~~~~~
.. [1] Brunel N (2000). Dynamics of sparsely connected networks of excitatory and
inhibitory spiking neurons. Journal of Computational Neuroscience 8,
183-208.
See Also
~~~~~~~~~~~~
:doc:`brunel_alpha_numpy`
"""
###############################################################################
# Import all necessary modules for simulation, analysis and plotting. Scipy
# should be imported before nest.
import time
import numpy as np
import scipy.special as sp
import nest
import nest.raster_plot
import matplotlib.pyplot as plt
###############################################################################
# Definition of functions used in this example. First, define the `Lambert W`
# function implemented in SLI. The second function computes the maximum of
# the postsynaptic potential for a synaptic input current of unit amplitude
# (1 pA) using the `Lambert W` function. Thus function will later be used to
# calibrate the synaptic weights.
def LambertWm1(x):
# Using scipy to mimic the gsl_sf_lambert_Wm1 function.
return sp.lambertw(x, k=-1 if x < 0 else 0).real
def ComputePSPnorm(tauMem, CMem, tauSyn):
a = (tauMem / tauSyn)
b = (1.0 / tauSyn - 1.0 / tauMem)
# time of maximum
t_max = 1.0 / b * (-LambertWm1(-np.exp(-1.0 / a) / a) - 1.0 / a)
# maximum of PSP for current of unit amplitude
return (np.exp(1.0) / (tauSyn * CMem * b) *
((np.exp(-t_max / tauMem) - np.exp(-t_max / tauSyn)) / b -
t_max * np.exp(-t_max / tauSyn)))
nest.ResetKernel()
###############################################################################
# Assigning the current time to a variable in order to determine the build
# time of the network.
startbuild = time.time()
###############################################################################
# Assigning the simulation parameters to variables.
dt = 0.1 # the resolution in ms
simtime = 1000.0 # Simulation time in ms
delay = 1.5 # synaptic delay in ms
###############################################################################
# Definition of the parameters crucial for asynchronous irregular firing of
# the neurons.
g = 5.0 # ratio inhibitory weight/excitatory weight
eta = 2.0 # external rate relative to threshold rate
epsilon = 0.1 # connection probability
###############################################################################
# Definition of the number of neurons in the network and the number of neuron
# recorded from
order = 2500
NE = 4 * order # number of excitatory neurons
NI = 1 * order # number of inhibitory neurons
N_neurons = NE + NI # number of neurons in total
N_rec = 50 # record from 50 neurons
###############################################################################
# Definition of connectivity parameter
CE = int(epsilon * NE) # number of excitatory synapses per neuron
CI = int(epsilon * NI) # number of inhibitory synapses per neuron
C_tot = int(CI + CE) # total number of synapses per neuron
###############################################################################
# Initialization of the parameters of the integrate and fire neuron and the
# synapses. The parameter of the neuron are stored in a dictionary. The
# synaptic currents are normalized such that the amplitude of the PSP is J.
tauSyn = 0.5 # synaptic time constant in ms
tauMem = 20.0 # time constant of membrane potential in ms
CMem = 250.0 # capacitance of membrane in in pF
theta = 20.0 # membrane threshold potential in mV
neuron_params = {"C_m": CMem,
"tau_m": tauMem,
"tau_syn_ex": tauSyn,
"tau_syn_in": tauSyn,
"t_ref": 2.0,
"E_L": 0.0,
"V_reset": 0.0,
"V_m": 0.0,
"V_th": theta}
J = 0.1 # postsynaptic amplitude in mV
J_unit = ComputePSPnorm(tauMem, CMem, tauSyn)
J_ex = J / J_unit # amplitude of excitatory postsynaptic current
J_in = -g * J_ex # amplitude of inhibitory postsynaptic current
###############################################################################
# Definition of threshold rate, which is the external rate needed to fix the
# membrane potential around its threshold, the external firing rate and the
# rate of the poisson generator which is multiplied by the in-degree CE and
# converted to Hz by multiplication by 1000.
nu_th = (theta * CMem) / (J_ex * CE * np.exp(1) * tauMem * tauSyn)
nu_ex = eta * nu_th
p_rate = 1000.0 * nu_ex * CE
################################################################################
# Configuration of the simulation kernel by the previously defined time
# resolution used in the simulation. Setting ``print_time`` to `True` prints the
# already processed simulation time as well as its percentage of the total
# simulation time.
nest.SetKernelStatus({"resolution": dt, "print_time": True,
"overwrite_files": True})
print("Building network")
###############################################################################
# Configuration of the model ``iaf_psc_alpha`` and ``poisson_generator`` using
# ``SetDefaults``. This function expects the model to be the inserted as a
# string and the parameter to be specified in a dictionary. All instances of
# theses models created after this point will have the properties specified
# in the dictionary by default.
nest.SetDefaults("iaf_psc_alpha", neuron_params)
nest.SetDefaults("poisson_generator", {"rate": p_rate})
###############################################################################
# Creation of the nodes using ``Create``. We store the returned handles in
# variables for later reference. Here the excitatory and inhibitory, as well
# as the poisson generator and two spike detectors. The spike detectors will
# later be used to record excitatory and inhibitory spikes.
nodes_ex = nest.Create("iaf_psc_alpha", NE)
nodes_in = nest.Create("iaf_psc_alpha", NI)
noise = nest.Create("poisson_generator")
espikes = nest.Create("spike_detector")
ispikes = nest.Create("spike_detector")
###############################################################################
# Configuration of the spike detectors recording excitatory and inhibitory
# spikes by sending parameter dictionaries to ``set``. Setting the property
# `record_to` to *"ascii"* ensures that the spikes will be recorded to a file,
# whose name starts with the string assigned to the property `label`.
espikes.set(label="brunel-py-ex", record_to="ascii")
ispikes.set(label="brunel-py-in", record_to="ascii")
print("Connecting devices")
###############################################################################
# Definition of a synapse using ``CopyModel``, which expects the model name of
# a pre-defined synapse, the name of the customary synapse and an optional
# parameter dictionary. The parameters defined in the dictionary will be the
# default parameter for the customary synapse. Here we define one synapse for
# the excitatory and one for the inhibitory connections giving the
# previously defined weights and equal delays.
nest.CopyModel("static_synapse", "excitatory",
{"weight": J_ex, "delay": delay})
nest.CopyModel("static_synapse", "inhibitory",
{"weight": J_in, "delay": delay})
#################################################################################
# Connecting the previously defined poisson generator to the excitatory and
# inhibitory neurons using the excitatory synapse. Since the poisson
# generator is connected to all neurons in the population the default rule
# (``all_to_all``) of ``Connect`` is used. The synaptic properties are inserted
# via ``syn_spec`` which expects a dictionary when defining multiple variables or
# a string when simply using a pre-defined synapse.
nest.Connect(noise, nodes_ex, syn_spec="excitatory")
nest.Connect(noise, nodes_in, syn_spec="excitatory")
###############################################################################
# Connecting the first ``N_rec`` nodes of the excitatory and inhibitory
# population to the associated spike detectors using excitatory synapses.
# Here the same shortcut for the specification of the synapse as defined
# above is used.
nest.Connect(nodes_ex[:N_rec], espikes, syn_spec="excitatory")
nest.Connect(nodes_in[:N_rec], ispikes, syn_spec="excitatory")
print("Connecting network")
print("Excitatory connections")
###############################################################################
# Connecting the excitatory population to all neurons using the pre-defined
# excitatory synapse. Beforehand, the connection parameter are defined in a
# dictionary. Here we use the connection rule ``fixed_indegree``,
# which requires the definition of the indegree. Since the synapse
# specification is reduced to assigning the pre-defined excitatory synapse it
# suffices to insert a string.
conn_params_ex = {'rule': 'fixed_indegree', 'indegree': CE}
nest.Connect(nodes_ex, nodes_ex + nodes_in, conn_params_ex, "excitatory")
print("Inhibitory connections")
###############################################################################
# Connecting the inhibitory population to all neurons using the pre-defined
# inhibitory synapse. The connection parameter as well as the synapse
# parameter are defined analogously to the connection from the excitatory
# population defined above.
conn_params_in = {'rule': 'fixed_indegree', 'indegree': CI}
nest.Connect(nodes_in, nodes_ex + nodes_in, conn_params_in, "inhibitory")
###############################################################################
# Storage of the time point after the buildup of the network in a variable.
endbuild = time.time()
###############################################################################
# Simulation of the network.
print("Simulating")
nest.Simulate(simtime)
###############################################################################
# Storage of the time point after the simulation of the network in a variable.
endsimulate = time.time()
###############################################################################
# Reading out the total number of spikes received from the spike detector
# connected to the excitatory population and the inhibitory population.
events_ex = espikes.n_events
events_in = ispikes.n_events
###############################################################################
# Calculation of the average firing rate of the excitatory and the inhibitory
# neurons by dividing the total number of recorded spikes by the number of
# neurons recorded from and the simulation time. The multiplication by 1000.0
# converts the unit 1/ms to 1/s=Hz.
rate_ex = events_ex / simtime * 1000.0 / N_rec
rate_in = events_in / simtime * 1000.0 / N_rec
###############################################################################
# Reading out the number of connections established using the excitatory and
# inhibitory synapse model. The numbers are summed up resulting in the total
# number of synapses.
num_synapses = (nest.GetDefaults("excitatory")["num_connections"] +
nest.GetDefaults("inhibitory")["num_connections"])
###############################################################################
# Establishing the time it took to build and simulate the network by taking
# the difference of the pre-defined time variables.
build_time = endbuild - startbuild
sim_time = endsimulate - endbuild
###############################################################################
# Printing the network properties, firing rates and building times.
print("Brunel network simulation (Python)")
print("Number of neurons : {0}".format(N_neurons))
print("Number of synapses: {0}".format(num_synapses))
print(" Exitatory : {0}".format(int(CE * N_neurons) + N_neurons))
print(" Inhibitory : {0}".format(int(CI * N_neurons)))
print("Excitatory rate : %.2f Hz" % rate_ex)
print("Inhibitory rate : %.2f Hz" % rate_in)
print("Building time : %.2f s" % build_time)
print("Simulation time : %.2f s" % sim_time)
###############################################################################
# Plot a raster of the excitatory neurons and a histogram.
nest.raster_plot.from_device(espikes, hist=True)
plt.show()
|
espenhgn/nest-simulator
|
pynest/examples/brunel_alpha_nest.py
|
Python
|
gpl-2.0
| 13,724
|
[
"NEURON"
] |
64a758f2204fff8018567601882ddccec4b4c9502a41bdfa3d9dbcd3ac18c355
|
from sqlalchemy import *
from sqlalchemy.sql import table, column, ClauseElement
from sqlalchemy.sql.expression import _clone, _from_objects
from sqlalchemy.test import *
from sqlalchemy.sql.visitors import *
from sqlalchemy import util
from sqlalchemy.sql import util as sql_util
from sqlalchemy.test.testing import eq_
class TraversalTest(TestBase, AssertsExecutionResults):
"""test ClauseVisitor's traversal, particularly its ability to copy and modify
a ClauseElement in place."""
@classmethod
def setup_class(cls):
global A, B
# establish two ficticious ClauseElements.
# define deep equality semantics as well as deep identity semantics.
class A(ClauseElement):
__visit_name__ = 'a'
def __init__(self, expr):
self.expr = expr
def is_other(self, other):
return other is self
__hash__ = ClauseElement.__hash__
def __eq__(self, other):
return other.expr == self.expr
def __ne__(self, other):
return other.expr != self.expr
def __str__(self):
return "A(%s)" % repr(self.expr)
class B(ClauseElement):
__visit_name__ = 'b'
def __init__(self, *items):
self.items = items
def is_other(self, other):
if other is not self:
return False
for i1, i2 in zip(self.items, other.items):
if i1 is not i2:
return False
return True
__hash__ = ClauseElement.__hash__
def __eq__(self, other):
for i1, i2 in zip(self.items, other.items):
if i1 != i2:
return False
return True
def __ne__(self, other):
for i1, i2 in zip(self.items, other.items):
if i1 != i2:
return True
return False
def _copy_internals(self, clone=_clone):
self.items = [clone(i) for i in self.items]
def get_children(self, **kwargs):
return self.items
def __str__(self):
return "B(%s)" % repr([str(i) for i in self.items])
def test_test_classes(self):
a1 = A("expr1")
struct = B(a1, A("expr2"), B(A("expr1b"), A("expr2b")), A("expr3"))
struct2 = B(a1, A("expr2"), B(A("expr1b"), A("expr2b")), A("expr3"))
struct3 = B(a1, A("expr2"), B(A("expr1b"), A("expr2bmodified")), A("expr3"))
assert a1.is_other(a1)
assert struct.is_other(struct)
assert struct == struct2
assert struct != struct3
assert not struct.is_other(struct2)
assert not struct.is_other(struct3)
def test_clone(self):
struct = B(A("expr1"), A("expr2"), B(A("expr1b"), A("expr2b")), A("expr3"))
class Vis(CloningVisitor):
def visit_a(self, a):
pass
def visit_b(self, b):
pass
vis = Vis()
s2 = vis.traverse(struct)
assert struct == s2
assert not struct.is_other(s2)
def test_no_clone(self):
struct = B(A("expr1"), A("expr2"), B(A("expr1b"), A("expr2b")), A("expr3"))
class Vis(ClauseVisitor):
def visit_a(self, a):
pass
def visit_b(self, b):
pass
vis = Vis()
s2 = vis.traverse(struct)
assert struct == s2
assert struct.is_other(s2)
def test_change_in_place(self):
struct = B(A("expr1"), A("expr2"), B(A("expr1b"), A("expr2b")), A("expr3"))
struct2 = B(A("expr1"), A("expr2modified"), B(A("expr1b"), A("expr2b")), A("expr3"))
struct3 = B(A("expr1"), A("expr2"), B(A("expr1b"), A("expr2bmodified")), A("expr3"))
class Vis(CloningVisitor):
def visit_a(self, a):
if a.expr == "expr2":
a.expr = "expr2modified"
def visit_b(self, b):
pass
vis = Vis()
s2 = vis.traverse(struct)
assert struct != s2
assert not struct.is_other(s2)
assert struct2 == s2
class Vis2(CloningVisitor):
def visit_a(self, a):
if a.expr == "expr2b":
a.expr = "expr2bmodified"
def visit_b(self, b):
pass
vis2 = Vis2()
s3 = vis2.traverse(struct)
assert struct != s3
assert struct3 == s3
def test_visit_name(self):
# override fns in testlib/schema.py
from sqlalchemy import Column
class CustomObj(Column):
pass
assert CustomObj.__visit_name__ == Column.__visit_name__ == 'column'
foo, bar = CustomObj('foo', String), CustomObj('bar', String)
bin = foo == bar
s = set(ClauseVisitor().iterate(bin))
assert set(ClauseVisitor().iterate(bin)) == set([foo, bar, bin])
class ClauseTest(TestBase, AssertsCompiledSQL):
"""test copy-in-place behavior of various ClauseElements."""
@classmethod
def setup_class(cls):
global t1, t2
t1 = table("table1",
column("col1"),
column("col2"),
column("col3"),
)
t2 = table("table2",
column("col1"),
column("col2"),
column("col3"),
)
def test_binary(self):
clause = t1.c.col2 == t2.c.col2
eq_(str(clause), str(CloningVisitor().traverse(clause)))
def test_binary_anon_label_quirk(self):
t = table('t1', column('col1'))
f = t.c.col1 * 5
self.assert_compile(select([f]), "SELECT t1.col1 * :col1_1 AS anon_1 FROM t1")
f.anon_label
a = t.alias()
f = sql_util.ClauseAdapter(a).traverse(f)
self.assert_compile(select([f]), "SELECT t1_1.col1 * :col1_1 AS anon_1 FROM t1 AS t1_1")
def test_join(self):
clause = t1.join(t2, t1.c.col2==t2.c.col2)
c1 = str(clause)
assert str(clause) == str(CloningVisitor().traverse(clause))
class Vis(CloningVisitor):
def visit_binary(self, binary):
binary.right = t2.c.col3
clause2 = Vis().traverse(clause)
assert c1 == str(clause)
assert str(clause2) == str(t1.join(t2, t1.c.col2==t2.c.col3))
def test_text(self):
clause = text("select * from table where foo=:bar", bindparams=[bindparam('bar')])
c1 = str(clause)
class Vis(CloningVisitor):
def visit_textclause(self, text):
text.text = text.text + " SOME MODIFIER=:lala"
text.bindparams['lala'] = bindparam('lala')
clause2 = Vis().traverse(clause)
assert c1 == str(clause)
assert str(clause2) == c1 + " SOME MODIFIER=:lala"
assert clause.bindparams.keys() == ['bar']
assert set(clause2.bindparams.keys()) == set(['bar', 'lala'])
def test_select(self):
s2 = select([t1])
s2_assert = str(s2)
s3_assert = str(select([t1], t1.c.col2==7))
class Vis(CloningVisitor):
def visit_select(self, select):
select.append_whereclause(t1.c.col2==7)
s3 = Vis().traverse(s2)
assert str(s3) == s3_assert
assert str(s2) == s2_assert
print str(s2)
print str(s3)
class Vis(ClauseVisitor):
def visit_select(self, select):
select.append_whereclause(t1.c.col2==7)
Vis().traverse(s2)
assert str(s2) == s3_assert
print "------------------"
s4_assert = str(select([t1], and_(t1.c.col2==7, t1.c.col3==9)))
class Vis(CloningVisitor):
def visit_select(self, select):
select.append_whereclause(t1.c.col3==9)
s4 = Vis().traverse(s3)
print str(s3)
print str(s4)
assert str(s4) == s4_assert
assert str(s3) == s3_assert
print "------------------"
s5_assert = str(select([t1], and_(t1.c.col2==7, t1.c.col1==9)))
class Vis(CloningVisitor):
def visit_binary(self, binary):
if binary.left is t1.c.col3:
binary.left = t1.c.col1
binary.right = bindparam("col1", unique=True)
s5 = Vis().traverse(s4)
print str(s4)
print str(s5)
assert str(s5) == s5_assert
assert str(s4) == s4_assert
def test_union(self):
u = union(t1.select(), t2.select())
u2 = CloningVisitor().traverse(u)
assert str(u) == str(u2)
assert [str(c) for c in u2.c] == [str(c) for c in u.c]
u = union(t1.select(), t2.select())
cols = [str(c) for c in u.c]
u2 = CloningVisitor().traverse(u)
assert str(u) == str(u2)
assert [str(c) for c in u2.c] == cols
s1 = select([t1], t1.c.col1 == bindparam('id_param'))
s2 = select([t2])
u = union(s1, s2)
u2 = u.params(id_param=7)
u3 = u.params(id_param=10)
assert str(u) == str(u2) == str(u3)
assert u2.compile().params == {'id_param':7}
assert u3.compile().params == {'id_param':10}
def test_adapt_union(self):
u = union(t1.select().where(t1.c.col1==4), t1.select().where(t1.c.col1==5)).alias()
assert sql_util.ClauseAdapter(u).traverse(t1) is u
def test_binds(self):
"""test that unique bindparams change their name upon clone() to prevent conflicts"""
s = select([t1], t1.c.col1==bindparam(None, unique=True)).alias()
s2 = CloningVisitor().traverse(s).alias()
s3 = select([s], s.c.col2==s2.c.col2)
self.assert_compile(s3, "SELECT anon_1.col1, anon_1.col2, anon_1.col3 FROM (SELECT table1.col1 AS col1, table1.col2 AS col2, "\
"table1.col3 AS col3 FROM table1 WHERE table1.col1 = :param_1) AS anon_1, "\
"(SELECT table1.col1 AS col1, table1.col2 AS col2, table1.col3 AS col3 FROM table1 WHERE table1.col1 = :param_2) AS anon_2 "\
"WHERE anon_1.col2 = anon_2.col2")
s = select([t1], t1.c.col1==4).alias()
s2 = CloningVisitor().traverse(s).alias()
s3 = select([s], s.c.col2==s2.c.col2)
self.assert_compile(s3, "SELECT anon_1.col1, anon_1.col2, anon_1.col3 FROM (SELECT table1.col1 AS col1, table1.col2 AS col2, "\
"table1.col3 AS col3 FROM table1 WHERE table1.col1 = :col1_1) AS anon_1, "\
"(SELECT table1.col1 AS col1, table1.col2 AS col2, table1.col3 AS col3 FROM table1 WHERE table1.col1 = :col1_2) AS anon_2 "\
"WHERE anon_1.col2 = anon_2.col2")
def test_extract(self):
s = select([extract('foo', t1.c.col1).label('col1')])
self.assert_compile(s, "SELECT EXTRACT(foo FROM table1.col1) AS col1 FROM table1")
s2 = CloningVisitor().traverse(s).alias()
s3 = select([s2.c.col1])
self.assert_compile(s, "SELECT EXTRACT(foo FROM table1.col1) AS col1 FROM table1")
self.assert_compile(s3, "SELECT anon_1.col1 FROM (SELECT EXTRACT(foo FROM table1.col1) AS col1 FROM table1) AS anon_1")
@testing.emits_warning('.*replaced by another column with the same key')
def test_alias(self):
subq = t2.select().alias('subq')
s = select([t1.c.col1, subq.c.col1], from_obj=[t1, subq, t1.join(subq, t1.c.col1==subq.c.col2)])
orig = str(s)
s2 = CloningVisitor().traverse(s)
assert orig == str(s) == str(s2)
s4 = CloningVisitor().traverse(s2)
assert orig == str(s) == str(s2) == str(s4)
s3 = sql_util.ClauseAdapter(table('foo')).traverse(s)
assert orig == str(s) == str(s3)
s4 = sql_util.ClauseAdapter(table('foo')).traverse(s3)
assert orig == str(s) == str(s3) == str(s4)
subq = subq.alias('subq')
s = select([t1.c.col1, subq.c.col1], from_obj=[t1, subq, t1.join(subq, t1.c.col1==subq.c.col2)])
s5 = CloningVisitor().traverse(s)
assert orig == str(s) == str(s5)
def test_correlated_select(self):
s = select(['*'], t1.c.col1==t2.c.col1, from_obj=[t1, t2]).correlate(t2)
class Vis(CloningVisitor):
def visit_select(self, select):
select.append_whereclause(t1.c.col2==7)
self.assert_compile(Vis().traverse(s), "SELECT * FROM table1 WHERE table1.col1 = table2.col1 AND table1.col2 = :col2_1")
def test_this_thing(self):
s = select([t1]).where(t1.c.col1=='foo').alias()
s2 = select([s.c.col1])
self.assert_compile(s2, "SELECT anon_1.col1 FROM (SELECT table1.col1 AS col1, table1.col2 AS col2, table1.col3 AS col3 FROM table1 WHERE table1.col1 = :col1_1) AS anon_1")
t1a = t1.alias()
s2 = sql_util.ClauseAdapter(t1a).traverse(s2)
self.assert_compile(s2, "SELECT anon_1.col1 FROM (SELECT table1_1.col1 AS col1, table1_1.col2 AS col2, table1_1.col3 AS col3 FROM table1 AS table1_1 WHERE table1_1.col1 = :col1_1) AS anon_1")
def test_select_fromtwice(self):
t1a = t1.alias()
s = select([1], t1.c.col1==t1a.c.col1, from_obj=t1a).correlate(t1)
self.assert_compile(s, "SELECT 1 FROM table1 AS table1_1 WHERE table1.col1 = table1_1.col1")
s = CloningVisitor().traverse(s)
self.assert_compile(s, "SELECT 1 FROM table1 AS table1_1 WHERE table1.col1 = table1_1.col1")
s = select([t1]).where(t1.c.col1=='foo').alias()
s2 = select([1], t1.c.col1==s.c.col1, from_obj=s).correlate(t1)
self.assert_compile(s2, "SELECT 1 FROM (SELECT table1.col1 AS col1, table1.col2 AS col2, table1.col3 AS col3 FROM table1 WHERE table1.col1 = :col1_1) AS anon_1 WHERE table1.col1 = anon_1.col1")
s2 = ReplacingCloningVisitor().traverse(s2)
self.assert_compile(s2, "SELECT 1 FROM (SELECT table1.col1 AS col1, table1.col2 AS col2, table1.col3 AS col3 FROM table1 WHERE table1.col1 = :col1_1) AS anon_1 WHERE table1.col1 = anon_1.col1")
class ClauseAdapterTest(TestBase, AssertsCompiledSQL):
@classmethod
def setup_class(cls):
global t1, t2
t1 = table("table1",
column("col1"),
column("col2"),
column("col3"),
)
t2 = table("table2",
column("col1"),
column("col2"),
column("col3"),
)
def test_correlation_on_clone(self):
t1alias = t1.alias('t1alias')
t2alias = t2.alias('t2alias')
vis = sql_util.ClauseAdapter(t1alias)
s = select(['*'], from_obj=[t1alias, t2alias]).as_scalar()
assert t2alias in s._froms
assert t1alias in s._froms
self.assert_compile(select(['*'], t2alias.c.col1==s), "SELECT * FROM table2 AS t2alias WHERE t2alias.col1 = (SELECT * FROM table1 AS t1alias)")
s = vis.traverse(s)
assert t2alias not in s._froms # not present because it's been cloned
assert t1alias in s._froms # present because the adapter placed it there
# correlate list on "s" needs to take into account the full _cloned_set for each element in _froms when correlating
self.assert_compile(select(['*'], t2alias.c.col1==s), "SELECT * FROM table2 AS t2alias WHERE t2alias.col1 = (SELECT * FROM table1 AS t1alias)")
s = select(['*'], from_obj=[t1alias, t2alias]).correlate(t2alias).as_scalar()
self.assert_compile(select(['*'], t2alias.c.col1==s), "SELECT * FROM table2 AS t2alias WHERE t2alias.col1 = (SELECT * FROM table1 AS t1alias)")
s = vis.traverse(s)
self.assert_compile(select(['*'], t2alias.c.col1==s), "SELECT * FROM table2 AS t2alias WHERE t2alias.col1 = (SELECT * FROM table1 AS t1alias)")
s = CloningVisitor().traverse(s)
self.assert_compile(select(['*'], t2alias.c.col1==s), "SELECT * FROM table2 AS t2alias WHERE t2alias.col1 = (SELECT * FROM table1 AS t1alias)")
s = select(['*']).where(t1.c.col1==t2.c.col1).as_scalar()
self.assert_compile(select([t1.c.col1, s]), "SELECT table1.col1, (SELECT * FROM table2 WHERE table1.col1 = table2.col1) AS anon_1 FROM table1")
vis = sql_util.ClauseAdapter(t1alias)
s = vis.traverse(s)
self.assert_compile(select([t1alias.c.col1, s]), "SELECT t1alias.col1, (SELECT * FROM table2 WHERE t1alias.col1 = table2.col1) AS anon_1 FROM table1 AS t1alias")
s = CloningVisitor().traverse(s)
self.assert_compile(select([t1alias.c.col1, s]), "SELECT t1alias.col1, (SELECT * FROM table2 WHERE t1alias.col1 = table2.col1) AS anon_1 FROM table1 AS t1alias")
s = select(['*']).where(t1.c.col1==t2.c.col1).correlate(t1).as_scalar()
self.assert_compile(select([t1.c.col1, s]), "SELECT table1.col1, (SELECT * FROM table2 WHERE table1.col1 = table2.col1) AS anon_1 FROM table1")
vis = sql_util.ClauseAdapter(t1alias)
s = vis.traverse(s)
self.assert_compile(select([t1alias.c.col1, s]), "SELECT t1alias.col1, (SELECT * FROM table2 WHERE t1alias.col1 = table2.col1) AS anon_1 FROM table1 AS t1alias")
s = CloningVisitor().traverse(s)
self.assert_compile(select([t1alias.c.col1, s]), "SELECT t1alias.col1, (SELECT * FROM table2 WHERE t1alias.col1 = table2.col1) AS anon_1 FROM table1 AS t1alias")
@testing.fails_on_everything_except()
def test_joins_dont_adapt(self):
# adapting to a join, i.e. ClauseAdapter(t1.join(t2)), doesn't make much sense.
# ClauseAdapter doesn't make any changes if it's against a straight join.
users = table('users', column('id'))
addresses = table('addresses', column('id'), column('user_id'))
ualias = users.alias()
s = select([func.count(addresses.c.id)], users.c.id==addresses.c.user_id).correlate(users) #.as_scalar().label(None)
s= sql_util.ClauseAdapter(ualias).traverse(s)
j1 = addresses.join(ualias, addresses.c.user_id==ualias.c.id)
self.assert_compile(sql_util.ClauseAdapter(j1).traverse(s), "SELECT count(addresses.id) AS count_1 FROM addresses WHERE users_1.id = addresses.user_id")
def test_table_to_alias(self):
t1alias = t1.alias('t1alias')
vis = sql_util.ClauseAdapter(t1alias)
ff = vis.traverse(func.count(t1.c.col1).label('foo'))
assert list(_from_objects(ff)) == [t1alias]
self.assert_compile(vis.traverse(select(['*'], from_obj=[t1])), "SELECT * FROM table1 AS t1alias")
self.assert_compile(select(['*'], t1.c.col1==t2.c.col2), "SELECT * FROM table1, table2 WHERE table1.col1 = table2.col2")
self.assert_compile(vis.traverse(select(['*'], t1.c.col1==t2.c.col2)), "SELECT * FROM table1 AS t1alias, table2 WHERE t1alias.col1 = table2.col2")
self.assert_compile(vis.traverse(select(['*'], t1.c.col1==t2.c.col2, from_obj=[t1, t2])), "SELECT * FROM table1 AS t1alias, table2 WHERE t1alias.col1 = table2.col2")
self.assert_compile(vis.traverse(select(['*'], t1.c.col1==t2.c.col2, from_obj=[t1, t2]).correlate(t1)), "SELECT * FROM table2 WHERE t1alias.col1 = table2.col2")
self.assert_compile(vis.traverse(select(['*'], t1.c.col1==t2.c.col2, from_obj=[t1, t2]).correlate(t2)), "SELECT * FROM table1 AS t1alias WHERE t1alias.col1 = table2.col2")
self.assert_compile(vis.traverse(case([(t1.c.col1==5, t1.c.col2)], else_=t1.c.col1)),
"CASE WHEN (t1alias.col1 = :col1_1) THEN t1alias.col2 ELSE t1alias.col1 END"
)
self.assert_compile(vis.traverse(case([(5, t1.c.col2)], value=t1.c.col1, else_=t1.c.col1)),
"CASE t1alias.col1 WHEN :param_1 THEN t1alias.col2 ELSE t1alias.col1 END"
)
s = select(['*'], from_obj=[t1]).alias('foo')
self.assert_compile(s.select(), "SELECT foo.* FROM (SELECT * FROM table1) AS foo")
self.assert_compile(vis.traverse(s.select()), "SELECT foo.* FROM (SELECT * FROM table1 AS t1alias) AS foo")
self.assert_compile(s.select(), "SELECT foo.* FROM (SELECT * FROM table1) AS foo")
ff = vis.traverse(func.count(t1.c.col1).label('foo'))
self.assert_compile(select([ff]), "SELECT count(t1alias.col1) AS foo FROM table1 AS t1alias")
assert list(_from_objects(ff)) == [t1alias]
# TODO:
# self.assert_compile(vis.traverse(select([func.count(t1.c.col1).label('foo')]), clone=True), "SELECT count(t1alias.col1) AS foo FROM table1 AS t1alias")
t2alias = t2.alias('t2alias')
vis.chain(sql_util.ClauseAdapter(t2alias))
self.assert_compile(vis.traverse(select(['*'], t1.c.col1==t2.c.col2)), "SELECT * FROM table1 AS t1alias, table2 AS t2alias WHERE t1alias.col1 = t2alias.col2")
self.assert_compile(vis.traverse(select(['*'], t1.c.col1==t2.c.col2, from_obj=[t1, t2])), "SELECT * FROM table1 AS t1alias, table2 AS t2alias WHERE t1alias.col1 = t2alias.col2")
self.assert_compile(vis.traverse(select(['*'], t1.c.col1==t2.c.col2, from_obj=[t1, t2]).correlate(t1)), "SELECT * FROM table2 AS t2alias WHERE t1alias.col1 = t2alias.col2")
self.assert_compile(vis.traverse(select(['*'], t1.c.col1==t2.c.col2, from_obj=[t1, t2]).correlate(t2)), "SELECT * FROM table1 AS t1alias WHERE t1alias.col1 = t2alias.col2")
def test_include_exclude(self):
m = MetaData()
a=Table( 'a',m,
Column( 'id', Integer, primary_key=True),
Column( 'xxx_id', Integer, ForeignKey( 'a.id', name='adf',use_alter=True ) )
)
e = (a.c.id == a.c.xxx_id)
assert str(e) == "a.id = a.xxx_id"
b = a.alias()
e = sql_util.ClauseAdapter( b, include= set([ a.c.id ]),
equivalents= { a.c.id: set([ a.c.id]) }
).traverse( e)
assert str(e) == "a_1.id = a.xxx_id"
def test_recursive_equivalents(self):
m = MetaData()
a = Table('a', m, Column('x', Integer), Column('y', Integer))
b = Table('b', m, Column('x', Integer), Column('y', Integer))
c = Table('c', m, Column('x', Integer), Column('y', Integer))
# force a recursion overflow, by linking a.c.x<->c.c.x, and
# asking for a nonexistent col. corresponding_column should prevent
# endless depth.
adapt = sql_util.ClauseAdapter( b, equivalents= {a.c.x: set([ c.c.x]), c.c.x:set([a.c.x])})
assert adapt._corresponding_column(a.c.x, False) is None
def test_multilevel_equivalents(self):
m = MetaData()
a = Table('a', m, Column('x', Integer), Column('y', Integer))
b = Table('b', m, Column('x', Integer), Column('y', Integer))
c = Table('c', m, Column('x', Integer), Column('y', Integer))
alias = select([a]).select_from(a.join(b, a.c.x==b.c.x)).alias()
# two levels of indirection from c.x->b.x->a.x, requires recursive
# corresponding_column call
adapt = sql_util.ClauseAdapter(alias, equivalents= {b.c.x: set([ a.c.x]), c.c.x:set([b.c.x])})
assert adapt._corresponding_column(a.c.x, False) is alias.c.x
assert adapt._corresponding_column(c.c.x, False) is alias.c.x
def test_join_to_alias(self):
metadata = MetaData()
a = Table('a', metadata,
Column('id', Integer, primary_key=True))
b = Table('b', metadata,
Column('id', Integer, primary_key=True),
Column('aid', Integer, ForeignKey('a.id')),
)
c = Table('c', metadata,
Column('id', Integer, primary_key=True),
Column('bid', Integer, ForeignKey('b.id')),
)
d = Table('d', metadata,
Column('id', Integer, primary_key=True),
Column('aid', Integer, ForeignKey('a.id')),
)
j1 = a.outerjoin(b)
j2 = select([j1], use_labels=True)
j3 = c.join(j2, j2.c.b_id==c.c.bid)
j4 = j3.outerjoin(d)
self.assert_compile(j4, "c JOIN (SELECT a.id AS a_id, b.id AS b_id, b.aid AS b_aid FROM a LEFT OUTER JOIN b ON a.id = b.aid) "
"ON b_id = c.bid"
" LEFT OUTER JOIN d ON a_id = d.aid")
j5 = j3.alias('foo')
j6 = sql_util.ClauseAdapter(j5).copy_and_process([j4])[0]
# this statement takes c join(a join b), wraps it inside an aliased "select * from c join(a join b) AS foo".
# the outermost right side "left outer join d" stays the same, except "d" joins against foo.a_id instead
# of plain "a_id"
self.assert_compile(j6, "(SELECT c.id AS c_id, c.bid AS c_bid, a_id AS a_id, b_id AS b_id, b_aid AS b_aid FROM "
"c JOIN (SELECT a.id AS a_id, b.id AS b_id, b.aid AS b_aid FROM a LEFT OUTER JOIN b ON a.id = b.aid) "
"ON b_id = c.bid) AS foo"
" LEFT OUTER JOIN d ON foo.a_id = d.aid")
def test_derived_from(self):
assert select([t1]).is_derived_from(t1)
assert not select([t2]).is_derived_from(t1)
assert not t1.is_derived_from(select([t1]))
assert t1.alias().is_derived_from(t1)
s1 = select([t1, t2]).alias('foo')
s2 = select([s1]).limit(5).offset(10).alias()
assert s2.is_derived_from(s1)
s2 = s2._clone()
assert s2.is_derived_from(s1)
def test_aliasedselect_to_aliasedselect(self):
# original issue from ticket #904
s1 = select([t1]).alias('foo')
s2 = select([s1]).limit(5).offset(10).alias()
self.assert_compile(sql_util.ClauseAdapter(s2).traverse(s1),
"SELECT foo.col1, foo.col2, foo.col3 FROM (SELECT table1.col1 AS col1, table1.col2 AS col2, table1.col3 AS col3 FROM table1) AS foo LIMIT 5 OFFSET 10")
j = s1.outerjoin(t2, s1.c.col1==t2.c.col1)
self.assert_compile(sql_util.ClauseAdapter(s2).traverse(j).select(),
"SELECT anon_1.col1, anon_1.col2, anon_1.col3, table2.col1, table2.col2, table2.col3 FROM "\
"(SELECT foo.col1 AS col1, foo.col2 AS col2, foo.col3 AS col3 FROM "\
"(SELECT table1.col1 AS col1, table1.col2 AS col2, table1.col3 AS col3 FROM table1) AS foo LIMIT 5 OFFSET 10) AS anon_1 "\
"LEFT OUTER JOIN table2 ON anon_1.col1 = table2.col1")
talias = t1.alias('bar')
j = s1.outerjoin(talias, s1.c.col1==talias.c.col1)
self.assert_compile(sql_util.ClauseAdapter(s2).traverse(j).select(),
"SELECT anon_1.col1, anon_1.col2, anon_1.col3, bar.col1, bar.col2, bar.col3 FROM "\
"(SELECT foo.col1 AS col1, foo.col2 AS col2, foo.col3 AS col3 FROM "\
"(SELECT table1.col1 AS col1, table1.col2 AS col2, table1.col3 AS col3 FROM table1) AS foo LIMIT 5 OFFSET 10) AS anon_1 "\
"LEFT OUTER JOIN table1 AS bar ON anon_1.col1 = bar.col1")
def test_functions(self):
self.assert_compile(sql_util.ClauseAdapter(t1.alias()).traverse(func.count(t1.c.col1)), "count(table1_1.col1)")
s = select([func.count(t1.c.col1)])
self.assert_compile(sql_util.ClauseAdapter(t1.alias()).traverse(s), "SELECT count(table1_1.col1) AS count_1 FROM table1 AS table1_1")
def test_recursive(self):
metadata = MetaData()
a = Table('a', metadata,
Column('id', Integer, primary_key=True))
b = Table('b', metadata,
Column('id', Integer, primary_key=True),
Column('aid', Integer, ForeignKey('a.id')),
)
c = Table('c', metadata,
Column('id', Integer, primary_key=True),
Column('bid', Integer, ForeignKey('b.id')),
)
d = Table('d', metadata,
Column('id', Integer, primary_key=True),
Column('aid', Integer, ForeignKey('a.id')),
)
u = union(
a.join(b).select().apply_labels(),
a.join(d).select().apply_labels()
).alias()
self.assert_compile(
sql_util.ClauseAdapter(u).traverse(select([c.c.bid]).where(c.c.bid==u.c.b_aid)),
"SELECT c.bid "\
"FROM c, (SELECT a.id AS a_id, b.id AS b_id, b.aid AS b_aid "\
"FROM a JOIN b ON a.id = b.aid UNION SELECT a.id AS a_id, d.id AS d_id, d.aid AS d_aid "\
"FROM a JOIN d ON a.id = d.aid) AS anon_1 "\
"WHERE c.bid = anon_1.b_aid"
)
class SpliceJoinsTest(TestBase, AssertsCompiledSQL):
@classmethod
def setup_class(cls):
global table1, table2, table3, table4
def _table(name):
return table(name, column("col1"), column("col2"),column("col3"))
table1, table2, table3, table4 = [_table(name) for name in ("table1", "table2", "table3", "table4")]
def test_splice(self):
(t1, t2, t3, t4) = (table1, table2, table1.alias(), table2.alias())
j = t1.join(t2, t1.c.col1==t2.c.col1).join(t3, t2.c.col1==t3.c.col1).join(t4, t4.c.col1==t1.c.col1)
s = select([t1]).where(t1.c.col2<5).alias()
self.assert_compile(sql_util.splice_joins(s, j),
"(SELECT table1.col1 AS col1, table1.col2 AS col2, "\
"table1.col3 AS col3 FROM table1 WHERE table1.col2 < :col2_1) AS anon_1 "\
"JOIN table2 ON anon_1.col1 = table2.col1 JOIN table1 AS table1_1 ON table2.col1 = table1_1.col1 "\
"JOIN table2 AS table2_1 ON table2_1.col1 = anon_1.col1")
def test_stop_on(self):
(t1, t2, t3) = (table1, table2, table3)
j1= t1.join(t2, t1.c.col1==t2.c.col1)
j2 = j1.join(t3, t2.c.col1==t3.c.col1)
s = select([t1]).select_from(j1).alias()
self.assert_compile(sql_util.splice_joins(s, j2),
"(SELECT table1.col1 AS col1, table1.col2 AS col2, table1.col3 AS col3 FROM table1 JOIN table2 "\
"ON table1.col1 = table2.col1) AS anon_1 JOIN table2 ON anon_1.col1 = table2.col1 JOIN table3 "\
"ON table2.col1 = table3.col1"
)
self.assert_compile(sql_util.splice_joins(s, j2, j1),
"(SELECT table1.col1 AS col1, table1.col2 AS col2, table1.col3 AS col3 FROM table1 "\
"JOIN table2 ON table1.col1 = table2.col1) AS anon_1 JOIN table3 ON table2.col1 = table3.col1")
def test_splice_2(self):
t2a = table2.alias()
t3a = table3.alias()
j1 = table1.join(t2a, table1.c.col1==t2a.c.col1).join(t3a, t2a.c.col2==t3a.c.col2)
t2b = table4.alias()
j2 = table1.join(t2b, table1.c.col3==t2b.c.col3)
self.assert_compile(sql_util.splice_joins(table1, j1),
"table1 JOIN table2 AS table2_1 ON table1.col1 = table2_1.col1 "\
"JOIN table3 AS table3_1 ON table2_1.col2 = table3_1.col2")
self.assert_compile(sql_util.splice_joins(table1, j2), "table1 JOIN table4 AS table4_1 ON table1.col3 = table4_1.col3")
self.assert_compile(sql_util.splice_joins(sql_util.splice_joins(table1, j1), j2),
"table1 JOIN table2 AS table2_1 ON table1.col1 = table2_1.col1 "\
"JOIN table3 AS table3_1 ON table2_1.col2 = table3_1.col2 "\
"JOIN table4 AS table4_1 ON table1.col3 = table4_1.col3")
class SelectTest(TestBase, AssertsCompiledSQL):
"""tests the generative capability of Select"""
@classmethod
def setup_class(cls):
global t1, t2
t1 = table("table1",
column("col1"),
column("col2"),
column("col3"),
)
t2 = table("table2",
column("col1"),
column("col2"),
column("col3"),
)
def test_select(self):
self.assert_compile(t1.select().where(t1.c.col1==5).order_by(t1.c.col3),
"SELECT table1.col1, table1.col2, table1.col3 FROM table1 WHERE table1.col1 = :col1_1 ORDER BY table1.col3")
self.assert_compile(t1.select().select_from(select([t2], t2.c.col1==t1.c.col1)).order_by(t1.c.col3),
"SELECT table1.col1, table1.col2, table1.col3 FROM table1, (SELECT table2.col1 AS col1, table2.col2 AS col2, table2.col3 AS col3 "\
"FROM table2 WHERE table2.col1 = table1.col1) ORDER BY table1.col3")
s = select([t2], t2.c.col1==t1.c.col1, correlate=False)
s = s.correlate(t1).order_by(t2.c.col3)
self.assert_compile(t1.select().select_from(s).order_by(t1.c.col3),
"SELECT table1.col1, table1.col2, table1.col3 FROM table1, (SELECT table2.col1 AS col1, table2.col2 AS col2, table2.col3 AS col3 "\
"FROM table2 WHERE table2.col1 = table1.col1 ORDER BY table2.col3) ORDER BY table1.col3")
def test_columns(self):
s = t1.select()
self.assert_compile(s, "SELECT table1.col1, table1.col2, table1.col3 FROM table1")
select_copy = s.column('yyy')
self.assert_compile(select_copy, "SELECT table1.col1, table1.col2, table1.col3, yyy FROM table1")
assert s.columns is not select_copy.columns
assert s._columns is not select_copy._columns
assert s._raw_columns is not select_copy._raw_columns
self.assert_compile(s, "SELECT table1.col1, table1.col2, table1.col3 FROM table1")
def test_froms(self):
s = t1.select()
self.assert_compile(s, "SELECT table1.col1, table1.col2, table1.col3 FROM table1")
select_copy = s.select_from(t2)
self.assert_compile(select_copy, "SELECT table1.col1, table1.col2, table1.col3 FROM table1, table2")
assert s._froms is not select_copy._froms
self.assert_compile(s, "SELECT table1.col1, table1.col2, table1.col3 FROM table1")
def test_correlation(self):
s = select([t2], t1.c.col1==t2.c.col1)
self.assert_compile(s, "SELECT table2.col1, table2.col2, table2.col3 FROM table2, table1 WHERE table1.col1 = table2.col1")
s2 = select([t1], t1.c.col2==s.c.col2)
self.assert_compile(s2, "SELECT table1.col1, table1.col2, table1.col3 FROM table1, "
"(SELECT table2.col1 AS col1, table2.col2 AS col2, table2.col3 AS col3 FROM table2 "
"WHERE table1.col1 = table2.col1) WHERE table1.col2 = col2")
s3 = s.correlate(None)
self.assert_compile(select([t1], t1.c.col2==s3.c.col2), "SELECT table1.col1, table1.col2, table1.col3 FROM table1, "
"(SELECT table2.col1 AS col1, table2.col2 AS col2, table2.col3 AS col3 FROM table2, table1 "
"WHERE table1.col1 = table2.col1) WHERE table1.col2 = col2")
self.assert_compile(select([t1], t1.c.col2==s.c.col2), "SELECT table1.col1, table1.col2, table1.col3 FROM table1, "
"(SELECT table2.col1 AS col1, table2.col2 AS col2, table2.col3 AS col3 FROM table2 "
"WHERE table1.col1 = table2.col1) WHERE table1.col2 = col2")
s4 = s3.correlate(t1)
self.assert_compile(select([t1], t1.c.col2==s4.c.col2), "SELECT table1.col1, table1.col2, table1.col3 FROM table1, "
"(SELECT table2.col1 AS col1, table2.col2 AS col2, table2.col3 AS col3 FROM table2 "
"WHERE table1.col1 = table2.col1) WHERE table1.col2 = col2")
self.assert_compile(select([t1], t1.c.col2==s3.c.col2), "SELECT table1.col1, table1.col2, table1.col3 FROM table1, "
"(SELECT table2.col1 AS col1, table2.col2 AS col2, table2.col3 AS col3 FROM table2, table1 "
"WHERE table1.col1 = table2.col1) WHERE table1.col2 = col2")
def test_prefixes(self):
s = t1.select()
self.assert_compile(s, "SELECT table1.col1, table1.col2, table1.col3 FROM table1")
select_copy = s.prefix_with("FOOBER")
self.assert_compile(select_copy, "SELECT FOOBER table1.col1, table1.col2, table1.col3 FROM table1")
self.assert_compile(s, "SELECT table1.col1, table1.col2, table1.col3 FROM table1")
def test_execution_options(self):
s = select().execution_options(foo='bar')
s2 = s.execution_options(bar='baz')
s3 = s.execution_options(foo='not bar')
# The original select should not be modified.
assert s._execution_options == dict(foo='bar')
# s2 should have its execution_options based on s, though.
assert s2._execution_options == dict(foo='bar', bar='baz')
assert s3._execution_options == dict(foo='not bar')
# this feature not available yet
def _NOTYET_test_execution_options_in_kwargs(self):
s = select(execution_options=dict(foo='bar'))
s2 = s.execution_options(bar='baz')
# The original select should not be modified.
assert s._execution_options == dict(foo='bar')
# s2 should have its execution_options based on s, though.
assert s2._execution_options == dict(foo='bar', bar='baz')
# this feature not available yet
def _NOTYET_test_execution_options_in_text(self):
s = text('select 42', execution_options=dict(foo='bar'))
assert s._execution_options == dict(foo='bar')
class InsertTest(TestBase, AssertsCompiledSQL):
"""Tests the generative capability of Insert"""
# fixme: consolidate converage from elsewhere here and expand
@classmethod
def setup_class(cls):
global t1, t2
t1 = table("table1",
column("col1"),
column("col2"),
column("col3"),
)
t2 = table("table2",
column("col1"),
column("col2"),
column("col3"),
)
def test_prefixes(self):
i = t1.insert()
self.assert_compile(i,
"INSERT INTO table1 (col1, col2, col3) "
"VALUES (:col1, :col2, :col3)")
gen = i.prefix_with("foober")
self.assert_compile(gen,
"INSERT foober INTO table1 (col1, col2, col3) "
"VALUES (:col1, :col2, :col3)")
self.assert_compile(i,
"INSERT INTO table1 (col1, col2, col3) "
"VALUES (:col1, :col2, :col3)")
i2 = t1.insert(prefixes=['squiznart'])
self.assert_compile(i2,
"INSERT squiznart INTO table1 (col1, col2, col3) "
"VALUES (:col1, :col2, :col3)")
gen2 = i2.prefix_with("quux")
self.assert_compile(gen2,
"INSERT squiznart quux INTO "
"table1 (col1, col2, col3) "
"VALUES (:col1, :col2, :col3)")
|
obeattie/sqlalchemy
|
test/sql/test_generative.py
|
Python
|
mit
| 38,671
|
[
"ADF"
] |
30e167addb32a282504934da473782a6284aa1a9622347c2f147538cdda1e321
|
# Copyright 2016 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Utilities for `gcloud app` deployment.
Mostly created to selectively enable Cloud Endpoints in the beta/preview release
tracks.
"""
import argparse
import os
from googlecloudsdk.api_lib.app import appengine_api_client
from googlecloudsdk.api_lib.app import appengine_client
from googlecloudsdk.api_lib.app import cloud_endpoints
from googlecloudsdk.api_lib.app import deploy_app_command_util
from googlecloudsdk.api_lib.app import deploy_command_util
from googlecloudsdk.api_lib.app import exceptions as api_lib_exceptions
from googlecloudsdk.api_lib.app import metric_names
from googlecloudsdk.api_lib.app import util
from googlecloudsdk.api_lib.app import version_util
from googlecloudsdk.api_lib.app import yaml_parsing
from googlecloudsdk.api_lib.storage import storage_util
from googlecloudsdk.calliope import actions
from googlecloudsdk.calliope import exceptions as calliope_exceptions
from googlecloudsdk.command_lib.app import create_util
from googlecloudsdk.command_lib.app import exceptions
from googlecloudsdk.command_lib.app import flags
from googlecloudsdk.command_lib.app import output_helpers
from googlecloudsdk.command_lib.app import staging
from googlecloudsdk.core import exceptions as core_exceptions
from googlecloudsdk.core import log
from googlecloudsdk.core import metrics
from googlecloudsdk.core import properties
from googlecloudsdk.core.console import console_io
from googlecloudsdk.core.console import progress_tracker
class VersionPromotionError(core_exceptions.Error):
def __init__(self, err):
super(VersionPromotionError, self).__init__(
'Your deployment has succeeded, but promoting the new version to '
'default failed. '
'You may not have permissions to change traffic splits. '
'Changing traffic splits requires the Owner, Editor, App Engine Admin, '
'or App Engine Service Admin role. '
'Please contact your project owner and use the '
'`gcloud app services set-traffic --splits <version>=1` command to '
'redirect traffic to your newly deployed version.\n\n'
'Original error: ' + str(err))
GSUTIL_DEPRECATION_WARNING = """\
Your gcloud installation has a deprecated config property enabled: \
[app/use_gsutil], which will be removed in a future version. Run \
`gcloud config unset app/use_gsutil` to switch to the recommended approach. \
If you encounter any issues, please report using `gcloud feedback`. To \
revert temporarily, run `gcloud config set app/use_gsutil True`.
"""
MANAGED_VMS_DEPRECATION_WARNING = """\
Deployments using `vm: true` have been deprecated. Please update your \
app.yaml to use `env: flex`. To learn more, please visit \
https://cloud.google.com/appengine/docs/flexible/migration.
"""
class DeployOptions(object):
"""Values of options that affect deployment process in general.
No deployment details (e.g. targets for a specific deployment).
Attributes:
promote: True if the deployed version should recieve all traffic.
stop_previous_version: Stop previous version
enable_endpoints: Enable Cloud Endpoints for the deployed app.
upload_strategy: deploy_app_command_util.UploadStrategy, the file upload
strategy to be used for this deployment.
use_runtime_builders: bool, whether to use the new CloudBuild-based
runtime builders (alternative is old externalized runtimes).
"""
def __init__(self, promote, stop_previous_version, enable_endpoints,
upload_strategy, use_runtime_builders):
self.promote = promote
self.stop_previous_version = stop_previous_version
self.enable_endpoints = enable_endpoints
self.upload_strategy = upload_strategy
self.use_runtime_builders = use_runtime_builders
@classmethod
def FromProperties(cls, enable_endpoints, upload_strategy,
use_runtime_builders):
promote = properties.VALUES.app.promote_by_default.GetBool()
stop_previous_version = (
properties.VALUES.app.stop_previous_version.GetBool())
if upload_strategy is None:
upload_strategy = deploy_app_command_util.UploadStrategy.PROCESSES
if properties.VALUES.app.use_gsutil.GetBool():
log.warning(GSUTIL_DEPRECATION_WARNING)
upload_strategy = deploy_app_command_util.UploadStrategy.GSUTIL
return cls(promote, stop_previous_version, enable_endpoints,
upload_strategy, use_runtime_builders)
class ServiceDeployer(object):
"""Coordinator (reusable) for deployment of one service at a time.
Attributes:
api_client: api_lib.app.appengine_api_client.AppengineClient, App Engine
Admin API client.
stager: command_lib.app.staging.Stager, the object used to potentially stage
applications with matching runtime/environment combinations.
deploy_options: DeployOptions, the options to use for services deployed by
this ServiceDeployer.
"""
def __init__(self, api_client, stager, deploy_options):
self.api_client = api_client
self.stager = stager
self.deploy_options = deploy_options
def _PossiblyConfigureEndpoints(self, service, source_dir, new_version):
"""Configures endpoints for this service (if enabled).
If the app has enabled Endpoints API Management features, pass control to
the cloud_endpoints handler.
The cloud_endpoints handler calls the Service Management APIs and creates an
endpoints/service.json file on disk which will need to be bundled into the
app Docker image.
Args:
service: yaml_parsing.ServiceYamlInfo, service configuration to be
deployed
source_dir: str, path to the service's source directory
new_version: version_util.Version describing where to deploy the service
Returns:
EndpointsServiceInfo, or None if endpoints were not created.
"""
if self.deploy_options.enable_endpoints:
return cloud_endpoints.ProcessEndpointsService(service, source_dir,
new_version.project)
return None
def _PossiblyBuildAndPush(self, new_version, service, source_dir, image,
code_bucket_ref):
"""Builds and Pushes the Docker image if necessary for this service.
Args:
new_version: version_util.Version describing where to deploy the service
service: yaml_parsing.ServiceYamlInfo, service configuration to be
deployed
source_dir: str, path to the service's source directory
image: str or None, the URL for the Docker image to be deployed (if image
already exists).
code_bucket_ref: cloud_storage.BucketReference where the service's files
have been uploaded
Returns:
str, The name of the pushed or given container image or None if the
service does not require an image.
"""
if service.RequiresImage():
if service.env in [util.Environment.FLEX, util.Environment.MANAGED_VMS]:
log.warning('Deployment of App Engine Flexible Environment apps is '
'currently in Beta')
if not image:
image = deploy_command_util.BuildAndPushDockerImage(
new_version.project, service, source_dir, new_version.id,
code_bucket_ref, self.deploy_options.use_runtime_builders)
elif service.parsed.skip_files.regex:
log.warning('Deployment of service [{0}] will ignore the skip_files '
'field in the configuration file, because the image has '
'already been built.'.format(new_version.service))
else:
image = None
return image
def _PossiblyPromote(self, all_services, new_version):
"""Promotes the new version to default (if specified by the user).
Args:
all_services: dict of service ID to service_util.Service objects
corresponding to all pre-existing services (used to determine how to
promote this version to receive all traffic, if applicable).
new_version: version_util.Version describing where to deploy the service
Raises:
VersionPromotionError: if the version could not successfully promoted
"""
if self.deploy_options.promote:
try:
version_util.PromoteVersion(
all_services, new_version, self.api_client,
self.deploy_options.stop_previous_version)
except calliope_exceptions.HttpException as err:
raise VersionPromotionError(err)
elif self.deploy_options.stop_previous_version:
log.info('Not stopping previous version because new version was '
'not promoted.')
def Deploy(self, service, new_version, code_bucket_ref, image, all_services):
"""Deploy the given service.
Performs all deployment steps for the given service (if applicable):
* Enable endpoints (for beta deployments)
* Build and push the Docker image (Flex only, if image_url not provided)
* Upload files (non-hermetic deployments)
* Create the new version
* Promote the version to receieve all traffic (if --promote given (default))
* Stop the previous version (if new version promoted and
--stop-previous-version given (default))
Args:
service: yaml_parsing.ServiceYamlInfo, service configuration to be
deployed
new_version: version_util.Version describing where to deploy the service
code_bucket_ref: cloud_storage.BucketReference where the service's files
have been uploaded
image: str or None, the URL for the Docker image to be deployed (if image
already exists).
all_services: dict of service ID to service_util.Service objects
corresponding to all pre-existing services (used to determine how to
promote this version to receive all traffic, if applicable).
"""
log.status.Print('Beginning deployment of service [{service}]...'
.format(service=new_version.service))
if service.env is util.Environment.MANAGED_VMS:
log.warning(MANAGED_VMS_DEPRECATION_WARNING)
with self.stager.Stage(service.file, service.runtime,
service.env) as staging_dir:
source_dir = staging_dir or os.path.dirname(service.file)
endpoints_info = self._PossiblyConfigureEndpoints(
service, source_dir, new_version)
image = self._PossiblyBuildAndPush(
new_version, service, source_dir, image, code_bucket_ref)
manifest = None
# "Non-hermetic" services require file upload outside the Docker image.
if not service.is_hermetic:
manifest = deploy_app_command_util.CopyFilesToCodeBucket(
service, source_dir, code_bucket_ref,
self.deploy_options.upload_strategy)
# Actually create the new version of the service.
message = 'Updating service [{service}]'.format(
service=new_version.service)
with progress_tracker.ProgressTracker(message):
self.api_client.DeployService(new_version.service, new_version.id,
service, manifest, image,
endpoints_info)
metrics.CustomTimedEvent(metric_names.DEPLOY_API)
self._PossiblyPromote(all_services, new_version)
def ArgsDeploy(parser):
"""Get arguments for this command.
Args:
parser: argparse.ArgumentParser, the parser for this command.
"""
flags.SERVER_FLAG.AddToParser(parser)
flags.IGNORE_CERTS_FLAG.AddToParser(parser)
flags.DOCKER_BUILD_FLAG.AddToParser(parser)
parser.add_argument(
'--version', '-v', type=flags.VERSION_TYPE,
help='The version of the app that will be created or replaced by this '
'deployment. If you do not specify a version, one will be generated for '
'you.')
parser.add_argument(
'--bucket',
type=storage_util.BucketReference.FromArgument,
help=("The Google Cloud Storage bucket used to stage files associated "
"with the deployment. If this argument is not specified, the "
"application's default code bucket is used."))
deployables = parser.add_argument(
'deployables', nargs='*',
help='The yaml files for the services or configurations you want to '
'deploy.')
deployables.detailed_help = (
'The yaml files for the services or configurations you want to deploy. '
'If not given, defaults to `app.yaml` in the current directory. '
'If that is not found, attempts to automatically generate necessary '
'configuration files (such as app.yaml) in the current directory.')
parser.add_argument(
'--stop-previous-version',
action=actions.StoreBooleanProperty(
properties.VALUES.app.stop_previous_version),
help='Stop the previously running version when deploying a new version '
'that receives all traffic.')
parser.add_argument(
'--image-url',
help='Deploy with a specific Docker image. Docker url must be from one '
'of the valid gcr hostnames.')
promote = parser.add_argument(
'--promote',
action=actions.StoreBooleanProperty(
properties.VALUES.app.promote_by_default),
help='Promote the deployed version to receive all traffic.')
promote.detailed_help = (
'Promote the deployed version to receive all traffic.\n\n'
'True by default. To change the default behavior for your current '
'environment, run:\n\n'
' $ gcloud config set app/promote_by_default false')
parser.add_argument(
'--skip-staging',
action='store_true',
default=False,
help=argparse.SUPPRESS)
# For internal use only
parser.add_argument(
'--skip-image-url-validation',
action='store_true',
default=False,
help=argparse.SUPPRESS)
def RunDeploy(args, enable_endpoints=False, use_beta_stager=False,
upload_strategy=None, use_runtime_builders=False):
"""Perform a deployment based on the given args.
Args:
args: argparse.Namespace, An object that contains the values for the
arguments specified in the ArgsDeploy() function.
enable_endpoints: Enable Cloud Endpoints for the deployed app.
use_beta_stager: Use the stager registry defined for the beta track rather
than the default stager registry.
upload_strategy: deploy_app_command_util.UploadStrategy, the parallelism
straetgy to use for uploading files, or None to use the default.
use_runtime_builders: bool, whether to use the new CloudBuild-based
runtime builders (alternative is old externalized runtimes).
Returns:
A dict on the form `{'versions': new_versions, 'configs': updated_configs}`
where new_versions is a list of version_util.Version, and updated_configs
is a list of config file identifiers, see yaml_parsing.ConfigYamlInfo.
"""
project = properties.VALUES.core.project.Get(required=True)
deploy_options = DeployOptions.FromProperties(
enable_endpoints, upload_strategy=upload_strategy,
use_runtime_builders=use_runtime_builders)
# Parse existing app.yamls or try to generate a new one if the directory is
# empty.
if not args.deployables:
yaml_path = deploy_command_util.DEFAULT_DEPLOYABLE
if not os.path.exists(deploy_command_util.DEFAULT_DEPLOYABLE):
log.warning('Automatic app detection is currently in Beta')
yaml_path = deploy_command_util.CreateAppYamlForAppDirectory(os.getcwd())
app_config = yaml_parsing.AppConfigSet([yaml_path])
else:
app_config = yaml_parsing.AppConfigSet(args.deployables)
# If applicable, sort services by order they were passed to the command.
services = app_config.Services()
if not args.skip_image_url_validation:
flags.ValidateImageUrl(args.image_url, services)
# The new API client.
api_client = appengine_api_client.GetApiClient()
# pylint: disable=protected-access
log.debug('API endpoint: [{endpoint}], API version: [{version}]'.format(
endpoint=api_client.client.url,
version=api_client.client._VERSION))
# The legacy admin console API client.
# The Admin Console API existed long before the App Engine Admin API, and
# isn't being improved. We're in the process of migrating all of the calls
# over to the Admin API, but a few things (notably config deployments) haven't
# been ported over yet.
ac_client = appengine_client.AppengineClient(
args.server, args.ignore_bad_certs)
app = _PossiblyCreateApp(api_client, project)
app = _PossiblyRepairApp(api_client, app)
# Tell the user what is going to happen, and ask them to confirm.
version_id = args.version or util.GenerateVersionId()
deployed_urls = output_helpers.DisplayProposedDeployment(
app, project, app_config, version_id, deploy_options.promote)
console_io.PromptContinue(cancel_on_no=True)
if services:
# Do generic app setup if deploying any services.
# All deployment paths for a service involve uploading source to GCS.
code_bucket_ref = args.bucket or flags.GetCodeBucket(app, project)
metrics.CustomTimedEvent(metric_names.GET_CODE_BUCKET)
log.debug('Using bucket [{b}].'.format(b=code_bucket_ref.ToBucketUrl()))
# Prepare Flex if any service is going to deploy an image.
if any([m.RequiresImage() for m in services.values()]):
deploy_command_util.DoPrepareManagedVms(ac_client)
all_services = dict([(s.id, s) for s in api_client.ListServices()])
else:
code_bucket_ref = None
all_services = {}
new_versions = []
if args.skip_staging:
stager = staging.GetNoopStager()
elif use_beta_stager:
stager = staging.GetBetaStager()
else:
stager = staging.GetStager()
deployer = ServiceDeployer(api_client, stager, deploy_options)
for name, service in services.iteritems():
new_version = version_util.Version(project, name, version_id)
deployer.Deploy(service, new_version, code_bucket_ref, args.image_url,
all_services)
new_versions.append(new_version)
log.status.Print('Deployed service [{0}] to [{1}]'.format(
name, deployed_urls[name]))
# Deploy config files.
for (name, config) in app_config.Configs().iteritems():
message = 'Updating config [{config}]'.format(config=name)
with progress_tracker.ProgressTracker(message):
ac_client.UpdateConfig(name, config.parsed)
updated_configs = app_config.Configs().keys()
PrintPostDeployHints(new_versions, updated_configs)
# Return all the things that were deployed.
return {
'versions': new_versions,
'configs': updated_configs
}
# TODO(b/30632016): Move to Epilog() when we have a good way to pass
# information about the deployed versions
def PrintPostDeployHints(new_versions, updated_configs):
"""Print hints for user at the end of a deployment."""
if yaml_parsing.ConfigYamlInfo.CRON in updated_configs:
log.status.Print('\nCron jobs have been updated.')
if yaml_parsing.ConfigYamlInfo.QUEUE not in updated_configs:
log.status.Print('\nVisit the Cloud Platform Console Task Queues page '
'to view your queues and cron jobs.')
if yaml_parsing.ConfigYamlInfo.DISPATCH in updated_configs:
log.status.Print('\nCustom routings have been updated.')
if yaml_parsing.ConfigYamlInfo.DOS in updated_configs:
log.status.Print('\nDoS protection has been updated.'
'\n\nTo delete all blacklist entries, change the dos.yaml '
'file to just contain:'
'\n blacklist:'
'and redeploy it.')
if yaml_parsing.ConfigYamlInfo.QUEUE in updated_configs:
log.status.Print('\nTask queues have been updated.')
log.status.Print('\nVisit the Cloud Platform Console Task Queues page '
'to view your queues and cron jobs.')
if yaml_parsing.ConfigYamlInfo.INDEX in updated_configs:
log.status.Print('\nIndexes are being rebuilt. This may take a moment.')
if not new_versions:
return
elif len(new_versions) > 1:
service_hint = ' -s <service>'
elif new_versions[0].service == 'default':
service_hint = ''
else:
service = new_versions[0].service
service_hint = ' -s {svc}'.format(svc=service)
log.status.Print(
'\nYou can stream logs from the command line by running:\n'
' $ gcloud app logs tail' + (service_hint or ' -s default'))
log.status.Print(
'\nTo view your application in the web browser run:\n'
' $ gcloud app browse' + service_hint)
def _PossiblyCreateApp(api_client, project):
"""Returns an app resource, and creates it if the stars are aligned.
App creation happens only if the current project is app-less, we are running
in interactive mode and the user explicitly wants to.
Args:
api_client: Admin API client.
project: The GCP project/app id.
Returns:
An app object (never returns None).
Raises:
MissingApplicationError: If an app does not exist and cannot be created.
"""
try:
return api_client.GetApplication()
except api_lib_exceptions.NotFoundError:
# Invariant: GCP Project does exist but (singleton) GAE app is not yet
# created.
#
# Check for interactive mode, since this action is irreversible and somewhat
# surprising. CreateAppInteractively will provide a cancel option for
# interactive users, and MissingApplicationException includes instructions
# for non-interactive users to fix this.
log.debug('No app found:', exc_info=True)
if console_io.CanPrompt():
# Equivalent to running `gcloud app create`
create_util.CreateAppInteractively(api_client, project)
# App resource must be fetched again
return api_client.GetApplication()
raise exceptions.MissingApplicationError(project)
def _PossiblyRepairApp(api_client, app):
"""Repairs the app if necessary and returns a healthy app object.
An app is considered unhealthy if the codeBucket field is missing.
This may include more conditions in the future.
Args:
api_client: Admin API client.
app: App object (with potentially missing resources).
Returns:
An app object (either the same or a new one), which contains the right
resources, including code bucket.
"""
if not app.codeBucket:
with progress_tracker.ProgressTracker('Initializing App Engine resources'):
api_client.RepairApplication()
app = api_client.GetApplication()
return app
|
Sorsly/subtle
|
google-cloud-sdk/lib/googlecloudsdk/command_lib/app/deploy_util.py
|
Python
|
mit
| 22,926
|
[
"VisIt"
] |
1edb4f13cc60e4ea952bc7b8fe9717c7c5104b2550248c3bd7d2d8ce9d7c79f4
|
#
# Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License, Version 2.0
# (the "License"); you may not use this file except in compliance with
# the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
"""Pipeline, the top-level Dataflow object.
A pipeline holds a DAG of data transforms. Conceptually the nodes of the DAG
are transforms (PTransform objects) and the edges are values (mostly PCollection
objects). The transforms take as inputs one or more PValues and output one or
more PValues.
The pipeline offers functionality to traverse the graph. The actual operation
to be executed for each node visited is specified through a runner object.
Typical usage:
# Create a pipeline object using a local runner for execution.
with beam.Pipeline('DirectRunner') as p:
# Add to the pipeline a "Create" transform. When executed this
# transform will produce a PCollection object with the specified values.
pcoll = p | 'Create' >> beam.Create([1, 2, 3])
# Another transform could be applied to pcoll, e.g., writing to a text file.
# For other transforms, refer to transforms/ directory.
pcoll | 'Write' >> beam.io.WriteToText('./output')
# run() will execute the DAG stored in the pipeline. The execution of the
# nodes visited is done using the specified local runner.
"""
from __future__ import absolute_import
import collections
import logging
import os
import shutil
import tempfile
from apache_beam import pvalue
from apache_beam.internal import pickler
from apache_beam.runners import create_runner
from apache_beam.runners import PipelineRunner
from apache_beam.transforms import ptransform
from apache_beam.typehints import typehints
from apache_beam.typehints import TypeCheckError
from apache_beam.options.pipeline_options import PipelineOptions
from apache_beam.options.pipeline_options import SetupOptions
from apache_beam.options.pipeline_options import StandardOptions
from apache_beam.options.pipeline_options import TypeOptions
from apache_beam.options.pipeline_options_validator import PipelineOptionsValidator
from apache_beam.utils.annotations import deprecated
__all__ = ['Pipeline']
class Pipeline(object):
"""A pipeline object that manages a DAG of PValues and their PTransforms.
Conceptually the PValues are the DAG's nodes and the PTransforms computing
the PValues are the edges.
All the transforms applied to the pipeline must have distinct full labels.
If same transform instance needs to be applied then the right shift operator
should be used to designate new names (e.g. `input | "label" >> my_tranform`).
"""
def __init__(self, runner=None, options=None, argv=None):
"""Initialize a pipeline object.
Args:
runner: An object of type 'PipelineRunner' that will be used to execute
the pipeline. For registered runners, the runner name can be specified,
otherwise a runner object must be supplied.
options: A configured 'PipelineOptions' object containing arguments
that should be used for running the Dataflow job.
argv: a list of arguments (such as sys.argv) to be used for building a
'PipelineOptions' object. This will only be used if argument 'options'
is None.
Raises:
ValueError: if either the runner or options argument is not of the
expected type.
"""
if options is not None:
if isinstance(options, PipelineOptions):
self._options = options
else:
raise ValueError(
'Parameter options, if specified, must be of type PipelineOptions. '
'Received : %r', options)
elif argv is not None:
if isinstance(argv, list):
self._options = PipelineOptions(argv)
else:
raise ValueError(
'Parameter argv, if specified, must be a list. Received : %r', argv)
else:
self._options = PipelineOptions([])
if runner is None:
runner = self._options.view_as(StandardOptions).runner
if runner is None:
runner = StandardOptions.DEFAULT_RUNNER
logging.info(('Missing pipeline option (runner). Executing pipeline '
'using the default runner: %s.'), runner)
if isinstance(runner, str):
runner = create_runner(runner)
elif not isinstance(runner, PipelineRunner):
raise TypeError('Runner must be a PipelineRunner object or the '
'name of a registered runner.')
# Validate pipeline options
errors = PipelineOptionsValidator(self._options, runner).validate()
if errors:
raise ValueError(
'Pipeline has validations errors: \n' + '\n'.join(errors))
# Default runner to be used.
self.runner = runner
# Stack of transforms generated by nested apply() calls. The stack will
# contain a root node as an enclosing (parent) node for top transforms.
self.transforms_stack = [AppliedPTransform(None, None, '', None)]
# Set of transform labels (full labels) applied to the pipeline.
# If a transform is applied and the full label is already in the set
# then the transform will have to be cloned with a new label.
self.applied_labels = set()
@property
@deprecated(since='First stable release',
extra_message='References to <pipeline>.options'
' will not be supported')
def options(self):
return self._options
def _current_transform(self):
"""Returns the transform currently on the top of the stack."""
return self.transforms_stack[-1]
def _root_transform(self):
"""Returns the root transform of the transform stack."""
return self.transforms_stack[0]
def run(self, test_runner_api=True):
"""Runs the pipeline. Returns whatever our runner returns after running."""
# When possible, invoke a round trip through the runner API.
if test_runner_api and self._verify_runner_api_compatible():
return Pipeline.from_runner_api(
self.to_runner_api(), self.runner, self._options).run(False)
if self._options.view_as(SetupOptions).save_main_session:
# If this option is chosen, verify we can pickle the main session early.
tmpdir = tempfile.mkdtemp()
try:
pickler.dump_session(os.path.join(tmpdir, 'main_session.pickle'))
finally:
shutil.rmtree(tmpdir)
return self.runner.run(self)
def __enter__(self):
return self
def __exit__(self, exc_type, exc_val, exc_tb):
if not exc_type:
self.run().wait_until_finish()
def visit(self, visitor):
"""Visits depth-first every node of a pipeline's DAG.
Runner-internal implementation detail; no backwards-compatibility guarantees
Args:
visitor: PipelineVisitor object whose callbacks will be called for each
node visited. See PipelineVisitor comments.
Raises:
TypeError: if node is specified and is not a PValue.
pipeline.PipelineError: if node is specified and does not belong to this
pipeline instance.
"""
visited = set()
self._root_transform().visit(visitor, self, visited)
def apply(self, transform, pvalueish=None, label=None):
"""Applies a custom transform using the pvalueish specified.
Args:
transform: the PTranform to apply.
pvalueish: the input for the PTransform (typically a PCollection).
label: label of the PTransform.
Raises:
TypeError: if the transform object extracted from the argument list is
not a PTransform.
RuntimeError: if the transform object was already applied to this pipeline
and needs to be cloned in order to apply again.
"""
if isinstance(transform, ptransform._NamedPTransform):
return self.apply(transform.transform, pvalueish,
label or transform.label)
if not isinstance(transform, ptransform.PTransform):
raise TypeError("Expected a PTransform object, got %s" % transform)
if label:
# Fix self.label as it is inspected by some PTransform operations
# (e.g. to produce error messages for type hint violations).
try:
old_label, transform.label = transform.label, label
return self.apply(transform, pvalueish)
finally:
transform.label = old_label
full_label = '/'.join([self._current_transform().full_label,
label or transform.label]).lstrip('/')
if full_label in self.applied_labels:
raise RuntimeError(
'Transform "%s" does not have a stable unique label. '
'This will prevent updating of pipelines. '
'To apply a transform with a specified label write '
'pvalue | "label" >> transform'
% full_label)
self.applied_labels.add(full_label)
pvalueish, inputs = transform._extract_input_pvalues(pvalueish)
try:
inputs = tuple(inputs)
for leaf_input in inputs:
if not isinstance(leaf_input, pvalue.PValue):
raise TypeError
except TypeError:
raise NotImplementedError(
'Unable to extract PValue inputs from %s; either %s does not accept '
'inputs of this format, or it does not properly override '
'_extract_input_pvalues' % (pvalueish, transform))
current = AppliedPTransform(
self._current_transform(), transform, full_label, inputs)
self._current_transform().add_part(current)
self.transforms_stack.append(current)
type_options = self._options.view_as(TypeOptions)
if type_options.pipeline_type_check:
transform.type_check_inputs(pvalueish)
pvalueish_result = self.runner.apply(transform, pvalueish)
if type_options is not None and type_options.pipeline_type_check:
transform.type_check_outputs(pvalueish_result)
for result in ptransform.GetPValues().visit(pvalueish_result):
assert isinstance(result, (pvalue.PValue, pvalue.DoOutputsTuple))
# Make sure we set the producer only for a leaf node in the transform DAG.
# This way we preserve the last transform of a composite transform as
# being the real producer of the result.
if result.producer is None:
result.producer = current
# TODO(robertwb): Multi-input, multi-output inference.
# TODO(robertwb): Ideally we'd do intersection here.
if (type_options is not None and type_options.pipeline_type_check
and isinstance(result, pvalue.PCollection)
and not result.element_type):
input_element_type = (
inputs[0].element_type
if len(inputs) == 1
else typehints.Any)
type_hints = transform.get_type_hints()
declared_output_type = type_hints.simple_output_type(transform.label)
if declared_output_type:
input_types = type_hints.input_types
if input_types and input_types[0]:
declared_input_type = input_types[0][0]
result.element_type = typehints.bind_type_variables(
declared_output_type,
typehints.match_type_variables(declared_input_type,
input_element_type))
else:
result.element_type = declared_output_type
else:
result.element_type = transform.infer_output_type(input_element_type)
assert isinstance(result.producer.inputs, tuple)
current.add_output(result)
if (type_options is not None and
type_options.type_check_strictness == 'ALL_REQUIRED' and
transform.get_type_hints().output_types is None):
ptransform_name = '%s(%s)' % (transform.__class__.__name__, full_label)
raise TypeCheckError('Pipeline type checking is enabled, however no '
'output type-hint was found for the '
'PTransform %s' % ptransform_name)
current.update_input_refcounts()
self.transforms_stack.pop()
return pvalueish_result
def _verify_runner_api_compatible(self):
class Visitor(PipelineVisitor): # pylint: disable=used-before-assignment
ok = True # Really a nonlocal.
def visit_transform(self, transform_node):
if transform_node.side_inputs:
# No side inputs (yet).
Visitor.ok = False
try:
# Transforms must be picklable.
pickler.loads(pickler.dumps(transform_node.transform,
enable_trace=False),
enable_trace=False)
except Exception:
Visitor.ok = False
def visit_value(self, value, _):
if isinstance(value, pvalue.PDone):
Visitor.ok = False
self.visit(Visitor())
return Visitor.ok
def to_runner_api(self):
"""For internal use only; no backwards-compatibility guarantees."""
from apache_beam.runners import pipeline_context
from apache_beam.portability.runners.api import beam_runner_api_pb2
context = pipeline_context.PipelineContext()
# Mutates context; placing inline would force dependence on
# argument evaluation order.
root_transform_id = context.transforms.get_id(self._root_transform())
proto = beam_runner_api_pb2.Pipeline(
root_transform_ids=[root_transform_id],
components=context.to_runner_api())
return proto
@staticmethod
def from_runner_api(proto, runner, options):
"""For internal use only; no backwards-compatibility guarantees."""
p = Pipeline(runner=runner, options=options)
from apache_beam.runners import pipeline_context
context = pipeline_context.PipelineContext(proto.components)
root_transform_id, = proto.root_transform_ids
p.transforms_stack = [
context.transforms.get_by_id(root_transform_id)]
# TODO(robertwb): These are only needed to continue construction. Omit?
p.applied_labels = set([
t.unique_name for t in proto.components.transforms.values()])
for id in proto.components.pcollections:
context.pcollections.get_by_id(id).pipeline = p
return p
class PipelineVisitor(object):
"""For internal use only; no backwards-compatibility guarantees.
Visitor pattern class used to traverse a DAG of transforms
(used internally by Pipeline for bookeeping purposes).
"""
def visit_value(self, value, producer_node):
"""Callback for visiting a PValue in the pipeline DAG.
Args:
value: PValue visited (typically a PCollection instance).
producer_node: AppliedPTransform object whose transform produced the
pvalue.
"""
pass
def visit_transform(self, transform_node):
"""Callback for visiting a transform node in the pipeline DAG."""
pass
def enter_composite_transform(self, transform_node):
"""Callback for entering traversal of a composite transform node."""
pass
def leave_composite_transform(self, transform_node):
"""Callback for leaving traversal of a composite transform node."""
pass
class AppliedPTransform(object):
"""For internal use only; no backwards-compatibility guarantees.
A transform node representing an instance of applying a PTransform
(used internally by Pipeline for bookeeping purposes).
"""
def __init__(self, parent, transform, full_label, inputs):
self.parent = parent
self.transform = transform
# Note that we want the PipelineVisitor classes to use the full_label,
# inputs, side_inputs, and outputs fields from this instance instead of the
# ones of the PTransform instance associated with it. Doing this permits
# reusing PTransform instances in different contexts (apply() calls) without
# any interference. This is particularly useful for composite transforms.
self.full_label = full_label
self.inputs = inputs or ()
self.side_inputs = () if transform is None else tuple(transform.side_inputs)
self.outputs = {}
self.parts = []
# Per tag refcount dictionary for PValues for which this node is a
# root producer.
self.refcounts = collections.defaultdict(int)
def __repr__(self):
return "%s(%s, %s)" % (self.__class__.__name__, self.full_label,
type(self.transform).__name__)
def update_input_refcounts(self):
"""Increment refcounts for all transforms providing inputs."""
def real_producer(pv):
real = pv.producer
while real.parts:
real = real.parts[-1]
return real
if not self.is_composite():
for main_input in self.inputs:
if not isinstance(main_input, pvalue.PBegin):
real_producer(main_input).refcounts[main_input.tag] += 1
for side_input in self.side_inputs:
real_producer(side_input.pvalue).refcounts[side_input.pvalue.tag] += 1
def add_output(self, output, tag=None):
if isinstance(output, pvalue.DoOutputsTuple):
self.add_output(output[output._main_tag])
elif isinstance(output, pvalue.PValue):
# TODO(BEAM-1833): Require tags when calling this method.
if tag is None and None in self.outputs:
tag = len(self.outputs)
assert tag not in self.outputs
self.outputs[tag] = output
else:
raise TypeError("Unexpected output type: %s" % output)
def add_part(self, part):
assert isinstance(part, AppliedPTransform)
self.parts.append(part)
def is_composite(self):
"""Returns whether this is a composite transform.
A composite transform has parts (inner transforms) or isn't the
producer for any of its outputs. (An example of a transform that
is not a producer is one that returns its inputs instead.)
"""
return bool(self.parts) or all(
pval.producer is not self for pval in self.outputs.values())
def visit(self, visitor, pipeline, visited):
"""Visits all nodes reachable from the current node."""
for pval in self.inputs:
if pval not in visited and not isinstance(pval, pvalue.PBegin):
assert pval.producer is not None
pval.producer.visit(visitor, pipeline, visited)
# The value should be visited now since we visit outputs too.
assert pval in visited, pval
# Visit side inputs.
for pval in self.side_inputs:
if isinstance(pval, pvalue.AsSideInput) and pval.pvalue not in visited:
pval = pval.pvalue # Unpack marker-object-wrapped pvalue.
assert pval.producer is not None
pval.producer.visit(visitor, pipeline, visited)
# The value should be visited now since we visit outputs too.
assert pval in visited
# TODO(silviuc): Is there a way to signal that we are visiting a side
# value? The issue is that the same PValue can be reachable through
# multiple paths and therefore it is not guaranteed that the value
# will be visited as a side value.
# Visit a composite or primitive transform.
if self.is_composite():
visitor.enter_composite_transform(self)
for part in self.parts:
part.visit(visitor, pipeline, visited)
visitor.leave_composite_transform(self)
else:
visitor.visit_transform(self)
# Visit the outputs (one or more). It is essential to mark as visited the
# tagged PCollections of the DoOutputsTuple object. A tagged PCollection is
# connected directly with its producer (a multi-output ParDo), but the
# output of such a transform is the containing DoOutputsTuple, not the
# PCollection inside it. Without the code below a tagged PCollection will
# not be marked as visited while visiting its producer.
for pval in self.outputs.values():
if isinstance(pval, pvalue.DoOutputsTuple):
pvals = (v for v in pval)
else:
pvals = (pval,)
for v in pvals:
if v not in visited:
visited.add(v)
visitor.visit_value(v, self)
def named_inputs(self):
# TODO(BEAM-1833): Push names up into the sdk construction.
return {str(ix): input for ix, input in enumerate(self.inputs)
if isinstance(input, pvalue.PCollection)}
def named_outputs(self):
return {str(tag): output for tag, output in self.outputs.items()
if isinstance(output, pvalue.PCollection)}
def to_runner_api(self, context):
from apache_beam.portability.runners.api import beam_runner_api_pb2
def transform_to_runner_api(transform, context):
if transform is None:
return None
else:
return transform.to_runner_api(context)
return beam_runner_api_pb2.PTransform(
unique_name=self.full_label,
spec=transform_to_runner_api(self.transform, context),
subtransforms=[context.transforms.get_id(part) for part in self.parts],
# TODO(BEAM-115): Side inputs.
inputs={tag: context.pcollections.get_id(pc)
for tag, pc in self.named_inputs().items()},
outputs={str(tag): context.pcollections.get_id(out)
for tag, out in self.named_outputs().items()},
# TODO(BEAM-115): display_data
display_data=None)
@staticmethod
def from_runner_api(proto, context):
result = AppliedPTransform(
parent=None,
transform=ptransform.PTransform.from_runner_api(proto.spec, context),
full_label=proto.unique_name,
inputs=[
context.pcollections.get_by_id(id) for id in proto.inputs.values()])
result.parts = [
context.transforms.get_by_id(id) for id in proto.subtransforms]
result.outputs = {
None if tag == 'None' else tag: context.pcollections.get_by_id(id)
for tag, id in proto.outputs.items()}
if not result.parts:
for tag, pc in result.outputs.items():
if pc not in result.inputs:
pc.producer = result
pc.tag = tag
result.update_input_refcounts()
return result
|
manuzhang/incubator-beam
|
sdks/python/apache_beam/pipeline.py
|
Python
|
apache-2.0
| 22,256
|
[
"VisIt"
] |
67945089b4e3616c65a4aaf603f7ba90d5599b9a6d3f118683c55f56bb84a527
|
"""
Stuff to make multi-D dispersion spectra, for instance for Mayavi ...
For now this works only for 4 curves, to give 3 dimensions.
"""
import sys
import numpy as np
#import matplotlib.pyplot as plt
import pycs.gen.util as util
import pycs.gen.lc as lc
import pycs.gen.polyml as ml
def dispcube(lcs, rawdispersionmethod, verbose=True, timewidth=30, timestep=1.0, optml=False, filename="dispcube.pkl"):
"""
3D specplot, calculates the dispersion over a cube of time-delays. And writes the result in a pickle.
For now this is quick and dirty programming : we want only 4 lightcurves.
This pickle can then be looked at with Mayavi (see example below)
"""
if len(lcs)!=4:
raise RuntimeError, "I want 4 lightcurves."
lcsc = [l.copy() for l in lcs]
# We apply microlensing if we do not need it.
for l in lcsc:
if optml==False and l.ml != None:
l.applyml()
# We generate the list of possible couples.
couplelist = [couple for couple in [[lc1, lc2] for lc1 in lcsc for lc2 in lcsc] if couple[0] != couple[1]]
#for couple in couplelist:
# print couple[0].object, couple[1].object
#nfree = len(lcs)-1
if optml:
pass
# def d2value(params):
# lc.multisettimedelays(lcsc, params[:nfree])
# ml.multisetfreeparams(lcsc, params[nfree:])
#
# # optimize ml here
#
# d2values = np.array([rawdispersionmethod(*couple)["d2"] for couple in couplelist])
# ret = np.mean(d2values)
# #print ret
# return ret
#
else:
def d2value(delays):
lc.multisettimedelays(lcsc, delays)
d2values = np.array([rawdispersionmethod(*couple)["d2"] for couple in couplelist])
ret = np.mean(d2values)
#print ret
return ret
initparams = np.concatenate([lc.multigettimedelays(lcsc), ml.multigetfreeparams(lcsc)])
print "Initial params : ", initparams
timeshifts = np.arange(-(timewidth)*timestep/2.0, (timewidth+1)*timestep/2.0, timestep)
cubeindexes = np.arange(timewidth + 1)
print "Points to calculate :", len(timeshifts)**3
d2cube = np.zeros((timewidth+1, timewidth+1, timewidth+1))
xshifts = timeshifts + initparams[0]
yshifts = timeshifts + initparams[1]
zshifts = timeshifts + initparams[2]
if optml==False:
for ix in cubeindexes:
print "Slice %i of %i" % (ix + 1, timewidth+1)
for iy in cubeindexes:
for iz in cubeindexes:
d2cube[ix, iy, iz] = d2value([xshifts[ix], yshifts[iy], zshifts[iz]])
# We do as if we used mgrid... no, this would be ogrid...
#xshifts = xshifts.reshape(xshifts.size, 1, 1)
#yshifts = yshifts.reshape(1, yshifts.size, 1)
#zshifts = zshifts.reshape(1, 1, zshifts.size)
beg = -(timewidth)*timestep/2.0
end = (timewidth+1)*timestep/2.0
step = timestep
x, y, z = np.mgrid[beg:end:step, beg:end:step, beg:end:step]
#print x, y, z
x += initparams[0]
y += initparams[1]
z += initparams[2]
#print x, y, z
util.writepickle({"lcs":lcs, "x":x, "y":y, "z":z, "d2":d2cube}, filename)
# To give an idea how to plot such a data cube with Mayavi2/mlab :
# import sys
# sys.path.append("../")
# from pycs.gen import *
# import numpy as np
# from enthought.mayavi import mlab
#
# pkldict = util.readpickle("dispcube50.pkl")
#
# maxval = 1.5
# minval = 1.43
#
# x = pkldict["x"]
# y = pkldict["y"]
# z = pkldict["z"]
# d2 = pkldict["d2"]
#
# lcs = pkldict["lcs"]
#
# minpos = np.argmin(d2)
# minpos = np.unravel_index(minpos, d2.shape)
# min_x = x[minpos]
# min_y = y[minpos]
# min_z = z[minpos]
#
#
# mlab.clf()
#
# src = mlab.pipeline.scalar_field(x, y, z, d2)
#
# # in green, the minimum
# mlab.points3d([min_x], [min_y], [min_z], color=(0,1,0), mode="cube", scale_mode="none", resolution=14, scale_factor=0.15)
#
# mlab.pipeline.scalar_cut_plane(src, vmin=minval, vmax=maxval)
#
# mlab.colorbar(title='Dispersion', orientation='vertical')
#
# mlab.xlabel("%s%s"% (lcs[0].object, lcs[1].object))
# mlab.ylabel("%s%s"% (lcs[0].object, lcs[2].object))
# mlab.zlabel("%s%s"% (lcs[0].object, lcs[3].object))
#
#
# mlab.show()
|
COSMOGRAIL/PyCS
|
pycs/disp/old/multispec.py
|
Python
|
gpl-3.0
| 4,026
|
[
"Mayavi"
] |
ad81d34069031d62672eeeab52619e89b0611a3b7213f9e05bde70d8b10009a2
|
# Copyright 2008-2015 Nokia Solutions and Networks
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Visitors can be used to easily traverse result structures.
This module contains :class:`ResultVisitor` for traversing the whole
:class:`~robot.result.executionresult.Result` object. It extends
:class:`~robot.model.visitor.SuiteVisitor` that contains visiting logic
for the test suite structure.
"""
from robot.model import SuiteVisitor
class ResultVisitor(SuiteVisitor):
"""Abstract class to conveniently travel :class:`~robot.result.executionresult.Result` objects.
A visitor implementation can be given to the :meth:`visit` method of a
result object. This will cause the result object to be traversed and the
visitor's :meth:`visit_x`, :meth:`start_x`, and :meth:`end_x` methods to
be called for each suite, test, keyword and message, as well as for errors,
statistics, and other information in the result object. See methods below
for a full list of available visitor methods.
See the :mod:`result package level <robot.result>` documentation for
more information about handling results and a concrete visitor example.
For more information about the visitor algorithm see documentation in
:mod:`robot.model.visitor` module.
"""
def visit_result(self, result):
if self.start_result(result) is not False:
result.suite.visit(self)
result.statistics.visit(self)
result.errors.visit(self)
self.end_result(result)
def start_result(self, result):
pass
def end_result(self, result):
pass
def visit_statistics(self, stats):
if self.start_statistics(stats) is not False:
stats.total.visit(self)
stats.tags.visit(self)
stats.suite.visit(self)
self.end_statistics(stats)
def start_statistics(self, stats):
pass
def end_statistics(self, stats):
pass
def visit_total_statistics(self, stats):
if self.start_total_statistics(stats) is not False:
for stat in stats:
stat.visit(self)
self.end_total_statistics(stats)
def start_total_statistics(self, stats):
pass
def end_total_statistics(self, stats):
pass
def visit_tag_statistics(self, stats):
if self.start_tag_statistics(stats) is not False:
for stat in stats:
stat.visit(self)
self.end_tag_statistics(stats)
def start_tag_statistics(self, stats):
pass
def end_tag_statistics(self, stats):
pass
def visit_suite_statistics(self, stats):
if self.start_suite_statistics(stats) is not False:
for stat in stats:
stat.visit(self)
self.end_suite_statistics(stats)
def start_suite_statistics(self, stats):
pass
def end_suite_statistics(self, suite_stats):
pass
def visit_stat(self, stat):
if self.start_stat(stat) is not False:
self.end_stat(stat)
def start_stat(self, stat):
pass
def end_stat(self, stat):
pass
def visit_errors(self, errors):
self.start_errors(errors)
for msg in errors:
msg.visit(self)
self.end_errors(errors)
def start_errors(self, errors):
pass
def end_errors(self, errors):
pass
|
caio2k/RIDE
|
src/robotide/lib/robot/result/visitor.py
|
Python
|
apache-2.0
| 3,924
|
[
"VisIt"
] |
aaaad08680ece9d4cc735276afbcfeeda21eb8d6003365b8f01cce847a23366a
|
# ***** BEGIN LICENSE BLOCK *****
# Version: MPL 1.1/GPL 2.0/LGPL 2.1
#
# The contents of this file are subject to the Mozilla Public License Version
# 1.1 (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.mozilla.org/MPL/
#
# Software distributed under the License is distributed on an "AS IS" basis,
# WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
# for the specific language governing rights and limitations under the
# License.
#
# The Original Code is Bespin.
#
# The Initial Developer of the Original Code is
# Mozilla.
# Portions created by the Initial Developer are Copyright (C) 2009
# the Initial Developer. All Rights Reserved.
#
# Contributor(s):
#
# Alternatively, the contents of this file may be used under the terms of
# either the GNU General Public License Version 2 or later (the "GPL"), or
# the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
# in which case the provisions of the GPL or the LGPL are applicable instead
# of those above. If you wish to allow use of your version of this file only
# under the terms of either the GPL or the LGPL, and not to allow others to
# use your version of this file under the terms of the MPL, indicate your
# decision by deleting the provisions above and replace them with the notice
# and other provisions required by the GPL or the LGPL. If you do not delete
# the provisions above, a recipient may use your version of this file under
# the terms of any one of the MPL, the GPL or the LGPL.
#
# ***** END LICENSE BLOCK *****
import sys
import os
import optparse
import subprocess
import codecs
from wsgiref.simple_server import make_server
try:
from json import loads, dumps
except ImportError:
from simplejson import loads, dumps
from dryice.path import path
from dryice import plugins, combiner
class BuildError(Exception):
def __init__(self, message, errors=None):
if errors:
message += "\n"
for e in errors:
message += "* %s\n" % (e)
Exception.__init__(self, message)
sample_dir = path(__file__).dirname() / "samples"
_boot_file = path(__file__).dirname() / "boot.js"
_script2loader = path(__file__).dirname() / "script2loader.js"
def ignore_css(src, names):
return [name for name in names if name.endswith(".css")]
class Manifest(object):
"""A manifest describes what should be built."""
unbundled_plugins = None
def __init__(self, include_tests=False, plugins=None,
dynamic_plugins=None, jquery="builtin",
search_path=None, output_dir="build", include_sample=False,
boot_file=None, unbundled_plugins=None, preamble=None, loader=None,
worker=None, config=None):
if plugins is None:
plugins = []
if dynamic_plugins is None:
dynamic_plugins = []
self.include_tests = include_tests
plugins.insert(0, "bespin")
self.plugins = plugins
self.dynamic_plugins = dynamic_plugins
self.jquery = jquery
if search_path is not None:
for i in range(0, len(search_path)):
name = search_path[i]
# did we get handed a dict already?
if not isinstance(name, basestring):
continue
# convert to the dict format that is used by
# the plugin module
search_path[i] = dict(name=name, path=path(name))
else:
search_path = []
# add the default plugin directory, if it exists
plugindir = path("plugins")
if plugindir.exists():
for name in plugindir.glob("*"):
if not name.isdir():
continue
search_path.append(dict(name=name, path=name))
self.search_path = search_path
if boot_file:
self.boot_file = path(boot_file).abspath()
else:
self.boot_file = _boot_file
if not output_dir:
raise BuildError("""Cannot run unless output_dir is set
(it defaults to 'build'). The contents of the output_dir directory
will be deleted before the build.""")
self.output_dir = path(output_dir)
self.include_sample = include_sample
if unbundled_plugins:
self.unbundled_plugins = path(unbundled_plugins).abspath()
self.preamble = path(__file__).dirname() / "preamble.js"
def location_of(file, default_location):
if default_location is not None:
return path(default_location)
static_path = path("static") / file
return static_path if static_path.exists() else path("lib") / file
self.loader = location_of("tiki.js", loader)
self.worker = location_of("BespinEmbedded.js", worker)
# this is a bit hacky. Because of the way worker_manager works,
# the server version of Bespin calls it "BespinEmbedded.js"
# and the embedded customizable version has a script called
# (more appropriately) worker.js
# hopefully, this will clear up in the move to JavaScript tooling
if not self.worker.exists():
self.worker = path("lib") / "worker.js"
self.config = config if config is not None else {}
self._created_javascript = set()
self._set_package_lists()
@classmethod
def from_json(cls, json_string, overrides=None):
"""Takes a JSON string and creates a Manifest object from it."""
try:
data = loads(json_string)
except ValueError:
raise BuildError("The manifest is not legal JSON: %s" % (json_string))
scrubbed_data = dict()
# you can't call a constructor with a unicode object
for key in data:
scrubbed_data[str(key)] = data[key]
if overrides:
scrubbed_data.update(overrides)
return cls(**scrubbed_data)
def _find_plugins(self):
self._plugin_catalog = dict((p.name, p) for p in plugins.find_plugins(self.search_path))
if self.jquery == "global":
self._plugin_catalog['jquery'] = plugins.Plugin("jquery",
path(__file__).dirname() / "globaljquery.js",
dict(name="thirdparty"))
errors = []
worker_plugins = []
for plugin in self.dynamic_plugins:
try:
plugin_obj = self.get_plugin(plugin)
except KeyError:
errors.append("Plugin %s not found" % plugin)
continue
# note that we need to copy self.plugins because
# we're going to be removing items from the list
for plugin in list(self.plugins):
try:
plugin_obj = self.get_plugin(plugin)
except KeyError:
errors.append("Plugin %s not found" % plugin)
continue
env = plugin_obj.metadata.get("environments")
if not env:
continue
is_worker = env.get("worker", False)
if is_worker:
worker_plugins.append(plugin)
is_main = env.get("main", False)
if not is_main:
self.plugins.remove(plugin)
self.worker_plugins = worker_plugins
return errors
@property
def errors(self):
try:
return self._errors
except AttributeError:
self._errors = self._find_plugins()
return self._errors
def get_plugin(self, name):
"""Retrieve a plugin by name."""
return self._plugin_catalog[name]
def get_package(self, name):
"""Retrieve a combiner.Package by name."""
plugin = self.get_plugin(name)
return combiner.Package(plugin.name, plugin.dependencies)
def generate_output_files(self, shared_js_file, main_js_file,
worker_js_file, css_file):
"""Generates the combined JavaScript file, putting the
output into output_file."""
output_dir = self.output_dir
shared_packages = self.shared_packages
static_packages = self.static_packages
worker_packages = self.worker_packages
dynamic_packages = self.dynamic_packages
if self.errors:
raise BuildError("Errors found, stopping...", self.errors)
shared_js_file.write(self.preamble.text('utf8'))
shared_js_file.write(self.loader.text('utf8'))
exclude_tests = not self.include_tests
# finally, package up the plugins
def process(package, output, dynamic):
plugin = self.get_plugin(package.name)
if dynamic:
plugin_subdir = path("plugins")
plugin_dir = output_dir / plugin_subdir
if not plugin_dir.isdir():
plugin_dir.makedirs()
plugin_filename = package.name + ".js"
plugin_location = plugin_subdir / plugin_filename
self._created_javascript.add(plugin_location)
combine_output_path = plugin_dir / plugin_filename
combine_output = combine_output_path.open("w")
else:
plugin_location = None
combine_output = output
combiner.write_metadata(output, plugin, plugin_location)
combiner.combine_files(combine_output, css_file, plugin,
plugin.location,
exclude_tests=exclude_tests,
image_path_prepend="resources/%s/"
% plugin.name)
if dynamic:
combine_output.write("bespin.tiki.script(%s);" %
dumps(plugin_filename))
for package in shared_packages:
process(package, shared_js_file, False)
for package in dynamic_packages:
process(package, main_js_file, True)
for package in static_packages:
process(package, main_js_file, False)
def make_plugin_metadata(packages):
md = dict()
for p in packages:
plugin = self.get_plugin(p.name)
md[plugin.name] = plugin.metadata
return dumps(md)
# include plugin metadata
# this comes after the plugins, because some plugins
# may need to be importable at the time the metadata
# becomes available.
all_packages = static_packages + dynamic_packages + worker_packages
all_md = make_plugin_metadata(all_packages)
bundled_plugins = set([ p.name for p in all_packages ])
self.bundled_plugins = bundled_plugins
main_js_file.write("""
(function() {
var $ = bespin.tiki.require("jquery").$;
$(document).ready(function() {
bespin.tiki.require("bespin:plugins").catalog.registerMetadata(%s);;
});
})();
""" % all_md)
shared_md = make_plugin_metadata(shared_packages)
shared_js_file.write("""
bespin.tiki.require("bespin:plugins").catalog.registerMetadata(%s);
""" % shared_md)
shared_js_file.write(_script2loader.text("utf8").encode("utf8"))
if self.boot_file:
boot_text = self.boot_file.text("utf8")
boot_text = boot_text % (dumps(self.config),)
main_js_file.write(boot_text.encode("utf8"))
for package in worker_packages:
process(package, worker_js_file, False)
worker_md = make_plugin_metadata(worker_packages)
worker_js_file.write("bespin.metadata = %s;" % worker_md)
worker_js_file.write(self.worker.text("utf8"))
def get_dependencies(self, packages, root_names):
"""Given a dictionary of package names to packages, returns the list of
root packages and all their dependencies, topologically sorted."""
visited = set()
result = []
def visit(name):
if name in visited:
return
visited.add(name)
pkg = packages[name]
for dep_name in pkg.dependencies:
visit(dep_name)
result.append(pkg)
for name in root_names:
visit(name)
return result
def _set_package_lists(self):
"""Returns a tuple consisting of the dynamic plugins, the static
plugins, and the worker plugins, in that order, along with all of their
dependencies."""
if self.errors:
return
plugins = self.plugins
worker_plugins = self.worker_plugins
dynamic_plugins = self.dynamic_plugins
# Filter the packages into static and dynamic parts. If a package is
# dynamically loaded, all of its dependencies must also be dynamically
# loaded.
def closure(plugins):
to_visit = plugins
pkgs = {}
for name in to_visit:
if name in pkgs:
continue
pkg = self.get_package(name)
pkgs[name] = pkg
to_visit += pkg.dependencies
return pkgs
pkgs = closure(dynamic_plugins + plugins)
dynamic_packages = self.get_dependencies(pkgs, dynamic_plugins)
dynamic_names = set([ pkg.name for pkg in dynamic_packages ])
deps = self.get_dependencies(pkgs, plugins)
static_packages = [ p for p in deps if p.name not in dynamic_names ]
pkgs = closure(worker_plugins)
worker_packages = self.get_dependencies(pkgs, worker_plugins)
static_set = set(static_packages)
worker_set = set(worker_packages)
shared_set = static_set.intersection(worker_set)
worker_set.difference_update(shared_set)
static_set.difference_update(shared_set)
self.shared_packages = list(shared_set)
self.static_packages = list(static_set)
self.worker_packages = list(worker_set)
self.dynamic_packages = dynamic_packages
def _output_unbundled_plugins(self, output_dir):
if not output_dir.exists():
output_dir.makedirs()
else:
if not output_dir.isdir():
raise BuildError("Unbundled plugins can't go in %s because it's not a directory" % output_dir)
bundled_plugins = self.bundled_plugins
for name, plugin in self._plugin_catalog.items():
if name in bundled_plugins:
continue
location = plugin.location
if location.isdir():
location.copytree(output_dir / location.basename())
else:
location.copy(output_dir / location.basename())
print "Unbundled plugins placed in: %s" % output_dir
def build(self):
"""Run the build according to the instructions in the manifest.
"""
if self.errors:
raise BuildError("Errors found, stopping...", self.errors)
output_dir = self.output_dir
print "Placing output in %s" % output_dir
if output_dir.exists():
output_dir.rmtree()
output_dir.makedirs()
filenames = [
output_dir / f for f in
("BespinEmbedded.js", "BespinMain.js", "BespinWorker.js", "BespinEmbedded.css")
]
self._created_javascript.add(filenames[0])
self._created_javascript.add(filenames[1])
self._created_javascript.add(filenames[2])
files = [ codecs.open(f, 'w', 'utf8') for f in filenames ]
[ jsfile, mainfile, workerfile, cssfile ] = files
self.generate_output_files(jsfile, mainfile, workerfile, cssfile)
for f in files:
f.close()
if self.unbundled_plugins:
self._output_unbundled_plugins(self.unbundled_plugins)
for package in self.static_packages + self.dynamic_packages + self.worker_packages + self.shared_packages:
plugin = self.get_plugin(package.name)
resources = plugin.location / "resources"
if resources.exists() and resources.isdir():
resources.copytree(output_dir / "resources" / plugin.name,
ignore=ignore_css)
if self.include_sample:
sample_dir.copytree(output_dir / "samples")
def compress_js(self, compressor):
"""Compress the output using Closure Compiler."""
for f in self._created_javascript:
print "Compressing %s" % (f)
compressed = f + ".compressed"
subprocess.call("java -jar %s "
"--js=%s"
" --js_output_file=%s"
" --warning_level=QUIET" % (compressor, f, f + ".compressed"),
shell=True)
if compressed.size == 0:
raise BuildError("File %s did not compile correctly. Check for errors." % (f))
newname = f.splitext()[0] + ".uncompressed.js"
f.rename(newname)
compressed.rename(f)
def compress_css(self, compressor):
"""Compress the CSS using YUI Compressor."""
print "Compressing CSS with YUI Compressor"
compressor = path(compressor).abspath()
subprocess.call("java -jar %s"
" --type css -o BespinEmbedded.compressed.css"
" BespinEmbedded.css" % compressor, shell=True,
cwd=self.output_dir)
uncompressed = self.output_dir / "BespinEmbedded.css"
compressed = self.output_dir / "BespinEmbedded.compressed.css"
if not compressed.exists():
raise BuildError("Unable to compress the css file at " + uncompressed)
uncompressed.rename(self.output_dir / "BespinEmbedded.uncompressed.css")
compressed.rename(uncompressed)
def main(args=None):
if args is None:
args = sys.argv
print "dryice: the Bespin build tool"
parser = optparse.OptionParser(
description="""Builds fast-loading JS and CSS packages.""")
parser.add_option("-j", "--jscompressor", dest="jscompressor",
help="path to Closure Compiler to compress the JS output")
parser.add_option("-c", "--csscompressor", dest="csscompressor",
help="path to YUI Compressor to compress the CSS output")
parser.add_option("-D", "--variable", dest="variables",
action="append",
help="override values in the manifest (use format KEY=VALUE, where VALUE is JSON)")
parser.add_option("-s", "--server", dest="server",
help="starts a server on [address:]port. example: -s 8080")
options, args = parser.parse_args(args)
overrides = {}
if options.variables:
for setting in options.variables:
key, value = setting.split("=")
overrides[key] = loads(value)
if len(args) > 1:
filename = args[1]
else:
filename = "manifest.json"
filename = path(filename)
if not filename.exists():
raise BuildError("Build manifest file (%s) does not exist" % (filename))
print "Using build manifest: ", filename
if options.server:
start_server(filename, options, overrides)
else:
do_build(filename, options, overrides)
index_html = """
<!DOCTYPE html>
<html><head>
<style>
html {
margin: 0;
padding: 0;
width: 100%;
height: 100%;
}
body {
margin: 0;
padding: 0;
width: 100%;
height: 100%;
overflow: hidden
}
</style>
<link href="BespinEmbedded.css" type="text/css" rel="stylesheet">
<script type="text/javascript" src="BespinEmbedded.js"></script>
</head>
<body class="bespin" data-bespinoptions='{ "settings": { "tabstop": 4 }, "syntax": "js", "stealFocus": true }'>
var thisCode = "what shows up in the editor";
function editMe() {
alert("and have fun!");
}
</body>
</html>
"""
class DryIceAndWSGI(object):
def __init__(self, filename, options, overrides):
from static import Cling
self.filename = filename
self.options = options
self.overrides = overrides
manifest = Manifest.from_json(filename.text())
self.static_app = Cling(manifest.output_dir)
def __call__(self, environ, start_response):
path_info = environ.get("PATH_INFO", "")
if not path_info or path_info == "/index.html" or path_info == "/":
headers = [
('Content-Type', 'text/html'),
('Content-Length', str(len(index_html)))
]
if environ['REQUEST_METHOD'] == "HEAD":
headers.append(('Allow', 'GET, HEAD'))
start_response("200 OK", headers)
return ['']
else:
start_response("200 OK", headers)
do_build(self.filename, self.options, self.overrides)
return [index_html]
else:
return self.static_app(environ, start_response)
def start_server(filename, options, overrides):
"""Starts the little webserver"""
app = DryIceAndWSGI(filename, options, overrides)
server_option = options.server
if ":" in server_option:
host, port = server_option.split(":")
else:
host = "localhost"
port = server_option
port = int(port)
print "Server started on %s, port %s" % (host, port)
try:
make_server(host, port, app).serve_forever()
except KeyboardInterrupt:
pass
def do_build(filename, options, overrides):
"""Runs the actual build"""
try:
manifest = Manifest.from_json(filename.text(), overrides=overrides)
manifest.build()
if options.jscompressor:
manifest.compress_js(options.jscompressor)
if options.csscompressor:
manifest.compress_css(options.csscompressor)
except BuildError, e:
print "Build aborted: %s" % (e)
|
samn/spectral-workbench
|
webserver/public/lib/bespin-0.9a2/lib/dryice/tool.py
|
Python
|
gpl-3.0
| 22,134
|
[
"VisIt"
] |
7ba1abe577598185d40923aaab7eba0cf629c3982d23cc078e41d70bdd0bf53e
|
# coding=utf-8
# This file is part of cclib (http://cclib.github.io), a library for parsing
# and interpreting the results of computational chemistry packages.
#
# Copyright (C) 2007-2014, the cclib development team
#
# The library is free software, distributed under the terms of
# the GNU Lesser General Public version 2.1 or later. You should have
# received a copy of the license along with cclib. You can also access
# the full license online at http://www.gnu.org/copyleft/lgpl.html.
"""Löwdin population analysis."""
import random
import numpy
from .population import Population
class LPA(Population):
"""The Löwdin population analysis"""
def __init__(self, *args):
# Call the __init__ method of the superclass.
super(LPA, self).__init__(logname="LPA", *args)
def __str__(self):
"""Return a string representation of the object."""
return "LPA of" % (self.data)
def __repr__(self):
"""Return a representation of the object."""
return 'LPA("%s")' % (self.data)
def calculate(self, indices=None, x=0.5, fupdate=0.05):
"""Perform a calculation of Löwdin population analysis.
Inputs:
indices - list of lists containing atomic orbital indices of fragments
x - overlap matrix exponent in wavefunxtion projection (x=0.5 for Lowdin)
"""
# Do we have the needed info in the parser?
if not hasattr(self.data,"mocoeffs"):
self.logger.error("Missing mocoeffs")
return False
if not (hasattr(self.data, "aooverlaps") \
or hasattr(self.data, "fooverlaps") ):
self.logger.error("Missing overlap matrix")
return False
if not hasattr(self.data, "nbasis"):
self.logger.error("Missing nbasis")
return False
if not hasattr(self.data, "homos"):
self.logger.error("Missing homos")
return False
unrestricted = (len(self.data.mocoeffs) == 2)
nbasis = self.data.nbasis
# Determine number of steps, and whether process involves beta orbitals.
self.logger.info("Creating attribute aoresults: [array[2]]")
alpha = len(self.data.mocoeffs[0])
self.aoresults = [ numpy.zeros([alpha, nbasis], "d") ]
nstep = alpha
if unrestricted:
beta = len(self.data.mocoeffs[1])
self.aoresults.append(numpy.zeros([beta, nbasis], "d"))
nstep += beta
#intialize progress if available
if self.progress:
self.progress.initialize(nstep)
if hasattr(self.data, "aooverlaps"):
S = self.data.aooverlaps
elif hasattr(self.data, "fooverlaps"):
S = self.data.fooverlaps
# Get eigenvalues and matrix of eigenvectors for transformation decomposition (U).
# Find roots of diagonal elements, and transform backwards using eigevectors.
# We need two matrices here, one for S^x, another for S^(1-x).
# We don't need to invert U, since S is symmetrical.
eigenvalues, U = numpy.linalg.eig(S)
UI = U.transpose()
Sdiagroot1 = numpy.identity(len(S))*numpy.power(eigenvalues, x)
Sdiagroot2 = numpy.identity(len(S))*numpy.power(eigenvalues, 1-x)
Sroot1 = numpy.dot(U, numpy.dot(Sdiagroot1, UI))
Sroot2 = numpy.dot(U, numpy.dot(Sdiagroot2, UI))
step = 0
for spin in range(len(self.data.mocoeffs)):
for i in range(len(self.data.mocoeffs[spin])):
if self.progress and random.random() < fupdate:
self.progress.update(step, "Lowdin Population Analysis")
ci = self.data.mocoeffs[spin][i]
temp1 = numpy.dot(ci, Sroot1)
temp2 = numpy.dot(ci, Sroot2)
self.aoresults[spin][i] = numpy.multiply(temp1, temp2).astype("d")
step += 1
if self.progress:
self.progress.update(nstep, "Done")
retval = super(LPA, self).partition(indices)
if not retval:
self.logger.error("Error in partitioning results")
return False
# Create array for charges.
self.logger.info("Creating fragcharges: array[1]")
size = len(self.fragresults[0][0])
self.fragcharges = numpy.zeros([size], "d")
for spin in range(len(self.fragresults)):
for i in range(self.data.homos[spin] + 1):
temp = numpy.reshape(self.fragresults[spin][i], (size,))
self.fragcharges = numpy.add(self.fragcharges, temp)
if not unrestricted:
self.fragcharges = numpy.multiply(self.fragcharges, 2)
return True
if __name__ == "__main__":
import doctest, lpa
doctest.testmod(lpa, verbose=False)
|
Clyde-fare/cclib
|
src/cclib/method/lpa.py
|
Python
|
lgpl-2.1
| 4,979
|
[
"cclib"
] |
dfbeed2e625b9fde59e77703ad215ba21e28f8db0872aa712481c9ac6e6fdce3
|
# coding: utf-8
# Copyright (c) Pymatgen Development Team.
# Distributed under the terms of the MIT License.
"""
This module provides the Stress class used to create, manipulate, and
calculate relevant properties of the stress tensor.
"""
import math
import numpy as np
from pymatgen.core.tensors import SquareTensor
__author__ = "Joseph Montoya"
__copyright__ = "Copyright 2012, The Materials Project"
__credits__ = "Maarten de Jong, Mark Asta, Anubhav Jain"
__version__ = "1.0"
__maintainer__ = "Joseph Montoya"
__email__ = "montoyjh@lbl.gov"
__status__ = "Production"
__date__ = "July 24, 2018"
class Stress(SquareTensor):
"""
This class extends SquareTensor as a representation of the
stress
"""
symbol = "s"
def __new__(cls, stress_matrix):
"""
Create a Stress object. Note that the constructor uses __new__
rather than __init__ according to the standard method of
subclassing numpy ndarrays.
Args:
stress_matrix (3x3 array-like): the 3x3 array-like
representing the stress
"""
obj = super().__new__(cls, stress_matrix)
return obj.view(cls)
@property
def dev_principal_invariants(self):
"""
returns the principal invariants of the deviatoric stress tensor,
which is calculated by finding the coefficients of the characteristic
polynomial of the stress tensor minus the identity times the mean
stress
"""
return self.deviator_stress.principal_invariants * np.array([1, -1, 1])
@property
def von_mises(self):
"""
returns the von mises stress
"""
if not self.is_symmetric():
raise ValueError(
"The stress tensor is not symmetric, Von Mises " "stress is based on a symmetric stress tensor."
)
return math.sqrt(3 * self.dev_principal_invariants[1])
@property
def mean_stress(self):
"""
returns the mean stress
"""
return 1.0 / 3.0 * self.trace()
@property
def deviator_stress(self):
"""
returns the deviatoric component of the stress
"""
if not self.is_symmetric:
raise ValueError("The stress tensor is not symmetric, so deviator stress will not be either")
return self - self.mean_stress * np.eye(3)
def piola_kirchoff_1(self, def_grad):
"""
calculates the first Piola-Kirchoff stress
Args:
def_grad (3x3 array-like): deformation gradient tensor
"""
if not self.is_symmetric:
raise ValueError(
"The stress tensor is not symmetric, \
PK stress is based on a symmetric stress tensor."
)
def_grad = SquareTensor(def_grad)
return def_grad.det * np.dot(self, def_grad.inv.trans)
def piola_kirchoff_2(self, def_grad):
"""
calculates the second Piola-Kirchoff stress
Args:
def_grad (3x3 array-like): rate of deformation tensor
"""
def_grad = SquareTensor(def_grad)
if not self.is_symmetric:
raise ValueError(
"The stress tensor is not symmetric, \
PK stress is based on a symmetric stress tensor."
)
return def_grad.det * np.dot(np.dot(def_grad.inv, self), def_grad.inv.trans)
|
gmatteo/pymatgen
|
pymatgen/analysis/elasticity/stress.py
|
Python
|
mit
| 3,442
|
[
"pymatgen"
] |
d2a5f2b137b445863a4104960fe8e053f668bc6a50efecd3b9bf64d42a6a0d9f
|
# -*- coding: utf-8 -*-
#
# test_rate_neuron_communication.py
#
# This file is part of NEST.
#
# Copyright (C) 2004 The NEST Initiative
#
# NEST is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 2 of the License, or
# (at your option) any later version.
#
# NEST 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 NEST. If not, see <http://www.gnu.org/licenses/>.
# This test checks interactions between rate neurons, i.e.
# the delay, weight and nonlinearities of rate neurons.
import nest
import unittest
import math
import numpy as np
def H(x):
return 0.5 * (np.sign(x) + 1.)
@nest.check_stack
class RateNeuronCommunicationTestCase(unittest.TestCase):
"""Check rate_neuron"""
def setUp(self):
# test parameter
self.rtol = 0.05
# neuron parameters
self.neuron_params = {'tau': 5., 'std': 0.}
self.neuron_params2 = self.neuron_params.copy()
self.neuron_params2.update({'mult_coupling': True})
self.neuron_params3 = self.neuron_params.copy()
self.neuron_params3.update({'rectify_output': True, 'rate': 1.})
self.drive = 1.5
self.delay = 2.
self.weight = 0.5
# simulation parameters
self.simtime = 100.
self.dt = 0.1
nest.set_verbosity('M_WARNING')
nest.ResetKernel()
nest.SetKernelStatus(
{'resolution': self.dt, 'use_wfr': True, 'print_time': True})
# set up rate neuron network
self.rate_neuron_drive = nest.Create(
'lin_rate_ipn', params={'rate': self.drive,
'mean': self.drive, 'std': 0.})
self.rate_neuron_negative_drive = nest.Create(
'lin_rate_ipn', params={'rate': -self.drive,
'mean': -self.drive, 'std': 0.})
self.rate_neuron_1 = nest.Create(
'lin_rate_ipn', params=self.neuron_params)
self.rate_neuron_2 = nest.Create(
'tanh_rate_ipn', params=self.neuron_params)
self.rate_neuron_3 = nest.Create(
'threshold_lin_rate_ipn', params=self.neuron_params)
self.rate_neuron_4 = nest.Create(
'lin_rate_ipn', params=self.neuron_params2)
self.rate_neuron_5 = nest.Create(
'lin_rate_ipn', params=self.neuron_params3)
self.parrot_neuron = nest.Create(
'rate_transformer_sigmoid_gg_1998')
self.multimeter = nest.Create("multimeter",
params={'record_from': ['rate'],
'interval': self.dt})
# record rates and connect neurons
self.neurons = self.rate_neuron_1 + \
self.rate_neuron_2 + self.rate_neuron_3 + self.rate_neuron_4 + \
self.rate_neuron_5
nest.Connect(
self.multimeter, self.neurons, 'all_to_all', {'delay': 10.})
nest.Connect(
self.multimeter, self.parrot_neuron, 'all_to_all', {'delay': 10.})
nest.Connect(self.rate_neuron_drive, self.rate_neuron_1,
'all_to_all', {'model': 'rate_connection_delayed',
'delay': self.delay,
'weight': self.weight})
nest.Connect(self.rate_neuron_drive, self.rate_neuron_2,
'all_to_all', {'model': 'rate_connection_instantaneous',
'weight': self.weight})
nest.Connect(self.rate_neuron_drive, self.rate_neuron_3,
'all_to_all', {'model': 'rate_connection_instantaneous',
'weight': self.weight})
nest.Connect(self.rate_neuron_drive, self.rate_neuron_4,
'all_to_all', {'model': 'rate_connection_instantaneous',
'weight': self.weight})
nest.Connect(self.rate_neuron_negative_drive, self.rate_neuron_5,
'all_to_all', {'model': 'rate_connection_instantaneous',
'weight': self.weight})
nest.Connect(self.rate_neuron_drive, self.parrot_neuron,
'all_to_all', {'model': 'rate_connection_instantaneous',
'weight': self.weight})
def test_RateNeuronDelay(self):
"""Check the delay of the connection"""
# simulate
nest.Simulate(self.simtime)
# get noise from rate neuron
events = nest.GetStatus(self.multimeter)[0]["events"]
senders = events['senders']
times = events['times'][np.where(senders == self.rate_neuron_1)]
rate_1 = events['rate'][np.where(senders == self.rate_neuron_1)]
rate_2 = events['rate'][np.where(senders == self.rate_neuron_2)]
delay_rate_1 = times[np.where(rate_1 > 0)[0][0]]
test_delay_1 = self.delay + self.dt
self.assertTrue(np.isclose(delay_rate_1, test_delay_1))
self.assertTrue(rate_2[0] > 0.)
def test_RateNeuronWeight(self):
"""Check the weight of the connection"""
# simulate
nest.Simulate(self.simtime)
# get noise from rate neuron
events = nest.GetStatus(self.multimeter)[0]["events"]
senders = events['senders']
rate_1 = events['rate'][np.where(senders == self.rate_neuron_1)]
value = rate_1[-1]
value_test = self.drive * self.weight
self.assertTrue(np.isclose(value, value_test))
def test_RateNeuronNL(self):
"""Check the non-linearity of the neuron"""
gs = [1., 2.]
lin_sums = [True, False]
for g, ls in zip(gs, lin_sums):
nest.SetStatus(self.neurons, {'g': g, 'linear_summation': ls})
# simulate
nest.Simulate(self.simtime)
# get noise from rate neuron
events = nest.GetStatus(self.multimeter)[0]["events"]
senders = events['senders']
rate_1 = events['rate'][
np.where(senders == self.rate_neuron_1)][-1]
rate_2 = events['rate'][
np.where(senders == self.rate_neuron_2)][-1]
rate_3 = events['rate'][
np.where(senders == self.rate_neuron_3)][-1]
rate_4 = events['rate'][
np.where(senders == self.rate_neuron_4)][-1]
rates = np.array([rate_1, rate_2, rate_3, rate_4])
# for multiplicative coupling
a = g * self.drive * self.weight * \
nest.GetStatus(self.rate_neuron_4)[0]['g_ex']
theta = nest.GetStatus(self.rate_neuron_4)[0]['theta_ex']
if ls:
rates_test = np.array(
[g * self.drive * self.weight,
np.tanh(g * self.drive * self.weight),
g * self.drive * self.weight * H(self.drive *
self.weight),
a * theta / (1 + a)])
else:
rates_test = np.array(
[g * self.drive * self.weight,
self.weight * np.tanh(g * self.drive),
self.weight * self.drive * g * H(self.drive),
a * theta / (1 + a)])
self.assertTrue(np.allclose(rates, rates_test))
def test_RectifyOutput(self):
"""Check the rectification of the output"""
# simulate
nest.Simulate(self.simtime)
# get activity from rate neuron
events = nest.GetStatus(self.multimeter)[0]["events"]
senders = events['senders']
rate_5 = events['rate'][np.where(senders == self.rate_neuron_5)]
value = rate_5[-1]
value_test = 0.
self.assertTrue(np.isclose(value, value_test))
def test_ParrotRateNeuron(self):
"""Check the parrot rate neuron with sigm non-linearity"""
nest.SetStatus(self.parrot_neuron, {'g': 0.1})
# simulate
nest.Simulate(self.simtime)
# get activity from rate neuron
events = nest.GetStatus(self.multimeter)[0]["events"]
senders = events['senders']
parrot_rate = events['rate'][np.where(senders == self.parrot_neuron)]
value = parrot_rate[-1]
g = nest.GetStatus(self.parrot_neuron)[0]['g']
value_test = (g * self.weight * self.drive)**4 / \
(0.1**4 + (g * self.weight * self.drive)**4)
self.assertTrue(np.isclose(value, value_test))
def suite():
# makeSuite is sort of obsolete http://bugs.python.org/issue2721
# using loadTestsFromTestCase instead.
suite1 = unittest.TestLoader().loadTestsFromTestCase(
RateNeuronCommunicationTestCase)
return unittest.TestSuite([suite1])
def run():
runner = unittest.TextTestRunner(verbosity=2)
runner.run(suite())
if __name__ == "__main__":
run()
|
mschmidt87/nest-simulator
|
pynest/nest/tests/test_rate_neuron_communication.py
|
Python
|
gpl-2.0
| 9,225
|
[
"NEURON"
] |
b69ddd1fc547a5edef5948722f900484d890d38898943158367815e93995d710
|
#!/usr/bin/env python
"""
Input
- reference sequence (fasta with samtools fai index)
- annotations (gff3, has to contain exon entries)
- filtered variants (vcf, primers are designed for variants with PASS)
Output
- PCR and genotyping primers selected using primer3 (gff3)
Algorithm
- there is only a few selected variants, so the least amount of work
will be to do the work only for variants
- for each of the selected variants
- request exons
- apply the technical constraints
(minimal primer length of 20 from the edge of an exon)
- patch exon sequence to mark positions of known variants
- find suitable genotyping primers
- design PCR primers to flank the (usable) genotyping primers
Author: Libor Morkovsky, 2012, 2014
"""
# This file is a part of Scrimer.
# See LICENSE.txt for details on licensing.
# Copyright (C) 2012, 2013 Libor Morkovsky
import sys
import os
import itertools
import argparse
import pysam
import vcf
import pybedtools
from scrimer import primer3_connector
min_gt_primer_len = 20
pref_gt_primer_len = 22
max_gt_primer_len = 28
# get location of config dir from environment
if 'PRIMER3_CONFIG' in os.environ:
PRIMER3_CONFIG = os.environ['PRIMER3_CONFIG']
else:
PRIMER3_CONFIG = '/opt/primer3/bin/primer3_config/'
def patched_sequence(seq, seq_start, variants):
"""Returns sequence with all variant sites replaced by Ns
a functional approach forced by python immutable strings
seq - sequence string
seq_start - start of sequence in refernce for variants
variants - [vcf._Record]
"""
# consider each variable site only once
uniq_positions = set((var.POS - 1 - seq_start) for var in variants)
# break the input seq apart, leaving out the variant sites
ends = sorted(uniq_positions)
begins = [0] + [pos + 1 for pos in ends]
ends.append(len(seq))
fragments = (seq[b:e] for (b, e) in zip(begins, ends))
# substite the variant sites with Ns
return 'N'.join(fragments)
#TODO: consider PRIMER_LOWERCASE_MASKING=1
def find_pcr_primers(pseq, target):
"""call primer3 executable, return the results
"""
def_params = {
'PRIMER_THERMODYNAMIC_PARAMETERS_PATH': PRIMER3_CONFIG,
'PRIMER_MAX_NS_ACCEPTED':'0',
}
p3 = primer3_connector.Primer3(**def_params)
rec_params = {
'SEQUENCE_ID':'pick_pcr_primers_task',
'SEQUENCE_TEMPLATE':pseq,
'SEQUENCE_TARGET': "%d,%d" % (target[0], target[1]),
'PRIMER_OPT_SIZE':'19',
'PRIMER_MIN_SIZE':'17',
'PRIMER_MAX_SIZE':'25',
'PRIMER_PRODUCT_SIZE_RANGE':'70-300',
'PRIMER_LOWERCASE_MASKING':'1',
}
return p3.call([rec_params])
def find_gt_primers(pseq, target):
"""call primer3 executable, return the results
simulating pick_discriminating_primers with FORCE_*_END
to avoid off-by-one error present in primer3
"""
def_params = {
'PRIMER_THERMODYNAMIC_PARAMETERS_PATH': PRIMER3_CONFIG,
'PRIMER_MAX_NS_ACCEPTED':'0',
}
p3 = primer3_connector.Primer3(**def_params)
rec_params = {
'PRIMER_TASK':'generic',
'SEQUENCE_ID':'pick_gt_primers_task',
'SEQUENCE_TEMPLATE': pseq,
'SEQUENCE_TARGET': "%d,1" % target,
'SEQUENCE_FORCE_LEFT_END': str(target - 1),
'SEQUENCE_FORCE_RIGHT_END': str(target + 1),
'PRIMER_OPT_SIZE': str(pref_gt_primer_len),
'PRIMER_MIN_SIZE': str(min_gt_primer_len),
'PRIMER_MAX_SIZE': str(max_gt_primer_len),
'PRIMER_PRODUCT_SIZE_RANGE':'%d-%d' % (2*min_gt_primer_len + 1, 2*max_gt_primer_len + 1),
'PRIMER_MIN_TM':'50',
'PRIMER_OPT_TM':'55',
'PRIMER_NUM_RETURN':'1',
# pick the primers even if there is no decent pair, we don't need pairs
'PRIMER_PICK_ANYWAY': '1',
# pick a thermodynamically worse primer, but avoid Ns at all costs
'PRIMER_WT_NUM_NS': '100',
}
return p3.call([rec_params])
def primer_to_gff(name, primer, tag, seq_name, seq_start, strand, **kwargs):
"""Create a gff feature from
partially parsed primer3 results.
"""
pos, len = map(int, primer['position'].split(','))
# transfer the calculated values to attributes
# skip the fields used elsewhere in gff
at = pybedtools.Attributes(' ')
for k, v in primer.iteritems():
if k == 'position': continue
at[k] = v.replace(';', '%3B')
at['ID'] = name
# pass all optional params to attributes
at.update({k:str(v) for k, v in kwargs.iteritems()})
# primer3 provides the coordinates of right primer with the
# pos pointing to the last base
if strand == '-':
start = seq_start + pos - len + 2
end = seq_start + pos + 1
else:
start = seq_start + pos + 1
end = seq_start + pos + len
gflist = [seq_name, 'design-primers', tag,
str(start), str(end),
primer['PENALTY'], strand, '.', str(at)]
return pybedtools.create_interval_from_list(gflist)
def get_flanking(seq, pos, size):
"""Get sequence flanking given position
add Ns if there is no input data (ends of input sequence)
"""
left = seq[max(pos - size, 0):pos]
right = seq[pos + 1:pos + size + 1]
return (left.rjust(size, 'N'), right.ljust(size, 'N'))
def reverse_complement(seq):
"""Return a DNA reverse complement
"""
compl = string.maketrans('ACGTNacgtn', 'TGCANtgcan')
return seq.translate(compl)[::-1]
def primers_for_var(genome, annotations, variants_random_access, var):
"""In ideal case this returns list of gff features representing
- a pair of pcr primers
- pcr product (carries the thermodynamic penalties for using
the combination of current pcr primers)
- two genotyping primers
or a feature carrying a Note about the error
"""
def rejected_var_feature(reason):
""" Output a dummy feature holding the
reason for rejection of selected variant in
the design process.
"""
at = pybedtools.Attributes(' ')
at['Note'] = reason
at['color'] = "#bb0000"
gflist = [var.CHROM, 'design-primers', 'rejected-var',
str(var.POS - max_gt_primer_len), str(var.POS + max_gt_primer_len),
'0', '+', '.', str(at)]
return pybedtools.create_interval_from_list(gflist)
# container for the output
result = []
var_features = annotations.tabix_intervals(pybedtools.Interval(var.CHROM, var.POS, var.POS + 1))
var_exons = [f for f in var_features if f.fields[2] == 'exon']
if len(var_exons) == 0:
return [rejected_var_feature('no predicted exons')]
# get a minimal predicted exon
# (trying to be conservative)
# consider only predicted, not transferred exons (source in attrs)
ex_predicted = [f for f in var_exons if 'source' in f.attrs]
ex_start = max(f.start for f in ex_predicted)
ex_end = min(f.end for f in ex_predicted)
min_exon = pybedtools.Interval(var.CHROM, ex_start, ex_end)
# check if the exon has a sane size (> 70)
if min_exon.length < 70:
return [rejected_var_feature('minimal exon too short for PCR')]
# check if the variant is in position that permits PCR amplification
# (more than 20 bases from both ends)
# this implies a check if the variant is still inside of the minimal exon
distances = (var.POS - min_exon.start, min_exon.end - var.POS)
if min(distances) < 20:
return [rejected_var_feature('variant too close to boundary or outside of minimal exon')]
# get all variants for the minimal exon
exon_variants = variants_random_access.fetch(var.CHROM, min_exon.start, min_exon.end)
# get sequence for the minimal exon
# and patch all the variants with Ns
seq = genome.fetch(min_exon.chrom, min_exon.start, min_exon.end)
pseq = patched_sequence(seq, min_exon.start, exon_variants)
# check if there is at least 20 fixed bases on either side
# of the target variant because of the genotyping primer
# (this could be faster exit path than a call to primer3)
gt_primer_seqs = get_flanking(pseq, var.POS - 1 - min_exon.start, max_gt_primer_len)
# attach 'N' to end of each primer, so we get the full len
# instead of -1, when there is no N in the original primer
max_gt_lens = [(s + 'N').find('N') for s in [gt_primer_seqs[0][::-1], gt_primer_seqs[1]]]
if all(x < min_gt_primer_len for x in max_gt_lens):
return [rejected_var_feature('no possible genotyping primer longer than %d bp' % min_gt_primer_len)]
# call primer3 to find suitable genotyping primers
gt_primers = find_gt_primers(pseq, var.POS - 1 - min_exon.start)
if all(len(p) == 0 for p in [gt_primers[0]['LEFT'], gt_primers[0]['RIGHT']]):
return [rejected_var_feature('no good genotyping primer found by primer3')]
# call primer3 to design PCR primers
# mark the region with suitable genotyping primers as a target
pcr_min = pcr_max = var.POS - 1 - min_exon.start
if len(gt_primers[0]['LEFT']):
pcr_min = int(gt_primers[0]['LEFT'][0]['position'].split(',')[0])
if len(gt_primers[0]['RIGHT']):
# primer3 uses coordinates of the 5' end
pcr_max = int(gt_primers[0]['RIGHT'][0]['position'].split(',')[0])
# find primers in the sequence patched with Ns
primers = find_pcr_primers(pseq, (pcr_min, pcr_max - pcr_min))
# if something was found, output the first pair
# (should be the best one)
if len(primers[0]['PAIR']):
# calculate the 'position' entry PAIR, so it is the same as in LEFT/RIGHT entries and can be used by primer_to_gff
# to represent the whole-product
primers[0]['PAIR'][0]['position'] = primers[0]['LEFT'][0]['position'].split(',')[0] + ',' + primers[0]['PAIR'][0]['PRODUCT_SIZE']
result.append(primer_to_gff('pcr-product', primers[0]['PAIR'][0], 'pcr-product', var.CHROM, min_exon.start, '+'))
result.append(primer_to_gff('pcr-left', primers[0]['LEFT'][0], 'pcr-primer', var.CHROM, min_exon.start, '+'))
result.append(primer_to_gff('pcr-right', primers[0]['RIGHT'][0], 'pcr-primer', var.CHROM, min_exon.start, '-'))
else:
return [rejected_var_feature('no suitable PCR primers found')]
# decorate all genotyping primers with basic statistics about the variant being genotyped
vkeys = ['FQ', 'MQ']
more = {('VAR_%s' % k):var.INFO[k] for k in vkeys if k in var.INFO}
more['VAR_mindps'] = min(sam['DP'] for sam in var.samples)
if 'DP4' in var.INFO:
more['VAR_dp4'] = ','.join(map(str, var.INFO['DP4']))
if len(gt_primers[0]['LEFT']):
color = '#bb0000' if 'PROBLEMS' in gt_primers[0]['LEFT'][0] else '#00bb00'
result.append(primer_to_gff('gt-left', gt_primers[0]['LEFT'][0], 'gt-primer', var.CHROM, min_exon.start, '+',
color=color, **more))
if len(gt_primers[0]['RIGHT']):
color = '#bb0000' if 'PROBLEMS' in gt_primers[0]['RIGHT'][0] else '#00bb00'
more = {('VAR_%s' % k):var.INFO[k] for k in vkeys if k in var.INFO}
result.append(primer_to_gff('gt-right', gt_primers[0]['RIGHT'][0], 'gt-primer', var.CHROM, min_exon.start, '-',
color=color, **more))
return result
def argparser():
args = argparse.ArgumentParser(description="Design primers using PRIMER3.")
args.add_argument("--primer-min", type=int, default=20,
help="Minimal length of the genotyping primer (default: 20).")
args.add_argument("--primer-pref", type=int, default=22,
help="Preferred length of the genotyping primer (default: 22).")
args.add_argument("--primer-max", type=int, default=28,
help="Minimal length of the genotyping primer (default: 28).")
#args.add_argument("--annot-type", default="exon",
# help="Annotatoin type that should represent contiguous sequence in DNA (default: exon).")
args.add_argument("genome",
help="Fasta file with associated .fai index (use samtools fai to index).")
args.add_argument("annots",
help="GFF file with associated .tbi (use tabix to index).")
args.add_argument("variants",
help="VCF file with selected variants.")
return args
def crc(line):
return zlib.crc32(line)
def main():
parser = argparser()
args = parser.parse_args()
genome = pysam.Fastafile(args.genome)
annotations = pybedtools.BedTool(args.annots)
variants = vcf.Reader(filename=args.variants)
# open the variants once more, so the ifilter is not broken by .fetch
var_fetcher = vcf.Reader(filename=args.variants)
# the most commonly changed value will be
# preferred length, fix the min/max if pref
# is not in the default range
if args.primer_pref < args.primer_min:
args.primer_min = args.primer_pref
if args.primer_pref > args.primer_max:
args.primer_max = args.primer_pref
min_gt_primer_len = args.primer_min
pref_gt_primer_len = args.primer_pref
max_gt_primer_len = args.primer_max
# locus can be either exon or mrna, for now we consider mrna a locus
# locus_feature_type = args.annot_type
seen_loci = set()
# by-locus naming convention implies following algo
# (almost single pass, keeping only the names of loci already seen
# in memory)
# algorithm:
# get a chosen variant
# find locus feature for chosen variant
# if locus already seen, get next variant
# find all other chosen variants for locus
# for each variant in locus design primers
# if designed primers overlap with others in locus, deduplicate
# use iterator filter, so the variants are streamed
for var in itertools.ifilter(lambda v: not v.FILTER, variants):
# get a locus feature for the var
var_features = annotations.tabix_intervals(pybedtools.Interval(var.CHROM, var.POS, var.POS + 1))
# var_loci = [f for f in var_features if f.fields[2] == locus_feature_type]
var_loci = [f for f in var_features if f.fields[2] == 'mRNA']
# var is not in any known feature
if len(var_loci) == 0:
continue
# quick check for now
if len(var_loci) > 1:
print >> sys.stderr, 'too many locus features for %s: %s' % (str(var), str(var_loci))
continue
locus = var_loci[0]
# all variants from this locus are already done
if locus.name in seen_loci:
continue
else:
seen_loci.add(locus.name)
# process all variants in current locus
# set the names and parenting structure
locus_variants = [v for v in var_fetcher.fetch(var.CHROM, locus.start, locus.end)]
locus_primers = []
pcr_id = 0
locus_out_name = "LU%04d" % len(seen_loci)
# summary statistics for whole locus
# used to decorate all products
pass_variants = sum(1 for var in locus_variants if not var.FILTER)
for lvar_num, lvar in enumerate(itertools.ifilter(lambda v: not v.FILTER, locus_variants)):
# create a convinient dict from the max-5 feature result
curr_primers = {f.name:f for f in primers_for_var(genome, annotations, var_fetcher, lvar)}
# if there was an error designing the primers
# output the error indicating features
if 'pcr-product' not in curr_primers:
map(lambda f: sys.stdout.write(str(f)), curr_primers.itervalues())
continue
def add_feature(f, name, parent):
f.name = name
f.attrs['Parent'] = parent
locus_primers.append(f)
# try to find the same pcr product
try:
# if the position of the primers is equal, the sequences are
# also equal, so the termodynamic parameters should be the same as well
# so we can use the Interval() '==' operator, which ignores gff attributes
# the == operator raises error when the intervals contain each other
def intervals_eq(a, b):
try:
return a == b
# when intervals contain each other, they're not equal
except NotImplementedError:
return False
# find function with custom comparator
def find(seq, item, _cmp):
for idx, i in enumerate(seq):
if _cmp(i, item): return idx
raise ValueError('item not found')
idx = find(locus_primers, curr_primers['pcr-product'], intervals_eq)
parent_pcr = locus_primers[idx]
# new pcr product
# add the product and pcr primers
except ValueError:
pcr_id += 1
parent_pcr = curr_primers['pcr-product']
parent_pcr.name = "%s-%d" % (locus_out_name, pcr_id)
locus_primers.append(curr_primers['pcr-product'])
# decorate the PCR product with reference genome transcript names
# and some statistics
ref_names = set(e.attrs['Name'] for e in var_features if 'coords' in e.attrs)
if len(ref_names): parent_pcr.attrs['ref_names'] = '|'.join(ref_names)
parent_pcr.attrs['variants_in_locus'] = str(pass_variants)
# add pcr primers
add_feature(curr_primers['pcr-left'], "%sF" % parent_pcr.name, parent_pcr.name)
add_feature(curr_primers['pcr-right'], "%sR" % parent_pcr.name, parent_pcr.name)
# add genotyping primers
if 'gt-left' in curr_primers:
add_feature(curr_primers['gt-left'], "%s-%dF" % (parent_pcr.name, lvar_num + 1), parent_pcr.name)
if 'gt-right' in curr_primers:
add_feature(curr_primers['gt-right'], "%s-%dR" % (parent_pcr.name, lvar_num + 1), parent_pcr.name)
# output all primers for current locus
map(lambda f: sys.stdout.write(str(f)), locus_primers)
if __name__ == "__main__": main()
|
libor-m/scrimer
|
scripts/design_primers.py
|
Python
|
agpl-3.0
| 18,284
|
[
"pysam"
] |
640ead9c97407c80762e555b5e5ced5842df5510de54df373b846ed510bd3568
|
import unittest
from test.support import (verbose, refcount_test, run_unittest,
strip_python_stderr, cpython_only, start_threads)
from test.script_helper import assert_python_ok, make_script, temp_dir
import sys
import time
import gc
import weakref
try:
import threading
except ImportError:
threading = None
try:
from _testcapi import with_tp_del
except ImportError:
def with_tp_del(cls):
class C(object):
def __new__(cls, *args, **kwargs):
raise TypeError('requires _testcapi.with_tp_del')
return C
### Support code
###############################################################################
# Bug 1055820 has several tests of longstanding bugs involving weakrefs and
# cyclic gc.
# An instance of C1055820 has a self-loop, so becomes cyclic trash when
# unreachable.
class C1055820(object):
def __init__(self, i):
self.i = i
self.loop = self
class GC_Detector(object):
# Create an instance I. Then gc hasn't happened again so long as
# I.gc_happened is false.
def __init__(self):
self.gc_happened = False
def it_happened(ignored):
self.gc_happened = True
# Create a piece of cyclic trash that triggers it_happened when
# gc collects it.
self.wr = weakref.ref(C1055820(666), it_happened)
@with_tp_del
class Uncollectable(object):
"""Create a reference cycle with multiple __del__ methods.
An object in a reference cycle will never have zero references,
and so must be garbage collected. If one or more objects in the
cycle have __del__ methods, the gc refuses to guess an order,
and leaves the cycle uncollected."""
def __init__(self, partner=None):
if partner is None:
self.partner = Uncollectable(partner=self)
else:
self.partner = partner
def __tp_del__(self):
pass
### Tests
###############################################################################
class GCTests(unittest.TestCase):
def test_list(self):
l = []
l.append(l)
gc.collect()
del l
self.assertEqual(gc.collect(), 1)
def test_dict(self):
d = {}
d[1] = d
gc.collect()
del d
self.assertEqual(gc.collect(), 1)
def test_tuple(self):
# since tuples are immutable we close the loop with a list
l = []
t = (l,)
l.append(t)
gc.collect()
del t
del l
self.assertEqual(gc.collect(), 2)
def test_class(self):
class A:
pass
A.a = A
gc.collect()
del A
self.assertNotEqual(gc.collect(), 0)
def test_newstyleclass(self):
class A(object):
pass
gc.collect()
del A
self.assertNotEqual(gc.collect(), 0)
def test_instance(self):
class A:
pass
a = A()
a.a = a
gc.collect()
del a
self.assertNotEqual(gc.collect(), 0)
def test_newinstance(self):
class A(object):
pass
a = A()
a.a = a
gc.collect()
del a
self.assertNotEqual(gc.collect(), 0)
class B(list):
pass
class C(B, A):
pass
a = C()
a.a = a
gc.collect()
del a
self.assertNotEqual(gc.collect(), 0)
del B, C
self.assertNotEqual(gc.collect(), 0)
A.a = A()
del A
self.assertNotEqual(gc.collect(), 0)
self.assertEqual(gc.collect(), 0)
def test_method(self):
# Tricky: self.__init__ is a bound method, it references the instance.
class A:
def __init__(self):
self.init = self.__init__
a = A()
gc.collect()
del a
self.assertNotEqual(gc.collect(), 0)
@cpython_only
def test_legacy_finalizer(self):
# A() is uncollectable if it is part of a cycle, make sure it shows up
# in gc.garbage.
@with_tp_del
class A:
def __tp_del__(self): pass
class B:
pass
a = A()
a.a = a
id_a = id(a)
b = B()
b.b = b
gc.collect()
del a
del b
self.assertNotEqual(gc.collect(), 0)
for obj in gc.garbage:
if id(obj) == id_a:
del obj.a
break
else:
self.fail("didn't find obj in garbage (finalizer)")
gc.garbage.remove(obj)
@cpython_only
def test_legacy_finalizer_newclass(self):
# A() is uncollectable if it is part of a cycle, make sure it shows up
# in gc.garbage.
@with_tp_del
class A(object):
def __tp_del__(self): pass
class B(object):
pass
a = A()
a.a = a
id_a = id(a)
b = B()
b.b = b
gc.collect()
del a
del b
self.assertNotEqual(gc.collect(), 0)
for obj in gc.garbage:
if id(obj) == id_a:
del obj.a
break
else:
self.fail("didn't find obj in garbage (finalizer)")
gc.garbage.remove(obj)
def test_function(self):
# Tricky: f -> d -> f, code should call d.clear() after the exec to
# break the cycle.
d = {}
exec("def f(): pass\n", d)
gc.collect()
del d
self.assertEqual(gc.collect(), 2)
@refcount_test
def test_frame(self):
def f():
frame = sys._getframe()
gc.collect()
f()
self.assertEqual(gc.collect(), 1)
def test_saveall(self):
# Verify that cyclic garbage like lists show up in gc.garbage if the
# SAVEALL option is enabled.
# First make sure we don't save away other stuff that just happens to
# be waiting for collection.
gc.collect()
# if this fails, someone else created immortal trash
self.assertEqual(gc.garbage, [])
L = []
L.append(L)
id_L = id(L)
debug = gc.get_debug()
gc.set_debug(debug | gc.DEBUG_SAVEALL)
del L
gc.collect()
gc.set_debug(debug)
self.assertEqual(len(gc.garbage), 1)
obj = gc.garbage.pop()
self.assertEqual(id(obj), id_L)
def test_del(self):
# __del__ methods can trigger collection, make this to happen
thresholds = gc.get_threshold()
gc.enable()
gc.set_threshold(1)
class A:
def __del__(self):
dir(self)
a = A()
del a
gc.disable()
gc.set_threshold(*thresholds)
def test_del_newclass(self):
# __del__ methods can trigger collection, make this to happen
thresholds = gc.get_threshold()
gc.enable()
gc.set_threshold(1)
class A(object):
def __del__(self):
dir(self)
a = A()
del a
gc.disable()
gc.set_threshold(*thresholds)
# The following two tests are fragile:
# They precisely count the number of allocations,
# which is highly implementation-dependent.
# For example, disposed tuples are not freed, but reused.
# To minimize variations, though, we first store the get_count() results
# and check them at the end.
@refcount_test
def test_get_count(self):
gc.collect()
a, b, c = gc.get_count()
x = []
d, e, f = gc.get_count()
self.assertEqual((b, c), (0, 0))
self.assertEqual((e, f), (0, 0))
# This is less fragile than asserting that a equals 0.
self.assertLess(a, 5)
# Between the two calls to get_count(), at least one object was
# created (the list).
self.assertGreater(d, a)
@refcount_test
def test_collect_generations(self):
gc.collect()
# This object will "trickle" into generation N + 1 after
# each call to collect(N)
x = []
gc.collect(0)
# x is now in gen 1
a, b, c = gc.get_count()
gc.collect(1)
# x is now in gen 2
d, e, f = gc.get_count()
gc.collect(2)
# x is now in gen 3
g, h, i = gc.get_count()
# We don't check a, d, g since their exact values depends on
# internal implementation details of the interpreter.
self.assertEqual((b, c), (1, 0))
self.assertEqual((e, f), (0, 1))
self.assertEqual((h, i), (0, 0))
def test_trashcan(self):
class Ouch:
n = 0
def __del__(self):
Ouch.n = Ouch.n + 1
if Ouch.n % 17 == 0:
gc.collect()
# "trashcan" is a hack to prevent stack overflow when deallocating
# very deeply nested tuples etc. It works in part by abusing the
# type pointer and refcount fields, and that can yield horrible
# problems when gc tries to traverse the structures.
# If this test fails (as it does in 2.0, 2.1 and 2.2), it will
# most likely die via segfault.
# Note: In 2.3 the possibility for compiling without cyclic gc was
# removed, and that in turn allows the trashcan mechanism to work
# via much simpler means (e.g., it never abuses the type pointer or
# refcount fields anymore). Since it's much less likely to cause a
# problem now, the various constants in this expensive (we force a lot
# of full collections) test are cut back from the 2.2 version.
gc.enable()
N = 150
for count in range(2):
t = []
for i in range(N):
t = [t, Ouch()]
u = []
for i in range(N):
u = [u, Ouch()]
v = {}
for i in range(N):
v = {1: v, 2: Ouch()}
gc.disable()
@unittest.skipUnless(threading, "test meaningless on builds without threads")
def test_trashcan_threads(self):
# Issue #13992: trashcan mechanism should be thread-safe
NESTING = 60
N_THREADS = 2
def sleeper_gen():
"""A generator that releases the GIL when closed or dealloc'ed."""
try:
yield
finally:
time.sleep(0.000001)
class C(list):
# Appending to a list is atomic, which avoids the use of a lock.
inits = []
dels = []
def __init__(self, alist):
self[:] = alist
C.inits.append(None)
def __del__(self):
# This __del__ is called by subtype_dealloc().
C.dels.append(None)
# `g` will release the GIL when garbage-collected. This
# helps assert subtype_dealloc's behaviour when threads
# switch in the middle of it.
g = sleeper_gen()
next(g)
# Now that __del__ is finished, subtype_dealloc will proceed
# to call list_dealloc, which also uses the trashcan mechanism.
def make_nested():
"""Create a sufficiently nested container object so that the
trashcan mechanism is invoked when deallocating it."""
x = C([])
for i in range(NESTING):
x = [C([x])]
del x
def run_thread():
"""Exercise make_nested() in a loop."""
while not exit:
make_nested()
old_switchinterval = sys.getswitchinterval()
sys.setswitchinterval(1e-5)
try:
exit = []
threads = []
for i in range(N_THREADS):
t = threading.Thread(target=run_thread)
threads.append(t)
with start_threads(threads, lambda: exit.append(1)):
time.sleep(1.0)
finally:
sys.setswitchinterval(old_switchinterval)
gc.collect()
self.assertEqual(len(C.inits), len(C.dels))
def test_boom(self):
class Boom:
def __getattr__(self, someattribute):
del self.attr
raise AttributeError
a = Boom()
b = Boom()
a.attr = b
b.attr = a
gc.collect()
garbagelen = len(gc.garbage)
del a, b
# a<->b are in a trash cycle now. Collection will invoke
# Boom.__getattr__ (to see whether a and b have __del__ methods), and
# __getattr__ deletes the internal "attr" attributes as a side effect.
# That causes the trash cycle to get reclaimed via refcounts falling to
# 0, thus mutating the trash graph as a side effect of merely asking
# whether __del__ exists. This used to (before 2.3b1) crash Python.
# Now __getattr__ isn't called.
self.assertEqual(gc.collect(), 4)
self.assertEqual(len(gc.garbage), garbagelen)
def test_boom2(self):
class Boom2:
def __init__(self):
self.x = 0
def __getattr__(self, someattribute):
self.x += 1
if self.x > 1:
del self.attr
raise AttributeError
a = Boom2()
b = Boom2()
a.attr = b
b.attr = a
gc.collect()
garbagelen = len(gc.garbage)
del a, b
# Much like test_boom(), except that __getattr__ doesn't break the
# cycle until the second time gc checks for __del__. As of 2.3b1,
# there isn't a second time, so this simply cleans up the trash cycle.
# We expect a, b, a.__dict__ and b.__dict__ (4 objects) to get
# reclaimed this way.
self.assertEqual(gc.collect(), 4)
self.assertEqual(len(gc.garbage), garbagelen)
def test_boom_new(self):
# boom__new and boom2_new are exactly like boom and boom2, except use
# new-style classes.
class Boom_New(object):
def __getattr__(self, someattribute):
del self.attr
raise AttributeError
a = Boom_New()
b = Boom_New()
a.attr = b
b.attr = a
gc.collect()
garbagelen = len(gc.garbage)
del a, b
self.assertEqual(gc.collect(), 4)
self.assertEqual(len(gc.garbage), garbagelen)
def test_boom2_new(self):
class Boom2_New(object):
def __init__(self):
self.x = 0
def __getattr__(self, someattribute):
self.x += 1
if self.x > 1:
del self.attr
raise AttributeError
a = Boom2_New()
b = Boom2_New()
a.attr = b
b.attr = a
gc.collect()
garbagelen = len(gc.garbage)
del a, b
self.assertEqual(gc.collect(), 4)
self.assertEqual(len(gc.garbage), garbagelen)
def test_get_referents(self):
alist = [1, 3, 5]
got = gc.get_referents(alist)
got.sort()
self.assertEqual(got, alist)
atuple = tuple(alist)
got = gc.get_referents(atuple)
got.sort()
self.assertEqual(got, alist)
adict = {1: 3, 5: 7}
expected = [1, 3, 5, 7]
got = gc.get_referents(adict)
got.sort()
self.assertEqual(got, expected)
got = gc.get_referents([1, 2], {3: 4}, (0, 0, 0))
got.sort()
self.assertEqual(got, [0, 0] + list(range(5)))
self.assertEqual(gc.get_referents(1, 'a', 4j), [])
def test_is_tracked(self):
# Atomic built-in types are not tracked, user-defined objects and
# mutable containers are.
# NOTE: types with special optimizations (e.g. tuple) have tests
# in their own test files instead.
self.assertFalse(gc.is_tracked(None))
self.assertFalse(gc.is_tracked(1))
self.assertFalse(gc.is_tracked(1.0))
self.assertFalse(gc.is_tracked(1.0 + 5.0j))
self.assertFalse(gc.is_tracked(True))
self.assertFalse(gc.is_tracked(False))
self.assertFalse(gc.is_tracked(b"a"))
self.assertFalse(gc.is_tracked("a"))
self.assertFalse(gc.is_tracked(bytearray(b"a")))
self.assertFalse(gc.is_tracked(type))
self.assertFalse(gc.is_tracked(int))
self.assertFalse(gc.is_tracked(object))
self.assertFalse(gc.is_tracked(object()))
class UserClass:
pass
self.assertTrue(gc.is_tracked(gc))
self.assertTrue(gc.is_tracked(UserClass))
self.assertTrue(gc.is_tracked(UserClass()))
self.assertTrue(gc.is_tracked([]))
self.assertTrue(gc.is_tracked(set()))
def test_bug1055820b(self):
# Corresponds to temp2b.py in the bug report.
ouch = []
def callback(ignored):
ouch[:] = [wr() for wr in WRs]
Cs = [C1055820(i) for i in range(2)]
WRs = [weakref.ref(c, callback) for c in Cs]
c = None
gc.collect()
self.assertEqual(len(ouch), 0)
# Make the two instances trash, and collect again. The bug was that
# the callback materialized a strong reference to an instance, but gc
# cleared the instance's dict anyway.
Cs = None
gc.collect()
self.assertEqual(len(ouch), 2) # else the callbacks didn't run
for x in ouch:
# If the callback resurrected one of these guys, the instance
# would be damaged, with an empty __dict__.
self.assertEqual(x, None)
def test_bug21435(self):
# This is a poor test - its only virtue is that it happened to
# segfault on Tim's Windows box before the patch for 21435 was
# applied. That's a nasty bug relying on specific pieces of cyclic
# trash appearing in exactly the right order in finalize_garbage()'s
# input list.
# But there's no reliable way to force that order from Python code,
# so over time chances are good this test won't really be testing much
# of anything anymore. Still, if it blows up, there's _some_
# problem ;-)
gc.collect()
class A:
pass
class B:
def __init__(self, x):
self.x = x
def __del__(self):
self.attr = None
def do_work():
a = A()
b = B(A())
a.attr = b
b.attr = a
do_work()
gc.collect() # this blows up (bad C pointer) when it fails
@cpython_only
def test_garbage_at_shutdown(self):
import subprocess
code = """if 1:
import gc
import _testcapi
@_testcapi.with_tp_del
class X:
def __init__(self, name):
self.name = name
def __repr__(self):
return "<X %%r>" %% self.name
def __tp_del__(self):
pass
x = X('first')
x.x = x
x.y = X('second')
del x
gc.set_debug(%s)
"""
def run_command(code):
p = subprocess.Popen([sys.executable, "-Wd", "-c", code],
stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
stdout, stderr = p.communicate()
p.stdout.close()
p.stderr.close()
self.assertEqual(p.returncode, 0)
self.assertEqual(stdout.strip(), b"")
return strip_python_stderr(stderr)
stderr = run_command(code % "0")
self.assertIn(b"ResourceWarning: gc: 2 uncollectable objects at "
b"shutdown; use", stderr)
self.assertNotIn(b"<X 'first'>", stderr)
# With DEBUG_UNCOLLECTABLE, the garbage list gets printed
stderr = run_command(code % "gc.DEBUG_UNCOLLECTABLE")
self.assertIn(b"ResourceWarning: gc: 2 uncollectable objects at "
b"shutdown", stderr)
self.assertTrue(
(b"[<X 'first'>, <X 'second'>]" in stderr) or
(b"[<X 'second'>, <X 'first'>]" in stderr), stderr)
# With DEBUG_SAVEALL, no additional message should get printed
# (because gc.garbage also contains normally reclaimable cyclic
# references, and its elements get printed at runtime anyway).
stderr = run_command(code % "gc.DEBUG_SAVEALL")
self.assertNotIn(b"uncollectable objects at shutdown", stderr)
def test_gc_main_module_at_shutdown(self):
# Create a reference cycle through the __main__ module and check
# it gets collected at interpreter shutdown.
code = """if 1:
import weakref
class C:
def __del__(self):
print('__del__ called')
l = [C()]
l.append(l)
"""
rc, out, err = assert_python_ok('-c', code)
self.assertEqual(out.strip(), b'__del__ called')
def test_gc_ordinary_module_at_shutdown(self):
# Same as above, but with a non-__main__ module.
with temp_dir() as script_dir:
module = """if 1:
import weakref
class C:
def __del__(self):
print('__del__ called')
l = [C()]
l.append(l)
"""
code = """if 1:
import sys
sys.path.insert(0, %r)
import gctest
""" % (script_dir,)
make_script(script_dir, 'gctest', module)
rc, out, err = assert_python_ok('-c', code)
self.assertEqual(out.strip(), b'__del__ called')
def test_get_stats(self):
stats = gc.get_stats()
self.assertEqual(len(stats), 3)
for st in stats:
self.assertIsInstance(st, dict)
self.assertEqual(set(st),
{"collected", "collections", "uncollectable"})
self.assertGreaterEqual(st["collected"], 0)
self.assertGreaterEqual(st["collections"], 0)
self.assertGreaterEqual(st["uncollectable"], 0)
# Check that collection counts are incremented correctly
if gc.isenabled():
self.addCleanup(gc.enable)
gc.disable()
old = gc.get_stats()
gc.collect(0)
new = gc.get_stats()
self.assertEqual(new[0]["collections"], old[0]["collections"] + 1)
self.assertEqual(new[1]["collections"], old[1]["collections"])
self.assertEqual(new[2]["collections"], old[2]["collections"])
gc.collect(2)
new = gc.get_stats()
self.assertEqual(new[0]["collections"], old[0]["collections"] + 1)
self.assertEqual(new[1]["collections"], old[1]["collections"])
self.assertEqual(new[2]["collections"], old[2]["collections"] + 1)
class GCCallbackTests(unittest.TestCase):
def setUp(self):
# Save gc state and disable it.
self.enabled = gc.isenabled()
gc.disable()
self.debug = gc.get_debug()
gc.set_debug(0)
gc.callbacks.append(self.cb1)
gc.callbacks.append(self.cb2)
self.othergarbage = []
def tearDown(self):
# Restore gc state
del self.visit
gc.callbacks.remove(self.cb1)
gc.callbacks.remove(self.cb2)
gc.set_debug(self.debug)
if self.enabled:
gc.enable()
# destroy any uncollectables
gc.collect()
for obj in gc.garbage:
if isinstance(obj, Uncollectable):
obj.partner = None
del gc.garbage[:]
del self.othergarbage
gc.collect()
def preclean(self):
# Remove all fluff from the system. Invoke this function
# manually rather than through self.setUp() for maximum
# safety.
self.visit = []
gc.collect()
garbage, gc.garbage[:] = gc.garbage[:], []
self.othergarbage.append(garbage)
self.visit = []
def cb1(self, phase, info):
self.visit.append((1, phase, dict(info)))
def cb2(self, phase, info):
self.visit.append((2, phase, dict(info)))
if phase == "stop" and hasattr(self, "cleanup"):
# Clean Uncollectable from garbage
uc = [e for e in gc.garbage if isinstance(e, Uncollectable)]
gc.garbage[:] = [e for e in gc.garbage
if not isinstance(e, Uncollectable)]
for e in uc:
e.partner = None
def test_collect(self):
self.preclean()
gc.collect()
# Algorithmically verify the contents of self.visit
# because it is long and tortuous.
# Count the number of visits to each callback
n = [v[0] for v in self.visit]
n1 = [i for i in n if i == 1]
n2 = [i for i in n if i == 2]
self.assertEqual(n1, [1]*2)
self.assertEqual(n2, [2]*2)
# Count that we got the right number of start and stop callbacks.
n = [v[1] for v in self.visit]
n1 = [i for i in n if i == "start"]
n2 = [i for i in n if i == "stop"]
self.assertEqual(n1, ["start"]*2)
self.assertEqual(n2, ["stop"]*2)
# Check that we got the right info dict for all callbacks
for v in self.visit:
info = v[2]
self.assertTrue("generation" in info)
self.assertTrue("collected" in info)
self.assertTrue("uncollectable" in info)
def test_collect_generation(self):
self.preclean()
gc.collect(2)
for v in self.visit:
info = v[2]
self.assertEqual(info["generation"], 2)
@cpython_only
def test_collect_garbage(self):
self.preclean()
# Each of these cause four objects to be garbage: Two
# Uncolectables and their instance dicts.
Uncollectable()
Uncollectable()
C1055820(666)
gc.collect()
for v in self.visit:
if v[1] != "stop":
continue
info = v[2]
self.assertEqual(info["collected"], 2)
self.assertEqual(info["uncollectable"], 8)
# We should now have the Uncollectables in gc.garbage
self.assertEqual(len(gc.garbage), 4)
for e in gc.garbage:
self.assertIsInstance(e, Uncollectable)
# Now, let our callback handle the Uncollectable instances
self.cleanup=True
self.visit = []
gc.garbage[:] = []
gc.collect()
for v in self.visit:
if v[1] != "stop":
continue
info = v[2]
self.assertEqual(info["collected"], 0)
self.assertEqual(info["uncollectable"], 4)
# Uncollectables should be gone
self.assertEqual(len(gc.garbage), 0)
class GCTogglingTests(unittest.TestCase):
def setUp(self):
gc.enable()
def tearDown(self):
gc.disable()
def test_bug1055820c(self):
# Corresponds to temp2c.py in the bug report. This is pretty
# elaborate.
c0 = C1055820(0)
# Move c0 into generation 2.
gc.collect()
c1 = C1055820(1)
c1.keep_c0_alive = c0
del c0.loop # now only c1 keeps c0 alive
c2 = C1055820(2)
c2wr = weakref.ref(c2) # no callback!
ouch = []
def callback(ignored):
ouch[:] = [c2wr()]
# The callback gets associated with a wr on an object in generation 2.
c0wr = weakref.ref(c0, callback)
c0 = c1 = c2 = None
# What we've set up: c0, c1, and c2 are all trash now. c0 is in
# generation 2. The only thing keeping it alive is that c1 points to
# it. c1 and c2 are in generation 0, and are in self-loops. There's a
# global weakref to c2 (c2wr), but that weakref has no callback.
# There's also a global weakref to c0 (c0wr), and that does have a
# callback, and that callback references c2 via c2wr().
#
# c0 has a wr with callback, which references c2wr
# ^
# |
# | Generation 2 above dots
#. . . . . . . .|. . . . . . . . . . . . . . . . . . . . . . . .
# | Generation 0 below dots
# |
# |
# ^->c1 ^->c2 has a wr but no callback
# | | | |
# <--v <--v
#
# So this is the nightmare: when generation 0 gets collected, we see
# that c2 has a callback-free weakref, and c1 doesn't even have a
# weakref. Collecting generation 0 doesn't see c0 at all, and c0 is
# the only object that has a weakref with a callback. gc clears c1
# and c2. Clearing c1 has the side effect of dropping the refcount on
# c0 to 0, so c0 goes away (despite that it's in an older generation)
# and c0's wr callback triggers. That in turn materializes a reference
# to c2 via c2wr(), but c2 gets cleared anyway by gc.
# We want to let gc happen "naturally", to preserve the distinction
# between generations.
junk = []
i = 0
detector = GC_Detector()
while not detector.gc_happened:
i += 1
if i > 10000:
self.fail("gc didn't happen after 10000 iterations")
self.assertEqual(len(ouch), 0)
junk.append([]) # this will eventually trigger gc
self.assertEqual(len(ouch), 1) # else the callback wasn't invoked
for x in ouch:
# If the callback resurrected c2, the instance would be damaged,
# with an empty __dict__.
self.assertEqual(x, None)
def test_bug1055820d(self):
# Corresponds to temp2d.py in the bug report. This is very much like
# test_bug1055820c, but uses a __del__ method instead of a weakref
# callback to sneak in a resurrection of cyclic trash.
ouch = []
class D(C1055820):
def __del__(self):
ouch[:] = [c2wr()]
d0 = D(0)
# Move all the above into generation 2.
gc.collect()
c1 = C1055820(1)
c1.keep_d0_alive = d0
del d0.loop # now only c1 keeps d0 alive
c2 = C1055820(2)
c2wr = weakref.ref(c2) # no callback!
d0 = c1 = c2 = None
# What we've set up: d0, c1, and c2 are all trash now. d0 is in
# generation 2. The only thing keeping it alive is that c1 points to
# it. c1 and c2 are in generation 0, and are in self-loops. There's
# a global weakref to c2 (c2wr), but that weakref has no callback.
# There are no other weakrefs.
#
# d0 has a __del__ method that references c2wr
# ^
# |
# | Generation 2 above dots
#. . . . . . . .|. . . . . . . . . . . . . . . . . . . . . . . .
# | Generation 0 below dots
# |
# |
# ^->c1 ^->c2 has a wr but no callback
# | | | |
# <--v <--v
#
# So this is the nightmare: when generation 0 gets collected, we see
# that c2 has a callback-free weakref, and c1 doesn't even have a
# weakref. Collecting generation 0 doesn't see d0 at all. gc clears
# c1 and c2. Clearing c1 has the side effect of dropping the refcount
# on d0 to 0, so d0 goes away (despite that it's in an older
# generation) and d0's __del__ triggers. That in turn materializes
# a reference to c2 via c2wr(), but c2 gets cleared anyway by gc.
# We want to let gc happen "naturally", to preserve the distinction
# between generations.
detector = GC_Detector()
junk = []
i = 0
while not detector.gc_happened:
i += 1
if i > 10000:
self.fail("gc didn't happen after 10000 iterations")
self.assertEqual(len(ouch), 0)
junk.append([]) # this will eventually trigger gc
self.assertEqual(len(ouch), 1) # else __del__ wasn't invoked
for x in ouch:
# If __del__ resurrected c2, the instance would be damaged, with an
# empty __dict__.
self.assertEqual(x, None)
def test_main():
enabled = gc.isenabled()
gc.disable()
assert not gc.isenabled()
debug = gc.get_debug()
gc.set_debug(debug & ~gc.DEBUG_LEAK) # this test is supposed to leak
try:
gc.collect() # Delete 2nd generation garbage
run_unittest(GCTests, GCTogglingTests, GCCallbackTests)
finally:
gc.set_debug(debug)
# test gc.enable() even if GC is disabled by default
if verbose:
print("restoring automatic collection")
# make sure to always test gc.enable()
gc.enable()
assert gc.isenabled()
if not enabled:
gc.disable()
if __name__ == "__main__":
test_main()
|
technologiescollege/Blockly-rduino-communication
|
scripts_XP/Lib/test/test_gc.py
|
Python
|
gpl-3.0
| 33,389
|
[
"VisIt"
] |
75d695d230c6b4c4acb53fcda3ca00ee1ca6cc5a4de74aae6d901ded741dbe29
|
import numpy as np
import matplotlib.pyplot as plt
from NumpyArrayHandler import *
class ModalNoise():
def __init__(self, image_obj, camera='nf'):
self.plot_buffer = 1.1
self.setImageObject(image_obj)
self.setCamera(camera)
def setImageObject(self, image_obj):
self.image_obj = image_obj
def setCamera(self, camera):
self.camera = camera
def getImageObject(self):
return self.image_obj
def getCamera(self):
return self.camera
@staticmethod
def getImageData(image_obj):
if image_obj.camera == 'ff':
method = 'gaussian'
else:
method = 'edge'
y0, x0 = image_obj.getFiberCenter(method=method, tol=1, test_range=10, show_image=False)
radius = image_obj.getFiberRadius()
image_array = image_obj.getImageArray()
#image_array = np.ones_like(image_array)
#image_array = image_obj.getTophatFit()
return image_array, y0, x0, radius
def getGiniCoefficient(self, test_array):
"""Finds gini coefficient for intensities in given array
Args:
test_array: arbitrary-dimension numpy array
Returns:
gini coefficient
"""
test_array = test_array.ravel()
gini_coeff = 0.0
for i in xrange(test_array.size):
gini_coeff += np.abs(test_array[i] - test_array).sum()
norm = 2.0 * test_array.sum() * test_array.size
return gini_coeff / norm
#=============================================================================#
#==== Modal Noise Methods ====================================================#
#=============================================================================#
def getModalNoise(self, image_obj=None, method='fft', output='array', radius_factor=0.95, deg=4):
"""Finds modal noise of camera image using specified method
Args:
camera: string designating near, far, or input
method: string designating tophat, polynomial, gaussian, gradient,
contrast, fft, gini, or entropy
Returns:
modal noise parameter
"""
if image_obj is None:
image_obj = self.image_obj
if len(method) < 3:
raise ValueError('Incorrect string for method type')
elif method in 'tophat':
return self.getModalNoiseTophat(image_obj, output, radius_factor)
elif method in 'fft' or method in 'fourier':
return self.getModalNoiseFFT(image_obj, output, radius_factor)
elif method in 'polynomial':
return self.getModalNoisePolynomial(image_obj, output, radius_factor, deg=deg)
elif method in 'gaussian':
return self.getModalNoiseGaussian(image_obj, output, radius_factor)
elif method in 'gradient':
return self.getModalNoiseGradient(image_obj, output, radius_factor)
elif method in 'contrast':
return self.getModalNoiseContrast(image_obj, radius_factor)
elif method in 'gini':
return self.getModalNoiseGini(image_obj, radius_factor)
elif method in 'entropy':
return self.getModalNoiseEntropy(image_obj, radius_factor)
else:
raise ValueError('Incorrect string for method type')
def getModalNoiseFFT(self, image_obj=None, output='array', radius_factor=1.05):
"""Finds modal noise of image using the image's power spectrum
Args:
image_obj (optional): ImageAnalysis object to be used
output: chooses whether to output as 'array' or 'parameter'
radius_factor (optional): fraction of the radius outside which
the array is padded with zeros
Returns:
array: (fft_array, freq_array) where fft_array is the normalized
azimuthally averaged power spectrum and freq_array are the
respective frequencies in 1/um
parameter: finds the Gini coefficient for the 2D power spectrum
"""
if image_obj is None:
image_obj = self.image_obj
image_array, y0, x0, radius = self.getImageData(image_obj)
height, width = image_array.shape
if image_obj.camera == 'nf':
image_array, x0, y0 = self.cropImage(image_array, x0, y0, radius*radius_factor)
image_array = self.isolateCircle(image_array, x0, y0, radius*radius_factor)
elif image_obj.camera == 'ff':
image_array, x0, y0 = self.cropImage(image_array, x0, y0, min(x0, y0, width-x0, height-y0))
image_array = self.applyWindow(image_array)
height, width = image_array.shape
fft_length = 2500 #8 * min(height, width)
fft_array = np.fft.fftshift(np.abs(np.fft.fft2(image_array, s=(fft_length, fft_length), norm='ortho')))
fx0 = fft_length/2
fy0 = fft_length/2
max_freq = fft_length/2
if len(output) < 3:
raise ValueError('Incorrect output string')
elif output in 'array':
bin_width = 1
list_len = int(max_freq / bin_width) + 1
fft_list = np.zeros(list_len).astype('float64')
weight_list = np.zeros(list_len).astype('float64')
freq_list = bin_width * np.arange(list_len).astype('float64')
bottom_right = fft_array[fy0:fy0+max_freq, fx0:fx0+max_freq]
bottom_left = fft_array[fy0:fy0+max_freq, fx0-max_freq+1:fx0+1][:, ::-1]
top_left = fft_array[fy0-max_freq+1:fy0+1, fx0-max_freq+1:fx0+1][::-1, ::-1]
top_right = fft_array[fy0-max_freq+1:fy0+1, fx0:fx0+max_freq][::-1, :]
fft_array = (bottom_right + bottom_left + top_left + top_right) / 4.0
#self.showImageArray(np.log(fft_array))
for i in xrange(max_freq):
for j in xrange(i+1):
freq = np.sqrt(i**2 + j**2)
if freq <= max_freq:
fft_list[int(freq/bin_width)] += fft_array[j, i] + fft_array[i, j]
weight_list[int(freq/bin_width)] += 2.0
# Remove bins with nothing in them
mask = (weight_list > 0.0).astype('bool')
weight_list = weight_list[mask]
freq_list = freq_list[mask]
fft_list = fft_list[mask] / weight_list # Average out
fft_list /= fft_list.sum() # Normalize
freq_list /= fft_length * image_obj.pixel_size / image_obj.magnification # Get frequencies in 1/um
self.plotFFT([freq_list], [fft_list], labels=['Modal Noise Power Spectrum'])
return fft_list, freq_list
elif output in 'parameter':
return self.getGiniCoefficient(intensityArray(fft_array, fx0, fy0, max_freq))
else:
ValueError('Incorrect output string')
def getModalNoiseTophat(self, image_obj=None, output='array', radius_factor=0.95):
"""Finds modal noise of image assumed to be a tophat
Modal noise is defined as the variance across the fiber face normalized
by the mean across the fiber face
Args:
image_obj (optional): ImageAnalysis object to be used
output: chooses whether to output as 'array' or 'parameter'
radius_factor (optional): fraction of the radius inside which the
modal noise calculation will be made
Returns:
array: (circle_fit, image_array) 2D numpy arrays of the best fit
tophat and the fiber image zoomed in to relevant area
parameter: STDEV / MEAN for the intensities inside the fiber face
"""
if image_obj is None:
image_obj = self.image_obj
image_array, y0, x0, radius = self.getImageData(image_obj)
intensity_array = intensityArray(image_array, x0, y0, radius*radius_factor)
if len(output) < 3:
raise ValueError('Incorrect output string')
elif output in 'array':
circle_fit = intensity_array.mean() * self.circleArray(self.getMeshGrid(image_array),
x0, y0, radius, res=10)
image_array, x0_new, y0_new = self.cropImage(image_array, x0, y0, radius*self.plot_buffer)
circle_fit = self.cropImage(circle_fit, x0, y0, radius*self.plot_buffer)[0]
self.showImageArray(image_array)
self.showImageArray(circle_fit)
self.plotOverlaidCrossSections(image_array, circle_fit, y0_new, x0_new)
return circle_fit, image_array
elif output in 'parameter':
return intensity_array.std() / intensity_array.mean()
else:
raise ValueError('Incorrect output string')
def getModalNoiseGradient(self, image_obj=None, output='array', radius_factor=0.95):
"""Finds modal noise of image using the image gradient
Args:
image_obj (optional): ImageAnalysis object to be used
output: chooses whether to output as 'array' or 'parameter'
radius_factor (optional): fraction of the radius inside which the
modal noise calculation will be made
Returns:
array: (gradient_array, image_array) 2D numpy array representing magnitude of the gradient
parameter: STDEV / MEAN for the gradient in the fiber image
"""
if image_obj is None:
image_obj = self.image_obj
image_array, y0, x0, radius = self.getImageData(image_obj)
image_array, x0, y0 = self.cropImage(image_array, x0, y0, radius*self.plot_buffer)
gradient_y, gradient_x = np.gradient(image_array)
gradient_array = np.sqrt(gradient_x**2 + gradient_y**2)
if len(output) < 3:
raise ValueError('Incorrect output string')
elif output in 'array':
self.showImageArray(gradient_array)
self.plotOverlaidCrossSections(image_array, gradient_array, y0, x0)
return gradient_array, image_array
elif output in 'parameter':
intensity_array = intensityArray(gradient_array, x0, y0, radius*radius_factor)
image_intensity_array = intensityArray(image_array, x0, y0, radius*radius_factor)
return intensity_array.std() / image_intensity_array.mean()
else:
ValueError('Incorrect output string')
def getModalNoisePolynomial(self, image_obj=None, output='array', radius_factor=0.95, deg=4):
"""Finds modal noise of image using polynomial fit
Crops image exactly around the circumference of the circle and fits a
polynomial to the 2D image. Modal noise is then defined as the STDEV
in the difference between the original image and the polynomial fit
normalized by the mean value inside the fiber face
Args:
image_obj (optional): ImageAnalysis object to be used
output: chooses whether to output as 'array' or 'parameter'
radius_factor (optional): fraction of the radius inside which the
modal noise calculation will be made
Returns:
array: (poly_fit, image_array) 2D numpy arrays of the best fit
polynomial and the fiber image zoomed in to relevant area
parameter: STDEV for the difference between the fiber image and
poly_fit divided by the mean of the fiber image intensities
"""
if image_obj is None:
image_obj = self.image_obj
image_array, y0, x0, radius = self.getImageData(image_obj)
radius *= radius_factor / np.sqrt(2)
image_array, x0, y0 = self.cropImage(image_array, x0, y0, radius)
poly_fit = self.getPolynomialFit(image_array, deg=deg, x0=x0, y0=y0)
if len(output) < 3:
raise ValueError('Incorrect output string')
elif output in 'array':
self.plotOverlaidCrossSections(image_array, poly_fit, radius, radius)
return poly_fit, image_array
elif output in 'parameter':
diff_array = image_array - poly_fit
intensity_array = intensityArray(diff_array, x0, y0, radius * np.sqrt(2))
image_intensity_array = intensityArray(image_array, x0, y0, radius * np.sqrt(2))
return intensity_array.std() / image_intensity_array.mean()
else:
raise ValueError('Incorrect output string')
def getModalNoiseGaussian(self, image_obj=None, output='array', radius_factor=0.95):
"""Finds modal noise of image using gaussian fit
Crops image exactly around the circumference of the circle and fits a
gaussian to the 2D image. Modal noise is then defined as the STDEV
in the difference between the original image and the gaussian fit
normalized by the mean value inside the fiber face
Args:
image_obj (optional): ImageAnalysis object to be used
output: chooses whether to output as 'array' or 'parameter'
radius_factor (optional): fraction of the radius inside which the
modal noise calculation will be made
Returns:
array: (gauss_fit, image_array) 2D numpy arrays of the best fit
polynomial and the fiber image zoomed in to relevant area
parameter: STDEV for the difference between the fiber image and
gauss_fit divided by the mean of the fiber image intensities
"""
if image_obj is None:
image_obj = self.image_obj
image_array, y0, x0, radius = self.getImageData(image_obj)
radius *= radius_factor / np.sqrt(2)
image_array, x0, y0 = self.cropImage(image_array, x0, y0, radius)
gauss_fit = self.getGaussianFit(image_array)
if len(output) < 3:
raise ValueError('Incorrect output string')
elif output in 'array':
self.showImageArray(gauss_fit)
self.plotOverlaidCrossSections(image_array, gauss_fit, radius, radius)
return gauss_fit, image_array
elif output in 'parameter':
diff_array = image_array - gauss_fit
intensity_array = intensityArray(diff_array, x0, y0, radius)
image_intensity_array = intensityArray(image_array, x0, y0, radius)
return intensity_array.std() / image_intensity_array.mean()
else:
raise ValueError('Incorrect output string')
def getModalNoiseGini(self, image_obj=None, radius_factor=0.95):
"""Find modal noise of image using Gini coefficient
Args:
image_obj (optional): ImageAnalysis object to be used
radius_factor (optional): fraction of the radius inside which the
modal noise calculation will be made
Returns:
array: 2D numpy array zoomed into the fiber face
parameter: Gini coefficient for intensities inside fiber face
"""
if image_obj is None:
image_obj = self.image_obj
image_array, y0, x0, radius = self.getImageData(image_obj)
radius *= radius_factor
intensity_array = intensityArray(image_array, x0, y0, radius)
return self.getGiniCoefficient(intensity_array)
def getModalNoiseContrast(self, image_obj=None, radius_factor=0.95):
"""Finds modal noise of image using Michelson contrast
Modal noise is defined as (I_max - I_min) / (I_max + I_min)
Args:
image_obj (optional): ImageAnalysis object to be used
radius_factor (optional): fraction of the radius inside which the
modal noise calculation will be made
Returns:
parameter: (I_max - I_min) / (I_max + I_min) for intensities inside
fiber face
"""
if image_obj is None:
image_obj = self.image_obj
image_array, y0, x0, radius = self.getImageData(image_obj)
radius *= radius_factor
intensity_array = intensityArray(image_array, x0, y0, radius)
return (intensity_array.max() - intensity_array.min()) / (intensity_array.max() + intensity_array.min())
def getModalNoiseEntropy(self, image_obj=None, radius_factor=0.95):
"""Find modal noise of image using hartley entropy
Args:
image_obj (optional): ImageAnalysis object to be used
radius_factor (optional): fraction of the radius inside which the
modal noise calculation will be made
Returns:
modal noise parameter
"""
if image_obj is None:
image_obj = self.image_obj
image_array, y0, x0, radius = self.getImageData(image_obj)
radius *= radius_factor
intensity_array = intensityArray(image_array, x0, y0, radius)
intensity_array = intensity_array / intensity_array.sum()
return (-intensity_array * np.log10(intensity_array)).sum()
#=============================================================================#
#==== Modal Noise Test =======================================================#
#=============================================================================#
if __name__ == '__main__':
from ImageAnalysis import ImageAnalysis
from Calibration import Calibration
import os as os
import matplotlib.pyplot as plt
from copy import deepcopy
plt.rc('font', size=16, family='sans-serif')
plt.rc('xtick', labelsize=14)
plt.rc('ytick', labelsize=14)
plt.rc('lines', lw=2)
base_folder = '2016-07-26/'
ambient_folder = base_folder + 'ambient/600um/'
dark_folder = base_folder + 'dark/'
agitated_folder = base_folder + 'single/600um/agitated/'
unagitated_folder = base_folder + 'single/600um/unagitated/'
ext = '.fit'
nf = {}
ff = {}
nf['calibration'] = Calibration([dark_folder + 'nf_dark_' + str(i).zfill(3) + ext for i in xrange(10)],
None,
[ambient_folder + 'nf_ambient_' + str(i).zfill(3) + '_0.1' + ext for i in xrange(10)])
print 'NF calibration initialized'
ff['calibration'] = Calibration([dark_folder + 'ff_dark_' + str(i).zfill(3) + ext for i in xrange(10)],
None,
[ambient_folder + 'ff_ambient_' + str(i).zfill(3) + '_0.1' + ext for i in xrange(10)])
print 'FF calibration initialized'
empty_data = {'images': [], 'fft': [], 'freq': []}
for test in ['agitated', 'unagitated', 'baseline']:
nf[test] = deepcopy(empty_data)
ff[test] = deepcopy(empty_data)
image_range = xrange(20)
nf['agitated']['images'] = [agitated_folder + 'nf_agitated_' + str(i).zfill(3) + ext for i in image_range]
nf['unagitated']['images'] = [unagitated_folder + 'nf_unagitated_' + str(i).zfill(3) + ext for i in image_range]
ff['agitated']['images'] = [agitated_folder + 'ff_agitated_' + str(i).zfill(3) + ext for i in image_range]
ff['unagitated']['images'] = [unagitated_folder + 'ff_unagitated_' + str(i).zfill(3) + ext for i in image_range]
for test in ['agitated', 'unagitated']:
nf[test]['obj'] = ImageAnalysis(nf[test]['images'], nf['calibration'])
nf_test_obj = nf['agitated']['obj']
nf['baseline']['obj'] = ImageAnalysis(nf_test_obj.getTophatFit(),
pixel_size=nf_test_obj.pixel_size,
camera='nf',
threshold = 0.1)
for test in ['agitated', 'unagitated']:
ff[test]['obj'] = ImageAnalysis(ff[test]['images'], ff['calibration'])
ff_test_obj = ff['agitated']['obj']
ff['baseline']['obj'] = ImageAnalysis(ff_test_obj.getGaussianFit(),
pixel_size=ff_test_obj.pixel_size,
camera='ff')
print
for cam in [nf, ff]:
for test in ['agitated', 'unagitated', 'baseline']:
print test + ':'
mn_obj = ModalNoise(cam[test]['obj'])
cam[test]['fft'], cam[test]['freq'] = mn_obj.getModalNoise(method='fft', output='array', radius_factor=1.0)
NumpyArrayHandler.plotFFT([cam[test]['freq'] for test in ['agitated', 'unagitated', 'baseline']],
[cam[test]['fft'] for test in ['agitated', 'unagitated', 'baseline']],
['Agitated laser', 'Unagitated laser', 'Baseline'],
cam[test]['obj'].camera.upper() + ' Modal Noise Comparison (600um Fiber)')
|
rpetersburg/FiberProperties
|
legacy_code/ModalNoise.py
|
Python
|
mit
| 20,835
|
[
"Gaussian"
] |
68de0178d36130f389d3be1032325418b5e250e37a9b7c22a9267d660d22f3b1
|
__author__ = 'stonerri'
'''
This code acts as the application's primary controller, and provides links to the following:
'''
import tornado.escape
import tornado.ioloop
import tornado.options
import tornado.web
import tornado.websocket
import tornado.gen
import tornado.auth
import tornado.autoreload
from tornado.options import define, options
#import oauth2
from redis import Redis
from rq import Queue
import requests
import sys, pprint, time, ConfigParser, os
from ConfigParser import SafeConfigParser
import json
import os.path
import uuid
import datetime
import logging
import random
import time
import string
from time import mktime, sleep
import github
# constants
TARGET_APLOG = 'aplog'
TARGET_CONSOLE = 'console'
TARGET_REMOTELOG = 'remotelog'
TARGET_ANGULAR = 'angular'
TARGET_NOTICE = 'notice'
TARGET_INIT = 'init'
define("port", default=8000, help="run on the given port", type=int)
root = os.path.dirname(__file__)
# needed to serialize any non-standard objects
class GenericEncoder(json.JSONEncoder):
def default(self, obj):
if isinstance(obj, datetime.datetime):
return int(mktime(obj.timetuple()))
return json.JSONEncoder.default(self, obj)
class FaviconHandler(tornado.web.RequestHandler):
def get(self):
self.redirect('/static/favicon.ico')
# generic object
class Object(object):
pass
class BaseHandler(tornado.web.RequestHandler):
@tornado.web.removeslash
def get_current_user(self):
return self.get_secure_cookie("user")
class LogoutHandler(BaseHandler):
def get(self):
self.clear_cookie("user")
self.redirect(self.get_argument("next","/"))
class WebHandler(BaseHandler):
def get(self):
user = self.get_current_user()
print user
try:
if user:
with open(os.path.join(root, 'templates/index.html')) as f:
self.write(f.read())
else:
with open(os.path.join(root, 'templates/landing.html')) as f:
self.write(f.read())
except IOError as e:
self.write("404: Not Found")
#try:
# with open(os.path.join(root, 'templates/index.html')) as f:
# self.write(f.read())
#@tornado.web.authenticated
from enginetasks import simpleVirtuosoPostExample
# websockets
class WSHandler(tornado.websocket.WebSocketHandler):
ws_open = False
def build_message(self, target, data, callback_id):
return json.dumps(dict(target=target, data=data, callback_id=callback_id))
def allow_draft76(self):
# for iOS 5.0 Safari
return True
def open(self):
print 'open'
#self.application.log.debug('Websocket connection opened')
#self.application.firefly.ws_callback = self.send_message
def send_message(self, target, data):
#self.application.log.debug('Client::%s: %s' % (target, data))
self.write_message(self.build_message(target=target, data=data, callback_id=-1))
def send_message_with_callback(self, target, data, callback_id):
#self.application.log.debug('Client::%s: %s' % (target, data))
self.write_message(self.build_message(target=target, data=data, callback_id=callback_id))
def on_close(self):
#self.application.log.debug('Websocket connection closed.')
#self.application.firefly.ws_callback = None
self.ws_open = False
# messages from the frontend
def on_message(self, message):
self.ws_open = True
#self.application.log.debug('Websocket message received.')
# assume all messaging is done with json-encoded strings
message_dict = json.loads(message)
# verify we have a message target
if 'target' in message_dict.keys():
if message_dict['target'] == 'tornado':
self.handle_tornado_message(message_dict)
elif message_dict['target'] == 'init':
self.handle_init_message(message_dict)
else:
print message_dict
# control main tornado methods here
def handle_tornado_message(self, message):
# tornado message data
tornado_function = message['data']['function']
args = message['data']['args']
if tornado_function == 'save':
print 'saving current state to file'
# self.send_message('console', 'Saved application state')
self.send_message_with_callback(TARGET_CONSOLE, True, message['callback_id'])
if tornado_function == 'getStatus':
# print 'getting current application status'
d = ''
#d = self.application.firefly.getAccessPointStatus()
self.send_message_with_callback(TARGET_CONSOLE, d, message['callback_id'])
# print tornado_function, args
def handle_init_message(self, message):
return_message = self.build_message('init', 'Welcome client!', -1)
self.write_message(return_message)
#
# def on_message(self, message):
#
# print 'message received %s' % message
# messagedict = json.loads(message)
#
# return_data = {}
# return_data['result'] = False
# return_data['callback_id'] = messagedict['callback_id']
#
# if messagedict['type'] == 'kickoff_queue':
#
# print 'test'
#
##simpleVirtuosoPostExample
#
# job = self.application.q.enqueue(simpleVirtuosoPostExample, 'some query string')
#
# #job = self.application.q.enqueue(count_words_at_url, 'http://nvie.com')
#
# #self.shared.js.append(job)
# self.application.jobs.append(job)
#
# while not job.result:
# time.sleep(1)
#
# return_data['data'] = job.result
# return_data['result'] = True
#
# print 'job complete'
# print job.result
#
# self.write_message(json.dumps(return_data))
#elif messagedict['type'] == 'dropbox':
#
# job = self.application.q.enqueue(processDropboxImage, messagedict['files'])
# self.application.jobs.append(job)
#elif messagedict['type'] == 't1':
#
# job = self.application.q.enqueue(processT1, messagedict)
# self.application.jobs.append(job)
#while not job.result:
# time.sleep(1)
#
#return_data['data'] = job.result
#return_data['result'] = True
#
#print 'job complete'
#print job.result
#self.write_message(json.dumps(return_data))
#else:
#
# self.write_message(json.dumps(return_data))
#tornado.ioloop.IOLoop.instance().add_timeout(datetime.timedelta(seconds=1), self.check_queue)
def check_queue(self):
#print '.'
list_to_remove = []
for i in range(len(self.application.jobs)):
j = self.application.jobs[i]
j.refresh()
print '\n***************************\n'
print j.meta
#from pprint import pprint
#pprint (vars(j))
if j.result:
#print j.result
print 'now removing it'
list_to_remove.append(i)
return_data = {}
return_data['result'] = True
return_data['func'] = 'update_image'
return_data['contents'] = j.result
self.write_message(json.dumps(return_data))
elif j.meta:
#todo add support for multiple jobs
return_data = {}
return_data['result'] = True
return_data['func'] = 'update_meta'
return_data['contents'] = j.meta
self.write_message(json.dumps(return_data))
for index in sorted(list_to_remove, reverse=True):
print 'removing job at index %d' % index
del self.application.jobs[index]
#jobs_list = self.shared.q.get_jobs()
#print self.shared.q.job_ids
#print jobs_list
#for n,j in enumerate(jobs_list):
# print n, j.result
if len(self.application.jobs) > 0:
tornado.ioloop.IOLoop.instance().add_timeout(datetime.timedelta(seconds=1), self.check_queue)
#tornado.ioloop.IOLoop.instance().add_timeout(datetime.timedelta(seconds=5), self.pollForAccessPoint)
#class UploadHandler(tornado.web.RequestHandler):
#
# def post(self):
# #print self.request.files.keys()
# file1 = self.request.files['file'][0]
# original_fname = file1['filename']
# extension = os.path.splitext(original_fname)[1]
# fname = ''.join(random.choice(string.ascii_lowercase + string.digits) for x in range(6))
# final_filename= fname+extension
# full_path = os.path.abspath(root) + "/static/uploads/" + final_filename
# output_file = open(os.path.abspath(root) + "/static/uploads/" + final_filename, 'w')
# output_file.write(file1['body'])
# output_file.close()
#
# from rqtasks import processImage
# job = self.application.q.enqueue(processImage,full_path)
# self.application.jobs.append(job)
#
# self.finish("file" + final_filename + " is uploaded")
class GithubLoginHandler(BaseHandler, github.GithubMixin):
#_OAUTH_REDIRECT_URL = 'http://localhost:8888/auth/github'
_OAUTH_REDIRECT_URL = 'http://frontend.incfcloud.org/auth/github'
@tornado.web.asynchronous
def get(self):
# we can append next to the redirect uri, so the user gets the
# correct URL on login
redirect_uri = tornado.httputil.url_concat(
self._OAUTH_REDIRECT_URL, {'next': self.get_argument('next', '/')})
# if we have a code, we have been authorized so we can log in
if self.get_argument("code", False):
print 'we have code'
self.get_authenticated_user(
redirect_uri=redirect_uri,
client_id=self.settings["github_client_id"],
client_secret=self.settings["github_secret"],
code=self.get_argument("code"),
callback=self.async_callback(self._on_login)
)
return
# otherwise we need to request an authorization code
self.authorize_redirect(
redirect_uri=redirect_uri,
client_id=self.settings["github_client_id"],
extra_params={"scope": self.settings['github_scope'], "foo":1})
def _on_login(self, user):
""" This handles the user object from the login request """
print('authenticated callback')
#print user
if user:
logging.info('logged in user from github: ' + str(user))
self.set_secure_cookie("user", tornado.escape.json_encode(user))
else:
self.clear_cookie("user")
self.redirect(self.get_argument("next","/"))
class Application(tornado.web.Application):
def __init__(self):
parser = SafeConfigParser()
parser.read('../settings.ini')
gen_key = parser.get('admin', 'admin_generate_key')
admin_key = ''
if gen_key==1:
import uuid
admin_key = uuid.uuid4()
else:
admin_key = parser.get('admin', 'admin_key')
self.jobs = []
self.admin_key = str(admin_key)
self.q = Queue(connection=Redis())
print 'to access the admin path, visit /admin/%s' % (admin_key)
handlers = [
(r'/', WebHandler),
(r'/ws', WSHandler),
(r"/auth/github", GithubLoginHandler),
(r"/auth/logout", LogoutHandler)
#(r'/upload', UploadHandler)
]
settings = dict(
cookie_secret="__TODO:_GENERATE_YOUR_OWN_RANDOM_VALUE_HERE__",
github_client_id="47663846f4ff92fbe8a3",
github_secret="3ac166be872348f12c848c7dbe8e92b32e5803e9",
github_scope = ['user','public_repo'],
login_url="http://frontend.incfcloud.org/auth/github",
template_path=os.path.join(os.path.dirname(__file__), "templates"),
static_path=os.path.join(os.path.dirname(__file__), "static"),
xsrf_cookies=True,
)
tornado.web.Application.__init__(self, handlers, **settings)
# Watch templates and static path directory
# for (path, dirs, files) in os.walk(settings["template_path"]):
# for item in files:
# tornado.autoreload.watch(os.path.join(path, item))
#
# for (path, dirs, files) in os.walk(settings["static_path"]):
# for item in files:
# tornado.autoreload.watch(os.path.join(path, item))
def main():
# I don't actually do anything here beyond configure port and allowable IPs
tornado.options.parse_command_line()
# init application
app = Application()
app.listen(options.port)
# start the IO loop
io_loop = tornado.ioloop.IOLoop.instance()
#tornado.autoreload.start(io_loop)
io_loop.start()
if __name__ == "__main__":
main()
|
richstoner/incf_engine
|
frontend/app/app.py
|
Python
|
mit
| 13,249
|
[
"Firefly",
"VisIt"
] |
cfda63f30e453b923b59be797354135faa2a6fa3244652b530a14c3e9980abd7
|
################################################################################
# #
# Copyright (C) 2010,2011,2012,2013,2014,2015,2016 The ESPResSo project #
# #
# This file is part of ESPResSo. #
# #
# ESPResSo 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. #
# #
# ESPResSo 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, see <http://www.gnu.org/licenses/>. #
# #
################################################################################
# #
# Catalytic Reactions: Enhanced Diffusion Tutorial #
# #
################################################################################
from __future__ import print_function
import numpy as np
import os
import sys
import time
from espressomd import assert_features
from espressomd.observables import ParticlePositions, ParticleBodyAngularMomentum
from espressomd.correlators import Correlator
from espressomd.reaction import Reaction
################################################################################
# Read in the active velocity from the command prompt
if len(sys.argv) != 2:
print("Usage:",sys.argv[0],"<passive/active = 0/1>")
exit()
active = int(sys.argv[1])
if (active != 0) and (active != 1):
print("Usage:",sys.argv[0],"<passive/active = 0/1>")
exit()
# Set the parameters
box_l = 10
radius = 3.0
csmall = 0.1
rate = 1000.0
# Print input parameters
print("Box length: {}".format(box_l))
print("Colloid radius: {}".format(radius))
print("Particle concentration: {}".format(csmall))
print("Reaction rate: {}".format(rate))
print("Active or Passive: {}".format(active))
# Create output directory
if active == 0:
outdir = "./passive-system"
else:
outdir = "./active-system"
try:
os.makedirs(outdir)
except:
print("INFO: Directory \"{}\" exists".format(outdir))
################################################################################
# Setup system parameters
equi_steps = 250
equi_length = 100
prod_steps = 2000
prod_length = 100
dt = 0.01
system = espressomd.System(box_l=[box_l, box_l, box_l])
system.cell_system.skin = 0.1
system.time_step = dt
system.min_global_cut = 1.1*radius
# Set up the random seeds
system.seed = np.random.randint(0,2**31-1)
################################################################################
# Thermostat parameters
# Catalyzer is assumed to be larger, thus larger friction
frict_trans_colloid = 20.0
frict_rot_colloid = 20.0
# Particles are small and have smaller friction
frict_trans_part = 1.0
frict_rot_part = 1.0
# Temperature
temp = 1.0
################################################################################
# Set up the swimmer
## Exercise 1 ##
# Determine the initial position of the particle, which
# should be in the center of the box.
x0pnt = ...
y0pnt = ...
z0pnt = ...
# Note that the swimmer needs to rotate freely
cent = len(system.part)
system.part.add(id=cent,pos=[x0pnt,y0pnt,z0pnt],type=0,temp=temp,
gamma=frict_trans_colloid,
gamma_rot=frict_rot_colloid,
rotation=[1,1,1])
# Set up the particles
## Exercise 2 ##
# Above, we have set the concentration of the particles in the
# variable $csmall. The concentration of both species of particles is
# equal. Determine *how many* particles of one species there are.
# There are two species of equal concentration
nB = ...
nA = nB
print("Number of reactive A particles: {}".format(nB))
print("Number of reactive B particles: {}".format(nA))
for i in range(nA):
x = box_l*np.random.random()
y = box_l*np.random.random()
z = box_l*np.random.random()
# Prevent overlapping the colloid
while (x-x0pnt)**2 + (y-y0pnt)**2 + (z-z0pnt)**2 < 1.15*radius**2:
x = box_l*np.random.random()
y = box_l*np.random.random()
z = box_l*np.random.random()
# reactants and products do not need to rotate
system.part.add(pos=[x,y,z],type=1,temp=temp,
gamma=frict_trans_part,
gamma_rot=frict_rot_part,
rotation=[0,0,0])
for i in range(nB):
x = box_l*np.random.random()
y = box_l*np.random.random()
z = box_l*np.random.random()
# Prevent overlapping the colloid
while (x-x0pnt)**2 + (y-y0pnt)**2 + (z-z0pnt)**2 < 1.15*radius**2:
x = box_l*np.random.random()
y = box_l*np.random.random()
z = box_l*np.random.random()
# reactants and products do not need to rotate
system.part.add(pos=[x,y,z],type=2,temp=temp,
gamma=frict_trans_part,
gamma_rot=frict_rot_part,
rotation=[0,0,0])
print("box: {}, npart: {}".format(system.box_l,len(system.part)))
################################################################################
# Set up the WCA potential
## Exercise 3 ##
# Why are there two different cutoff lengths for the LJ interaction
# catalyzer/product and catalyzer/reactant?
eps = 5.0
sig = 1.0
shift = 0.25
roff = radius - 0.5*sig
# central and A particles
cut = 2**(1/6.)*sig
system.non_bonded_inter[0,1].lennard_jones.set_params(epsilon=eps, sigma=sig, cutoff=cut, shift=shift, offset=roff)
# central and B particles (larger cutoff)
cut = 1.5*sig
system.non_bonded_inter[0,2].lennard_jones.set_params(epsilon=eps, sigma=sig, cutoff=cut, shift=shift, offset=roff)
################################################################################
# Set up the reaction
cat_range = radius + 1.0*sig
cat_rate = rate
## Exercise 4 ##
# We have read the acticity parameter from the command line into
# $active, where 0 means off and 1 means on. When $active = 0 we can
# simply go on, but when $active = 1 we have to set up the reaction.
# Check the $active parameter and setup a reaction for the catalyzer
# of type 0 with the reactants of type 1 and products of type 2. The
# reaction range is stored in $cat_range, the reaction rate in
# $cat_rate. Use the number-conserving scheme by setting swap on.
...
################################################################################
# Perform warmup
cap = 1.0
warm_length = 100
## Exercise 5 ##
# Consult the User Guide for minimize_energy to find out the
# difference to warmup with explicit force-capping.
system.minimize_energy.init(f_max=cap,max_steps=warm_length,gamma=1.0/20.0,max_displacement=0.05)
system.minimize_energy.minimize()
################################################################################
# Enable the thermostat
## Exercise 6 ##
# Why do we enable the thermostat only after warmup?
system.thermostat.set_langevin(kT=temp, gamma=frict_trans_colloid)
################################################################################
# Perform equilibration
# Integrate
for k in range(equi_steps):
print("Equilibration: {} of {}".format(k,equi_steps))
system.integrator.run(equi_length)
################################################################################
for cnt in range(5):
# Set up the MSD calculation
tmax = prod_steps*prod_length*dt
pos_id = ParticlePositions(ids=[cent])
msd = Correlator(obs1=pos_id,
corr_operation="square_distance_componentwise",
dt=dt,
tau_max=tmax,
tau_lin=16)
system.auto_update_correlators.add(msd)
## Exercise 7a ##
# Construct the auto-correlators for the AVACF, using the example
# of the MSD.
# Initialize the angular velocity auto-correlation function
# (AVACF) correlator
...
# Perform production
# Integrate
for k in range(prod_steps):
print("Production {} of 5: {} of {}".format(cnt+1,k,prod_steps))
system.integrator.run(prod_length)
# Finalize the MSD and export
system.auto_update_correlators.remove(msd)
msd.finalize()
np.savetxt("{}/msd_{}.dat".format(outdir,cnt),msd.result())
## Exercise 7b ##
# Finalize the angular velocity auto-correlation function (AVACF)
# correlator and write the result to a file.
...
np.savetxt("{}/avacf_{}.dat".format(outdir,cnt),avacf.result())
|
KonradBreitsprecher/espresso
|
doc/tutorials/09-swimmer_reactions/EXERCISES/reaction.py
|
Python
|
gpl-3.0
| 9,461
|
[
"ESPResSo"
] |
d0d210b7eaa085430403a03a41f7c974d1fd1cea41f44780306641ce3b86efe4
|
import caching.base as caching
import jingo
import jinja2
from tower import ugettext_lazy as _
import amo
from addons.models import Addon
from api.views import addon_filter
from bandwagon.models import Collection, MonthlyPick as MP
from versions.compare import version_int
# The global registry for promo modules. Managed through PromoModuleMeta.
registry = {}
class PromoModuleMeta(type):
"""Adds new PromoModules to the module registry."""
def __new__(mcs, name, bases, dict_):
cls = type.__new__(mcs, name, bases, dict_)
if 'abstract' not in dict_:
registry[cls.slug] = cls
return cls
class PromoModule(object):
"""
Base class for promo modules in the discovery pane.
Subclasses should assign a slug and define render(). The slug is only used
internally, so it doesn't have to really be a slug.
"""
__metaclass__ = PromoModuleMeta
abstract = True
slug = None
def __init__(self, request, platform, version):
self.request = request
self.platform = platform
self.version = version
self.compat_mode = 'strict'
if version_int(self.version) >= version_int('10.0'):
self.compat_mode = 'ignore'
def render(self):
raise NotImplementedError
class TemplatePromo(PromoModule):
abstract = True
template = None
def context(self):
return {}
def render(self, **kw):
c = dict(self.context())
c.update(kw)
r = jingo.render_to_string(self.request, self.template, c)
return jinja2.Markup(r)
class MonthlyPick(TemplatePromo):
slug = 'Monthly Pick'
template = 'discovery/modules/monthly.html'
def context(self):
try:
pick = MP.objects.filter(locale=self.request.LANG)[0]
except IndexError:
try:
pick = MP.objects.filter(locale='')[0]
except IndexError:
pick = None
return {'pick': pick, 'module_context': 'discovery'}
class GoMobile(TemplatePromo):
slug = 'Go Mobile'
template = 'discovery/modules/go-mobile.html'
class CollectionPromo(PromoModule):
abstract = True
template = 'discovery/modules/collection.html'
title = None
subtitle = None
cls = 'promo'
limit = 3
linkify_title = False
def __init__(self, *args, **kw):
super(CollectionPromo, self).__init__(*args, **kw)
self.collection = None
if hasattr(self, 'pk'):
try:
self.collection = Collection.objects.get(pk=self.pk)
except Collection.DoesNotExist:
pass
elif (hasattr(self, 'collection_author') and
hasattr(self, 'collection_slug')):
try:
self.collection = Collection.objects.get(
author__username=self.collection_author,
slug=self.collection_slug)
except Collection.DoesNotExist:
pass
def get_descriptions(self):
return {}
def get_addons(self):
addons = self.collection.addons.filter(status=amo.STATUS_PUBLIC)
kw = dict(addon_type='ALL', limit=self.limit, app=self.request.APP,
platform=self.platform, version=self.version,
compat_mode=self.compat_mode)
f = lambda: addon_filter(addons, **kw)
return caching.cached_with(addons, f, repr(kw))
def render(self, module_context='discovery'):
if module_context == 'home':
self.platform = 'ALL'
self.version = None
c = dict(promo=self, module_context=module_context,
descriptions=self.get_descriptions())
if self.collection:
c.update(addons=self.get_addons())
return jinja2.Markup(
jingo.render_to_string(self.request, self.template, c))
class ShoppingCollection(CollectionPromo):
slug = 'Shopping Collection'
collection_author, collection_slug = 'mozilla', 'onlineshopping'
cls = 'promo promo-purple'
title = _(u'Shopping Made Easy')
subtitle = _(u'Save on your favorite items '
'from the comfort of your browser.')
class WebdevCollection(CollectionPromo):
slug = 'Webdev Collection'
pk = 10
cls = 'webdev'
title = _(u'Build the perfect website')
class TesterCollection(CollectionPromo):
slug = 'Firefox Tester Tools'
pk = 82266
cls = 'tester'
title = _(u'Help test Firefox with these tools')
class StarterPack(CollectionPromo):
slug = 'Starter Pack'
pk = 153649
id = 'starter'
cls = 'promo'
title = _(u'First time with Add-ons?')
subtitle = _(u'Not to worry, here are three to get started.')
def get_descriptions(self):
return {
2257: _(u'Translate content on the web from and into over 40 '
'languages.'),
1833: _(u"Easily connect to your social networks, and share or "
"comment on the page you're visiting."),
11377: _(u'A quick view to compare prices when you shop online '
'or search for flights.')
}
class Fx4Collection(CollectionPromo):
slug = 'Fx4 Collection'
pk = 153651
id = 'fx4-collection'
cls = 'promo'
title = _(u'Firefox 4 Collection')
subtitle = _(u'Here are some great add-ons for Firefox 4.')
linkify_title = True
class StPatricksPersonas(CollectionPromo):
slug = 'St. Pat Themes'
pk = 666627
id = 'st-patricks'
cls = 'promo'
title = _(u'St. Patrick’s Day Themes')
subtitle = _(u'Decorate your browser to celebrate '
'St. Patrick’s Day.')
class FxSummerCollection(CollectionPromo):
slug = 'Fx Summer Collection'
pk = 2128026
id = 'fx4-collection'
cls = 'promo'
title = _(u'Firefox Summer Collection')
subtitle = _(u'Here are some great add-ons for Firefox.')
class ThunderbirdCollection(CollectionPromo):
slug = 'Thunderbird Collection'
pk = 2128303
id = 'tb-collection'
cls = 'promo'
title = _(u'Thunderbird Collection')
subtitle = _(u'Here are some great add-ons for Thunderbird.')
class TravelCollection(CollectionPromo):
slug = 'Travelers Pack'
pk = 4
id = 'travel'
cls = 'promo'
title = _(u'Sit Back and Relax')
subtitle = _(u'Add-ons that help you on your travels!')
def get_descriptions(self):
return {
5791: _(u"Displays a country flag depicting the location of the "
"current website's server and more."),
1117: _(u'FoxClocks let you keep an eye on the time around the '
'world.'),
11377: _(u'Automatically get the lowest price when you shop '
'online or search for flights.')
}
class SchoolCollection(CollectionPromo):
slug = 'School'
pk = 2133887
id = 'school'
cls = 'promo'
title = _(u'A+ add-ons for School')
subtitle = _(u'Add-ons for teachers, parents, and students heading back '
'to school.')
def get_descriptions(self):
return {
3456: _(u'Would you like to know which websites you can trust?'),
2410: _(u'Xmarks is the #1 bookmarking add-on.'),
2444: _(u'Web page and text translator, dictionary, and more!')
}
# The add-ons that go with the promo modal. Not an actual PromoModule
class PromoVideoCollection():
items = (349111, 349155, 349157, 52659, 5579, 252539, 11377, 2257)
def get_items(self):
items = Addon.objects.in_bulk(self.items)
return [items[i] for i in self.items if i in items]
class NewYearCollection(CollectionPromo):
slug = 'New Year'
collection_author, collection_slug = 'mozilla', 'newyear_2012'
id = 'new-year'
title = _(u'Add-ons to help you on your way in 2012')
class ValentinesDay(CollectionPromo):
slug = 'Valentines Day'
collection_author, collection_slug = 'amoteam', 'va'
id = 'valentines'
title = _(u'Love is in the Air')
subtitle = _(u'Add some romance to your Firefox.')
class MobileThemes(CollectionPromo):
slug = 'Mobile Themes'
cls = 'promo promo-grey'
collection_author, collection_slug = 'mozilla', 'mobilethemes'
title = _(u'Put a Theme on It!')
subtitle = _(u'Visit addons.mozilla.org from Firefox for Android and '
'dress up your mobile browser to match your style, mood, '
'or the season.')
class Fitness(CollectionPromo):
slug = 'Fitness'
cls = 'promo promo-yellow'
collection_author, collection_slug = 'mozilla', 'fitness'
title = _(u'Get up and move!')
subtitle = _(u'Install these fitness add-ons to keep you active and '
'healthy.')
class UpAndComing(CollectionPromo):
slug = 'Up & Coming'
cls = 'promo promo-blue'
collection_author, collection_slug = 'mozilla', 'up_coming'
title = _(u'New & Now')
subtitle = _(u'Get the latest, must-have add-ons of the moment.')
class Olympics(TemplatePromo):
slug = 'Olympics'
template = 'discovery/modules/olympics.html'
class ContestWinners(TemplatePromo):
slug = 'Contest Winners'
template = 'discovery/modules/contest-winners.html'
def render(self, module_context='discovery'):
# Hide on discovery pane.
if module_context == 'home':
return super(ContestWinners, self).render()
class Holiday(TemplatePromo):
slug = 'Holiday'
template = 'discovery/modules/holiday.html'
def render(self, module_context='discovery'):
# Hide on discovery pane.
if module_context == 'home':
return super(Holiday, self).render()
class Privacy(CollectionPromo):
slug = 'Privacy Collection'
cls = 'promo promo-purple'
collection_author, collection_slug = 'mozilla', 'privacy'
title = _(u'Worry-free browsing')
subtitle = _(u'Protect your privacy online with the add-ons in this '
'collection.')
class Featured(CollectionPromo):
slug = 'Featured Add-ons Collection'
cls = 'promo promo-yellow'
collection_author, collection_slug = 'mozilla', 'featured-add-ons'
title = _(u'Featured Add-ons')
subtitle = _(u'Great add-ons for work, fun, privacy, productivity… '
'just about anything!')
class AmpYourFirefoxWinner(CollectionPromo):
slug = 'Amp Your Firefox Best Overall Add-on'
template = 'discovery/modules/amp-your-firefox-winner.html'
|
Joergen/zamboni
|
apps/discovery/modules.py
|
Python
|
bsd-3-clause
| 10,559
|
[
"VisIt"
] |
e0bf1b89bf78d11af2298fa1d5e49f3b0d911bc0615f814cad122919cfd616f0
|
#!/usr/bin/env python3
#* This file is part of the MOOSE framework
#* https://www.mooseframework.org
#*
#* All rights reserved, see COPYRIGHT for full restrictions
#* https://github.com/idaholab/moose/blob/master/COPYRIGHT
#*
#* Licensed under LGPL 2.1, please see LICENSE for details
#* https://www.gnu.org/licenses/lgpl-2.1.html
import subprocess
import time
import sys
import os
import gc
import shutil
import csv
import tempfile
import threading
# try to import the resource module. We check further down if it failed
try:
import resource
except:
pass
from TestHarness.testers.Tester import Tester
def process_timeout(proc, timeout_sec):
kill_proc = lambda p: p.kill()
timer = threading.Timer(timeout_sec, kill_proc, [proc])
try:
timer.start()
proc.wait()
finally:
timer.cancel()
class Test:
def __init__(self, executable, infile, rootdir='.', args=None, perflog=False):
self.rootdir = rootdir
self.executable = executable
self.infile = infile
self.args = args
self.dur_secs = 0
self.perflog = []
self.getpot_options = ['Outputs/console=false', 'Outputs/exodus=false', 'Outputs/csv=false', '--no-gdb-backtrace']
self.have_perflog = perflog
if self.have_perflog:
self.getpot_options.append('UserObjects/perflog/type=PerflogDumper')
def _buildcmd(self):
cmdpath = os.path.abspath(os.path.join(self.rootdir, self.executable))
infilepath = os.path.abspath(os.path.join(self.rootdir, self.infile))
cmd = [cmdpath, '-i', infilepath]
if self.args is not None:
cmd.extend(self.args)
cmd.extend(self.getpot_options)
# check for linux cpu isolation
isolpath = '/sys/devices/system/cpu/isolated'
cpuid = None
if os.path.exists(isolpath):
with open(isolpath, 'r') as f:
cpus = f.read().split(',')
if len(cpus[0].strip()) > 0:
cpuid = cpus[0]
if cpuid:
cmd = ['taskset', '-c', cpuid] + cmd
return cmd
def reset(self):
self.perflog = []
self.dur_secs = 0
def run(self, timer=None, timeout=300):
self.reset()
cmd = self._buildcmd()
tmpdir = tempfile.mkdtemp()
shutil.rmtree(tmpdir, ignore_errors=True)
os.makedirs(tmpdir)
rusage = resource.getrusage(resource.RUSAGE_CHILDREN)
start = rusage.ru_utime
gc.disable()
with open(os.devnull, 'w') as devnull:
if timer:
timer.start()
p = subprocess.Popen(cmd, cwd=tmpdir, stdout=devnull, stderr=devnull)
process_timeout(p, timeout)
if timer:
timer.stop()
gc.enable()
rusage = resource.getrusage(resource.RUSAGE_CHILDREN)
end = rusage.ru_utime
if p.returncode != 0:
raise RuntimeError('command {} returned nonzero exit code'.format(cmd))
self.dur_secs = end - start
# write perflog
if self.have_perflog:
with open(os.path.join(tmpdir, 'perflog.csv'), 'r') as csvfile:
reader = csv.reader(csvfile)
skip = True # use to skip header line
for row in reader:
if not skip:
self.perflog.append(row)
else:
skip = False
shutil.rmtree(tmpdir)
class SpeedTest(Tester):
@staticmethod
def validParams():
params = Tester.validParams()
params.addParam('input', 'The input file to use for this test.')
params.addParam('test_name', 'The name of the test - populated automatically')
params.addParam('cumulative_dur', 60, 'cumulative time (secs) to run each benchmark')
params.addParam('min_runs', 40, 'minimum number of runs for each benchmark')
params.addParam('max_runs', 400, 'maximum number of runs for each benchmark')
params.addParam('perflog', False, 'true to enable perflog and store its output')
return params
def __init__(self, name, params):
Tester.__init__(self, name, params)
self.tags.append('speedtests')
self.timeout = max(3600, float(params['max_time']))
self.check_only = False
self.params = params
self.benchmark = None
self.db = os.environ.get('MOOSE_SPEED_DB', 'speedtests.sqlite')
# override
def getMaxTime(self):
return self.timeout
# override
def checkRunnable(self, options):
# check if resource is available
if 'resource' not in sys.modules:
return False
# if user is not explicitly running benchmarks, we only run moose once and just check
# input - to make sure the benchmark isn't broken.
if 'speedtests' not in options.runtags:
self.params['max_runs'] = 1
self.params['cli_args'].insert(0, '--check-input')
self.check_only = True
return True
# override
def run(self, timer, options):
p = self.params
if not self.check_only and options.method not in ['opt', 'oprof', 'dbg']:
raise ValueError('cannot run benchmark with "' + options.method + '" build')
t = Test(p['executable'], p['input'], args=p['cli_args'], rootdir=p['test_dir'], perflog=p['perflog'])
if self.check_only:
t.run(timer, timeout=p['max_time'])
return
name = p['test_name'].split('.')[-1]
self.benchmark = Bench(name, test=t, cum_dur=float(p['cumulative_dur']), min_runs=int(p['min_runs']), max_runs=int(p['max_runs']))
self.benchmark.run(timer, timeout=self.timeout)
with DB(self.db) as db:
db.store(self.benchmark)
# override
def processResults(self, moose_dir, options, output):
self.setStatus(self.success)
return output
class Bench:
def __init__(self, name, realruns=None, test=None, cum_dur=60, min_runs=40, max_runs=400):
self.name = name
self.test = test
self.realruns = []
self.perflogruns = []
if realruns is not None:
self.realruns.extend(realruns)
self._cum_dur = cum_dur
self._min_runs = min_runs
self._max_runs = max_runs
def run(self, timer=None, timeout=3600):
tot = 0.0
start = time.time()
while (len(self.realruns) < self._min_runs or tot < self._cum_dur) and len(self.realruns) < self._max_runs:
dt = time.time() - start
if dt >= timeout:
raise RuntimeError('benchmark timed out after {} with {} runs'.format(dt, len(self.realruns)))
self.test.run(timer, timeout=timeout - dt)
self.realruns.append(self.test.dur_secs)
self.perflogruns.append(self.test.perflog)
tot += self.test.dur_secs
class BenchComp:
def __init__(self, oldbench, newbench, psig=0.01):
self.name = oldbench.name
self.psig = psig
self.old = oldbench.realruns
self.new = newbench.realruns
self.iqr_old = _iqr(self.old)
self.iqr_new = _iqr(self.new)
from scipy.stats import mannwhitneyu
try:
result = mannwhitneyu(self.iqr_old, self.iqr_new, alternative='two-sided')
self.pvalue = result.pvalue
except:
self.pvalue = 1.0
self.u = result[0]
self.avg_old = float(sum(self.iqr_old))/len(self.iqr_old)
self.avg_new = float(sum(self.iqr_new))/len(self.iqr_new)
self.speed_change = (self.avg_new - self.avg_old) / self.avg_old
@classmethod
def header(cls, revold, revnew):
oldstr, newstr = revold, revnew
if len(oldstr) > 12:
oldstr = oldstr[:12]
if len(newstr) > 12:
newstr = newstr[:12]
revstr = ' {} to {} '.format(oldstr, newstr)
revstr = revstr.center(30,'-')
return '' \
+ '--------------------------------{}--------------------------------'.format(revstr) \
+ '\n{:^30s} {:^15s} {:^15s} {:5s}'.format('benchmark', 'old (sec/run)', 'new (sec/run)', 'speedup (pvalue, nsamples)') \
+ '\n----------------------------------------------------------------------------------------------'
@classmethod
def footer(cls):
return '----------------------------------------------------------------------------------------------'
def __str__(self):
name = self.name
if len(name) > 30:
name = name[:27] + '...'
if self.pvalue <= self.psig:
return '{:>30s}: {:^15f} {:^15f} {:+5.1f}% (p={:.4f},n={}+{})'.format(name, self.avg_old, self.avg_new, self.speed_change*100, self.pvalue, len(self.iqr_old), len(self.iqr_new))
else:
return '{:>30s}: {:^15f} {:^15f} ~ (p={:.4f},n={}+{})'.format(name, self.avg_old, self.avg_new, self.pvalue, len(self.iqr_old), len(self.iqr_new))
def _iqr(a, frac=1000):
"""return elements of a within frac*iqr of the the interquartile range (inclusive)"""
import numpy
qup, qlow = numpy.percentile(a, [75 ,25])
iqr = qup - qlow
clean = []
for val in a:
if qlow - frac*iqr <= val and val <= qup + frac*iqr:
clean.append(val)
return clean
class DB:
def __init__(self, fname):
CREATE_BENCH_TABLE = '''CREATE TABLE IF NOT EXISTS benchmarks
(
id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT,
executable TEXT,
executable_name TEXT,
executable_method TEXT,
input_file TEXT,
timestamp INTEGER,
revision TEXT,
date INTEGER,
load REAL
);'''
CREATE_TIMES_TABLE = '''CREATE TABLE IF NOT EXISTS timings
(
benchmark_id INTEGER,
run INTEGER,
realtime_secs REAL
);'''
CREATE_PERFLOG_TABLE = '''CREATE TABLE IF NOT EXISTS perflog
(
benchmark_id INTEGER,
run INTEGER,
field TEXT,
subfield TEXT,
exec_count INTEGER,
self_time_secs REAL,
cum_time_secs REAL
);'''
self.fname = fname
# python might not have sqlite3 builtin, so do the import here so
# that the TestHarness can always import this file
import sqlite3
self.conn = sqlite3.connect(fname)
c = self.conn.cursor()
c.execute(CREATE_BENCH_TABLE)
c.execute(CREATE_TIMES_TABLE)
c.execute(CREATE_PERFLOG_TABLE)
def __enter__(self):
return self
def __exit__(self, *args):
self.close()
def revisions(self, method='opt'):
c = self.conn.cursor()
c.execute('SELECT revision,date FROM benchmarks WHERE executable_method=? GROUP BY revision ORDER BY date ASC', (method,))
rows = c.fetchall()
revs = []
times = []
for r in rows:
revs.append(r[0])
times.append(r[1])
return revs, times
def bench_names(self, method='opt'):
c = self.conn.cursor()
c.execute('SELECT DISTINCT name FROM benchmarks WHERE executable_method=?', (method,))
rows = c.fetchall()
names = []
for r in rows:
names.append(r[0])
return names
def list(self, revision, benchmark='', method='opt'):
c = self.conn.cursor()
if benchmark == '':
c.execute('SELECT id,name,executable,input_file FROM benchmarks WHERE INSTR(revision,?) AND executable_method=? ORDER BY date ASC', (revision,method))
else:
c.execute('SELECT id,name,executable,input_file FROM benchmarks WHERE INSTR(revision,?) AND name=? AND executable_method=? ORDER BY date ASC', (revision,benchmark,method))
benchmarks = c.fetchall()
return benchmarks
def load_times(self, bench_id):
c = self.conn.cursor()
c.execute('SELECT realtime_secs FROM timings WHERE benchmark_id=?', (bench_id,))
ents = c.fetchall()
real = []
for ent in ents:
real.append(float(ent[0]))
return real
def load(self, revision, bench_name, method='opt'):
"""loads and returns a Bench object for the given revision and benchmark name"""
entries = self.list(revision, benchmark=bench_name, method=method)
if len(entries) < 1:
raise RuntimeError('load: no benchamrk for revision="{}",bench_name="{}"'.format(revision, bench_name))
b = entries[0]
real = self.load_times(b[0])
return Bench(b[1], test=Test(b[2], b[3]), realruns=real)
def store(self, benchmark, rev=None):
"""stores a (run/executed) Bench in the database. if rev is None, git revision is retrieved from git"""
ex = benchmark.test.executable
(ex_name, ex_method) = os.path.basename(ex).rsplit('-', 1)
infile = benchmark.test.infile
timestamp = time.time()
date = timestamp
if rev is None:
if 'MOOSE_REVISION' in os.environ:
rev = os.environ['MOOSE_REVISION']
else:
rev, date = git_revision()
load = os.getloadavg()[0]
c = self.conn.cursor()
c.execute('INSERT INTO benchmarks (name,executable,executable_name,executable_method,input_file,timestamp,revision,date,load) VALUES (?,?,?,?,?,?,?,?,?)',
(benchmark.name, ex, ex_name, ex_method, infile, timestamp, rev, date, load))
bench_id = c.lastrowid
self.conn.commit()
i = 0
for real, perflog in zip(benchmark.realruns, benchmark.perflogruns):
c.execute('INSERT INTO timings (benchmark_id, run, realtime_secs) VALUES (?,?,?)', (bench_id, i, real))
i += 1
for entry in perflog:
cat, subcat, nruns, selftime, cumtime = entry
c.execute('INSERT INTO perflog (benchmark_id, run, field, subfield, exec_count, self_time_secs, cum_time_secs) VALUES (?,?,?,?,?,?,?)',
(bench_id, i, cat, subcat, nruns, selftime, cumtime))
return bench_id
def close(self):
self.conn.commit()
self.conn.close()
def git_revision(dir='.'):
# return hash and (unix secs since epoch) date
cmd = ['git', 'log', '--date', 'raw', '--pretty=format:%H %ad', '-n', '1']
p = subprocess.Popen(cmd, stdout=subprocess.PIPE, cwd=dir)
stdout, stderr = p.communicate()
if p.returncode != 0:
raise RuntimeError('failed to retrieve git revision')
commit = str(stdout).strip().split(' ')[0]
date = int(str(stdout).strip().split(' ')[1])
return commit, date
|
nuclear-wizard/moose
|
python/TestHarness/testers/bench.py
|
Python
|
lgpl-2.1
| 14,805
|
[
"MOOSE"
] |
ee9a67e7a556b4e0335fed1621c91aecb7bbe6de0e54846423048e4861a3ddf9
|
"""
API operations on remote files.
"""
import os
import time
import hashlib
from galaxy import web
from galaxy import exceptions
from galaxy.web import _future_expose_api as expose_api
from galaxy.util import jstree
from galaxy.web.base.controller import BaseAPIController, url_for
from operator import itemgetter
import logging
log = logging.getLogger( __name__ )
class FTPFilesAPIController( BaseAPIController ):
@expose_api
def index( self, trans, **kwd ):
"""
GET /api/ftp_files/
Displays remote files.
:param target: target to load available datasets from, defaults to ftp
possible values: ftp, userdir
:type target: str
:param format: requested format of data, defaults to flat
possible values: flat, jstree, ajax
:returns: list of available files
:rtype: list
"""
target = kwd.get( 'target', None )
format = kwd.get( 'format', None )
if target == 'userdir':
user_login = trans.user.email
user_base_dir = trans.app.config.user_library_import_dir
if user_base_dir is None:
raise exceptions.ConfigDoesNotAllowException( 'The configuration of this Galaxy instance does not allow upload from user directories.' )
full_import_dir = os.path.join( user_base_dir, user_login )
if full_import_dir is not None:
if format == 'jstree':
disable = kwd.get( 'disable', 'folders')
try:
userdir_jstree = self.__create_jstree( full_import_dir, disable )
response = userdir_jstree.jsonData()
except Exception, exception:
log.debug(str(exception))
raise exceptions.InternalServerError( 'Could not create tree representation of the given folder: ' + str( full_import_dir ) )
elif format == 'ajax':
raise exceptions.NotImplemented( 'Not implemented yet. Sorry.' )
else:
try:
response = self.__load_all_filenames( full_import_dir )
except Exception, exception:
log.error( 'Could not get user import files: %s', str( exception ), exc_info=True )
raise exceptions.InternalServerError( 'Could not get the files from your user directory folder.' )
else:
raise exceptions.InternalServerError( 'Could not get the files from your user directory folder.' )
else:
user_ftp_base_dir = trans.app.config.ftp_upload_dir
if user_ftp_base_dir is None:
raise exceptions.ConfigDoesNotAllowException( 'The configuration of this Galaxy instance does not allow upload from FTP directories.' )
try:
user_ftp_dir = None
identifier = trans.app.config.ftp_upload_dir_identifier
user_ftp_dir = os.path.join( user_ftp_base_dir, getattr(trans.user, identifier) )
if user_ftp_dir is not None:
response = self.__load_all_filenames( user_ftp_dir )
else:
raise exceptions.ConfigDoesNotAllowException( 'You do not have an FTP directory named as your login at this Galaxy instance.' )
except Exception, exception:
log.error( 'Could not get ftp files: %s', str( exception ), exc_info=True )
raise exceptions.InternalServerError( 'Could not get the files from your FTP folder.' )
return response
def __load_all_filenames( self, directory ):
"""
Loads recursively all files within the given folder and its
subfolders and returns a flat list.
"""
response = []
if os.path.exists( directory ):
for ( dirpath, dirnames, filenames ) in os.walk( directory ):
for filename in filenames:
path = os.path.relpath( os.path.join( dirpath, filename ), directory )
statinfo = os.lstat( os.path.join( dirpath, filename ) )
response.append( dict( path = path,
size = statinfo.st_size,
ctime = time.strftime( "%m/%d/%Y %I:%M:%S %p", time.localtime( statinfo.st_ctime ) ) ) )
else:
raise exceptions.ConfigDoesNotAllowException( 'The given directory does not exist.' )
# sort by path
response = sorted(response, key=itemgetter("path"))
return response
def __create_jstree( self, directory, disable='folders' ):
"""
Loads recursively all files and folders within the given folder
and its subfolders and returns jstree representation
of its structure.
"""
userdir_jstree = None
jstree_paths = []
if os.path.exists( directory ):
for ( dirpath, dirnames, filenames ) in os.walk( directory ):
for dirname in dirnames:
dir_path = os.path.relpath( os.path.join( dirpath, dirname ), directory )
dir_path_hash = hashlib.sha1( dir_path ).hexdigest()
disabled = True if disable == 'folders' else False
jstree_paths.append( jstree.Path( dir_path, dir_path_hash, { 'type': 'folder', 'state': { 'disabled': disabled }, 'li_attr': { 'full_path': dir_path } } ) )
for filename in filenames:
file_path = os.path.relpath( os.path.join( dirpath, filename ), directory )
file_path_hash = hashlib.sha1( file_path ).hexdigest()
disabled = True if disable == 'files' else False
jstree_paths.append( jstree.Path( file_path, file_path_hash, { 'type': 'file', 'state': { 'disabled': disabled }, 'li_attr': { 'full_path': file_path } } ) )
else:
raise exceptions.ConfigDoesNotAllowException( 'The given directory does not exist.' )
userdir_jstree = jstree.JSTree( jstree_paths )
return userdir_jstree
|
mikel-egana-aranguren/SADI-Galaxy-Docker
|
galaxy-dist/lib/galaxy/webapps/galaxy/api/ftp_files.py
|
Python
|
gpl-3.0
| 6,231
|
[
"Galaxy"
] |
6fa0187171730a466bd9422f488f692dee5841bb3ced6555fe05462b312fb103
|
#! /usr/bin/python
import os;
import sys;
import math;
import random;
class StructEvent:
def __init__(self, size=0, type='', position=0):
self.size = size;
self.type = type;
self.position = position;
self.position_final = position;
self.open_cov = 0;
self.close_cov = 0;
self.max_cov = 0;
self.max_event_length = 0;
self.comment = '';
self.evaluation = '(not evaluated)';
def verbose(self):
sys.stderr.write(self.verbose_to_string());
def verbose_to_string(self):
event_type = 'insertion_in_read' if (self.type == 'D' or self.type == 'insertion_in_read') else 'deletion_in_read';
return 'Event type: %s, position: %7d, end: %7d, size: %4d, max_event_length = %4d, result: %s, comment: %s' % (event_type, self.position, (self.position + self.size), self.size, self.max_event_length, self.evaluation, self.comment);
def csv_line(self):
# ret = 'type: %s\tstart: %d\tend: %d\topen_cov: %d\tclose_cov: %d\tmax_cov: %d' % (self.type, self.start, self.end, self.open_coverage, self.close_coverage, self.max_coverage);
event_type = 'insertion_in_read' if (self.type == 'D' or self.type == 'insertion_in_read') else 'deletion_in_read';
ret = '%s\t%d\t%d\t%d\t%d\t%d\t%d\t%d\t%s' % (event_type, self.position, (self.position + self.size), self.size, self.open_cov, self.close_cov, self.max_cov, self.max_event_length, self.comment);
return ret;
def csv_header(self):
ret = 'type\tstart\tend\tlength\topen_cov\tclose_cov\tmax_cov\tmax_event_length\tcomment';
return ret;
def check_event_near_blacklist(event, blacklist_events, allowed_distance):
# print event.verbose_to_string();
for blacklist_event in blacklist_events:
if (blacklist_event.comment != 'real'):
# print blacklist_event.verbose_to_string();
event_start = event.position;
event_end = event.position + event.size;
blacklist_event_start = blacklist_event.position;
# blacklist_event_end = (blacklist_event.position + blacklist_event.size) if (blacklist_event.type == 'I') else (blacklist_event.position + 1);
blacklist_event_end = (blacklist_event.position + blacklist_event.size);
# print 'Blacklisted event: ', blacklist_event.verbose_to_string();
# print blacklist_event_start;
# print blacklist_event_end;
if ((event_start < blacklist_event_start and event_end < blacklist_event_start) or
(event_start > blacklist_event_end and event_end > blacklist_event_end)):
### If the events do not overlap, check the distances.
dists = [abs(event_start - blacklist_event_start),
abs(event_start - blacklist_event_end),
abs(event_end - blacklist_event_start),
abs(event_end - blacklist_event_end)];
# print dists;
for dist in dists:
if (dist < allowed_distance):
return True;
else:
### If they overlap, just return True.
return True;
# if (event.position == 1096291):
# print 'Tu sam!';
# print allowed_distance;
# exit(1);
return False;
def evaluate_event(event, truth_events, allowed_percent_variation):
event_distances = [];
allowed_distance = event.size * allowed_percent_variation;
for truth_event in truth_events:
event_start = event.position;
event_end = event.position + event.size;
truth_event_start = truth_event.position;
truth_event_end = (truth_event.position + truth_event.size) if (truth_event.type == 'I') else (truth_event.position + 1);
##### allowed_distance = truth_event.size * allowed_percent_variation;
if (check_event_near_blacklist(event, truth_events, allowed_distance) == True):
event.evaluation = TN;
return TN;
else:
distance = abs(truth_event_start - event_start);
event_distances.append([distance, truth_event]);
sorted_event_distances = sorted(event_distances, key=lambda x: x[0]);
### Take only the truth event with the smallest distance.
### best_truth[0] is the distance from the tested event to the truth event.
### best_truth[1] is a reference to the truth event.
best_truth = sorted_event_distances[0];
truth_size = best_truth[1].size;
size_difference = abs(event.max_event_length - truth_size);
##### allowed_distance = best_truth[1].size * allowed_percent_variation;
# sys.stderr.write(best_truth[1].verbose_to_string() + '\n');
### Check the starting position of the event, as well as its length.
if (best_truth[1].type == event.type and best_truth[0] < allowed_distance and size_difference < math.ceil(allowed_percent_variation * truth_size)):
event.evaluation = TP;
best_truth_type = 'insertion_in_read' if (best_truth[1].type == 'D' or best_truth[1].type == 'insertion_in_read') else 'deletion_in_read';
event.comment += ' nearest_truth=[dist:%d size:%d pos:%d type:%s]' % (best_truth[0], best_truth[1].size, best_truth[1].position, best_truth_type);
return TP;
# print '-> %s\t%s' % (best_truth[0], best_truth[1].verbose_to_string());
event.evaluation = FP;
# event.evaluation += ' nearest_truths=[%s]' % (';'.join([str(truth_event[1].position) for truth_event in sorted_event_distances]));
# event.comment += ' nearest_truth=[dist:%d type:%s pos:%d size:%d]' % (best_truth[0], best_truth[1].type, best_truth[1].position, best_truth[1].size);
best_truth_type = 'insertion_in_read' if (best_truth[1].type == 'D' or best_truth[1].type == 'insertion_in_read') else 'deletion_in_read';
event.comment += ' nearest_truth=[dist:%d type:%s pos:%d size:%d]' % (best_truth[0], best_truth_type, best_truth[1].position, best_truth[1].size);
if (best_truth[0] >= allowed_distance):
event.comment += ' dist=%d/%d' % (best_truth[0], allowed_distance);
if (size_difference >= allowed_percent_variation * truth_size):
event.comment += ' size=%d/%d' % (size_difference, math.ceil(allowed_percent_variation * truth_size));
if (best_truth[1].type != event.type):
event.comment += ' wrong_type';
return FP;
def evaluate(events, events_truth, fp_out=sys.stdout):
sorted_events = sorted(events, key=lambda x: x.position);
sorted_events_truth = sorted(events_truth, key=lambda x: x.position);
i = 0;
for event in sorted_events:
i += 1;
fp_out.write('[%d] %s\t%s\n' % (i, evaluate_event(event, events_truth, 0.25), event.verbose_to_string()));
# print '\n';
def load_events(events_path):
events = [];
num_lines = 0;
fp = open(events_path);
for line in fp:
num_lines += 1;
line = line.strip();
if (len(line) == 0):
continue;
if (num_lines == 1):
labels = line;
continue;
# print line;
values = line.split('\t');
# event_type = 'I' if (values[0] == 'deletion_in_read') else 'D';
event_type = 'insertion_in_read' if (values[0] == 'D' or values[0] == 'insertion_in_read') else 'deletion_in_read';
start = int(values[1]);
end = int(values[2]);
length = int(values[3]);
open_cov = int(values[4]);
close_cov = int(values[5]);
max_cov = int(values[6]);
max_event_length = int(values[7]);
comment = values[8] if (len(values) > 8) else '';
event = StructEvent(length, event_type, start);
event.open_cov = open_cov;
event.close_cov = close_cov;
event.max_cov = max_cov;
event.max_event_length = max_event_length;
event.comment = comment;
events.append(event);
fp.close();
### Chain events that got fragmented
sorted_events = sorted(events, key=lambda x: x.position);
chained_events = [];
for event in sorted_events:
if (len(chained_events) > 0):
last_size = chained_events[-1].size;
last_endpoint = chained_events[-1].position + last_size;
last_type = chained_events[-1].type;
distance = abs(event.position - last_endpoint);
if (distance <= (last_size + event.size) and last_type == event.type):
chained_events[-1].close_cov = event.close_cov;
chained_events[-1].max_cov = max(chained_events[-1].max_cov, event.max_cov);
chained_events[-1].max_event_length = max(chained_events[-1].max_event_length, event.max_event_length);
chained_events[-1].size = event.position + event.size - chained_events[-1].position + 1;
# print 'Chaining: %s' % chained_events[-1].verbose_to_string();
else:
chained_events.append(event);
else:
chained_events.append(event);
# sys.stderr.write('Chained events:\n');
# for event in chained_events:
# sys.stderr.write(event.csv_line() + '\n');
return chained_events;
# return events;
def calculate_stats(events, events_truth, fp_out):
tp = 0;
fp = 0;
for event in events:
if (event.evaluation == TP):
tp += 1;
elif (event.evaluation == FP):
fp += 1;
num_real_events = 0;
for truth_event in events_truth:
if ('real' in truth_event.comment):
num_real_events += 1;
recall = float(tp) / float(num_real_events);
if (tp + fp) > 0:
precision = float(tp) / float(tp + fp)
else:
precision = 0.0
F1 = 0.0 if (tp == 0) else (2.0 * (precision * recall) / (precision + recall));
fp_out.write('Precision: %.1f%% (%d / %d)\n' % (precision * 100.0, tp, (tp + fp)));
fp_out.write('Recall: %.1f%% (%d / %d)\n' % (recall * 100.0, tp, (num_real_events)));
fp_out.write('F1: %.1f%%\n' % (F1 * 100.0));
def main():
if (len(sys.argv) < 3):
sys.stderr.write('Usage:\n');
sys.stderr.write('\t%s default\n' % (sys.argv[0]));
sys.stderr.write('\tor\n');
sys.stderr.write('\t%s <path_to_truths_csv> <events1.csv> [<events2.csv> ...]\n' % (sys.argv[0]));
sys.stderr.write('\n');
sys.stderr.write('Using default files for legacy.\n');
sys.stderr.write('\n');
exit(0);
### This is the full list. Commented out when I tested on the latest version of the anchored alignment.
# if (len(sys.argv) == 1 or (len(sys.argv) == 2 and sys.argv[1] == 'default')):
# events_truth_path = 'results/truth_events-full.csv';
# all_events_paths = ['results/events-indel_events-graphmap.csv',
# 'results/events-indel_events-bwamem.csv',
# 'results/events-indel_events-last.csv',
# 'results/events-indel_events-last-nanopore.csv',
# 'results/events-indel_events-blasr.csv'];
# else:
events_truth_path = sys.argv[1];
all_events_paths = [];
for event_file in sys.argv[2:]:
all_events_paths.append(event_file);
# all_events_paths = ['results/events-indel_events-graphmap-20150525.csv'];
### all_events_paths = ['results/events-indel_events-graphmap-20150527.csv'];
# all_events_paths = ['results/events-indel-graphmap.csv'];
# all_events_paths = ['results/events-indel_events-blasr.csv'];
# events_for_evaluation_path = 'results/events-indel-graphmap.csv';
# events_for_evaluation_path = 'results/events-indel_events-bwamem.csv';
# events_for_evaluation_path = 'results/events-indel_events-blasr.csv';
# znaci problem je u tome sto u ovim konkretnim primjerima postoji read koji ima event, ali jako veliki, preveliki od ocekivanoga
# vrlo vjerojatno lose filtrirano
# prije se to nije pojavljivalo
# max_event_length je preveliki
# pogledati figure za "channel_51_read_42_twodirections_/dev/shm/downloads/LomanLabz_E.coli_MG1655_3311_1_ch51_file42_strand.fast5"
sys.stderr.write('Loading truth events...\n');
events_truth = load_events(events_truth_path);
for events_for_evaluation_path in all_events_paths:
dirname_path = os.path.dirname(events_truth_path);
if (len(dirname_path) == 0 or (dirname_path[0] in './') == False):
dirname_path = './%s' % dirname_path;
out_path = '%s/evaluated-%s' % (dirname_path, os.path.basename(events_for_evaluation_path));
sys.stderr.write('Processing file "%s" and writing output to "%s"...\n' % (events_for_evaluation_path, out_path));
fp_out = open(out_path, 'w');
events = load_events(events_for_evaluation_path);
evaluate(events, events_truth, fp_out);
calculate_stats(events, events_truth, fp_out);
sys.stderr.write('Stats for "%s":\n' % (os.path.basename(events_for_evaluation_path)));
calculate_stats(events, events_truth, sys.stderr);
sys.stderr.write('\n');
fp_out.close();
sys.stderr.write('Done!\n\n');
# events_for_evaluation_path = 'results/events-blacklist-bwamem.csv';
# events_for_evaluation_path = 'results/events-blacklist_events-blasr.csv';
# ./evaluate_events.py > results/test-BWA-MEM.csv
# ./evaluate_events.py > results/test-GraphMap.csv
# ./evaluate_events.py > results/test-BLASR.csv
# for event in events:
# event.verbose();
# sys.stderr.write('\n');
if __name__ == "__main__":
TP = 'true';
FP = 'false';
TN = 'blacklisted';
main();
|
isovic/test-scripts
|
src/evaluate_events.py
|
Python
|
mit
| 12,260
|
[
"BWA"
] |
efe049f412afaa07c6d14c5e2a6fa5209353f22244f79df6b9f0a858dc3d4fa8
|
"""
Module for managing the installation of DIRAC components:
MySQL, DB's, NoSQL DBs, Services, Agents, Executors
It only makes use of defaults in LocalInstallation Section in dirac.cfg
The Following Options are used::
/DIRAC/Setup: Setup to be used for any operation
/LocalInstallation/InstanceName: Name of the Instance for the current Setup (default /DIRAC/Setup)
/LocalInstallation/LogLevel: LogLevel set in "run" script for all components installed
/LocalInstallation/RootPath: Python 2 only! Used instead of rootPath in "run" script
if defined (if links are used to named versions)
/LocalInstallation/InstancePath: Python 2 only! Location where runit and
startup directories are created (default rootPath)
/LocalInstallation/UseVersionsDir: Python 2 only! DIRAC is installed under
versions/<Versioned Directory> with a link from pro
(This option overwrites RootPath and InstancePath)
/LocalInstallation/Host: Used when build the URL to be published for the installed
service (default: socket.getfqdn())
/LocalInstallation/RunitDir: Location where runit directory is created (default InstancePath/runit)
/LocalInstallation/StartupDir: Location where startup directory is created (default InstancePath/startup)
/LocalInstallation/Database/User: (default Dirac)
/LocalInstallation/Database/Password: (must be set for SystemAdministrator Service to work)
/LocalInstallation/Database/RootUser: (default root)
/LocalInstallation/Database/RootPwd: (must be set for SystemAdministrator Service to work)
/LocalInstallation/Database/Host: (must be set for SystemAdministrator Service to work)
/LocalInstallation/Database/Port: (default 3306)
/LocalInstallation/NoSQLDatabase/Host: (must be set for SystemAdministrator Service to work)
/LocalInstallation/NoSQLDatabase/Port: (default 9200)
/LocalInstallation/NoSQLDatabase/User: (default '')
/LocalInstallation/NoSQLDatabase/Password: (not strictly necessary)
/LocalInstallation/NoSQLDatabase/SSL: (default True)
The setupSite method (used by the dirac-setup-site command) will use the following info::
/LocalInstallation/Systems: List of Systems to be defined for this instance
in the CS (default: Configuration, Framework)
/LocalInstallation/Databases: List of MySQL Databases to be installed and configured
/LocalInstallation/Services: List of System/ServiceName to be setup
/LocalInstallation/Agents: List of System/AgentName to be setup
/LocalInstallation/WebPortal: Boolean to setup the Web Portal (default no)
/LocalInstallation/ConfigurationMaster: Boolean, requires Configuration/Server to be given
in the list of Services (default: no)
/LocalInstallation/PrivateConfiguration: Boolean, requires Configuration/Server to be given
in the list of Services (default: no)
If a Master Configuration Server is being installed the following Options can be used::
/LocalInstallation/ConfigurationName: Name of the Configuration (default: Setup )
/LocalInstallation/AdminUserName: Name of the Admin user (default: None )
/LocalInstallation/AdminUserDN: DN of the Admin user certificate (default: None )
/LocalInstallation/AdminUserEmail: Email of the Admin user (default: None )
/LocalInstallation/AdminGroupName: Name of the Admin group (default: dirac_admin )
/LocalInstallation/HostDN: DN of the host certificate (default: None )
/LocalInstallation/VirtualOrganization: Name of the main Virtual Organization (default: None)
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
__RCSID__ = "$Id$"
import glob
import importlib
import inspect
import io
import MySQLdb
import os
import pkgutil
import re
import shutil
import stat
import time
from collections import defaultdict
from importlib import metadata
import importlib_resources
import subprocess32 as subprocess
from diraccfg import CFG
from prompt_toolkit import prompt
import DIRAC
from DIRAC import rootPath
from DIRAC import gConfig
from DIRAC import gLogger
from DIRAC.Core.Utilities.Subprocess import systemCall
from DIRAC.Core.Utilities.ReturnValues import S_OK, S_ERROR
from DIRAC.Core.Utilities.Version import getVersion
from DIRAC.Core.Utilities.File import mkDir, mkLink
from DIRAC.ConfigurationSystem.Client.CSAPI import CSAPI
from DIRAC.ConfigurationSystem.Client.Helpers import (
cfgPath,
cfgPathToList,
cfgInstallPath,
cfgInstallSection,
CSGlobals,
)
from DIRAC.Core.Security.Properties import (
ALARMS_MANAGEMENT,
SERVICE_ADMINISTRATOR,
CS_ADMINISTRATOR,
JOB_ADMINISTRATOR,
FULL_DELEGATION,
PROXY_MANAGEMENT,
OPERATOR,
NORMAL_USER,
TRUSTED_HOST,
)
from DIRAC.ConfigurationSystem.Client import PathFinder
from DIRAC.Core.Utilities.MySQL import MySQL
from DIRAC.Core.Base.private.ModuleLoader import ModuleLoader
from DIRAC.Core.Base.AgentModule import AgentModule
from DIRAC.Core.Base.ExecutorModule import ExecutorModule
from DIRAC.Core.DISET.RequestHandler import RequestHandler
from DIRAC.Core.Utilities.Decorators import deprecated
from DIRAC.Core.Utilities.PrettyPrint import printTable
from DIRAC.Core.Utilities.Extensions import (
extensionsByPriority,
findDatabases,
findModules,
findAgents,
findServices,
findExecutors,
findSystems,
)
from DIRAC.FrameworkSystem.Client.ComponentMonitoringClient import ComponentMonitoringClient
__RCSID__ = "$Id$"
def _safeFloat(value):
try:
return float(value)
except ValueError:
return -1
def _safeInt(value):
try:
return int(value)
except ValueError:
return -1
def _makeComponentDict(component, setupDict, installedDict, compType, system, runitDict):
componentDict = {
"Setup": component in setupDict.get(compType, {}).get(system, {}),
"Installed": component in installedDict.get(compType, {}).get(system, {}),
"RunitStatus": "Unknown",
"Timeup": 0,
"PID": 0,
}
compDir = system + "_" + component
if compDir in runitDict:
componentDict["RunitStatus"] = runitDict[compDir]["RunitStatus"]
componentDict["Timeup"] = runitDict[compDir]["Timeup"]
componentDict["PID"] = _safeInt(runitDict[compDir].get("PID", -1))
componentDict["CPU"] = _safeFloat(runitDict[compDir].get("CPU", -1))
componentDict["MEM"] = _safeFloat(runitDict[compDir].get("MEM", -1))
componentDict["RSS"] = _safeFloat(runitDict[compDir].get("RSS", -1))
componentDict["VSZ"] = _safeFloat(runitDict[compDir].get("VSZ", -1))
return componentDict
def _getSectionName(compType):
"""
Returns the section name for a component in the CS
For self.instance, the section for service is Services,
whereas the section for agent is Agents
"""
return "%ss" % compType.title()
class ComponentInstaller(object):
def __init__(self):
self.gDefaultPerms = (
stat.S_IWUSR | stat.S_IRUSR | stat.S_IXUSR | stat.S_IRGRP | stat.S_IXGRP | stat.S_IROTH | stat.S_IXOTH
)
# On command line tools this can be set to True to abort after the first error.
self.exitOnError = False
# First some global defaults
gLogger.debug("DIRAC Root Path =", rootPath)
self.mysqlMode = ""
self.localCfg = None
self.cfgFile = ""
self.setup = ""
self.instance = ""
self.logLevel = ""
self.linkedRootPath = ""
self.host = ""
self.basePath = ""
self.instancePath = ""
self.runitDir = ""
self.startDir = ""
self.db = {}
self.mysqlUser = ""
self.mysqlPassword = ""
self.mysqlRootUser = ""
self.mysqlRootPwd = ""
self.mysqlHost = ""
self.mysqlPort = ""
self.noSQLHost = ""
self.noSQLPort = ""
self.noSQLUser = ""
self.noSQLPassword = ""
self.noSQLSSL = ""
self.controlDir = ""
self.componentTypes = ["service", "agent", "executor"]
self.monitoringClient = None
self.loadDiracCfg()
def resultIndexes(self, componentTypes):
resultIndexes = {}
for cType in componentTypes:
resultIndexes[cType] = _getSectionName(cType)
return S_OK(resultIndexes)
def loadDiracCfg(self):
"""Read again defaults from dirac.cfg"""
from DIRAC.Core.Utilities.Network import getFQDN
self.localCfg = CFG()
self.cfgFile = os.path.join(rootPath, "etc", "dirac.cfg")
try:
self.localCfg.loadFromFile(self.cfgFile)
except Exception:
gLogger.always("Can't load ", self.cfgFile)
gLogger.always("Might be OK if setting up the site")
self.setup = self.localCfg.getOption(cfgPath("DIRAC", "Setup"), "")
self.instance = self.localCfg.getOption(cfgInstallPath("InstanceName"), self.setup)
self.logLevel = self.localCfg.getOption(cfgInstallPath("LogLevel"), "INFO")
self.linkedRootPath = rootPath
self.host = self.localCfg.getOption(cfgInstallPath("Host"), getFQDN())
self.basePath = os.path.dirname(rootPath)
self.instancePath = rootPath
self.runitDir = os.path.join(self.instancePath, "runit")
self.runitDir = self.localCfg.getOption(cfgInstallPath("RunitDir"), self.runitDir)
gLogger.verbose("Using Runit Dir at", self.runitDir)
self.startDir = os.path.join(self.instancePath, "startup")
self.startDir = self.localCfg.getOption(cfgInstallPath("StartupDir"), self.startDir)
gLogger.verbose("Using Startup Dir at", self.startDir)
self.controlDir = os.path.join(self.instancePath, "control")
self.controlDir = self.localCfg.getOption(cfgInstallPath("ControlDir"), self.controlDir)
gLogger.verbose("Using Control Dir at", self.controlDir)
# Now some MySQL default values
self.mysqlRootPwd = self.localCfg.getOption(cfgInstallPath("Database", "RootPwd"), self.mysqlRootPwd)
if self.mysqlRootPwd:
gLogger.verbose("Reading Root MySQL Password from local configuration")
else:
gLogger.warn("MySQL root password not found")
self.mysqlUser = self.localCfg.getOption(cfgInstallPath("Database", "User"), self.mysqlUser)
if self.mysqlUser:
gLogger.verbose("Reading MySQL User from local configuration")
else:
gLogger.warn("Using 'Dirac' as MySQL user name")
self.mysqlUser = "Dirac"
self.mysqlPassword = self.localCfg.getOption(cfgInstallPath("Database", "Password"), self.mysqlPassword)
if self.mysqlPassword:
gLogger.verbose("Reading %s MySQL Password from local configuration " % self.mysqlUser)
else:
gLogger.warn("MySQL password not found")
self.mysqlHost = self.localCfg.getOption(cfgInstallPath("Database", "Host"), "")
if self.mysqlHost:
gLogger.verbose("Using MySQL Host from local configuration", self.mysqlHost)
else:
gLogger.warn("Using the same host for MySQL as dirac services")
self.mysqlHost = self.host
self.mysqlPort = self.localCfg.getOption(cfgInstallPath("Database", "Port"), 0)
if self.mysqlPort:
gLogger.verbose("Using MySQL Port from local configuration ", self.mysqlPort)
else:
gLogger.warn("Using port '3306' as MySQL port")
self.mysqlPort = 3306
self.mysqlRootUser = self.localCfg.getOption(cfgInstallPath("Database", "RootUser"), "")
if self.mysqlRootUser:
gLogger.verbose("Using MySQL root user from local configuration ", self.mysqlRootUser)
else:
gLogger.warn("Using 'root' as root MySQL user")
self.mysqlRootUser = "root"
self.mysqlMode = self.localCfg.getOption(cfgInstallPath("Database", "MySQLMode"), "")
if self.mysqlMode:
gLogger.verbose("Configuring MySQL server as %s" % self.mysqlMode)
# Now some noSQL defaults
self.noSQLHost = self.localCfg.getOption(cfgInstallPath("NoSQLDatabase", "Host"), "")
if self.noSQLHost:
gLogger.verbose("Using NoSQL Host from local configuration", self.noSQLHost)
else:
gLogger.warn("Using the same host for NoSQL as dirac services")
self.noSQLHost = self.host
self.noSQLPort = self.localCfg.getOption(cfgInstallPath("NoSQLDatabase", "Port"), 0)
if self.noSQLPort:
gLogger.verbose("Using NoSQL Port from local configuration ", self.noSQLPort)
else:
gLogger.warn("Using the default port 9200")
self.noSQLPort = 9200
self.noSQLUser = self.localCfg.getOption(cfgInstallPath("NoSQLDatabase", "User"), self.noSQLUser)
if self.noSQLUser:
gLogger.verbose("Reading NoSQL User from local configuration")
else:
gLogger.warn("NoSQL user not found")
self.noSQLPassword = self.localCfg.getOption(cfgInstallPath("NoSQLDatabase", "Password"), self.noSQLPassword)
if self.noSQLPassword:
gLogger.verbose("Reading %s NoSQL Password from local configuration " % self.noSQLUser)
else:
gLogger.warn("NoSQL password not found")
self.noSQLSSL = self.localCfg.getOption(cfgInstallPath("NoSQLDatabase", "SSL"), self.noSQLSSL)
if self.noSQLSSL:
gLogger.verbose("Reading NoSQL SSL choice from local configuration")
else:
gLogger.warn("NoSQL SSL choice not found")
# Now ready to insert components in the Component Monitoring DB
self.monitoringClient = ComponentMonitoringClient()
gLogger.verbose("Client configured for Component Monitoring")
def getInfo(self):
result = getVersion()
if not result["OK"]:
return result
rDict = result["Value"]
rDict["Setup"] = self.setup or "Unknown"
return S_OK(rDict)
@deprecated("Use DIRAC.Core.Utilities.Extensions.extensionsByPriority instead")
def getExtensions(self):
"""Get the list of installed extensions"""
extensions = extensionsByPriority()
try:
extensions.remove("DIRAC")
except Exception:
error = "DIRAC is not properly installed"
gLogger.exception(error)
if self.exitOnError:
DIRAC.exit(-1)
return S_ERROR(error)
return S_OK(extensions)
def _addCfgToDiracCfg(self, cfg):
"""
Merge cfg into existing dirac.cfg file
"""
newCfg = self.localCfg.mergeWith(cfg) if str(self.localCfg) else cfg
result = newCfg.writeToFile(self.cfgFile)
if not result:
return result
self.loadDiracCfg()
return result
def _addCfgToCS(self, cfg):
"""
Merge cfg into central CS
"""
gLogger.debug("Adding CFG to CS:")
gLogger.debug(cfg)
cfgClient = CSAPI()
result = cfgClient.downloadCSData()
if not result["OK"]:
return result
result = cfgClient.mergeFromCFG(cfg)
if not result["OK"]:
return result
result = cfgClient.commit()
return result
def _addCfgToLocalCS(self, cfg):
"""
Merge cfg into local CS
"""
csName = self.localCfg.getOption(cfgPath("DIRAC", "Configuration", "Name"), "")
if not csName:
error = "Missing %s" % cfgPath("DIRAC", "Configuration", "Name")
if self.exitOnError:
gLogger.error(error)
DIRAC.exit(-1)
return S_ERROR(error)
csCfg = CFG()
csFile = os.path.join(rootPath, "etc", "%s.cfg" % csName)
if os.path.exists(csFile):
csCfg.loadFromFile(csFile)
newCfg = csCfg.mergeWith(cfg) if str(csCfg) else cfg
return newCfg.writeToFile(csFile)
def _removeOptionFromCS(self, path):
"""
Delete options from central CS
"""
cfgClient = CSAPI()
result = cfgClient.downloadCSData()
if not result["OK"]:
return result
result = cfgClient.delOption(path)
if not result["OK"]:
return result
result = cfgClient.commit()
return result
def _removeSectionFromCS(self, path):
"""
Delete setions from central CS
"""
cfgClient = CSAPI()
result = cfgClient.downloadCSData()
if not result["OK"]:
return result
result = cfgClient.delSection(path)
if not result["OK"]:
return result
result = cfgClient.commit()
return result
def _getCentralCfg(self, installCfg):
"""
Create the skeleton of central Cfg for an initial Master CS
"""
# First copy over from installation cfg
centralCfg = CFG()
# DIRAC/Extensions
extensions = self.localCfg.getOption(cfgInstallPath("Extensions"), [])
centralCfg.createNewSection("DIRAC", "")
if extensions:
centralCfg["DIRAC"].addKey("Extensions", ",".join(extensions), "") # pylint: disable=no-member
vo = self.localCfg.getOption(cfgInstallPath("VirtualOrganization"), "")
if vo:
centralCfg["DIRAC"].addKey("VirtualOrganization", vo, "") # pylint: disable=no-member
for section in ["Systems", "Resources", "Resources/Sites", "Operations", "Registry"]:
if installCfg.isSection(section):
centralCfg.createNewSection(section, contents=installCfg[section])
# Now try to add things from the Installation section
# Registry
adminUserName = self.localCfg.getOption(cfgInstallPath("AdminUserName"), "")
adminUserDN = self.localCfg.getOption(cfgInstallPath("AdminUserDN"), "")
adminUserEmail = self.localCfg.getOption(cfgInstallPath("AdminUserEmail"), "")
adminGroupName = self.localCfg.getOption(cfgInstallPath("AdminGroupName"), "dirac_admin")
hostDN = self.localCfg.getOption(cfgInstallPath("HostDN"), "")
defaultGroupName = self.localCfg.getOption(cfgInstallPath("DefaultGroupName"), "dirac_user")
adminGroupProperties = [
ALARMS_MANAGEMENT,
SERVICE_ADMINISTRATOR,
CS_ADMINISTRATOR,
JOB_ADMINISTRATOR,
FULL_DELEGATION,
PROXY_MANAGEMENT,
OPERATOR,
]
defaultGroupProperties = [NORMAL_USER]
defaultHostProperties = [
TRUSTED_HOST,
CS_ADMINISTRATOR,
JOB_ADMINISTRATOR,
FULL_DELEGATION,
PROXY_MANAGEMENT,
OPERATOR,
]
for section in (
cfgPath("Registry"),
cfgPath("Registry", "Users"),
cfgPath("Registry", "Groups"),
cfgPath("Registry", "Hosts"),
):
if not centralCfg.isSection(section):
centralCfg.createNewSection(section)
# pylint: disable=unsubscriptable-object
if adminUserName:
if not (adminUserDN and adminUserEmail):
gLogger.error("AdminUserName is given but DN or Mail is missing it will not be configured")
else:
for section in [
cfgPath("Registry", "Users", adminUserName),
cfgPath("Registry", "Groups", defaultGroupName),
cfgPath("Registry", "Groups", adminGroupName),
]:
if not centralCfg.isSection(section):
centralCfg.createNewSection(section)
if centralCfg["Registry"].existsKey("DefaultGroup"): # pylint: disable=no-member
centralCfg["Registry"].deleteKey("DefaultGroup") # pylint: disable=no-member
centralCfg["Registry"].addKey("DefaultGroup", defaultGroupName, "") # pylint: disable=no-member
if centralCfg["Registry"]["Users"][adminUserName].existsKey("DN"):
centralCfg["Registry"]["Users"][adminUserName].deleteKey("DN")
centralCfg["Registry"]["Users"][adminUserName].addKey("DN", adminUserDN, "")
if centralCfg["Registry"]["Users"][adminUserName].existsKey("Email"):
centralCfg["Registry"]["Users"][adminUserName].deleteKey("Email")
centralCfg["Registry"]["Users"][adminUserName].addKey("Email", adminUserEmail, "")
# Add Admin User to Admin Group and default group
for group in [adminGroupName, defaultGroupName]:
if not centralCfg["Registry"]["Groups"][group].isOption("Users"):
centralCfg["Registry"]["Groups"][group].addKey("Users", "", "")
users = centralCfg["Registry"]["Groups"][group].getOption("Users", [])
if adminUserName not in users:
centralCfg["Registry"]["Groups"][group].appendToOption("Users", ", %s" % adminUserName)
if not centralCfg["Registry"]["Groups"][group].isOption("Properties"):
centralCfg["Registry"]["Groups"][group].addKey("Properties", "", "")
properties = centralCfg["Registry"]["Groups"][adminGroupName].getOption("Properties", [])
for prop in adminGroupProperties:
if prop not in properties:
properties.append(prop)
centralCfg["Registry"]["Groups"][adminGroupName].appendToOption("Properties", ", %s" % prop)
properties = centralCfg["Registry"]["Groups"][defaultGroupName].getOption("Properties", [])
for prop in defaultGroupProperties:
if prop not in properties:
properties.append(prop)
centralCfg["Registry"]["Groups"][defaultGroupName].appendToOption("Properties", ", %s" % prop)
# Add the master Host description
if hostDN:
hostSection = cfgPath("Registry", "Hosts", self.host)
if not centralCfg.isSection(hostSection):
centralCfg.createNewSection(hostSection)
if centralCfg["Registry"]["Hosts"][self.host].existsKey("DN"):
centralCfg["Registry"]["Hosts"][self.host].deleteKey("DN")
centralCfg["Registry"]["Hosts"][self.host].addKey("DN", hostDN, "")
if not centralCfg["Registry"]["Hosts"][self.host].isOption("Properties"):
centralCfg["Registry"]["Hosts"][self.host].addKey("Properties", "", "")
properties = centralCfg["Registry"]["Hosts"][self.host].getOption("Properties", [])
for prop in defaultHostProperties:
if prop not in properties:
properties.append(prop)
centralCfg["Registry"]["Hosts"][self.host].appendToOption("Properties", ", %s" % prop)
# Operations
if adminUserEmail:
operationsCfg = self.__getCfg(cfgPath("Operations", "Defaults", "EMail"), "Production", adminUserEmail)
centralCfg = centralCfg.mergeWith(operationsCfg)
operationsCfg = self.__getCfg(cfgPath("Operations", "Defaults", "EMail"), "Logging", adminUserEmail)
centralCfg = centralCfg.mergeWith(operationsCfg)
# Website
websiteCfg = self.__getCfg(cfgPath("WebApp", "Access"), "upload", "TrustedHost")
centralCfg = centralCfg.mergeWith(websiteCfg)
return centralCfg
def __getCfg(self, section, option="", value=""):
"""
Create a new Cfg with given info
"""
if not section:
return None
cfg = CFG()
sectionList = []
for sect in cfgPathToList(section):
if not sect:
continue
sectionList.append(sect)
cfg.createNewSection(cfgPath(*sectionList))
if not sectionList:
return None
if option and value:
sectionList.append(option)
cfg.setOption(cfgPath(*sectionList), value)
return cfg
def addOptionToDiracCfg(self, option, value):
"""
Add Option to dirac.cfg
"""
optionList = cfgPathToList(option)
optionName = optionList[-1]
section = cfgPath(*optionList[:-1])
cfg = self.__getCfg(section, optionName, value)
if not cfg:
return S_ERROR("Wrong option: %s = %s" % (option, value))
if self._addCfgToDiracCfg(cfg):
return S_OK()
return S_ERROR("Could not merge %s=%s with local configuration" % (option, value))
def removeComponentOptionsFromCS(self, system, component, mySetup=None):
"""
Remove the section with Component options from the CS, if possible
"""
if mySetup is None:
mySetup = self.setup
result = self.monitoringClient.getInstallations(
{"UnInstallationTime": None, "Instance": component}, {"DIRACSystem": system}, {}, True
)
if not result["OK"]:
return result
installations = result["Value"]
instanceOption = cfgPath("DIRAC", "Setups", mySetup, system)
if gConfig:
compInstance = gConfig.getValue(instanceOption, "")
else:
compInstance = self.localCfg.getOption(instanceOption, "")
if len(installations) == 1:
remove = True
removeMain = False
installation = installations[0]
cType = installation["Component"]["Type"]
# Is the component a rename of another module?
isRenamed = installation["Instance"] != installation["Component"]["DIRACModule"]
result = self.monitoringClient.getInstallations(
{"UnInstallationTime": None},
{"DIRACSystem": system, "DIRACModule": installation["Component"]["DIRACModule"]},
{},
True,
)
if not result["OK"]:
return result
installations = result["Value"]
# If the component is not renamed we keep it in the CS if there are any renamed ones
if not isRenamed:
if len(installations) > 1:
remove = False
# If the component is renamed and is the last one, we remove the entry for the main module as well
else:
if len(installations) == 1:
removeMain = True
if remove:
result = self._removeSectionFromCS(
cfgPath("Systems", system, compInstance, installation["Component"]["Type"].title() + "s", component)
)
if not result["OK"]:
return result
if not isRenamed and cType == "service":
result = self._removeOptionFromCS(cfgPath("Systems", system, compInstance, "URLs", component))
if not result["OK"]:
# It is maybe in the FailoverURLs ?
result = self._removeOptionFromCS(
cfgPath("Systems", system, compInstance, "FailoverURLs", component)
)
if not result["OK"]:
return result
if removeMain:
result = self._removeSectionFromCS(
cfgPath(
"Systems",
system,
compInstance,
installation["Component"]["Type"].title() + "s",
installation["Component"]["Module"],
)
)
if not result["OK"]:
return result
if cType == "service":
result = self._removeOptionFromCS(
cfgPath("Systems", system, compInstance, "URLs", installation["Component"]["Module"])
)
if not result["OK"]:
# it is maybe in the FailoverURLs ?
result = self._removeOptionFromCS(
cfgPath(
"Systems", system, compInstance, "FailoverURLs", installation["Component"]["Module"]
)
)
if not result["OK"]:
return result
return S_OK("Successfully removed entries from CS")
return S_OK("Instances of this component still exist. It won't be completely removed")
def addDefaultOptionsToCS(
self,
gConfig_o,
componentType,
systemName,
component,
extensions,
mySetup=None,
specialOptions={},
overwrite=False,
addDefaultOptions=True,
):
"""
Add the section with the component options to the CS
"""
if mySetup is None:
mySetup = self.setup
if gConfig_o:
gConfig_o.forceRefresh()
system = systemName.replace("System", "")
instanceOption = cfgPath("DIRAC", "Setups", mySetup, system)
if gConfig_o:
compInstance = gConfig_o.getValue(instanceOption, "")
else:
compInstance = self.localCfg.getOption(instanceOption, "")
if not compInstance:
return S_ERROR("%s not defined in %s" % (instanceOption, self.cfgFile))
sectionName = _getSectionName(componentType)
# Check if the component CS options exist
addOptions = True
componentSection = cfgPath("Systems", system, compInstance, sectionName, component)
if not overwrite:
if gConfig_o:
result = gConfig_o.getOptions(componentSection)
if result["OK"]:
addOptions = False
if not addOptions:
return S_OK("Component options already exist")
# Add the component options now
result = self.getComponentCfg(
componentType, system, component, compInstance, extensions, specialOptions, addDefaultOptions
)
if not result["OK"]:
return result
compCfg = result["Value"]
gLogger.notice("Adding to CS", "%s %s/%s" % (componentType, system, component))
resultAddToCFG = self._addCfgToCS(compCfg)
if componentType == "executor":
# Is it a container ?
execList = compCfg.getOption("%s/Load" % componentSection, [])
for element in execList:
result = self.addDefaultOptionsToCS(
gConfig_o, componentType, systemName, element, extensions, self.setup, {}, overwrite
)
if not result["OK"]:
gLogger.warn("Can't add to default CS", result["Message"])
resultAddToCFG.setdefault("Modules", {})
resultAddToCFG["Modules"][element] = result["OK"]
return resultAddToCFG
def addDefaultOptionsToComponentCfg(self, componentType, systemName, component, extensions):
"""
Add default component options local component cfg
"""
system = systemName.replace("System", "")
instanceOption = cfgPath("DIRAC", "Setups", self.setup, system)
compInstance = self.localCfg.getOption(instanceOption, "")
if not compInstance:
return S_ERROR("%s not defined in %s" % (instanceOption, self.cfgFile))
# Add the component options now
result = self.getComponentCfg(componentType, system, component, compInstance, extensions)
if not result["OK"]:
return result
compCfg = result["Value"]
compCfgFile = os.path.join(rootPath, "etc", "%s_%s.cfg" % (system, component))
if compCfg.writeToFile(compCfgFile): # this returns a True/False
return S_OK()
return S_ERROR()
def addCfgToComponentCfg(self, componentType, systemName, component, cfg):
"""
Add some extra configuration to the local component cfg
"""
sectionName = _getSectionName(componentType)
if not cfg:
return S_OK()
system = systemName.replace("System", "")
instanceOption = cfgPath("DIRAC", "Setups", self.setup, system)
compInstance = self.localCfg.getOption(instanceOption, "")
if not compInstance:
return S_ERROR("%s not defined in %s" % (instanceOption, self.cfgFile))
compCfgFile = os.path.join(rootPath, "etc", "%s_%s.cfg" % (system, component))
compCfg = CFG()
if os.path.exists(compCfgFile):
compCfg.loadFromFile(compCfgFile)
sectionPath = cfgPath("Systems", system, compInstance, sectionName)
newCfg = self.__getCfg(sectionPath)
newCfg.createNewSection(cfgPath(sectionPath, component), "Added by ComponentInstaller", cfg)
if newCfg.writeToFile(compCfgFile):
return S_OK(compCfgFile)
error = "Can not write %s" % compCfgFile
gLogger.error(error)
return S_ERROR(error)
def getComponentCfg(
self, componentType, system, component, compInstance, extensions, specialOptions={}, addDefaultOptions=True
):
"""
Get the CFG object of the component configuration
"""
sectionName = _getSectionName(componentType)
componentModule = specialOptions.get("Module", component)
compCfg = CFG()
if addDefaultOptions:
for ext in extensions:
cfgTemplateModule = "%s.%sSystem" % (ext, system)
try:
cfgTemplate = importlib_resources.read_text(cfgTemplateModule, "ConfigTemplate.cfg")
except (ImportError, OSError):
continue
gLogger.notice("Loading configuration template from", cfgTemplateModule)
loadCfg = CFG()
loadCfg.loadFromBuffer(cfgTemplate)
compCfg = loadCfg.mergeWith(compCfg)
compPath = cfgPath(sectionName, componentModule)
if not compCfg.isSection(compPath):
error = "Can not find %s in template" % compPath
gLogger.error(error)
if self.exitOnError:
DIRAC.exit(-1)
return S_ERROR(error)
compCfg = compCfg[sectionName][componentModule] # pylint: disable=unsubscriptable-object
# Delete Dependencies section if any
compCfg.deleteKey("Dependencies")
sectionPath = cfgPath("Systems", system, compInstance, sectionName)
cfg = self.__getCfg(sectionPath)
cfg.createNewSection(cfgPath(sectionPath, component), "", compCfg)
for option, value in specialOptions.items():
cfg.setOption(cfgPath(sectionPath, component, option), value)
# Add the service URL
if componentType == "service":
port = compCfg.getOption("Port", 0)
protocol = compCfg.getOption("Protocol", "dips")
if (port or protocol == "https") and self.host:
urlsPath = cfgPath("Systems", system, compInstance, "URLs")
cfg.createNewSection(urlsPath)
failoverUrlsPath = cfgPath("Systems", system, compInstance, "FailoverURLs")
cfg.createNewSection(failoverUrlsPath)
if protocol == "https":
tornadoPort = gConfig.getValue(
"/Systems/Tornado/%s/Port" % PathFinder.getSystemInstance("Tornado"),
8443,
)
cfg.setOption(
# Strip "Tornado" from the beginning of component name if present
cfgPath(urlsPath, component[len("Tornado") if component.startswith("Tornado") else 0 :]),
"https://%s:%s/%s/%s" % (self.host, tornadoPort, system, component),
)
else:
cfg.setOption(
cfgPath(urlsPath, component), "dips://%s:%d/%s/%s" % (self.host, port, system, component)
)
return S_OK(cfg)
def addDatabaseOptionsToCS(self, gConfig_o, systemName, dbName, mySetup=None, overwrite=False):
"""
Add the section with the database options to the CS
"""
if mySetup is None:
mySetup = self.setup
if gConfig_o:
gConfig_o.forceRefresh()
system = systemName.replace("System", "")
instanceOption = cfgPath("DIRAC", "Setups", mySetup, system)
if gConfig_o:
compInstance = gConfig_o.getValue(instanceOption, "")
else:
compInstance = self.localCfg.getOption(instanceOption, "")
if not compInstance:
return S_ERROR("%s not defined in %s" % (instanceOption, self.cfgFile))
# Check if the component CS options exist
addOptions = True
if not overwrite:
databasePath = cfgPath("Systems", system, compInstance, "Databases", dbName)
result = gConfig_o.getOptions(databasePath)
if result["OK"]:
addOptions = False
if not addOptions:
return S_OK("Database options already exist")
# Add the component options now
result = self.getDatabaseCfg(system, dbName, compInstance)
if not result["OK"]:
return result
databaseCfg = result["Value"]
gLogger.notice("Adding to CS", "%s/%s" % (system, dbName))
return self._addCfgToCS(databaseCfg)
def removeDatabaseOptionsFromCS(self, gConfig_o, system, dbName, mySetup=None):
"""
Remove the section with database options from the CS, if possible
"""
if mySetup is None:
mySetup = self.setup
result = self.monitoringClient.installationExists(
{"UnInstallationTime": None}, {"DIRACSystem": system, "Type": "DB", "DIRACModule": dbName}, {}
)
if not result["OK"]:
return result
exists = result["Value"]
instanceOption = cfgPath("DIRAC", "Setups", mySetup, system)
if gConfig_o:
compInstance = gConfig_o.getValue(instanceOption, "")
else:
compInstance = self.localCfg.getOption(instanceOption, "")
if not exists:
result = self._removeSectionFromCS(cfgPath("Systems", system, compInstance, "Databases", dbName))
if not result["OK"]:
return result
return S_OK("Successfully removed entries from CS")
def getDatabaseCfg(self, system, dbName, compInstance):
"""
Get the CFG object of the database configuration
"""
databasePath = cfgPath("Systems", system, compInstance, "Databases", dbName)
cfg = self.__getCfg(databasePath, "DBName", dbName)
cfg.setOption(cfgPath(databasePath, "Host"), self.mysqlHost)
cfg.setOption(cfgPath(databasePath, "Port"), self.mysqlPort)
return S_OK(cfg)
def addSystemInstance(self, systemName, compInstance, mySetup=None, myCfg=False):
"""
Add a new system self.instance to dirac.cfg and CS
"""
if mySetup is None:
mySetup = self.setup
system = systemName.replace("System", "")
gLogger.notice(
"Adding %s system as %s self.instance for %s self.setup to dirac.cfg and CS"
% (system, compInstance, mySetup)
)
cfg = self.__getCfg(cfgPath("DIRAC", "Setups", mySetup), system, compInstance)
if myCfg:
if not self._addCfgToDiracCfg(cfg):
return S_ERROR("Failed to add system self.instance to dirac.cfg")
return self._addCfgToCS(cfg)
def printStartupStatus(self, rDict):
"""
Print in nice format the return dictionary from self.getStartupComponentStatus
(also returned by self.runsvctrlComponent)
"""
fields = ["Name", "Runit", "Uptime", "PID"]
records = []
try:
for comp in rDict:
records.append([comp, rDict[comp]["RunitStatus"], rDict[comp]["Timeup"], str(rDict[comp]["PID"])])
printTable(fields, records)
except Exception as x:
print("Exception while gathering data for printing: %s" % str(x))
return S_OK()
def printOverallStatus(self, rDict):
"""
Print in nice format the return dictionary from self.getOverallStatus
"""
fields = ["System", "Name", "Type", "Setup", "Installed", "Runit", "Uptime", "PID"]
records = []
try:
for compType in rDict:
for system in rDict[compType]:
for component in rDict[compType][system]:
record = [system, component, compType.lower()[:-1]]
if rDict[compType][system][component]["Setup"]:
record.append("SetUp")
else:
record.append("NotSetUp")
if rDict[compType][system][component]["Installed"]:
record.append("Installed")
else:
record.append("NotInstalled")
record.append(str(rDict[compType][system][component]["RunitStatus"]))
record.append(str(rDict[compType][system][component]["Timeup"]))
record.append(str(rDict[compType][system][component]["PID"]))
records.append(record)
printTable(fields, records)
except Exception as x:
print("Exception while gathering data for printing: %s" % str(x))
return S_OK()
@deprecated("Use DIRAC.Core.Utilities.Extensions.findSystems instead")
def getAvailableSystems(self, extensions):
"""Get the list of all systems (in all given extensions) locally available"""
return list(findSystems(extensions))
def getSoftwareComponents(self, extensions):
"""
Get the list of all the components (services, agents, executors) for which the software
is installed on the system
"""
# The Gateway does not need a handler
services = defaultdict(list, {"Framework": ["Gateway"]})
agents = defaultdict(list)
executors = defaultdict(list)
remainders = defaultdict(lambda: defaultdict(list))
# Components other than services, agents and executors
remainingTypes = set(self.componentTypes) - {"service", "agent", "executor"}
result = self.resultIndexes(remainingTypes)
if not result["OK"]:
return result
resultIndexes = result["Value"]
for extension in extensions:
for system, agent in findAgents(extension):
loader = pkgutil.get_loader(".".join([extension, system, "Agent", agent]))
with io.open(loader.get_filename(), "rt") as fp:
body = fp.read()
if "AgentModule" in body or "OptimizerModule" in body:
agents[system.replace("System", "")].append(agent)
for system, service in findServices(extension):
if system == "Configuration" and service == "ConfigurationHandler":
service = "ServerHandler"
services[system.replace("System", "")].append(service.replace("Handler", ""))
for system, executor in findExecutors(extension):
loader = pkgutil.get_loader(".".join([extension, system, "Executor", executor]))
with io.open(loader.get_filename(), "rt") as fp:
body = fp.read()
if "OptimizerExecutor" in body:
executors[system.replace("System", "")].append(executor)
# Rest of component types
for cType in remainingTypes:
for system, remainder in findModules(extension, cType.title()):
remainders[cType][system.replace("System", "")].append(remainder)
resultDict = {resultIndexes[cType]: dict(remainders[cType]) for cType in remainingTypes}
resultDict["Services"] = dict(services)
resultDict["Agents"] = dict(agents)
resultDict["Executors"] = dict(executors)
return S_OK(resultDict)
def getInstalledComponents(self):
"""
Get the list of all the components (services, agents, executors)
installed on the system in the runit directory
"""
result = self.resultIndexes(self.componentTypes)
if not result["OK"]:
return result
resultIndexes = result["Value"]
resultDict = defaultdict(lambda: defaultdict(list))
for system in os.listdir(self.runitDir):
systemDir = os.path.join(self.runitDir, system)
for component in os.listdir(systemDir):
runFile = os.path.join(systemDir, component, "run")
try:
with io.open(runFile, "rt") as rFile:
body = rFile.read()
except IOError:
pass
else:
for cType in self.componentTypes:
if "dirac-%s" % cType in body or (cType.lower() == "service" and "tornado-start-all" in body):
resultDict[cType][system].append(component)
return S_OK({resultIndexes[cType]: dict(resultDict[cType]) for cType in self.componentTypes})
def getSetupComponents(self):
"""
Get the list of all the components (services, agents, executors)
set up for running with runsvdir in startup directory
"""
if not os.path.isdir(self.startDir):
return S_ERROR("Startup Directory does not exit: %s" % self.startDir)
result = self.resultIndexes(self.componentTypes)
if not result["OK"]:
return result
resultIndexes = result["Value"]
resultDict = defaultdict(lambda: defaultdict(list))
for component in os.listdir(self.startDir):
runFile = os.path.join(self.startDir, component, "run")
try:
with io.open(runFile, "rt") as rfile:
body = rfile.read()
except IOError:
pass
else:
for cType in self.componentTypes:
if "dirac-%s" % cType in body or (cType.lower() == "service" and "tornado-start-all" in body):
system, compT = component.split("_", 1)
resultDict[cType][system].append(compT)
return S_OK({resultIndexes[cType]: dict(resultDict[cType]) for cType in self.componentTypes})
def getStartupComponentStatus(self, componentTupleList):
"""
Get the list of all the components (services, agents, executors)
set up for running with runsvdir in startup directory
"""
try:
if componentTupleList:
cList = []
for componentTuple in componentTupleList:
cList.extend(glob.glob(os.path.join(self.startDir, "_".join(componentTuple))))
else:
cList = glob.glob(os.path.join(self.startDir, "*"))
except Exception:
error = "Failed to parse List of Components"
gLogger.exception(error)
if self.exitOnError:
DIRAC.exit(-1)
return S_ERROR(error)
result = self.execCommand(0, ["runsvstat"] + cList)
if not result["OK"]:
return result
output = result["Value"][1].strip().split("\n")
componentDict = {}
for line in output:
if not line:
continue
cname, routput = line.split(":")
cname = cname.replace("%s/" % self.startDir, "")
run = False
reResult = re.search("^ run", routput)
if reResult:
run = True
down = False
reResult = re.search("^ down", routput)
if reResult:
down = True
reResult = re.search("([0-9]+) seconds", routput)
timeup = 0
if reResult:
timeup = reResult.group(1)
reResult = re.search("pid ([0-9]+)", routput)
pid = 0
if reResult:
pid = reResult.group(1)
runsv = "Not running"
if run or down:
runsv = "Running"
reResult = re.search("runsv not running", routput)
if reResult:
runsv = "Not running"
runDict = {}
runDict["CPU"] = -1
runDict["MEM"] = -1
runDict["VSZ"] = -1
runDict["RSS"] = -1
if pid: # check the process CPU usage and memory
# PID %CPU %MEM VSZ
result = self.execCommand(0, ["ps", "-p", pid, "u"])
if result["OK"] and result["Value"]:
stats = result["Value"][1]
values = re.findall(r"\d*\.\d+|\d+", stats)
if values:
runDict["CPU"] = values[1]
runDict["MEM"] = values[2]
runDict["VSZ"] = values[3]
runDict["RSS"] = values[4]
runDict["Timeup"] = timeup
runDict["PID"] = pid
runDict["RunitStatus"] = "Unknown"
if run:
runDict["RunitStatus"] = "Run"
if down:
runDict["RunitStatus"] = "Down"
if runsv == "Not running":
runDict["RunitStatus"] = "NoRunitControl"
componentDict[cname] = runDict
return S_OK(componentDict)
def getComponentModule(self, system, component, compType):
"""
Get the component software module
"""
self.setup = CSGlobals.getSetup()
self.instance = gConfig.getValue(cfgPath("DIRAC", "Setups", self.setup, system), "")
if not self.instance:
return S_OK(component)
module = gConfig.getValue(cfgPath("Systems", system, self.instance, compType, component, "Module"), "")
if not module:
module = component
return S_OK(module)
def getOverallStatus(self, extensions):
"""
Get the list of all the components (services, agents, executors)
set up for running with runsvdir in startup directory
"""
result = self.getSoftwareComponents(extensions)
if not result["OK"]:
return result
softDict = result["Value"]
result = self.getSetupComponents()
if not result["OK"]:
return result
setupDict = result["Value"]
result = self.getInstalledComponents()
if not result["OK"]:
return result
installedDict = result["Value"]
result = self.getStartupComponentStatus([])
if not result["OK"]:
return result
runitDict = result["Value"]
# Collect the info now
result = self.resultIndexes(self.componentTypes)
if not result["OK"]:
return result
resultIndexes = result["Value"]
resultDict = defaultdict(lambda: defaultdict(dict))
for cType in resultIndexes.values():
if "Services" in softDict:
for system in softDict[cType]:
for component in softDict[cType][system]:
if system == component == "Configuration":
# Fix to avoid missing CS due to different between Service name and Handler name
component = "Server"
resultDict[cType][system][component] = _makeComponentDict(
component, setupDict, installedDict, cType, system, runitDict
)
# Installed components can be not the same as in the software list
if "Services" in installedDict:
for system in installedDict[cType]:
for component in installedDict[cType][system]:
if component in resultDict.get(cType, {}).get(system, {}):
continue
resultDict[cType][system][component] = _makeComponentDict(
component, setupDict, installedDict, cType, system, runitDict
)
return S_OK({k: dict(v) for k, v in resultDict.items()})
def checkComponentModule(self, componentType, system, module):
"""
Check existence of the given module
and if it inherits from the proper class
"""
if componentType == "agent":
loader = ModuleLoader("Agent", PathFinder.getAgentSection, AgentModule)
elif componentType == "service":
loader = ModuleLoader("Service", PathFinder.getServiceSection, RequestHandler, moduleSuffix="Handler")
elif componentType == "executor":
loader = ModuleLoader("Executor", PathFinder.getExecutorSection, ExecutorModule)
else:
return S_ERROR("Unknown component type %s" % componentType)
return loader.loadModule("%s/%s" % (system, module))
def checkComponentSoftware(self, componentType, system, component, extensions):
"""
Check the component software
"""
result = self.getSoftwareComponents(extensions)
if not result["OK"]:
return result
softComp = result["Value"]
try:
softDict = softComp[_getSectionName(componentType)]
except KeyError:
return S_ERROR("Unknown component type %s" % componentType)
if system in softDict and component in softDict[system]:
return S_OK()
return S_ERROR("Unknown Component %s/%s" % (system, component))
def runsvctrlComponent(self, system, component, mode):
"""
Execute runsvctrl and check status of the specified component
"""
if mode not in ["u", "d", "o", "p", "c", "h", "a", "i", "q", "1", "2", "t", "k", "x", "e"]:
return S_ERROR('Unknown runsvctrl mode "%s"' % mode)
startCompDirs = glob.glob(os.path.join(self.startDir, "%s_%s" % (system, component)))
# Make sure that the Configuration server restarts first and the SystemAdmin restarts last
tmpList = list(startCompDirs)
for comp in tmpList:
if "Framework_SystemAdministrator" in comp:
startCompDirs.append(startCompDirs.pop(startCompDirs.index(comp)))
if "Configuration_Server" in comp:
startCompDirs.insert(0, startCompDirs.pop(startCompDirs.index(comp)))
startCompList = [[k] for k in startCompDirs]
for startComp in startCompList:
result = self.execCommand(0, ["runsvctrl", mode] + startComp)
if not result["OK"]:
return result
time.sleep(2)
# Check the runsv status
if system == "*" or component == "*":
time.sleep(10)
# Final check
result = self.getStartupComponentStatus([(system, component)])
if not result["OK"]:
gLogger.error("Failed to start the component %s %s" % (system, component))
return S_ERROR("Failed to start the component")
return result
def getLogTail(self, system, component, length=100):
"""
Get the tail of the component log file
"""
retDict = {}
for startCompDir in glob.glob(os.path.join(self.startDir, "%s_%s" % (system, component))):
compName = os.path.basename(startCompDir)
logFileName = os.path.join(startCompDir, "log", "current")
if not os.path.exists(logFileName):
retDict[compName] = "No log file found"
else:
with io.open(logFileName, "rt") as logFile:
lines = [line.strip() for line in logFile.readlines()]
retDict[compName] = "\n".join(lines[-length:])
return S_OK(retDict)
def setupSite(self, scriptCfg, cfg=None):
"""
Setup a new site using the options defined
"""
# First we need to find out what needs to be installed
# by default use dirac.cfg, but if a cfg is given use it and
# merge it into the dirac.cfg
diracCfg = CFG()
installCfg = None
if cfg:
try:
installCfg = CFG()
installCfg.loadFromFile(cfg)
for section in ["DIRAC", "LocalSite", cfgInstallSection]:
if installCfg.isSection(section):
diracCfg.createNewSection(section, contents=installCfg[section])
if self.instancePath != self.basePath:
if not diracCfg.isSection("LocalSite"):
diracCfg.createNewSection("LocalSite")
diracCfg.setOption(cfgPath("LocalSite", "InstancePath"), self.instancePath)
self._addCfgToDiracCfg(diracCfg)
except Exception: # pylint: disable=broad-except
error = "Failed to load %s" % cfg
gLogger.exception(error)
if self.exitOnError:
DIRAC.exit(-1)
return S_ERROR(error)
# Now get the necessary info from self.localCfg
setupSystems = self.localCfg.getOption(cfgInstallPath("Systems"), ["Configuration", "Framework"])
setupDatabases = self.localCfg.getOption(cfgInstallPath("Databases"), [])
setupServices = [k.split("/") for k in self.localCfg.getOption(cfgInstallPath("Services"), [])]
setupAgents = [k.split("/") for k in self.localCfg.getOption(cfgInstallPath("Agents"), [])]
setupExecutors = [k.split("/") for k in self.localCfg.getOption(cfgInstallPath("Executors"), [])]
setupWeb = self.localCfg.getOption(cfgInstallPath("WebPortal"), False)
setupConfigurationMaster = self.localCfg.getOption(cfgInstallPath("ConfigurationMaster"), False)
setupPrivateConfiguration = self.localCfg.getOption(cfgInstallPath("PrivateConfiguration"), False)
setupConfigurationName = self.localCfg.getOption(cfgInstallPath("ConfigurationName"), self.setup)
setupAddConfiguration = self.localCfg.getOption(cfgInstallPath("AddConfiguration"), True)
for serviceTuple in setupServices:
if len(serviceTuple) != 2:
error = "Wrong service specification: system/service"
if self.exitOnError:
gLogger.error(error)
DIRAC.exit(-1)
return S_ERROR(error)
serviceSysInstance = serviceTuple[0]
if serviceSysInstance not in setupSystems:
setupSystems.append(serviceSysInstance)
for agentTuple in setupAgents:
if len(agentTuple) != 2:
error = "Wrong agent specification: system/agent"
if self.exitOnError:
gLogger.error(error)
DIRAC.exit(-1)
return S_ERROR(error)
agentSysInstance = agentTuple[0]
if agentSysInstance not in setupSystems:
setupSystems.append(agentSysInstance)
for executorTuple in setupExecutors:
if len(executorTuple) != 2:
error = "Wrong executor specification: system/executor"
if self.exitOnError:
gLogger.error(error)
DIRAC.exit(-1)
return S_ERROR(error)
executorSysInstance = executorTuple[0]
if executorSysInstance not in setupSystems:
setupSystems.append(executorSysInstance)
# And to find out the available extensions
extensions = extensionsByPriority()
# Make sure the necessary directories are there
if self.basePath != self.instancePath:
mkDir(self.instancePath)
instanceEtcDir = os.path.join(self.instancePath, "etc")
etcDir = os.path.dirname(self.cfgFile)
if not os.path.exists(instanceEtcDir):
mkLink(etcDir, instanceEtcDir)
if os.path.realpath(instanceEtcDir) != os.path.realpath(etcDir):
error = "Instance etc (%s) is not the same as DIRAC etc (%s)" % (instanceEtcDir, etcDir)
if self.exitOnError:
gLogger.error(error)
DIRAC.exit(-1)
return S_ERROR(error)
# if any server or agent needs to be install we need the startup directory and runsvdir running
if setupServices or setupAgents or setupExecutors or setupWeb:
if not os.path.exists(self.startDir):
mkDir(self.startDir)
# And need to make sure runsvdir is running
result = self.execCommand(0, ["ps", "-ef"])
if not result["OK"]:
if self.exitOnError:
gLogger.error("Failed to verify runsvdir running", result["Message"])
DIRAC.exit(-1)
return S_ERROR(result["Message"])
processList = result["Value"][1].split("\n")
# it is pointless to look for more detailed command.
# Nobody uses runsvdir.... so if it is there, it is us.
if all("runsvdir" not in process for process in processList):
gLogger.notice("Starting runsvdir ...")
with io.open(os.devnull, "w") as devnull:
subprocess.Popen(
["nohup", "runsvdir", self.startDir, "log: DIRAC runsv"],
stdout=devnull,
stderr=devnull,
universal_newlines=True,
)
if ["Configuration", "Server"] in setupServices and setupConfigurationMaster:
# This server hosts the Master of the CS
from DIRAC.ConfigurationSystem.Client.ConfigurationData import gConfigurationData
gLogger.notice("Installing Master Configuration Server")
cfg = self.__getCfg(cfgPath("DIRAC", "Setups", self.setup), "Configuration", self.instance)
self._addCfgToDiracCfg(cfg)
cfg = self.__getCfg(cfgPath("DIRAC", "Configuration"), "Master", "yes")
cfg.setOption(cfgPath("DIRAC", "Configuration", "Name"), setupConfigurationName)
serversCfgPath = cfgPath("DIRAC", "Configuration", "Servers")
if not self.localCfg.getOption(serversCfgPath, []):
serverUrl = "dips://%s:9135/Configuration/Server" % self.host
cfg.setOption(serversCfgPath, serverUrl)
gConfigurationData.setOptionInCFG(serversCfgPath, serverUrl)
instanceOptionPath = cfgPath("DIRAC", "Setups", self.setup)
instanceCfg = self.__getCfg(instanceOptionPath, "Configuration", self.instance)
cfg = cfg.mergeWith(instanceCfg)
self._addCfgToDiracCfg(cfg)
result = self.getComponentCfg(
"service", "Configuration", "Server", self.instance, extensions, addDefaultOptions=True
)
if not result["OK"]:
if self.exitOnError:
DIRAC.exit(-1)
return result
compCfg = result["Value"]
cfg = cfg.mergeWith(compCfg)
gConfigurationData.mergeWithLocal(cfg)
self.addDefaultOptionsToComponentCfg("service", "Configuration", "Server", ["DIRAC"])
centralCfg = self._getCentralCfg(installCfg or self.localCfg)
self._addCfgToLocalCS(centralCfg)
self.setupComponent("service", "Configuration", "Server", ["DIRAC"], checkModule=False)
self.runsvctrlComponent("Configuration", "Server", "t")
while ["Configuration", "Server"] in setupServices:
setupServices.remove(["Configuration", "Server"])
time.sleep(5)
# Now need to check if there is valid CS to register the info
result = scriptCfg.enableCS()
if not result["OK"]:
if self.exitOnError:
DIRAC.exit(-1)
return result
cfgClient = CSAPI()
if not cfgClient.initialize():
error = "Configuration Server not defined"
if self.exitOnError:
gLogger.error(error)
DIRAC.exit(-1)
return S_ERROR(error)
# We need to make sure components are connecting to the Master CS, that is the only one being update
localServers = self.localCfg.getOption(cfgPath("DIRAC", "Configuration", "Servers"))
masterServer = gConfig.getValue(cfgPath("DIRAC", "Configuration", "MasterServer"), "")
initialCfg = self.__getCfg(cfgPath("DIRAC", "Configuration"), "Servers", localServers)
masterCfg = self.__getCfg(cfgPath("DIRAC", "Configuration"), "Servers", masterServer)
self._addCfgToDiracCfg(masterCfg)
# 1.- Setup the instances in the CS
# If the Configuration Server used is not the Master, it can take some time for this
# info to be propagated, this may cause the later self.setup to fail
if setupAddConfiguration:
gLogger.notice("Registering System instances")
for system in setupSystems:
self.addSystemInstance(system, self.instance, self.setup, True)
for system, service in setupServices:
if not self.addDefaultOptionsToCS(None, "service", system, service, extensions, overwrite=True)["OK"]:
# If we are not allowed to write to the central CS, add the configuration to the local file
gLogger.warn(
"Can't write to central CS, so adding to the specific component CFG",
"for %s : %s" % (system, service),
)
res = self.addDefaultOptionsToComponentCfg("service", system, service, extensions)
if not res["OK"]:
gLogger.warn("Can't write to the specific component CFG")
for system, agent in setupAgents:
if not self.addDefaultOptionsToCS(None, "agent", system, agent, extensions, overwrite=True)["OK"]:
# If we are not allowed to write to the central CS, add the configuration to the local file
gLogger.warn("Can't write to central CS, so adding to the specific component CFG")
res = self.addDefaultOptionsToComponentCfg("agent", system, agent, extensions)
if not res["OK"]:
gLogger.warn("Can't write to the specific component CFG", "for %s : %s" % (system, agent))
for system, executor in setupExecutors:
if not self.addDefaultOptionsToCS(None, "executor", system, executor, extensions, overwrite=True)["OK"]:
# If we are not allowed to write to the central CS, add the configuration to the local file
gLogger.warn("Can't write to central CS, so adding to the specific component CFG")
res = self.addDefaultOptionsToComponentCfg("executor", system, executor, extensions)
if not res["OK"]:
gLogger.warn("Can't write to the specific component CFG", "for %s : %s" % (system, executor))
else:
gLogger.warn("Configuration parameters definition is not requested")
if ["Configuration", "Server"] in setupServices and setupPrivateConfiguration:
cfg = self.__getCfg(cfgPath("DIRAC", "Configuration"), "AutoPublish", "no")
self._addCfgToDiracCfg(cfg)
# 2.- Install requested Databases
# if MySQL is not installed locally, we assume a host is given
if setupDatabases:
result = self.getDatabases()
if not result["OK"]:
if self.exitOnError:
gLogger.error("Failed to get databases", result["Message"])
DIRAC.exit(-1)
return result
installedDatabases = result["Value"]
result = self.getAvailableDatabases()
gLogger.debug("Available databases", result)
if not result["OK"]:
return result
dbDict = result["Value"]
for dbName in setupDatabases:
gLogger.verbose("Setting up database", dbName)
if dbName not in installedDatabases:
result = self.installDatabase(dbName)
if not result["OK"]:
gLogger.error(result["Message"])
DIRAC.exit(-1)
extension, system = result["Value"]
gLogger.notice("Database %s from %s/%s installed" % (dbName, extension, system))
else:
gLogger.notice("Database %s already installed" % dbName)
dbSystem = dbDict[dbName]["System"]
result = self.addDatabaseOptionsToCS(None, dbSystem, dbName, overwrite=True)
if not result["OK"]:
gLogger.error("Database %s CS registration failed: %s" % (dbName, result["Message"]))
if self.mysqlPassword and not self._addMySQLToDiracCfg():
error = "Failed to add MySQL user/password to local configuration"
if self.exitOnError:
gLogger.error(error)
DIRAC.exit(-1)
return S_ERROR(error)
if self.noSQLHost and not self._addNoSQLToDiracCfg():
error = "Failed to add NoSQL connection details to local configuration"
if self.exitOnError:
gLogger.error(error)
DIRAC.exit(-1)
return S_ERROR(error)
# 3.- Then installed requested services
for system, service in setupServices:
result = self.setupComponent("service", system, service, extensions)
if not result["OK"]:
gLogger.error(result["Message"])
continue
# 4.- Now the agents
for system, agent in setupAgents:
result = self.setupComponent("agent", system, agent, extensions)
if not result["OK"]:
gLogger.error(result["Message"])
continue
# 5.- Now the executors
for system, executor in setupExecutors:
result = self.setupComponent("executor", system, executor, extensions)
if not result["OK"]:
gLogger.error(result["Message"])
continue
# 6.- And finally the Portal
if setupWeb:
self.setupPortal()
if localServers != masterServer:
self._addCfgToDiracCfg(initialCfg)
for system, service in setupServices:
self.runsvctrlComponent(system, service, "t")
for system, agent in setupAgents:
self.runsvctrlComponent(system, agent, "t")
for system, executor in setupExecutors:
self.runsvctrlComponent(system, executor, "t")
return S_OK()
def _createRunitLog(self, runitCompDir):
self.controlDir = os.path.join(runitCompDir, "control")
mkDir(self.controlDir)
logDir = os.path.join(runitCompDir, "log")
mkDir(logDir)
logConfigFile = os.path.join(logDir, "config")
with io.open(logConfigFile, "w") as fd:
fd.write(
u"""s10000000
n20
"""
)
logRunFile = os.path.join(logDir, "run")
with io.open(logRunFile, "w") as fd:
fd.write(
u"""#!/bin/bash
rcfile=%(bashrc)s
[[ -e $rcfile ]] && source ${rcfile}
#
exec svlogd .
"""
% {"bashrc": os.path.join(self.instancePath, "bashrc")}
)
os.chmod(logRunFile, self.gDefaultPerms)
def installComponent(self, componentType, system, component, extensions, componentModule="", checkModule=True):
"""
Install runit directory for the specified component
"""
# Check if the component is already installed
runitCompDir = os.path.join(self.runitDir, system, component)
if os.path.exists(runitCompDir):
msg = "%s %s_%s already installed" % (componentType, system, component)
gLogger.notice(msg)
return S_OK(runitCompDir)
# Check that the software for the component is installed
# Any "Load" or "Module" option in the configuration defining what modules the given "component"
# needs to load will be taken care of by self.checkComponentModule.
if checkModule:
cModule = componentModule or component
result = self.checkComponentModule(componentType, system, cModule)
if (
not result["OK"]
and not self.checkComponentSoftware(componentType, system, cModule, extensions)["OK"]
and componentType != "executor"
):
error = "Software for %s %s/%s is not installed" % (componentType, system, component)
if self.exitOnError:
gLogger.error(error)
DIRAC.exit(-1)
return S_ERROR(error)
gLogger.notice("Installing %s %s/%s" % (componentType, system, component))
# Retrieve bash variables to be set
result = gConfig.getOption("DIRAC/Setups/%s/%s" % (CSGlobals.getSetup(), system))
if not result["OK"]:
return result
self.instance = result["Value"]
specialOptions = {}
if componentModule:
specialOptions["Module"] = componentModule
result = self.getComponentCfg(
componentType, system, component, self.instance, extensions, specialOptions=specialOptions
)
if not result["OK"]:
return result
compCfg = result["Value"]
section = _getSectionName(componentType)
bashVars = ""
if compCfg.isSection("Systems/%s/%s/%s/%s/Environment" % (system, self.instance, section, component)):
dictionary = compCfg.getAsDict()
bashSection = dictionary["Systems"][system][self.instance][section][component]["BashVariables"]
for var in bashSection:
bashVars = "%s\nexport %s=%s" % (bashVars, var, bashSection[var])
# Now do the actual installation
try:
componentCfg = os.path.join(self.linkedRootPath, "etc", "%s_%s.cfg" % (system, component))
if not os.path.exists(componentCfg):
io.open(componentCfg, "w").close()
self._createRunitLog(runitCompDir)
runFile = os.path.join(runitCompDir, "run")
with io.open(runFile, "w") as fd:
fd.write(
u"""#!/bin/bash
rcfile=%(bashrc)s
[[ -e $rcfile ]] && source ${rcfile}
#
exec 2>&1
#
[[ "%(componentType)s" = "agent" ]] && renice 20 -p $$
#%(bashVariables)s
#
exec dirac-%(componentType)s %(system)s/%(component)s --cfg %(componentCfg)s < /dev/null
"""
% {
"bashrc": os.path.join(self.instancePath, "bashrc"),
"bashVariables": bashVars,
"componentType": componentType.replace("-", "_"),
"system": system,
"component": component,
"componentCfg": componentCfg,
}
)
os.chmod(runFile, self.gDefaultPerms)
cTypeLower = componentType.lower()
if cTypeLower == "agent":
# This is, e.g., /opt/dirac/runit/WorkfloadManagementSystem/Matcher/control/t
stopFile = os.path.join(runitCompDir, "control", "t")
# This is, e.g., /opt/dirac/control/WorkfloadManagementSystem/Matcher/
controlDir = self.runitDir.replace("runit", "control")
with io.open(stopFile, "w") as fd:
fd.write(
u"""#!/bin/bash
echo %(controlDir)s/%(system)s/%(component)s/stop_%(type)s
touch %(controlDir)s/%(system)s/%(component)s/stop_%(type)s
"""
% {"controlDir": controlDir, "system": system, "component": component, "type": cTypeLower}
)
os.chmod(stopFile, self.gDefaultPerms)
except Exception:
error = "Failed to prepare self.setup for %s %s/%s" % (componentType, system, component)
gLogger.exception(error)
if self.exitOnError:
DIRAC.exit(-1)
return S_ERROR(error)
result = self.execCommand(5, [runFile])
gLogger.notice(result["Value"][1])
return S_OK(runitCompDir)
def setupComponent(self, componentType, system, component, extensions, componentModule="", checkModule=True):
"""
Install and create link in startup
"""
result = self.installComponent(componentType, system, component, extensions, componentModule, checkModule)
if not result["OK"]:
return result
# Create the startup entry now
runitCompDir = result["Value"]
startCompDir = os.path.join(self.startDir, "%s_%s" % (system, component))
mkDir(self.startDir)
if not os.path.lexists(startCompDir):
gLogger.notice("Creating startup link at", startCompDir)
mkLink(runitCompDir, startCompDir)
# Wait for the service to be recognised (can't use isfile as supervise/ok is a device)
start = time.time()
while (time.time() - 10) < start:
time.sleep(1)
if os.path.exists(os.path.join(startCompDir, "supervise", "ok")):
break
else:
return S_ERROR("Failed to find supervise/ok for component %s_%s" % (system, component))
# Check the runsv status
start = time.time()
while (time.time() - 20) < start:
result = self.getStartupComponentStatus([(system, component)])
if not result["OK"]:
continue
if result["Value"] and result["Value"]["%s_%s" % (system, component)]["RunitStatus"] == "Run":
break
time.sleep(1)
else:
return S_ERROR("Failed to start the component %s_%s" % (system, component))
resDict = {}
resDict["ComponentType"] = componentType
resDict["RunitStatus"] = result["Value"]["%s_%s" % (system, component)]["RunitStatus"]
return S_OK(resDict)
def unsetupComponent(self, system, component):
"""
Remove link from startup
"""
for startCompDir in glob.glob(os.path.join(self.startDir, "%s_%s" % (system, component))):
try:
os.unlink(startCompDir)
except Exception:
gLogger.exception()
return S_OK()
def uninstallComponent(self, system, component, removeLogs):
"""
Remove startup and runit directories
"""
self.runsvctrlComponent(system, component, "d")
self.unsetupComponent(system, component)
if removeLogs:
for runitCompDir in glob.glob(os.path.join(self.runitDir, system, component)):
try:
shutil.rmtree(runitCompDir)
except Exception:
gLogger.exception()
result = self.removeComponentOptionsFromCS(system, component)
if not result["OK"]:
return result
return S_OK()
def setupPortal(self):
"""
Install and create link in startup
"""
result = self.installPortal()
if not result["OK"]:
return result
# Create the startup entries now
runitCompDir = result["Value"]
startCompDir = os.path.join(self.startDir, "Web_WebApp")
mkDir(self.startDir)
mkLink(runitCompDir, startCompDir)
time.sleep(5)
# Check the runsv status
start = time.time()
while (time.time() - 10) < start:
result = self.getStartupComponentStatus([("Web", "WebApp")])
if not result["OK"]:
return S_ERROR("Failed to start the Portal")
if result["Value"] and result["Value"]["%s_%s" % ("Web", "WebApp")]["RunitStatus"] == "Run":
break
time.sleep(1)
# Final check
return self.getStartupComponentStatus([("Web", "WebApp")])
def installPortal(self):
"""
Install runit directories for the Web Portal
"""
# Check that the software for the Web Portal is installed
try:
metadata.version("WebAppDIRAC")
except metadata.PackageNotFoundError:
webappInstalled = False
else:
webappInstalled = True
if not webappInstalled:
error = "WebApp extension not installed"
gLogger.error(error)
if self.exitOnError:
gLogger.error(error)
DIRAC.exit(-1)
return S_ERROR(error)
# Check if the component is already installed
runitWebAppDir = os.path.join(self.runitDir, "Web", "WebApp")
# Check if the component is already installed
if os.path.exists(runitWebAppDir):
msg = "Web Portal already installed"
gLogger.notice(msg)
else:
gLogger.notice("Installing Web Portal")
# Now do the actual installation
try:
self._createRunitLog(runitWebAppDir)
runFile = os.path.join(runitWebAppDir, "run")
with io.open(runFile, "w") as fd:
fd.write(
u"""#!/bin/bash
rcfile=%(bashrc)s
[[ -e $rcfile ]] && source $rcfile
#
exec 2>&1
#
exec dirac-webapp-run -p < /dev/null
"""
% {"bashrc": os.path.join(self.instancePath, "bashrc"), "DIRAC": self.linkedRootPath}
)
os.chmod(runFile, self.gDefaultPerms)
except Exception:
error = "Failed to prepare self.setup for Web Portal"
gLogger.exception(error)
if self.exitOnError:
DIRAC.exit(-1)
return S_ERROR(error)
result = self.execCommand(5, [runFile])
gLogger.notice(result["Value"][1])
return S_OK(runitWebAppDir)
def getMySQLPasswords(self):
"""
Get MySQL passwords from local configuration or prompt
"""
if not self.mysqlRootPwd:
self.mysqlRootPwd = prompt(u"MySQL root password: ", is_password=True)
if not self.mysqlPassword:
# Take it if it is already defined
self.mysqlPassword = self.localCfg.getOption("/Systems/Databases/Password", "")
if not self.mysqlPassword:
self.mysqlPassword = prompt(u"MySQL Dirac password: ", is_password=True)
return S_OK()
def setMySQLPasswords(self, root="", dirac=""):
"""
Set MySQL passwords
"""
if root:
self.mysqlRootPwd = root
if dirac:
self.mysqlPassword = dirac
return S_OK()
def getMySQLStatus(self):
"""
Get the status of the MySQL database installation
"""
result = self.execCommand(0, ["mysqladmin", "status"])
if not result["OK"]:
return result
keys = [
None,
"UpTime",
"NumberOfThreads",
"NumberOfQuestions",
"NumberOfSlowQueries",
"NumberOfOpens",
"FlushTables",
"OpenTables",
"QueriesPerSecond",
]
return S_OK({key: output.strip().split()[0] for key, output in zip(keys, result["Value"][1].split(":")) if key})
def getAvailableDatabases(self, extensions=None):
"""Find all databases defined"""
if not extensions:
extensions = extensionsByPriority()
res = self.getAvailableSQLDatabases(extensions)
gLogger.debug("Available SQL databases", res)
if not res["OK"]:
return res
sqlDBs = res["Value"]
res = self.getAvailableESDatabases(extensions)
gLogger.debug("Available ES databases", res)
if not res["OK"]:
return res
esDBs = res["Value"]
allDBs = sqlDBs.copy()
allDBs.update(esDBs)
return S_OK(allDBs)
def getAvailableSQLDatabases(self, extensions):
"""
Find the sql files
:param list extensions: list of DIRAC extensions
:return: dict of MySQL DBs
"""
dbDict = {}
for extension in extensions:
databases = findDatabases(extensions)
for systemName, dbSql in databases:
dbName = dbSql.replace(".sql", "")
dbDict[dbName] = {}
dbDict[dbName]["Type"] = "MySQL"
# TODO: Does this need to be replaced
dbDict[dbName]["Extension"] = extension.replace("DIRAC", "")
dbDict[dbName]["System"] = systemName.replace("System", "")
return S_OK(dbDict)
def getAvailableESDatabases(self, extensions):
"""
Find the ES DBs definitions, by introspection.
This method makes a few assumptions:
- the files defining modules interacting with ES DBs are found in the xyzSystem/DB/ directories
- the files defining modules interacting with ES DBs are named xyzDB.py (e.g. MonitoringDB.py)
- the modules define ES DBs classes with the same name of the module (e.g. class MonitoringDB())
- the classes are inheriting from the ElasticDB module (e.g. class MonitoringDB(ElasticDB))
Result should be something like::
{'MonitoringDB': {'Type': 'ES', 'System': 'Monitoring', 'Extension': ''},
'ElasticJobParametersDB': {'Type': 'ES', 'System': 'WorkloadManagement', 'Extension': ''}}
:param list extensions: list of DIRAC extensions
:return: dict of ES DBs
"""
dbDict = {}
for extension in extensions:
sqlDatabases = findDatabases(extension)
for systemName, dbName in findModules(extension, "DB", "*DB"):
if (systemName, dbName + ".sql") in sqlDatabases:
continue
# Introspect all possible ones for a ElasticDB attribute
try:
module = importlib.import_module(".".join([extension, systemName, "DB", dbName]))
dbClass = getattr(module, dbName)
except (AttributeError, ImportError):
continue
if "ElasticDB" not in str(inspect.getmro(dbClass)):
continue
dbDict[dbName] = {}
dbDict[dbName]["Type"] = "ES"
# TODO: Does this need to be replaced
dbDict[dbName]["Extension"] = extension.replace("DIRAC", "")
dbDict[dbName]["System"] = systemName
return S_OK(dbDict)
def getDatabases(self):
"""
Get the list of installed databases
"""
result = self.execMySQL("SHOW DATABASES")
if not result["OK"]:
return result
dbList = []
for dbName in result["Value"]:
if not dbName[0] in ["Database", "information_schema", "mysql", "test"]:
dbList.append(dbName[0])
return S_OK(dbList)
def installDatabase(self, dbName):
"""
Install requested DB in MySQL server
"""
dbName = MySQLdb.escape_string(dbName.encode()).decode()
if not self.mysqlRootPwd:
rootPwdPath = cfgInstallPath("Database", "RootPwd")
return S_ERROR("Missing %s in %s" % (rootPwdPath, self.cfgFile))
if not self.mysqlPassword:
self.mysqlPassword = self.localCfg.getOption(
cfgPath("Systems", "Databases", "Password"), self.mysqlPassword
)
if not self.mysqlPassword:
mysqlPwdPath = cfgPath("Systems", "Databases", "Password")
return S_ERROR("Missing %s in %s" % (mysqlPwdPath, self.cfgFile))
gLogger.notice("Installing", dbName)
# is there by chance an extension of it?
for extension in extensionsByPriority():
databases = {k: v for v, k in findDatabases(extension)}
filename = dbName + ".sql"
if filename in databases:
break
else:
error = "Database %s not found" % dbName
gLogger.error(error)
if self.exitOnError:
DIRAC.exit(-1)
return S_ERROR(error)
systemName = databases[filename]
moduleName = ".".join([extension, systemName, "DB"])
gLogger.debug("Installing %s from %s" % (filename, moduleName))
dbSql = importlib_resources.read_text(moduleName, filename)
# just check
result = self.execMySQL("SHOW STATUS")
if not result["OK"]:
error = "Could not connect to MySQL server"
gLogger.error(error)
if self.exitOnError:
DIRAC.exit(-1)
return S_ERROR(error)
gLogger.debug("SHOW STATUS : OK")
# now creating the Database
result = self.execMySQL("CREATE DATABASE `%s`" % dbName)
if not result["OK"] and "database exists" not in result["Message"]:
gLogger.error("Failed to create databases", result["Message"])
if self.exitOnError:
DIRAC.exit(-1)
return result
gLogger.debug("CREATE DATABASES : OK")
perms = (
"SELECT,INSERT,LOCK TABLES,UPDATE,DELETE,CREATE,DROP,ALTER,REFERENCES,"
"CREATE VIEW,SHOW VIEW,INDEX,TRIGGER,ALTER ROUTINE,CREATE ROUTINE"
)
cmd = "GRANT %s ON `%s`.* TO '%s'@'%%'" % (perms, dbName, self.mysqlUser)
result = self.execMySQL(cmd)
if not result["OK"]:
error = "Error executing '%s'" % cmd
gLogger.error(error, result["Message"])
if self.exitOnError:
DIRAC.exit(-1)
return S_ERROR(error)
gLogger.debug("%s : OK" % cmd, result["Value"])
result = self.execMySQL("FLUSH PRIVILEGES")
if not result["OK"]:
gLogger.error("Failed to flush privileges", result["Message"])
if self.exitOnError:
exit(-1)
return result
gLogger.debug("FLUSH PRIVILEGES : OK")
# first getting the lines to be executed, and then execute them
try:
cmdLines = self._createMySQLCMDLines(dbSql)
# We need to run one SQL cmd at once, mysql is much happier that way.
# Create a string of commands, ignoring comment lines
sqlString = "\n".join(x for x in cmdLines if not x.startswith("--"))
# Now run each command (They are seperated by ;)
# Ignore any empty ones
cmds = [x.strip() for x in sqlString.split(";") if x.strip()]
for cmd in cmds:
result = self.execMySQL(cmd, dbName)
if not result["OK"]:
error = "Failed to initialize Database"
gLogger.notice(cmd)
gLogger.error(error, result["Message"])
if self.exitOnError:
DIRAC.exit(-1)
return S_ERROR(error)
except Exception as e:
gLogger.error(str(e))
if self.exitOnError:
DIRAC.exit(-1)
return S_ERROR(error)
return S_OK([extension, systemName])
def uninstallDatabase(self, gConfig_o, dbName):
"""
Remove a database from DIRAC
"""
result = self.getAvailableDatabases()
if not result["OK"]:
return result
dbSystem = result["Value"][dbName]["System"]
result = self.removeDatabaseOptionsFromCS(gConfig_o, dbSystem, dbName)
if not result["OK"]:
return result
return S_OK("DB successfully uninstalled")
def _createMySQLCMDLines(self, dbSql):
"""Creates a list of MYSQL commands to be executed, inspecting the SQL
:param str dbSql: The SQL to parse
:returns: list of str corresponding to executable SQL statements
"""
cmdLines = []
for line in dbSql.split("\n"):
# Should we first source an SQL file (is this sql file an extension)?
if line.lower().startswith("source"):
sourcedDBbFileName = line.split(" ")[1].replace("\n", "")
gLogger.info("Found file to source: %s" % sourcedDBbFileName)
module, filename = sourcedDBbFileName.rsplit("/", 1)
dbSourced = importlib_resources.read_text(module.replace("/", "."), filename)
for lineSourced in dbSourced.split("\n"):
if lineSourced.strip():
cmdLines.append(lineSourced.strip())
# Creating/adding cmdLines
else:
if line.strip():
cmdLines.append(line.strip())
return cmdLines
def execMySQL(self, cmd, dbName="mysql", localhost=False):
"""
Execute MySQL Command
"""
if not self.mysqlRootPwd:
return S_ERROR("MySQL root password is not defined")
if dbName not in self.db:
dbHost = self.mysqlHost
if localhost:
dbHost = "localhost"
self.db[dbName] = MySQL(dbHost, self.mysqlRootUser, self.mysqlRootPwd, dbName, self.mysqlPort)
if not self.db[dbName]._connected:
error = "Could not connect to MySQL server"
gLogger.error(error)
if self.exitOnError:
DIRAC.exit(-1)
return S_ERROR(error)
return self.db[dbName]._query(cmd)
def _addMySQLToDiracCfg(self):
"""
Add the database access info to the local configuration
"""
if not self.mysqlPassword:
return S_ERROR("Missing %s in %s" % (cfgInstallPath("Database", "Password"), self.cfgFile))
sectionPath = cfgPath("Systems", "Databases")
cfg = self.__getCfg(sectionPath, "User", self.mysqlUser)
cfg.setOption(cfgPath(sectionPath, "Password"), self.mysqlPassword)
cfg.setOption(cfgPath(sectionPath, "Host"), self.mysqlHost)
cfg.setOption(cfgPath(sectionPath, "Port"), self.mysqlPort)
return self._addCfgToDiracCfg(cfg)
def _addNoSQLToDiracCfg(self):
"""
Add the NoSQL database access info to the local configuration
"""
sectionPath = cfgPath("Systems", "NoSQLDatabases")
cfg = self.__getCfg(sectionPath, "Host", self.noSQLHost)
cfg.setOption(cfgPath(sectionPath, "Port"), self.noSQLPort)
if self.noSQLUser:
cfg.setOption(cfgPath(sectionPath, "User"), self.noSQLUser)
if self.noSQLPassword:
cfg.setOption(cfgPath(sectionPath, "Password"), self.noSQLPassword)
if self.noSQLSSL:
cfg.setOption(cfgPath(sectionPath, "SSL"), self.noSQLSSL)
return self._addCfgToDiracCfg(cfg)
def execCommand(self, timeout, cmd):
"""
Execute command tuple and handle Error cases
"""
gLogger.debug("Executing command %s with timeout %d" % (cmd, timeout))
result = systemCall(timeout, cmd)
if not result["OK"]:
if timeout and result["Message"].startswith("Timeout"):
return result
gLogger.error("Failed to execute", "%s: %s" % (cmd[0], result["Message"]))
if self.exitOnError:
DIRAC.exit(-1)
return result
if result["Value"][0]:
error = "Failed to execute"
gLogger.error(error, cmd[0])
gLogger.error("Exit code:", ("%s\n" % result["Value"][0]) + "\n".join(result["Value"][1:]))
if self.exitOnError:
DIRAC.exit(-1)
error = S_ERROR(error)
error["Value"] = result["Value"]
return error
gLogger.verbose(result["Value"][1])
return result
def installTornado(self):
"""
Install runit directory for the tornado, and add the configuration of the required service
"""
# Check if the Tornado itself is already installed
runitCompDir = os.path.join(self.runitDir, "Tornado", "Tornado")
if os.path.exists(runitCompDir):
msg = "Tornado_Tornado already installed"
gLogger.notice(msg)
return S_OK(runitCompDir)
# Check the setup for the given system
result = gConfig.getOption("DIRAC/Setups/%s/Tornado" % (CSGlobals.getSetup()))
if not result["OK"]:
return result
self.instance = result["Value"]
# Now do the actual installation
try:
self._createRunitLog(runitCompDir)
runFile = os.path.join(runitCompDir, "run")
with io.open(runFile, "wt") as fd:
fd.write(
u"""#!/bin/bash
rcfile=%(bashrc)s
[ -e $rcfile ] && source $rcfile
#
export DIRAC_USE_TORNADO_IOLOOP=Yes
exec 2>&1
#
#
exec tornado-start-all
"""
% {"bashrc": os.path.join(self.instancePath, "bashrc")}
)
os.chmod(runFile, self.gDefaultPerms)
except Exception:
error = "Failed to prepare self.setup forTornado"
gLogger.exception(error)
if self.exitOnError:
DIRAC.exit(-1)
return S_ERROR(error)
result = self.execCommand(5, [runFile])
gLogger.notice(result["Value"][1])
return S_OK(runitCompDir)
def addTornadoOptionsToCS(self, gConfig_o):
"""
Add the section with the component options to the CS
"""
if gConfig_o:
gConfig_o.forceRefresh()
instanceOption = cfgPath("DIRAC", "Setups", self.setup, "Tornado")
if gConfig_o:
compInstance = gConfig_o.getValue(instanceOption, "")
else:
compInstance = self.localCfg.getOption(instanceOption, "")
if not compInstance:
return S_ERROR("%s not defined in %s" % (instanceOption, self.cfgFile))
tornadoSection = cfgPath("Systems", "Tornado", compInstance)
cfg = self.__getCfg(tornadoSection, "Port", 8443)
# cfg.setOption(cfgPath(tornadoSection, 'Password'), self.mysqlPassword)
return self._addCfgToCS(cfg)
def setupTornadoService(self, system, component, extensions, componentModule="", checkModule=True):
"""
Install and create link in startup
"""
# Create the startup entry now
# Force the system and component to be 'Tornado' but preserve the interface and the code
# just to allow for easier refactoring maybe later
system = "Tornado"
component = "Tornado"
componentType = "Tornado"
runitCompDir = os.path.join(self.runitDir, "Tornado", "Tornado")
startCompDir = os.path.join(self.startDir, "%s_%s" % (system, component))
mkDir(self.startDir)
if not os.path.lexists(startCompDir):
gLogger.notice("Creating startup link at", startCompDir)
mkLink(runitCompDir, startCompDir)
# Wait for the service to be recognised (can't use isfile as supervise/ok is a device)
start = time.time()
while (time.time() - 10) < start:
time.sleep(1)
if os.path.exists(os.path.join(startCompDir, "supervise", "ok")):
break
else:
return S_ERROR("Failed to find supervise/ok for component %s_%s" % (system, component))
# Check the runsv status
start = time.time()
while (time.time() - 20) < start:
result = self.getStartupComponentStatus([(system, component)])
if not result["OK"]:
continue
if result["Value"] and result["Value"]["%s_%s" % (system, component)]["RunitStatus"] == "Run":
break
time.sleep(1)
else:
return S_ERROR("Failed to start the component %s_%s" % (system, component))
resDict = {}
resDict["ComponentType"] = componentType
resDict["RunitStatus"] = result["Value"]["%s_%s" % (system, component)]["RunitStatus"]
return S_OK(resDict)
# port = compCfg.getOption('Port', 0)
# if port and self.host:
# urlsPath = cfgPath('Systems', system, compInstance, 'URLs')
# cfg.createNewSection(urlsPath)
# failoverUrlsPath = cfgPath('Systems', system, compInstance, 'FailoverURLs')
# cfg.createNewSection(failoverUrlsPath)
# cfg.setOption(cfgPath(urlsPath, component),
# 'dips://%s:%d/%s/%s' % (self.host, port, system, component))
gComponentInstaller = ComponentInstaller()
|
ic-hep/DIRAC
|
src/DIRAC/FrameworkSystem/Client/ComponentInstaller.py
|
Python
|
gpl-3.0
| 102,343
|
[
"DIRAC"
] |
c3bafd71de4c22aa6dc0c9403fbd84f26d24b1d50f2adb09081d34a3e597ca67
|
""" X509Request is a class for managing X509 requests with their Pkeys
"""
__RCSID__ = "$Id$"
import GSI
from DIRAC import S_OK, S_ERROR
from DIRAC.Core.Utilities import DErrno
from DIRAC.Core.Security.X509Chain import X509Chain
class X509Request( object ):
def __init__( self, reqObj = None, pkeyObj = None ):
self.__valid = False
self.__reqObj = reqObj
self.__pkeyObj = pkeyObj
if reqObj and pkeyObj:
self.__valid = True
# It is not used
# def setParentCerts( self, certList ):
# self.__cerList = certList
def generateProxyRequest( self, bitStrength = 1024, limited = False ) :
self.__pkeyObj = GSI.crypto.PKey()
self.__pkeyObj.generate_key( GSI.crypto.TYPE_RSA, bitStrength )
self.__reqObj = GSI.crypto.X509Req()
self.__reqObj.set_pubkey( self.__pkeyObj )
if limited:
self.__reqObj.get_subject().insert_entry( "CN", "limited proxy" )
else:
self.__reqObj.get_subject().insert_entry( "CN", "proxy" )
self.__reqObj.sign( self.__pkeyObj, "SHA256" )
self.__valid = True
def dumpRequest( self ):
"""
Get the request as a string
"""
if not self.__valid:
return S_ERROR( DErrno.ENOCERT )
try:
reqStr = GSI.crypto.dump_certificate_request( GSI.crypto.FILETYPE_PEM, self.__reqObj )
except Exception, e:
return S_ERROR( DErrno.EX509, "Can't serialize request: %s" % e )
return S_OK( reqStr )
def getPKey( self ):
"""
Get PKey Internal
"""
return self.__pkeyObj
def dumpPKey( self ):
"""
Get the pkey as a string
"""
if not self.__valid:
return S_ERROR( DErrno.ENOCERT )
try:
pkeyStr = GSI.crypto.dump_privatekey( GSI.crypto.FILETYPE_PEM, self.__pkeyObj )
except Exception, e:
return S_ERROR( DErrno.EX509, "Can't serialize pkey: %s" % e )
return S_OK( pkeyStr )
def dumpAll( self ):
"""
Dump the contents into a string
"""
if not self.__valid:
return S_ERROR( DErrno.ENOCERT )
try:
reqStr = GSI.crypto.dump_certificate_request( GSI.crypto.FILETYPE_PEM, self.__reqObj )
except Exception, e:
return S_ERROR( DErrno.EX509, "Can't serialize request: %s" % e )
try:
pkeyStr = GSI.crypto.dump_privatekey( GSI.crypto.FILETYPE_PEM, self.__pkeyObj )
except Exception, e:
return S_ERROR( DErrno.EX509, "Can't serialize pkey: %s" % e )
return S_OK( "%s%s" % ( reqStr, pkeyStr ) )
def loadAllFromString( self, pemData ):
try:
self.__reqObj = GSI.crypto.load_certificate_request( GSI.crypto.FILETYPE_PEM, pemData )
except Exception, e:
return S_ERROR( DErrno.ENOCERT, str( e ) )
try:
self.__pkeyObj = GSI.crypto.load_privatekey( GSI.crypto.FILETYPE_PEM, pemData )
except Exception, e:
return S_ERROR( DErrno.ENOPKEY, str( e ) )
self.__valid = True
return S_OK()
def generateChainFromResponse( self, pemData ):
"""
Generate a X509 Chain from the pkey and the pem data passed as the argument
Return : S_OK( X509Chain ) / S_ERROR
"""
if not self.__valid:
return S_ERROR( DErrno.ENOCERT )
try:
certList = GSI.crypto.load_certificate_chain( GSI.crypto.FILETYPE_PEM, pemData )
except Exception, e:
return S_ERROR( DErrno.ENOCERT, str( e ) )
chain = X509Chain()
chain.setChain( certList )
chain.setPKey( self.__pkeyObj )
return chain
def getSubjectDN( self ):
"""
Get subject DN
Return: S_OK( string )/S_ERROR
"""
if not self.__valid:
return S_ERROR( DErrno.ENOCERT )
return S_OK( self.__reqObj.get_subject().one_line() )
def getIssuerDN( self ):
"""
Get issuer DN
Return: S_OK( string )/S_ERROR
"""
if not self.__valid:
return S_ERROR( DErrno.ENOCERT )
return S_OK( self.__reqObj.get_issuer().one_line() )
def checkChain( self, chain ):
"""
Check that the chain matches the request
"""
if not self.__valid:
return S_ERROR( DErrno.ENOCERT )
retVal = chain.getCertInChain()
if not retVal[ 'OK' ]:
return retVal
lastCert = retVal[ 'Value' ]
chainPubKey = GSI.crypto.dump_publickey( GSI.crypto.FILETYPE_PEM, lastCert.getPublicKey()[ 'Value' ] )
reqPubKey = GSI.crypto.dump_publickey( GSI.crypto.FILETYPE_PEM, self.__pkeyObj )
if not chainPubKey == reqPubKey:
retVal = S_OK( False )
retVal[ 'Message' ] = "Public keys do not match"
return retVal
return S_OK( True )
|
andresailer/DIRAC
|
Core/Security/X509Request.py
|
Python
|
gpl-3.0
| 4,466
|
[
"DIRAC"
] |
029dc52b83176a50e1338e2fb779d806c20e4e8f2f325a86a0402bb0ba8a11f8
|
from ..codes import CodeOutput
import numpy as np
class OctopusOutput(CodeOutput):
@property
def is_finished(self):
return False
def __init__(self, dirname):
self.dirname = dirname
CodeOutput.__init__(self)
def read(self):
coords = coordinates(self.dirname)
energs = energy(self.dirname)
self.output_values = {'energetics': energs, 'coordinates': coords}
def coordinates(dirname):
"""
Reads the 'coordinates' file and extracts its
data as the numpy arrays 'positions','velocities'
and 'forces'.
Each of those arrays has the following structure:
Args:
dirname:
The path were the octopus data is produced
Returns:
natom:
Number of atoms
iterations:
Array with iterations
times:
Array with times
positions:
positions[0:MaxIteration,0:natom,0:3]
velocities:
velocities[0:MaxIteration,0:natom,0:3]
forces:
forces[0:MaxIteration,0:natom,0:3]
"""
geo = np.loadtxt(dirname + '/td.general/coordinates')
natom = (geo.shape[1] - 2) / 9
iterations = geo[:, 0]
times = geo[:, 1]
positions = geo[:, 2:3 * natom + 2]
velocities = geo[:, 3 * natom + 2:6 * natom + 2]
forces = geo[:, 6 * natom + 2:9 * natom + 2]
positions = positions.reshape([-1, 3])
velocities = velocities.reshape([-1, 3])
forces = forces.reshape([-1, 3])
return natom, iterations, times, positions, velocities, forces
def energy(dirname):
"""
Reads the 'energy' file and extracts its
data as the numpy arrays 'Total','Kinetic', etc.
Args:
dirname:
The directory where the octopus data was produced
Returns:
iterations:
numpy array of iterations recorded
times:
numpy array with time for each iteration
energy_dict:
dictionary of numpy arrays with values of
Total, Kinetic (ions), Ion-Ion, Electronic,
Eigenvalues, Hartree, Int[n v_xc], Exchange
and Correlation
"""
ene = np.loadtxt(dirname + '/td.general/energy')
iterations = ene[:, 0]
times = ene[:, 1]
energy_dict = {'Total': ene[:, 2], 'Kinetic': ene[:, 3], 'Ion-Ion': ene[:, 4], 'Electronic': ene[:, 5],
'Eigenvalues': ene[:, 6], 'Hartree': ene[:, 7], 'Int': ene[:, 8], 'Exchange': ene[:, 9],
'Correlation': ene[:, 10]}
return iterations, times, energy_dict
|
MaterialsDiscovery/PyChemia
|
pychemia/code/octopus/output.py
|
Python
|
mit
| 2,529
|
[
"Octopus"
] |
f3c0925db517026d0f32eca0a6c7bf5b181dabb40584bb877fdc51f89c642c4a
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.