text
stringlengths 3
1.05M
|
---|
/* Description: Raptor frida android enum
* Mode: S
* Version: 1.0
* Credit: https://github.com/0xdea/frida-scripts/tree/master/android-snippets
* Author: @0xdea
*/
/*
* raptor_frida_android_enum.js - Java class/method enumerator
* Copyright (c) 2017 Marco Ivaldi <[email protected]>
*
* Frida.re JS functions to enumerate Java classes and methods
* declared in an iOS app. See https://www.frida.re/ and
* https://codeshare.frida.re/ for further information on this
* powerful tool.
*
* "We want to help others achieve interop through reverse
* engineering" -- @oleavr
*
* Example usage:
* # frida -U -f com.target.app -l raptor_frida_android_enum.js --no-pause
*
* Get the latest version at:
* https://github.com/0xdea/frida-scripts/
*/
// enumerate all Java classes
function enumAllClasses()
{
var allClasses = [];
var classes = Java.enumerateLoadedClassesSync();
classes.forEach(function(aClass) {
try {
var className = aClass.match(/[L](.*);/)[1].replace(/\//g, ".");
}
catch(err) {} // avoid TypeError: cannot read property 1 of null
allClasses.push(className);
});
return allClasses;
}
// find all Java classes that match a pattern
function findClasses(pattern)
{
var allClasses = enumAllClasses();
var foundClasses = [];
allClasses.forEach(function(aClass) {
try {
if (aClass.match(pattern)) {
foundClasses.push(aClass);
}
}
catch(err) {} // avoid TypeError: cannot read property 'match' of undefined
});
return foundClasses;
}
// enumerate all methods declared in a Java class
function enumMethods(targetClass)
{
var hook = Java.use(targetClass);
var ownMethods = hook.class.getDeclaredMethods();
hook.$dispose;
return ownMethods;
}
/*
* The following functions were not implemented because deemed impractical:
*
* enumAllMethods() - enumerate all methods declared in all Java classes
* findMethods(pattern) - find all Java methods that match a pattern
*
* See raptor_frida_ios_enum.js for a couple of ObjC implementation examples.
*/
// usage examples
setTimeout(function() { // avoid java.lang.ClassNotFoundException
Java.perform(function() {
// enumerate all classes
/*
var a = enumAllClasses();
a.forEach(function(s) {
console.log(s);
});
*/
// find classes that match a pattern
/*
var a = findClasses(/password/i);
a.forEach(function(s) {
console.log(s);
});
*/
// enumerate all methods in a class
/*
var a = enumMethods("com.target.app.PasswordManager")
a.forEach(function(s) {
console.log(s);
});
*/
});
}, 0);
|
from telegram import Update
from telegram.ext import CallbackContext
from app.extensions import db
from app.lib.handlers.base import BaseHandler, app_context
from app.models import (
Bot,
BotChannelMember,
Channel,
Human,
HumanChannelMember,
)
class LeftChatMemberFilter(BaseHandler):
@app_context
def handler(self, update: Update, context: CallbackContext):
message = update.message
channel = Channel.query.filter(
Channel.chat_id == str(message.chat_id)
).one_or_none()
if not channel:
self.logger.warning(
f"Supposed to get removed from channel that doesn't exists, chat_id: {message.chat_id}"
)
return
# Only handle case when bot was removed from channel
if not message.left_chat_member.id == context.bot.id:
if message.left_chat_member.is_bot:
bot = (
db.session.query(Bot)
.filter_by(user_id=str(message.left_chat_member.id))
.one_or_none()
)
if bot is None:
# Should never be called
return
db.session.query(BotChannelMember).filter(
BotChannelMember.bot_id == bot.id,
BotChannelMember.channel_id == channel.id,
).delete()
db.session.commit()
else:
human = (
db.session.query(Human)
.filter_by(user_id=str(message.left_chat_member.id))
.one_or_none()
)
if human is None:
# Should never be called
return
db.session.query(HumanChannelMember).filter(
HumanChannelMember.human_id == human.id,
HumanChannelMember.channel_id == channel.id,
).delete()
db.session.commit()
return
self.logger.info(f"Leaving chat_id: {message.chat_id}...")
# Delete
# Is this a desired behaviour?
db.session.query(BotChannelMember).filter(
BotChannelMember.channel_id == channel.id
).delete()
db.session.flush()
db.session.query(HumanChannelMember).filter(
HumanChannelMember.channel_id == channel.id
).delete()
db.session.flush()
db.session.delete(channel)
db.session.commit()
|
import numpy as np
from ..errors import KaffeError, print_stderr
from ..graph import GraphBuilder, NodeMapper
from ..layers import NodeKind
from ..transformers import (DataInjector, DataReshaper, NodeRenamer, ReLUFuser,
BatchNormScaleBiasFuser, BatchNormPreprocessor, ParameterNamer)
from . import network
def get_padding_type(kernel_params, input_shape, output_shape):
'''Translates Caffe's numeric padding to one of ('SAME', 'VALID').
Caffe supports arbitrary padding values, while TensorFlow only
supports 'SAME' and 'VALID' modes. So, not all Caffe paddings
can be translated to TensorFlow. There are some subtleties to
how the padding edge-cases are handled. These are described here:
https://github.com/Yangqing/caffe2/blob/master/caffe2/proto/caffe2_legacy.proto
'''
k_h, k_w, s_h, s_w, p_h, p_w = kernel_params
s_o_h = np.ceil(input_shape.height / float(s_h))
s_o_w = np.ceil(input_shape.width / float(s_w))
if (output_shape.height == s_o_h) and (output_shape.width == s_o_w):
return 'SAME'
v_o_h = np.ceil((input_shape.height - k_h + 1.0) / float(s_h))
v_o_w = np.ceil((input_shape.width - k_w + 1.0) / float(s_w))
if (output_shape.height == v_o_h) and (output_shape.width == v_o_w):
return 'VALID'
return None
class TensorFlowNode(object):
'''An intermediate representation for TensorFlow operations.'''
def __init__(self, op, *args, **kwargs):
# A string corresponding to the TensorFlow operation
self.op = op
# Positional arguments for the operation
self.args = args
# Keyword arguments for the operation
self.kwargs = list(kwargs.items())
# The source Caffe node
self.node = None
def format(self, arg):
'''Returns a string representation for the given value.'''
return "'%s'" % arg if isinstance(arg, str) else str(arg)
def pair(self, key, value):
'''Returns key=formatted(value).'''
return '%s=%s' % (key, self.format(value))
def emit(self):
'''Emits the Python source for this node.'''
# Format positional arguments
args = [self.format(arg) for arg in self.args]
# Format any keyword arguments
if self.kwargs:
args += [self.pair(k, v) for k, v in self.kwargs]
# Set the node name
args.append(self.pair('name', self.node.name))
args = ', '.join(args)
return '%s(%s)' % (self.op, args)
class MaybeActivated(object):
def __init__(self, node, default=True):
self.inject_kwargs = {}
if node.metadata.get('relu', False) != default:
self.inject_kwargs['relu'] = not default
def __call__(self, *args, **kwargs):
kwargs.update(self.inject_kwargs)
return TensorFlowNode(*args, **kwargs)
class TensorFlowMapper(NodeMapper):
def get_kernel_params(self, node):
kernel_params = node.layer.kernel_parameters
input_shape = node.get_only_parent().output_shape
padding = get_padding_type(kernel_params, input_shape, node.output_shape)
# Only emit the padding if it's not the default value.
padding = {'padding': padding} if padding != network.DEFAULT_PADDING else {}
return (kernel_params, padding)
def map_convolution(self, node):
(kernel_params, kwargs) = self.get_kernel_params(node)
h = kernel_params.kernel_h
w = kernel_params.kernel_w
c_o = node.output_shape[1]
c_i = node.parents[0].output_shape[1]
group = node.parameters.group
if group != 1:
kwargs['group'] = group
if not node.parameters.bias_term:
kwargs['biased'] = False
assert kernel_params.kernel_h == h
assert kernel_params.kernel_w == w
return MaybeActivated(node)('conv', kernel_params.kernel_h, kernel_params.kernel_w, c_o,
kernel_params.stride_h, kernel_params.stride_w, **kwargs)
def map_relu(self, node):
return TensorFlowNode('relu')
def map_pooling(self, node):
pool_type = node.parameters.pool
if pool_type == 0:
pool_op = 'max_pool'
elif pool_type == 1:
pool_op = 'avg_pool'
else:
# Stochastic pooling, for instance.
raise KaffeError('Unsupported pooling type.')
(kernel_params, padding) = self.get_kernel_params(node)
return TensorFlowNode(pool_op, kernel_params.kernel_h, kernel_params.kernel_w,
kernel_params.stride_h, kernel_params.stride_w, **padding)
def map_inner_product(self, node):
#TODO: Axis
assert node.parameters.axis == 1
#TODO: Unbiased
assert node.parameters.bias_term == True
return MaybeActivated(node)('fc', node.parameters.num_output)
def map_softmax(self, node):
return TensorFlowNode('softmax')
def map_lrn(self, node):
params = node.parameters
# The window size must be an odd value. For a window
# size of (2*n+1), TensorFlow defines depth_radius = n.
assert params.local_size % 2 == 1
# Caffe scales by (alpha/(2*n+1)), whereas TensorFlow
# just scales by alpha (as does Krizhevsky's paper).
# We'll account for that here.
alpha = params.alpha / float(params.local_size)
return TensorFlowNode('lrn', int(params.local_size / 2), alpha, params.beta)
def map_concat(self, node):
axis = (2, 3, 1, 0)[node.parameters.axis]
return TensorFlowNode('concat', axis)
def map_dropout(self, node):
return TensorFlowNode('dropout', node.parameters.dropout_ratio)
def map_batch_norm(self, node):
scale_offset = len(node.data) == 4
kwargs = {} if scale_offset else {'scale_offset': False}
return MaybeActivated(node, default=False)('batch_normalization', **kwargs)
def map_eltwise(self, node):
operations = {0: 'multiply', 1: 'add', 2: 'max'}
op_code = node.parameters.operation
try:
return TensorFlowNode(operations[op_code])
except KeyError:
raise KaffeError('Unknown elementwise operation: {}'.format(op_code))
def commit(self, chains):
return chains
class TensorFlowEmitter(object):
def __init__(self, tab=None):
self.tab = tab or ' ' * 4
self.prefix = ''
def indent(self):
self.prefix += self.tab
def outdent(self):
self.prefix = self.prefix[:-len(self.tab)]
def statement(self, s):
return self.prefix + s + '\n'
def emit_imports(self):
return self.statement('from kaffe.tensorflow import Network\n')
def emit_class_def(self, name):
return self.statement('class %s(Network):' % (name))
def emit_setup_def(self):
return self.statement('def setup(self):')
def emit_parents(self, chain):
assert len(chain)
s = '(self.feed('
sep = ', \n' + self.prefix + (' ' * len(s))
s += sep.join(["'%s'" % parent.name for parent in chain[0].node.parents])
return self.statement(s + ')')
def emit_node(self, node):
return self.statement(' ' * 5 + '.' + node.emit())
def emit(self, name, chains):
s = self.emit_imports()
s += self.emit_class_def(name)
self.indent()
s += self.emit_setup_def()
self.indent()
blocks = []
for chain in chains:
b = ''
b += self.emit_parents(chain)
for node in chain:
b += self.emit_node(node)
blocks.append(b[:-1] + ')')
s = s + '\n\n'.join(blocks)
return s
class TensorFlowTransformer(object):
def __init__(self, def_path, data_path, verbose=True, phase='test'):
self.verbose = verbose
self.phase = phase
self.load(def_path, data_path, phase)
self.params = None
self.source = None
def load(self, def_path, data_path, phase):
# Build the graph
graph = GraphBuilder(def_path, phase).build()
if data_path is not None:
# Load and associate learned parameters
graph = DataInjector(def_path, data_path)(graph)
# Transform the graph
transformers = [
# Fuse split batch normalization layers
BatchNormScaleBiasFuser(),
# Fuse ReLUs
# TODO: Move non-linearity application to layer wrapper, allowing
# any arbitrary operation to be optionally activated.
ReLUFuser(allowed_parent_types=[NodeKind.Convolution, NodeKind.InnerProduct,
NodeKind.BatchNorm]),
# Rename nodes
# Slashes are used for scoping in TensorFlow. Replace slashes
# in node names with underscores.
# (Caffe's GoogLeNet implementation uses slashes)
NodeRenamer(lambda node: node.name.replace('/', '_'))
]
self.graph = graph.transformed(transformers)
# Display the graph
if self.verbose:
print_stderr(self.graph)
def transform_data(self):
if self.params is None:
transformers = [
# Reshape the parameters to TensorFlow's ordering
DataReshaper({
# (c_o, c_i, h, w) -> (h, w, c_i, c_o)
NodeKind.Convolution: (2, 3, 1, 0),
# (c_o, c_i) -> (c_i, c_o)
NodeKind.InnerProduct: (1, 0)
}),
# Pre-process batch normalization data
BatchNormPreprocessor(),
# Convert parameters to dictionaries
ParameterNamer(),
]
self.graph = self.graph.transformed(transformers)
self.params = {node.name: node.data for node in self.graph.nodes if node.data}
return self.params
def transform_source(self):
if self.source is None:
mapper = TensorFlowMapper(self.graph)
chains = mapper.map()
emitter = TensorFlowEmitter()
if not self.graph.name:
self.graph.name = 'MyNet'
self.source = emitter.emit(self.graph.name, chains)
return self.source
|
// let previousScrollPosition = window.pageYOffset;
let showMenu = false;
window.onscroll = () => {
showMenu = false;
let currentScrollPosition = window.pageYOffset;
let social = document.querySelectorAll('.social');
const menuIcon = document.querySelector("#menuIcon");
const menuElement = document.querySelector("#menu");
const vertical = document.querySelector('#vertical');
menuElement.classList.add('menu-disappear');
if (currentScrollPosition > "80") {
social.forEach(icon => icon.style.opacity = 0);
menuElement.classList.add('menu-disappear');
menuIcon.classList.add('menu-icon-show');
menuIcon.classList.remove('rotate-icon');
menuElement.classList.add('add-gradient');
menuElement.style.justifyContent = "space-around";
vertical.style.width = "100%";
vertical.style.height = "2px";
}else {
social.forEach(icon => icon.style.opacity = 1);
menuElement.classList.remove('menu-disappear');
menuElement.classList.remove('add-gradient');
menuIcon.classList.remove('menu-icon-show');
menuElement.style.transform = "translateY(0)";
vertical.style.height = "calc(100% - 433px)";
vertical.style.width = "2px";
}
// previousScrollPosition = currentScrollPosition;
};
export const menuToggle = () => {
console.log(showMenu);
showMenu = !showMenu;
return showMenu;
};
|
from .dataset import *
from .t2d import *
from .semtab import *
from .wdc import *
from .efthymiou import *
from .toughtables import ToughTables
__all__ = [
"Dataset",
"Annotation",
"T2D",
"Semtab",
"WebDataCommons",
"LimayeGS",
"ToughTables",
]
|
import json
import lzma
import tempfile
import zipfile
from collections import namedtuple
from pathlib import Path
from celery import shared_task
from django.core.files import File
from django.utils import timezone
from capapi.serializers import BulkCaseSerializer
from capapi.views.api_views import CaseViewSet
from capdb.models import Jurisdiction, Reporter, CaseExport
from scripts.helpers import HashingFile, ordered_query_iterator
def export_all(before_date=None):
"""
Queue celery tasks to export all jurisdictions and reporters.
If before_date is provided, only queue jobs where the last export's export_date was less than before_date.
"""
for model, task in ((Jurisdiction, export_cases_by_jurisdiction), (Reporter, export_cases_by_reporter)):
print("Queueing %s" % model.__name__)
for item in model.objects.all():
if before_date and item.case_exports.filter(export_date__gte=before_date).exists():
print("- Skipping %s" % item)
continue
print("- Adding %s" % item)
task.delay(item.pk)
@shared_task
def export_cases_by_jurisdiction(id):
"""
Write a .jsonl.gz file with all cases for jurisdiction.
"""
jurisdiction = Jurisdiction.objects.get(pk=id)
cases = CaseViewSet.queryset.filter(jurisdiction=jurisdiction)
out_path = "{}-{:%Y%m%d}".format(jurisdiction.name_long, timezone.now())
export_queryset(cases, out_path, jurisdiction, public=jurisdiction.whitelisted)
@shared_task
def export_cases_by_reporter(id):
"""
Write a .jsonl.gz file with all cases for reporter.
"""
reporter = Reporter.objects.get(pk=id)
cases = CaseViewSet.queryset.filter(reporter=reporter)
out_path = "{}-{:%Y%m%d}".format(reporter.short_name, timezone.now())
export_queryset(cases, out_path, reporter, public=False)
def try_to_close(file_handle):
"""
Cleanup helper used by exception handler. Try calling .close() on file_handle.
If this fails, presumably file_handle was never opened so no cleanup necessary.
"""
if file_handle:
try:
file_handle.close()
except Exception:
pass
def export_queryset(queryset, dir_name, filter_item, public=False):
"""
Export cases in queryset to dir_name.zip.
filter_item is the Jurisdiction or Reporter used to select the cases.
public controls whether export is downloadable by non-researchers.
"""
formats = {'xml': {}, 'text': {}}
# we can safely select_related case_xml because we fetch these in blocks of 1000 via ordered_query_iterator
queryset = queryset.select_related('case_xml', 'body_cache').order_by('id')
try:
# set up vars for each format
for format_name, vars in formats.items():
# set up bagit metadata files
vars['payload'] = []
vars['bagit'] = "BagIt-Version: 1.0\nTag-File-Character-Encoding: UTF-8\n"
vars['baginfo'] = (
"Source-Organization: Harvard Law School Library Innovation Lab\n"
"Organization-Address: 1545 Massachusetts Avenue, Cambridge, MA 02138\n"
"Contact-Name: Library Innovation Lab\n"
"Contact-Email: [email protected]\n"
"External-Description: Cases for %s\n"
"Bagging-Date: %s\n"
) % (filter_item, timezone.now().strftime("%Y-%m-%d"))
# fake Request object used for serializing cases with DRF's serializer
vars['fake_request'] = namedtuple('Request', ['query_params', 'accepted_renderer'])(
query_params={'body_format': format_name},
accepted_renderer=None,
)
# set up paths for zip file output
vars['internal_path'] = Path(dir_name + '-' + format_name)
vars['data_file_path'] = Path('data', 'data.jsonl.xz')
# create new zip file in memory
vars['out_spool'] = tempfile.TemporaryFile()
vars['archive'] = zipfile.ZipFile(vars['out_spool'], 'w', zipfile.ZIP_STORED)
vars['data_file'] = tempfile.NamedTemporaryFile()
vars['hashing_data_file'] = HashingFile(vars['data_file'], 'sha512')
vars['compressed_data_file'] = lzma.open(vars['hashing_data_file'], "w")
# write each case
for item in ordered_query_iterator(queryset):
for format_name, vars in formats.items():
serializer = BulkCaseSerializer(item, context={'request': vars['fake_request']})
vars['compressed_data_file'].write(bytes(json.dumps(serializer.data), 'utf8'))
vars['compressed_data_file'].write(b'\n')
# finish bag for each format
for format_name, vars in formats.items():
# write temp data file to bag
vars['compressed_data_file'].close()
vars['data_file'].flush()
vars['payload'].append("%s %s" % (vars['hashing_data_file'].hexdigest(), vars['data_file_path']))
vars['archive'].write(vars['data_file'].name, str(vars['internal_path'] / vars['data_file_path']))
vars['data_file'].close()
# write bagit metadata files and close zip
vars['archive'].writestr(str(vars['internal_path'] / "bagit.txt"), vars['bagit'])
vars['archive'].writestr(str(vars['internal_path'] / "bag-info.txt"), vars['baginfo'])
vars['archive'].writestr(str(vars['internal_path'] / "manifest-sha512.txt"), "\n".join(vars['payload']))
vars['archive'].close()
# copy temp file to django storage
vars['out_spool'].seek(0)
zip_name = str(vars['internal_path']) + '.zip'
case_export = CaseExport(public=public, filter_id=filter_item.pk, filter_type=filter_item.__class__.__name__.lower(), body_format=format_name, file_name=zip_name)
case_export.file.save(zip_name, File(vars['out_spool']))
vars['out_spool'].close()
finally:
# in case of error, make sure anything opened was closed
for format_name, vars in formats.items():
for file_handle in ('compressed_data_file', 'data_file', 'archive', 'out_spool'):
try_to_close(vars.get(file_handle))
|
# -*- coding: utf-8 -*-
## @package inversetoon.pyqt.tool.base_tool
#
# inversetoon.pyqt.tool.base_tool utility package.
# @author tody
# @date 2015/07/21
from PyQt4.QtGui import *
from PyQt4.QtCore import *
## Base Tool.
class BaseTool(QObject):
## Constructor
def __init__(self):
super(BaseTool, self).__init__()
def setView(self, view):
self._view = view
self._view.setOverlayFunc(self._overlayFunc)
def mousePressEvent(self, e):
print "mousePressEvent:", self._mousePosition(e)
def mouseReleaseEvent(self, e):
print "mouseReleaseEvent:", self._mousePosition(e)
def mouseMoveEvent(self, e):
print "mouseMoveEvent:", self._mousePosition(e)
def wheelEvent(self, e):
pass
def keyPressEvent(self, e):
print "keyPressEvent:", str(e.key())
def keyReleaseEvent(self, e):
print "keyReleaseEvent:", str(e.key())
def _mousePosition(self, e):
p = self._view._numpy_position(e)
return self._view.unproject(p)
def _overlayFunc(self, painter):
pass
|
# Generate plain notebooks with the required frontmatter defined
# Usage:
# $ python generate.py <notebook-names>... [-h]
#
# Generate plain notebooks with the required frontmatter defined.
#
# Positional arguments:
# notebook_names Notebooks to generate
#
# Options:
# -h, --help show this help message and exit
#
# Example:
# python generate.py {data-iterator,fastai-lr-finder,gradient-accumulation,installation}
import json
import os
from argparse import ArgumentParser
from datetime import datetime
today = datetime.now().strftime('%Y-%m-%d')
notebook = {
'nbformat': 4,
'nbformat_minor': 0,
'metadata': {
'kernelspec': {
'display_name': 'Python 3',
'name': 'python3',
},
'accelerator': 'GPU',
},
'cells': [
{
'cell_type': 'markdown',
'metadata': {},
'source': [
'<!-- ---\n',
'title: <required-title>\n',
f'date: {today}\n',
'downloads: true\n',
'weight: <required-weight> See: https://github.com/pytorch-ignite/examples/issues/30\n',
'summary: <use either this or the `<!--more-->` tag below to provide summary for this notebook, '
'and delete the other>\n'
'tags:\n',
' - <required-tag>\n',
'--- -->\n',
'\n',
'# title-placeholder\n',
'\n',
'<If you are not using the `summary` variable above, use this space to '
'provide a summary for this notebook.>\n',
'<Otherwise, delete the `<!--more-->` below.>',
'\n',
'<!--more-->',
]
}
]
}
if __name__ == '__main__':
cwd = os.getcwd()
parser = ArgumentParser(
'generate',
'$ python generate.py <notebook-names>... [-h]',
'Generate plain notebooks with the required frontmatter defined.'
)
parser.add_argument(
'notebook_names',
help='Notebooks to generate',
nargs='+',
)
args = parser.parse_args()
for name in args.notebook_names:
if not name.endswith('.ipynb'):
name = name + ".ipynb"
if os.path.isfile(name):
with open(name) as fp:
content = json.load(fp)
if len(content['cells']) > 0 and content['cells'][0] == notebook['cells'][0]:
print(f'Frontmatter cell already exists in {os.path.join(cwd, name)}. Exiting')
else:
for key, value in content.items():
if key != 'cells':
content[key] = notebook[key]
else:
content[key] = notebook[key] + content[key]
with open(name, mode='w') as f:
f.write(json.dumps(content, indent=2))
print(f'Added frontmatter to {os.path.join(cwd, name)}')
else:
with open(name, 'w') as fp:
json.dump(notebook, fp, indent=2)
print(f'Generated {os.path.join(cwd, name)}')
|
/**
* Copyright 2018 The AMP HTML 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.
*/
import {NameFrameRenderer} from '../name-frame-renderer';
import {parseJson} from '../../../../src/json';
import {utf8Encode} from '../../../../src/utils/bytes';
const realWinConfig = {
amp: {},
ampAdCss: true,
allowExternalResources: true,
};
describes.realWin('NameFrameRenderer', realWinConfig, env => {
const minifiedCreative = '<p>Hello, World!</p>';
let containerElement;
let context;
let creativeData;
beforeEach(() => {
context = {
size: {width: '320', height: '50'},
requestUrl: 'http://www.google.com',
win: env.win,
applyFillContent: () => {},
sentinel: 's-1234',
};
creativeData = {
rawCreativeBytes: utf8Encode(minifiedCreative),
additionalContextMetadata: {},
};
containerElement = document.createElement('div');
containerElement.setAttribute('height', 50);
containerElement.setAttribute('width', 320);
containerElement.getPageLayoutBox = () => ({
left: 0, top: 0, width: 0, height: 0,
});
containerElement.getIntersectionChangeEntry = () => ({});
document.body.appendChild(containerElement);
new NameFrameRenderer().render(context, containerElement, creativeData);
});
afterEach(() => {
document.body.removeChild(containerElement);
});
it('should append iframe child', () => {
const iframe = containerElement.querySelector('iframe');
expect(iframe).to.be.ok;
const parsedName = parseJson(iframe.getAttribute('name'));
expect(parsedName).to.be.ok;
expect(parsedName.width).to.equal(320);
expect(parsedName.height).to.equal(50);
expect(parsedName._context).to.be.ok;
expect(parsedName._context.sentinel).to.equal('s-1234');
expect(parsedName.creative).to.equal(minifiedCreative);
});
it('should have src pointing to nameframe', () => {
const iframe = containerElement.querySelector('iframe');
expect(iframe).to.be.ok;
expect(iframe.getAttribute('src')).to.match(/nameframe\.max\.html$/);
});
it('should set correct attributes on the iframe', () => {
const iframe = containerElement.querySelector('iframe');
expect(iframe).to.be.ok;
expect(iframe.getAttribute('width')).to.equal('320');
expect(iframe.getAttribute('height')).to.equal('50');
expect(iframe.getAttribute('frameborder')).to.equal('0');
expect(iframe.getAttribute('allowfullscreen')).to.equal('');
expect(iframe.getAttribute('allowtransparency')).to.equal('');
expect(iframe.getAttribute('scrolling')).to.equal('no');
});
});
|
const { createMacro } = require('babel-plugin-macros');
// copy to:
// https://astexplorer.net/#/gist/642aebbb9e449e959f4ad8907b4adf3a/4a65742e2a3e926eb55eaa3d657d1472b9ac7970
module.exports = createMacro(ICUMacro);
function ICUMacro({ references, state, babel }) {
const t = babel.types;
const { Trans = [], Plural = [], Select = [], SelectOrdinal = [] } = references;
// assert we have the react-i18next Trans component imported
addNeededImports(state, babel);
// transform Plural and SelectOrdinal
[...Plural, ...SelectOrdinal].forEach(referencePath => {
if (referencePath.parentPath.type === 'JSXOpeningElement') {
pluralAsJSX(
referencePath.parentPath,
{
attributes: referencePath.parentPath.get('attributes'),
children: referencePath.parentPath.parentPath.get('children'),
},
babel,
);
} else {
// throw a helpful error message or something :)
}
});
// transform Select
Select.forEach(referencePath => {
if (referencePath.parentPath.type === 'JSXOpeningElement') {
selectAsJSX(
referencePath.parentPath,
{
attributes: referencePath.parentPath.get('attributes'),
children: referencePath.parentPath.parentPath.get('children'),
},
babel,
);
} else {
// throw a helpful error message or something :)
}
});
// transform Trans
Trans.forEach(referencePath => {
if (referencePath.parentPath.type === 'JSXOpeningElement') {
transAsJSX(
referencePath.parentPath,
{
attributes: referencePath.parentPath.get('attributes'),
children: referencePath.parentPath.parentPath.get('children'),
},
babel,
);
} else {
// throw a helpful error message or something :)
}
});
}
function pluralAsJSX(parentPath, { attributes }, babel) {
const t = babel.types;
const toObjectProperty = (name, value) =>
t.objectProperty(t.identifier(name), t.identifier(name), false, !value);
// plural or selectordinal
const nodeName = parentPath.node.name.name.toLocaleLowerCase();
// will need to merge count attribute with existing values attribute in some cases
const existingValuesAttribute = findAttribute('values', attributes);
const existingValues = existingValuesAttribute
? existingValuesAttribute.node.value.expression.properties
: [];
let componentStartIndex = 0;
const extracted = attributes.reduce(
(mem, attr) => {
if (attr.node.name.name === 'i18nKey') {
// copy the i18nKey
mem.attributesToCopy.push(attr.node);
} else if (attr.node.name.name === 'count') {
// take the count for element
let exprName = attr.node.value.expression.name;
if (!exprName) {
exprName = 'count';
}
if (exprName === 'count') {
// if the prop expression name is also "count", copy it instead: <Plural count={count} --> <Trans count={count}
mem.attributesToCopy.push(attr.node);
} else {
mem.values.unshift(toObjectProperty(exprName));
}
mem.defaults = `{${exprName}, ${nodeName}, ${mem.defaults}`;
} else if (attr.node.name.name === 'values') {
// skip the values attribute, as it has already been processed into mem from existingValues
} else if (attr.node.value.type === 'StringLiteral') {
// take any string node as plural option
let pluralForm = attr.node.name.name;
if (pluralForm.indexOf('$') === 0) pluralForm = pluralForm.replace('$', '=');
mem.defaults = `${mem.defaults} ${pluralForm} {${attr.node.value.value}}`;
} else if (attr.node.value.type === 'JSXExpressionContainer') {
// convert any Trans component to plural option extracting any values and components
const children = attr.node.value.expression.children || [];
const thisTrans = processTrans(children, babel, componentStartIndex);
let pluralForm = attr.node.name.name;
if (pluralForm.indexOf('$') === 0) pluralForm = pluralForm.replace('$', '=');
mem.defaults = `${mem.defaults} ${pluralForm} {${thisTrans.defaults}}`;
mem.components = mem.components.concat(thisTrans.components);
componentStartIndex += thisTrans.components.length;
}
return mem;
},
{ attributesToCopy: [], values: existingValues, components: [], defaults: '' },
);
// replace the node with the new Trans
parentPath.replaceWith(buildTransElement(extracted, extracted.attributesToCopy, t, true));
}
function selectAsJSX(parentPath, { attributes }, babel) {
const t = babel.types;
const toObjectProperty = (name, value) =>
t.objectProperty(t.identifier(name), t.identifier(name), false, !value);
// will need to merge switch attribute with existing values attribute
const existingValuesAttribute = findAttribute('values', attributes);
const existingValues = existingValuesAttribute
? existingValuesAttribute.node.value.expression.properties
: [];
let componentStartIndex = 0;
const extracted = attributes.reduce(
(mem, attr) => {
if (attr.node.name.name === 'i18nKey') {
// copy the i18nKey
mem.attributesToCopy.push(attr.node);
} else if (attr.node.name.name === 'switch') {
// take the switch for select element
let exprName = attr.node.value.expression.name;
if (!exprName) {
exprName = 'selectKey';
mem.values.unshift(t.objectProperty(t.identifier(exprName), attr.node.value.expression));
} else {
mem.values.unshift(toObjectProperty(exprName));
}
mem.defaults = `{${exprName}, select, ${mem.defaults}`;
} else if (attr.node.name.name === 'values') {
// skip the values attribute, as it has already been processed into mem as existingValues
} else if (attr.node.value.type === 'StringLiteral') {
// take any string node as select option
mem.defaults = `${mem.defaults} ${attr.node.name.name} {${attr.node.value.value}}`;
} else if (attr.node.value.type === 'JSXExpressionContainer') {
// convert any Trans component to select option extracting any values and components
const children = attr.node.value.expression.children || [];
const thisTrans = processTrans(children, babel, componentStartIndex);
mem.defaults = `${mem.defaults} ${attr.node.name.name} {${thisTrans.defaults}}`;
mem.components = mem.components.concat(thisTrans.components);
componentStartIndex += thisTrans.components.length;
}
return mem;
},
{ attributesToCopy: [], values: existingValues, components: [], defaults: '' },
);
// replace the node with the new Trans
parentPath.replaceWith(buildTransElement(extracted, extracted.attributesToCopy, t, true));
}
function transAsJSX(parentPath, { attributes, children }, babel) {
const defaultsAttr = findAttribute('defaults', attributes);
const componentsAttr = findAttribute('components', attributes);
// if there is "defaults" attribute and no "components" attribute, parse defaults and extract from the parsed defaults instead of children
// if a "components" attribute has been provided, we assume they have already constructed a valid "defaults" and it does not need to be parsed
const parseDefaults = defaultsAttr && !componentsAttr;
let extracted;
if (parseDefaults) {
const defaultsExpression = defaultsAttr.node.value.value;
const parsed = babel.parse(`<>${defaultsExpression}</>`, {
presets: ['@babel/react'],
}).program.body[0].expression.children;
extracted = processTrans(parsed, babel);
} else {
extracted = processTrans(children, babel);
}
let clonedAttributes = cloneExistingAttributes(attributes);
if (parseDefaults) {
// remove existing defaults so it can be replaced later with the new parsed defaults
clonedAttributes = clonedAttributes.filter(node => node.name.name !== 'defaults');
}
// replace the node with the new Trans
const replacePath = children.length ? children[0].parentPath : parentPath;
replacePath.replaceWith(
buildTransElement(extracted, clonedAttributes, babel.types, false, !!children.length),
);
}
function buildTransElement(
extracted,
finalAttributes,
t,
closeDefaults = false,
wasElementWithChildren = false,
) {
const nodeName = t.jSXIdentifier('Trans');
// plural, select open { but do not close it while reduce
if (closeDefaults) extracted.defaults += '}';
// convert arrays into needed expressions
extracted.components = t.arrayExpression(extracted.components);
extracted.values = t.objectExpression(extracted.values);
// add generated Trans attributes
if (!attributeExistsAlready('defaults', finalAttributes))
finalAttributes.push(
t.jSXAttribute(t.jSXIdentifier('defaults'), t.StringLiteral(extracted.defaults)),
);
if (!attributeExistsAlready('components', finalAttributes))
finalAttributes.push(
t.jSXAttribute(t.jSXIdentifier('components'), t.jSXExpressionContainer(extracted.components)),
);
if (!attributeExistsAlready('values', finalAttributes))
finalAttributes.push(
t.jSXAttribute(t.jSXIdentifier('values'), t.jSXExpressionContainer(extracted.values)),
);
// create selfclosing Trans component
const openElement = t.jSXOpeningElement(nodeName, finalAttributes, true);
if (!wasElementWithChildren) return openElement;
return t.jSXElement(openElement, null, [], true);
}
function cloneExistingAttributes(attributes) {
return attributes.reduce((mem, attr) => {
mem.push(attr.node);
return mem;
}, []);
}
function findAttribute(name, attributes) {
return attributes.find(child => {
const ele = child.node ? child.node : child;
return ele.name.name === name;
});
}
function attributeExistsAlready(name, attributes) {
return !!findAttribute(name, attributes);
}
function processTrans(children, babel, componentStartIndex = 0) {
const res = {};
res.defaults = mergeChildren(children, babel, componentStartIndex);
res.components = getComponents(children, babel);
res.values = getValues(children, babel);
return res;
}
// eslint-disable-next-line no-control-regex
const leadingNewLineAndWhitespace = new RegExp('^\n\\s+', 'g');
// eslint-disable-next-line no-control-regex
const trailingNewLineAndWhitespace = new RegExp('\n\\s+$', 'g');
function trimIndent(text) {
const newText = text
.replace(leadingNewLineAndWhitespace, '')
.replace(trailingNewLineAndWhitespace, '');
return newText;
}
function mergeChildren(children, babel, componentStartIndex = 0) {
const t = babel.types;
let componentFoundIndex = componentStartIndex;
return children.reduce((mem, child) => {
const ele = child.node ? child.node : child;
// add text, but trim indentation whitespace
if (t.isJSXText(ele) && ele.value) mem += trimIndent(ele.value);
// add ?!? forgot
if (ele.expression && ele.expression.value) mem += ele.expression.value;
// add `{ val }`
if (ele.expression && ele.expression.name) mem += `{${ele.expression.name}}`;
// add `{ val, number }`
if (ele.expression && ele.expression.expressions) {
mem += `{${ele.expression.expressions
.reduce((m, i) => {
m.push(i.name || i.value);
return m;
}, [])
.join(', ')}}`;
}
// add <strong>...</strong> with replace to <0>inner string</0>
if (t.isJSXElement(ele)) {
mem += `<${componentFoundIndex}>${mergeChildren(
ele.children,
babel,
)}</${componentFoundIndex}>`;
componentFoundIndex++;
}
return mem;
}, '');
}
function getValues(children, babel) {
const t = babel.types;
const toObjectProperty = (name, value) =>
t.objectProperty(t.identifier(name), t.identifier(name), false, !value);
return children.reduce((mem, child) => {
const ele = child.node ? child.node : child;
// add `{ var }` to values
if (ele.expression && ele.expression.name) mem.push(toObjectProperty(ele.expression.name));
// add `{ var, number }` to values
if (ele.expression && ele.expression.expressions)
mem.push(
toObjectProperty(ele.expression.expressions[0].name || ele.expression.expressions[0].value),
);
// add `{ var: 'bar' }` to values
if (ele.expression && ele.expression.properties) mem = mem.concat(ele.expression.properties);
// recursive add inner elements stuff to values
if (t.isJSXElement(ele)) {
mem = mem.concat(getValues(ele.children, babel));
}
return mem;
}, []);
}
function getComponents(children, babel) {
const t = babel.types;
return children.reduce((mem, child) => {
const ele = child.node ? child.node : child;
if (t.isJSXElement(ele)) {
const clone = t.clone(ele);
clone.children = clone.children.reduce((clonedMem, clonedChild) => {
const clonedEle = clonedChild.node ? clonedChild.node : clonedChild;
// clean out invalid definitions by replacing `{ catchDate, date, short }` with `{ catchDate }`
if (clonedEle.expression && clonedEle.expression.expressions)
clonedEle.expression.expressions = [clonedEle.expression.expressions[0]];
clonedMem.push(clonedChild);
return clonedMem;
}, []);
mem.push(ele);
}
return mem;
}, []);
}
function addNeededImports(state, babel) {
const t = babel.types;
const importsToAdd = ['Trans'];
// check if there is an existing react-i18next import
const existingImport = state.file.path.node.body.find(
importNode => t.isImportDeclaration(importNode) && importNode.source.value === 'react-i18next',
);
// append Trans to existing or add a new react-i18next import for the Trans
if (existingImport) {
importsToAdd.forEach(name => {
if (
existingImport.specifiers.findIndex(
specifier => specifier.imported && specifier.imported.name === name,
) === -1
) {
existingImport.specifiers.push(t.importSpecifier(t.identifier(name), t.identifier(name)));
}
});
} else {
state.file.path.node.body.unshift(
t.importDeclaration(
importsToAdd.map(name => t.importSpecifier(t.identifier(name), t.identifier(name))),
t.stringLiteral('react-i18next'),
),
);
}
}
|
var searchData=
[
['uart_2eh_75',['uart.h',['../uart_8h.html',1,'']]]
];
|
# coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may cause incorrect behavior and will be lost if the code is regenerated.
# --------------------------------------------------------------------------
from typing import Any, AsyncIterable, Callable, Dict, Generic, Optional, TypeVar, Union
import warnings
from azure.core.async_paging import AsyncItemPaged, AsyncList
from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error
from azure.core.pipeline import PipelineResponse
from azure.core.pipeline.transport import AsyncHttpResponse, HttpRequest
from azure.core.polling import AsyncLROPoller, AsyncNoPolling, AsyncPollingMethod
from azure.mgmt.core.exceptions import ARMErrorFormat
from azure.mgmt.core.polling.async_arm_polling import AsyncARMPolling
from ... import models as _models
T = TypeVar('T')
ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]]
class NatRulesOperations:
"""NatRulesOperations async operations.
You should not instantiate this class directly. Instead, you should create a Client instance that
instantiates it for you and attaches it as an attribute.
:ivar models: Alias to model classes used in this operation group.
:type models: ~azure.mgmt.network.v2020_08_01.models
:param client: Client for service requests.
:param config: Configuration of service client.
:param serializer: An object model serializer.
:param deserializer: An object model deserializer.
"""
models = _models
def __init__(self, client, config, serializer, deserializer) -> None:
self._client = client
self._serialize = serializer
self._deserialize = deserializer
self._config = config
async def get(
self,
resource_group_name: str,
gateway_name: str,
nat_rule_name: str,
**kwargs: Any
) -> "_models.VpnGatewayNatRule":
"""Retrieves the details of a nat ruleGet.
:param resource_group_name: The resource group name of the VpnGateway.
:type resource_group_name: str
:param gateway_name: The name of the gateway.
:type gateway_name: str
:param nat_rule_name: The name of the nat rule.
:type nat_rule_name: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: VpnGatewayNatRule, or the result of cls(response)
:rtype: ~azure.mgmt.network.v2020_08_01.models.VpnGatewayNatRule
:raises: ~azure.core.exceptions.HttpResponseError
"""
cls = kwargs.pop('cls', None) # type: ClsType["_models.VpnGatewayNatRule"]
error_map = {
401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
}
error_map.update(kwargs.pop('error_map', {}))
api_version = "2020-08-01"
accept = "application/json"
# Construct URL
url = self.get.metadata['url'] # type: ignore
path_format_arguments = {
'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'),
'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'),
'gatewayName': self._serialize.url("gateway_name", gateway_name, 'str'),
'natRuleName': self._serialize.url("nat_rule_name", nat_rule_name, 'str'),
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {} # type: Dict[str, Any]
query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str')
# Construct headers
header_parameters = {} # type: Dict[str, Any]
header_parameters['Accept'] = self._serialize.header("accept", accept, 'str')
request = self._client.get(url, query_parameters, header_parameters)
pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
raise HttpResponseError(response=response, error_format=ARMErrorFormat)
deserialized = self._deserialize('VpnGatewayNatRule', pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
get.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/vpnGateways/{gatewayName}/natRules/{natRuleName}'} # type: ignore
async def _create_or_update_initial(
self,
resource_group_name: str,
gateway_name: str,
nat_rule_name: str,
nat_rule_parameters: "_models.VpnGatewayNatRule",
**kwargs: Any
) -> "_models.VpnGatewayNatRule":
cls = kwargs.pop('cls', None) # type: ClsType["_models.VpnGatewayNatRule"]
error_map = {
401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
}
error_map.update(kwargs.pop('error_map', {}))
api_version = "2020-08-01"
content_type = kwargs.pop("content_type", "application/json")
accept = "application/json"
# Construct URL
url = self._create_or_update_initial.metadata['url'] # type: ignore
path_format_arguments = {
'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'),
'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'),
'gatewayName': self._serialize.url("gateway_name", gateway_name, 'str'),
'natRuleName': self._serialize.url("nat_rule_name", nat_rule_name, 'str'),
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {} # type: Dict[str, Any]
query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str')
# Construct headers
header_parameters = {} # type: Dict[str, Any]
header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str')
header_parameters['Accept'] = self._serialize.header("accept", accept, 'str')
body_content_kwargs = {} # type: Dict[str, Any]
body_content = self._serialize.body(nat_rule_parameters, 'VpnGatewayNatRule')
body_content_kwargs['content'] = body_content
request = self._client.put(url, query_parameters, header_parameters, **body_content_kwargs)
pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs)
response = pipeline_response.http_response
if response.status_code not in [200, 201]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
raise HttpResponseError(response=response, error_format=ARMErrorFormat)
if response.status_code == 200:
deserialized = self._deserialize('VpnGatewayNatRule', pipeline_response)
if response.status_code == 201:
deserialized = self._deserialize('VpnGatewayNatRule', pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
_create_or_update_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/vpnGateways/{gatewayName}/natRules/{natRuleName}'} # type: ignore
async def begin_create_or_update(
self,
resource_group_name: str,
gateway_name: str,
nat_rule_name: str,
nat_rule_parameters: "_models.VpnGatewayNatRule",
**kwargs: Any
) -> AsyncLROPoller["_models.VpnGatewayNatRule"]:
"""Creates a nat rule to a scalable vpn gateway if it doesn't exist else updates the existing nat
rules.
:param resource_group_name: The resource group name of the VpnGateway.
:type resource_group_name: str
:param gateway_name: The name of the gateway.
:type gateway_name: str
:param nat_rule_name: The name of the nat rule.
:type nat_rule_name: str
:param nat_rule_parameters: Parameters supplied to create or Update a Nat Rule.
:type nat_rule_parameters: ~azure.mgmt.network.v2020_08_01.models.VpnGatewayNatRule
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be AsyncARMPolling.
Pass in False for this operation to not poll, or pass in your own initialized polling object for a personal polling strategy.
:paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present.
:return: An instance of AsyncLROPoller that returns either VpnGatewayNatRule or the result of cls(response)
:rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.network.v2020_08_01.models.VpnGatewayNatRule]
:raises ~azure.core.exceptions.HttpResponseError:
"""
polling = kwargs.pop('polling', True) # type: Union[bool, AsyncPollingMethod]
cls = kwargs.pop('cls', None) # type: ClsType["_models.VpnGatewayNatRule"]
lro_delay = kwargs.pop(
'polling_interval',
self._config.polling_interval
)
cont_token = kwargs.pop('continuation_token', None) # type: Optional[str]
if cont_token is None:
raw_result = await self._create_or_update_initial(
resource_group_name=resource_group_name,
gateway_name=gateway_name,
nat_rule_name=nat_rule_name,
nat_rule_parameters=nat_rule_parameters,
cls=lambda x,y,z: x,
**kwargs
)
kwargs.pop('error_map', None)
kwargs.pop('content_type', None)
def get_long_running_output(pipeline_response):
deserialized = self._deserialize('VpnGatewayNatRule', pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
path_format_arguments = {
'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'),
'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'),
'gatewayName': self._serialize.url("gateway_name", gateway_name, 'str'),
'natRuleName': self._serialize.url("nat_rule_name", nat_rule_name, 'str'),
}
if polling is True: polling_method = AsyncARMPolling(lro_delay, lro_options={'final-state-via': 'azure-async-operation'}, path_format_arguments=path_format_arguments, **kwargs)
elif polling is False: polling_method = AsyncNoPolling()
else: polling_method = polling
if cont_token:
return AsyncLROPoller.from_continuation_token(
polling_method=polling_method,
continuation_token=cont_token,
client=self._client,
deserialization_callback=get_long_running_output
)
else:
return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method)
begin_create_or_update.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/vpnGateways/{gatewayName}/natRules/{natRuleName}'} # type: ignore
async def _delete_initial(
self,
resource_group_name: str,
gateway_name: str,
nat_rule_name: str,
**kwargs: Any
) -> None:
cls = kwargs.pop('cls', None) # type: ClsType[None]
error_map = {
401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
}
error_map.update(kwargs.pop('error_map', {}))
api_version = "2020-08-01"
accept = "application/json"
# Construct URL
url = self._delete_initial.metadata['url'] # type: ignore
path_format_arguments = {
'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'),
'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'),
'gatewayName': self._serialize.url("gateway_name", gateway_name, 'str'),
'natRuleName': self._serialize.url("nat_rule_name", nat_rule_name, 'str'),
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {} # type: Dict[str, Any]
query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str')
# Construct headers
header_parameters = {} # type: Dict[str, Any]
header_parameters['Accept'] = self._serialize.header("accept", accept, 'str')
request = self._client.delete(url, query_parameters, header_parameters)
pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs)
response = pipeline_response.http_response
if response.status_code not in [200, 202, 204]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
raise HttpResponseError(response=response, error_format=ARMErrorFormat)
if cls:
return cls(pipeline_response, None, {})
_delete_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/vpnGateways/{gatewayName}/natRules/{natRuleName}'} # type: ignore
async def begin_delete(
self,
resource_group_name: str,
gateway_name: str,
nat_rule_name: str,
**kwargs: Any
) -> AsyncLROPoller[None]:
"""Deletes a nat rule.
:param resource_group_name: The resource group name of the VpnGateway.
:type resource_group_name: str
:param gateway_name: The name of the gateway.
:type gateway_name: str
:param nat_rule_name: The name of the nat rule.
:type nat_rule_name: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be AsyncARMPolling.
Pass in False for this operation to not poll, or pass in your own initialized polling object for a personal polling strategy.
:paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present.
:return: An instance of AsyncLROPoller that returns either None or the result of cls(response)
:rtype: ~azure.core.polling.AsyncLROPoller[None]
:raises ~azure.core.exceptions.HttpResponseError:
"""
polling = kwargs.pop('polling', True) # type: Union[bool, AsyncPollingMethod]
cls = kwargs.pop('cls', None) # type: ClsType[None]
lro_delay = kwargs.pop(
'polling_interval',
self._config.polling_interval
)
cont_token = kwargs.pop('continuation_token', None) # type: Optional[str]
if cont_token is None:
raw_result = await self._delete_initial(
resource_group_name=resource_group_name,
gateway_name=gateway_name,
nat_rule_name=nat_rule_name,
cls=lambda x,y,z: x,
**kwargs
)
kwargs.pop('error_map', None)
kwargs.pop('content_type', None)
def get_long_running_output(pipeline_response):
if cls:
return cls(pipeline_response, None, {})
path_format_arguments = {
'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'),
'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'),
'gatewayName': self._serialize.url("gateway_name", gateway_name, 'str'),
'natRuleName': self._serialize.url("nat_rule_name", nat_rule_name, 'str'),
}
if polling is True: polling_method = AsyncARMPolling(lro_delay, lro_options={'final-state-via': 'location'}, path_format_arguments=path_format_arguments, **kwargs)
elif polling is False: polling_method = AsyncNoPolling()
else: polling_method = polling
if cont_token:
return AsyncLROPoller.from_continuation_token(
polling_method=polling_method,
continuation_token=cont_token,
client=self._client,
deserialization_callback=get_long_running_output
)
else:
return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method)
begin_delete.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/vpnGateways/{gatewayName}/natRules/{natRuleName}'} # type: ignore
def list_by_vpn_gateway(
self,
resource_group_name: str,
gateway_name: str,
**kwargs: Any
) -> AsyncIterable["_models.ListVpnGatewayNatRulesResult"]:
"""Retrieves all nat rules for a particular virtual wan vpn gateway.
:param resource_group_name: The resource group name of the VpnGateway.
:type resource_group_name: str
:param gateway_name: The name of the gateway.
:type gateway_name: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: An iterator like instance of either ListVpnGatewayNatRulesResult or the result of cls(response)
:rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.network.v2020_08_01.models.ListVpnGatewayNatRulesResult]
:raises: ~azure.core.exceptions.HttpResponseError
"""
cls = kwargs.pop('cls', None) # type: ClsType["_models.ListVpnGatewayNatRulesResult"]
error_map = {
401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
}
error_map.update(kwargs.pop('error_map', {}))
api_version = "2020-08-01"
accept = "application/json"
def prepare_request(next_link=None):
# Construct headers
header_parameters = {} # type: Dict[str, Any]
header_parameters['Accept'] = self._serialize.header("accept", accept, 'str')
if not next_link:
# Construct URL
url = self.list_by_vpn_gateway.metadata['url'] # type: ignore
path_format_arguments = {
'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'),
'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'),
'gatewayName': self._serialize.url("gateway_name", gateway_name, 'str'),
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {} # type: Dict[str, Any]
query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str')
request = self._client.get(url, query_parameters, header_parameters)
else:
url = next_link
query_parameters = {} # type: Dict[str, Any]
request = self._client.get(url, query_parameters, header_parameters)
return request
async def extract_data(pipeline_response):
deserialized = self._deserialize('ListVpnGatewayNatRulesResult', pipeline_response)
list_of_elem = deserialized.value
if cls:
list_of_elem = cls(list_of_elem)
return deserialized.next_link or None, AsyncList(list_of_elem)
async def get_next(next_link=None):
request = prepare_request(next_link)
pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
raise HttpResponseError(response=response, error_format=ARMErrorFormat)
return pipeline_response
return AsyncItemPaged(
get_next, extract_data
)
list_by_vpn_gateway.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/vpnGateways/{gatewayName}/natRules'} # type: ignore
|
let item = `
<div class="row">
<input type="text" name="score" value="0" readonly>
<input type="text" name="name" placeholder="Task (e.g. code a todo list app)">
<input type="date" name="date" placeholder="Due (Click to select)">
<input type="text" name="priority" placeholder="Priority">
<!--<div class="button">X</div>-->
<input class="remove-item" type="button" value="X">
</div>
`;
function score(date, priority) {
const oneDay = 24 * 60 * 60 * 1000; // hours*minutes*seconds*milliseconds
const diffDays = Math.round((date - new Date()) / oneDay);
return priority - diffDays * Math.abs(diffDays);
}
function recalc(elem) {
let date = new Date(elem.children('input[name="date"]').val()) || new Date();
let priority = parseInt(elem.children('input[name="priority"]').val()) || 0;
console.log(date, priority);
elem.children('input[name="score"]').val(score(date, priority));
}
$(() => {
//$('input[name="date"]').datepicker();
$('.list').on('click', '.remove-item', e => {
$(e.target).parent().remove();
});
$('.list').on('change', 'input[name="date"], input[name="priority"]', e => {
recalc($(e.target).parent());
});
$('.add-item').click(e => {
$('.list').append(item);
});
$('.sort-by-score').click(e => {
let list = $('.list');
var listitems = list.children().get();
listitems.sort(function(a, b) {
var compA = parseInt($(a).children('input[name="score"]').val());
var compB = parseInt($(b).children('input[name="score"]').val());
return (compA < compB) ? 1 : (compA > compB) ? -1 : 0;
})
$(list).append(listitems);
});
});
|
import KUtils from '@/core/utils'
import marked from 'marked'
marked.setOptions({
gfm: true,
tables: true,
breaks: false,
pedantic: false,
sanitize: false,
smartLists: true,
smartypants: false
})
/**
* 根据当前swagger分组实例得到当前组下word文本
* @param {*} instance
*/
export default function wordText(instance) {
var markdownCollections = [];
if (instance != null && instance != undefined) {
createWordHeader(markdownCollections);
createWordBasicInfo(instance, markdownCollections);
createWordTagsInfo(instance, markdownCollections);
//增强文档
createWordPlusInfo(instance, markdownCollections);
createWordFooter(markdownCollections);
}
return markdownCollections.join('\n');
}
/**
* 主动换行
* @param {*} markdownCollections
*/
function wordLines(markdownCollections) {
markdownCollections.push('\n');
}
function createWordHeader(markdownCollections){
var wordHeader=`<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1"/>
<title>导出Swagger文档到Word</title>
<script src="https://cdn.bootcss.com/jquery/3.2.1/jquery.min.js"></script>
<style type="text/css">
.knife4j-word-body{
width: 90%;
margin: 20px auto;
font-family:"宋体";
font-size: 16px;
}
.knife4j-word-row{
position: relative;
height: auto;
margin-right: 0;
margin-left: 0;
zoom: 1;
display: block;
box-sizing: border-box;
}
.knife4j-word-line{
height: 35px;
line-height:35px;
}
.knife4j-word-divider{
height: 1px;
background: #e8e8e8;
border-bottom: 1px solid #e8e8e8;
}
.knife4j-word-title{
font-weight: 600;
font-size: 18px;
margin-top: 15px;
border-left: 3px solid #00ab6d;
}
.knife4j-word-api{
margin-top: 10px;
}
.knife4j-word-content{
margin-top: 10px;
}
.knife4j-word-code-editor{
border: #ccc 1px solid;
border-left-width: 4px;
background-color: #fefefe;
box-shadow: 0 0 4px #eee;
word-break: break-all;
word-wrap: break-word;
color: #444;
}
.knife4j-word-code-editor .string { color: green; } /*字符串的样式*/
.knife4j-word-code-editor .number { color: darkorange; } /*数字的样式*/
.knife4j-word-code-editor .boolean { color: blue; } /*布尔型数据的样式*/
.knife4j-word-code-editor .null { color: magenta; } /*null值的样式*/
.knife4j-word-code-editor .key { color: red; } /*key值的样式*/
.knife4j-word-method{
font-size: 14px;
font-weight: 600;
margin-right: 10px;
text-align: center;
border-radius: 3px;
text-shadow: 0 1px 0 rgba(0, 0, 0, 0.1);
}
.knife4j-word-table{
width: 120%;
border: 1px solid #c7c4c4;
border-collapse: collapse;
}
.knife4j-word-table tr{
border: 1px solid #c7c4c4;
height: 40px;
}
.knife4j-word-table th{
border: 1px solid #c7c4c4;
background-color: #dfdada;
}
.knife4j-word-table td{
border: 1px solid #c7c4c4;
}
</style>
</head>
<body>
<div class="knife4j-word-body">`
markdownCollections.push(wordHeader);
}
function createWordFooter(markdownCollections){
markdownCollections.push('</div></body></html>');
}
/**
* 基本信息
* @param {*} instance 当前分组实例对象
* @param {*} markdownCollections markdown文本集合对象
*/
function createWordBasicInfo(instance, markdownCollections) {
markdownCollections.push('<h1>1.项目说明</h1>');
markdownCollections.push('<div class="knife4j-word-row">');
markdownCollections.push('<div class="knife4j-word-line"><strong>标题</strong>:'+instance.title+'</div>');
markdownCollections.push('<div class="knife4j-word-divider"></div>');
markdownCollections.push('<div class="knife4j-word-line"><strong>简介</strong>:'+instance.description+'</div>');
markdownCollections.push('<div class="knife4j-word-divider"></div>');
markdownCollections.push('<div class="knife4j-word-line"><strong>作者</strong>:<code>'+instance.contact+'</code></div>');
markdownCollections.push('<div class="knife4j-word-divider"></div>');
markdownCollections.push('<div class="knife4j-word-line"><strong>HOST</strong>:'+instance.host+'</div>');
markdownCollections.push('<div class="knife4j-word-divider"></div>');
markdownCollections.push('<div class="knife4j-word-line"><strong>basePath</strong>:'+instance.basePath+'</div>');
markdownCollections.push('<div class="knife4j-word-divider"></div>');
markdownCollections.push('<div class="knife4j-word-line"><strong>termsOfService</strong>:'+instance.termsOfService+'</div>');
markdownCollections.push('<div class="knife4j-word-divider"></div>');
markdownCollections.push('<div class="knife4j-word-line"><strong>联系人</strong>:'+instance.contact+'</div>')
markdownCollections.push('<div class="knife4j-word-divider"></div>');
markdownCollections.push('<div class="knife4j-word-line"><strong>Version</strong>:'+instance.version+'</div>');
markdownCollections.push('<div class="knife4j-word-divider"></div>');
markdownCollections.push('<div class="knife4j-word-line"><strong>GroupName</strong>:'+instance.name+'</div>');
markdownCollections.push('<div class="knife4j-word-divider"></div>');
markdownCollections.push('<div class="knife4j-word-line"><strong>分组Url</strong>:'+instance.url+'</div>');
markdownCollections.push('<div class="knife4j-word-divider"></div>');
markdownCollections.push('<div class="knife4j-word-line"><strong>分组Location</strong>:'+instance.location+'</div>');
markdownCollections.push('<div class="knife4j-word-divider"></div>');
markdownCollections.push('</div>');
}
/**
* 增加增强文档
* @param {*} instance
* @param {*} markdownCollections
*/
function createWordPlusInfo(instance, markdownCollections) {
if (KUtils.checkUndefined(instance.markdownFiles)) {
if(KUtils.arrNotEmpty(instance.markdownFiles)){
//if (instance.markdownFiles.length > 0) {
wordLines(markdownCollections);
//markdownCollections.push('# 附录');
markdownCollections.push('<h1>3.附录</h1>')
instance.markdownFiles.forEach(function (md,mdIndex) {
wordLines(markdownCollections);
var mindex=mdIndex+1;
var mdTitle='3.'+mindex+md.name;
markdownCollections.push('<h2>'+mdTitle+'</h2>');
if(KUtils.arrNotEmpty(md.children)){
md.children.forEach(mdfile=>{
markdownCollections.push('<h3>'+mdfile.title+'</h3>');
markdownCollections.push('<div class="knife4j-word-content">');
//判断非空
if(KUtils.strNotBlank(mdfile.content)){
markdownCollections.push(marked(mdfile.content));
}
markdownCollections.push('</div>');
})
}
})
}
}
}
/**
* 遍历tags分组信息
* @param {*} instance 当前分组实例对象
* @param {*} markdownCollections markdown文本集合对象
*/
function createWordTagsInfo(instance, markdownCollections) {
if (instance.tags != undefined && instance.tags != null) {
markdownCollections.push('\n');
markdownCollections.push('<h1>2.接口列表</h1>')
instance.tags.forEach(function (tag,index) {
var docIdex=parseInt(index)+1;
var docParent='2.'+docIdex;
var tagTitle=docParent+tag.name;
markdownCollections.push('<h2>'+tagTitle+'</h2>');
wordLines(markdownCollections);
if (tag.childrens != undefined && tag.childrens != null && tag.childrens.length > 0) {
//遍历
tag.childrens.forEach(function (apiInfo,aIndex) {
var apiIndex=aIndex+1;
createWrodApiInfo(apiInfo, markdownCollections,docParent,apiIndex);
})
} else {
markdownCollections.push('暂无接口文档')
}
})
}
}
/**
* 遍历接口详情
* @param {*} apiInfo 接口实例
* @param {*} markdownCollections markdown文本集合对象
*/
function createWrodApiInfo(apiInfo, markdownCollections,parentDoc,apiIndex) {
//二级标题
wordLines(markdownCollections);
var h3Title=parentDoc+'.'+apiIndex+apiInfo.summary;
markdownCollections.push('<h3>'+h3Title+'</h3>');
markdownCollections.push('<div class="knife4j-word-api">');
markdownCollections.push('<div class="knife4j-word-title">接口地址</div>')
markdownCollections.push('<div class="knife4j-word-content"><span class="knife4j-word-method">'+apiInfo.methodType+'</span> <code>'+apiInfo.showUrl+'</code></div>');
markdownCollections.push('<div class="knife4j-word-title">接口描述</div>');
markdownCollections.push('<div class="knife4j-word-content">'+KUtils.toString(apiInfo.description, '暂无')+'</div>');
markdownCollections.push('<div class="knife4j-word-title">请求数据类型</div>');
markdownCollections.push('<div class="knife4j-word-content"><code>'+KUtils.toString(apiInfo.consumes, '*')+'</code></div>')
markdownCollections.push('<div class="knife4j-word-title">响应数据类型</div>');
markdownCollections.push('<div class="knife4j-word-content"><code>'+KUtils.toString(apiInfo.produces, '*')+'</code></div>')
if(KUtils.strNotBlank(apiInfo.author)){
markdownCollections.push('<div class="knife4j-word-title">开发者</div>');
markdownCollections.push('<div class="knife4j-word-content">'+KUtils.toString(apiInfo.author, '暂无')+'</div>');
}
//判断是否有请求示例
if (KUtils.checkUndefined(apiInfo.requestValue)) {
markdownCollections.push('<div class="knife4j-word-title">请求示例</div>');
markdownCollections.push('<div class="knife4j-word-content">');
//需要判断是否是xml请求
markdownCollections.push('<pre class="knife4j-word-code-editor">');
if(apiInfo.xmlRequest){
//xml请求,不做处理
markdownCollections.push(apiInfo.requestValue);
}else{
markdownCollections.push(wordJsonFormatter(apiInfo.requestValue));
}
markdownCollections.push('</pre>');
markdownCollections.push('</div>');
}
//请求参数
createWordApiRequestParameters(apiInfo, markdownCollections);
//响应状态
createWordApiResponseStatus(apiInfo, markdownCollections);
//响应Schema-参数
//判断响应参数
createWordApiResponseParameters(apiInfo, markdownCollections);
markdownCollections.push('</div>');
}
/**
* 响应状态
* @param {*} apiInfo
* @param {*} markdownCollections
*/
function createWordApiResponseStatus(apiInfo, markdownCollections) {
if (KUtils.checkUndefined(apiInfo.responseCodes) && apiInfo.responseCodes.length > 0) {
wordLines(markdownCollections);
markdownCollections.push('<div class="knife4j-word-title">响应状态</div><br/>');
markdownCollections.push('<div class="knife4j-word-content">');
markdownCollections.push('<table class="knife4j-word-table">');
//表头
markdownCollections.push('<thead><tr><th>状态码</th><th>说明</th><th>schema</th></tr></thead>')
//内容
markdownCollections.push('<tbody>');
wordLines(markdownCollections);
//拥有参数
apiInfo.responseCodes.forEach(function (respcode) {
markdownCollections.push('<tr>');
markdownCollections.push('<td>'+KUtils.toString(respcode.code, '')+'</td>');
markdownCollections.push('<td>'+KUtils.toString(respcode.description, '')+'</td>');
markdownCollections.push('<td>'+KUtils.toString(respcode.schema, '')+'</td>');
//markdownCollections.push('|' + KUtils.toString(respcode.code, '') + '|' + KUtils.toString(respcode.description, '') + '|' + KUtils.toString(respcode.schema, '') + '|')
markdownCollections.push('</tr>');
})
markdownCollections.push('</tbody>');
markdownCollections.push('</table><br/>');
markdownCollections.push('</div>');
}
}
/**
* 响应参数拥有响应头
* @param {*} responseHeaderParameters
* @param {*} markdownCollections
*/
function createWordApiResponseHeaderParams(responseHeaderParameters, markdownCollections) {
if (KUtils.checkUndefined(responseHeaderParameters)) {
if(KUtils.arrNotEmpty(responseHeaderParameters)){
//if (responseHeaderParameters.length > 0) {
wordLines(markdownCollections);
markdownCollections.push('<div class="knife4j-word-title">响应Header</div>')
wordLines(markdownCollections);
//拥有参数
markdownCollections.push('<div class="knife4j-word-content">');
markdownCollections.push('<table class="knife4j-word-table">');
//表头
markdownCollections.push('<thead><tr><th>参数名称</th><th>参数说明</th><th>类型</th></tr></thead>');
//内容
markdownCollections.push('<tbody>');
responseHeaderParameters.forEach(function (respHeader) {
markdownCollections.push('<tr>')
markdownCollections.push('<td>'+KUtils.toString(respHeader.name, '')+'</td>');
markdownCollections.push('<td>'+KUtils.toString(respHeader.description, '')+'</td>');
markdownCollections.push('<td>'+KUtils.toString(respHeader.type, '')+'</td>');
//markdownCollections.push('|' + KUtils.toString(respHeader.name, '') + '|' + KUtils.toString(respHeader.description, '') + '|' + KUtils.toString(respHeader.type, '') + '|');
markdownCollections.push('</tr>')
})
markdownCollections.push('</tbody>');
markdownCollections.push('</table>');
markdownCollections.push('</div>');
}
}
}
/**
* 响应参数
* @param {*} apiInfo
* @param {*} markdownCollections
* @param {*} singleFlag
*/
function createWordApiResponseParameters(apiInfo, markdownCollections) {
//判断是否多个schema
if (apiInfo.multipartResponseSchema) {
var multipartData = apiInfo.multipCodeDatas;
if (KUtils.arrNotEmpty(multipartData)) {
multipartData.forEach(function (resp) {
wordLines(markdownCollections);
markdownCollections.push('<div class="knife4j-word-title">响应状态码-'+KUtils.toString(resp.code, '')+'</div>');
//markdownCollections.push('**响应状态码-' + KUtils.toString(resp.code, '') + '**:');
createWordApiResponseSingleParam(resp, markdownCollections);
})
}
} else {
//单个
createWordApiResponseSingleParam(apiInfo.multipData, markdownCollections);
}
}
/**
* 单个响应状态
* @param {*} resp
* @param {*} markdownCollections
*/
function createWordApiResponseSingleParam(resp, markdownCollections) {
//判断是否有响应Header
createWordApiResponseHeaderParams(resp.responseHeaderParameters, markdownCollections);
//数据
wordLines(markdownCollections);
markdownCollections.push('<div class="knife4j-word-title">响应参数</div>');
//markdownCollections.push('**响应参数**:');
wordLines(markdownCollections);
markdownCollections.push('<div class="knife4j-word-content">');
markdownCollections.push('<table class="knife4j-word-table">');
//表头
markdownCollections.push('<thead><tr><th>参数名称</th><th>参数说明</th><th>类型</th><th>schema</th></tr></thead>');
markdownCollections.push('<tbody>')
if (KUtils.arrNotEmpty(resp.data)) {
//拥有参数
resp.data.forEach(function (param) {
param.level = 1;
markdownCollections.push('<tr>')
markdownCollections.push('<td>'+getWordTableByLevel(param)+'</td>');
markdownCollections.push('<td>'+KUtils.toString(param.description, '')+'</td>');
markdownCollections.push('<td>'+KUtils.toString(param.type, '')+'</td>');
markdownCollections.push('<td>'+KUtils.toString(param.schemaValue, '')+'</td>');
markdownCollections.push('</tr>');
//markdownCollections.push('|' + getWordTableByLevel(param) + '|' + KUtils.toString(param.description, '') + '|' + KUtils.toString(param.type, '') + '|' + KUtils.toString(param.schemaValue, '') + '|')
deepWordTableByResponseParameter(param.children, markdownCollections, (param.level + 1));
})
} else {
//markdownCollections.push('暂无');
markdownCollections.push('<tr><td colspan="4">暂无</td></tr>')
}
markdownCollections.push('</tbody>')
markdownCollections.push('</table>');
markdownCollections.push('</div>');
//判断是否拥有响应示例
wordLines(markdownCollections);
markdownCollections.push('<div class="knife4j-word-title">响应示例</div>')
markdownCollections.push('<div class="knife4j-word-content"><pre class="knife4j-word-code-editor">');
if (resp.responseBasicType) {
markdownCollections.push(resp.responseText)
} else {
markdownCollections.push(wordJsonFormatter(resp.responseValue))
}
markdownCollections.push('</pre></div>');
}
/**
* 请求参数
* @param {*} apiInfo
* @param {*} markdownCollections
*/
function createWordApiRequestParameters(apiInfo, markdownCollections) {
let reqParameters = apiInfo.reqParameters;
wordLines(markdownCollections);
markdownCollections.push('<div class="knife4j-word-title">请求参数</div><br/>')
markdownCollections.push('<div class="knife4j-word-content">');
markdownCollections.push('<table class="knife4j-word-table">');
//表头
markdownCollections.push('<thead><tr><th>参数名称</th><th>参数说明</th><th>请求类型</th><th>必须</th><th>数据类型</th><th>schema</th></tr></thead>');
markdownCollections.push('<tbody>');
//判断是否拥有请求参数
if(KUtils.arrNotEmpty(reqParameters)){
//if (reqParameters.length > 0) {
//级联表格,在表格需要最佳空格缩进符号
deepWordTableByRequestParameter(reqParameters, markdownCollections, 1);
}else{
//无参数
markdownCollections.push('<tr><td colspan="6">暂无</td></tr>');
}
markdownCollections.push('</tbody>');
markdownCollections.push('</table>')
markdownCollections.push('</div>');
}
/**
* 递归循环遍历响应参数得到markdown表格
* @param {*} parameters
* @param {*} markdownCollections
*/
function deepWordTableByResponseParameter(parameters, markdownCollections, level) {
if (parameters != null && parameters != undefined && parameters.length > 0) {
parameters.forEach(function (param) {
param.level = level;
markdownCollections.push('<tr>')
markdownCollections.push('<td>'+getWordTableByLevel(param)+'</td>');
markdownCollections.push('<td>'+KUtils.toString(param.description, '')+'</td>');
markdownCollections.push('<td>'+KUtils.toString(param.type, '')+'</td>');
markdownCollections.push('<td>'+KUtils.toString(param.schemaValue, '')+'</td>');
markdownCollections.push('</tr>');
//markdownCollections.push('|' + getWordTableByLevel(param) + '|' + KUtils.toString(param.description, '') + '|' + KUtils.toString(param.type, '') + '|' + KUtils.toString(param.schemaValue, '') + '|')
deepWordTableByResponseParameter(param.children, markdownCollections, (param.level + 1));
})
}
}
/**
* 递归循环遍历参数得到markdown表格
* @param {*} parameters
* @param {*} markdownCollections
*/
function deepWordTableByRequestParameter(parameters, markdownCollections, level) {
if (parameters != null && parameters != undefined && parameters.length > 0) {
parameters.forEach(function (param) {
//赋值一个level
param.level = level;
markdownCollections.push('<tr>');
markdownCollections.push('<td>'+getWordTableByLevel(param)+'</td>');
markdownCollections.push('<td>'+KUtils.toString(param.description, '')+'</td>');
markdownCollections.push('<td>'+KUtils.toString(param.in, '')+'</td>');
markdownCollections.push('<td>'+KUtils.toString(param.require, '')+'</td>');
markdownCollections.push('<td>'+KUtils.toString(param.type, '') +'</td>');
markdownCollections.push('<td>'+KUtils.toString(param.schemaValue, '') +'</td>');
markdownCollections.push('</tr>');
//markdownCollections.push('|' + getWordTableByLevel(param) + '|' + KUtils.toString(param.description, '') + '|' + KUtils.toString(param.in, '') + '|' + KUtils.toString(param.require, '') + '|' + KUtils.toString(param.type, '') + '|' + KUtils.toString(param.schemaValue, '') + '|')
deepWordTableByRequestParameter(param.children, markdownCollections, (param.level + 1));
})
}
}
/**
* 根据参数级别获取名称
* @param {*} param
*/
function getWordTableByLevel(param) {
var spaceArr = [];
for (var i = 1; i < param.level; i++) {
spaceArr.push(' ')
}
var tmpName = spaceArr.join('') + param.name;
return tmpName;
}
function wordJsonFormatter(json){
try {
if (typeof json != "string") {
json = JSON.stringify(json, undefined, 2);
}
json = json
.replace(/&/g, "&")
.replace(/</g, "<")
.replace(/>/g, ">");
return json.replace(
/("(\\u[a-zA-Z0-9]{4}|\\[^u]|[^\\"])*"(\s*:)?|\b(true|false|null)\b|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?)/g,
function(match) {
var cls = "number";
if (/^"/.test(match)) {
if (/:$/.test(match)) {
cls = "key";
} else {
cls = "string";
}
} else if (/true|false/.test(match)) {
cls = "boolean";
} else if (/null/.test(match)) {
cls = "null";
}
return '<span class="' + cls + '">' + match + "</span>";
}
);
} catch (error) {
return json;
}
}
|
# -*- coding:utf-8 -*-
# Author: hankcs
# Date: 2021-02-15 12:21
from tensorboardX import SummaryWriter
from elit.common.structure import History
from elit.utils.io_util import pushd
class HistoryWithSummary(History):
def __init__(self, save_dir):
super().__init__()
with pushd(save_dir):
self.writer = SummaryWriter()
|
/*!
* Copied from ic-modal which is adapted from jQuery UI core
*
* http://jqueryui.com
* https://github.com/instructure/ic-modal/tree/gh-pages
*
* Copyright 2014 jQuery Foundation and other contributors
* Released under the MIT license.
* http://jquery.org/license
*
* http://api.jqueryui.com/category/ui-core/
*/
var $ = Ember.$;
function focusable( element, isTabIndexNotNaN ) {
var nodeName = element.nodeName.toLowerCase();
return ( /input|select|textarea|button|object/.test( nodeName ) ?
!element.disabled :
"a" === nodeName ?
element.href || isTabIndexNotNaN :
isTabIndexNotNaN) && visible( element );
}
function visible( element ) {
return $.expr.filters.visible( element ) &&
!$( element ).parents().addBack().filter(function() {
return $.css( this, "visibility" ) === "hidden";
}).length;
}
if (!$.expr[':'].tabbable) {
$.expr[':'].tabbable = function( element ) {
var tabIndex = $.attr( element, "tabindex" ),
isTabIndexNaN = isNaN( tabIndex );
return ( isTabIndexNaN || tabIndex >= 0 ) && focusable( element, !isTabIndexNaN );
}
};
|
import path from 'path';
import pubsub from 'pubsub.js';
import utils from '../utils';
const EVENTS = utils.loadJSONSync(path.join(__dirname, '..', 'constants', 'events.json'));
const EVENTS2 = {
"APPLICATION_QUIT": "APPLICATION_QUIT",
"FILE_LOAD": "FILE_LOAD",
"FILE_LOAD_ERROR": "FILE_LOAD_ERROR",
"PROJECT_LOAD": "PROJECT_LOAD",
"PROJECT_LOAD_ERROR": "PROJECT_LOAD_ERROR",
"PROJECT_OPEN": "PROJECT_OPEN"
};
module.exports = {
EVENTS,
pubsub
};
|
System.register(['angular2/core', 'angular2/http', 'rxjs/Observable', 'rxjs/add/operator/map', 'rxjs/add/operator/do', 'rxjs/add/operator/catch', './app.constants'], function(exports_1, context_1) {
"use strict";
var __moduleName = context_1 && context_1.id;
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __metadata = (this && this.__metadata) || function (k, v) {
if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
var core_1, http_1, Observable_1, app_constants_1;
var LoginServices;
return {
setters:[
function (core_1_1) {
core_1 = core_1_1;
},
function (http_1_1) {
http_1 = http_1_1;
},
function (Observable_1_1) {
Observable_1 = Observable_1_1;
},
function (_1) {},
function (_2) {},
function (_3) {},
function (app_constants_1_1) {
app_constants_1 = app_constants_1_1;
}],
execute: function() {
//import * as Rx from "rxjs/Rx"
LoginServices = (function () {
function LoginServices(_http, _configuration) {
this._http = _http;
this._configuration = _configuration;
this.token = localStorage.getItem('token');
this.actionUrl = _configuration.ServerWithApiUrl + 'login';
console.log(this.actionUrl);
this.headers = new http_1.Headers();
this.headers.append('Content-Type', 'application/json');
this.headers.append('Accept', 'application/json');
this.headers.append('Access-Control-Allow-Origin', '*');
this.headers.append('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS');
this.headers.append('Access-Control-Allow-Headers', 'Accept, Accept-CH, Accept-Charset, Accept-Datetime, Accept-Encoding, Accept-Ext, Accept-Features, Accept-Language, Accept-Params, Accept-Ranges, Access-Control-Allow-Credentials, Access-Control-Allow-Headers, Access-Control-Allow-Methods, Access-Control-Allow-Origin, Access-Control-Expose-Headers, Access-Control-Max-Age, Access-Control-Request-Headers, Access-Control-Request-Method, Age, Allow, Alternates, Authentication-Info, Authorization, C-Ext, C-Man, C-Opt, C-PEP, C-PEP-Info, CONNECT, Cache-Control, Compliance, Connection, Content-Base, Content-Disposition, Content-Encoding, Content-ID, Content-Language, Content-Length, Content-Location, Content-MD5, Content-Range, Content-Script-Type, Content-Security-Policy, Content-Style-Type, Content-Transfer-Encoding, Content-Type, Content-Version, Cookie, Cost, DAV, DELETE, DNT, DPR, Date, Default-Style, Delta-Base, Depth, Derived-From, Destination, Differential-ID, Digest, ETag, Expect, Expires, Ext, From, GET, GetProfile, HEAD, HTTP-date, Host, IM, If, If-Match, If-Modified-Since, If-None-Match, If-Range, If-Unmodified-Since, Keep-Alive, Label, Last-Event-ID, Last-Modified, Link, Location, Lock-Token, MIME-Version, Man, Max-Forwards, Media-Range, Message-ID, Meter, Negotiate, Non-Compliance, OPTION, OPTIONS, OWS, Opt, Optional, Ordering-Type, Origin, Overwrite, P3P, PEP, PICS-Label, POST, PUT, Pep-Info, Permanent, Position, Pragma, ProfileObject, Protocol, Protocol-Query, Protocol-Request, Proxy-Authenticate, Proxy-Authentication-Info, Proxy-Authorization, Proxy-Features, Proxy-Instruction, Public, RWS, Range, Referer, Refresh, Resolution-Hint, Resolver-Location, Retry-After, Safe, Sec-Websocket-Extensions, Sec-Websocket-Key, Sec-Websocket-Origin, Sec-Websocket-Protocol, Sec-Websocket-Version, Security-Scheme, Server, Set-Cookie, Set-Cookie2, SetProfile, SoapAction, Status, Status-URI, Strict-Transport-Security, SubOK, Subst, Surrogate-Capability, Surrogate-Control, TCN, TE, TRACE, Timeout, Title, Trailer, Transfer-Encoding, UA-Color, UA-Media, UA-Pixels, UA-Resolution, UA-Windowpixels, URI, Upgrade, User-Agent, Variant-Vary, Vary, Version, Via, Viewport-Width, WWW-Authenticate, Want-Digest, Warning, Width, X-Content-Duration, X-Content-Security-Policy, X-Content-Type-Options, X-CustomHeader, X-DNSPrefetch-Control, X-Forwarded-For, X-Forwarded-Port, X-Forwarded-Proto, X-Frame-Options, X-Modified, X-OTHER, X-PING, X-PINGOTHER, X-Powered-By, X-Requested-With'); //'X-Requested-With,content-type');
this.headers.append('Access-Control-Allow-Credentials', "true");
}
LoginServices.prototype.login = function (usuario) {
// if (username === 'test' && password === 'test') {
// this.token = 'token';
// localStorage.setItem('token', this.token);
// return Observable.of('token');
// }
var _this = this;
console.log("voy a enviar login con nombre y contrasenia");
var body = JSON.stringify({ "nombre": usuario.nombre,
"contrasenia": usuario.contrasenia
});
console.log(body);
var options = new http_1.RequestOptions({ headers: this.headers });
console.log(options);
return this._http.post(this.actionUrl, body, options)
.map(function (res) { _this.token = 'token'; localStorage.setItem('token', _this.token); return res.json(); })
.do(function (data) { return console.log('server data:', data); }) // debug
.catch(this.handleError);
};
LoginServices.prototype.logout = function () {
/*
* If we had a login api, we would have done something like this
return this.http.get(this.config.serverUrl + '/auth/logout', {
headers: new Headers({
'x-security-token': this.token
})
})
.map((res : any) => {
this.token = undefined;
localStorage.removeItem('token');
});
*/
this.token = undefined;
localStorage.removeItem('token');
return Observable_1.Observable.of(true);
};
LoginServices.prototype.handleError = function (error) {
// in a real world app, we may send the error to some remote logging infrastructure
// instead of just logging it to the console
console.error(error);
return Observable_1.Observable.throw(error.json().error || 'Server error');
};
LoginServices = __decorate([
core_1.Injectable(),
__metadata('design:paramtypes', [http_1.Http, app_constants_1.Configuration])
], LoginServices);
return LoginServices;
}());
exports_1("LoginServices", LoginServices);
}
}
});
//# sourceMappingURL=login.services.js.map |
import React from 'react';
import Header from '../components/Header';
export default function About() {
return (
<>
<Header />
<h1>About Page</h1>
</>
)
}
|
"""This file and its contents are licensed under the Apache License 2.0. Please see the included NOTICE for copyright information and LICENSE for a copy of the license.
"""
import pytest
import json
from ..utils import make_task, make_annotation, make_prediction, project_id, make_annotator
from projects.models import Project
from data_import.models import FileUpload
from django.conf import settings
from django.core.files.base import ContentFile
from django.utils.timezone import now
@pytest.mark.parametrize(
"ordering, element_index, undefined",
[
[["tasks:id"], 0, False], # ordered by id ascending, first element api == first created
[["tasks:-id"], -1, False], # ordered by id descending, first element api == last created
[["tasks:completed_at"], 0, False],
[["tasks:-completed_at"], 0, False], # only one task is labeled
[["tasks:total_annotations"], -1, False],
[["tasks:-total_annotations"], 0, False],
[["tasks:total_predictions"], 0, False],
[["tasks:-total_predictions"], -1, False],
[["tasks:cancelled_annotations"], 0, False],
[["tasks:-cancelled_annotations"], -1, False],
[["tasks:annotations_results"], 0, False],
[["tasks:-annotations_results"], -1, False],
[["tasks:predictions_results"], 0, False],
[["tasks:-predictions_results"], -1, False],
[["tasks:predictions_score"], 0, False],
[["tasks:-predictions_score"], -1, False],
[["tasks:data.text"], 0, False],
[["tasks:-data.text"], -1, False],
[["tasks:data.data"], 0, True],
[["-tasks:data.data"], 1, True],
[["tasks:file_upload"], 0, False],
[["-tasks:file_upload"], 1, False],
],
)
@pytest.mark.django_db
def test_views_ordering(ordering, element_index, undefined, business_client, project_id):
payload = dict(
project=project_id,
data={"test": 1, "ordering": ordering},
)
response = business_client.post(
"/api/dm/views/",
data=json.dumps(payload),
content_type="application/json",
)
assert response.status_code == 201, response.content
view_id = response.json()["id"]
project = Project.objects.get(pk=project_id)
if undefined:
task_field_name = settings.DATA_UNDEFINED_NAME
else:
task_field_name = 'text'
file_upload1 = FileUpload.objects.create(user=project.created_by, project=project, file=ContentFile('', name='file_upload1'))
task_id_1 = make_task({"data": {task_field_name: 1}, 'file_upload': file_upload1}, project).id
make_annotation({"result": [{"1": True}]}, task_id_1)
make_prediction({"result": [{"1": True}], "score": 1}, task_id_1)
file_upload2 = FileUpload.objects.create(user=project.created_by, project=project, file=ContentFile('', name='file_upload2'))
task_id_2 = make_task({"data": {task_field_name: 2}, 'file_upload': file_upload2}, project).id
for _ in range(0, 2):
make_annotation({"result": [{"2": True}], "was_cancelled": True}, task_id_2)
for _ in range(0, 2):
make_prediction({"result": [{"2": True}], "score": 2}, task_id_2)
task_ids = [task_id_1, task_id_2]
response = business_client.get(f"/api/tasks?view={view_id}")
response_data = response.json()
assert response_data["tasks"][0]["id"] == task_ids[element_index]
@pytest.mark.parametrize(
"filters, ids",
[
[
{
"conjunction": "or",
"items": [{"filter": "filter:tasks:id", "operator": "equal", "value": 1, "type": "Number"}],
},
[1],
],
[
{
"conjunction": "or",
"items": [
{"filter": "filter:tasks:id", "operator": "equal", "value": 1, "type": "Number"},
{"filter": "filter:tasks:id", "operator": "equal", "value": 2, "type": "Number"},
],
},
[1, 2],
],
[
{
"conjunction": "or",
"items": [
{"filter": "filter:tasks:id", "operator": "not_equal", "value": 1, "type": "Number"},
{"filter": "filter:tasks:id", "operator": "greater", "value": 3, "type": "Number"},
],
},
[2, 3, 4],
],
[
{
"conjunction": "or",
"items": [{"filter": "filter:tasks:id", "operator": "not_equal", "value": 1, "type": "Number"}],
},
[2, 3, 4],
],
[
{
"conjunction": "or",
"items": [{"filter": "filter:tasks:id", "operator": "less", "value": 3, "type": "Number"}],
},
[1, 2],
],
[
{
"conjunction": "or",
"items": [{"filter": "filter:tasks:id", "operator": "greater", "value": 2, "type": "Number"}],
},
[3, 4],
],
[
{
"conjunction": "or",
"items": [{"filter": "filter:tasks:id", "operator": "less_or_equal", "value": 3, "type": "Number"}],
},
[1, 2, 3],
],
[
{
"conjunction": "or",
"items": [{"filter": "filter:tasks:id", "operator": "greater_or_equal", "value": 2, "type": "Number"}],
},
[2, 3, 4],
],
[
{
"conjunction": "or",
"items": [
{"filter": "filter:tasks:id", "operator": "in", "value": {"min": 2, "max": 3}, "type": "Number"}
],
},
[2, 3],
],
[
{
"conjunction": "or",
"items": [
{
"filter": "filter:tasks:id",
"operator": "not_in",
"value": {"min": 2, "max": 3},
"type": "Number",
}
],
},
[1, 4],
],
[
{
"conjunction": "or",
"items": [
{
"filter": "filter:tasks:completed_at",
"operator": "less",
"type": "Datetime",
"value": now().strftime('%Y-%m-%dT%H:%M:%S.%fZ'),
}
],
},
[],
],
[
{
"conjunction": "or",
"items": [
{
"filter": "filter:tasks:completed_at",
"operator": "greater",
"type": "Datetime",
"value": now().strftime('%Y-%m-%dT%H:%M:%S.%fZ'),
}
],
},
[1], # only first task is labeled, second one is skipped
],
[
{
"conjunction": "or",
"items": [
{
"filter": "filter:tasks:completed_at",
"operator": "empty",
"type": "Datetime",
"value": "True",
}
],
},
[2, 3, 4],
],
[
{
"conjunction": "or",
"items": [
{
"filter": "filter:tasks:completed_at",
"operator": "empty",
"type": "Datetime",
"value": "False",
}
],
},
[1],
],
[
{
"conjunction": "or",
"items": [
{
"filter": "filter:tasks:annotations_results",
"operator": "contains",
"type": "String",
"value": "first",
}
],
},
[1, ],
],
[
{
"conjunction": "or",
"items": [
{
"filter": "filter:tasks:data.data",
"operator": "contains",
"type": "String",
"value": "text1",
}
],
},
[1, ],
],
[
{
"conjunction": "and",
"items": [
{
"filter": "filter:tasks:data.data", # undefined column test
"operator": "contains",
"type": "String",
"value": "text",
},
{"filter": "filter:tasks:id", "operator": "equal", "value": 1, "type": "Number"},
],
},
[1, ],
],
[
{
"conjunction": "or",
"items": [
{
"filter": "filter:tasks:annotations_results",
"operator": "not_contains",
"type": "String",
"value": "first",
}
],
},
[2, 3, 4],
],
[
{
"conjunction": "and",
"items": [
{"filter": "filter:tasks:annotators", "operator": "contains", "value": "$ANN1_ID", "type": "List"},
{"filter": "filter:tasks:annotators", "operator": "contains", "value": "$ANN2_ID", "type": "List"},
],
},
[2],
],
],
)
@pytest.mark.django_db
def test_views_filters(filters, ids, business_client, project_id):
project = Project.objects.get(pk=project_id)
ann1 = make_annotator({'email': '[email protected]'}, project)
ann2 = make_annotator({'email': '[email protected]'}, project)
ann_ids = {
'$ANN1_ID': ann1.id,
'$ANN2_ID': ann2.id,
}
for item in filters['items']:
for ann_id_key, ann_id_value in ann_ids.items():
if isinstance(item['value'], str) and ann_id_key in item['value']:
item['value'] = ann_id_value
payload = dict(
project=project_id,
data={"test": 1, "filters": filters},
)
response = business_client.post(
"/api/dm/views/",
data=json.dumps(payload),
content_type="application/json",
)
assert response.status_code == 201, response.content
view_id = response.json()["id"]
task_data_field_name = settings.DATA_UNDEFINED_NAME
task_id_1 = make_task({"data": {task_data_field_name: "some text1"}}, project).id
make_annotation({"result": [{"from_name": "1_first", "to_name": "", "value": {}}], "completed_by": ann1}, task_id_1)
make_prediction({"result": [{"from_name": "1_first", "to_name": "", "value": {}}], "score": 1}, task_id_1)
task_id_2 = make_task({"data": {task_data_field_name: "some text2"}}, project).id
for ann in (ann1, ann2):
make_annotation({"result": [{"from_name": "2_second", "to_name": "", "value": {}}], "was_cancelled": True, "completed_by": ann}, task_id_2)
for _ in range(0, 2):
make_prediction({"result": [{"from_name": "2_second", "to_name": "", "value": {}}], "score": 2}, task_id_2)
task_ids = [0, task_id_1, task_id_2]
for _ in range(0, 2):
task_id = make_task({"data": {task_data_field_name: "some text_"}}, project).id
task_ids.append(task_id)
for item in filters['items']:
if item['type'] == 'Number':
if isinstance(item['value'], dict):
item['value']['min'] = task_ids[int(item['value']['min'])]
item['value']['max'] = task_ids[int(item['value']['max'])]
else:
item['value'] = task_ids[int(item['value'])]
updated_payload = dict(
data={"filters": filters},
)
response = business_client.patch(
f"/api/dm/views/{view_id}",
data=json.dumps(payload),
content_type="application/json",
)
response = business_client.get(f"/api/tasks/?view={view_id}")
response_data = response.json()
assert 'tasks' in response_data, response_data
response_ids = [task["id"] for task in response_data["tasks"]]
correct_ids = [task_ids[i] for i in ids]
assert response_ids == correct_ids, (response_ids, correct_ids, filters)
|
/*
YUI 3.17.2 (build 9c3c78e)
Copyright 2014 Yahoo! Inc. All rights reserved.
Licensed under the BSD License.
http://yuilibrary.com/license/
*/
YUI.add('series-areaspline', function (Y, NAME) {
/**
* Provides functionality for creating an areaspline series.
*
* @module charts
* @submodule series-areaspline
*/
/**
* AreaSplineSeries renders an area graph with data points connected by a curve.
*
* @class AreaSplineSeries
* @extends AreaSeries
* @uses CurveUtil
* @constructor
* @param {Object} config (optional) Configuration parameters.
* @submodule series-areaspline
*/
Y.AreaSplineSeries = Y.Base.create("areaSplineSeries", Y.AreaSeries, [Y.CurveUtil], {
/**
* @protected
*
* Draws the series.
*
* @method drawSeries
*/
drawSeries: function()
{
this.drawAreaSpline();
}
}, {
ATTRS : {
/**
* Read-only attribute indicating the type of series.
*
* @attribute type
* @type String
* @default areaSpline
*/
type: {
value:"areaSpline"
}
/**
* Style properties used for drawing area fills. This attribute is inherited from `Renderer`. Below are the default values:
*
* <dl>
* <dt>color</dt><dd>The color of the fill. The default value is determined by the order of the series on the graph. The color will be
* retrieved from the following array:
* `["#66007f", "#a86f41", "#295454", "#996ab2", "#e8cdb7", "#90bdbd","#000000","#c3b8ca", "#968373", "#678585"]`
* </dd>
* <dt>alpha</dt><dd>Number between 0 and 1 that indicates the opacity of the fill. The default value is 1</dd>
* </dl>
*
* @attribute styles
* @type Object
*/
}
});
}, '3.17.2', {"requires": ["series-area", "series-curve-util"]});
|
/*
Copyright (c) 2003-2016, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.md or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang( 'print', 'sk', {
toolbar: 'Tlač'
} );
|
var lconfig = require("lconfig");
var dal = require('dal');
var logger = require('logger').logger('acl');
var crypto = require('crypto');
var ijod = require("ijod");
var async = require('async');
exports.init = function(callback) {
logger.debug("Accounts DB Check");
logger.debug("If this spins, you need to import the database or otherwise check your connection settings.");
callback();
};
// for oauth grants
exports.getGrant = function(code, callback) {
dal.query("SELECT account, app FROM Grants WHERE code = ? LIMIT 1", [code], function(err, rows) {
rows = rows || [];
callback(err, rows[0]);
});
};
// temporary cache of grants for oauth
exports.addGrant = function(code, account, app, callback) {
dal.query("INSERT INTO Grants (code, account, app) VALUES (?, ?, ?)", [code, account, app], callback);
};
// cleanup!
exports.delGrant = function(code, callback) {
dal.query("DELETE FROM Grants WHERE code = ?", [code], callback);
};
// looks for any account matching this app+profile
exports.getAppProfile = function(id, app, profile, callback) {
logger.debug("getting app profile "+app+" "+profile);
var sql = "SELECT account FROM Accounts WHERE app = ? AND profile = ? ";
var binds = [app, profile];
if (id) {
sql += "AND account = ? ";
binds.push(id);
}
dal.query(sql, binds, function(err, rows) {
rows = rows || [];
callback(err, rows[0], rows.length);
});
};
// validates an account against an app
exports.isAppAccount = function(app, account, callback) {
dal.query("SELECT account FROM Accounts WHERE app = ? AND account = ? LIMIT 1", [app, account], function(err, rows) {
callback(rows && rows.length > 0);
});
};
// account id is optional, creates new random one and returns it if none
exports.addAppProfile = function(id, app, profile, callback) {
logger.debug("adding app profile "+id+" "+app+" "+profile);
id = id || require('crypto').createHash('md5').update(Math.random().toString()).digest('hex');
dal.query("INSERT INTO Accounts (account, app, profile) VALUES (?, ?, ?)", [id, app, profile], function(err) {
callback(err, {account:id, app:app, profile:profile});
});
};
// construct a unique device id and associate it with an account, only do this if there isn't one already
exports.addDevice = function(id, app, device, callback) {
var pid = [device,id,app].join('.') + '@devices';
exports.addAppProfile(id, app, pid, callback);
};
// convenience to find existing or create new if none
exports.getOrAdd = function(id, app, profile, callback) {
// lookup app+profile, if existing return account id, if none create one
exports.getAppProfile(id, app, profile, function(err, account, count) {
if (err) return callback(err);
if (account) return callback(null, account, count);
exports.addAppProfile(id, app, profile, callback);
});
};
exports.getAppsForAccount = function(account, callback) {
logger.debug("getting apps for account "+account);
dal.query("SELECT app, secret, apikeys, notes FROM Apps", [], function(err, rows) {
var apps = [];
for (var i = 0; i < rows.length; i++) {
try {
rows[i].notes = JSON.parse(rows[i].notes);
} catch(E) {
rows[i].notes = {};
}
if (exports.hasAppPerms(account, rows[i])) apps.push(rows[i]);
}
callback(err, apps);
});
};
// centralize this logic
exports.hasAppPerms = function(account, app) {
if (!app) return false;
if (!app.notes) return false;
if (account === app.notes.account) return true;
if (Array.isArray(app.notes.collab) && app.notes.collab.indexOf(account) >= 0) return true;
return false;
};
/* Retrieve the number of accounts on a particular app */
exports.getAppAccountCount = function(appId, callback) {
logger.debug("Counting accounts for app " + appId);
var query = "SELECT COUNT(DISTINCT account) as count FROM Accounts WHERE app = ?";
dal.query(query, [appId], function (err, results) {
if (err || results.length === 0) return callback(new Error ('Could not find accounts for app ' + appId));
else return callback (null, results[0]);
});
};
// given an updated auth object for a profile, make sure it has all the correct
// tasks in the system
var APPCACHE = {};
// dump the cache hourly
setInterval(function(){
APPCACHE = {};
}, 3600000);
// just fetch the info for a given app id
exports.getApp = function(app, useCache, callback) {
if (!callback && typeof useCache === 'function') {
callback = useCache;
useCache = false;
}
if (useCache && APPCACHE[app]) {
return process.nextTick(callback.bind(null, null, APPCACHE[app]));
}
logger.debug("getting app "+app);
// TODO: add memcached caching here, this is called on every pipeline now!
var q = "SELECT app, secret, apikeys, notes FROM Apps WHERE app = ? LIMIT 1";
dal.query(q, [app], function(err, rows) {
rows = rows || [];
// optionally parse any json
if (rows[0]) {
try {
rows[0].apikeys = JSON.parse(rows[0].apikeys);
} catch(E) {
rows[0].apikeys = {};
}
try {
rows[0].notes = JSON.parse(rows[0].notes);
} catch(E) {
rows[0].notes = {};
}
APPCACHE[app] = rows[0];
}
callback(err, rows[0]);
});
};
var PERSONAL_FEATURES = [
'PersonalCheckins',
'PersonalNews',
'PersonalPhotos',
'PersonalStatuses'
];
var SOCIAL_FEATURES = [
'SocialCheckins',
'SocialNews',
'SocialPhotos',
'SocialStatuses'
];
exports.getAppClasses = function(app, useCache, callback) {
if (!callback && typeof useCache === 'function') {
callback = useCache;
useCache = false;
}
exports.getApp(app, useCache, function(err, app) {
if (err) return callback(err, app);
if (!app) return callback('invalid app');
var classes = {core:true};
if (!app.notes) {
return process.nextTick(callback.bind(null, null, classes));
}
for(var i in PERSONAL_FEATURES) {
if (app.notes[PERSONAL_FEATURES[i]]) classes.personal = true;
}
for(var j in SOCIAL_FEATURES) {
if (app.notes[SOCIAL_FEATURES[j]]) classes.social = true;
}
return callback(null, classes);
});
};
exports.getAppsClasses = function(apps, useCache, callback) {
if (!callback && typeof useCache === 'function') {
callback = useCache;
useCache = false;
}
var classes = {};
async.forEach(apps, function(app, cbEach) {
exports.getAppClasses(app, useCache, function(err, theseClasses) {
if (err) {
logger.warn('error getting classes for app %s: %j', app, err);
} else {
for(var i in theseClasses) if (theseClasses[i]) classes[i] = true;
}
cbEach();
});
}, function(err) {
callback(err, classes);
});
};
exports.isFixedFreq = function(app, useCache, callback) {
if (!callback && typeof useCache === 'function') {
callback = useCache;
useCache = false;
}
exports.getApp(app, useCache, function(err, appinfo) {
if (!appinfo || !appinfo.notes) return callback(null, false);
return callback(null, appinfo.hasOwnProperty('ExtraFast Sync'));
});
};
exports.areFixedFreq = function(apps, useCache, callback) {
if (!callback && typeof useCache === 'function') {
callback = useCache;
useCache = false;
}
var fixed = false;
async.forEach(apps, function(app, cbLoop) {
exports.isFixedFreq(app, useCache, function(err, isFixed) {
if (err) return cbLoop(err, isFixed);
if (isFixed) fixed = true;
cbLoop();
});
}, function(err) {
return callback(err, fixed);
});
};
// validate that the account has permission to the app first, or error
exports.getAppFor = function(appId, account, callback) {
exports.getApp(appId, function(err, app){
if (err) return callback(err);
if (!app) return callback("no such app");
if (!exports.hasAppPerms(account, app)) return callback("no permission");
callback(null, app);
});
};
// return the full list (used by dawg)
exports.getApps = function(callback) {
dal.query("SELECT app FROM Apps", [], function(err, rows) {
callback(err, rows);
});
};
// create a new app and generate it's keys
exports.addApp = function(notes, callback) {
// may want to encrypt something into this id someday
var app = (typeof notes.key === 'string' && notes.key.length > 0) ? notes.key : crypto.createHash('md5').update(Math.random().toString()).digest('hex');
var secret = crypto.createHash('md5').update(Math.random().toString()).digest('hex');
logger.debug("creating new app", app);
var q = dal.query("INSERT INTO Apps (app, secret, notes) VALUES (?, ?, ?)", [app, secret, JSON.stringify(notes)], function(err) {
if (err) logger.error(q, err);
if (err) return callback(err);
notes.key = app;
notes.secret = secret;
callback(null, notes);
});
};
// update the notes field which contains the user configurable data
exports.updateApp = function(appId, newNotes, newKeys, callback) {
logger.debug("updating app "+appId);
var q = dal.query("UPDATE Apps set notes=?, apikeys=? WHERE app=?", [JSON.stringify(newNotes), JSON.stringify(newKeys), appId], function(err) {
if (err) logger.error("query failed: ", q, err);
callback(err);
});
};
// remove a developer's app
exports.deleteApp = function(appId, callback) {
logger.debug("deleting app "+appId);
var q = dal.query("DELETE FROM Apps WHERE app=?", [appId], function(err) {
if (err) logger.error("query failed: ", q, err);
q = dal.query("DELETE FROM Accounts WHERE app=?", [appId], function(err) {
if (err) logger.error("query failed: ", q, err);
callback(err);
});
});
};
// for a given account, return all the profiles
exports.getProfiles = function(account, callback) {
logger.debug("getting account profiles "+account);
dal.query("SELECT profile FROM Accounts WHERE account = ?", [account], function(err, rows) {
rows = rows || [];
// TODO make this result set easier to use by indexing the service name mappings
callback(err, rows);
});
};
// for a given account, return all the profiles
exports.getManyProfiles = function(app, accounts, callback) {
logger.debug("getting many profiles ",app,accounts);
var ins = accounts.map(function(){
return '?';
}).join(',');
accounts.unshift(app);
dal.query("SELECT profile FROM Accounts WHERE app = ? and account in ("+ins+")", accounts, function(err, rows) {
rows = rows || [];
var ret = {};
rows.forEach(function(row){
ret[row.profile] = true;
});
callback(err, ret);
});
};
// Get just one profile for an account
exports.getProfile = function(account, pid, callback) {
logger.debug("getting account profile " + account + ', ' + pid);
dal.query("SELECT profile FROM Accounts WHERE account = ? AND profile = ?",
[account, pid], function(err, rows) {
callback(err, (rows || [])[0]);
});
};
// whackawhacka
exports.delProfiles = function(account, callback) {
logger.debug("deleting account profiles "+account);
dal.query("DELETE FROM Accounts WHERE account = ?", [account], callback);
};
// whackawhacka
exports.delProfile = function(account, pid, callback) {
logger.debug("deleting account profile ",account,pid);
dal.query("DELETE FROM Accounts WHERE account = ? AND profile = ?", [account, pid], callback);
};
|
import json
import re
#### READ LIST
def read_list(text,value_list=None,sep = ',',modifier_list_not=None):
if not modifier_list_not:
modifier_list_not = ['!', '~', 'not', 'Not', 'NOT']
text = text.strip()
negation = False
# Test for Not
if len(text) > 1 and text[0] in modifier_list_not :
text = text[1:-1]
negation = True
elif len(text) > 3 and text[:3] in modifier_list_not :
text = text[4:-1].strip()
negation = True
result_list = [x.strip().strip("'").strip('"') for x in text.split(sep)]
if negation :
if not value_list :
raise ValueError("Negation needs a value list to exclude items")
result_list = [x for x in value_list if x not in result_list]
return result_list
#### READ MAP
def read_map(text,sep = ',',):
list_maps = [x.strip() for x in text.split(sep)]
return {cm.split(':')[0].strip().strip("'").strip('"'): \
cm.split(':')[1].strip().strip("'").strip('"') for cm in list_maps}
#### READ JSON
def read_json(text) :
j = json.loads(text)
return j
#### READ Relation
def read_relation(text,sep=',',relation_map=None):
if not relation_map :
relation_map = {'!=': '!', '==': '=', '>=': '≥', '=>': '≥', '<=': '≤', '=<': '≤'}
for key,value in relation_map.items() :
text = text.replace(key,value)
text_list = text.split(sep)
print (text_list)
relation_list = list()
for selection in text_list:
m = re.match(u'(.+)\s*([<>!≤≥]+)\s*(.+)', selection)
if m:
left = m.group(1).strip().strip('"').strip("'")
right = float(m.group(3).strip())
relation = m.group(2).strip()
relation_list.append([left,relation,right])
else:
raise ValueError('Could not parse relation statement: ' + selection)
return relation_list
##############################
### MAIN
##############################
if __name__ == '__main__':
### list
text = "'Hello', 'a list', separated by , me"
not_text = "Not Mercedes, Renault, Citroen, Peugeaut, 'Rolls Royce'"
list2 = ['Mercedes', 'Audi', 'VW', 'Skoda', 'Renault', 'Citroen', 'Peugeot', 'Rolls Royce']
print('Not: ' + str(read_list(not_text, list2)))
print('All :' + str(read_list('All', list2)))
print('List: ' + str(read_list(text)))
### map
maplist = "'Mercedes':expensive, Audi:'sportiv', VW : 'people', Citroen:cool, 'Rolls Rocye': royal"
print('Map :' + str(read_map(maplist)))
### json
json_text = "{\"Luxury Class\": {\"Mercedes\":\"expensive\",\"Rolls Rocye\": \"royal\"}, \"High Middle Class\":{\"Audi\":\"sportiv\"}, \"Middle Class\": {}, \
\"Middle Class\" : {\"Citroen\":\"cool\",\"VW\" : \"people\" }}"
print('JSON: ' + str(read_json(json_text)))
### comparison
comparison = ' anna > 1.70, norbert != 900, cindy <= 1.65'
print('Comparison: ' + str(read_relation(comparison))) |
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const merge = require('webpack-merge');
const base = require('./webpack.base');
module.exports = merge(base, {
entry: {
'client': path.resolve(__dirname, '../src//entry-client.js')
},
plugins: [
new HtmlWebpackPlugin({
template: '../public/index.html'
})
]
}) |
const { MessageVisual } = require('discord.js-prompts')
const LocalizedPrompt = require('../common/utils/LocalizedPrompt.js')
const Translator = require('../../../structs/Translator.js')
const getConfig = require('../../../config.js').get
const createLogger = require('../../../util/logger/create.js')
/**
* @typedef {Object} Data
* @property {import('../../../structs/db/Feed.js')} selectedFeed
* @property {import('../../../structs/db/Profile.js')} profile
*/
/**
* @param {Data} data
*/
function setMessageVisual (data) {
const config = getConfig()
const profile = data.profile
const { locale } = profile || {}
const { text, url } = data.selectedFeed
const prefix = profile && profile.prefix ? profile.prefix : config.bot.prefix
let currentMsg = ''
if (text) {
currentMsg = '```Markdown\n' + text + '```'
} else {
currentMsg = `\`\`\`Markdown\n${Translator.translate('commands.text.noSetText', locale)}\n\n\`\`\`\`\`\`\n` + config.feeds.defaultText + '```'
}
return new MessageVisual(Translator.translate('commands.text.prompt', locale, {
prefix,
currentMsg,
link: url
}))
}
/**
* @param {import('discord.js').Message} message
* @param {Data} data
*/
async function setMessageFn (message, data) {
const text = message.content
const selectedFeed = data.selectedFeed
const log = createLogger(message.client.shard.ids[0])
if (text === 'reset') {
selectedFeed.text = undefined
} else {
selectedFeed.text = text
}
await selectedFeed.save()
log.info({
guild: message.guild,
text
}, `Text set for ${selectedFeed.url}`)
return data
}
const prompt = new LocalizedPrompt(setMessageVisual, setMessageFn)
exports.prompt = prompt
|
#
# The Python Imaging Library.
# $Id$
#
# MPO file handling
#
# See "Multi-Picture Format" (CIPA DC-007-Translation 2009, Standard of the
# Camera & Imaging Products Association)
#
# The multi-picture object combines multiple JPEG images (with a modified EXIF
# data format) into a single file. While it can theoretically be used much like
# a GIF animation, it is commonly used to represent 3D photographs and is (as
# of this writing) the most commonly used format by 3D cameras.
#
# History:
# 2014-03-13 Feneric Created
#
# See the README file for information on usage and redistribution.
#
from . import Image, ImageFile, JpegImagePlugin
from ._binary import i16be as i16
def _accept(prefix):
return JpegImagePlugin._accept(prefix)
def _save(im, fp, filename):
# Note that we can only save the current frame at present
return JpegImagePlugin._save(im, fp, filename)
##
# Image plugin for MPO images.
class MpoImageFile(JpegImagePlugin.JpegImageFile):
format = "MPO"
format_description = "MPO (CIPA DC-007)"
_close_exclusive_fp_after_loading = False
def _open(self):
self.fp.seek(0) # prep the fp in order to pass the JPEG test
JpegImagePlugin.JpegImageFile._open(self)
self._after_jpeg_open()
def _after_jpeg_open(self, mpheader=None):
self.mpinfo = mpheader if mpheader is not None else self._getmp()
self.n_frames = self.mpinfo[0xB001]
self.__mpoffsets = [
mpent["DataOffset"] + self.info["mpoffset"] for mpent in self.mpinfo[0xB002]
]
self.__mpoffsets[0] = 0
# Note that the following assertion will only be invalid if something
# gets broken within JpegImagePlugin.
assert self.n_frames == len(self.__mpoffsets)
del self.info["mpoffset"] # no longer needed
self.is_animated = self.n_frames > 1
self.__fp = self.fp # FIXME: hack
self.__fp.seek(self.__mpoffsets[0]) # get ready to read first frame
self.__frame = 0
self.offset = 0
# for now we can only handle reading and individual frame extraction
self.readonly = 1
def load_seek(self, pos):
self.__fp.seek(pos)
def seek(self, frame):
if not self._seek_check(frame):
return
self.fp = self.__fp
self.offset = self.__mpoffsets[frame]
self.fp.seek(self.offset + 2) # skip SOI marker
segment = self.fp.read(2)
if not segment:
raise ValueError("No data found for frame")
if i16(segment) == 0xFFE1: # APP1
n = i16(self.fp.read(2)) - 2
self.info["exif"] = ImageFile._safe_read(self.fp, n)
exif = self.getexif()
if 40962 in exif and 40963 in exif:
self._size = (exif[40962], exif[40963])
elif "exif" in self.info:
del self.info["exif"]
self.tile = [("jpeg", (0, 0) + self.size, self.offset, (self.mode, ""))]
self.__frame = frame
def tell(self):
return self.__frame
def _close__fp(self):
try:
if self.__fp != self.fp:
self.__fp.close()
except AttributeError:
pass
finally:
self.__fp = None
@staticmethod
def adopt(jpeg_instance, mpheader=None):
"""
Transform the instance of JpegImageFile into
an instance of MpoImageFile.
After the call, the JpegImageFile is extended
to be an MpoImageFile.
This is essentially useful when opening a JPEG
file that reveals itself as an MPO, to avoid
double call to _open.
"""
jpeg_instance.__class__ = MpoImageFile
jpeg_instance._after_jpeg_open(mpheader)
return jpeg_instance
# ---------------------------------------------------------------------
# Registry stuff
# Note that since MPO shares a factory with JPEG, we do not need to do a
# separate registration for it here.
# Image.register_open(MpoImageFile.format,
# JpegImagePlugin.jpeg_factory, _accept)
Image.register_save(MpoImageFile.format, _save)
Image.register_extension(MpoImageFile.format, ".mpo")
Image.register_mime(MpoImageFile.format, "image/mpo")
|
class ContributionsButton extends HyperHTMLElement {
created() {this.render()}
render() {
return this.html`
<a id="contributions-button"
class="fixed right-1 bottom-1 f6 link pointer br-pill ph3 pv2 gold bg-dark-gray animated bounceInRight"
onclick=${this}>Contribution Opportunities</a>`
}
onclick() {
const body = document.querySelector('body')
const modal = document.createElement('contributions-modal')
body.appendChild(modal)
ga('send', 'event', 'Contribution modal', 'opened')
}
}
ContributionsButton.define('contributions-button')
|
#!/usr/bin/env python3
#
# Copyright (c) 2016 Intel Corporation.
#
# SPDX-License-Identifier: Apache-2.0
import sys
import os
import copy
import threading
import re
try:
import ply.lex as lex
import ply.yacc as yacc
except ImportError:
print("PLY library for Python 3 not installed.")
print("Please install the python3-ply package using your workstation's")
print("package manager or the 'pip' tool.")
sys.exit(1)
reserved = {
'and' : 'AND',
'or' : 'OR',
'not' : 'NOT',
'in' : 'IN',
}
tokens = [
"HEX",
"STR",
"INTEGER",
"EQUALS",
"NOTEQUALS",
"LT",
"GT",
"LTEQ",
"GTEQ",
"OPAREN",
"CPAREN",
"OBRACKET",
"CBRACKET",
"COMMA",
"SYMBOL",
"COLON",
] + list(reserved.values())
def t_HEX(t):
r"0x[0-9a-fA-F]+"
t.value = str(int(t.value, 16))
return t
def t_INTEGER(t):
r"\d+"
t.value = str(int(t.value))
return t
def t_STR(t):
r'\"([^\\\n]|(\\.))*?\"|\'([^\\\n]|(\\.))*?\''
# nip off the quotation marks
t.value = t.value[1:-1]
return t
t_EQUALS = r"=="
t_NOTEQUALS = r"!="
t_LT = r"<"
t_GT = r">"
t_LTEQ = r"<="
t_GTEQ = r">="
t_OPAREN = r"[(]"
t_CPAREN = r"[)]"
t_OBRACKET = r"\["
t_CBRACKET = r"\]"
t_COMMA = r","
t_COLON = ":"
def t_SYMBOL(t):
r"[A-Za-z_][0-9A-Za-z_]*"
t.type = reserved.get(t.value, "SYMBOL")
return t
t_ignore = " \t\n"
def t_error(t):
raise SyntaxError("Unexpected token '%s'" % t.value)
lex.lex()
precedence = (
('left', 'OR'),
('left', 'AND'),
('right', 'NOT'),
('nonassoc' , 'EQUALS', 'NOTEQUALS', 'GT', 'LT', 'GTEQ', 'LTEQ', 'IN'),
)
def p_expr_or(p):
'expr : expr OR expr'
p[0] = ("or", p[1], p[3])
def p_expr_and(p):
'expr : expr AND expr'
p[0] = ("and", p[1], p[3])
def p_expr_not(p):
'expr : NOT expr'
p[0] = ("not", p[2])
def p_expr_parens(p):
'expr : OPAREN expr CPAREN'
p[0] = p[2]
def p_expr_eval(p):
"""expr : SYMBOL EQUALS const
| SYMBOL NOTEQUALS const
| SYMBOL GT number
| SYMBOL LT number
| SYMBOL GTEQ number
| SYMBOL LTEQ number
| SYMBOL IN list
| SYMBOL COLON STR"""
p[0] = (p[2], p[1], p[3])
def p_expr_single(p):
"""expr : SYMBOL"""
p[0] = ("exists", p[1])
def p_list(p):
"""list : OBRACKET list_intr CBRACKET"""
p[0] = p[2]
def p_list_intr_single(p):
"""list_intr : const"""
p[0] = [p[1]]
def p_list_intr_mult(p):
"""list_intr : list_intr COMMA const"""
p[0] = copy.copy(p[1])
p[0].append(p[3])
def p_const(p):
"""const : STR
| number"""
p[0] = p[1]
def p_number(p):
"""number : INTEGER
| HEX"""
p[0] = p[1]
def p_error(p):
if p:
raise SyntaxError("Unexpected token '%s'" % p.value)
else:
raise SyntaxError("Unexpected end of expression")
if "PARSETAB_DIR" not in os.environ:
parser = yacc.yacc(debug=0)
else:
parser = yacc.yacc(debug=0, outputdir=os.environ["PARSETAB_DIR"])
def ast_sym(ast, env):
if ast in env:
return str(env[ast])
return ""
def ast_sym_int(ast, env):
if ast in env:
v = env[ast]
if v.startswith("0x") or v.startswith("0X"):
return int(v, 16)
else:
return int(v, 10)
return 0
def ast_expr(ast, env):
if ast[0] == "not":
return not ast_expr(ast[1], env)
elif ast[0] == "or":
return ast_expr(ast[1], env) or ast_expr(ast[2], env)
elif ast[0] == "and":
return ast_expr(ast[1], env) and ast_expr(ast[2], env)
elif ast[0] == "==":
return ast_sym(ast[1], env) == ast[2]
elif ast[0] == "!=":
return ast_sym(ast[1], env) != ast[2]
elif ast[0] == ">":
return ast_sym_int(ast[1], env) > int(ast[2])
elif ast[0] == "<":
return ast_sym_int(ast[1], env) < int(ast[2])
elif ast[0] == ">=":
return ast_sym_int(ast[1], env) >= int(ast[2])
elif ast[0] == "<=":
return ast_sym_int(ast[1], env) <= int(ast[2])
elif ast[0] == "in":
return ast_sym(ast[1], env) in ast[2]
elif ast[0] == "exists":
return True if ast_sym(ast[1], env) else False
elif ast[0] == ":":
return True if re.compile(ast[2]).match(ast_sym(ast[1], env)) else False
mutex = threading.Lock()
def parse(expr_text, env):
"""Given a text representation of an expression in our language,
use the provided environment to determine whether the expression
is true or false"""
# Like it's C counterpart, state machine is not thread-safe
mutex.acquire()
try:
ast = parser.parse(expr_text)
finally:
mutex.release()
return ast_expr(ast, env)
# Just some test code
if __name__ == "__main__":
local_env = {
"A" : "1",
"C" : "foo",
"D" : "20",
"E" : 0x100,
"F" : "baz"
}
for line in open(sys.argv[1]).readlines():
lex.input(line)
for tok in iter(lex.token, None):
print(tok.type, tok.value)
parser = yacc.yacc()
print(parser.parse(line))
print(parse(line, local_env))
|
import cv2
import numpy
# Camera resolution to capture at
width = 240
height = 160
def process_stream(processor):
#Camera buffers and handle
camera = cv2.VideoCapture(0)
camera.set(cv2.CAP_PROP_FRAME_WIDTH, width)
camera.set(cv2.CAP_PROP_FRAME_HEIGHT, height)
img = None
while True:
retval, img = camera.read(img)
if processor.should_process():
processor.process(img)
|
'use strict'
import * as FormActions from './formActions'
export const ActionCreator = Object.assign({},
// add all action creators here
FormActions
)
|
/**
* Represents a special return value during commmand execution or argument parsing.
* @param {string} type - Type of flag.
* @param {any} [data={}] - Extra data.
*/
class Flag {
constructor(type, data = {}) {
this.type = type;
Object.assign(this, data);
}
/**
* Creates a flag that cancels the command.
* @returns {Flag}
*/
static cancel() {
return new Flag("cancel");
}
/**
* Creates a flag that retries with another input.
* @param {Message} message - Message to handle.
* @returns {Flag}
*/
static retry(message) {
return new Flag("retry", { message });
}
/**
* Creates a flag that acts as argument cast failure with extra data.
* @param {any} value - The extra data for the failure.
* @returns {Flag}
*/
static fail(value) {
return new Flag("fail", { value });
}
/**
* Creates a flag that runs another command with the rest of the arguments.
* @param {string} command - Command ID.
* @param {boolean} [ignore=false] - Whether or not to ignore permission checks.
* @param {string} [rest] - The rest of the arguments.
* If this is not set, the argument handler will automatically use the rest of the content.
* @returns {Flag}
*/
static continue(command, ignore = false, rest = null) {
return new Flag("continue", { command, ignore, rest });
}
/**
* Checks if a value is a flag and of some type.
* @param {any} value - Value to check.
* @param {string} type - Type of flag.
* @returns {boolean}
*/
static is(value, type) {
return value instanceof Flag && value.type === type;
}
}
module.exports = Flag;
|
/**
*
* Copyright (c) 2020 Silicon Labs
*
* 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.
*
*
* @jest-environment node
*/
const fs = require('fs')
const path = require('path')
const axios = require('axios')
const dbApi = require('../src-electron/db/db-api.js')
const dbEnum = require('../src-shared/db-enum.js')
const queryLoader = require('../src-electron/db/query-loader.js')
const queryPackage = require('../src-electron/db/query-package.js')
const querySession = require('../src-electron/db/query-session.js')
const httpServer = require('../src-electron/server/http-server.js')
const env = require('../src-electron/util/env.js')
const exportJs = require('../src-electron/importexport/export.js')
const importJs = require('../src-electron/importexport/import.js')
const restApi = require('../src-shared/rest-api.js')
const testUtil = require('./test-util.js')
const testQuery = require('./test-query.js')
const _ = require('lodash')
const util = require('../src-electron/util/util.js')
let db
const { port, baseUrl } = testUtil.testServer(__filename)
let packageId
let sessionId, secondSessionId
let sessionCookie = null
let axiosInstance = null
let uuid = util.createUuid()
beforeAll(async () => {
env.setDevelopmentEnv()
let file = env.sqliteTestFile('server')
axiosInstance = axios.create({ baseURL: baseUrl })
db = await dbApi.initDatabaseAndLoadSchema(
file,
env.schemaFile(),
env.zapVersion()
)
}, testUtil.timeout.medium())
afterAll(
() => httpServer.shutdownHttpServer().then(() => dbApi.closeDatabase(db)),
testUtil.timeout.medium()
)
describe('Session specific tests', () => {
test(
'make sure there is no session at the beginning',
() =>
testQuery.selectCountFrom(db, 'SESSION').then((cnt) => {
expect(cnt).toBe(0)
}),
testUtil.timeout.short()
)
test(
'http server initialization',
() => httpServer.initHttpServer(db, port),
testUtil.timeout.medium()
)
test(
'get index.html',
() =>
axiosInstance.get('/index.html').then((response) => {
sessionCookie = response.headers['set-cookie'][0]
axiosInstance.defaults.headers.Cookie = sessionCookie
expect(
response.data.includes(
'Configuration tool for the Zigbee Cluster Library'
)
).toBeTruthy()
}),
testUtil.timeout.medium()
)
test(
'make sure there is still no session after index.html',
() =>
testQuery.selectCountFrom(db, 'SESSION').then((cnt) => {
expect(cnt).toBe(0)
}),
testUtil.timeout.medium()
)
test(
'test that there is 0 clusters initially',
() =>
axiosInstance
.get(`${restApi.uri.zclCluster}all?sessionId=${uuid}`)
.then((response) => {
expect(response.data.clusterData.length).toBe(0)
}),
testUtil.timeout.medium()
)
test(
'make sure there is 1 session after previous call',
() =>
testQuery.selectCountFrom(db, 'SESSION').then((cnt) => {
expect(cnt).toBe(1)
}),
testUtil.timeout.medium()
)
test(
'save session',
() =>
querySession.getAllSessions(db).then((results) => {
sessionId = results[0].sessionId
}),
testUtil.timeout.medium()
)
test(
'add a package',
() =>
queryPackage
.insertPathCrc(db, 'PATH', 32, dbEnum.packageType.zclProperties)
.then((pkg) => {
packageId = pkg
})
.then(() =>
queryPackage.insertSessionPackage(db, sessionId, packageId)
),
testUtil.timeout.medium()
)
test(
'load 2 clusters',
() =>
queryLoader.insertClusters(db, packageId, [
{
code: 0x1111,
name: 'One',
description: 'Cluster one',
define: 'ONE',
},
{
code: 0x2222,
name: 'Two',
description: 'Cluster two',
define: 'TWO',
},
]),
testUtil.timeout.medium()
)
test(
'test that there are 2 clusters now',
() =>
axiosInstance
.get(`${restApi.uri.zclCluster}all?sessionId=${uuid}`)
.then((response) => {
expect(response.data.clusterData.length).toBe(2)
}),
testUtil.timeout.medium()
)
test(
'make sure there is still 1 session after previous call',
() =>
testQuery.selectCountFrom(db, 'SESSION').then((cnt) => {
expect(cnt).toBe(1)
}),
testUtil.timeout.medium()
)
test(
'load domains',
() =>
queryLoader.insertDomains(db, packageId, [
{ name: 'one' },
{ name: 'two' },
{ name: 'three' },
{ name: 'four' },
]),
testUtil.timeout.medium()
)
test(
'test that there are domains',
() =>
axiosInstance
.get(`${restApi.uri.zclDomain}all?sessionId=${uuid}`)
.then((response) => {
expect(response.data.length).toBe(4)
}),
testUtil.timeout.medium()
)
// We save and then load, which creates a new session.
test(
'save into a file and load from file',
() => {
let f = path.join(env.appDirectory(), 'test-output.json')
if (fs.existsSync(f)) fs.unlinkSync(f)
expect(fs.existsSync(f)).toBeFalsy()
return exportJs
.exportDataIntoFile(db, sessionId, f)
.then(() => {
expect(fs.existsSync(f)).toBeTruthy()
})
.then(() => importJs.importDataFromFile(db, f))
.then((importResult) => {
secondSessionId = importResult.sessionId
fs.unlinkSync(f)
return Promise.resolve(1)
})
},
testUtil.timeout.medium()
)
// After a new file is loaded a new session will be created.
// Therefore, at this point, there have to be EXACTLY 2 sessions.
test(
'make sure there is now 2 sessions after previous call',
() =>
testQuery.selectCountFrom(db, 'SESSION').then((cnt) => {
expect(cnt).toBe(2)
}),
testUtil.timeout.medium()
)
test(
'delete the first session',
() =>
querySession
.deleteSession(db, sessionId)
.then(() => testQuery.selectCountFrom(db, 'SESSION'))
.then((cnt) => {
expect(cnt).toBe(1)
}),
testUtil.timeout.medium()
)
test(
'delete the second session',
() =>
querySession
.deleteSession(db, secondSessionId)
.then(() => testQuery.selectCountFrom(db, 'SESSION'))
.then((cnt) => {
expect(cnt).toBe(0)
}),
testUtil.timeout.medium()
)
})
describe('Miscelaneous REST API tests', () => {
test(
'test initial state',
() =>
axiosInstance.get(restApi.uri.initialState).then((response) => {
expect(response.data).not.toBeNull()
expect('endpoints' in response.data).toBeTruthy()
expect('endpointTypes' in response.data).toBeTruthy()
expect('sessionKeyValues' in response.data).toBeTruthy()
}),
testUtil.timeout.medium()
)
})
describe('Admin tests', () => {
test(
'test sql admin interface',
() =>
axiosInstance
.post('/sql', { sql: 'SELECT * FROM PACKAGE' })
.then((response) => {
expect(response).not.toBeNull()
expect(response.data.result).not.toBeNull()
expect(response.data.result.length).toBeGreaterThan(1)
}),
testUtil.timeout.medium()
)
test(
'test version interface',
() =>
axiosInstance.get('version').then((response) => {
expect(response.data).toEqual(env.zapVersion())
}),
testUtil.timeout.medium()
)
})
describe('User and session tests', () => {
let userId
let sessionId
test(
'create new user session',
async () => {
// New session
let userSession = await querySession.ensureZapUserAndSession(
db,
'user1',
'session1'
)
userId = userSession.userId
sessionId = userSession.sessionId
expect(userId).not.toBeNull()
expect(sessionId).not.toBeNull()
let sessions = await querySession.getUserSessions(db, userId)
expect(sessions.length).toBe(1)
},
testUtil.timeout.medium()
)
test(
'create new session for existing user',
async () => {
let userSession = await querySession.ensureZapUserAndSession(
db,
'user1',
'session2',
{
userId: userId,
}
)
expect(userSession.userId).toEqual(userId)
expect(userSession.sessionId).not.toBeNull()
expect(userSession.sessionId).not.toEqual(sessionId)
let sessions = await querySession.getUserSessions(db, userId)
expect(sessions.length).toBe(2)
},
testUtil.timeout.medium()
)
test(
'create new user for existing session',
async () => {
let userSession = await querySession.ensureZapUserAndSession(
db,
'user2',
'session1',
{
sessionId: sessionId,
}
)
expect(userSession.userId).not.toBeNull()
expect(userSession.userId).not.toEqual(userId)
expect(userSession.sessionId).toEqual(sessionId)
let sessions = await querySession.getUserSessions(db, userId)
expect(sessions.length).toBe(1)
sessions = await querySession.getUserSessions(db, userSession.userId)
expect(sessions.length).toBe(1)
},
testUtil.timeout.medium()
)
test(
'reuse existing user and session',
async () => {
let userSession = await querySession.ensureZapUserAndSession(
db,
'user1',
'session1',
{
sessionId: sessionId,
userId: userId,
}
)
expect(userSession.userId).toEqual(userId)
expect(userSession.sessionId).toEqual(sessionId)
let sessions = await querySession.getUserSessions(db, userId)
expect(sessions.length).toBe(1)
},
testUtil.timeout.medium()
)
})
|
'use strict';
/* jshint ignore:start */
/**
* This code was generated by
* \ / _ _ _| _ _
* | (_)\/(_)(_|\/| |(/_ v1.0.0
* / /
*/
/* jshint ignore:end */
var Holodeck = require('../../../../holodeck'); /* jshint ignore:line */
var Request = require(
'../../../../../../lib/http/request'); /* jshint ignore:line */
var Response = require(
'../../../../../../lib/http/response'); /* jshint ignore:line */
var RestException = require(
'../../../../../../lib/base/RestException'); /* jshint ignore:line */
var Twilio = require('../../../../../../lib'); /* jshint ignore:line */
var client;
var holodeck;
describe('IncomingPhoneNumber', function() {
beforeEach(function() {
holodeck = new Holodeck();
client = new Twilio('ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', 'AUTHTOKEN', {
httpClient: holodeck
});
});
it('should generate valid update request',
function(done) {
holodeck.mock(new Response(500, '{}'));
var promise = client.api.v2010.accounts('ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX')
.incomingPhoneNumbers('PNXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX').update();
promise.then(function() {
throw new Error('failed');
}, function(error) {
expect(error.constructor).toBe(RestException.prototype.constructor);
done();
}).done();
var accountSid = 'ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX';
var sid = 'PNXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX';
var url = `https://api.twilio.com/2010-04-01/Accounts/${accountSid}/IncomingPhoneNumbers/${sid}.json`;
holodeck.assertHasRequest(new Request({
method: 'POST',
url: url
}));
}
);
it('should generate valid update response',
function(done) {
var body = JSON.stringify({
'account_sid': 'ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa',
'address_requirements': 'none',
'address_sid': 'ADaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa',
'api_version': '2010-04-01',
'beta': false,
'capabilities': {
'mms': true,
'sms': false,
'voice': true
},
'date_created': 'Thu, 30 Jul 2015 23:19:04 +0000',
'date_updated': 'Thu, 30 Jul 2015 23:19:04 +0000',
'emergency_status': 'Inactive',
'emergency_address_sid': 'ADaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa',
'friendly_name': '(808) 925-5327',
'identity_sid': 'RIaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa',
'origin': 'origin',
'phone_number': '+18089255327',
'sid': 'PNaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa',
'sms_application_sid': '',
'sms_fallback_method': 'POST',
'sms_fallback_url': '',
'sms_method': 'POST',
'sms_url': '',
'status_callback': '',
'status_callback_method': 'POST',
'trunk_sid': null,
'uri': '/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/IncomingPhoneNumbers/PNaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.json',
'voice_application_sid': '',
'voice_caller_id_lookup': false,
'voice_fallback_method': 'POST',
'voice_fallback_url': null,
'voice_method': 'POST',
'voice_url': null,
'bundle_sid': 'BUaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa'
});
holodeck.mock(new Response(200, body));
var promise = client.api.v2010.accounts('ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX')
.incomingPhoneNumbers('PNXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX').update();
promise.then(function(response) {
expect(response).toBeDefined();
done();
}, function() {
throw new Error('failed');
}).done();
}
);
it('should generate valid fetch request',
function(done) {
holodeck.mock(new Response(500, '{}'));
var promise = client.api.v2010.accounts('ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX')
.incomingPhoneNumbers('PNXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX').fetch();
promise.then(function() {
throw new Error('failed');
}, function(error) {
expect(error.constructor).toBe(RestException.prototype.constructor);
done();
}).done();
var accountSid = 'ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX';
var sid = 'PNXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX';
var url = `https://api.twilio.com/2010-04-01/Accounts/${accountSid}/IncomingPhoneNumbers/${sid}.json`;
holodeck.assertHasRequest(new Request({
method: 'GET',
url: url
}));
}
);
it('should generate valid fetch response',
function(done) {
var body = JSON.stringify({
'account_sid': 'ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa',
'address_requirements': 'none',
'address_sid': 'ADaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa',
'api_version': '2010-04-01',
'beta': false,
'capabilities': {
'mms': true,
'sms': false,
'voice': true
},
'date_created': 'Thu, 30 Jul 2015 23:19:04 +0000',
'date_updated': 'Thu, 30 Jul 2015 23:19:04 +0000',
'emergency_status': 'Active',
'emergency_address_sid': 'ADaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa',
'friendly_name': '(808) 925-5327',
'identity_sid': 'RIaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa',
'origin': 'origin',
'phone_number': '+18089255327',
'sid': 'PNaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa',
'sms_application_sid': '',
'sms_fallback_method': 'POST',
'sms_fallback_url': '',
'sms_method': 'POST',
'sms_url': '',
'status_callback': '',
'status_callback_method': 'POST',
'trunk_sid': null,
'uri': '/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/IncomingPhoneNumbers/PNaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.json',
'voice_application_sid': '',
'voice_caller_id_lookup': false,
'voice_fallback_method': 'POST',
'voice_fallback_url': null,
'voice_method': 'POST',
'voice_url': null,
'bundle_sid': 'BUaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa'
});
holodeck.mock(new Response(200, body));
var promise = client.api.v2010.accounts('ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX')
.incomingPhoneNumbers('PNXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX').fetch();
promise.then(function(response) {
expect(response).toBeDefined();
done();
}, function() {
throw new Error('failed');
}).done();
}
);
it('should generate valid remove request',
function(done) {
holodeck.mock(new Response(500, '{}'));
var promise = client.api.v2010.accounts('ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX')
.incomingPhoneNumbers('PNXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX').remove();
promise.then(function() {
throw new Error('failed');
}, function(error) {
expect(error.constructor).toBe(RestException.prototype.constructor);
done();
}).done();
var accountSid = 'ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX';
var sid = 'PNXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX';
var url = `https://api.twilio.com/2010-04-01/Accounts/${accountSid}/IncomingPhoneNumbers/${sid}.json`;
holodeck.assertHasRequest(new Request({
method: 'DELETE',
url: url
}));
}
);
it('should generate valid delete response',
function(done) {
var body = JSON.stringify(null);
holodeck.mock(new Response(204, body));
var promise = client.api.v2010.accounts('ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX')
.incomingPhoneNumbers('PNXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX').remove();
promise.then(function(response) {
expect(response).toBe(true);
done();
}, function() {
throw new Error('failed');
}).done();
}
);
it('should treat the first each arg as a callback',
function(done) {
var body = JSON.stringify({
'end': 0,
'first_page_uri': '/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/IncomingPhoneNumbers.json?PageSize=1&Page=0',
'incoming_phone_numbers': [
{
'account_sid': 'ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa',
'address_requirements': 'none',
'address_sid': 'ADaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa',
'api_version': '2010-04-01',
'beta': null,
'capabilities': {
'mms': true,
'sms': false,
'voice': true
},
'date_created': 'Thu, 30 Jul 2015 23:19:04 +0000',
'date_updated': 'Thu, 30 Jul 2015 23:19:04 +0000',
'emergency_status': 'Active',
'emergency_address_sid': 'ADaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa',
'friendly_name': '(808) 925-5327',
'identity_sid': 'RIaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa',
'origin': 'origin',
'phone_number': '+18089255327',
'sid': 'PNaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa',
'sms_application_sid': '',
'sms_fallback_method': 'POST',
'sms_fallback_url': '',
'sms_method': 'POST',
'sms_url': '',
'status_callback': '',
'status_callback_method': 'POST',
'trunk_sid': null,
'uri': '/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/IncomingPhoneNumbers/PNaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.json',
'voice_application_sid': '',
'voice_caller_id_lookup': false,
'voice_fallback_method': 'POST',
'voice_fallback_url': null,
'voice_method': 'POST',
'voice_url': null,
'bundle_sid': 'BUaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa'
}
],
'last_page_uri': '/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/IncomingPhoneNumbers.json?PageSize=1&Page=2',
'next_page_uri': null,
'num_pages': 3,
'page': 0,
'page_size': 1,
'previous_page_uri': null,
'start': 0,
'total': 3,
'uri': '/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/IncomingPhoneNumbers.json?PageSize=1'
});
holodeck.mock(new Response(200, body));
client.api.v2010.accounts('ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX')
.incomingPhoneNumbers.each(() => done());
}
);
it('should treat the second arg as a callback',
function(done) {
var body = JSON.stringify({
'end': 0,
'first_page_uri': '/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/IncomingPhoneNumbers.json?PageSize=1&Page=0',
'incoming_phone_numbers': [
{
'account_sid': 'ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa',
'address_requirements': 'none',
'address_sid': 'ADaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa',
'api_version': '2010-04-01',
'beta': null,
'capabilities': {
'mms': true,
'sms': false,
'voice': true
},
'date_created': 'Thu, 30 Jul 2015 23:19:04 +0000',
'date_updated': 'Thu, 30 Jul 2015 23:19:04 +0000',
'emergency_status': 'Active',
'emergency_address_sid': 'ADaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa',
'friendly_name': '(808) 925-5327',
'identity_sid': 'RIaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa',
'origin': 'origin',
'phone_number': '+18089255327',
'sid': 'PNaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa',
'sms_application_sid': '',
'sms_fallback_method': 'POST',
'sms_fallback_url': '',
'sms_method': 'POST',
'sms_url': '',
'status_callback': '',
'status_callback_method': 'POST',
'trunk_sid': null,
'uri': '/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/IncomingPhoneNumbers/PNaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.json',
'voice_application_sid': '',
'voice_caller_id_lookup': false,
'voice_fallback_method': 'POST',
'voice_fallback_url': null,
'voice_method': 'POST',
'voice_url': null,
'bundle_sid': 'BUaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa'
}
],
'last_page_uri': '/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/IncomingPhoneNumbers.json?PageSize=1&Page=2',
'next_page_uri': null,
'num_pages': 3,
'page': 0,
'page_size': 1,
'previous_page_uri': null,
'start': 0,
'total': 3,
'uri': '/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/IncomingPhoneNumbers.json?PageSize=1'
});
holodeck.mock(new Response(200, body));
client.api.v2010.accounts('ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX')
.incomingPhoneNumbers.each({pageSize: 20}, () => done());
holodeck.assertHasRequest(new Request({
method: 'GET',
url: 'https://api.twilio.com/2010-04-01/Accounts/${accountSid}/IncomingPhoneNumbers.json',
params: {PageSize: 20},
}));
}
);
it('should find the callback in the opts object',
function(done) {
var body = JSON.stringify({
'end': 0,
'first_page_uri': '/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/IncomingPhoneNumbers.json?PageSize=1&Page=0',
'incoming_phone_numbers': [
{
'account_sid': 'ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa',
'address_requirements': 'none',
'address_sid': 'ADaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa',
'api_version': '2010-04-01',
'beta': null,
'capabilities': {
'mms': true,
'sms': false,
'voice': true
},
'date_created': 'Thu, 30 Jul 2015 23:19:04 +0000',
'date_updated': 'Thu, 30 Jul 2015 23:19:04 +0000',
'emergency_status': 'Active',
'emergency_address_sid': 'ADaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa',
'friendly_name': '(808) 925-5327',
'identity_sid': 'RIaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa',
'origin': 'origin',
'phone_number': '+18089255327',
'sid': 'PNaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa',
'sms_application_sid': '',
'sms_fallback_method': 'POST',
'sms_fallback_url': '',
'sms_method': 'POST',
'sms_url': '',
'status_callback': '',
'status_callback_method': 'POST',
'trunk_sid': null,
'uri': '/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/IncomingPhoneNumbers/PNaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.json',
'voice_application_sid': '',
'voice_caller_id_lookup': false,
'voice_fallback_method': 'POST',
'voice_fallback_url': null,
'voice_method': 'POST',
'voice_url': null,
'bundle_sid': 'BUaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa'
}
],
'last_page_uri': '/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/IncomingPhoneNumbers.json?PageSize=1&Page=2',
'next_page_uri': null,
'num_pages': 3,
'page': 0,
'page_size': 1,
'previous_page_uri': null,
'start': 0,
'total': 3,
'uri': '/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/IncomingPhoneNumbers.json?PageSize=1'
});
holodeck.mock(new Response(200, body));
client.api.v2010.accounts('ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX')
.incomingPhoneNumbers.each({callback: () => done()}, () => fail('wrong callback!'));
}
);
it('should generate valid list request',
function(done) {
holodeck.mock(new Response(500, '{}'));
var promise = client.api.v2010.accounts('ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX')
.incomingPhoneNumbers.list();
promise.then(function() {
throw new Error('failed');
}, function(error) {
expect(error.constructor).toBe(RestException.prototype.constructor);
done();
}).done();
var accountSid = 'ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX';
var url = `https://api.twilio.com/2010-04-01/Accounts/${accountSid}/IncomingPhoneNumbers.json`;
holodeck.assertHasRequest(new Request({
method: 'GET',
url: url
}));
}
);
it('should generate valid read_full response',
function(done) {
var body = JSON.stringify({
'end': 0,
'first_page_uri': '/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/IncomingPhoneNumbers.json?PageSize=1&Page=0',
'incoming_phone_numbers': [
{
'account_sid': 'ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa',
'address_requirements': 'none',
'address_sid': 'ADaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa',
'api_version': '2010-04-01',
'beta': null,
'capabilities': {
'mms': true,
'sms': false,
'voice': true
},
'date_created': 'Thu, 30 Jul 2015 23:19:04 +0000',
'date_updated': 'Thu, 30 Jul 2015 23:19:04 +0000',
'emergency_status': 'Active',
'emergency_address_sid': 'ADaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa',
'friendly_name': '(808) 925-5327',
'identity_sid': 'RIaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa',
'origin': 'origin',
'phone_number': '+18089255327',
'sid': 'PNaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa',
'sms_application_sid': '',
'sms_fallback_method': 'POST',
'sms_fallback_url': '',
'sms_method': 'POST',
'sms_url': '',
'status_callback': '',
'status_callback_method': 'POST',
'trunk_sid': null,
'uri': '/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/IncomingPhoneNumbers/PNaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.json',
'voice_application_sid': '',
'voice_caller_id_lookup': false,
'voice_fallback_method': 'POST',
'voice_fallback_url': null,
'voice_method': 'POST',
'voice_url': null,
'bundle_sid': 'BUaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa'
}
],
'last_page_uri': '/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/IncomingPhoneNumbers.json?PageSize=1&Page=2',
'next_page_uri': null,
'num_pages': 3,
'page': 0,
'page_size': 1,
'previous_page_uri': null,
'start': 0,
'total': 3,
'uri': '/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/IncomingPhoneNumbers.json?PageSize=1'
});
holodeck.mock(new Response(200, body));
var promise = client.api.v2010.accounts('ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX')
.incomingPhoneNumbers.list();
promise.then(function(response) {
expect(response).toBeDefined();
done();
}, function() {
throw new Error('failed');
}).done();
}
);
it('should generate valid read_empty response',
function(done) {
var body = JSON.stringify({
'end': 0,
'first_page_uri': '/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/IncomingPhoneNumbers.json?PageSize=1&Page=0',
'incoming_phone_numbers': [],
'last_page_uri': '/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/IncomingPhoneNumbers.json?PageSize=1&Page=2',
'next_page_uri': null,
'num_pages': 3,
'page': 0,
'page_size': 1,
'previous_page_uri': null,
'start': 0,
'total': 3,
'uri': '/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/IncomingPhoneNumbers.json?PageSize=1'
});
holodeck.mock(new Response(200, body));
var promise = client.api.v2010.accounts('ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX')
.incomingPhoneNumbers.list();
promise.then(function(response) {
expect(response).toBeDefined();
done();
}, function() {
throw new Error('failed');
}).done();
}
);
it('should generate valid create request',
function(done) {
holodeck.mock(new Response(500, '{}'));
var promise = client.api.v2010.accounts('ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX')
.incomingPhoneNumbers.create();
promise.then(function() {
throw new Error('failed');
}, function(error) {
expect(error.constructor).toBe(RestException.prototype.constructor);
done();
}).done();
var accountSid = 'ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX';
var url = `https://api.twilio.com/2010-04-01/Accounts/${accountSid}/IncomingPhoneNumbers.json`;
holodeck.assertHasRequest(new Request({
method: 'POST',
url: url
}));
}
);
it('should generate valid create response',
function(done) {
var body = JSON.stringify({
'account_sid': 'ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa',
'address_requirements': 'none',
'address_sid': 'ADaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa',
'api_version': '2010-04-01',
'beta': false,
'capabilities': {
'mms': true,
'sms': false,
'voice': true
},
'date_created': 'Thu, 30 Jul 2015 23:19:04 +0000',
'date_updated': 'Thu, 30 Jul 2015 23:19:04 +0000',
'emergency_status': 'Active',
'emergency_address_sid': 'ADaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa',
'friendly_name': '(808) 925-5327',
'identity_sid': 'RIaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa',
'origin': 'origin',
'phone_number': '+18089255327',
'sid': 'PNaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa',
'sms_application_sid': '',
'sms_fallback_method': 'POST',
'sms_fallback_url': '',
'sms_method': 'POST',
'sms_url': '',
'status_callback': '',
'status_callback_method': 'POST',
'trunk_sid': null,
'uri': '/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/IncomingPhoneNumbers/PNaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.json',
'voice_application_sid': '',
'voice_caller_id_lookup': false,
'voice_fallback_method': 'POST',
'voice_fallback_url': null,
'voice_method': 'POST',
'voice_url': null,
'bundle_sid': 'BUaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa'
});
holodeck.mock(new Response(201, body));
var promise = client.api.v2010.accounts('ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX')
.incomingPhoneNumbers.create();
promise.then(function(response) {
expect(response).toBeDefined();
done();
}, function() {
throw new Error('failed');
}).done();
}
);
});
|
/*
* This file is used to prevent cluttering of the main index file
* Routes used in web application are defined here
* Created by Ahmed Farghaly
*/
// Requiring necessarily files
var express = require("express");
var router = express.Router(); // to break the routes out into little modular chunks. we will require them back in the index.js (main file).
var db = require("../models");
var helpers = require("../helpers/todos");
// Defining Routes
// GET and POST routes
router.route('/')
.get(helpers.getTodos)
.post(helpers.createTodos);
// Show, Update, and Delete Routes
router.route('/:todoId')
.get(helpers.getTodo)
.put(helpers.updateTodo)
.delete(helpers.deleteTodo);
module.exports = router; |
/**
* Hilo 1.4.0 for commonjs
* Copyright 2016 alibaba.com
* Licensed under the MIT License
*/
var Class=require("../core/Class"),Hilo=require("../core/Hilo"),Renderer=require("./Renderer"),CanvasRenderer=Class.create({Extends:Renderer,constructor:function(e){CanvasRenderer.superclass.constructor.call(this,e),this.context=this.canvas.getContext("2d")},renderType:"canvas",context:null,startDraw:function(e){return!!(e.visible&&e.alpha>0)&&(e===this.stage&&this.context.clearRect(0,0,e.width,e.height),e.blendMode!==this.blendMode&&(this.context.globalCompositeOperation=this.blendMode=e.blendMode),this.context.save(),!0)},draw:function(e){var t=this.context,a=e.width,r=e.height,i=e.background;i&&(t.fillStyle=i,t.fillRect(0,0,a,r));var n=e.drawable,s=n&&n.image;if(s){var l=n.rect,o=l[2],c=l[3],h=l[4],d=l[5];if(!o||!c)return;a||r||(a=e.width=o,r=e.height=c),(h||d)&&t.translate(h-.5*o,d-.5*c),t.drawImage(s,l[0],l[1],o,c,0,0,a,r)}},endDraw:function(e){this.context.restore()},transform:function(e){var t=e.drawable;if(t&&t.domElement)return void Hilo.setElementStyleByView(e);var a=this.context,r=e.scaleX,i=e.scaleY;if(e===this.stage){var n=this.canvas.style,s=e._scaleX,l=e._scaleY,o=!1;(!s&&1!=r||s&&s!=r)&&(e._scaleX=r,n.width=r*e.width+"px",o=!0),(!l&&1!=i||l&&l!=i)&&(e._scaleY=i,n.height=i*e.height+"px",o=!0),o&&e.updateViewport()}else{var c=e.x,h=e.y,d=e.pivotX,v=e.pivotY,u=e.rotation%360,g=e.transform,f=e.mask;f&&(f._render(this),a.clip());var p=e.align;if(p){var x=e.getAlignPosition();c=x.x,h=x.y}g?a.transform(g.a,g.b,g.c,g.d,g.tx,g.ty):(0==c&&0==h||a.translate(c,h),0!=u&&a.rotate(u*Math.PI/180),1==r&&1==i||a.scale(r,i),0==d&&0==v||a.translate(-d,-v))}e.alpha>0&&(a.globalAlpha*=e.alpha)},remove:function(e){var t=e.drawable,a=t&&t.domElement;if(a){var r=a.parentNode;r&&r.removeChild(a)}},clear:function(e,t,a,r){this.context.clearRect(e,t,a,r)},resize:function(e,t){var a=this.canvas,r=this.stage,i=a.style;a.width=e,a.height=t,i.width=r.width*r.scaleX+"px",i.height=r.height*r.scaleY+"px"}});module.exports=CanvasRenderer; |
/*!
* UI development toolkit for HTML5 (OpenUI5)
* (c) Copyright 2009-2016 SAP SE or an SAP affiliate company.
* Licensed under the Apache License, Version 2.0 - see LICENSE.txt.
*/
// Provides object sap.ui.model.odata.AnnotationHelper
sap.ui.define([
"jquery.sap.global",
"sap/ui/base/BindingParser",
"./_AnnotationHelperBasics",
"./_AnnotationHelperExpression"
], function(jQuery, BindingParser, Basics, Expression) {
'use strict';
/**
* Returns a function representing the composition <code>fnAfter</code> after
* <code>fnBefore</code>.
*
* @param {function} fnAfter
* the second function, taking a single argument
* @param {function} [fnBefore]
* the optional first function, taking multiple arguments
* @returns {function}
* the composition <code>fnAfter</code> after <code>fnBefore</code>
*/
function chain(fnAfter, fnBefore) {
if (!fnBefore) {
return fnAfter;
}
function formatter() {
return fnAfter.call(this, fnBefore.apply(this, arguments));
}
return formatter;
}
/**
* @classdesc
* A collection of methods which help to consume
* <a href="http://docs.oasis-open.org/odata/odata/v4.0/odata-v4.0-part3-csdl.html">
* OData V4 annotations</a> in XML template views. Every context argument must belong to a
* <code>sap.ui.model.odata.ODataMetaModel</code> instance.
*
* Formatter functions like {@link #.format format} and {@link #.simplePath simplePath} can
* be used in complex bindings to turn OData V4 annotations into texts or data bindings,
* e.g. <code><sfi:SmartField value="{path : 'meta>Value', formatter :
* 'sap.ui.model.odata.AnnotationHelper.simplePath'}"/></code>.
*
* Helper functions like {@link #.resolvePath resolvePath} can be used by template
* instructions in XML template views, e.g. <code><template:with path="meta>Value"
* helper="sap.ui.model.odata.AnnotationHelper.resolvePath" var="target"></code>.
*
* Since 1.31.0, you DO NOT need to {@link jQuery.sap.require} this module before use.
*
* @public
* @since 1.27.0
* @namespace
* @alias sap.ui.model.odata.AnnotationHelper
*/
var AnnotationHelper = {
/**
* Creates a property setting (which is either a constant value or a binding info
* object) from the given parts and from the optional root formatter function.
* Each part can have one of the following types:
* <ul>
* <li><code>boolean</code>, <code>number</code>, <code>undefined</code>: The part is
* a constant value.
*
* <li><code>string</code>: The part is a data binding expression with complex
* binding syntax (for example, as created by {@link #.format format}) and is parsed
* accordingly to create either a constant value or a binding info object. Proper
* backslash escaping must be used for constant values with curly braces.
*
* <li><code>object</code>: The part is a binding info object if it has a "path" or
* "parts" property, otherwise it is a constant value.
* </ul>
* If a binding info object is not the only part and has a "parts" property itself,
* then it must have no other properties except "formatter"; this is the case for
* expression bindings and data binding expressions created by {@link #.format format}.
*
* If all parts are constant values, the resulting property setting is also a constant
* value computed by applying the root formatter function to the constant parts once.
* If at least one part is a binding info object, the resulting property setting is
* also a binding info object and the root formatter function will be applied again and
* again to the current values of all parts, no matter whether constant or variable.
*
* Note: The root formatter function should not rely on its <code>this</code> value
* because it depends on how the function is called.
*
* Note: A single data binding expression can be given directly to
* {@link sap.ui.base.ManagedObject#applySettings applySettings}, no need to call this
* function first.
*
* Example:
* <pre>
* function myRootFormatter(oValue1, oValue2, sFullName, sGreeting, iAnswer) {
* return ...; //TODO compute something useful from the given values
* }
*
* oSupplierContext = oMetaModel.getMetaContext("/ProductSet('HT-1021')/ToSupplier");
* oValueContext = oMetaModel.createBindingContext("com.sap.vocabularies.UI.v1.DataPoint/Value", oSupplierContext);
*
* vPropertySetting = sap.ui.model.odata.AnnotationHelper.createPropertySetting([
* sap.ui.model.odata.AnnotationHelper.format(oValueContext),
* "{path : 'meta>Value', formatter : 'sap.ui.model.odata.AnnotationHelper.simplePath'}",
* "{:= 'Mr. ' + ${/FirstName} + ' ' + ${/LastName}}",
* "hello, world!",
* 42
* ], myRootFormatter);
*
* oControl.applySettings({"someProperty" : vPropertySetting});
* </pre>
*
* @param {any[]} vParts
* array of parts
* @param {function} [fnRootFormatter]
* root formatter function; default: <code>Array.prototype.join(., " ")</code>
* in case of multiple parts, just like
* {@link sap.ui.model.CompositeBinding#getExternalValue getExternalValue}
* @returns {any|object}
* constant value or binding info object for a property as expected by
* {@link sap.ui.base.ManagedObject#applySettings applySettings}
* @throws {Error}
* if some part has an unsupported type or refers to a function name which is not
* found
* @public
* @since 1.31.0
*/
createPropertySetting : function (vParts, fnRootFormatter) {
var bMergeNeeded = false,
vPropertySetting;
vParts = vParts.slice(); // shallow copy to avoid changes visible to caller
vParts.forEach(function (vPart, i) {
switch (typeof vPart) {
case "boolean":
case "number":
case "undefined":
bMergeNeeded = true;
break;
case "string":
vPropertySetting = BindingParser.complexParser(vPart, null, true, true);
if (vPropertySetting !== undefined) {
if (vPropertySetting.functionsNotFound) {
throw new Error("Function name(s) "
+ vPropertySetting.functionsNotFound.join(", ")
+ " not found");
}
vParts[i] = vPart = vPropertySetting;
}
// falls through
case "object":
// merge is needed if some parts are constants or again have parts
// Note: a binding info object has either "path" or "parts"
if (!vPart || typeof vPart !== "object" || !("path" in vPart)) {
bMergeNeeded = true;
}
break;
default:
throw new Error("Unsupported part: " + vPart);
}
});
vPropertySetting = {
formatter : fnRootFormatter,
parts : vParts
};
if (bMergeNeeded) {
BindingParser.mergeParts(vPropertySetting);
}
if (vPropertySetting.parts.length === 0) {
// special case: all parts are constant values, call formatter once
vPropertySetting = vPropertySetting.formatter && vPropertySetting.formatter();
if (typeof vPropertySetting === "string") {
vPropertySetting = BindingParser.complexParser.escape(vPropertySetting);
}
} else if (vPropertySetting.parts.length === 1) {
// special case: a single property setting only
// Note: sap.ui.base.ManagedObject#_bindProperty cannot handle the single-part
// case with two formatters, unless the root formatter is marked with
// "textFragments". We unpack here and chain the formatters ourselves.
fnRootFormatter = vPropertySetting.formatter;
vPropertySetting = vPropertySetting.parts[0];
if (fnRootFormatter) {
vPropertySetting.formatter
= chain(fnRootFormatter, vPropertySetting.formatter);
}
}
return vPropertySetting;
},
/**
* A formatter function to be used in a complex binding inside an XML template view
* in order to interpret OData V4 annotations. It knows about
* <ul>
* <li> the "14.4 Constant Expressions" for "edm:Bool", "edm:Date",
* "edm:DateTimeOffset", "edm:Decimal", "edm:Float", "edm:Guid", "edm:Int",
* "edm:TimeOfDay".
* <li> the constant "14.4.11 Expression edm:String": This is turned into a fixed
* text (e.g. <code>"Width"</code>) or into a data binding expression (e.g. <code>
* "{/##/dataServices/schema/0/entityType/1/com.sap.vocabularies.UI.v1.FieldGroup#Dimensions/Data/0/Label/String}"
* </code>). Data binding expressions are used in case XML template processing has
* been started with the setting <code>bindTexts : true</code>. The purpose is to
* reference translatable texts from OData V4 annotations, especially for XML
* template processing at design time. Since 1.31.0, string constants that contain a
* simple binding <code>"{@i18n>...}"</code> to the hard-coded model name "@i18n"
* with arbitrary path are not turned into a fixed text, but kept as a data binding
* expression; this allows local annotation files to refer to a resource bundle for
* internationalization.
* <li> the dynamic "14.5.1 Comparison and Logical Operators": These are turned into
* expression bindings to perform the operations at run-time.
* <li> the dynamic "14.5.3 Expression edm:Apply":
* <ul>
* <li> "14.5.3.1.1 Function odata.concat": This is turned into a data binding
* expression relative to an entity.
* <li> "14.5.3.1.2 Function odata.fillUriTemplate": This is turned into an
* expression binding to fill the template at run-time.
* <li> "14.5.3.1.3 Function odata.uriEncode": This is turned into an expression
* binding to encode the parameter at run-time.
* <li> Apply functions may be nested arbitrarily.
* </ul>
* <li> the dynamic "14.5.6 Expression edm:If": This is turned into an expression
* binding to be evaluated at run-time. The expression is a conditional expression
* like <code>"{=condition ? expression1 : expression2}"</code>.
* <li> the dynamic "14.5.10 Expression edm:Null": This is turned into a
* <code>null</code> value. In <code>odata.concat</code> it is ignored.
* <li> the dynamic "14.5.12 Expression edm:Path" and "14.5.13 Expression
* edm:PropertyPath": This is turned into a data binding relative to an entity,
* including type information and constraints as available from meta data,
* e.g. <code>"{path : 'Name', type : 'sap.ui.model.odata.type.String',
* constraints : {'maxLength':'255'}}"</code>.
* Depending on the used type, some additional constraints of this type are set:
* <ul>
* <li>Edm.DateTime: The "displayFormat" constraint is set to the value of the
* "sap:display-format" annotation of the referenced property.
* <li>Edm.Decimal: The "precision" and "scale" constraints are set to the values
* of the corresponding attributes of the referenced property.
* <li>Edm.String: The "maxLength" constraint is set to the value of the
* corresponding attribute of the referenced property and the "isDigitSequence"
* constraint is set to the value of the
* "com.sap.vocabularies.Common.v1.IsDigitSequence" annotation of the referenced
* property.
* </ul>
* </ul>
* Unsupported or incorrect values are turned into a string nevertheless, but indicated
* as such. Proper escaping is used to make sure that data binding syntax is not
* corrupted. An error describing the problem is logged to the console in such a case.
*
* Example:
* <pre>
* <Text text="{path: 'meta>Value', formatter: 'sap.ui.model.odata.AnnotationHelper.format'}" />
* </pre>
*
* @param {sap.ui.core.util.XMLPreprocessor.IContext|sap.ui.model.Context} oInterface
* the callback interface related to the current formatter call
* @param {any} [vRawValue]
* the raw value from the meta model, which is embedded within an entity set or
* entity type:
* <ul>
* <li>if this function is used as formatter the value
* is provided by the framework</li>
* <li>if this function is called directly, provide the parameter only if it is
* already calculated</li>
* <li>if the parameter is omitted, it is calculated automatically through
* <code>oInterface.getObject("")</code></li>
* </ul>
* @returns {string}
* the resulting string value to write into the processed XML
* @public
*/
format : function (oInterface, vRawValue) {
if (arguments.length === 1) {
vRawValue = oInterface.getObject("");
}
return Expression.getExpression(oInterface, vRawValue, true);
},
/**
* A formatter function to be used in a complex binding inside an XML template view
* in order to interpret OData V4 annotations. It knows about the following dynamic
* expressions:
* <ul>
* <li>"14.5.2 Expression edm:AnnotationPath"</li>
* <li>"14.5.11 Expression edm:NavigationPropertyPath"</li>
* <li>"14.5.12 Expression edm:Path"</li>
* <li>"14.5.13 Expression edm:PropertyPath"</li>
* </ul>
* It returns a binding expression for a navigation path in an OData model, starting at
* an entity.
* Currently supports navigation properties. Term casts and annotations of
* navigation properties terminate the navigation path.
*
* Examples:
* <pre>
* <template:if test="{path: 'facet>Target', formatter: 'sap.ui.model.odata.AnnotationHelper.getNavigationPath'}">
* <form:SimpleForm binding="{path: 'facet>Target', formatter: 'sap.ui.model.odata.AnnotationHelper.getNavigationPath'}" />
* </template:if>
* </pre>
*
* @param {sap.ui.core.util.XMLPreprocessor.IContext|sap.ui.model.Context} oInterface
* the callback interface related to the current formatter call
* @param {any} [vRawValue]
* the raw value from the meta model, e.g. <code>{AnnotationPath :
* "ToSupplier/@com.sap.vocabularies.Communication.v1.Address"}</code> or <code>
* {AnnotationPath : "@com.sap.vocabularies.UI.v1.FieldGroup#Dimensions"}</code>;
* embedded within an entity set or entity type;
* <ul>
* <li>if this function is used as formatter the value
* is provided by the framework</li>
* <li>if this function is called directly, provide the parameter only if it is
* already calculated</li>
* <li>if the parameter is omitted, it is calculated automatically through
* <code>oInterface.getObject("")</code></li>
* </ul>
* @returns {string}
* the resulting string value to write into the processed XML, e.g. "{ToSupplier}"
* or "{}" (in case no navigation is needed); returns "" in case the navigation path
* cannot be determined (this is treated as falsy in <code>template:if</code>
* statements!)
* @public
*/
getNavigationPath : function (oInterface, vRawValue) {
if (arguments.length === 1) {
vRawValue = oInterface.getObject("");
}
var oResult = Basics.followPath(oInterface, vRawValue);
return oResult
? "{" + oResult.navigationProperties.join("/") + "}"
: "";
},
/**
* Helper function for a <code>template:with</code> instruction that depending on how
* it is called goes to the entity set with the given name or to the one determined
* by the last navigation property. Supports the following dynamic expressions:
* <ul>
* <li>"14.5.2 Expression edm:AnnotationPath"</li>
* <li>"14.5.11 Expression edm:NavigationPropertyPath"</li>
* <li>"14.5.12 Expression edm:Path"</li>
* <li>"14.5.13 Expression edm:PropertyPath"</li>
* </ul>
*
* Example:
* <pre>
* <template:with path="facet>Target" helper="sap.ui.model.odata.AnnotationHelper.gotoEntitySet" var="entitySet"/>
* <template:with path="associationSetEnd>entitySet" helper="sap.ui.model.odata.AnnotationHelper.gotoEntitySet" var="entitySet"/>
* </pre>
*
* @param {sap.ui.model.Context} oContext
* a context which must point to a simple string or to an annotation (or annotation
* property) of type <code>Edm.AnnotationPath</code>,
* <code>Edm.NavigationPropertyPath</code>, <code>Edm.Path</code>, or
* <code>Edm.PropertyPath</code> embedded within an entity set or entity type;
* the context's model must be an {@link sap.ui.model.odata.ODataMetaModel}
* @returns {string}
* the path to the entity set, or <code>undefined</code> if no such set is found. In
* this case, a warning is logged to the console.
* @public
*/
gotoEntitySet : function (oContext) {
var sEntitySet,
sEntitySetPath,
vRawValue = oContext.getObject(),
oResult;
if (typeof vRawValue === "string") {
sEntitySet = vRawValue;
} else {
oResult = Basics.followPath(oContext, vRawValue);
sEntitySet = oResult
&& oResult.associationSetEnd
&& oResult.associationSetEnd.entitySet;
}
if (sEntitySet) {
sEntitySetPath = oContext.getModel().getODataEntitySet(sEntitySet, true);
}
if (!sEntitySetPath) {
jQuery.sap.log.warning(oContext.getPath() + ": found '" + sEntitySet
+ "' which is not a name of an entity set", undefined,
"sap.ui.model.odata.AnnotationHelper");
}
return sEntitySetPath;
},
/**
* Helper function for a <code>template:with</code> instruction that goes to the
* entity type with the qualified name which <code>oContext</code> points at.
*
* Example: Assume that "entitySet" refers to an entity set within an OData meta model;
* the helper function is then called on the "entityType" property of that entity set
* (which holds the qualified name of the entity type) and in turn the path of that
* entity type is assigned to the variable "entityType".
* <pre>
* <template:with path="entitySet>entityType" helper="sap.ui.model.odata.AnnotationHelper.gotoEntityType" var="entityType">
* </pre>
*
* @param {sap.ui.model.Context} oContext
* a context which must point to the qualified name of an entity type;
* the context's model must be an {@link sap.ui.model.odata.ODataMetaModel}
* @returns {string}
* the path to the entity type with the given qualified name,
* or <code>undefined</code> if no such type is found. In this case, a warning is
* logged to the console.
* @public
*/
gotoEntityType : function (oContext) {
var sEntityType = oContext.getProperty(""),
oResult = oContext.getModel().getODataEntityType(sEntityType, true);
if (!oResult) {
jQuery.sap.log.warning(oContext.getPath() + ": found '" + sEntityType
+ "' which is not a name of an entity type", undefined,
"sap.ui.model.odata.AnnotationHelper");
}
return oResult;
},
/**
* Helper function for a <code>template:with</code> instruction that goes to the
* function import with the name which <code>oContext</code> points at.
*
* Example: Assume that "dataField" refers to a DataFieldForAction within an
* OData meta model;
* the helper function is then called on the "Action" property of that data field
* (which holds an object with the qualified name of the function import in the
* <code>String</code> property) and in turn the path of that function import
* is assigned to the variable "function".
* <pre>
* <template:with path="dataField>Action"
* helper="sap.ui.model.odata.AnnotationHelper.gotoFunctionImport" var="function">
* </pre>
* @param {sap.ui.model.Context} oContext
* a context which must point to an object with a <code>String</code> property, which
* holds the qualified name of the function import;
* the context's model must be an {@link sap.ui.model.odata.ODataMetaModel}
* @returns {string}
* the path to the function import with the given qualified name,
* or <code>undefined</code> if no function import is found. In this case, a warning
* is logged to the console.
* @since 1.29.1
* @public
*/
gotoFunctionImport : function (oContext) {
var sFunctionImport = oContext.getProperty("String"),
oResult = oContext.getModel().getODataFunctionImport(sFunctionImport, true);
if (!oResult) {
jQuery.sap.log.warning(oContext.getPath() + ": found '" + sFunctionImport
+ "' which is not a name of a function import", undefined,
"sap.ui.model.odata.AnnotationHelper");
}
return oResult;
},
/**
* A formatter function to be used in a complex binding inside an XML template view
* in order to interpret OData V4 annotations. It knows about the following dynamic
* expressions:
* <ul>
* <li>"14.5.2 Expression edm:AnnotationPath"</li>
* <li>"14.5.11 Expression edm:NavigationPropertyPath"</li>
* <li>"14.5.12 Expression edm:Path"</li>
* <li>"14.5.13 Expression edm:PropertyPath"</li>
* </ul>
* It returns the information whether the navigation path ends with an association end
* with multiplicity "*". It throws an error if the navigation path has an association
* end with multiplicity "*" which is not the last one.
* Currently supports navigation properties. Term casts and annotations of
* navigation properties terminate the navigation path.
*
* Examples:
* <pre>
* <template:if test="{path: 'facet>Target', formatter: 'sap.ui.model.odata.AnnotationHelper.isMultiple'}">
* </pre>
*
* @param {sap.ui.core.util.XMLPreprocessor.IContext|sap.ui.model.Context} oInterface
* the callback interface related to the current formatter call
* @param {any} [vRawValue]
* the raw value from the meta model, e.g. <code>{AnnotationPath :
* "ToSupplier/@com.sap.vocabularies.Communication.v1.Address"}</code> or <code>
* {AnnotationPath : "@com.sap.vocabularies.UI.v1.FieldGroup#Dimensions"}</code>;
* embedded within an entity set or entity type;
* <ul>
* <li>if this function is used as formatter the value
* is provided by the framework</li>
* <li>if this function is called directly, provide the parameter only if it is
* already calculated</li>
* <li>if the parameter is omitted, it is calculated automatically through
* <code>oInterface.getObject("")</code></li>
* </ul>
* @returns {string}
* <code>"true"</code> if the navigation path ends with an association end with
* multiplicity "*", <code>""</code> in case the navigation path cannot be
* determined, <code>"false"</code> otherwise (the latter are both treated as falsy
* in <code>template:if</code> statements!)
* @throws {Error}
* if the navigation path has an association end with multiplicity "*" which is not
* the last one
* @public
*/
isMultiple : function (oInterface, vRawValue) {
if (arguments.length === 1) {
vRawValue = oInterface.getObject("");
}
var oResult = Basics.followPath(oInterface, vRawValue);
if (oResult) {
if (oResult.navigationAfterMultiple) {
throw new Error(
'Association end with multiplicity "*" is not the last one: '
+ vRawValue.AnnotationPath);
}
return String(oResult.isMultiple);
}
return "";
},
/**
* Helper function for a <code>template:with</code> instruction that resolves a dynamic
* "14.5.2 Expression edm:AnnotationPath",
* "14.5.11 Expression edm:NavigationPropertyPath", "14.5.12 Expression edm:Path" or
* "14.5.13 Expression edm:PropertyPath".
* Currently supports navigation properties and term casts.
*
* Example:
* <pre>
* <template:with path="meta>Value" helper="sap.ui.model.odata.AnnotationHelper.resolvePath" var="target">
* </pre>
*
* @param {sap.ui.model.Context} oContext
* a context which must point to an annotation or annotation property of type
* <code>Edm.AnnotationPath</code>, <code>Edm.NavigationPropertyPath</code>,
* <code>Edm.Path</code> or <code>Edm.PropertyPath</code>, embedded within an entity
* set or entity type;
* the context's model must be an {@link sap.ui.model.odata.ODataMetaModel}
* @returns {string}
* the path to the target, or <code>undefined</code> in case the path cannot be
* resolved. In this case, a warning is logged to the console.
* @public
*/
resolvePath : function (oContext) {
var oResult = Basics.followPath(oContext, oContext.getObject());
if (!oResult) {
jQuery.sap.log.warning(oContext.getPath() + ": Path could not be resolved ",
undefined, "sap.ui.model.odata.AnnotationHelper");
}
return oResult
? oResult.resolvedPath
: undefined;
},
/**
* Formatter function that is used in a complex binding inside an XML template view.
* The function is used to interpret OData V4 annotations, supporting the same
* annotations as {@link #.format format} but with a simplified output aimed at
* design-time templating with smart controls.
*
* In contrast to <code>format</code>, "14.5.12 Expression edm:Path" or
* "14.5.13 Expression edm:PropertyPath" is turned into a simple binding path without
* type or constraint information. In certain cases, a complex binding is required to
* allow for proper escaping of the path.
*
* Example:
* <pre>
* <sfi:SmartField value="{path: 'meta>Value', formatter: 'sap.ui.model.odata.AnnotationHelper.simplePath'}"/>
* </pre>
*
* @param {sap.ui.core.util.XMLPreprocessor.IContext|sap.ui.model.Context} oInterface
* the callback interface related to the current formatter call
* @param {any} [vRawValue]
* the raw value from the meta model, which is embedded within an entity set or
* entity type:
* <ul>
* <li>if this function is used as formatter the value
* is provided by the framework</li>
* <li>if this function is called directly, provide the parameter only if it is
* already calculated</li>
* <li>if the parameter is omitted, it is calculated automatically through
* <code>oInterface.getObject("")</code></li>
* </ul>
* @returns {string}
* the resulting string value to write into the processed XML
* @public
*/
simplePath : function (oInterface, vRawValue) {
if (arguments.length === 1) {
vRawValue = oInterface.getObject("");
}
return Expression.getExpression(oInterface, vRawValue, false);
}
};
// BEWARE: keep this in sync with sap/ui/core/library.js!
AnnotationHelper.format.requiresIContext = true;
AnnotationHelper.getNavigationPath.requiresIContext = true;
AnnotationHelper.isMultiple.requiresIContext = true;
AnnotationHelper.simplePath.requiresIContext = true;
return AnnotationHelper;
}, /* bExport= */ true);
|
/// <reference path="../_all.ts" />
var app;
(function (app) {
var about;
(function (about) {
'use strict';
angular.
module('app.about').
config(AboutConfig);
AboutConfig.$inject = ['$stateProvider'];
function AboutConfig($stateProvider) {
$stateProvider.
state("about", {
url: '/about',
controller: 'app.about.AboutController',
controllerAs: 'about',
templateUrl: '/app/about/About.html'
});
}
})(about = app.about || (app.about = {}));
})(app || (app = {}));
//# sourceMappingURL=config.route.js.map |
import styled from '@emotion/styled/macro'
const View = styled.div`
align-items: stretch;
border-width: 0;
border-style: solid;
box-sizing: border-box;
display: flex;
flex-basis: auto;
flex-direction: column;
flex-shrink: 0;
margin: 0;
padding: 0;
position: relative;
min-height: 0;
min-width: 0;
`
export default View
|
/* eslint-disable no-underscore-dangle */
import { createStore, applyMiddleware, compose } from 'redux';
import thunk from 'redux-thunk';
import reducers from './reducers';
const middleware = [thunk];
// const composeEnhancers =
// typeof window !== 'undefined'
// ? window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__
// : compose;
let state;
if (typeof window !== 'undefined') {
state = window.__PRELOADED_STATE__;
delete window.__PRELOADED_STATE__;
}
let isClient = typeof window !== 'undefined';
let isServer = typeof window === 'undefined';
const store = createStore(
reducers,
state,
applyMiddleware(...middleware)
);
if(isClient){
window.store = store;
};
export { store };
|
load("bf4b12814bc95f34eeb130127d8438ab.js");
load("93fae755edd261212639eed30afa2ca4.js");
// Copyright (c) 2012 Ecma International. All rights reserved.
// This code is governed by the BSD license found in the LICENSE file.
/*---
es5id: 10.4.3-1-10-s
description: >
Strict Mode - checking 'this' (FunctionExpression includes strict
directive prologue)
flags: [noStrict]
---*/
var f = function () {
"use strict";
return typeof this;
}
assert.sameValue(f(), "undefined", 'f()');
|
/********************************************
* This file is part of Webelexis *
* Copyright (c) 2016-2018 by G. Weirich *
* License and Terms see LICENSE *
********************************************/
const assert = require('assert');
const should=require('chai').should()
const app = require('../../src/app');
class KonsService{
async get(id){
return {
fallid: "007"
}
}
}
class FallService{
async get(id){
return {
extjson:{
billing: "KVG"
},
gesetz: "KVG"
}
}
}
xdescribe('\'billing\' service', () => {
let ks;
let fs;
before(()=>{
ks=app.service("konsultation")
fs=app.service('fall')
app.use("/konsultation", new KonsService())
app.use("/fall", new FallService())
})
after(()=>{
app.use("/konsultation",ks)
app.use("/fall",fs)
})
it('registered the service', () => {
const service = app.service('billing');
assert.ok(service, 'Registered the service');
});
it('creates a billing from a tarmed billable',async ()=>{
const service = app.service('billing');
const tarmedService=app.service('tarmed')
const tarmeds=await tarmedService.find({query:{code:'00.0010', law:"KVG"}})
tarmeds.should.be.ok
tarmeds.should.have.property('data')
tarmeds.data.length.should.be.gt(0)
const tarmed=tarmeds.data[0]
tarmed.uid=tarmed.id
tarmed.codesystem='ch.elexis.data.TarmedLeistung'
tarmed.encounter_id="007"
tarmed.count=1
const billed=await service.create(tarmed)
billed.should.be.ok
})
});
|
# Copyright The OpenTelemetry 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.
"""OpenTelemetry Collector Exporter."""
import logging
from typing import Optional, Sequence
import grpc
from opencensus.proto.agent.trace.v1 import (
trace_service_pb2,
trace_service_pb2_grpc,
)
from opencensus.proto.trace.v1 import trace_pb2
import opentelemetry.ext.otcollector.util as utils
import opentelemetry.trace as trace_api
from opentelemetry.sdk.trace import Span, SpanContext
from opentelemetry.sdk.trace.export import SpanExporter, SpanExportResult
from opentelemetry.trace import SpanKind, TraceState
DEFAULT_ENDPOINT = "localhost:55678"
logger = logging.getLogger(__name__)
# pylint: disable=no-member
class CollectorSpanExporter(SpanExporter):
"""OpenTelemetry Collector span exporter.
Args:
endpoint: OpenTelemetry Collector OpenCensus receiver endpoint.
service_name: Name of Collector service.
host_name: Host name.
client: TraceService client stub.
"""
def __init__(
self,
endpoint=DEFAULT_ENDPOINT,
service_name=None,
host_name=None,
client=None,
):
self.endpoint = endpoint
if client is None:
self.channel = grpc.insecure_channel(self.endpoint)
self.client = trace_service_pb2_grpc.TraceServiceStub(
channel=self.channel
)
else:
self.client = client
self.node = utils.get_node(service_name, host_name)
def export(self, spans: Sequence[Span]) -> SpanExportResult:
try:
responses = self.client.Export(self.generate_span_requests(spans))
# Read response
for _ in responses:
pass
except grpc.RpcError:
return SpanExportResult.FAILURE
return SpanExportResult.SUCCESS
def shutdown(self) -> None:
pass
def generate_span_requests(self, spans):
collector_spans = translate_to_collector(spans)
service_request = trace_service_pb2.ExportTraceServiceRequest(
node=self.node, spans=collector_spans
)
yield service_request
# pylint: disable=too-many-branches
def translate_to_collector(spans: Sequence[Span]):
collector_spans = []
for span in spans:
status = None
if span.status is not None:
status = trace_pb2.Status(
code=span.status.canonical_code.value,
message=span.status.description,
)
collector_span = trace_pb2.Span(
name=trace_pb2.TruncatableString(value=span.name),
kind=utils.get_collector_span_kind(span.kind),
trace_id=span.context.trace_id.to_bytes(16, "big"),
span_id=span.context.span_id.to_bytes(8, "big"),
start_time=utils.proto_timestamp_from_time_ns(span.start_time),
end_time=utils.proto_timestamp_from_time_ns(span.end_time),
status=status,
)
parent_id = 0
if isinstance(span.parent, trace_api.Span):
parent_id = span.parent.get_context().span_id
elif isinstance(span.parent, trace_api.SpanContext):
parent_id = span.parent.span_id
collector_span.parent_span_id = parent_id.to_bytes(8, "big")
if span.context.trace_state is not None:
for (key, value) in span.context.trace_state.items():
collector_span.tracestate.entries.add(key=key, value=value)
if span.attributes:
for (key, value) in span.attributes.items():
utils.add_proto_attribute_value(
collector_span.attributes, key, value
)
if span.events:
for event in span.events:
collector_annotation = trace_pb2.Span.TimeEvent.Annotation(
description=trace_pb2.TruncatableString(value=event.name)
)
if event.attributes:
for (key, value) in event.attributes.items():
utils.add_proto_attribute_value(
collector_annotation.attributes, key, value
)
collector_span.time_events.time_event.add(
time=utils.proto_timestamp_from_time_ns(event.timestamp),
annotation=collector_annotation,
)
if span.links:
for link in span.links:
collector_span_link = collector_span.links.link.add()
collector_span_link.trace_id = link.context.trace_id.to_bytes(
16, "big"
)
collector_span_link.span_id = link.context.span_id.to_bytes(
8, "big"
)
collector_span_link.type = (
trace_pb2.Span.Link.Type.TYPE_UNSPECIFIED
)
if isinstance(span.parent, trace_api.Span):
if (
link.context.span_id
== span.parent.get_context().span_id
and link.context.trace_id
== span.parent.get_context().trace_id
):
collector_span_link.type = (
trace_pb2.Span.Link.Type.PARENT_LINKED_SPAN
)
elif isinstance(span.parent, trace_api.SpanContext):
if (
link.context.span_id == span.parent.span_id
and link.context.trace_id == span.parent.trace_id
):
collector_span_link.type = (
trace_pb2.Span.Link.Type.PARENT_LINKED_SPAN
)
if link.attributes:
for (key, value) in link.attributes.items():
utils.add_proto_attribute_value(
collector_span_link.attributes, key, value
)
collector_spans.append(collector_span)
return collector_spans
|
(window["webpackJsonp"]=window["webpackJsonp"]||[]).push([[78],{"71a3":function(t,e,a){"use strict";a.r(e);var o=function(){var t=this,e=t.$createElement,a=t._self._c||e;return a("q-page",{staticClass:"flex flex-top"},[[a("div",{staticClass:"q-pa-md"},[a("div",{staticClass:"q-gutter-y-md",staticStyle:{"max-width":"100%"}},[a("q-tabs",{model:{value:t.detaillink,callback:function(e){t.detaillink=e},expression:"detaillink"}},[a("transition",{attrs:{appear:"","enter-active-class":"animated zoomIn"}},[a("q-route-tab",{directives:[{name:"show",rawName:"v-show",value:"Admin"!==t.$q.localStorage.getItem("staff_type")&&"Manager"!==t.$q.localStorage.getItem("staff_type")&&"Supervisor"!==t.$q.localStorage.getItem("staff_type")&&"Inbound"!==t.$q.localStorage.getItem("staff_type")&&"Outbound"!==t.$q.localStorage.getItem("staff_type")&&"StockControl"!==t.$q.localStorage.getItem("staff_type")&&"Customer"!==t.$q.localStorage.getItem("staff_type"),expression:"$q.localStorage.getItem('staff_type') !== 'Admin' &&\n $q.localStorage.getItem('staff_type') !== 'Manager' &&\n $q.localStorage.getItem('staff_type') !== 'Supervisor' &&\n $q.localStorage.getItem('staff_type') !== 'Inbound' &&\n $q.localStorage.getItem('staff_type') !== 'Outbound' &&\n $q.localStorage.getItem('staff_type') !== 'StockControl' &&\n $q.localStorage.getItem('staff_type') !== 'Customer'\n "}],attrs:{name:"supplierasnlist",label:t.$t("inbound.asn"),icon:"img:statics/inbound/asn.png",to:"/supplierasn/supplierasnlist",exact:""}})],1),a("transition",{attrs:{appear:"","enter-active-class":"animated zoomIn"}},[a("q-route-tab",{directives:[{name:"show",rawName:"v-show",value:"Admin"!==t.$q.localStorage.getItem("staff_type")&&"Manager"!==t.$q.localStorage.getItem("staff_type")&&"Supervisor"!==t.$q.localStorage.getItem("staff_type")&&"Inbound"!==t.$q.localStorage.getItem("staff_type")&&"Outbound"!==t.$q.localStorage.getItem("staff_type")&&"StockControl"!==t.$q.localStorage.getItem("staff_type")&&"Customer"!==t.$q.localStorage.getItem("staff_type"),expression:"$q.localStorage.getItem('staff_type') !== 'Admin' &&\n $q.localStorage.getItem('staff_type') !== 'Manager' &&\n $q.localStorage.getItem('staff_type') !== 'Supervisor' &&\n $q.localStorage.getItem('staff_type') !== 'Inbound' &&\n $q.localStorage.getItem('staff_type') !== 'Outbound' &&\n $q.localStorage.getItem('staff_type') !== 'StockControl' &&\n $q.localStorage.getItem('staff_type') !== 'Customer'\n "}],attrs:{name:"supplierasnfinish",label:t.$t("inbound.asnfinish"),icon:"img:statics/inbound/asnfinish.png",to:"/supplierasn/supplierasnfinish",exact:""}})],1)],1)],1)])],a("div",{staticClass:"main-table"},[a("router-view")],1)],2)},s=[],n={name:"Pageinbound",data(){return{detaillink:"asn"}},methods:{}},l=n,r=a("42e1"),i=a("9989"),g=a("429b"),f=a("7867"),p=a("eebe"),c=a.n(p),m=Object(r["a"])(l,o,s,!1,null,null,null);e["default"]=m.exports;c()(m,"components",{QPage:i["a"],QTabs:g["a"],QRouteTab:f["a"]})}}]); |
import {
mapSetters,
normalizePopulated,
paginateQuery,
initLogger,
} from '../../utils/store';
import _ from 'lodash';
import { MEDICAL_RECORD_TYPES } from './constants';
export const STORE_NAME = 'medical-records';
const log = initLogger(STORE_NAME);
const currentEncounterRecords = {};
MEDICAL_RECORD_TYPES.forEach(record => {
currentEncounterRecords[record.type] = [];
if (record.subtype) currentEncounterRecords[record.subtype] = [];
});
export default class Store {
constructor (mycure) {
this.state = {
hasUnsavedRecords: false,
currentEncounterRecords,
medicinesDefaults: [],
faveMedicines: [],
medicalRecordsDraft: {},
};
this.getters = {};
this.actions = {
getMedicalRecords: async (context, {
patient,
organization,
types,
queryOpts,
pageNo,
pageSize,
latest,
}) => {
const query = {
...queryOpts,
patient,
type: { $in: types },
$sort: { createdAt: latest ? -1 : 1 },
$populate: {
diagnosticTests: {
service: 'diagnostic-tests',
method: 'find',
localKey: 'tests',
extractKey: 'id',
foreignKey: 'id',
foreignOps: '$in',
},
createdByDetails: {
service: 'organization-members',
method: 'findOne',
localKey: 'createdBy',
foreignKey: 'uid',
organization,
},
results: {
service: 'medical-records',
method: 'find',
localKey: 'id',
foreignKey: 'order',
$populate: {
orderDetails: {
service: 'medical-records',
localKey: 'order',
method: 'get',
},
},
},
},
};
log('getMedicalRecords#query: %O', query);
const { items, total } = await mycure.medical.records()
.find(paginateQuery({ query, pageNo, pageSize }));
log(`getMedicalRecords#total: ${total}`);
log('getMedicalRecords#items: %O', items);
const normalizedItems = normalizePopulated(items);
const itemsWithTests = _.map(normalizedItems, item => ({
...item,
tests: _.map(item.tests, test => ({
...test,
test: _.find(_.get(normalizedItems, 'diagnosticTests'), d => d.id === test.id),
})),
}));
log('getMedicalRecords#records: %O', itemsWithTests);
return { items: itemsWithTests, total };
},
searchMedicalRecords: async (context, query) => {
const { items } = await mycure.medical.records().find(query);
return items;
},
updateMedicalRecordsBatch: async (store, { ids, update }) => {
if (!ids || !ids.length) throw new Error('No ids provided.');
await mycure.medical.records().update({ id: { $in: ids } }, update);
},
updateSingletonNote: async ({ rootState }, { facility, patient, text }) => {
log(`updateSingletonNote#text: ${text}`);
const query = {
type: 'medical-note',
patient,
facility,
};
log('updateSingletonNote#query: %O', query);
const record = await mycure.medical.records().findOne(query);
log('updateSingletonNote#record: %O', record);
if (_.isEmpty(record)) {
log('updateSingletonNote: creating');
const payload = {
type: 'medical-note',
patient,
facility,
text,
};
const currentUser = _.get(rootState, 'auth.currentUser');
if (currentUser.isDoctor) {
payload.provider = currentUser.uid;
}
await mycure.medical.records().create(payload);
} else {
log('updateSingletonNote#update#query: %O', query);
await mycure.medical.records().update(query, { text });
}
},
createMedicalRecord: async ({ rootState }, record) => {
const currentUser = _.get(rootState, 'auth.currentUser');
if (currentUser.isDoctor) {
record.provider = currentUser.uid;
}
await mycure.medical.records().create(record);
},
createMedicalRecords: async ({ state, rootState, commit }, { records, returnResult = false }) => {
const currentUser = rootState?.auth?.currentUser;
if (currentUser.isDoctor) {
records = records?.map(record => ({ ...record, provider: currentUser.uid }));
}
// Get newly created records
const newRecords = await mycure.medical.records().create(records);
// Get current encouter records
const currentRecords = state.currentEncounterRecords;
const promises = [];
// Fetch the newly created record to
// get the populated data.
newRecords.forEach((record) => {
promises.push(this.fetchRecord(mycure, record.id));
});
const result = _.flatten(await Promise.all(promises));
// Add the newly created records with
// populated data to current encouter
// records
result.forEach(record => {
if (_.isEmpty(currentRecords[record.type])) {
currentRecords[record.type] = [];
}
currentRecords[record.type].push(record);
if (record.subtype && _.isEmpty(currentRecords[record.subtype])) {
currentRecords[record.subtype] = [];
}
if (record.subtype) {
currentRecords[record.subtype].push(record);
}
});
commit('setCurrentEncounterRecords', currentRecords);
commit('clearMedicalRecordsDraft');
if (returnResult) {
return result;
}
},
updateMedicalRecords: async ({ state, commit, rootGetters }, { type, subtype, data }) => {
const { id, payload } = data;
await mycure.medical.records().update(id, payload);
const currentRecords = _.cloneDeep(state.currentEncounterRecords);
// Fetch the udpated data with populated values
const updatedRecord = await this.fetchRecord(mycure, id);
// Replace the old record with the udpated record.
currentRecords[type] = _.map(currentRecords[type], record => {
if (record.id === id) return updatedRecord;
return record;
});
currentRecords[subtype] = _.map(currentRecords[subtype], record => {
if (record.id === id) return updatedRecord;
return record;
});
commit('setCurrentEncounterRecords', currentRecords);
// Update records in current encounter
const currentEncounter = rootGetters['encounter/currentEncounter'];
if (currentEncounter) {
currentEncounter.medicalRecords = {};
currentEncounter.medicalRecordsGrouped = {};
currentEncounter.medicalRecordsArr = [];
_.forEach(Object.keys(currentRecords), key => {
if (!_.isEmpty(currentRecords[key])) {
currentEncounter.medicalRecords[key] = currentRecords[key];
currentEncounter.medicalRecordsGrouped[key] = currentRecords[key];
currentRecords[key].forEach(record => currentEncounter.medicalRecordsArr.push(record));
}
});
commit('encounter/setCurrentEncounter', currentEncounter, { root: true });
}
},
updateGenericMedicalRecord: async (context, { id, data }) => {
await mycure.medical.records().update(id, data);
},
createGenericMedicalRecord: async ({ rootState }, { payload, singleton }) => {
log('createGenericMedicalRecord#payload: %O', payload);
log(`createGenericMedicalRecord#singleton: ${singleton}`);
const currentUser = _.get(rootState, 'auth.currentUser');
if (currentUser.isDoctor && !payload.provider) {
payload.provider = currentUser.uid;
}
// if not singleton, simply create
if (!singleton) return mycure.medical.records().create(payload);
// if singleton, decide based on existence of previous record
const query = { type: payload.type, encounter: payload.encounter };
const record = await mycure.medical.records().findOne(query);
log('createGenericMedicalRecord#record: %O', record);
// if no previous record exists, create one
if (!record) return mycure.medical.records().create(payload);
// special case for empty medical-note: remove if empty
const types = ['medical-note', 'care-plan'];
const isMedicalNote = types.includes(payload.type);
log(`createGenericMedicalRecord#isMedicalNote: ${isMedicalNote}`);
if (isMedicalNote && _.isEmpty(payload.text)) {
return mycure.medical.records().remove(record.id);
}
// singleton record already exists: update in-place
const update = _.omit(payload, 'type', 'facility', 'patient', 'encounter');
log('createGenericMedicalRecord#update: %O', update);
return mycure.medical.records().update(record.id, update);
},
saveMedicalRecord: async ({ dispatch, rootState }, { data }) => {
let id = '';
if (data.id) {
id = data.id;
await mycure.medical.records().update(data.id, _.omit(data, ['id', 'patient']));
} else {
const currentUser = _.get(rootState, 'auth.currentUser');
if (currentUser.isDoctor) {
data.provider = currentUser.uid;
}
const newRecord = await mycure.medical.records().create(data);
id = newRecord.id;
}
await dispatch('encounter/getCurrentEncounter', { patient: data.patient }, { root: true });
return id;
},
removeMedicalRecord: async ({ commit, state, rootGetters }, { data }) => {
await mycure.medical.records().remove(data.id);
const removedRecordId = data.id;
const currentRecords = state.currentEncounterRecords;
const recordsByType = currentRecords[data.type].filter((record) => record.id !== removedRecordId);
const recordsBySubtype = data.subtype ? currentRecords[data.subtype].filter((record) => record.id !== removedRecordId) : [];
currentRecords[data.type] = recordsByType;
currentRecords[data.subtype] = recordsBySubtype;
commit('setCurrentEncounterRecords', currentRecords);
// Update records in current encounter
const currentEncounter = rootGetters['encounter/currentEncounter'];
if (currentEncounter) {
currentEncounter.medicalRecords = {};
currentEncounter.medicalRecordsGrouped = {};
currentEncounter.medicalRecordsArr = currentEncounter.medicalRecordsArr.filter((record) => record.id !== removedRecordId);
_.forEach(Object.keys(currentRecords), key => {
if (!_.isEmpty(currentRecords[key])) {
currentEncounter.medicalRecords[key] = currentRecords[key];
currentEncounter.medicalRecordsGrouped[key] = currentRecords[key];
}
});
commit('encounter/setCurrentEncounter', currentEncounter, { root: true });
}
},
uploadRecordAttachments: async (store, { id, attachments }) => {
let attachmentURLs = [];
const promises = [];
attachments.forEach((attachment) => {
const obsTask = mycure.medical.records().uploadPic(id, attachment);
promises.push(obsTask.upload());
});
attachmentURLs = await Promise.all(promises);
return attachmentURLs;
},
getRecordsHistory: async (context, { encounter, pageNo }) => {
const query = {
encounter,
$history: true,
$populate: {
createdByDetails: {
service: 'organization-members',
method: 'findOne',
localKey: 'createdBy',
foreignKey: 'uid',
},
_createdByDetails: {
service: 'organization-members',
method: 'findOne',
localKey: '_createdBy',
foreignKey: 'uid',
},
},
};
const { items } = await mycure.medical.records().find(paginateQuery({ query, pageNo, pageSize: 20 }));
return items.map(item => {
const obj = {
createdByDetails: item.$populated.createdByDetails,
historyCreatedBy: item.$populated._createdByDetails,
...item,
};
return _.omit(obj, ['$populated']);
});
},
getAttachments: async (context, { patient, pageNo, pageSize }) => {
const query = {
patient,
type: 'attachment',
$sort: {
createdAt: -1,
},
$populate: {
template: {
service: 'form-templates',
localKey: 'template',
method: 'get',
},
createdByDetails: {
service: 'personal-details',
idField: 'id',
method: 'findOne',
key: 'createdBy',
},
createdByMembership: {
service: 'organization-members',
idField: 'uid',
method: 'findOne',
key: 'createdBy',
},
medicalProcedureProviders: {
service: 'personal-details',
method: 'find',
localKey: 'providers',
foreignKey: 'id',
},
ref: {
service: 'services',
method: 'get',
localKey: 'ref',
},
results: {
service: 'medical-records',
method: 'find',
localKey: 'id',
foreignKey: 'order',
type: {
$in: ['lab-test-result', 'imaging-test-result'],
},
$populate: {
tests: {
service: 'diagnostic-tests',
method: 'find',
localKey: 'results',
extractKey: 'test',
foreignKey: 'id',
},
measures: {
service: 'diagnostic-measures',
method: 'find',
localKey: 'results',
extractKey: 'measure',
foreignKey: 'id',
},
},
},
},
};
const result = await mycure.medical.records().find(paginateQuery({ query, pageNo, pageSize }));
return result;
},
getRecordByType: async (context, {
type,
subtype,
patient,
encounter,
queryOpts = {},
dateFilter,
limit,
skip,
}) => {
const query = {
type,
patient,
...queryOpts,
$populate: {
createdByDetails: {
service: 'personal-details',
idField: 'id',
method: 'findOne',
key: 'createdBy',
},
createdByMembership: {
service: 'organization-members',
idField: 'uid',
method: 'findOne',
key: 'createdBy',
},
tests: {
service: 'diagnostic-tests',
method: 'find',
localKey: 'results',
extractKey: 'test',
foreignKey: 'id',
},
measures: {
service: 'diagnostic-measures',
method: 'find',
localKey: 'tests',
extractKey: 'id',
foreignKey: 'test',
},
results: {
service: 'medical-records',
method: 'find',
localKey: 'id',
foreignKey: 'order',
type: {
$in: ['lab-test-result', 'imaging-test-result'],
},
$populate: {
tests: {
service: 'diagnostic-tests',
method: 'find',
localKey: 'results',
extractKey: 'test',
foreignKey: 'id',
},
measures: {
service: 'diagnostic-measures',
method: 'find',
localKey: 'results',
extractKey: 'measure',
foreignKey: 'id',
},
},
},
},
};
if (subtype) {
query.subtype = subtype;
}
if (encounter) {
query.encounter = encounter;
}
if (dateFilter && dateFilter.start && dateFilter.end) {
query.createdAt = {
$gte: dateFilter.start,
$lte: dateFilter.end,
};
}
if (limit) {
query.$limit = limit;
}
if (skip) {
query.$skip = skip;
}
const data = await mycure.medical.records().find(query);
return data;
},
getLabTestResult: async (context, { patient, facility }) => {
const query = {
type: 'lab-test-result',
patient,
facility,
$populate: {
tests: {
service: 'diagnostic-tests',
method: 'find',
localKey: 'results',
extractKey: 'test',
foreignKey: 'id',
foreignOps: '$in',
},
measures: {
service: 'diagnostic-measures',
method: 'find',
localKey: 'results',
extractKey: 'measure',
foreignKey: 'id',
foreignOps: '$in',
},
},
};
const { items } = await mycure.medical.records().find(query);
const mapped = _.map(items, (item) => {
const { measures, tests } = item.$populated;
const results = _.map(item.results, (result) => {
return {
...result,
test: _.find(tests, (test) => test.id === result.test),
measure: _.find(measures, (measure) => measure.id === result.measure),
};
});
return {
..._.omit(item, ['$populated']),
results,
};
});
return mapped;
},
createLabOrderResults: async ({ rootState }, payload) => {
const currentUser = _.get(rootState, 'auth.currentUser');
if (currentUser.isDoctor) {
payload.provider = currentUser.uid;
}
return mycure.medical.records().create(payload);
},
/**
* @param {Object} opts - Options
* @param {string} opts.id - Diagnostic Order Record ID
*/
getLabOrderFromRecordId: async (ctx, opts) => {
const query = {
order: opts.id,
};
return mycure.diagnostic.orders().findOne(query);
},
getRecordsByProvider: async (ctx, opts = {}) => {
const { type, provider, encounter } = opts;
const query = {
type,
encounter,
$or: [
{ provider },
{ doctor: provider },
{ createdBy: provider },
],
$populate: {
createdByDetails: {
service: 'personal-details',
idField: 'id',
method: 'findOne',
key: 'createdBy',
},
createdByMembership: {
service: 'organization-members',
idField: 'uid',
method: 'findOne',
key: 'createdBy',
},
tests: {
service: 'diagnostic-tests',
method: 'find',
localKey: 'results',
extractKey: 'test',
foreignKey: 'id',
},
measures: {
service: 'diagnostic-measures',
method: 'find',
localKey: 'tests',
extractKey: 'id',
foreignKey: 'test',
},
results: {
service: 'medical-records',
method: 'find',
localKey: 'id',
foreignKey: 'order',
type: {
$in: ['lab-test-result', 'imaging-test-result'],
},
$populate: {
tests: {
service: 'diagnostic-tests',
method: 'find',
localKey: 'results',
extractKey: 'test',
foreignKey: 'id',
},
measures: {
service: 'diagnostic-measures',
method: 'find',
localKey: 'results',
extractKey: 'measure',
foreignKey: 'id',
},
},
},
},
};
const { items, total } = await mycure.medical.records().find(query);
return {
items,
total,
};
},
clearCurrentEncounterRecords: (ctx, opts) => {
ctx.commit('clearCurrentEncounterRecords');
},
};
this.mutations = {
...mapSetters(Object.keys(_.omit(this.state, ['currentEncounterRecords', 'medicalRecordsDraft']))),
setCurrentEncounterRecords: (s, val) => {
MEDICAL_RECORD_TYPES.forEach(record => {
s.currentEncounterRecords[record.type] = _.get(val, record.type) || [];
});
},
setMedicalRecordsDraft: (s, { type, data }) => {
s.medicalRecordsDraft[type] = data;
},
clearMedicalRecordsDraft: (s) => {
s.medicalRecordsDraft = {};
},
clearCurrentEncounterRecords: (s, val) => {
console.warn('clearing...');
s.currentEncounterRecords = currentEncounterRecords;
},
};
}
fetchRecord (mycure, record) {
const query = {
id: record,
$populate: {
createdByDetails: {
service: 'personal-details',
idField: 'id',
method: 'findOne',
key: 'createdBy',
},
createdByMembership: {
service: 'organization-members',
idField: 'uid',
method: 'findOne',
key: 'createdBy',
},
tests: {
service: 'diagnostic-tests',
method: 'find',
localKey: 'results',
extractKey: 'test',
foreignKey: 'id',
},
measures: {
service: 'diagnostic-measures',
method: 'find',
localKey: 'tests',
extractKey: 'id',
foreignKey: 'test',
},
results: {
service: 'medical-records',
method: 'find',
localKey: 'id',
foreignKey: 'order',
type: {
$in: ['lab-test-result', 'imaging-test-result'],
},
$populate: {
tests: {
service: 'diagnostic-tests',
method: 'find',
localKey: 'results',
extractKey: 'test',
foreignKey: 'id',
},
measures: {
service: 'diagnostic-measures',
method: 'find',
localKey: 'results',
extractKey: 'measure',
foreignKey: 'id',
},
},
},
},
};
return mycure.medical.records().findOne(query);
}
extractModule () {
return {
namespaced: true,
state: this.state,
getters: this.getters,
actions: this.actions,
mutations: this.mutations,
};
}
}
|
import { context } from '@ember/-internals/environment';
import { run } from '@ember/runloop';
import { get, setNamespaceSearchDisabled } from '@ember/-internals/metal';
import { guidFor, getName } from '@ember/-internals/utils';
import EmberObject from '../../../lib/system/object';
import Namespace from '../../../lib/system/namespace';
import { moduleFor, AbstractTestCase } from 'internal-test-helpers';
const originalLookup = context.lookup;
let lookup;
moduleFor(
'Namespace',
class extends AbstractTestCase {
beforeEach() {
setNamespaceSearchDisabled(false);
lookup = context.lookup = {};
}
afterEach() {
setNamespaceSearchDisabled(false);
for (let prop in lookup) {
if (lookup[prop]) {
run(lookup[prop], 'destroy');
}
}
context.lookup = originalLookup;
}
['@test Namespace should be a subclass of EmberObject'](assert) {
assert.ok(EmberObject.detect(Namespace));
}
['@test Namespace should be duck typed'](assert) {
let namespace = Namespace.create();
try {
assert.ok(get(namespace, 'isNamespace'), 'isNamespace property is true');
} finally {
run(namespace, 'destroy');
}
}
['@test Namespace is found and named'](assert) {
let nsA = (lookup.NamespaceA = Namespace.create());
assert.equal(
nsA.toString(),
'NamespaceA',
'namespaces should have a name if they are on lookup'
);
let nsB = (lookup.NamespaceB = Namespace.create());
assert.equal(
nsB.toString(),
'NamespaceB',
'namespaces work if created after the first namespace processing pass'
);
}
['@test Classes under an Namespace are properly named'](assert) {
let nsA = (lookup.NamespaceA = Namespace.create());
nsA.Foo = EmberObject.extend();
Namespace.processAll();
assert.equal(getName(nsA.Foo), 'NamespaceA.Foo', 'Classes pick up their parent namespace');
nsA.Bar = EmberObject.extend();
Namespace.processAll();
assert.equal(getName(nsA.Bar), 'NamespaceA.Bar', 'New Classes get the naming treatment too');
let nsB = (lookup.NamespaceB = Namespace.create());
nsB.Foo = EmberObject.extend();
Namespace.processAll();
assert.equal(
getName(nsB.Foo),
'NamespaceB.Foo',
'Classes in new namespaces get the naming treatment'
);
}
//test("Classes under Ember are properly named", function() {
// // ES6TODO: This test does not work reliably when running independent package build with Broccoli config.
// Ember.TestObject = EmberObject.extend({});
// equal(Ember.TestObject.toString(), "Ember.TestObject", "class under Ember is given a string representation");
//});
['@test Lowercase namespaces are no longer supported'](assert) {
let nsC = (lookup.namespaceC = Namespace.create());
Namespace.processAll();
assert.equal(getName(nsC), guidFor(nsC));
}
['@test A namespace can be assigned a custom name'](assert) {
let nsA = Namespace.create({
name: 'NamespaceA',
});
try {
let nsB = (lookup.NamespaceB = Namespace.create({
name: 'CustomNamespaceB',
}));
nsA.Foo = EmberObject.extend();
nsB.Foo = EmberObject.extend();
Namespace.processAll();
assert.equal(
getName(nsA.Foo),
'NamespaceA.Foo',
"The namespace's name is used when the namespace is not in the lookup object"
);
assert.equal(
getName(nsB.Foo),
'CustomNamespaceB.Foo',
"The namespace's name is used when the namespace is in the lookup object"
);
} finally {
run(nsA, 'destroy');
}
}
['@test Calling namespace.nameClasses() eagerly names all classes'](assert) {
setNamespaceSearchDisabled(true);
let namespace = (lookup.NS = Namespace.create());
namespace.ClassA = EmberObject.extend();
namespace.ClassB = EmberObject.extend();
Namespace.processAll();
assert.equal(getName(namespace.ClassA), 'NS.ClassA');
assert.equal(getName(namespace.ClassB), 'NS.ClassB');
}
['@test A namespace can be looked up by its name'](assert) {
let NS = (lookup.NS = Namespace.create());
let UI = (lookup.UI = Namespace.create());
let CF = (lookup.CF = Namespace.create());
assert.equal(Namespace.byName('NS'), NS);
assert.equal(Namespace.byName('UI'), UI);
assert.equal(Namespace.byName('CF'), CF);
}
['@test A nested namespace can be looked up by its name'](assert) {
let UI = (lookup.UI = Namespace.create());
UI.Nav = Namespace.create();
assert.equal(Namespace.byName('UI.Nav'), UI.Nav);
run(UI.Nav, 'destroy');
}
['@test Destroying a namespace before caching lookup removes it from the list of namespaces'](
assert
) {
let CF = (lookup.CF = Namespace.create());
run(CF, 'destroy');
assert.equal(Namespace.byName('CF'), undefined, 'namespace can not be found after destroyed');
}
['@test Destroying a namespace after looking up removes it from the list of namespaces'](
assert
) {
let CF = (lookup.CF = Namespace.create());
assert.equal(Namespace.byName('CF'), CF, 'precondition - namespace can be looked up by name');
run(CF, 'destroy');
assert.equal(Namespace.byName('CF'), undefined, 'namespace can not be found after destroyed');
}
}
);
|
/**
* @flow
*/
export type AttribsType = {
type: string,
id: string,
src: string;
width: string;
height: string;
}
export type NodeType = {
name: string,
attribs: AttribsType,
children?: Array<NodeType>,
type: string,
data: string,
}
export type AttachmentType = {
id: string,
src: string,
height: number,
width: number,
}
export type AttachmentsType = {
videos?: Array<AttachmentType>,
images?: Array<AttachmentType>,
}
|
module.exports = [
{ name: 'CSS Gradient', url: 'https://cssgradient.io/' },
{ name: 'Crontab Cheatsheet', url: 'https://devhints.io/cron' },
{
name: 'Moment.js Cheatsheet',
url: 'https://devhints.io/moment',
},
{ name: 'Svelte Examples', url: 'https://svelte.dev/examples' },
{
name: 'Chrome DevTools Console Utilities API',
url:
'https://developers.google.com/web/tools/chrome-devtools/console/utilities',
},
]
|
// Copyright (C) 2015 André Bargull. All rights reserved.
// Copyright (C) 2017 Mozilla Corporation. All rights reserved.
// This code is governed by the BSD license found in the LICENSE file.
/*---
description: >
Atomics.isLockFree.name is "isLockFree".
includes: [propertyHelper.js]
---*/
assert.sameValue(Atomics.isLockFree.name, "isLockFree");
verifyNotEnumerable(Atomics.isLockFree, "name");
verifyNotWritable(Atomics.isLockFree, "name");
verifyConfigurable(Atomics.isLockFree, "name");
|
import React from 'react';
const Panel = ({ children }) => <div className="panel">{children}</div>;
export default Panel;
|
/*
* Lamarr JS
*
* @author Jiri Hybek <[email protected]>
* @license See LICENSE file distriubted with this source code.
*/
var def = require("./langdef.js");
/*
* Parser exceptions
*
* @param Parser parser
* @param string message
* @param integer offset (optional)
*/
var ParserException = function(parser, message, offset){
var index = parser.index+= (offset || 0);
this.name = "ParserException";
this.message = message + " at '" + parser.source.substr(0, index) + ">>>" + parser.source.substr(index, 1) + "<<<" + parser.source.substr(index + 1) + "'.";
this.source = parser.source;
};
ParserException.prototype = Object.create(Error.prototype);
/*
* Parser library
*/
var Parser = function(){
this.source = null;
this.tokenizer = null;
this.tokenizerCb = null;
this.context = null;
this.stack = null;
this.index = null;
this.buffer = null;
this.output = null;
};
/*
* Returns buffer contents
*
* @return string
*/
Parser.prototype.getBuffer = function(){
return this.buffer;
};
/*
* Returns buffer conents and clears it
*
* @return string
*/
Parser.prototype.flushBuffer = function(){
var b = this.buffer;
this.buffer = "";
return b;
};
/*
* Clears buffer
*
* @void
*/
Parser.prototype.clearBuffer = function(){
this.buffer = "";
};
/*
* Eats pattern, if match saves to buffer, moves index and returns true, else return false
*
* @param string pattern
* @return bool
*/
Parser.prototype.eat = function(pattern, toBuffer, skip){
var haystack = this.source.substr(this.index);
var xp = new RegExp("^" + pattern);
var match = xp.exec(haystack);
if(match){
if(skip !== false) this.index+= String(match[0]).length;
if(toBuffer !== false) this.buffer+= match[0];
return true;
}
return false;
};
/*
* Eats one character and adds it to buffer
*/
Parser.prototype.next = function(){
this.buffer+= this.source.substr(this.index, 1);
this.index++;
return true;
};
/*
* Skip specified characters without adding to buffer
*
* @param integer count
*/
Parser.prototype.skip = function(count){
this.index+= (count || 1);
return true;
};
Parser.prototype.begin = function(tokenizer, context, cb){
if(this.tokenizer)
this.stack.push({
t: this.tokenizer,
c: this.context,
b: this.tokenizerCb
});
this.tokenizer = tokenizer;
this.context = context || {};
this.tokenizerCb = cb;
return true;
};
Parser.prototype.end = function(){
if(this.stack.length === 0)
return this.error("Not in scope");
if(this.tokenizerCb)
this.tokenizerCb(this.context, this.buffer);
var prev = this.stack.pop();
this.tokenizer = prev.t;
this.context = prev.c;
this.tokenizerCb = prev.b;
return true;
};
Parser.prototype.error = function(message, offset){
throw new ParserException(this, message, offset);
};
Parser.prototype.debug = function(){
console.log("---- Char: " + this.index + " ----");
console.log(this.source.substr(0, this.index) + ">>>" + this.source.substr(this.index, 1) + "<<<" + this.source.substr(this.index + 1));
console.log("----");
};
Parser.prototype.parse = function(source){
//Reset state
this.source = source;
this.tokenizer = null;
this.tokenizerCb = null;
this.context = null;
this.stack = [];
this.index = 0;
this.buffer = "";
this.output = {
"variables": {},
"nodes": {},
"edges": {},
"entities": {},
"conds": {},
"modifiers": {}
};
//Set default tokenizer
this.begin(Parser.RootTokenizer);
//Go until end
while(this.index < this.source.length){
var r = this.tokenizer.call(this, this.context);
if(r !== true)
return this.error(r || "Unexpected token");
}
if(this.stack.length > 0)
this.end();
if(this.stack.length > 0)
return this.error("Unexpected end of input");
return this.output;
};
/*
*
* Tokenizers
*
*/
Parser.RootTokenizer = function(ctx){
//Multiline comment
if(this.eat(def.mlCommentOpen))
return this.begin(Parser.MultilineCommentTokenizer);
//Single line comment
if(this.eat(def.comment))
return this.begin(Parser.CommentTokenizer);
if(this.eat(def.sectionNodes))
return this.begin(Parser.NodesTokenizer);
//Blank line
if(this.eat(def.blank))
return true;
};
Parser.CommentTokenizer = function(ctx){
if(this.eat(def.lineEnd)){
return this.end();
} else {
return this.next();
}
};
Parser.MultilineCommentTokenizer = function(ctx){
if(this.eat(def.mlCommentClose)){
return this.end();
} else {
return this.next();
}
};
Parser.StringTokenizer = function(ctx){
if(!ctx.contents) ctx.contents = "";
if(this.eat("\\\\", false))
return this.next();
if(this.eat(def.stringClose, false))
return this.end();
return this.eat(".");
};
Parser.VarDeclarationTokenizer = function(ctx){
this.clearBuffer();
//Get name
if(!ctx.name && this.eat(def.varName)){
ctx.name = this.flushBuffer();
return true;
}
//Assign and get expression
if(ctx.name && !ctx.assignment && this.eat(def.varAssignment)){
ctx.assignment = true;
return this.begin(Parser.ExpressionTokenizer, {}, function(ectx){
ctx.expression = ectx.expression;
});
}
//Line end
if(ctx.name && this.eat(def.lineEnd))
return this.end();
//Blank
if(this.eat(def.blank))
return true;
if(!ctx.name) return "Expecting variable name";
if(!ctx.assignment) return "Expecting variable assignment";
if(!ctx.expression) return "Expecting expression";
};
Parser.ExpressionTokenizer = function(ctx){
if(ctx.expression === undefined) ctx.expression = "";
if(ctx.mode === undefined) ctx.mode = 0;
this.clearBuffer();
//Basic operators
if(this.eat(def.expOperators)){
if(ctx.mode < 1) return "Expecting operand";
ctx.expression+= this.getBuffer();
ctx.mode = 0;
return true;
}
//Function operand
if(this.eat(def.expFunction)){
if(ctx.mode !== 0) return "Unexpected operand";
var fnName;
var argCount;
var token = this.getBuffer();
var name = token.substr(0, token.length - 1).toLowerCase();
switch(name){
case 'min': fnName = "Math.min"; break;
case 'max': fnName = "Math.max"; break;
case 'abs': fnName = "Math.abs"; argCount = 1; break;
case 'pow': fnName = "Math.pow"; argCount = 2; break;
case 'callmod': fnName = "helpers.callmod"; break;
default: return "Undefined function '" + name + "'";
}
return this.begin(Parser.ExpressionArgsTokenizer, { _fnName: fnName, argcount: argCount }, function(_ctx){
ctx.expression+= _ctx._fnName + "(" + _ctx.args.join(",") + ")";
ctx.mode = 1;
});
}
//Sub expression open
if(this.eat(def.expOpen)){
if(ctx.mode !== 0) return "Unexpected operand";
return this.begin(Parser.ExpressionTokenizer, { sub: true }, function(_ctx){
ctx.expression+= "(" + _ctx.expression + ")";
ctx.mode = 1;
});
}
//Constants
if(this.eat(def.expConstants)){
if(ctx.mode !== 0) return "Unexpected operand";
var constToken = this.getBuffer().toLowerCase();
switch(constToken){
case 'true': ctx.expression+= "1"; break;
case 'false': ctx.expression+= "0"; break;
case 'null': ctx.expression+= "0"; break;
default: return "Internal parser error (const not implemented)";
}
ctx.mode = 1;
}
//Numeric operand
if(this.eat("[0-9]+(\.[0-9]+)?")){
if(ctx.mode !== 0) return "Unexpected operand";
ctx.expression+= this.getBuffer();
ctx.mode = 1;
return true;
}
//Dot notation
if(this.eat(def.expProperty)){
if(ctx.mode !== 2) return "Unexpected dot notation";
var propName = this.getBuffer();
ctx.expression+= '["' + propName.substr(1) + '"]';
ctx.mode = 2;
return true;
}
//Local variable operand
if(this.eat(def.expLocalVar)){
if(ctx.mode !== 0) return "Unexpected operand";
var lvarName = this.getBuffer();
ctx.expression+= 'locals["' + lvarName.substr(1) + '"]';
ctx.mode = 2;
return true;
}
//Global variable operand
if(this.eat(def.expGlobalVar)){
if(ctx.mode !== 0) return "Unexpected operand";
var gvarName = this.getBuffer();
ctx.expression+= 'globals["' + gvarName + '"]';
ctx.mode = 2;
return true;
}
//Subexpression end
if(ctx.sub && this.eat(( ctx.expClose ? ctx.expClose : def.expClose ), false, ( ctx.skipClose === false ? false : true ))){
if(ctx.mode < 1) return "Unterminated expression";
return this.end();
}
//End
if(!ctx.sub && this.eat(def.lineEnd, false, false)){
if(ctx.expression === "") return "Empty expression";
if(ctx.mode < 1) return "Unterminated expression";
ctx.fn = 'function(locals, globals, helpers){return ' + ctx.expression + ';}';
return this.end();
}
//Blank
if(this.eat(def.blank))
return true;
};
Parser.ExpressionArgsTokenizer = function(ctx){
if(ctx.args === undefined){
ctx.args = [];
return this.begin(Parser.ExpressionTokenizer, { sub: true, skipClose: false, expClose: def.expArgDelimiter }, function(_ctx){
ctx.args.push(_ctx.expression);
});
}
if(this.eat(def.expClose)){
if(ctx.argcount !== undefined && ctx.argcount != ctx.args.length)
return "Expecting {" + ctx.argcount + "} arguments";
return this.end();
}
if(this.eat(def.expArgDelimiter)){
if(ctx.args.length === 0) return "Expecting argument expression.";
this.begin(Parser.ExpressionTokenizer, { sub: true, skipClose: false, expClose: def.expArgDelimiter }, function(_ctx){
ctx.args.push(_ctx.expression);
});
}
//Blank
if(this.eat(def.blank))
return true;
};
Parser.NodesTokenizer = function(ctx){
this.clearBuffer();
if(ctx.mode < 1 && this.eat(def.lineEnd)){
ctx.mode = 1;
return this.begin(Parser.NodesRecordTokenizer);
}
if(ctx.mode > 0 && this.eat(def.lineEnd)){
return this.end();
}
if()
//Blank
if(this.eat(def.blank))
return true;
};
/*
* Parse shorthand
*
* Creates parser and parses source
*
* @param string source
* @return object
*/
Parser.parse = function(source){
var p = new Parser();
return p.parse(source);
};
//EXPORT
module.exports = Parser; |
angular.module('adminNg.resources')
.factory('NewEventProcessingResource', ['$resource', function ($resource) {
var transform = function (data) {
var result = [];
try {
result = JSON.parse(data);
} catch (e) { }
return result;
};
return $resource('/admin-ng/event/new/processing', {}, {
get: { method: 'GET', isArray: true, transformResponse: transform }
});
}]);
|
/*global define*/
define(function() {
"use strict";
/**
* Functions for performing Lagrange interpolation.
* @exports LagrangePolynomialApproximation
*
* @see LinearApproximation
* @see HermitePolynomialApproximation
*/
var LagrangePolynomialApproximation = {
type : 'Lagrange'
};
/**
* Given the desired degree, returns the number of data points required for interpolation.
*
* @memberof LagrangePolynomialApproximation
*
* @param degree The desired degree of interpolation.
*
* @returns The number of required data points needed for the desired degree of interpolation.
*/
LagrangePolynomialApproximation.getRequiredDataPoints = function(degree) {
return Math.max(degree + 1.0, 2);
};
/**
* <p>
* Interpolates values using Lagrange Polynomial Approximation.
* </p>
*
* @param {Number} x The independent variable for which the dependent variables will be interpolated.
*
* @param {Array} xTable The array of independent variables to use to interpolate. The values
* in this array must be in increasing order and the same value must not occur twice in the array.
*
* @param {Array} yTable The array of dependent variables to use to interpolate. For a set of three
* dependent values (p,q,w) at time 1 and time 2 this should be as follows: {p1, q1, w1, p2, q2, w2}.
*
* @param {Number} yStride The number of dependent variable values in yTable corresponding to
* each independent variable value in xTable.
*
* @param {Array} [result] An existing array into which to store the result.
*
* @returns The array of interpolated values, or the result parameter if one was provided.
*
* @see LinearApproximation
* @see HermitePolynomialApproximation
*
* @memberof LagrangePolynomialApproximation
*/
LagrangePolynomialApproximation.interpolateOrderZero = function(x, xTable, yTable, yStride, result) {
if (typeof result === 'undefined') {
result = new Array(yStride);
}
var i;
var j;
var length = xTable.length;
for (i = 0; i < yStride; i++) {
result[i] = 0;
}
for (i = 0; i < length; i++) {
var coefficient = 1;
for (j = 0; j < length; j++) {
if (j !== i) {
var diffX = xTable[i] - xTable[j];
coefficient *= (x - xTable[j]) / diffX;
}
}
for (j = 0; j < yStride; j++) {
result[j] += coefficient * yTable[i * yStride + j];
}
}
return result;
};
return LagrangePolynomialApproximation;
}); |
// # Ghost bootloader
// Orchestrates the loading of Ghost
// When run from command line.
var express,
ghost,
parentApp,
errors;
var path = require('path');
var hbs = require('express-hbs');
// Make sure dependencies are installed and file system permissions are correct.
require('./core/server/utils/startup-check').check();
// Proceed with startup
express = require('express');
ghost = require('./core');
errors = require('./core/server/errors');
// Create our parent express app instance.
parentApp = express();
ghost().then(function (ghostServer) {
// Mount our ghost instance on our desired subdirectory path if it exists.
parentApp.use(ghostServer.config.paths.subdir, ghostServer.rootApp);
// Load helpers if available
try {
var helpersPath = path.join(ghostServer.config.paths.contentPath, 'helpers');
var helpers = require(helpersPath);
helpers(hbs);
} catch (error) {
console.error(('Error loading helpers: ' + error.message).red);
}
// Let ghost handle starting our server instance.
ghostServer.start(parentApp);
}).catch(function (err) {
errors.logErrorAndExit(err, err.context, err.help);
});
|
import React from 'react'
import './ExtensionControls.css'
export const ControlMeta = ( {
title,
description,
error
} ) => (
<div className='control-meta'>
<div
className='control-meta-error'
style={ { display: error ? '' : 'none' } }>
{ error ? error.toString(): null }
</div>
<div className='control-meta-title'>
{ title }
</div>
<div className='control-meta-description'>
{ description }
</div>
</div>
)
export const SelectControlItem = ( {
value,
error,
onChange,
item: {
options,
title,
description
}
} ) => {
const optionItems = options.map( ( [ val, label ] ) => (
<option
key={ val }
value={ val }>
{ label }
</option>
) )
return (
<div className='control-item control-select'>
<ControlMeta
error={ error }
title={ title }
description={ description } />
<select
onChange={ e => onChange( e.target.value ) }
value={ value }>
{ optionItems }
</select>
</div>
)
}
export const TextControlItem = ( {
value,
error,
onChange,
item: {
title,
description,
inputType='text'
}
} ) => (
<div className='control-item control-text'>
<ControlMeta
error={ error }
title={ title }
description={ description } />
<input
type={ inputType }
value={ value !== null? value : '' }
onChange={ e => onChange( e.target.value ) } />
</div>
)
export class ControlGroup extends React.Component {
state = {
values: {}
}
onSubmit = () => {
const controlValues = {}
this.props.item.controls.forEach( control => controlValues[ control.key ] = control.value )
this.props.onChange( {
...controlValues,
...this.state.values
} )
}
onChange = ( key, value ) => {
console.log( `Set ${this.props.item.key}.${key} to ${JSON.stringify(value)}` )
this.setState( {
values: {
...this.state.values,
[key]: value
}
} )
}
render() {
const {
error,
item
} = this.props
const {
submit_label,
controls
} = item
const {
values
} = this.state
const controlItems = controls.map( control => (
<ControlItem
key={ control.key }
item={ control }
value={ values[ control.key ] }
onChange={ value => this.onChange( control.key, value ) } />
) )
return (
<div className='control-group'>
<ControlMeta error={ error } />
<div className='control-group-items'>
{ controlItems }
</div>
<button onClick={ this.onSubmit }>
{ submit_label }
</button>
</div>
)
}
}
export const ControlItem = ( {
item,
value,
error,
onChange
} ) => {
if ( !EXTENSION_CONTROLS_TYPE_MAP[ item.type ] )
return null
return React.createElement( EXTENSION_CONTROLS_TYPE_MAP[ item.type ], {
item,
onChange,
error,
value: typeof value !== 'undefined'? value : item.value
} )
}
export const EXTENSION_CONTROLS_TYPE_MAP = {
controlgroup: ControlGroup,
select: SelectControlItem,
text: TextControlItem
}
|
{
"global" : {
"save" : "ذخیره",
"cancel" : "لغو",
"delete" : "حذف",
"required" : "لازم",
"download" : "بارگیری",
"link" : "پیوند",
"bookmark" : "بوکمارک",
"close" : "بستن",
"tags" : "برجسپها"
},
"tree" : {
"subscribe" : "مشترک شوید",
"import" : "درونریزی",
"new_category" : "ردهٔ جدید",
"all" : "کل مطالب",
"starred" : "ستارهدار"
},
"subscribe" : {
"feed_url" : "نشانی خوراک",
"feed_name" : "نام خوراک",
"category" : "دسته"
},
"import" : {
"google_reader_prefix" : "اجازه بده خوراکهایتان را از حساب",
"google_reader_suffix" : "وارد سازم.",
"google_download" : "یا به جای آن، پروندهٔ subscriptions.xml خود را بارگذاری کنید.",
"google_download_link" : "آن را اینجا بارگیری کنید.",
"xml_file" : "پروندهٔ OPML"
},
"new_category" : {
"name" : "نام",
"parent" : "پدر"
},
"toolbar" : {
"unread" : "خواندهنشده",
"all" : "همه",
"previous_entry" : "مطلب قبلی",
"next_entry" : "مطلب بعدی",
"refresh" : "تازهسازی",
"refresh_all" : "مجبورکردن تازهسازی همهٔ خوراکها",
"sort_by_asc_desc" : "مرتبکردن بر اساس تاریخ بهصورت صعودی/نزولی",
"titles_only" : "فقط عنوانها",
"expanded_view" : "نمای گسترشیافته",
"mark_all_as_read" : "علامتگذاری تمامی مطالب بهعنوان خواندهشده",
"mark_all_older_12_hours" : "مطالب قدیمیتر از ۱۲ ساعت",
"mark_all_older_day" : "مطالب قدیمیتر از یک روز",
"mark_all_older_week" : "مطالب قدیمیتر از یک هفته",
"mark_all_older_two_weeks" : "مطالب قدیمی تر از چند هفته قیل",
"settings" : "تنظیمات",
"profile" : "نمایه",
"admin" : "مدیریت",
"about" : "درباره",
"logout" : "خروج",
"donate" : "کمک مالی"
},
"view" : {
"entry_source" : "از",
"entry_author" : "توسط",
"error_while_loading_feed" : "متأسفانه، هنگام بارگیری این خوراک خطایی رخدادهاست.",
"keep_unread" : "خواندهنشده نگهدار",
"no_unread_items" : "هیچ مطلب خواندهنشدهای ندارد.",
"mark_up_to_here" : "تا اینجا را خواندهشده در نظر بگیر",
"search_for" : "جستجو برای:",
"no_search_results" : "هیج نتیجهای برای کلیدواژههای درخواستی یافت نشد"
},
"feedsearch" : {
"hint" : "نوشتن بر روی یک اشتراک...",
"help" : "دکمهٔ بازگشت برای انتخاب و دکمههای جهتدار را برای ناوبری استفاده کن.",
"result_prefix" : "اشتراکهای شما:"
},
"settings" : {
"general" : {
"value" : "همگانی",
"language" : "زبان",
"language_contribute" : "مشارکت در ترجمه",
"show_unread" : "تنها خوراکها و دستههای را که دارای مطالب نخوانده هستند نمایش بده.",
"social_buttons" : "نشاندادن دکمههای اشتراکگذاری در شبکههای اجتماعی",
"scroll_marks" : "در نمای گسترشیافته، لغزیدن بر روی مطالب بهعنوان نشانهگذاری بهعنوان خواندهشده در نظر گرفتهشوند."
},
"appearance" : "ظاهر",
"scroll_speed" : "سرعت لغزش هنگام گشتن بین مدخلها (به میلیثانیه)",
"scroll_speed_help" : "قراردادن به ۰ برای غیرفعالکردن",
"theme" : "پوسته",
"submit_your_theme" : "پوستهٔ خود را ارسالکنید",
"custom_css" : "سیاساس شخصیسازیشده"
},
"details" : {
"feed_details" : "جزئیات خوراک",
"url" : "نشانی",
"website" : "وبگاه",
"name" : "نام",
"category" : "دسته",
"position" : "موقعیت",
"last_refresh" : "آخرین بروزرسانی",
"message" : "پیام آخرین تازهسازی",
"next_refresh" : "بروزرسانی بعدی",
"queued_for_refresh" : "منتظر برای بروزرسانی",
"feed_url" : "نشانی خوراک",
"generate_api_key_first" : "ابتدا یک کلید API در نمایهٔ خود ایجاد کنید.",
"unsubscribe" : "لغو اشتراک",
"unsubscribe_confirmation" : "مطمئنید میخواهید از این این لغو اشتراک کنید؟",
"delete_category_confirmation" : "مطمئنید میخواهید این رده را حذف کنید؟",
"category_details" : "جزئیات دسته",
"tag_details" : "جزئیات برچسپ",
"parent_category" : "ردهٔ پدر"
},
"profile" : {
"user_name" : "نام کاربری",
"email" : "رایانامه",
"change_password" : "تغییر گذرواژه",
"confirm_password" : "تأیید گذرواژه",
"minimum_6_chars" : "حداقل ۶ نویسه",
"passwords_do_not_match" : "گذرواژهها انطباق ندارند",
"api_key" : "کلید API",
"api_key_not_generated" : "هنوز ایجاد نشدهاست",
"generate_new_api_key" : "ایجاد کلید جدید API",
"generate_new_api_key_info" : "تغییر گذرواژه کلید API بهوجود خواهد آورد.",
"opml_export" : "خارجسازی OPML",
"delete_account" : "حذف حساب کاربری",
"delete_account_confirmation" : "حذف حسابتان؟ بازگشتی وجود ندارد!"
},
"about" : {
"rest_api" : {
"value" : "REST API",
"line1" : "کامافید بر روی JAX-RS و AngularJS ساختهشدهاست. به همین دلیل API REST موجود است.",
"link_to_documentation" : "پیوند به مستندات."
},
"keyboard_shortcuts" : "کلیدهای میانبر",
"version" : "نسخهٔ کامافید",
"line1_prefix" : "کامافید یک پروژه متنباز است. مخازن آن در ",
"line1_suffix" : "میزبانی میشود.",
"line2_prefix" : "اگر شما به مسئلهای برخورده اید، لطفاً آن را در صفحه مسائل گزارش دهید ",
"line2_suffix" : " پروژه.",
"line3" : "در صورتی که شما به این پروژه علاقمندید، لطفاً مبلغی را هرچند ناچیزه برای حمایت از توسعهدهنده و کمک به تأمین هزینههای نگهداری این وبگاه کمک کنید.",
"line4" : "برای کسانی که بیتکوین را ترجیح میدهند، نشانی آن اینجاست",
"goodies" : {
"value" : "افزونهها",
"android_app" : "برنامهٔ اندرویدی",
"subscribe_url" : "اشتراک در نشانی",
"chrome_extension" : "افزونهٔ کروم",
"firefox_extension" : "افزونهٔ فایرفاکس",
"opera_extension" : "افزونهٔ اپرا",
"subscribe_bookmarklet" : "افزودن بوکمارکلت اشتراک (با کلیک)",
"subscribe_bookmarklet_asc" : "اول قدیمیترینها",
"subscribe_bookmarklet_desc" : "اول جدیدترینها",
"next_unread_bookmarklet" : "بوکمارکلت مطلب خوانده نشدهٔ بعدی(با کشیدن و رهاکردن در نوار بوکمارکلت)"
},
"translation" : {
"value" : "ترجمه",
"message" : "ما به کمک شما برای ترجمهٔ کامافید نیازمدیم.",
"link" : "ببینید چگونه میتوان در ترجمههای مشارکت نمود."
},
"announcements" : "اطلاعیهها",
"shortcuts" : {
"mouse_middleclick" : "کلیک وسطی موشواره",
"open_next_entry" : "بازکردن مطلب بعدی",
"open_previous_entry" : "بازکردن مطلب قبلی",
"spacebar" : "space/shift+space",
"move_page_down_up" : "صفحه را بالا/پایین انتقال میدهد",
"focus_next_entry" : "رفتن بر روی مطلب بعدی بدون بازکردن کامل آن",
"focus_previous_entry" : "رفتن بر روی مطلب بعدی قبلی بازکردن کامل آن",
"open_next_feed" : "بازکردن خوراک یا دستهٔ بعدی",
"open_previous_feed" : "بازکردن خوراک یا دستهٔ بعدی",
"open_close_current_entry" : "باز/بستن مطلب جاری",
"open_current_entry_in_new_window" : "بازکردن مطلب جاری در پنجرهای جدید",
"open_current_entry_in_new_window_background" : "بازکردن مطلب جاری در پنجرهای جدید در پسزمینه",
"star_unstar" : "نشانهدارکردن/نکردن مطلب جاری",
"mark_current_entry" : "علامتگذاری مطلب جاری بهعنوان خواندهشده/نشده",
"mark_all_as_read" : "علامتگذاری تمامی مطالب بهعنوان خواندهشده",
"open_in_new_tab_mark_as_read" : "بازکردن مطلب در سربرگ جدید و علامتگذاری آن بهعنوان خواندهشده",
"fullscreen" : "فعال/غیرفعالکردن حالت تمام صفحه",
"font_size" : "افزایش/کاهش اندازهٔ قلم مدخل فعلی",
"go_to_all" : "رفتن به نمای همه",
"go_to_starred" : "رفتن به نمای ستاره دادهشدهها",
"feed_search" : "ناوبری به یک اشتراک با نوشتن نام اشتراک"
}
}
} |
import torch
import torch.nn as nn
import torch.nn.functional as F
# this class is heavily based on the one implemented in the tutorial from pytorch
# and forum https://discuss.pytorch.org/t/lstm-to-bi-lstm/12967
class BiLSTMClassifier(nn.Module):
def __init__(self, embedding_dim, hidden_dim, sentset_size, num_layers, batch_size, bidirectional=True, dropout=0.):
super(BiLSTMClassifier, self).__init__()
self.hidden_dim = hidden_dim
self.batch_size = batch_size
self.num_layers = num_layers
self.bidirectional = bidirectional
# The LSTM takes word embeddings as inputs, and outputs hidden states
# with dimensionality hidden_dim.
self.lstm = nn.LSTM(embedding_dim, hidden_dim, bidirectional=True, num_layers=num_layers, dropout=dropout, batch_first=True, bias=False)
# The linear layer that maps from hidden state space to sentiment classification space
self.hidden2sent = nn.Linear(hidden_dim * 2, sentset_size)
self.hidden = self.init_hidden()
self.loss_fn = nn.BCEWithLogitsLoss(reduction='mean')
def init_hidden(self):
if self.bidirectional:
directions = 2
else:
directions = 1
# As of the documentation from nn.LSTM in pytorch, the input to the lstm cell is
# the input and a tuple of (h, c) hidden state and memory state. We initialize that
# tuple with the proper shape: num_layers*directions, batch_size, hidden_dim. Don't worry
# that the batch here is second, this is dealt with internally if the lstm is created with
# batch_first=True
shape = (self.num_layers * directions, self.batch_size, self.hidden_dim)
return (torch.zeros(shape, requires_grad=True), torch.zeros(shape, requires_grad=True))
def loss(self, predicted, target):
return self.loss_fn(predicted, target)
def forward(self, input):
lstm_out, self.hidden = self.lstm(input, self.hidden)
# we use the last lstm output for classification
sent_space = self.hidden2sent(lstm_out[:, -1, :])
sent_scores = F.softmax(sent_space, dim=1)
return sent_scores
|
import numpy as NP
import numpy.ma as MA
import multiprocessing as MP
import itertools as IT
import copy
import h5py
import scipy.constants as FCNST
import scipy.sparse as SpM
from astropy.io import fits
import matplotlib.pyplot as PLT
import progressbar as PGB
from astroutils import DSP_modules as DSP
from astroutils import geometry as GEOM
from astroutils import gridding_modules as GRD
from astroutils import mathops as OPS
from astroutils import lookup_operations as LKP
import aperture as APR
################### Routines essential for parallel processing ################
def unwrap_antenna_FT(args, **kwargs):
return Antenna.FT_pp(*args, **kwargs)
def unwrap_interferometer_FX(args, **kwargs):
return Interferometer.FX_pp(*args, **kwargs)
def unwrap_interferometer_stack(args, **kwargs):
return Interferometer.stack_pp(*args, **kwargs)
def unwrap_antenna_update(args, **kwargs):
return Antenna.update_pp(*args, **kwargs)
def unwrap_interferometer_update(args, **kwargs):
return Interferometer.update_pp(*args, **kwargs)
def antenna_grid_mapping(gridind_raveled, values, bins=None):
if bins is None:
raise ValueError('Input parameter bins must be specified')
if NP.iscomplexobj(values):
retval = OPS.binned_statistic(gridind_raveled, values.real, statistic='sum', bins=bins)[0]
retval = retval.astype(NP.complex64)
retval += 1j * OPS.binned_statistic(gridind_raveled, values.imag, statistic='sum', bins=bins)[0]
else:
retval = OPS.binned_statistic(gridind_raveled, values, statistic='sum', bins=bins)[0]
# print MP.current_process().name
return retval
def antenna_grid_mapping_arg_splitter(args, **kwargs):
return antenna_grid_mapping(*args, **kwargs)
def antenna_grid_mapper(gridind_raveled, values, bins, label, outq):
if NP.iscomplexobj(values):
retval = OPS.binned_statistic(gridind_raveled, values.real, statistic='sum', bins=bins)[0]
retval = retval.astype(NP.complex64)
retval += 1j * OPS.binned_statistic(gridind_raveled, values.imag, statistic='sum', bins=bins)[0]
else:
retval = OPS.binned_statistic(gridind_raveled, values, statistic='sum', bins=bins)[0]
outdict = {}
outdict[label] = retval
# print MP.current_process().name
outq.put(outdict)
def baseline_grid_mapping(gridind_raveled, values, bins=None):
if bins is None:
raise ValueError('Input parameter bins must be specified')
if NP.iscomplexobj(values):
retval = OPS.binned_statistic(gridind_raveled, values.real, statistic='sum', bins=bins)[0]
retval = retval.astype(NP.complex64)
retval += 1j * OPS.binned_statistic(gridind_raveled, values.imag, statistic='sum', bins=bins)[0]
else:
retval = OPS.binned_statistic(gridind_raveled, values, statistic='sum', bins=bins)[0]
# print MP.current_process().name
return retval
def baseline_grid_mapping_arg_splitter(args, **kwargs):
return baseline_grid_mapping(*args, **kwargs)
def baseline_grid_mapper(gridind_raveled, values, bins, label, outq):
if NP.iscomplexobj(values):
retval = OPS.binned_statistic(gridind_raveled, values.real, statistic='sum', bins=bins)[0]
retval = retval.astype(NP.complex64)
retval += 1j * OPS.binned_statistic(gridind_raveled, values.imag, statistic='sum', bins=bins)[0]
else:
retval = OPS.binned_statistic(gridind_raveled, values, statistic='sum', bins=bins)[0]
outdict = {}
outdict[label] = retval
# print MP.current_process().name
outq.put(outdict)
def find_1NN_arg_splitter(args, **kwargs):
return LKP.find_1NN(*args, **kwargs)
def genMatrixMapper_arg_splitter(args, **kwargs):
return genMatrixMapper(*args, **kwargs)
def genMatrixMapper(val, ind, shape):
if not isinstance(val, NP.ndarray):
raise TypeError('Input parameter val must be a numpy array')
if not isinstance(ind, (list,tuple)):
raise TypeError('Input parameter ind must be a list or tuple containing numpy arrays')
if val.size != ind[0].size:
raise ValueError('Input parameters val and ind must have the same size')
if not isinstance(shape, (tuple,list)):
raise TypeError('Input parameter shape must be a tuple or list')
if len(ind) != len(shape):
raise ValueError('Number of index groups in input parameter must match the number of dimensions specified in input parameter shape')
if len(ind) > 1:
for i in range(len(ind)-1):
if ind[i+1].size != ind[i].size:
raise ValueError('All index groups must have same size')
return SpM.csr_matrix((val, ind), shape=shape)
def unwrap_multidim_product(args, **kwargs):
return multidim_product(*args, **kwargs)
def multidim_product(spmat, dnsmat1, dnsmat2, spmatshape):
dnsmat = dnsmat1 * dnsmat2
return spmat.toarray().reshape(spmatshape)[NP.newaxis,:,:,:] * dnsmat[:,NP.newaxis,NP.newaxis,:]
################################################################################
def evalApertureResponse(wts_grid, ulocs, vlocs, pad=0, skypos=None):
"""
--------------------------------------------------------------------------
Evaluate response on sky from aperture weights on the UV-plane. It applies
to both single antennas and antenna pairs
Inputs:
wts_grid [numpy array or scipy sparse matrix] Complex weights on
the aperture-plane and along frequency axis. It can be a numpy
array of size nv x nu x nchan or a scipy sparse matrix of
size (nv x nu) x nchan.
ulocs [numpy array] u-locations on grid. It is of size nu and must
match the dimension in wts_grid
vlocs [numpy array] v-locations on grid. It is of size nv and must
match the dimension in wts_grid
pad [integer] indicates the amount of padding before estimating
power pattern. Applicable only when skypos is set to None.
The output power pattern will be of size 2**pad-1 times the
size of the UV-grid along l- and m-axes. Value must
not be negative. Default=0 (implies no padding). pad=1
implies padding by factor 2 along u- and v-axes
skypos [numpy array] Positions on sky at which power pattern is
to be esimated. It is a 2- or 3-column numpy array in
direction cosine coordinates. It must be of size nsrc x 2
or nsrc x 3. If set to None (default), the power pattern is
estimated over a grid on the sky. If a numpy array is
specified, then power pattern at the given locations is
estimated.
Outputs:
pbinfo is a dictionary with the following keys and values:
'pb' [numpy array] If skypos was set to None, the numpy array is
3D masked array of size nm x nl x nchan. The mask is based on
which parts of the grid are valid direction cosine coordinates
on the sky. If skypos was a numpy array denoting specific sky
locations, the value in this key is a 2D numpy array of size
nsrc x nchan
'llocs' [None or numpy array] If the power pattern estimated is a grid
(if input skypos was set to None), it contains the l-locations
of the grid on the sky. If input skypos was not set to None,
the value under this key is set to None
'mlocs' [None or numpy array] If the power pattern estimated is a grid
(if input skypos was set to None), it contains the m-locations
of the grid on the sky. If input skypos was not set to None,
the value under this key is set to None
------------------------------------------------------------------------
"""
try:
wts_grid, ulocs, vlocs
except NameError:
raise NameError('Inputs wts_grid, ulocs and vlocs must be specified')
if skypos is not None:
if not isinstance(skypos, NP.ndarray):
raise TypeError('Input skypos must be a numpy array')
if skypos.ndim != 2:
raise ValueError('Input skypos must be a 2D numpy array')
if (skypos.shape[1] < 2) or (skypos.shape[1] > 3):
raise ValueError('Input skypos must be a 2- or 3-column array')
skypos = skypos[:,:2]
if NP.any(NP.sum(skypos**2, axis=1) > 1.0):
raise ValueError('Magnitude of skypos direction cosine must not exceed unity')
if not isinstance(ulocs, NP.ndarray):
raise TypeError('Input ulocs must be a numpy array')
if not isinstance(vlocs, NP.ndarray):
raise TypeError('Input vlocs must be a numpy array')
if not isinstance(pad, int):
raise TypeError('Input must be an integer')
if pad < 0:
raise ValueError('Input pad must be non-negative')
ulocs = ulocs.ravel()
vlocs = vlocs.ravel()
wts_shape = wts_grid.shape
if wts_shape[0] != ulocs.size * vlocs.size:
raise ValueError('Shape of input wts_grid incompatible with that of ulocs and vlocs')
if SpM.issparse(wts_grid):
sum_wts = wts_grid.sum(axis=0).A # 1 x nchan
sum_wts = sum_wts[NP.newaxis,:,:] # 1 x 1 x nchan
else:
sum_wts = NP.sum(wts_grid, axis=(0,1), keepdims=True) # 1 x 1 x nchan
llocs = None
mlocs = None
if skypos is None:
if SpM.issparse(wts_grid):
shape_tuple = (vlocs.size, ulocs.size) + (wts_grid.shape[1],)
wts_grid = wts_grid.toarray().reshape(shape_tuple)
padded_wts_grid = NP.pad(wts_grid, (((2**pad-1)*vlocs.size/2,(2**pad-1)*vlocs.size/2),((2**pad-1)*ulocs.size/2,(2**pad-1)*ulocs.size/2),(0,0)), mode='constant', constant_values=0)
padded_wts_grid = NP.fft.ifftshift(padded_wts_grid, axes=(0,1))
wts_lmf = NP.fft.fft2(padded_wts_grid, axes=(0,1)) / sum_wts
pb = NP.fft.fftshift(wts_lmf, axes=(0,1))
llocs = NP.fft.fftshift(NP.fft.fftfreq(2**pad * ulocs.size, ulocs[1]-ulocs[0]))
mlocs = NP.fft.fftshift(NP.fft.fftfreq(2**pad * vlocs.size, vlocs[1]-vlocs[0]))
lmgrid_invalid = llocs.reshape(1,-1)**2 + mlocs.reshape(-1,1)**2 > 1.0
lmgrid_invalid = lmgrid_invalid[:,:,NP.newaxis] * NP.ones(pb.shape[2], dtype=NP.bool).reshape(1,1,-1)
pb = MA.array(pb, mask=lmgrid_invalid)
else:
gridu, gridv = NP.meshgrid(ulocs, vlocs)
griduv = NP.hstack((gridu.reshape(-1,1),gridv.reshape(-1,1)))
if SpM.issparse(wts_grid):
uvind = SpM.find(wts_grid)[0]
else:
eps = 1e-10
wts_grid = wts_grid.reshape(griduv.shape[0],-1)
uvind, freqind = NP.where(NP.abs(wts_grid) > eps)
wts_grid = SpM.csr_matrix((wts_grid[(uvind, freqind)], (uvind, freqind)), shape=(gridu.size,wts_grid.shape[1]), dtype=NP.complex64)
uniq_uvind = NP.unique(uvind)
matFT = NP.exp(-1j*2*NP.pi*NP.dot(skypos, griduv[uniq_uvind,:].T))
uvmeshind, srcmeshind = NP.meshgrid(uniq_uvind, NP.arange(skypos.shape[0]))
uvmeshind = uvmeshind.ravel()
srcmeshind = srcmeshind.ravel()
spFTmat = SpM.csr_matrix((matFT.ravel(), (srcmeshind, uvmeshind)), shape=(skypos.shape[0],griduv.shape[0]), dtype=NP.complex64)
sum_wts = wts_grid.sum(axis=0).A
pb = spFTmat.dot(wts_grid) / sum_wts
pb = pb.A
pb = pb.real
pbinfo = {'pb': pb, 'llocs': llocs, 'mlocs': mlocs}
return pbinfo
################################################################################
class CrossPolInfo(object):
"""
----------------------------------------------------------------------------
Class to manage cross polarization products of an interferometer.
Attributes:
Vt [dictionary] holds cross-correlation time series under 4 cross-
polarizations which are stored under keys 'P11', 'P12', 'P21', and
'P22'
Vf [dictionary] holds cross-correlation spectra under 4 cross-
polarizations which are stored under keys 'P11', 'P12', 'P21', and
'P22'
flag [dictionary] holds boolean flags for each of the 4 cross-
polarizations which are stored under keys 'P11', 'P12', 'P21', and
'P22'. Default=True means it is flagged.
Member functions:
__init__() Initializes an instance of class CrossPolInfo
__str__() Prints a summary of current attributes.
update_flags() Updates the flags based on current inputs and verifies and
updates flags based on current values of the electric field.
update() Updates the visibility time series and spectra for different
cross-polarizations
Read the member function docstrings for details.
----------------------------------------------------------------------------
"""
def __init__(self, nsamples=1):
"""
------------------------------------------------------------------------
Initialize the CrossPolInfo Class which manages polarization information
of an interferometer.
Class attributes initialized are:
Vt, Vf, flags, internal attributes _init_flags_on and _init_data_on
Read docstring of class PolInfo for details on these attributes.
------------------------------------------------------------------------
"""
self.Vt = {}
self.Vf = {}
self.flag = {}
self._init_flags_on = True
self._init_data_on = True
if not isinstance(nsamples, int):
raise TypeError('nsamples must be an integer')
elif nsamples <= 0:
nsamples = 1
for pol in ['P11', 'P12', 'P21', 'P22']:
self.Vt[pol] = NP.empty(nsamples, dtype=NP.complex64)
self.Vf[pol] = NP.empty(nsamples, dtype=NP.complex64)
self.Vt[pol].fill(NP.nan)
self.Vf[pol].fill(NP.nan)
self.flag[pol] = True
############################################################################
def __str__(self):
return ' Instance of class "{0}" in module "{1}" \n flag (P11): {2} \n flag (P12): {3} \n flag (P21): {4} \n flag (P22): {5} '.format(self.__class__.__name__, self.__module__, self.flag['P11'], self.flag['P12'], self.flag['P21'], self.flag['P22'])
############################################################################
def update_flags(self, flags=None, verify=True):
"""
------------------------------------------------------------------------
Updates the flags based on current inputs and verifies and updates flags
based on current values of the visibilities.
Inputs:
flags [dictionary] holds boolean flags for each of the 4 cross-
polarizations which are stored under keys 'P11', 'P12', 'P21',
and 'P22'. Default=None means no new flagging to be applied. If
the value under the cross-polarization key is True, it is to be
flagged and if False, it is to be unflagged.
verify [boolean] If True, verify and update the flags, if necessary.
Visibilities are checked for NaN values and if found, the
flag in the corresponding polarization is set to True.
Default=True.
Flag verification and re-updating happens if flags is set to None or if
verify is set to True.
------------------------------------------------------------------------
"""
if not isinstance(verify, bool):
raise TypeError('Input keyword verify must be of boolean type')
if flags is not None:
if not isinstance(flags, dict):
raise TypeError('Input parameter flags must be a dictionary')
for pol in ['P11', 'P12', 'P21', 'P22']:
if pol in flags:
if isinstance(flags[pol], bool):
self.flag[pol] = flags[pol]
else:
raise TypeError('flag values must be boolean')
self._init_flags_on = False
# self.flags = {pol: flags[pol] for pol in ['P11', 'P12', 'P21', 'P22'] if pol in flags}
# self._init_flags_on = False
# Perform flag verification and re-update current flags
if verify or (flags is None):
if not self._init_data_on:
for pol in ['P11', 'P12', 'P21', 'P22']:
if NP.any(NP.isnan(self.Vt[pol])):
self.flag[pol] = True
self._init_flags_on = False
############################################################################
def update(self, Vt=None, Vf=None, flags=None, verify=False):
"""
------------------------------------------------------------------------
Updates the visibility time series and spectra for different
cross-polarizations
Inputs:
Vt [dictionary] holds cross-correlation time series under 4 cross-
polarizations which are stored under keys 'P11', 'P12', 'P21',
and 'P22'. Default=None implies no updates for Vt.
Vf [dictionary] holds cross-correlation spectra under 4 cross-
polarizations which are stored under keys 'P11', 'P12', 'P21',
and 'P22'. Default=None implies no updates for Vt.
flag [dictionary] holds boolean flags for each of the 4 cross-
polarizations which are stored under keys 'P11', 'P12', 'P21',
and 'P22'. Default=None means no updates for flags.
verify [boolean] If True, verify and update the flags, if necessary.
Visibilities are checked for NaN values and if found, the
flag in the corresponding polarization is set to True.
Default=False.
------------------------------------------------------------------------
"""
current_flags = copy.deepcopy(self.flag)
if flags is None:
flags = copy.deepcopy(current_flags)
# if flags is not None:
# self.update_flags(flags)
if Vt is not None:
if isinstance(Vt, dict):
for pol in ['P11', 'P12', 'P21', 'P22']:
if pol in Vt:
self.Vt[pol] = Vt[pol]
if NP.any(NP.isnan(Vt[pol])):
# self.Vt[pol] = NP.nan
flags[pol] = True
# self.flag[pol] = True
self._init_data_on = False
else:
raise TypeError('Input parameter Vt must be a dictionary')
if Vf is not None:
if isinstance(Vf, dict):
for pol in ['P11', 'P12', 'P21', 'P22']:
if pol in Vf:
self.Vf[pol] = Vf[pol]
if NP.any(NP.isnan(Vf[pol])):
# self.Vf[pol] = NP.nan
flags[pol] = True
# self.flag[pol] = True
self._init_data_on = False
else:
raise TypeError('Input parameter Vf must be a dictionary')
# Update flags
self.update_flags(flags=flags, verify=verify)
################################################################################
class Interferometer(object):
"""
----------------------------------------------------------------------------
Class to manage individual 2-element interferometer information.
Attributes:
A1 [instance of class Antenna] First antenna
A2 [instance of class Antenna] Second antenna
corr_type [string] Correlator type. Accepted values are 'FX' (default) and
'XF'
label: [Scalar] A unique identifier (preferably a string) for the
antenna.
latitude: [Scalar] Latitude of the antenna's location.
location: [Instance of GEOM.Point class] The location of the antenna in
local East, North, Up coordinate system.
timestamp: [Scalar] String or float representing the timestamp for the
current attributes
timestamps [list] consists of a list of timestamps common to both of the
individual antennas in the antenna pair
t: [vector] The time axis for the time series of electric fields
f: [vector] Frequency axis obtained by a Fourier Transform of
the electric field time series. Same length as attribute t
f0: [Scalar] Center frequency in Hz.
crosspol: [Instance of class CrossPolInfo] polarization information for
the interferometer. Read docstring of class CrossPolInfo for
details
aperture [Instance of class APR.Aperture] aperture information
for the interferometer. Read docstring of class Aperture for
details
Vt_stack [dictionary] holds a stack of complex visibility time series
measured at various time stamps under 4 polarizations which are
stored under keys 'P11', 'P12', 'P21', and 'P22'. Each value
under the polarization key is stored as numpy array with rows
equal to the number of timestamps and columns equal to the
number of samples in a timeseries
Vf_stack [dictionary] holds a stack of complex visibility spectra
measured at various time stamps under 4 polarizations which are
stored under keys 'P11', 'P12', 'P21' and 'P22'. Each value
under the polarization key is stored as numpy array with rows
equal to the number of timestamps and columns equal to the
number of spectral channels
flag_stack [dictionary] holds a stack of flags appropriate for different
time stamps as a numpy array under 4 polarizations which are
stored under keys 'P11', 'P12', 'P21' and 'P22'. Each value
under the polarization key is stored as numpy array with
number of elements equal to the number of timestamps
Vf_avg [dictionary] holds in keys 'P11', 'P12', 'P21', 'P22' for each
polarization the stacked and averaged complex visibility spectra
as a numpy array where the number of rows is the number of time
bins after averaging visibilities in those time bins and the
number of columns is equal to the number of spectral channels
(same as in Vf_stack)
twts [dictionary] holds in keys 'P11', 'P12', 'P21', 'P22' for each
polarization the number of unflagged timestamps in each time
bin that contributed to the averaging of visibilities stored in
Vf_avg. Each array size equal to the number of rows in Vf_avg
under the corresponding polarization.
tbinsize [scalar or dictionary] Contains bin size of timestamps while
stacking. Default = None means all visibility spectra over all
timestamps are averaged. If scalar, the same (positive) value
applies to all polarizations. If dictionary, timestamp bin size
(positive) is provided under each key 'P11', 'P12', 'P21',
'P22'. If any of the keys is missing the visibilities for that
polarization are averaged over all timestamps.
wts: [dictionary] The gridding weights for interferometer. Different
cross-polarizations 'P11', 'P12', 'P21' and 'P22' form the keys
of this dictionary. These values are in general complex. Under
each key, the values are maintained as a list of numpy vectors,
where each vector corresponds to a frequency channel. See
wtspos_scale for more requirements.
wtspos [dictionary] two-dimensional locations of the gridding weights
in wts for each cross-polarization under keys 'P11', 'P12',
'P21', and 'P22'. The locations are in ENU coordinate system
as a list of 2-column numpy arrays. Each 2-column array in the
list is the position of the gridding weights for a corresponding
frequency channel. The size of the list must be the same as wts
and the number of channels. Units are in number of wavelengths.
See wtspos_scale for more requirements.
wtspos_scale [dictionary] The scaling of weights is specified for each
cross-polarization under one of the keys 'P11', 'P12', 'P21'
or 'P22'. The values under these keys can be either None
(default) or 'scale'. If None, numpy vectors in wts and
wtspos under corresponding keys are provided for each
frequency channel. If set to 'scale' wts and wtspos contain a
list of only one numpy array corresponding to a reference
frequency. This is scaled internally to correspond to the
first channel. The gridding positions are correspondingly
scaled to all the frequency channels.
blc [2-element numpy array] Bottom Left corner where the
interferometer contributes non-zero weight to the grid. Same
for all cross-polarizations
trc [2-element numpy array] Top right corner where the
interferometer contributes non-zero weight to the grid. Same
for all cross-polarizations
Member Functions:
__init__(): Initializes an instance of class Interferometer
__str__(): Prints a summary of current attributes
channels(): Computes the frequency channels from a temporal Fourier
Transform
FX() Computes the visibility spectrum using an FX operation,
i.e., Fourier transform (F) followed by multiplication (X)
using antenna information in attributes A1 and A2. All four
cross polarizations are computed.
FX_pp() Computes the visibility spectrum using an FX operation,
i.e., Fourier transform (F) followed by multiplication (X).
All four cross polarizations are computed. To be used
internally for parallel processing and not by the user directly
XF() Computes the visibility spectrum using an XF operation,
i.e., corss-correlation (X) followed by Fourier transform
(F) using antenna information in attributes A1 and A2. All
four cross polarizations are computed.
f2t() Computes the visibility time-series from the spectra for each
cross-polarization
t2f() Computes the visibility spectra from the time-series for each
cross-polarization
FX_on_stack()
Computes the visibility spectrum using an FX operation on the
time-stacked electric fields in the individual antennas in the
pair, i.e., Fourier transform (F) followed by multiplication
(X). All four cross-polarizations are computed.
flags_on_stack()
Computes the visibility flags from the time-stacked electric
fields for the common timestamps between the pair of antennas.
All four cross-polarizations are computed.
XF_on_stack()
Computes the visibility lags using an XF operation on the
time-stacked electric fields time-series in the individual
antennas in the pair, i.e., Cross-correlation (X) followed by
Fourier transform (F). All four cross-polarizations are
computed.
f2t_on_stack()
Computes the visibility lags from the spectra for each
cross-polarization from time-stacked visibilities
t2f_on_stack()
Computes the visibility spectra from the time-series for each
cross-polarization from time-stacked visibility lags
flip_antenna_pair()
Flip the antenna pair in the interferometer. This inverts the
baseline vector and conjugates the visibility spectra
refresh_antenna_pairs()
Update the individual antenna instances of the antenna pair
forming the interferometer with provided values
get_visibilities()
Returns the visibilities based on selection criteria on
timestamp flags, timestamps and frequency channel indices
and the type of data (most recent, stack or averaged
visibilities)
update_flags()
Updates flags for cross-polarizations from component antenna
polarization flags and also overrides with flags if provided
as input parameters
update(): Updates the interferometer instance with newer attribute values
Updates the visibility spectrum and timeseries and applies FX
or XF operation.
update_pp() Updates the interferometer instance with newer attribute
values. Updates the visibility spectrum and timeseries and
applies FX or XF operation. Used internally when parallel
processing is used. Not to be used by the user directly.
stack() Stacks and computes visibilities and flags from the individual
antennas in the pair.
accumulate() Accumulate and average visibility spectra across timestamps
under different polarizations depending on the time bin size
for the corresponding polarization.
save(): Saves the interferometer information to disk. Needs serious
development.
Read the member function docstrings for details.
----------------------------------------------------------------------------
"""
def __init__(self, antenna1, antenna2, corr_type=None, aperture=None):
"""
------------------------------------------------------------------------
Initialize the Interferometer Class which manages an interferometer's
information
Class attributes initialized are:
label, latitude, location, pol, t, timestamp, f0, f, wts, wtspos,
wtspos_scale, gridinfo, blc, trc, timestamps, Vt_stack, Vf_stack,
flag_stack, Vf_avg, twts, tbinsize, aperture
Read docstring of class Antenna for details on these attributes.
------------------------------------------------------------------------
"""
try:
antenna1, antenna2
except NameError:
raise NameError('Two individual antenna instances must be provided.')
if not isinstance(antenna1, Antenna):
raise TypeError('antenna1 not an instance of class Antenna')
if not isinstance(antenna2, Antenna):
raise TypeError('antenna2 not an instance of class Antenna')
self.A1 = antenna1
self.A2 = antenna2
if (corr_type is None) or (corr_type == 'FX'):
self.corr_type = 'FX'
elif corr_type == 'XF':
self.corr_type = corr_type
else:
raise ValueError('Invalid correlator type')
self.corr_type = corr_type
self.latitude = 0.5 * (self.A1.latitude + self.A2.latitude) # mean latitude of two antennas
self.location = self.A1.location - self.A2.location # Baseline vector
if self.A1.f0 != self.A2.f0:
raise ValueError('The center frequencies of the two antennas must be identical')
self.f0 = self.A1.f0
self.f = self.A1.f
self.label = (self.A1.label, self.A2.label)
self.t = 0.0
self.timestamp = 0.0
self.timestamps = []
if aperture is not None:
if isinstance(aperture, APR.Aperture):
if len(aperture.pol) != 4:
raise ValueError('Interferometer aperture must contain four cross-polarization types')
self.aperture = aperture
else:
raise TypeError('aperture must be an instance of class Aperture found in module {0}'.format(APR.__name__))
else:
self.aperture = APR.Aperture(pol_type='cross')
self.crosspol = CrossPolInfo(self.f.size)
self.Vt_stack = {}
self.Vf_stack = {}
self.flag_stack = {}
self.Vf_avg = {}
self.twts = {}
self.tbinsize = None
self.wtspos = {}
self.wts = {}
self.wtspos_scale = {}
self._gridinfo = {}
for pol in ['P11', 'P12', 'P21', 'P22']:
self.Vt_stack[pol] = None
self.Vf_stack[pol] = None
self.flag_stack[pol] = NP.asarray([])
self.Vf_avg[pol] = None
self.twts[pol] = None
self.wtspos[pol] = []
self.wts[pol] = []
self.wtspos_scale[pol] = None
self._gridinfo[pol] = {}
self.blc = NP.asarray([self.location.x, self.location.y]).reshape(1,-1)
self.trc = NP.asarray([self.location.x, self.location.y]).reshape(1,-1)
############################################################################
def __str__(self):
return ' Instance of class "{0}" in module "{1}" \n label: ({2[0]}, {2[1]}) \n location: {3}'.format(self.__class__.__name__, self.__module__, self.label, self.location.__str__())
############################################################################
def channels(self):
"""
------------------------------------------------------------------------
Computes the frequency channels from a temporal Fourier Transform
Output(s):
Frequencies corresponding to channels obtained by a Fourier Transform
of the time series.
------------------------------------------------------------------------
"""
return DSP.spectax(self.A1.t.size + self.A2.t.size, resolution=self.A1.t[1]-self.A1.t[0], shift=True)
############################################################################
def FX(self):
"""
------------------------------------------------------------------------
Computes the visibility spectrum using an FX operation, i.e., Fourier
transform (F) followed by multiplication (X). All four cross
polarizations are computed.
------------------------------------------------------------------------
"""
self.t = NP.hstack((self.A1.t.ravel(), self.A1.t.max()+self.A2.t.ravel()))
self.f = self.f0 + self.channels()
self.crosspol.Vf['P11'] = self.A1.antpol.Ef['P1'] * self.A2.antpol.Ef['P1'].conjugate()
self.crosspol.Vf['P12'] = self.A1.antpol.Ef['P1'] * self.A2.antpol.Ef['P2'].conjugate()
self.crosspol.Vf['P21'] = self.A1.antpol.Ef['P2'] * self.A2.antpol.Ef['P1'].conjugate()
self.crosspol.Vf['P22'] = self.A1.antpol.Ef['P2'] * self.A2.antpol.Ef['P2'].conjugate()
self.f2t()
self.crosspol._init_data_on = False
self.update_flags(flags=None, stack=False, verify=True)
############################################################################
def FX_pp(self):
"""
------------------------------------------------------------------------
Computes the visibility spectrum using an FX operation, i.e., Fourier
transform (F) followed by multiplication (X). All four cross
polarizations are computed. To be used internally for parallel
processing and not by the user directly
------------------------------------------------------------------------
"""
self.t = NP.hstack((self.A1.t.ravel(), self.A1.t.max()+self.A2.t.ravel()))
self.f = self.f0 + self.channels()
self.crosspol.Vf['P11'] = self.A1.antpol.Ef['P1'] * self.A2.antpol.Ef['P1'].conjugate()
self.crosspol.Vf['P12'] = self.A1.antpol.Ef['P1'] * self.A2.antpol.Ef['P2'].conjugate()
self.crosspol.Vf['P21'] = self.A1.antpol.Ef['P2'] * self.A2.antpol.Ef['P1'].conjugate()
self.crosspol.Vf['P22'] = self.A1.antpol.Ef['P2'] * self.A2.antpol.Ef['P2'].conjugate()
self.f2t()
self.crosspol._init_data_on = False
self.update_flags(flags=None, stack=False, verify=True)
return self
############################################################################
def XF(self):
"""
------------------------------------------------------------------------
Computes the visibility spectrum using an XF operation, i.e.,
Correlation (X) followed by Fourier transform (X). All four cross
polarizations are computed.
------------------------------------------------------------------------
"""
self.t = NP.hstack((self.A1.t.ravel(), self.A1.t.max()+self.A2.t.ravel()))
self.f = self.f0 + self.channels()
self.crosspol.Vt['P11'] = DSP.XC(self.A1.antpol.Et['P1'], self.A2.antpol.Et['P1'], shift=False)
self.crosspol.Vt['P12'] = DSP.XC(self.A1.antpol.Et['P1'], self.A2.antpol.Et['P2'], shift=False)
self.crosspol.Vt['P21'] = DSP.XC(self.A1.antpol.Et['P2'], self.A2.antpol.Et['P1'], shift=False)
self.crosspol.Vt['P22'] = DSP.XC(self.A1.antpol.Et['P2'], self.A2.antpol.Et['P2'], shift=False)
self.t2f()
self.crosspol._init_data_on = False
self.update_flags(flags=None, stack=False, verify=True)
############################################################################
def f2t(self):
"""
------------------------------------------------------------------------
Computes the visibility time-series from the spectra for each cross-
polarization
------------------------------------------------------------------------
"""
for pol in ['P11', 'P12', 'P21', 'P22']:
self.crosspol.Vt[pol] = DSP.FT1D(NP.fft.fftshift(self.crosspol.Vf[pol]), inverse=True, shift=True, verbose=False)
############################################################################
def t2f(self):
"""
------------------------------------------------------------------------
Computes the visibility spectra from the time-series for each cross-
polarization
------------------------------------------------------------------------
"""
for pol in ['P11', 'P12', 'P21', 'P22']:
self.crosspol.Vf[pol] = DSP.FT1D(NP.fft.ifftshift(self.crosspol.Vt[pol]), shift=True, verbose=False)
############################################################################
def FX_on_stack(self):
"""
------------------------------------------------------------------------
Computes the visibility spectrum using an FX operation on the
time-stacked electric fields in the individual antennas in the pair,
i.e., Fourier transform (F) followed by multiplication (X). All four
cross-polarizations are computed.
------------------------------------------------------------------------
"""
self.t = NP.hstack((self.A1.t.ravel(), self.A1.t.max()+self.A2.t.ravel()))
self.f = self.f0 + self.channels()
ts1 = NP.asarray(self.A1.timestamps)
ts2 = NP.asarray(self.A2.timestamps)
common_ts = NP.intersect1d(ts1, ts2, assume_unique=True)
ind1 = NP.in1d(ts1, common_ts, assume_unique=True)
ind2 = NP.in1d(ts2, common_ts, assume_unique=True)
self.Vf_stack['P11'] = self.A1.Ef_stack['P1'][ind1,:] * self.A2.Ef_stack['P1'][ind2,:].conjugate()
self.Vf_stack['P12'] = self.A1.Ef_stack['P1'][ind1,:] * self.A2.Ef_stack['P2'][ind2,:].conjugate()
self.Vf_stack['P21'] = self.A1.Ef_stack['P2'][ind1,:] * self.A2.Ef_stack['P1'][ind2,:].conjugate()
self.Vf_stack['P22'] = self.A1.Ef_stack['P2'][ind1,:] * self.A2.Ef_stack['P2'][ind2,:].conjugate()
self.f2t_on_stack()
############################################################################
def flags_on_stack(self):
"""
------------------------------------------------------------------------
Computes the visibility flags from the time-stacked electric fields for
the common timestamps between the pair of antennas. All four
cross-polarizations are computed.
------------------------------------------------------------------------
"""
ts1 = NP.asarray(self.A1.timestamps)
ts2 = NP.asarray(self.A2.timestamps)
common_ts = NP.intersect1d(ts1, ts2, assume_unique=True)
ind1 = NP.in1d(ts1, common_ts, assume_unique=True)
ind2 = NP.in1d(ts2, common_ts, assume_unique=True)
self.flag_stack['P11'] = NP.logical_or(self.A1.flag_stack['P1'][ind1],
self.A2.flag_stack['P1'][ind2])
self.flag_stack['P12'] = NP.logical_or(self.A1.flag_stack['P1'][ind1],
self.A2.flag_stack['P2'][ind2])
self.flag_stack['P21'] = NP.logical_or(self.A1.flag_stack['P2'][ind1],
self.A2.flag_stack['P1'][ind2])
self.flag_stack['P22'] = NP.logical_or(self.A1.flag_stack['P2'][ind1],
self.A2.flag_stack['P2'][ind2])
############################################################################
def XF_on_stack(self):
"""
------------------------------------------------------------------------
Computes the visibility lags using an XF operation on the time-stacked
electric fields time-series in the individual antennas in the pair,
i.e., Cross-correlation (X) followed by Fourier transform (F). All four
cross-polarizations are computed.
THIS WILL NOT WORK IN ITS CURRENT FORM BECAUSE THE ENGINE OF THIS IS
THE CORRELATE FUNCTION OF NUMPY WRAPPED INSIDE XC() IN MY_DSP_MODULE
AND CURRENTLY IT CAN HANDLE ONLY 1D ARRAYS. NEEDS SERIOUS DEVELOPMENT!
------------------------------------------------------------------------
"""
self.t = NP.hstack((self.A1.t.ravel(), self.A1.t.max()+self.A2.t.ravel()))
self.f = self.f0 + self.channels()
ts1 = NP.asarray(self.A1.timestamps)
ts2 = NP.asarray(self.A2.timestamps)
common_ts = NP.intersect1d(ts1, ts2, assume_unique=True)
ind1 = NP.in1d(ts1, common_ts, assume_unique=True)
ind2 = NP.in1d(ts2, common_ts, assume_unique=True)
self.Vt_stack['P11'] = DSP.XC(self.A1.Et_stack['P1'], self.A2.Et_stack['P1'], shift=False)
self.Vt_stack['P12'] = DSP.XC(self.A1.Et_stack['P1'], self.A2.Et_stack['P2'], shift=False)
self.Vt_stack['P21'] = DSP.XC(self.A1.Et_stack['P2'], self.A2.Et_stack['P1'], shift=False)
self.Vt_stack['P22'] = DSP.XC(self.A1.Et_stack['P2'], self.A2.Et_stack['P2'], shift=False)
self.t2f_on_stack()
############################################################################
def f2t_on_stack(self):
"""
------------------------------------------------------------------------
Computes the visibility lags from the spectra for each cross-
polarization from time-stacked visibilities
------------------------------------------------------------------------
"""
for pol in ['P11', 'P12', 'P21', 'P22']:
self.Vt_stack[pol] = DSP.FT1D(NP.fft.fftshift(self.Vf_stack[pol]),
ax=1, inverse=True, shift=True,
verbose=False)
############################################################################
def t2f_on_stack(self):
"""
------------------------------------------------------------------------
Computes the visibility spectra from the time-series for each cross-
polarization from time-stacked visibility lags
------------------------------------------------------------------------
"""
for pol in ['P11', 'P12', 'P21', 'P22']:
self.Vf_stack[pol] = DSP.FT1D(NP.fft.ifftshift(self.Vt_stack[pol]),
ax=1, shift=True, verbose=False)
############################################################################
def flip_antenna_pair(self):
"""
------------------------------------------------------------------------
Flip the antenna pair in the interferometer. This inverts the baseline
vector and conjugates the visibility spectra
------------------------------------------------------------------------
"""
self.A1, self.A2 = self.A2, self.A1 # Flip antenna instances
self.location = -1 * self.location # Multiply baseline vector by -1
self.blc *= -1
self.trc *= -1
self.crosspol.flag['P12'], self.crosspol.flag['P21'] = self.crosspol.flag['P21'], self.crosspol.flag['P12']
self.crosspol.Vf['P11'] = self.crosspol.Vf['P11'].conjugate()
self.crosspol.Vf['P22'] = self.crosspol.Vf['P22'].conjugate()
self.crosspol.Vf['P12'], self.crosspol.Vf['P21'] = self.crosspol.Vf['P21'].conjugate(), self.crosspol.Vf['P12'].conjugate()
self.f2t()
############################################################################
def refresh_antenna_pairs(self, A1=None, A2=None):
"""
------------------------------------------------------------------------
Update the individual antenna instances of the antenna pair forming
the interferometer with provided values
Inputs:
A1 [instance of class Antenna] first antenna instance in the
antenna pair corresponding to attribute A1. Default=None (no
update for attribute A1)
A2 [instance of class Antenna] first antenna instance in the
antenna pair corresponding to attribute A2. Default=None (no
update for attribute A2)
------------------------------------------------------------------------
"""
if isinstance(A1, Antenna):
self.A1 = A1
else:
raise TypeError('Input A1 must be an instance of class Antenna')
if isinstance(A2, Antenna):
self.A2 = A2
else:
raise TypeError('Input A2 must be an instance of class Antenna')
############################################################################
def get_visibilities(self, pol, flag=None, tselect=None, fselect=None,
datapool=None):
"""
------------------------------------------------------------------------
Returns the visibilities based on selection criteria on timestamp
flags, timestamps and frequency channel indices and the type of data
(most recent, stack or averaged visibilities)
Inputs:
pol [string] select baselines of this polarization that are either
flagged or unflagged as specified by input parameter flag.
Allowed values are 'P11', 'P12', 'P21', and 'P22'. Only one of
these values must be specified.
flag [boolean] If False, return visibilities of unflagged
timestamps, otherwise return flagged ones. Default=None means
all visibilities independent of flagging are returned. This
flagging refers to that along the timestamp axis under each
polarization
tselect [scalar, list, numpy array] timestamp index for visibilities
selection. For most recent visibility, it must be set to -1.
For all other selections, indices in tselect must be in the
valid range of indices along time axis for stacked and
averaged visibilities. Default=None means most recent data is
selected.
fselect [scalar, list, numpy array] frequency channel index for
visibilities selection. Indices must be in the valid range of
indices along the frequency axis for visibilities.
Default=None selects all frequency channels
datapool [string] denotes the data pool from which visibilities are to
be selected. Accepted values are 'current', 'stack', 'avg' and
None (default, same as 'current'). If set to None or
'current', the value in tselect is ignored and only
visibilities of the most recent timestamp are selected. If set
to None or 'current' the attribute Vf_stack is checked first
and if unavailable, attribute crosspol.Vf is used. For 'stack'
and 'avg', attributes Vf_stack and Vf_avg are used
respectively
Output:
outdict [dictionary] consists of visibilities information under the
following keys:
'label' [tuple] interferometer label as a tuple of
individual antenna labels
'pol' [string] polarization string, one of 'P11',
'P12', 'P21', or 'P22'
'visibilities' [numpy array] selected visibilities spectra
with dimensions n_ts x nchan which
are in time-frequency order. If no
visibilities are found satisfying the selection
criteria, the value under this key is set to
None.
'twts' [numpy array] weights corresponding to the time
axis in the selected visibilities. These
weights are determined by flagging of
timestamps. A zero weight indicates unflagged
visibilities were not found for that timestamp.
A non-zero weight indicates how many unflagged
visibilities were found for that time bin (in
case of averaged visibilities) or timestamp.
If no visibilities are found satisfying the
selection criteria, the value under this key
is set to None.
------------------------------------------------------------------------
"""
try:
pol
except NameError:
raise NameError('Input parameter pol must be specified.')
if not isinstance(pol, str):
raise TypeError('Input parameter must be a string')
if not pol in ['P11', 'P12', 'P21', 'P22']:
raise ValueError('Invalid specification for input parameter pol')
if datapool is None:
n_timestamps = 1
datapool = 'current'
elif datapool == 'stack':
n_timestamps = len(self.timestamps)
elif datapool == 'avg':
n_timestamps = self.Vf_avg[pol].shape[0]
elif datapool == 'current':
n_timestamps = 1
else:
raise ValueError('Invalid datapool specified')
if tselect is None:
tsind = NP.asarray(-1).reshape(-1) # Selects most recent data
elif isinstance(tselect, (int, float, list, NP.ndarray)):
tsind = NP.asarray(tselect).ravel()
tsind = tsind.astype(NP.int)
if tsind.size == 1:
if (tsind < -1) or (tsind >= n_timestamps):
tsind = NP.asarray(-1).reshape(-1)
else:
if NP.any(tsind < 0) or NP.any(tsind >= n_timestamps):
raise IndexError('Timestamp indices outside available range for the specified datapool')
else:
raise TypeError('tselect must be None, integer, float, list or numpy array for visibilities selection')
if fselect is None:
chans = NP.arange(self.f.size) # Selects all channels
elif isinstance(fselect, (int, float, list, NP.ndarray)):
chans = NP.asarray(fselect).ravel()
chans = chans.astype(NP.int)
if NP.any(chans < 0) or NP.any(chans >= self.f.size):
raise IndexError('Channel indices outside available range')
else:
raise TypeError('fselect must be None, integer, float, list or numpy array for visibilities selection')
select_ind = NP.ix_(tsind, chans)
outdict = {}
outdict['pol'] = pol
outdict['twts'] = None
outdict['label'] = self.label
outdict['visibilities'] = None
if datapool == 'current':
if self.Vf_stack[pol] is not None:
outdict['visibilities'] = self.Vf_stack[pol][-1,chans].reshape(1,chans.size)
outdict['twts'] = NP.logical_not(NP.asarray(self.flag_stack[pol][-1]).astype(NP.bool).reshape(-1)).astype(NP.float)
else:
outdict['visibilities'] = self.crosspol.Vf[pol][chans].reshape(1,chans.size)
outdict['twts'] = NP.logical_not(NP.asarray(self.crosspol.flag[pol]).astype(NP.bool).reshape(-1)).astype(NP.float)
elif datapool == 'stack':
if self.Vf_stack[pol] is not None:
outdict['visibilities'] = self.Vf_stack[pol][select_ind].reshape(tsind.size,chans.size)
outdict['twts'] = NP.logical_not(NP.asarray(self.flag_stack[pol][tsind]).astype(NP.bool).reshape(-1)).astype(NP.float)
else:
raise ValueError('Attribute Vf_stack has not been initialized to obtain visibilities from. Consider running method stack()')
else:
if self.Vf_avg[pol] is not None:
outdict['visibilities'] = self.Vf_avg[pol][select_ind].reshape(tsind.size,chans.size)
outdict['twts'] = NP.asarray(self.twts[pol][tsind]).reshape(-1)
else:
raise ValueError('Attribute Vf_avg has not been initialized to obtain visibilities from. Consider running methods stack() and accumulate()')
if flag is not None:
if not isinstance(flag, bool):
raise TypeError('flag keyword has to be a Boolean value.')
if flag:
if NP.sum(outdict['twts'] == 0) == 0:
outdict['twts'] = None
outdict['visibilities'] = None
else:
outdict['visibilities'] = outdict['visibilities'][outdict['twts']==0,:].reshape(-1,chans.size)
outdict['twts'] = outdict['twts'][outdict['twts']==0].reshape(-1,1)
else:
if NP.sum(outdict['twts'] > 0) == 0:
outdict['twts'] = None
outdict['visibilities'] = None
else:
outdict['visibilities'] = outdict['visibilities'][outdict['twts']>0,:].reshape(-1,chans.size)
outdict['twts'] = outdict['twts'][outdict['twts']>0].reshape(-1,1)
return outdict
############################################################################
def update_flags(self, flags=None, stack=False, verify=True):
"""
------------------------------------------------------------------------
Updates flags for cross-polarizations from component antenna
polarization flags and also overrides with flags if provided as input
parameters
Inputs:
flags [dictionary] boolean flags for each of the 4 cross-polarizations
of the interferometer which are stored under keys 'P11', 'P12',
'P21', and 'P22'. Default=None means no updates for flags.
stack [boolean] If True, appends the updated flag to the
end of the stack of flags as a function of timestamp. If False,
updates the last flag in the stack with the updated flag and
does not append. Default=False
verify [boolean] If True, verify and update the flags, if necessary.
Visibilities are checked for NaN values and if found, the
flag in the corresponding polarization is set to True. Flags of
individual antennas forming a pair are checked and transferred
to the visibility flags. Default=True
------------------------------------------------------------------------
"""
# By default carry over the flags from previous timestamp
# unless updated in this timestamp as below
# Flags determined from interferometer level
if flags is None:
if self.crosspol._init_flags_on: # begin with all flags set to False for first time update of flags
flags = {pol: False for pol in ['P11', 'P12', 'P21', 'P22']}
else: # for non-first time updates carry over flags from last timestamp and process
flags = copy.deepcopy(self.crosspol.flag)
# now update flags based on current antenna flags
if self.A1.antpol.flag['P1'] or self.A2.antpol.flag['P1']:
flags['P11'] = True
if self.A1.antpol.flag['P2'] or self.A2.antpol.flag['P1']:
flags['P21'] = True
if self.A1.antpol.flag['P1'] or self.A2.antpol.flag['P2']:
flags['P12'] = True
if self.A1.antpol.flag['P2'] or self.A2.antpol.flag['P2']:
flags['P22'] = True
if verify: # Verify provided flags or default flags created above
if self.A1.antpol.flag['P1'] or self.A2.antpol.flag['P1']:
flags['P11'] = True
if self.A1.antpol.flag['P2'] or self.A2.antpol.flag['P1']:
flags['P21'] = True
if self.A1.antpol.flag['P1'] or self.A2.antpol.flag['P2']:
flags['P12'] = True
if self.A1.antpol.flag['P2'] or self.A2.antpol.flag['P2']:
flags['P22'] = True
self.crosspol.update_flags(flags=flags, verify=verify)
# Stack on to last value or update last value in stack
for pol in ['P11', 'P12', 'P21', 'P22']:
if stack is True:
self.flag_stack[pol] = NP.append(self.flag_stack[pol], self.crosspol.flag[pol])
else:
if self.flag_stack[pol].size > 0:
self.flag_stack[pol][-1] = self.crosspol.flag[pol]
# else:
# self.flag_stack[pol] = NP.asarray(self.crosspol.flag[pol]).reshape(-1)
self.flag_stack[pol] = self.flag_stack[pol].astype(NP.bool)
############################################################################
def update_old(self, label=None, Vt=None, t=None, timestamp=None,
location=None, wtsinfo=None, flags=None, gridfunc_freq=None,
ref_freq=None, do_correlate=None, stack=False,
verify_flags=True, verbose=False):
"""
------------------------------------------------------------------------
Updates the interferometer instance with newer attribute values. Updates
the visibility spectrum and timeseries and applies FX or XF operation.
Inputs:
label [Scalar] A unique identifier (preferably a string) for the
antenna. Default=None means no update to apply
latitude [Scalar] Latitude of the antenna's location. Default=None
means no update to apply
location [Instance of GEOM.Point class] The location of the antenna in
local East, North, Up (ENU) coordinate system. Default=None
means no update to apply
timestamp [Scalar] String or float representing the timestamp for the
current attributes. Default=None means no update to apply
t [vector] The time axis for the visibility time series.
Default=None means no update to apply
flags [dictionary] holds boolean flags for each of the 4 cross-
polarizations which are stored under keys 'P11', 'P12',
'P21', and 'P22'. Default=None means no updates for flags.
Vt [dictionary] holds cross-correlation time series under 4
cross-polarizations which are stored under keys 'P11', 'P12',
'P21', and 'P22'. Default=None implies no updates for Vt.
wtsinfo [dictionary] consists of weights information for each of the
four cross-polarizations under keys 'P11', 'P12', 'P21', and
'P22'. Each of the values under the keys is a list of
dictionaries. Length of list is equal to the number
of frequency channels or one (equivalent to setting
wtspos_scale to 'scale'.). The list is indexed by
the frequency channel number. Each element in the list
consists of a dictionary corresponding to that frequency
channel. Each dictionary consists of these items with the
following keys:
wtspos [2-column Numpy array, optional] u- and v-
positions for the gridding weights. Units
are in number of wavelengths.
wts [Numpy array] Complex gridding weights. Size is
equal to the number of rows in wtspos above
orientation [scalar] Orientation (in radians) of the wtspos
coordinate system relative to the local ENU
coordinate system. It is measured North of East.
lookup [string] If set, refers to a file location
containing the wtspos and wts information above
as columns (x-loc [float], y-loc [float], wts
[real], wts[imag if any]). If set, wtspos and wts
information are obtained from this lookup table
and the wtspos and wts keywords in the dictionary
are ignored. Note that wtspos values are obtained
after dividing x- and y-loc lookup values by the
wavelength
gridfunc_freq
[String scalar] If set to None (not provided) or to 'scale'
assumes that wtspos in wtsinfo are given for a
reference frequency which need to be scaled for the frequency
channels. Will be ignored if the list of dictionaries under
the cross-polarization keys in wtsinfo have number of
elements equal to the number of frequency channels.
ref_freq [Scalar] Positive value (in Hz) of reference frequency (used
if gridfunc_freq is set to None or 'scale') at which
wtspos is provided. If set to None, ref_freq is assumed to be
equal to the center frequency in the class Interferometer's
attribute.
do_correlate
[string] Indicates whether correlation operation is to be
performed after updates. Accepted values are 'FX' (for FX
operation) and 'XF' (for XF operation). Default=None means
no correlating operation is to be performed after updates.
stack [boolean] If True (default), appends the updated flag
and data to the end of the stack as a function of
timestamp. If False, updates the last flag and data in
the stack and does not append
verify_flags
[boolean] If True, verify and update the flags, if necessary.
Visibilities are checked for NaN values and if found, the
flag in the corresponding polarization is set to True. Flags
of individual antennas forming a pair are checked and
transferred to the visibility flags. Default=True
verbose [boolean] If True, prints diagnostic and progress messages.
If False (default), suppress printing such messages.
------------------------------------------------------------------------
"""
if label is not None: self.label = label
if location is not None: self.location = location
if timestamp is not None: self.timestamp = timestamp
# if latitude is not None: self.latitude = latitude
# Proceed with interferometer updates only if timestamps align
if (self.timestamp != self.A1.timestamp) or (self.timestamp != self.A2.timestamp):
if verbose:
print 'Interferometer timestamp does not match with the component antenna timestamp(s). Update for interferometer {0} will be skipped.'.format(self.label)
else:
self.timestamps += [copy.deepcopy(self.timestamp)]
if t is not None:
self.t = t
self.f = self.f0 + self.channels()
if (Vt is not None) or (flags is not None):
self.crosspol.update(Vt=Vt, flags=flags, verify=verify_flags)
if do_correlate is not None:
if do_correlate == 'FX':
self.FX()
elif do_correlate == 'XF':
self.XF()
else:
raise ValueError('Invalid specification for input parameter do_correlate.')
self.update_flags(flags=None, stack=stack, verify=True) # Re-check flags and stack
for pol in ['P11', 'P12', 'P21', 'P22']:
if self.Vt_stack[pol] is None:
self.Vt_stack[pol] = copy.deepcopy(self.crosspol.Vt[pol].reshape(1,-1))
self.Vf_stack[pol] = copy.deepcopy(self.crosspol.Vf[pol].reshape(1,-1))
else:
if stack:
self.Vt_stack[pol] = NP.vstack((self.Vt_stack[pol], self.crosspol.Vt[pol].reshape(1,-1)))
self.Vf_stack[pol] = NP.vstack((self.Vf_stack[pol], self.crosspol.Vf[pol].reshape(1,-1)))
else:
self.Vt_stack[pol][-1,:] = copy.deepcopy(self.crosspol.Vt[pol].reshape(1,-1))
self.Vf_stack[pol][-1,:] = copy.deepcopy(self.crosspol.Vf[pol].reshape(1,-1))
blc_orig = NP.copy(self.blc)
trc_orig = NP.copy(self.trc)
eps = 1e-6
if wtsinfo is not None:
if not isinstance(wtsinfo, dict):
raise TypeError('Input parameter wtsinfo must be a dictionary.')
self.wtspos = {}
self.wts = {}
self.wtspos_scale = {}
angles = []
max_wtspos = []
for pol in ['P11', 'P12', 'P21', 'P22']:
self.wts[pol] = []
self.wtspos[pol] = []
self.wtspos_scale[pol] = None
if pol in wtsinfo:
if len(wtsinfo[pol]) == len(self.f):
angles += [elem['orientation'] for elem in wtsinfo[pol]]
for i in xrange(len(self.f)):
rotation_matrix = NP.asarray([[NP.cos(-angles[i]), NP.sin(-angles[i])],
[-NP.sin(-angles[i]), NP.cos(-angles[i])]])
if ('lookup' not in wtsinfo[pol][i]) or (wtsinfo[pol][i]['lookup'] is None):
self.wts[pol] += [wtsinfo[pol][i]['wts']]
wtspos = wtsinfo[pol][i]['wtspos']
else:
lookupdata = LKP.read_lookup(wtsinfo[pol][i]['lookup'])
wtspos = NP.hstack((lookupdata[0].reshape(-1,1),lookupdata[1].reshape(-1,1))) * (self.f[i]/FCNST.c)
self.wts[pol] += [lookupdata[2]]
self.wtspos[pol] += [ NP.dot(NP.asarray(wtspos), rotation_matrix.T) ]
max_wtspos += [NP.amax(NP.abs(self.wtspos[pol][-1]), axis=0)]
elif len(wtsinfo[pol]) == 1:
if (gridfunc_freq is None) or (gridfunc_freq == 'scale'):
self.wtspos_scale[pol] = 'scale'
if ref_freq is None:
ref_freq = self.f0
angles = wtsinfo[pol][0]['orientation']
rotation_matrix = NP.asarray([[NP.cos(-angles), NP.sin(-angles)],
[-NP.sin(-angles), NP.cos(-angles)]])
if ('lookup' not in wtsinfo[pol][0]) or (wtsinfo[pol][0]['lookup'] is None):
self.wts[pol] += [ wtsinfo[pol][0]['wts'] ]
wtspos = wtsinfo[pol][0]['wtspos']
else:
lookupdata = LKP.read_lookup(wtsinfo[pol][0]['lookup'])
wtspos = NP.hstack((lookupdata[0].reshape(-1,1),lookupdata[1].reshape(-1,1))) * (ref_freq/FCNST.c)
self.wts[pol] += [lookupdata[2]]
self.wtspos[pol] += [ (self.f[0]/ref_freq) * NP.dot(NP.asarray(wtspos), rotation_matrix.T) ]
max_wtspos += [NP.amax(NP.abs(self.wtspos[pol][-1]), axis=0)]
else:
raise ValueError('gridfunc_freq must be set to None, "scale" or "noscale".')
self.blc = NP.asarray([self.location.x, self.location.y]).reshape(1,-1) - FCNST.c/self.f.min() * NP.amin(NP.abs(self.wtspos[pol][0]), 0)
self.trc = NP.asarray([self.location.x, self.location.y]).reshape(1,-1) + FCNST.c/self.f.min() * NP.amax(NP.abs(self.wtspos[pol][0]), 0)
else:
raise ValueError('Number of elements in wtsinfo for {0} is incompatible with the number of channels.'.format(pol))
max_wtspos = NP.amax(NP.asarray(max_wtspos).reshape(-1,blc_orig.size), axis=0)
self.blc = NP.asarray([self.location.x, self.location.y]).reshape(1,-1) - FCNST.c/self.f.min() * max_wtspos
self.trc = NP.asarray([self.location.x, self.location.y]).reshape(1,-1) + FCNST.c/self.f.min() * max_wtspos
if (NP.abs(NP.linalg.norm(blc_orig)-NP.linalg.norm(self.blc)) > eps) or (NP.abs(NP.linalg.norm(trc_orig)-NP.linalg.norm(self.trc)) > eps):
if verbose:
print 'Grid corner(s) of interferometer {0} have changed. Should re-grid the interferometer array.'.format(self.label)
############################################################################
def update(self, update_dict=None, verbose=False):
"""
------------------------------------------------------------------------
Updates the interferometer instance with newer attribute values. Updates
the visibility spectrum and timeseries and applies FX or XF operation.
Inputs:
update_dict [dictionary] contains the following keys and values:
label [Scalar] A unique identifier (preferably a string) for
the antenna. Default=None means no update to apply
latitude [Scalar] Latitude of the antenna's location. Default=None
means no update to apply
location [Instance of GEOM.Point class] The location of the
antenna in local East, North, Up (ENU) coordinate system.
Default=None means no update to apply
timestamp [Scalar] String or float representing the timestamp for
the current attributes. Default=None means no update to
apply
t [vector] The time axis for the visibility time series.
Default=None means no update to apply
flags [dictionary] holds boolean flags for each of the 4
cross-polarizations which are stored under keys 'P11',
'P12', 'P21', and 'P22'. Default=None means no updates
for flags.
Vt [dictionary] holds cross-correlation time series under 4
cross-polarizations which are stored under keys 'P11',
'P12', 'P21', and 'P22'. Default=None implies no updates
for Vt.
aperture [instance of class APR.Aperture] aperture information for
the interferometer. Read docstring of class Aperture for
details
wtsinfo [dictionary] consists of weights information for each of
the four cross-polarizations under keys 'P11', 'P12',
'P21', and 'P22'. Each of the values under the keys is a
list of dictionaries. Length of list is equal to the
number of frequency channels or one (equivalent to
setting wtspos_scale to 'scale'.). The list is indexed by
the frequency channel number. Each element in the list
consists of a dictionary corresponding to that frequency
channel. Each dictionary consists of these items with the
following keys:
wtspos [2-column Numpy array, optional] u- and v-
positions for the gridding weights. Units
are in number of wavelengths.
wts [Numpy array] Complex gridding weights. Size
is equal to the number of rows in wtspos
above
orientation [scalar] Orientation (in radians) of the
wtspos coordinate system relative to the
local ENU coordinate system. It is measured
North of East.
lookup [string] If set, refers to a file location
containing the wtspos and wts information
above as columns (x-loc [float], y-loc
[float], wts[real], wts[imag if any]). If
set, wtspos and wts information are obtained
from this lookup table and the wtspos and wts
keywords in the dictionary are ignored. Note
that wtspos values are obtained after
dividing x- and y-loc lookup values by the
wavelength
gridfunc_freq
[String scalar] If set to None (not provided) or to
'scale' assumes that wtspos in wtsinfo are given for a
reference frequency which need to be scaled for the
frequency channels. Will be ignored if the list of
dictionaries under the cross-polarization keys in
wtsinfo have number of elements equal to the number of
frequency channels.
ref_freq [Scalar] Positive value (in Hz) of reference frequency
(used if gridfunc_freq is set to None or 'scale') at
which wtspos is provided. If set to None, ref_freq is
assumed to be equal to the center frequency in the class
Interferometer's attribute.
do_correlate
[string] Indicates whether correlation operation is to be
performed after updates. Accepted values are 'FX' (for FX
operation) and 'XF' (for XF operation). Default=None
means no correlating operation is to be performed after
updates.
stack [boolean] If True (default), appends the updated flag
and data to the end of the stack as a function of
timestamp. If False, updates the last flag and data in
the stack and does not append
verify_flags
[boolean] If True, verify and update the flags, if
necessary. Visibilities are checked for NaN values and if
found, the flag in the corresponding polarization is set
to True. Flags of individual antennas forming a pair are
checked and transferred to the visibility flags.
Default=True
verbose [boolean] If True, prints diagnostic and progress messages.
If False (default), suppress printing such messages.
------------------------------------------------------------------------
"""
label = None
location = None
timestamp = None
t = None
flags = None
stack = False
verify_flags = True
Vt = None
do_correlate = None
wtsinfo = None
gridfunc_freq = None
ref_freq = None
aperture = None
if update_dict is not None:
if not isinstance(update_dict, dict):
raise TypeError('Input parameter containing updates must be a dictionary')
if 'label' in update_dict: label = update_dict['label']
if 'location' in update_dict: location = update_dict['location']
if 'timestamp' in update_dict: timestamp = update_dict['timestamp']
if 't' in update_dict: t = update_dict['t']
if 'Vt' in update_dict: Vt = update_dict['Vt']
if 'flags' in update_dict: flags = update_dict['flags']
if 'stack' in update_dict: stack = update_dict['stack']
if 'verify_flags' in update_dict: verify_flags = update_dict['verify_flags']
if 'do_correlate' in update_dict: do_correlate = update_dict['do_correlate']
if 'wtsinfo' in update_dict: wtsinfo = update_dict['wtsinfo']
if 'gridfunc_freq' in update_dict: gridfunc_freq = update_dict['gridfunc_freq']
if 'ref_freq' in update_dict: ref_freq = update_dict['ref_freq']
if 'aperture' in update_dict: aperture = update_dict['aperture']
if label is not None: self.label = label
if location is not None: self.location = location
if timestamp is not None: self.timestamp = timestamp
# if latitude is not None: self.latitude = latitude
# Proceed with interferometer updates only if timestamps align
if (self.timestamp != self.A1.timestamp) or (self.timestamp != self.A2.timestamp):
if verbose:
print 'Interferometer timestamp does not match with the component antenna timestamp(s). Update for interferometer {0} will be skipped.'.format(self.label)
else:
self.timestamps += [copy.deepcopy(self.timestamp)]
if t is not None:
self.t = t
self.f = self.f0 + self.channels()
self.crosspol.update(Vt=Vt, flags=flags, verify=verify_flags)
if do_correlate is not None:
if do_correlate == 'FX':
self.FX()
elif do_correlate == 'XF':
self.XF()
else:
raise ValueError('Invalid specification for input parameter do_correlate.')
self.update_flags(flags=None, stack=stack, verify=False) # Stack flags. Flag verification has already been performed inside FX() or XF()
for pol in ['P11', 'P12', 'P21', 'P22']:
if not self.crosspol._init_data_on:
if self.Vt_stack[pol] is None:
if stack:
self.Vt_stack[pol] = copy.deepcopy(self.crosspol.Vt[pol].reshape(1,-1))
self.Vf_stack[pol] = copy.deepcopy(self.crosspol.Vf[pol].reshape(1,-1))
else:
if stack:
self.Vt_stack[pol] = NP.vstack((self.Vt_stack[pol], self.crosspol.Vt[pol].reshape(1,-1)))
self.Vf_stack[pol] = NP.vstack((self.Vf_stack[pol], self.crosspol.Vf[pol].reshape(1,-1)))
else:
self.Vt_stack[pol][-1,:] = copy.deepcopy(self.crosspol.Vt[pol].reshape(1,-1))
self.Vf_stack[pol][-1,:] = copy.deepcopy(self.crosspol.Vf[pol].reshape(1,-1))
blc_orig = NP.copy(self.blc)
trc_orig = NP.copy(self.trc)
eps = 1e-6
if aperture is not None:
if isinstance(aperture, APR.Aperture):
self.aperture = copy.deepcopy(aperture)
else:
raise TypeError('Update for aperture must be an instance of class Aperture.')
if wtsinfo is not None:
if not isinstance(wtsinfo, dict):
raise TypeError('Input parameter wtsinfo must be a dictionary.')
self.wtspos = {}
self.wts = {}
self.wtspos_scale = {}
angles = []
max_wtspos = []
for pol in ['P11', 'P12', 'P21', 'P22']:
self.wts[pol] = []
self.wtspos[pol] = []
self.wtspos_scale[pol] = None
if pol in wtsinfo:
if len(wtsinfo[pol]) == len(self.f):
angles += [elem['orientation'] for elem in wtsinfo[pol]]
for i in xrange(len(self.f)):
rotation_matrix = NP.asarray([[NP.cos(-angles[i]), NP.sin(-angles[i])],
[-NP.sin(-angles[i]), NP.cos(-angles[i])]])
if ('lookup' not in wtsinfo[pol][i]) or (wtsinfo[pol][i]['lookup'] is None):
self.wts[pol] += [wtsinfo[pol][i]['wts']]
wtspos = wtsinfo[pol][i]['wtspos']
else:
lookupdata = LKP.read_lookup(wtsinfo[pol][i]['lookup'])
wtspos = NP.hstack((lookupdata[0].reshape(-1,1),lookupdata[1].reshape(-1,1))) * (self.f[i]/FCNST.c)
self.wts[pol] += [lookupdata[2]]
self.wtspos[pol] += [ NP.dot(NP.asarray(wtspos), rotation_matrix.T) ]
max_wtspos += [NP.amax(NP.abs(self.wtspos[pol][-1]), axis=0)]
elif len(wtsinfo[pol]) == 1:
if (gridfunc_freq is None) or (gridfunc_freq == 'scale'):
self.wtspos_scale[pol] = 'scale'
if ref_freq is None:
ref_freq = self.f0
angles = wtsinfo[pol][0]['orientation']
rotation_matrix = NP.asarray([[NP.cos(-angles), NP.sin(-angles)],
[-NP.sin(-angles), NP.cos(-angles)]])
if ('lookup' not in wtsinfo[pol][0]) or (wtsinfo[pol][0]['lookup'] is None):
self.wts[pol] += [ wtsinfo[pol][0]['wts'] ]
wtspos = wtsinfo[pol][0]['wtspos']
else:
lookupdata = LKP.read_lookup(wtsinfo[pol][0]['lookup'])
wtspos = NP.hstack((lookupdata[0].reshape(-1,1),lookupdata[1].reshape(-1,1))) * (ref_freq/FCNST.c)
self.wts[pol] += [lookupdata[2]]
self.wtspos[pol] += [ (self.f[0]/ref_freq) * NP.dot(NP.asarray(wtspos), rotation_matrix.T) ]
max_wtspos += [NP.amax(NP.abs(self.wtspos[pol][-1]), axis=0)]
else:
raise ValueError('gridfunc_freq must be set to None, "scale" or "noscale".')
self.blc = NP.asarray([self.location.x, self.location.y]).reshape(1,-1) - FCNST.c/self.f.min() * NP.amin(NP.abs(self.wtspos[pol][0]), 0)
self.trc = NP.asarray([self.location.x, self.location.y]).reshape(1,-1) + FCNST.c/self.f.min() * NP.amax(NP.abs(self.wtspos[pol][0]), 0)
else:
raise ValueError('Number of elements in wtsinfo for {0} is incompatible with the number of channels.'.format(pol))
max_wtspos = NP.amax(NP.asarray(max_wtspos).reshape(-1,blc_orig.size), axis=0)
self.blc = NP.asarray([self.location.x, self.location.y]).reshape(1,-1) - FCNST.c/self.f.min() * max_wtspos
self.trc = NP.asarray([self.location.x, self.location.y]).reshape(1,-1) + FCNST.c/self.f.min() * max_wtspos
if (NP.abs(NP.linalg.norm(blc_orig)-NP.linalg.norm(self.blc)) > eps) or (NP.abs(NP.linalg.norm(trc_orig)-NP.linalg.norm(self.trc)) > eps):
if verbose:
print 'Grid corner(s) of interferometer {0} have changed. Should re-grid the interferometer array.'.format(self.label)
############################################################################
def update_pp_old(self, update_dict=None, verbose=True):
"""
------------------------------------------------------------------------
Updates the interferometer instance with newer attribute values. Updates
the visibility spectrum and timeseries and applies FX or XF operation.
Used internally when parallel processing is used. Not to be used by the
user directly.
Inputs:
update_dict [dictionary] contains the following keys and values:
label [Scalar] A unique identifier (preferably a string) for
the interferometer. Default=None means no update to apply
latitude [Scalar] Latitude of the interferometer's location.
Default=None means no update to apply
location [Instance of GEOM.Point class] The location of the
interferometer in local East, North, Up (ENU) coordinate
system. Default=None means no update to apply
timestamp [Scalar] String or float representing the timestamp for
the current attributes. Default=None means no update to
apply
t [vector] The time axis for the visibility time series.
Default=None means no update to apply
flags [dictionary] holds boolean flags for each of the 4 cross-
polarizations which are stored under keys 'P11', 'P12',
'P21', and 'P22'. Default=None means no updates for
flags.
Vt [dictionary] holds cross-correlation time series under 4
cross-polarizations which are stored under keys 'P11',
'P12', 'P21', and 'P22'. Default=None implies no updates
for Vt.
wtsinfo [dictionary] consists of weights information for each of
the four cross-polarizations under keys 'P11', 'P12',
'P21', and 'P22'. Each of the values under the keys is a
list of dictionaries. Length of list is equal to the
number of frequency channels or one (equivalent to
setting wtspos_scale to 'scale'.). The list is indexed by
the frequency channel number. Each element in the list
consists of a dictionary corresponding to that frequency
channel. Each dictionary consists of these items with the
following keys:
wtspos [2-column Numpy array, optional] u- and v-
positions for the gridding weights. Units
are in number of wavelengths.
wts [Numpy array] Complex gridding weights. Size
is equal to the number of rows in wtspos
above
orientation [scalar] Orientation (in radians) of the
wtspos coordinate system relative to the
local ENU coordinate system. It is measured
North of East.
lookup [string] If set, refers to a file location
containing the wtspos and wts information
above as columns (x-loc [float], y-loc
[float], wts[real], wts[imag if any]). If
set, wtspos and wts information are obtained
from this lookup table and the wtspos and wts
keywords in the dictionary are ignored. Note
that wtspos values are obtained after
dividing x- and y-loc lookup values by the
wavelength
gridfunc_freq
[String scalar] If set to None (not provided) or to
'scale' assumes that wtspos in wtsinfo are given for a
reference frequency which need to be scaled for the
frequency channels. Will be ignored if the list of
dictionaries under the cross-polarization keys in wtsinfo
have number of elements equal to the number of frequency
channels.
ref_freq [Scalar] Positive value (in Hz) of reference frequency
(used if gridfunc_freq is set to None or 'scale') at
which wtspos is provided. If set to None, ref_freq is
assumed to be equal to the center frequency in the class
Interferometer's attribute.
do_correlate
[string] Indicates whether correlation operation is to be
performed after updates. Accepted values are 'FX' (for FX
operation) and 'XF' (for XF operation). Default=None
means no correlating operation is to be performed after
updates.
stack [boolean] If True (default), appends the updated flag
and data to the end of the stack as a function of
timestamp. If False, updates the last flag and data in
the stack and does not append
verify_flags
[boolean] If True, verify and update the flags, if necessary.
Visibilities are checked for NaN values and if found, the
flag in the corresponding polarization is set to True. Flags
of individual antennas forming a pair are checked and
transferred to the visibility flags. Default=True
verbose [boolean] If True, prints diagnostic and progress messages.
If False (default), suppress printing such messages.
------------------------------------------------------------------------
"""
label = None
location = None
timestamp = None
t = None
flags = None
Vt = None
do_correlate = None
wtsinfo = None
gridfunc_freq = None
ref_freq = None
stack = False
verify_flags = True
if update_dict is not None:
if not isinstance(update_dict, dict):
raise TypeError('Input parameter containing updates must be a dictionary')
if 'label' in update_dict: label = update_dict['label']
if 'location' in update_dict: location = update_dict['location']
if 'timestamp' in update_dict: timestamp = update_dict['timestamp']
if 't' in update_dict: t = update_dict['t']
if 'Vt' in update_dict: Vt = update_dict['Vt']
if 'flags' in update_dict: flags = update_dict['flags']
if 'stack' in update_dict: stack = update_dict['stack']
if 'verify_flags' in update_dict: verify_flags = update_dict['verify_flags']
if 'do_correlate' in update_dict: do_correlate = update_dict['do_correlate']
if 'wtsinfo' in update_dict: wtsinfo = update_dict['wtsinfo']
if 'gridfunc_freq' in update_dict: gridfunc_freq = update_dict['gridfunc_freq']
if 'ref_freq' in update_dict: ref_freq = update_dict['ref_freq']
if label is not None: self.label = label
if location is not None: self.location = location
if timestamp is not None: self.timestamp = timestamp
# Proceed with interferometer updates only if timestamps align
if (self.timestamp != self.A1.timestamp) or (self.timestamp != self.A2.timestamp):
if verbose:
print 'Interferometer timestamp does not match with the component antenna timestamp(s). Update for interferometer {0} will be skipped.'.format(self.label)
else:
self.timestamps += [copy.deepcopy(self.timestamp)]
if t is not None:
self.t = t
self.f = self.f0 + self.channels()
if (Vt is not None) or (flags is not None):
self.crosspol.update(Vt=Vt, flags=flags, verify=verify_flags)
if do_correlate is not None:
if do_correlate == 'FX':
self.FX()
elif do_correlate == 'XF':
self.XF()
else:
raise ValueError('Invalid specification for input parameter do_correlate.')
self.update_flags(flags=None, stack=stack, verify=True) # Re-check flags and stack
for pol in ['P11', 'P12', 'P21', 'P22']:
if self.Vt_stack[pol] is None:
self.Vt_stack[pol] = copy.deepcopy(self.crosspol.Vt[pol].reshape(1,-1))
self.Vf_stack[pol] = copy.deepcopy(self.crosspol.Vf[pol].reshape(1,-1))
else:
if stack:
self.Vt_stack[pol] = NP.vstack((self.Vt_stack[pol], self.crosspol.Vt[pol].reshape(1,-1)))
self.Vf_stack[pol] = NP.vstack((self.Vf_stack[pol], self.crosspol.Vf[pol].reshape(1,-1)))
else:
self.Vt_stack[pol][-1,:] = copy.deepcopy(self.crosspol.Vt[pol].reshape(1,-1))
self.Vf_stack[pol][-1,:] = copy.deepcopy(self.crosspol.Vf[pol].reshape(1,-1))
blc_orig = NP.copy(self.blc)
trc_orig = NP.copy(self.trc)
eps = 1e-6
if wtsinfo is not None:
if not isinstance(wtsinfo, dict):
raise TypeError('Input parameter wtsinfo must be a dictionary.')
self.wtspos = {}
self.wts = {}
self.wtspos_scale = {}
angles = []
max_wtspos = []
for pol in ['P11', 'P12', 'P21', 'P22']:
self.wts[pol] = []
self.wtspos[pol] = []
self.wtspos_scale[pol] = None
if pol in wtsinfo:
if len(wtsinfo[pol]) == len(self.f):
angles += [elem['orientation'] for elem in wtsinfo[pol]]
for i in xrange(len(self.f)):
rotation_matrix = NP.asarray([[NP.cos(-angles[i]), NP.sin(-angles[i])],
[-NP.sin(-angles[i]), NP.cos(-angles[i])]])
if ('lookup' not in wtsinfo[pol][i]) or (wtsinfo[pol][i]['lookup'] is None):
self.wts[pol] += [wtsinfo[pol][i]['wts']]
wtspos = wtsinfo[pol][i]['wtspos']
else:
lookupdata = LKP.read_lookup(wtsinfo[pol][i]['lookup'])
wtspos = NP.hstack((lookupdata[0].reshape(-1,1),lookupdata[1].reshape(-1,1))) * (self.f[i]/FCNST.c)
self.wts[pol] += [lookupdata[2]]
self.wtspos[pol] += [ NP.dot(NP.asarray(wtspos), rotation_matrix.T) ]
max_wtspos += [NP.amax(NP.abs(self.wtspos[pol][-1]), axis=0)]
elif len(wtsinfo[pol]) == 1:
if (gridfunc_freq is None) or (gridfunc_freq == 'scale'):
self.wtspos_scale[pol] = 'scale'
if ref_freq is None:
ref_freq = self.f0
angles = wtsinfo[pol][0]['orientation']
rotation_matrix = NP.asarray([[NP.cos(-angles), NP.sin(-angles)],
[-NP.sin(-angles), NP.cos(-angles)]])
if ('lookup' not in wtsinfo[pol][0]) or (wtsinfo[pol][0]['lookup'] is None):
self.wts[pol] += [ wtsinfo[pol][0]['wts'] ]
wtspos = wtsinfo[pol][0]['wtspos']
else:
lookupdata = LKP.read_lookup(wtsinfo[pol][0]['lookup'])
wtspos = NP.hstack((lookupdata[0].reshape(-1,1),lookupdata[1].reshape(-1,1))) * (ref_freq/FCNST.c)
self.wts[pol] += [lookupdata[2]]
self.wtspos[pol] += [ (self.f[0]/ref_freq) * NP.dot(NP.asarray(wtspos), rotation_matrix.T) ]
max_wtspos += [NP.amax(NP.abs(self.wtspos[pol][-1]), axis=0)]
else:
raise ValueError('gridfunc_freq must be set to None, "scale" or "noscale".')
self.blc = NP.asarray([self.location.x, self.location.y]).reshape(1,-1) - FCNST.c/self.f.min() * NP.amin(NP.abs(self.wtspos[pol][0]), 0)
self.trc = NP.asarray([self.location.x, self.location.y]).reshape(1,-1) + FCNST.c/self.f.min() * NP.amax(NP.abs(self.wtspos[pol][0]), 0)
else:
raise ValueError('Number of elements in wtsinfo for {0} is incompatible with the number of channels.'.format(pol))
max_wtspos = NP.amax(NP.asarray(max_wtspos).reshape(-1,blc_orig.size), axis=0)
self.blc = NP.asarray([self.location.x, self.location.y]).reshape(1,-1) - FCNST.c/self.f.min() * max_wtspos
self.trc = NP.asarray([self.location.x, self.location.y]).reshape(1,-1) + FCNST.c/self.f.min() * max_wtspos
if (NP.abs(NP.linalg.norm(blc_orig)-NP.linalg.norm(self.blc)) > eps) or (NP.abs(NP.linalg.norm(trc_orig)-NP.linalg.norm(self.trc)) > eps):
if verbose:
print 'Grid corner(s) of interferometer {0} have changed. Should re-grid the interferometer array.'.format(self.label)
return self
############################################################################
def update_pp(self, update_dict=None, verbose=True):
"""
------------------------------------------------------------------------
Updates the interferometer instance with newer attribute values. Updates
the visibility spectrum and timeseries and applies FX or XF operation.
Used internally when parallel processing is used. Not to be used by the
user directly.
See member function update() for details on inputs.
------------------------------------------------------------------------
"""
self.update(update_dict=update_dict, verbose=verbose)
return self
############################################################################
def stack(self, on_flags=True, on_data=True):
"""
------------------------------------------------------------------------
Stacks and computes visibilities and flags from the individual antennas
in the pair.
Inputs:
on_flags [boolean] if set to True (default), combines the time-stacked
electric field flags from individual antennas from the
common timestamps into time-stacked visibility flags
on_data [boolean] if set to True (default), combines the time-stacked
electric fields from individual antennas from the common
timestamps into time-stacked visibilities
------------------------------------------------------------------------
"""
ts1 = NP.asarray(self.A1.timestamps)
ts2 = NP.asarray(self.A2.timestamps)
common_ts = NP.intersect1d(ts1, ts2, assume_unique=True)
ind1 = NP.in1d(ts1, common_ts, assume_unique=True)
ind2 = NP.in1d(ts2, common_ts, assume_unique=True)
self.timestamps = common_ts.tolist()
if on_data:
self.FX_on_stack()
if on_flags:
self.flags_on_stack()
############################################################################
def stack_pp(self, on_flags=True, on_data=True):
"""
------------------------------------------------------------------------
Stacks and computes visibilities and flags from the individual antennas
in the pair. To be used internally as a wrapper for stack() in case of
parallel processing. Not to be used directly by the user.
Inputs:
on_flags [boolean] if set to True (default), combines the time-stacked
electric field flags from individual antennas from the
common timestamps into time-stacked visibility flags
on_data [boolean] if set to True (default), combines the time-stacked
electric fields from individual antennas from the common
timestamps into time-stacked visibilities
------------------------------------------------------------------------
"""
self.stack(on_flags=on_flags, on_data=on_data)
return self
############################################################################
def accumulate(self, tbinsize=None):
"""
------------------------------------------------------------------------
Accumulate and average visibility spectra across timestamps under
different polarizations depending on the time bin size for the
corresponding polarization.
Inputs:
tbinsize [scalar or dictionary] Contains bin size of timestamps while
stacking. Default = None means all visibility spectra over all
timestamps are averaged. If scalar, the same (positive) value
applies to all polarizations. If dictionary, timestamp bin size
(positive) is provided under each key 'P11', 'P12', 'P21',
'P22'. If any of the keys is missing the visibilities for that
polarization are averaged over all timestamps.
------------------------------------------------------------------------
"""
timestamps = NP.asarray(self.timestamps).astype(NP.float)
Vf_acc = {}
twts = {}
Vf_avg = {}
for pol in ['P11', 'P12', 'P21', 'P22']:
Vf_acc[pol] = None
Vf_avg[pol] = None
twts[pol] = []
if tbinsize is None: # Average visibilities across all timestamps
for pol in ['P11', 'P12', 'P21', 'P22']:
unflagged_ind = NP.logical_not(self.flag_stack[pol])
Vf_acc[pol] = NP.nansum(self.Vf_stack[pol][unflagged_ind,:], axis=0, keepdims=True)
twts[pol] = NP.sum(unflagged_ind).astype(NP.float).reshape(-1,1)
# twts[pol] = NP.asarray(len(self.timestamps) - NP.sum(self.flag_stack[pol])).reshape(-1,1)
self.tbinsize = tbinsize
elif isinstance(tbinsize, (int, float)): # Apply same time bin size to all polarizations
eps = 1e-10
tbins = NP.arange(timestamps.min(), timestamps.max(), tbinsize)
tbins = NP.append(tbins, timestamps.max()+eps)
for pol in ['P11', 'P12', 'P21', 'P22']:
counts, tbin_edges, tbinnum, ri = OPS.binned_statistic(timestamps, statistic='count', bins=tbins)
for binnum in range(counts.size):
ind = ri[ri[binnum]:ri[binnum+1]]
unflagged_ind = NP.logical_not(self.flag_stack[pol][ind])
twts[pol] += [NP.sum(unflagged_ind)]
# twts[pol] += [counts[binnum] - NP.sum(self.flag_stack[pol][ind])]
if Vf_acc[pol] is None:
Vf_acc[pol] = NP.nansum(self.Vf_stack[pol][ind[unflagged_ind],:], axis=0, keepdims=True)
else:
Vf_acc[pol] = NP.vstack((Vf_acc[pol], NP.nansum(self.Vf_stack[pol][ind[unflagged_ind],:], axis=0, keepdims=True)))
twts[pol] = NP.asarray(twts[pol]).astype(NP.float).reshape(-1,1)
self.tbinsize = tbinsize
elif isinstance(tbinsize, dict): # Apply different time binsizes to corresponding polarizations
tbsize = {}
for pol in ['P11', 'P12', 'P21', 'P22']:
if pol not in tbinsize:
unflagged_ind = NP.logical_not(self.flag_stack[pol])
Vf_acc[pol] = NP.nansum(self.Vf_stack[pol][unflagged_ind,:], axis=0, keepdims=True)
twts[pol] = NP.sum(unflagged_ind).astype(NP.float).reshape(-1,1)
# twts[pol] = NP.asarray(len(self.timestamps) - NP.sum(self.flag_stack[pol])).reshape(-1,1)
tbsize[pol] = None
elif isinstance(tbinsize[pol], (int,float)):
eps = 1e-10
tbins = NP.arange(timestamps.min(), timestamps.max(), tbinsize[pol])
tbins = NP.append(tbins, timestamps.max()+eps)
counts, tbin_edges, tbinnum, ri = OPS.binned_statistic(timestamps, statistic='count', bins=tbins)
for binnum in range(counts.size):
ind = ri[ri[binnum]:ri[binnum+1]]
unflagged_ind = NP.logical_not(self.flag_stack[pol][ind])
twts[pol] += [NP.sum(unflagged_ind)]
# twts[pol] += [counts[binnum] - NP.sum(self.flag_stack[pol][ind])]
if Vf_acc[pol] is None:
Vf_acc[pol] = NP.nansum(self.Vf_stack[pol][ind[unflagged_ind],:], axis=0, keepdims=True)
else:
Vf_acc[pol] = NP.vstack((Vf_acc[pol], NP.nansum(self.Vf_stack[pol][ind[unflagged_ind],:], axis=0, keepdims=True)))
twts[pol] = NP.asarray(twts[pol]).astype(NP.float).reshape(-1,1)
tbsize[pol] = tbinsize[pol]
else:
unflagged_ind = NP.logical_not(self.flag_stack[pol])
Vf_acc[pol] = NP.nansum(self.Vf_stack[pol][unflagged_ind,:], axis=0, keepdims=True)
twts[pol] = NP.sum(unflagged_ind).astype(NP.float).reshape(-1,1)
# twts[pol] = NP.asarray(len(self.timestamps) - NP.sum(self.flag_stack[pol])).reshape(-1,1)
tbsize[pol] = None
self.tbinsize = tbsize
# Compute the average from the accumulated visibilities
for pol in ['P11', 'P12', 'P21', 'P22']:
Vf_avg[pol] = Vf_acc[pol] / twts[pol]
self.Vf_avg = Vf_avg
self.twts = twts
################################################################################
class InterferometerArray(object):
"""
----------------------------------------------------------------------------
Class to manage interferometer array information.
Attributes:
antenna_array [instance of class AntennaArray] consists of the antenna array
information that determines all the interferometer pairs
interferometers
[dictionary] keys hold instances of class Interferometer. The
keys themselves are identical to the label attributes of the
interferometer instances they hold.
timestamp [Scalar] String or float representing the timestamp for the
current attributes
t [vector] The time axis for the time series of electric fields
f [vector] Frequency axis obtained by a Fourier Transform of
the electric field time series. Same length as attribute t
f0 [Scalar] Center frequency in Hz.
blc [numpy array] 2-element numpy array specifying bottom left
corner of the grid coincident with bottom left interferometer
location in ENU coordinate system
trc [numpy array] 2-element numpy array specifying top right
corner of the grid coincident with top right interferometer
location in ENU coordinate system
grid_blc [numpy array] 2-element numpy array specifying bottom left
corner of the grid in ENU coordinate system including any
padding used
grid_trc [numpy array] 2-element numpy array specifying top right
corner of the grid in ENU coordinate system including any
padding used
gridx [numpy array] two-dimensional numpy meshgrid array specifying
grid x-locations in units of physical distance (in metres) in
the ENU coordinate system whose corners are specified by
attributes grid_blc and grid_trc
gridy [numpy array] two-dimensional numpy meshgrid array specifying
grid y-locations in units of physical distance (in metres) in
the ENU coordinate system whose corners are specified by
attributes grid_blc and grid_trc
grid_ready [boolean] set to True if the gridding has been performed,
False if grid is not available yet. Set to False in case
blc, trc, grid_blc or grid_trc is updated indicating gridding
is to be perfomed again
grid_illumination
[dictionary] Gridded illumination cube for each
cross-polarization is under one of the four keys 'P11', 'P12',
'P21' or 'P22'. Under each of these keys the grid illumination
is a three-dimensional complex numpy array of shape
n_u x n_v x nchan, where, n_u, n_v and nchan are the grid size
along u-axis, v-axis and frequency axis respectively.
grid_Vf [dictionary] Gridded visibility cube for each
cross-polarization is under one of the four keys 'P11', 'P12',
'P21' or 'P22'. Under each of these keys the grid illumination
is a three-dimensional complex numpy array of shape
n_u x n_v x nchan, where, n_u, n_v and nchan are the grid size
along u-axis, v-axis and frequency axis respectively.
ordered_labels
[list] list of interferometer labels sorted by the first
antenna label
grid_mapper [dictionary] baseline-to-grid mapping information for each of
four cross-polarizations under keys 'P11', 'P12', 'P21', and
'P22'. Under each cross-polarization, it is a dictionary with
values under the following keys:
'refind' [list] each element in the list corresponds to a
sequential frequency channel and is another list
with indices to the lookup locations that map to
the grid locations (indices in 'gridind') for this
frequency channel. These indices index the array
in 'refwts'
'gridind' [list] each element in the list corresponds to a
sequential frequency channel and is another list
with indices to the grid locations that map to
the lookup locations (indices in 'refind') for
this frequency channel.
'refwts' [numpy array] interferometer weights of size
n_bl x n_wts flattened to be a vector. Indices in
'refind' index to this array. Currently only valid
when lookup weights scale with frequency.
'labels' [dictionary] contains mapping information from
interferometer (specified by key which is the
interferometer label). The value under each label
key is another dictionary with the following keys
and information:
'twts' [scalar] if positive, indicates
the number of timestamps that
have gone into the measurement of
complex Vf made by the
interferometer under the
specific polarization. If zero, it
indicates no unflagged timestamp
data was found for the
interferometer and will not
contribute to the complex grid
illumination and visibilities
'twts' [scalar] denotes the number of
timestamps for which the
interferometer data was not flagged
which were used in stacking and
averaging
'gridind' [numpy vector] one-dimensional
index into the three-dimensional
grid locations where the
interferometer contributes
illumination and visibilities. The
one-dimensional indices are
obtained using numpy's
multi_ravel_index() using the grid
shape, n_u x n_v x nchan
'illumination' [numpy vector] complex grid
illumination contributed by the
interferometer to different grid
locations in 'gridind'. It is
mapped to the
grid as specified by indices in
key 'gridind'
'Vf' [numpy vector] complex grid
visibilities contributed by the
interferometer. It is mapped to the
grid as specified by indices in
key 'gridind'
'bl' [dictionary] dictionary with information on
contribution of all baseline lookup weights. This
contains another dictionary with the following
keys:
'ind_freq' [list] each element in the list is
for a frequency channel and
consists of a numpy vector which
consists of indices of the
contributing interferometers
'ind_all' [numpy vector] consists of numpy
vector which consists of indices
of the contributing interferometers
for all frequencies appended
together. Effectively, this is just
values in 'ind_freq' of all
frequencies appended together.
'uniq_ind_all' [numpy vector] consists of numpy
vector which consists of unique
indices of contributing baselines
for all frequencies.
'rev_ind_all' [numpy vector] reverse indices of
'ind_all' with reference to bins of
'uniq_ind_all'
'illumination' [numpy vector] complex grid
illumination weights contributed by
each baseline (including associated
kernel weight locations) and has a
size equal to that in 'ind_all'
'grid' [dictionary] contains information about populated
portions of the grid. It consists of values in the
following keys:
'ind_all' [numpy vector] indices of all grid
locations raveled to one dimension
from three dimensions of size
n_u x n_v x nchan
'per_bl2grid'
[list] each element in the list is a dictionary
corresponding to an interferometer with information
on its mapping and contribution to the grid. Each
dictionary has the following keys and values:
'label' [tuple of two strings]
interferometer label
'f_gridind' [numpy array] mapping information
with indices to the frequency axis
of the grid
'u_gridind' [numpy array] mapping information
with indices to the u-axis
of the grid. Must be of same size
as array under 'f_gridind'
'v_gridind' [numpy array] mapping information
with indices to the v-axis
of the grid. Must be of same size
as array under 'f_gridind'
'per_bl_per_freq_norm_wts'
[numpy array] mapping information
on the (complex) normalizing
multiplicative factor required to
make the sum of illumination/weights
per interferometer per frequency on
the grid equal to unity. Must be of
same size as array under 'f_gridind'
'illumination' [numpy array] Complex aperture
illumination/weights contributed
by the interferometer onto the grid.
The grid pixels to which it
contributes is given by 'f_gridind',
'u_gridind', 'v_gridind'. Must be of
same size as array under 'f_gridind'
'Vf' [numpy array] Complex visibilities
contributed by the
interferometer onto the grid. The
grid pixels to which it contributes
is given by 'f_gridind',
'u_gridind', 'v_gridind'. Must be of
same size as array under 'f_gridind'
'all_bl2grid'
[dictionary] contains the combined information of
mapping of all interferometers to the grid. It
consists of the following keys and values:
'blind' [numpy array] all interferometer
indices (to attribute ordered
labels) that map to the uvf-grid
'u_gridind' [numpy array] all indices to the
u-axis of the uvf-grid mapped to by
all interferometers whose indices
are given in key 'blind'. Must be
of same size as the array under key
'blind'
'v_gridind' [numpy array] all indices to the
v-axis of the uvf-grid mapped to by
all interferometers whose indices
are given in key 'blind'. Must be
of same size as the array under key
'blind'
'f_gridind' [numpy array] all indices to the
f-axis of the uvf-grid mapped to by
all interferometers whose indices
are given in key 'blind'. Must be
of same size as the array under key
'blind'
'indNN_list' [list of lists] Each item in the
top level list corresponds to an
interferometer in the same order as
in the attribute ordered_labels.
Each of these items is another list
consisting of the unraveled grid
indices it contributes to. The
unraveled indices are what are used
to obtain the u-, v- and f-indices
in the grid using a conversion
assuming f is the first axis, v is
the second and u is the third
'illumination' [numpy array] complex values of
aperture illumination contributed
by all interferometers to the grid.
The interferometer indices are in
'blind' and the grid indices are
in 'u_gridind', 'v_gridind' and
'f_gridind'. Must be of same size as
these indices
'per_bl_per_freq_norm_wts'
[numpy array] mapping information
on the (complex) normalizing
multiplicative factor required to
make the sum of illumination or
weights per interferometer per
frequency on the grid equal to
unity. This is appended for all
interferometers together. Must be of
same size as array under
'illumination'
'Vf' [numpy array] Complex visibilities
contributed by all
interferometers onto the grid. The
grid pixels to which it contributes
is given by 'f_gridind',
'u_gridind', 'v_gridind'. Must be of
same size as array under 'f_gridind'
and 'illumination'
bl2grid_mapper
[sparse matrix] contains the interferometer array to grid
mapping information in sparse matrix format. When converted
to a dense array, it will have dimensions nrows equal to size
of the 3D cube and ncols equal to number of visibility spectra
of all interferometers over all channels. In other words,
nrows = nu x nv x nchan and ncols = n_bl x nchan. Dot product
of this matrix with flattened visibility spectra or
interferometer weights will give the 3D cubes of gridded
visibilities and interferometer array illumination
respectively
Member Functions:
__init__() Initializes an instance of class InterferometerArray
__str__() Prints summary of an instance of this class
__add__() Operator overloading for adding interferometer(s)
__radd__() Operator overloading for adding interferometer(s)
__sub__() Operator overloading for removing interferometer(s)
add_interferometers()
Routine to add interferometer(s) to the interferometer
array instance. A wrapper for operator overloading
__add__() and __radd__()
remove_interferometers()
Routine to remove interferometer(s) from the interferometer
array instance. A wrapper for operator overloading __sub__()
interferometers_containing_antenna()
Find interferometer pairs which contain the specified
antenna labels
baseline_vectors()
Routine to return the interferometer label and baseline
vectors (sorted by interferometer label if specified)
refresh_antenna_pairs()
Refresh the individual antennas in the interferometer(s)
with the information in the Antenna instances in the
attribute antenna_array which is an instance of class
AntennaArray
FX() Computes the Fourier transform of the cross-correlated time
series of the interferometer pairs in the interferometer
array to compute the visibility spectra
XF() Computes the visibility spectra by cross-multiplying the
electric field spectra for all the interferometer pairs in
the interferometer array
get_visibilities()
Routine to return the interferometer labels, time-based
weights and visibilities (sorted by interferometer label
if specified) based on selection criteria specified by
flags, timestamps, frequency channels, labels and data pool
(most recent, stack, averaged, etc.)
stack() Stacks and computes visibilities and flags for all the
interferometers in the interferometer array from the
individual antennas in the pair.
accumulate() Accumulate and average visibility spectra across timestamps
under different polarizations depending on the time bin
size for the corresponding polarization for all
interferometers in the interferometer array
grid() Routine to produce a grid based on the interferometer array
grid_convolve() Routine to project the complex illumination power pattern
and the visibilities on the grid. It can operate on the
entire interferometer array or incrementally project the
visibilities and complex illumination power patterns from
specific interferometers on to an already existing grid.
(The latter is not implemented yet)
grid_convolve_old()
Routine to project the visibility illumination pattern and
the visibilities on the grid. It can operate on the entire
antenna array or incrementally project the visibilities and
illumination patterns from specific antenna pairs on to an
already existing grid.
grid_convolve_new()
Routine to project the complex illumination power pattern
and the visibilities on the grid from the interferometer
array
make_grid_cube()
Constructs the grid of complex power illumination and
visibilities using the gridding information determined for
every baseline. Flags are taken into account while
constructing this grid.
grid_unconvolve()
[Needs to be re-written] Routine to de-project the
visibility illumination pattern and the visibilities on the
grid. It can operate on the entire interferometer array or
incrementally de-project the visibilities and illumination
patterns of specific antenna pairs from an already existing
grid.
quick_beam_synthesis()
A quick generator of synthesized beam using interferometer
array grid illumination pattern using the center frequency.
Not intended to be used rigorously but rather for comparison
purposes and making quick plots
update_flags() Updates all flags in the interferometer array followed by
any flags that need overriding through inputs of specific
flag information
update() Updates the interferometer array instance with newer
attribute values. Can also be used to add and/or remove
interferometers with/without affecting the existing grid.
----------------------------------------------------------------------------
"""
def __init__(self, antenna_pairs=None, antenna_array=None):
"""
------------------------------------------------------------------------
Initializes an instance of class InterferometerArray
Class attributes initialized are:
antenna_array, interferometers, timestamp, t, f, f0, blc, trc, grid_blc,
grid_trc, gridx, gridy, grid_ready, grid_illumination, grid_Vf,
ordered_labels, grid_mapper
------------------------------------------------------------------------
"""
self.antenna_array = AntennaArray()
self.interferometers = {}
self.blc = NP.zeros(2)
self.trc = NP.zeros(2)
self.grid_blc = NP.zeros(2)
self.grid_trc = NP.zeros(2)
self.gridx, self.gridy = None, None
self.gridu, self.gridv = None, None
self.grid_ready = False
self.grid_illumination = {}
self.grid_Vf = {}
self._bl_contribution = {}
self.ordered_labels = [] # Usually output from member function baseline_vectors() or get_visibilities()
self.grid_mapper = {}
self.bl2grid_mapper = {} # contains the sparse mapping matrix
for pol in ['P11', 'P12', 'P21', 'P22']:
self.grid_mapper[pol] = {}
self.grid_mapper[pol]['labels'] = {}
self.grid_mapper[pol]['refind'] = []
# self.grid_mapper[pol]['bl_ind'] = []
self.grid_mapper[pol]['gridind'] = []
self.grid_mapper[pol]['refwts'] = None
self.grid_mapper[pol]['bl'] = {}
self.grid_mapper[pol]['bl']['ind_freq'] = []
self.grid_mapper[pol]['bl']['ind_all'] = None
self.grid_mapper[pol]['bl']['uniq_ind_all'] = None
self.grid_mapper[pol]['bl']['rev_ind_all'] = None
self.grid_mapper[pol]['bl']['illumination'] = None
self.grid_mapper[pol]['grid'] = {}
self.grid_mapper[pol]['grid']['ind_all'] = None
self.grid_mapper[pol]['per_bl2grid'] = []
self.grid_mapper[pol]['all_bl2grid'] = {}
self.grid_illumination[pol] = None
self.grid_Vf[pol] = None
self._bl_contribution[pol] = {}
self.bl2grid_mapper[pol] = None
if (antenna_array is not None) and (antenna_pairs is not None):
raise ValueError('InterferometerArray instance cannot be initialized with both inputs antenna_array and antenna_pairs.')
if antenna_array is not None:
if isinstance(antenna_array, AntennaArray):
self.antenna_array = antenna_array
else: # if antenna_array is just a list of antennas (Check this piece of code again)
self.antenna_array = self.antenna_array + antenna_array
ant_labels = self.antenna_array.antennas.keys()
for i in xrange(len(ant_labels)-1):
for j in xrange(i+1,len(ant_labels)):
ant_pair = Interferometer(self.antenna_array.antennas[ant_labels[i]], self.antenna_array.antennas[ant_labels[j]])
self.interferometers[ant_pair.label] = ant_pair
if antenna_pairs is not None:
if isinstance(antenna_pairs, Interferometer):
self.interferometers[antenna_pairs.label] = antenna_pairs
elif isinstance(antenna_pairs, dict):
for key,value in antenna_pairs.items():
if isinstance(key, tuple):
if len(key) == 2:
if isinstance(value, Interferometer):
self.interferometers[key] = value
else:
print 'An item found not to be an instance of class Interferometer. Discarding and proceeding ahead.'
else:
print 'Invalid interferometer label found. Discarding and proceeding ahead.'
else:
print 'Invalid interferometer label found. Discarding and proceeding ahead.'
elif isinstance(antenna_pairs, list):
for value in antenna_pairs:
if isinstance(value, Interferometer):
self.interferometers[value.label] = value
else:
print 'An item found not to be an instance of class Interferometer. Discarding and proceeding ahead.'
else:
raise TypeError('Input parameter antenna_pairs found to be of compatible type, namely, instance of class Interferometer, list of instances of class Interferometer or dictionary of interferometers.')
for label, interferometer in self.interferometers.items():
if label[0] not in self.antenna_array.antennas:
self.antenna_array = self.antenna_array + interferometer.A1
# self.antenna_array.add_antennas(interferometer.A1)
if label[1] not in self.antenna_array.antennas:
self.antenna_array = self.antenna_array + interferometer.A2
# self.antenna_array.add_antennas(interferometer.A2)
self.f = self.antenna_array.f
self.f0 = self.antenna_array.f0
self.t = None
self.timestamp = self.antenna_array.timestamp
############################################################################
def __str__(self):
printstr = '\n-----------------------------------------------------------------'
printstr += '\n Instance of class "{0}" in module "{1}".\n Holds the following "Interferometer" class instances with labels:\n '.format(self.__class__.__name__, self.__module__)
printstr += str(self.interferometers.keys()).strip('[]')
# printstr += ' '.join(sorted(self.interferometers.keys()))
printstr += '\n Interferometer array bounds: blc = [{0[0]}, {0[1]}],\n\ttrc = [{1[0]}, {1[1]}]'.format(self.blc, self.trc)
printstr += '\n Grid bounds: blc = [{0[0]}, {0[1]}],\n\ttrc = [{1[0]}, {1[1]}]'.format(self.grid_blc, self.grid_trc)
printstr += '\n-----------------------------------------------------------------'
return printstr
############################################################################
def __add__(self, others):
"""
------------------------------------------------------------------------
Operator overloading for adding interferometer(s)
Inputs:
others [Instance of class InterferometerArray, dictionary holding
instance(s) of class Interferometer, list of instances of
class Interferometer, or a single instance of class
Interferometer] If a dictionary is provided, the keys should
be the antenna labels and the values should be instances of
class Interferometer. If a list is provided, it should be a
list of valid instances of class Interferometer. These
instance(s) of class Interferometer will be added to the
existing instance of InterferometerArray class.
------------------------------------------------------------------------
"""
retval = self
if isinstance(others, InterferometerArray):
# for k,v in others.interferometers.items():
for k,v in others.interferometers.iteritems():
if k in retval.interferometers:
print "Interferometer {0} already included in the list of interferometers.".format(k)
print "For updating, use the update() method. Ignoring interferometer {0}".format(k)
else:
retval.interferometers[k] = v
print 'Interferometer "{0}" added to the list of interferometers.'.format(k)
elif isinstance(others, dict):
# for item in others.values():
for item in others.itervalues():
if isinstance(item, Interferometer):
if item.label in retval.interferometers:
print "Interferometer {0} already included in the list of interferometers.".format(item.label)
print "For updating, use the update() method. Ignoring interferometer {0}".format(item.label)
else:
retval.interferometers[item.label] = item
print 'Interferometer "{0}" added to the list of interferometers.'.format(item.label)
elif isinstance(others, list):
for i in range(len(others)):
if isinstance(others[i], Interferometer):
if others[i].label in retval.interferometers:
print "Interferometer {0} already included in the list of interferometers.".format(others[i].label)
print "For updating, use the update() method. Ignoring interferometer {0}".format(others[i].label)
else:
retval.interferometers[others[i].label] = others[i]
print 'Interferometer "{0}" added to the list of interferometers.'.format(others[i].label)
else:
print 'Element \# {0} is not an instance of class Interferometer.'.format(i)
elif isinstance(others, Interferometer):
if others.label in retval.interferometers:
print "Interferometer {0} already included in the list of interferometers.".format(others.label)
print "For updating, use the update() method. Ignoring interferometer {0}".format(others[i].label)
else:
retval.interferometers[others.label] = others
print 'Interferometer "{0}" added to the list of interferometers.'.format(others.label)
else:
print 'Input(s) is/are not instance(s) of class Interferometer.'
return retval
############################################################################
def __radd__(self, others):
"""
------------------------------------------------------------------------
Operator overloading for adding interferometer(s)
Inputs:
others [Instance of class InterferometerArray, dictionary holding
instance(s) of class Interferometer, list of instances of
class Interferometer, or a single instance of class
Interferometer] If a dictionary is provided, the keys should
be the interferometer labels and the values should be
instances of class Interferometer. If a list is provided, it
should be a list of valid instances of class Interferometer.
These instance(s) of class Interferometer will be added to
the existing instance of InterferometerArray class.
------------------------------------------------------------------------
"""
return self.__add__(others)
############################################################################
def __sub__(self, others):
"""
------------------------------------------------------------------------
Operator overloading for removing interferometer(s)
Inputs:
others [Instance of class InterferometerArray, dictionary holding
instance(s) of class Interferometer, list of instances of
class Interferometer, list of strings containing
interferometer labels or a single instance of class
Interferometer] If a dictionary is provided, the keys should
be the interferometer labels and the values should be
instances of class Interferometer. If a list is provided, it
should be a list of valid instances of class Interferometer.
These instance(s) of class Interferometer will be removed
from the existing instance of InterferometerArray class.
------------------------------------------------------------------------
"""
retval = self
if isinstance(others, dict):
for item in others.values():
if isinstance(item, Interferometer):
if item.label not in retval.interferometers:
print "Interferometer {0} does not exist in the list of interferometers.".format(item.label)
else:
del retval.interferometers[item.label]
print 'Interferometer "{0}" removed from the list of interferometers.'.format(item.label)
elif isinstance(others, list):
for i in range(0,len(others)):
if isinstance(others[i], str):
if others[i] in retval.interferometers:
del retval.interferometers[others[i]]
print 'Interferometer {0} removed from the list of interferometers.'.format(others[i])
elif isinstance(others[i], Interferometer):
if others[i].label in retval.interferometers:
del retval.interferometers[others[i].label]
print 'Interferometer {0} removed from the list of interferometers.'.format(others[i].label)
else:
print "Interferometer {0} does not exist in the list of interferometers.".format(others[i].label)
else:
print 'Element \# {0} has no matches in the list of interferometers.'.format(i)
elif others in retval.interferometers:
del retval.interferometers[others]
print 'Interferometer "{0}" removed from the list of interferometers.'.format(others)
elif isinstance(others, Interferometer):
if others.label in retval.interferometers:
del retval.interferometers[others.label]
print 'Interferometer "{0}" removed from the list of interferometers.'.format(others.label)
else:
print "Interferometer {0} does not exist in the list of interferometers.".format(others.label)
else:
print 'No matches found in existing list of interferometers.'
return retval
############################################################################
def add_interferometers(self, A=None):
"""
------------------------------------------------------------------------
Routine to add interferometer(s) to the interferometer array instance.
A wrapper for operator overloading __add__() and __radd__()
Inputs:
A [Instance of class InterferometerArray, dictionary holding
instance(s) of class Interferometer, list of instances of
class Interferometer, or a single instance of class
Interferometer] If a dictionary is provided, the keys should
be the interferometer labels and the values should be
instances of class Interferometer. If a list is provided, it
should be a list of valid instances of class Interferometer.
These instance(s) of class Interferometer will be added to
the existing instance of InterferometerArray class.
------------------------------------------------------------------------
"""
if A is None:
print 'No interferometer(s) supplied.'
elif isinstance(A, (list, Interferometer)):
self = self.__add__(A)
else:
print 'Input(s) is/are not instance(s) of class Interferometer.'
############################################################################
def remove_interferometers(self, A=None):
"""
------------------------------------------------------------------------
Routine to remove interferometer(s) from the interferometer array
instance. A wrapper for operator overloading __sub__()
Inputs:
A [Instance of class InterferometerArray, dictionary holding
instance(s) of class Interferometer, list of instances of
class Interferometer, or a single instance of class
Interferometer] If a dictionary is provided, the keys should
be the interferometer labels and the values should be
instances of class Interferometer. If a list is provided, it
should be a list of valid instances of class Interferometer.
These instance(s) of class Interferometer will be removed
from the existing instance of InterferometerArray class.
------------------------------------------------------------------------
"""
if A is None:
print 'No interferometer specified for removal.'
else:
self = self.__sub__(A)
############################################################################
def interferometers_containing_antenna(self, antenna_label):
"""
------------------------------------------------------------------------
Find interferometer pairs which contain the specified antenna labels
Inputs:
antenna_label [list] List of antenna labels which will be searched for
in the interferometer pairs in the interferometer array.
Outputs:
ant_pair_labels
[list] List of interferometer pair labels containing one
of more of the specified antenna labels
ant_order [list] List of antenna order of antenna labels found in
the interferometer pairs of the interferometer array. If
the antenna label appears as the first antenna in the
antenna pair, ant_order is assigned to 1 and if it is
the second antenna in the pair, it is assigned to 2.
------------------------------------------------------------------------
"""
ant_pair_labels = [ant_pair_label for ant_pair_label in self.interferometers if antenna_label in ant_pair_label]
ant_order = [1 if ant_pair_label[0] == antenna_label else 2 for ant_pair_label in ant_pair_labels]
return (ant_pair_labels, ant_order)
############################################################################
def baseline_vectors(self, pol=None, flag=False, sort=True):
"""
------------------------------------------------------------------------
Routine to return the interferometer label and baseline vectors (sorted
by interferometer label if specified)
Keyword Inputs:
pol [string] select baselines of this polarization that are either
flagged or unflagged as specified by input parameter flag.
Allowed values are 'P11', 'P12', 'P21', and 'P22'.
Default=None. This means all baselines are returned
irrespective of the flags
flag [boolean] If False, return unflagged baselines, otherwise
return flagged ones. Default=None means return all baselines
independent of flagging or polarization
sort [boolean] If True, returned interferometer information is
sorted by interferometer's first antenna label. Default = True.
Output:
outdict [dictionary] Output consists of a dictionary with the following
keys and information:
'labels': list of tuples of strings of interferometer labels
'baselines': baseline vectors of interferometers (3-column
array)
------------------------------------------------------------------------
"""
if not isinstance(sort, bool):
raise TypeError('sort keyword has to be a Boolean value.')
if flag is not None:
if not isinstance(flag, bool):
raise TypeError('flag keyword has to be a Boolean value.')
if pol is None:
if sort: # sort by first antenna label
xyz = NP.asarray([[self.interferometers[label].location.x, self.interferometers[label].location.y, self.interferometers[label].location.z] for label in sorted(self.interferometers.keys(), key=lambda tup: tup[0])])
labels = sorted(self.interferometers.keys(), key=lambda tup: tup[0])
else:
xyz = NP.asarray([[self.interferometers[label].location.x, self.interferometers[label].location.y, self.interferometers[label].location.z] for label in self.interferometers.keys()])
labels = self.interferometers.keys()
else:
if not isinstance(pol, str):
raise TypeError('Input parameter must be a string')
if not pol in ['P11', 'P12', 'P21', 'P22']:
raise ValueError('Invalid specification for input parameter pol')
if sort: # sort by first antenna label
if flag is None: # get all baselines
xyz = NP.asarray([[self.interferometers[label].location.x, self.interferometers[label].location.y, self.interferometers[label].location.z] for label in sorted(self.interferometers.keys(), key=lambda tup: tup[0])])
labels = [label for label in sorted(self.interferometers.keys(), key=lambda tup: tup[0])]
else:
if flag: # get flagged baselines
xyz = NP.asarray([[self.interferometers[label].location.x, self.interferometers[label].location.y, self.interferometers[label].location.z] for label in sorted(self.interferometers.keys(), key=lambda tup: tup[0]) if self.interferometers[label].crosspol.flag[pol]])
labels = [label for label in sorted(self.interferometers.keys(), key=lambda tup: tup[0]) if self.interferometers[label].crosspol.flag[pol]]
else: # get unflagged baselines
xyz = NP.asarray([[self.interferometers[label].location.x, self.interferometers[label].location.y, self.interferometers[label].location.z] for label in sorted(self.interferometers.keys(), key=lambda tup: tup[0]) if not self.interferometers[label].crosspol.flag[pol]])
labels = [label for label in sorted(self.interferometers.keys(), key=lambda tup: tup[0]) if not self.interferometers[label].crosspol.flag[pol]]
else: # no sorting
if flag is None: # get all baselines
xyz = NP.asarray([[self.interferometers[label].location.x, self.interferometers[label].location.y, self.interferometers[label].location.z] for label in self.interferometers.keys()])
labels = [label for label in self.interferometers.keys()]
else:
if flag: # get flagged baselines
xyz = NP.asarray([[self.interferometers[label].location.x, self.interferometers[label].location.y, self.interferometers[label].location.z] for label in self.interferometers.keys() if self.interferometers[label].crosspol.flag[pol]])
labels = [label for label in self.interferometers.keys() if self.interferometers[label].crosspol.flag[pol]]
else: # get unflagged baselines
xyz = NP.asarray([[self.interferometers[label].location.x, self.interferometers[label].location.y, self.interferometers[label].location.z] for label in self.interferometers.keys() if not self.interferometers[label].crosspol.flag[pol]])
labels = [label for label in self.interferometers.keys() if not self.interferometers[label].crosspol.flag[pol]]
outdict = {}
outdict['labels'] = labels
outdict['baselines'] = xyz
return outdict
############################################################################
def refresh_antenna_pairs(self, interferometer_labels=None,
antenna_labels=None):
"""
------------------------------------------------------------------------
Refresh the individual antennas in the interferometer(s) with the
information in the Antenna instances in the attribute antenna_array
which is an instance of class AntennaArray
Inputs:
interferometer_labels
[list] list of interferometer labels each given as a tuple
of antenna labels. The antennas in these pairs are refreshed
using the corresponding antenna instances in the attribute
antenna_array. Default = None.
antenna_labels
[list] list of antenna labels to determine which
interferometers they contribute to. The antenna pairs in
these interferometers are refreshed based on the current
antenna instances in the attribute antenna_array.
Default = None.
If both input keywords interferometer_labels and antenna_labels are
set to None, all the interferometer instances are refreshed.
------------------------------------------------------------------------
"""
ilabels = []
if interferometer_labels is not None:
if not isinstance(interferometer_labels, list):
raise TypeError('Input keyword interferometer_labels must be a list')
ilabels = antenna_labels
if antenna_labels is not None:
if not isinstance(interferometer_labels, list):
raise TypeError('Input keyword interferometer_labels must be a list')
ant_pair_labels, = self.interferometers_containing_antenna(antenna_labels)
ilabels += ant_pair_labels
if len(ilabels) == 0:
ilabels = self.interferometers.keys()
for antpair_label in ilabels:
if antpair_label in self.interferometers:
self.interferometers[antpair_label].refresh_antenna_pairs(A1=self.antenna_array.antennas[antpair_label[0]], A2=self.antenna_array.antennas[antpair_label[1]])
############################################################################
def FX(self, parallel=False, nproc=None):
"""
------------------------------------------------------------------------
Computes the Fourier transform of the cross-correlated time series of
the interferometer pairs in the interferometer array to compute the
visibility spectra
Inputs:
parallel [boolean] specifies if parallelization is to be invoked.
False (default) means only serial processing
nproc [integer] specifies number of independent processes to spawn.
Default = None, means automatically determines the number of
process cores in the system and use one less than that to
avoid locking the system for other processes. Applies only
if input parameter 'parallel' (see above) is set to True.
If nproc is set to a value more than the number of process
cores in the system, it will be reset to number of process
cores in the system minus one to avoid locking the system out
for other processes
------------------------------------------------------------------------
"""
if self.t is None:
self.t = self.interferometers.itervalues().next().t
if self.f is None:
self.f = self.interferometers.itervalues().next().f
if self.f0 is None:
self.f0 = self.interferometers.itervalues().next().f0
# for label in self.interferometers: # Start processes in parallel
# self.interferometers[label].start()
if not parallel:
for label in self.interferometers:
self.interferometers[label].FX()
elif parallel or (nproc is not None):
if nproc is None:
nproc = max(MP.cpu_count()-1, 1)
else:
nproc = min(nproc, max(MP.cpu_count()-1, 1))
pool = MP.Pool(processes=nproc)
updated_interferometers = pool.map(unwrap_interferometer_FX, IT.izip(self.interferometers.values()))
pool.close()
pool.join()
for interferometer in updated_interferometers:
self.interferometers[interferometer.label] = interferometer
del updated_interferometers
############################################################################
def XF(self):
"""
------------------------------------------------------------------------
Computes the visibility spectra by cross-multiplying the electric field
spectra for all the interferometer pairs in the interferometer array
------------------------------------------------------------------------
"""
if self.t is None:
self.t = self.interferometers.itervalues().next().t
if self.f is None:
self.f = self.interferometers.itervalues().next().f
if self.f0 is None:
self.f0 = self.interferometers.itervalues().next().f0
for label in self.interferometers:
self.interferometers[label].XF()
############################################################################
def get_visibilities_old(self, pol, flag=None, sort=True):
"""
------------------------------------------------------------------------
Routine to return the interferometer label and visibilities (sorted by
interferometer label if specified)
Keyword Inputs:
pol [string] select baselines of this polarization that are either
flagged or unflagged as specified by input parameter flag.
Allowed values are 'P11', 'P12', 'P21', and 'P22'. Only one of
these values must be specified.
flag [boolean] If False, return visibilities of unflagged baselines,
otherwise return flagged ones. Default=None means all
visibilities independent of flagging are returned.
sort [boolean] If True, returned interferometer information is
sorted by interferometer's first antenna label. Default = True.
Output:
outdict [dictionary] Output consists of a dictionary with the following
keys and information:
'labels': Contains a numpy array of strings of
interferometer labels
'visibilities':
interferometer visibilities (n_bl x nchan array)
------------------------------------------------------------------------
"""
try:
pol
except NameError:
raise NameError('Input parameter pol must be specified.')
if not isinstance(pol, str):
raise TypeError('Input parameter must be a string')
if not pol in ['P11', 'P12', 'P21', 'P22']:
raise ValueError('Invalid specification for input parameter pol')
if not isinstance(sort, bool):
raise TypeError('sort keyword has to be a Boolean value.')
if flag is not None:
if not isinstance(flag, bool):
raise TypeError('flag keyword has to be a Boolean value.')
if sort: # sort by first antenna label
if flag is None: # get all baselines
vis = NP.asarray([self.interferometers[label].crosspol.Vf[pol] for label in sorted(self.interferometers.keys(), key=lambda tup: tup[0])])
labels = [label for label in sorted(self.interferometers.keys(), key=lambda tup: tup[0])]
else:
if flag: # get flagged baselines
vis = NP.asarray([self.interferometers[label].crosspol.Vf[pol] for label in sorted(self.interferometers.keys(), key=lambda tup: tup[0]) if self.interferometers[label].crosspol.flag[pol]])
labels = [label for label in sorted(self.interferometers.keys(), key=lambda tup: tup[0]) if self.interferometers[label].crosspol.flag[pol]]
else: # get unflagged baselines
vis = NP.asarray([self.interferometers[label].crosspol.Vf[pol] for label in sorted(self.interferometers.keys(), key=lambda tup: tup[0]) if not self.interferometers[label].crosspol.flag[pol]])
labels = [label for label in sorted(self.interferometers.keys(), key=lambda tup: tup[0]) if not self.interferometers[label].crosspol.flag[pol]]
else: # no sorting
if flag is None:
vis = NP.asarray([self.interferometers[label].crosspol.Vf[pol] for label in self.interferometers.keys()])
labels = [label for label in self.interferometers.keys()]
else:
if flag: # get flagged baselines
vis = NP.asarray([self.interferometers[label].crosspol.Vf[pol] for label in self.interferometers.keys() if self.interferometers[label].crosspol.flag[pol]])
labels = [label for label in self.interferometers.keys() if self.interferometers[label].crosspol.flag[pol]]
else: # get unflagged baselines
vis = NP.asarray([self.interferometers[label].crosspol.Vf[pol] for label in self.interferometers.keys() if not self.interferometers[label].crosspol.flag[pol]])
labels = [label for label in sorted(self.interferometers.keys(), key=lambda tup: tup[0]) if not self.interferometers[label].crosspol.flag[pol]]
outdict = {}
outdict['labels'] = labels
outdict['visibilities'] = vis
return outdict
############################################################################
def get_visibilities(self, pol, flag=None, tselect=None, fselect=None,
bselect=None, datapool=None, sort=True):
"""
------------------------------------------------------------------------
Routine to return the interferometer labels, time-based weights and
visibilities (sorted by interferometer label if specified) based on
selection criteria specified by flags, timestamps, frequency channels,
labels and data pool (most recent, stack, averaged, etc.)
Keyword Inputs:
pol [string] select baselines of this polarization that are either
flagged or unflagged as specified by input parameter flag.
Allowed values are 'P11', 'P12', 'P21', and 'P22'. Only one of
these values must be specified.
flag [boolean] If False, return visibilities of unflagged baselines,
otherwise return flagged ones. Default=None means all
visibilities independent of flagging are returned.
tselect [scalar, list, numpy array] timestamp index for visibilities
selection. For most recent visibility, it must be set to -1.
For all other selections, indices in tselect must be in the
valid range of indices along time axis for stacked and
averaged visibilities. Default=None means most recent data is
selected.
fselect [scalar, list, numpy array] frequency channel index for
visibilities selection. Indices must be in the valid range of
indices along the frequency axis for visibilities.
Default=None selects all frequency channels
bselect [list of tuples] labels of interferometers to select. If set
to None (default) all interferometers are selected.
datapool [string] denotes the data pool from which visibilities are to
be selected. Accepted values are 'current', 'stack', 'avg' and
None (default, same as 'current'). If set to None or
'current', the value in tselect is ignored and only
visibilities of the most recent timestamp are selected. If set
to None or 'current' the attribute Vf_stack is checked first
and if unavailable, attribute crosspol.Vf is used. For 'stack'
and 'avg', attributes Vf_stack and Vf_avg are used
respectively
sort [boolean] If True, returned interferometer information is
sorted by interferometer's first antenna label. Default=True.
Output:
outdict [dictionary] Output consists of a dictionary with the following
keys and information:
'labels' [list of tuples] Contains a list of
interferometer labels
'visibilities' [list or numpy array] interferometer
visibilities under the specified polarization.
In general, it is a list of
numpy arrays where each array in the list
corresponds to
an individual interferometer and the size of
each numpy array is n_ts x nchan. If input
keyword flag is set to None, the visibilities
are rearranged into a numpy array of size
n_ts x n_bl x nchan.
'twts' [list or numpy array] weights based on flags
along time axis under the specified
polarization. In general it is a list of numpy
arrays where each array in the list corresponds
to an individual interferometer and the size
of each array is n_ts x 1. If input
keyword flag is set to None, the time weights
are rearranged into a numpy array of size
n_ts x n_bl x 1
------------------------------------------------------------------------
"""
if not isinstance(sort, bool):
raise TypeError('sort keyword has to be a Boolean value.')
if bselect is None:
labels = self.interferometers.keys()
elif isinstance(bselect, list):
labels = [label for label in bselect if label in self.interferometers]
if sort:
labels_orig = copy.deepcopy(labels)
labels = [label for label in sorted(labels_orig, key=lambda tup: tup[0])]
visinfo = [self.interferometers[label].get_visibilities(pol, flag=flag, tselect=tselect, fselect=fselect, datapool=datapool) for label in labels]
outdict = {}
outdict['labels'] = labels
outdict['twts'] = [vinfo['twts'] for vinfo in visinfo]
outdict['visibilities'] = [vinfo['visibilities'] for vinfo in visinfo]
if flag is None:
outdict['visibilities'] = NP.swapaxes(NP.asarray(outdict['visibilities']), 0, 1)
outdict['twts'] = NP.swapaxes(NP.asarray(outdict['twts']), 0, 1)
outdict['twts'] = outdict['twts'][:,:,NP.newaxis]
return outdict
############################################################################
def stack(self, on_flags=True, on_data=True, parallel=False, nproc=None):
"""
------------------------------------------------------------------------
Stacks and computes visibilities and flags for all the interferometers
in the interferometer array from the individual antennas in the pair.
Inputs:
on_flags [boolean] if set to True (default), combines the time-stacked
electric field flags from individual antennas from the
common timestamps into time-stacked visibility flags
on_data [boolean] if set to True (default), combines the time-stacked
electric fields from individual antennas from the common
timestamps into time-stacked visibilities
parallel [boolean] specifies if parallelization is to be invoked.
False (default) means only serial processing
nproc [integer] specifies number of independent processes to spawn.
Default = None, means automatically determines the number of
process cores in the system and use one less than that to
avoid locking the system for other processes. Applies only
if input parameter 'parallel' (see above) is set to True.
If nproc is set to a value more than the number of process
cores in the system, it will be reset to number of process
cores in the system minus one to avoid locking the system out
for other processes
------------------------------------------------------------------------
"""
if parallel:
if nproc is None:
nproc = max(MP.cpu_count()-1, 1)
else:
nproc = min(nproc, max(MP.cpu_count()-1, 1))
list_of_perform_flag_stack = [on_flags] * len(self.interferometers)
list_of_perform_data_stack = [on_data] * len(self.interferometers)
pool = MP.Pool(processes=nproc)
updated_interferometers = pool.map(unwrap_interferometer_stack, IT.izip(self.interferometers.values(), list_of_perform_flag_stack, list_of_perform_data_stack))
pool.close()
pool.join()
for interferometer in updated_interferometers:
self.interferometers[interferometer.label] = interferometer
del updated_interferometers
else:
for label in self.interferometers:
self.interferometers[label].stack(on_flags=on_flags, on_data=on_data)
############################################################################
def accumulate(self, tbinsize=None):
"""
------------------------------------------------------------------------
Accumulate and average visibility spectra across timestamps under
different polarizations depending on the time bin size for the
corresponding polarization for all interferometers in the
interferometer array
Inputs:
tbinsize [scalar or dictionary] Contains bin size of timestamps while
stacking. Default = None means all visibility spectra over all
timestamps are averaged. If scalar, the same (positive) value
applies to all polarizations. If dictionary, timestamp bin size
(positive) is provided under each key 'P11', 'P12', 'P21',
'P22'. If any of the keys is missing the visibilities for that
polarization are averaged over all timestamps.
------------------------------------------------------------------------
"""
for label in self.interferometers:
self.interferometers[label].accumulate(tbinsize=tbinsize)
############################################################################
def grid(self, uvspacing=0.5, uvpad=None, pow2=True):
"""
------------------------------------------------------------------------
Routine to produce a grid based on the interferometer array
Inputs:
uvspacing [Scalar] Positive value indicating the maximum uv-spacing
desirable at the lowest wavelength (max frequency).
Default = 0.5
xypad [List] Padding to be applied around the interferometer
locations before forming a grid. List elements should be
positive. If it is a one-element list, the element is
applicable to both x and y axes. If list contains three or
more elements, only the first two elements are considered
one for each axis. Default = None.
pow2 [Boolean] If set to True, the grid is forced to have a size
a next power of 2 relative to the actual sie required. If
False, gridding is done with the appropriate size as
determined by uvspacing. Default = True.
------------------------------------------------------------------------
"""
if self.f is None:
self.f = self.interferometers.itervalues().next().f
if self.f0 is None:
self.f0 = self.interferometers.itervalues().next().f0
wavelength = FCNST.c / self.f
min_lambda = NP.abs(wavelength).min()
# Change itervalues() to values() when porting to Python 3.x
# May have to change *blc and *trc with zip(*blc) and zip(*trc) when using Python 3.x
blc = [[self.interferometers[label].blc[0,0], self.interferometers[label].blc[0,1]] for label in self.interferometers]
trc = [[self.interferometers[label].trc[0,0], self.interferometers[label].trc[0,1]] for label in self.interferometers]
self.trc = NP.amax(NP.abs(NP.vstack((NP.asarray(blc), NP.asarray(trc)))), axis=0).ravel() / min_lambda
self.blc = -1 * self.trc
self.gridu, self.gridv = GRD.grid_2d([(self.blc[0], self.trc[0]), (self.blc[1], self.trc[1])], pad=uvpad, spacing=uvspacing, pow2=True)
self.grid_blc = NP.asarray([self.gridu.min(), self.gridv.min()])
self.grid_trc = NP.asarray([self.gridu.max(), self.gridv.max()])
self.grid_ready = True
############################################################################
def grid_convolve(self, pol=None, antpairs=None, unconvolve_existing=False,
normalize=False, method='NN', distNN=NP.inf, tol=None,
maxmatch=None, identical_interferometers=True,
gridfunc_freq=None, mapping='weighted', wts_change=False,
parallel=False, nproc=None, pp_method='pool', verbose=True):
"""
------------------------------------------------------------------------
Routine to project the complex illumination power pattern and the
visibilities on the grid. It can operate on the entire interferometer
array or incrementally project the visibilities and complex illumination
power patterns from specific interferometers on to an already existing
grid. (The latter is not implemented yet)
Inputs:
pol [String] The polarization to be gridded. Can be set to
'P11', 'P12', 'P21' or 'P22'. If set to None, gridding for
all the polarizations is performed. Default = None
antpairs [instance of class InterferometerArray, single instance or
list of instances of class Interferometer, or a dictionary
holding instances of class Interferometer] If a dictionary
is provided, the keys should be the interferometer labels
and the values should be instances of class Interferometer.
If a list is provided, it should be a list of valid
instances of class Interferometer. These instance(s) of
class Interferometer will be merged to the existing grid
contained in the instance of InterferometerArray class. If
ants is not provided (set to None), the gridding operations
will be performed on the entire set of interferometers
contained in the instance of class InterferometerArray.
Default=None.
unconvolve_existing
[Boolean] Default = False. If set to True, the effects of
gridding convolution contributed by the interferometer(s)
specified will be undone before updating the interferometer
measurements on the grid, if the interferometer(s) is/are
already found to in the set of interferometers held by the
instance of InterferometerArray. If False and if one or more
interferometer instances specified are already found to be
held in the instance of class InterferometerArray, the code
will stop raising an error indicating the gridding oepration
cannot proceed.
normalize [Boolean] Default = False. If set to True, the gridded
weights are divided by the sum of weights so that the
gridded weights add up to unity. (Need to work on
normaliation)
method [string] The gridding method to be used in applying the
interferometer weights on to the interferometer array grid.
Accepted values are 'NN' (nearest neighbour - default), 'CS'
(cubic spline), or 'BL' (Bi-linear). In case of applying grid
weights by 'NN' method, an optional distance upper bound for
the nearest neighbour can be provided in the parameter distNN
to prune the search and make it efficient. Currently, only
the nearest neighbour method is operational.
distNN [scalar] A positive value indicating the upper bound on
distance to the nearest neighbour in the gridding process. It
has units of distance, the same units as the interferometer
attribute location and interferometer array attribute gridx
and gridy. Default is NP.inf (infinite distance). It will be
internally converted to have same units as interferometer
attributes wtspos (units in number of wavelengths)
maxmatch [scalar] A positive value indicating maximum number of input
locations in the interferometer grid to be assigned.
Default = None. If set to None, all the interferometer array
grid elements specified are assigned values for each
interferometer. For instance, to have only one interferometer
array grid element to be populated per interferometer, use
maxmatch=1.
tol [scalar] If set, only lookup data with abs(val) > tol will be
considered for nearest neighbour lookup. Default = None
implies all lookup values will be considered for nearest
neighbour determination. tol is to be interpreted as a
minimum value considered as significant in the lookup table.
identical_interferometers
[boolean] indicates if all interferometer elements are to be
treated as identical. If True (default), they are identical
and their gridding kernels are identical. If False, they are
not identical and each one has its own gridding kernel.
gridfunc_freq
[String scalar] If set to None (not provided) or to 'scale'
assumes that attribute wtspos is given for a
reference frequency which need to be scaled for the frequency
channels. Will be ignored if the number of elements of list
in this attribute under the specific polarization are the
same as the number of frequency channels.
mapping [string] indicates the type of mapping between baseline
locations and the grid locations. Allowed values are
'sampled' and 'weighted' (default). 'sampled' means only the
baseline measurement closest ot a grid location contributes
to that grid location, whereas, 'weighted' means that all the
baselines contribute in a weighted fashion to their nearest
grid location. The former is faster but possibly discards
baseline data whereas the latter is slower but includes all
data along with their weights.
wts_change [boolean] indicates if weights and/or their lcoations have
changed from the previous intergration or snapshot.
Default=False means they have not changed. In such a case the
baseline-to-grid mapping and grid illumination pattern do not
have to be determined, and mapping and values from the
previous snapshot can be used. If True, a new mapping has to
be determined.
parallel [boolean] specifies if parallelization is to be invoked.
False (default) means only serial processing
nproc [integer] specifies number of independent processes to spawn.
Default = None, means automatically determines the number of
process cores in the system and use one less than that to
avoid locking the system for other processes. Applies only
if input parameter 'parallel' (see above) is set to True.
If nproc is set to a value more than the number of process
cores in the system, it will be reset to number of process
cores in the system minus one to avoid locking the system out
for other processes
pp_method [string] specifies if the parallelization method is handled
automatically using multirocessing pool or managed manually
by individual processes and collecting results in a queue.
The former is specified by 'pool' (default) and the latter
by 'queue'. These are the two allowed values. The pool method
has easier bookkeeping and can be fast if the computations
not expected to be memory bound. The queue method is more
suited for memory bound processes but can be slower or
inefficient in terms of CPU management.
verbose [boolean] If True, prints diagnostic and progress messages.
If False (default), suppress printing such messages.
------------------------------------------------------------------------
"""
eps = 1.0e-10
if pol is None:
pol = ['P11', 'P12', 'P21', 'P22']
elif not isinstance(pol, list):
pol = [pol]
if not self.grid_ready:
self.grid()
crosspol = ['P11', 'P12', 'P21', 'P22']
for cpol in crosspol:
if cpol in pol:
if antpairs is not None:
if isinstance(antpairs, Interferometer):
antpairs = [antpairs]
if isinstance(antpairs, (dict, InterferometerArray)):
# Check if these interferometers are new or old and compatible
for key in antpairs:
if isinstance(antpairs[key], Interferometer): # required if antpairs is a dictionary and not instance of InterferometerArray
if key in self.interferometers:
if unconvolve_existing: # Effects on the grid of interferometers already existing must be removed
if self.interferometers[key]._gridinfo[cpol]: # if gridding info is not empty
for i in range(len(self.f)):
self.grid_unconvolve(antpairs[key].label)
else:
raise KeyError('Interferometer {0} already found to exist in the dictionary of interferometers but cannot proceed grid_convolve() without unconvolving first.'.format(antpairs[key].label))
else:
del antpairs[key] # remove the dictionary element since it is not an Interferometer instance
if identical_interferometers and (gridfunc_freq == 'scale'):
bl_dict = self.baseline_vectors(pol=cpol, flag=False, sort=True)
bl_xy = bl_dict['baselines'][:,:2]
self.ordered_labels = bl_dict['labels']
n_bl = bl_xy.shape[0]
vis_dict = self.get_visibilities_old(cpol, flag=False, sort=True)
vis = vis_dict['visibilities'].astype(NP.complex64)
# Since antenna pairs are identical, read from first antenna pair, since wtspos are scaled with frequency, read from first frequency channel
wtspos_xy = antpairs[0].wtspos[cpol][0] * FCNST.c/self.f[0]
wts = antpairs[0].wts[cpol][0]
n_wts = wts.size
reflocs_xy = bl_xy[:,NP.newaxis,:] + wtspos_xy[NP.newaxis,:,:]
refwts_xy = wts.reshape(1,-1) * NP.ones((n_bl,1))
reflocs_xy = reflocs_xy.reshape(-1,bl_xy.shape[1])
refwts_xy = refwts_xy.reshape(-1,1).astype(NP.complex64)
reflocs_uv = reflocs_xy[:,NP.newaxis,:] * self.f.reshape(1,-1,1) / FCNST.c
refwts_uv = refwts_xy * NP.ones((1,self.f.size))
reflocs_uv = reflocs_uv.reshape(-1,bl_xy.shape[1])
refwts_uv = refwts_uv.reshape(-1,1).ravel()
inplocs = NP.hstack((self.gridu.reshape(-1,1), self.gridv.reshape(-1,1)))
ibind, nnval = LKP.lookup_1NN(reflocs_uv, refwts_uv, inplocs,
distance_ULIM=distNN*self.f.max()/FCNST.c,
remove_oob=True, tol=tol, maxmatch=maxmatch)[:2]
else:
bl_dict = self.baseline_vectors(pol=cpol, flag=None, sort=True)
self.ordered_labels = bl_dict['labels']
bl_xy = bl_dict['baselines'][:,:2] # n_bl x 2
n_bl = bl_xy.shape[0]
# Vf_dict = self.get_visibilities_old(cpol, flag=None, sort=True)
# Vf = Vf_dict['visibilities'].astype(NP.complex64) # n_bl x nchan
Vf_dict = self.get_visibilities(cpol, flag=None, tselect=-1, fselect=None, bselect=None, datapool='avg', sort=True)
Vf = Vf_dict['visibilities'].astype(NP.complex64) # (n_ts=1) x n_bl x nchan
Vf = NP.squeeze(Vf, axis=0) # n_bl x nchan
if Vf.shape[0] != n_bl:
raise ValueError('Encountered unexpected behavior. Need to debug.')
bl_labels = Vf_dict['labels']
twts = Vf_dict['twts'] # (n_ts=1) x n_bl x (nchan=1)
twts = NP.squeeze(twts, axis=(0,2)) # n_bl
if verbose:
print 'Gathered baseline data for gridding convolution for timestamp {0}'.format(self.timestamp)
if wts_change or (not self.grid_mapper[cpol]['labels']):
if gridfunc_freq == 'scale':
if identical_interferometers:
wts_tol = 1e-6
# Since antenna pairs are identical, read from first antenna pair, since wtspos are scaled with frequency, read from first frequency channel
wtspos_xy = self.interferometers.itervalues().next().wtspos[cpol][0] * FCNST.c/self.f[0]
wts = self.interferometers.itervalues().next().wts[cpol][0].astype(NP.complex64)
wtspos_xy = wtspos_xy[NP.abs(wts) >= wts_tol, :]
wts = wts[NP.abs(wts) >= wts_tol]
n_wts = wts.size
reflocs_xy = bl_xy[:,NP.newaxis,:] + wtspos_xy[NP.newaxis,:,:] # n_bl x n_wts x 2
refwts = wts.reshape(1,-1) * NP.ones((n_bl,1)) # n_bl x n_wts
else:
for i,label in enumerate(self.ordered_labels):
bl_wtspos = self.interferometers[label].wtspos[cpol][0]
bl_wts = self.interferometers[label].wts[cpol][0].astype(NP.complex64)
if i == 0:
wtspos = bl_wtspos[NP.newaxis,:,:] # 1 x n_wts x 2
refwts = bl_wts.reshape(1,-1) # 1 x n_wts
else:
wtspos = NP.vstack((wtspos, bl_wtspos[NP.newaxis,:,:])) # n_bl x n_wts x 2
refwts = NP.vstack((refwts, bl_wts.reshape(1,-1))) # n_bl x n_wts
reflocs_xy = bl_xy[:,NP.newaxis,:] + wtspos * FCNST.c/self.f[0] # n_bl x n_wts x 2
reflocs_xy = reflocs_xy.reshape(-1,bl_xy.shape[1]) # (n_bl x n_wts) x 2
refwts = refwts.ravel()
self.grid_mapper[cpol]['refwts'] = NP.copy(refwts.ravel()) # (n_bl x n_wts)
else: # Weights do not scale with frequency (needs serious development)
pass
gridlocs = NP.hstack((self.gridu.reshape(-1,1), self.gridv.reshape(-1,1)))
contributed_bl_grid_Vf = None
if parallel: # Use parallelization over frequency to determine gridding convolution
if nproc is None:
nproc = max(MP.cpu_count()-1, 1)
else:
nproc = min(nproc, max(MP.cpu_count()-1, 1))
if pp_method == 'queue': ## Use MP.Queue(): useful for memory intensive parallelizing but can be slow
job_chunk_begin = range(0,self.f.size,nproc)
if verbose:
progress = PGB.ProgressBar(widgets=[PGB.Percentage(), PGB.Bar(marker='-', left=' |', right='| '), PGB.Counter(), '/{0:0d} job chunks '.format(len(job_chunk_begin)), PGB.ETA()], maxval=len(job_chunk_begin)).start()
for ijob, job_start in enumerate(job_chunk_begin):
pjobs = []
out_q = MP.Queue()
for job_ind in xrange(job_start, min(job_start+nproc, self.f.size)): # Start the processes and store outputs in the queue
if mapping == 'weighted':
pjob = MP.Process(target=LKP.find_1NN_pp, args=(gridlocs, reflocs_xy * self.f[job_ind]/FCNST.c, job_ind, out_q, distNN*self.f.max()/FCNST.c, True), name='process-{0:0d}-channel-{1:0d}'.format(job_ind-job_start, job_ind))
else:
pjob = MP.Process(target=LKP.find_1NN_pp, args=(reflocs_xy * self.f[job_ind]/FCNST.c, gridlocs, job_ind, out_q, distNN*self.f.max()/FCNST.c, True), name='process-{0:0d}-channel-{1:0d}'.format(job_ind-job_start, job_ind))
pjob.start()
pjobs.append(pjob)
for p in xrange(len(pjobs)): # Unpack the queue output
outdict = out_q.get()
chan = outdict.keys()[0]
if mapping == 'weighted':
refind, gridind = outdict[chan]['inpind'], outdict[chan]['refind']
else:
gridind, refind = outdict[chan]['inpind'], outdict[chan]['refind']
self.grid_mapper[cpol]['refind'] += [refind]
self.grid_mapper[cpol]['gridind'] += [gridind]
bl_ind, lkp_ind = NP.unravel_index(refind, (n_bl, n_wts))
self.grid_mapper[cpol]['bl']['ind_freq'] += [bl_ind]
gridind_unraveled = NP.unravel_index(gridind, self.gridu.shape) + (chan+NP.zeros(gridind.size,dtype=int),)
gridind_raveled = NP.ravel_multi_index(gridind_unraveled, self.gridu.shape+(self.f.size,))
if self.grid_mapper[cpol]['bl']['ind_all'] is None:
self.grid_mapper[cpol]['bl']['ind_all'] = NP.copy(bl_ind)
self.grid_mapper[cpol]['bl']['illumination'] = refwts[refind]
contributed_bl_grid_Vf = refwts[refind] * Vf[bl_ind,chan]
self.grid_mapper[cpol]['grid']['ind_all'] = NP.copy(gridind_raveled)
else:
self.grid_mapper[cpol]['bl']['ind_all'] = NP.append(self.grid_mapper[cpol]['bl']['ind_all'], bl_ind)
self.grid_mapper[cpol]['bl']['illumination'] = NP.append(self.grid_mapper[cpol]['bl']['illumination'], refwts[refind])
contributed_bl_grid_Vf = NP.append(contributed_bl_grid_Vf, refwts[refind] * Vf[bl_ind,chan])
self.grid_mapper[cpol]['grid']['ind_all'] = NP.append(self.grid_mapper[cpol]['grid']['ind_all'], gridind_raveled)
for pjob in pjobs:
pjob.join()
del out_q
if verbose:
progress.update(ijob+1)
if verbose:
progress.finish()
elif pp_method == 'pool': ## Using MP.Pool.map(): Can be faster if parallelizing is not memory intensive
list_of_gridlocs = [gridlocs] * self.f.size
list_of_reflocs = [reflocs_xy * f/FCNST.c for f in self.f]
list_of_dist_NN = [distNN*self.f.max()/FCNST.c] * self.f.size
list_of_remove_oob = [True] * self.f.size
pool = MP.Pool(processes=nproc)
if mapping == 'weighted':
list_of_NNout = pool.map(find_1NN_arg_splitter, IT.izip(list_of_gridlocs, list_of_reflocs, list_of_dist_NN, list_of_remove_oob))
else:
list_of_NNout = pool.map(find_1NN_arg_splitter, IT.izip(list_of_reflocs, list_of_gridlocs, list_of_dist_NN, list_of_remove_oob))
pool.close()
pool.join()
for chan, NNout in enumerate(list_of_NNout): # Unpack the pool output
if mapping == 'weighted':
refind, gridind = NNout[0], NNout[1]
else:
gridind, refind = NNout[0], NNout[1]
self.grid_mapper[cpol]['refind'] += [refind]
self.grid_mapper[cpol]['gridind'] += [gridind]
bl_ind, lkp_ind = NP.unravel_index(refind, (n_bl, n_wts))
self.grid_mapper[cpol]['bl']['ind_freq'] += [bl_ind]
gridind_unraveled = NP.unravel_index(gridind, self.gridu.shape) + (chan+NP.zeros(gridind.size,dtype=int),)
gridind_raveled = NP.ravel_multi_index(gridind_unraveled, self.gridu.shape+(self.f.size,))
if chan == 0:
self.grid_mapper[cpol]['bl']['ind_all'] = NP.copy(bl_ind)
self.grid_mapper[cpol]['bl']['illumination'] = refwts[refind]
contributed_bl_grid_Vf = refwts[refind] * Vf[bl_ind,chan]
self.grid_mapper[cpol]['grid']['ind_all'] = NP.copy(gridind_raveled)
else:
self.grid_mapper[cpol]['bl']['ind_all'] = NP.append(self.grid_mapper[cpol]['bl']['ind_all'], bl_ind)
self.grid_mapper[cpol]['bl']['illumination'] = NP.append(self.grid_mapper[cpol]['bl']['illumination'], refwts[refind])
contributed_bl_grid_Vf = NP.append(contributed_bl_grid_Vf, refwts[refind] * Vf[bl_ind,chan])
self.grid_mapper[cpol]['grid']['ind_all'] = NP.append(self.grid_mapper[cpol]['grid']['ind_all'], gridind_raveled)
else:
raise ValueError('Parallel processing method specified by input parameter ppmethod has to be "pool" or "queue"')
else: # Use serial processing over frequency to determine gridding convolution
if verbose:
progress = PGB.ProgressBar(widgets=[PGB.Percentage(), PGB.Bar(marker='-', left=' |', right='| '), PGB.Counter(), '/{0:0d} Frequency channels '.format(self.f.size), PGB.ETA()], maxval=self.f.size).start()
for i in xrange(self.f.size):
if mapping == 'weighted':
refind, gridind = LKP.find_1NN(gridlocs, reflocs_xy * self.f[i]/FCNST.c,
distance_ULIM=distNN*self.f.max()/FCNST.c,
remove_oob=True)[:2]
else:
gridind, refind = LKP.find_1NN(reflocs_xy * self.f[i]/FCNST.c, gridlocs,
distance_ULIM=distNN*self.f.max()/FCNST.c,
remove_oob=True)[:2]
self.grid_mapper[cpol]['refind'] += [refind]
self.grid_mapper[cpol]['gridind'] += [gridind]
bl_ind, lkp_ind = NP.unravel_index(refind, (n_bl, n_wts))
self.grid_mapper[cpol]['bl']['ind_freq'] += [bl_ind]
gridind_unraveled = NP.unravel_index(gridind, self.gridu.shape) + (i+NP.zeros(gridind.size,dtype=int),)
gridind_raveled = NP.ravel_multi_index(gridind_unraveled, self.gridu.shape+(self.f.size,))
if i == 0:
self.grid_mapper[cpol]['bl']['ind_all'] = NP.copy(bl_ind)
self.grid_mapper[cpol]['bl']['illumination'] = refwts[refind]
contributed_bl_grid_Vf = refwts[refind] * Vf[bl_ind,i]
self.grid_mapper[cpol]['grid']['ind_all'] = NP.copy(gridind_raveled)
else:
self.grid_mapper[cpol]['bl']['ind_all'] = NP.append(self.grid_mapper[cpol]['bl']['ind_all'], bl_ind)
self.grid_mapper[cpol]['bl']['illumination'] = NP.append(self.grid_mapper[cpol]['bl']['illumination'], refwts[refind])
contributed_bl_grid_Vf = NP.append(contributed_bl_grid_Vf, refwts[refind] * Vf[bl_ind,i])
self.grid_mapper[cpol]['grid']['ind_all'] = NP.append(self.grid_mapper[cpol]['grid']['ind_all'], gridind_raveled)
if verbose:
progress.update(i+1)
if verbose:
progress.finish()
self.grid_mapper[cpol]['bl']['uniq_ind_all'] = NP.unique(self.grid_mapper[cpol]['bl']['ind_all'])
self.grid_mapper[cpol]['bl']['rev_ind_all'] = OPS.binned_statistic(self.grid_mapper[cpol]['bl']['ind_all'], statistic='count', bins=NP.append(self.grid_mapper[cpol]['bl']['uniq_ind_all'], self.grid_mapper[cpol]['bl']['uniq_ind_all'].max()+1))[3]
if parallel and (mapping == 'weighted'): # Use parallel processing over baselines to determine baseline-grid mapping of gridded aperture illumination and visibilities
if nproc is None:
nproc = max(MP.cpu_count()-1, 1)
else:
nproc = min(nproc, max(MP.cpu_count()-1, 1))
if pp_method == 'queue': ## Use MP.Queue(): useful for memory intensive parallelizing but can be slow
num_bl = self.grid_mapper[cpol]['bl']['uniq_ind_all'].size
job_chunk_begin = range(0,num_bl,nproc)
if verbose:
progress = PGB.ProgressBar(widgets=[PGB.Percentage(), PGB.Bar(marker='-', left=' |', right='| '), PGB.Counter(), '/{0:0d} job chunks '.format(len(job_chunk_begin)), PGB.ETA()], maxval=len(job_chunk_begin)).start()
for ijob, job_start in enumerate(job_chunk_begin):
pjobs1 = []
pjobs2 = []
out_q1 = MP.Queue()
out_q2 = MP.Queue()
for job_ind in xrange(job_start, min(job_start+nproc, num_bl)): # Start the parallel processes and store the output in the queue
label = self.ordered_labels[self.grid_mapper[cpol]['bl']['uniq_ind_all'][job_ind]]
if self.grid_mapper[cpol]['bl']['rev_ind_all'][job_ind] < self.grid_mapper[cpol]['bl']['rev_ind_all'][job_ind+1]:
self.grid_mapper[cpol]['labels'][label] = {}
self.grid_mapper[cpol]['labels'][label]['twts'] = twts[bl_labels.index(label)]
# self.grid_mapper[cpol]['labels'][label]['flag'] = self.interferometers[label].crosspol.flag[cpol]
select_bl_ind = self.grid_mapper[cpol]['bl']['rev_ind_all'][self.grid_mapper[cpol]['bl']['rev_ind_all'][job_ind]:self.grid_mapper[cpol]['bl']['rev_ind_all'][job_ind+1]]
gridind_raveled_around_bl = self.grid_mapper[cpol]['grid']['ind_all'][select_bl_ind]
uniq_gridind_raveled_around_bl = NP.unique(gridind_raveled_around_bl)
self.grid_mapper[cpol]['labels'][label]['gridind'] = uniq_gridind_raveled_around_bl
pjob1 = MP.Process(target=baseline_grid_mapper, args=(gridind_raveled_around_bl, contributed_bl_grid_Vf[select_bl_ind], NP.append(uniq_gridind_raveled_around_bl, uniq_gridind_raveled_around_bl.max()+1), label, out_q1), name='process-{0:0d}-{1}-visibility'.format(job_ind, label))
pjob2 = MP.Process(target=baseline_grid_mapper, args=(gridind_raveled_around_bl, self.grid_mapper[cpol]['bl']['illumination'][select_bl_ind], NP.append(uniq_gridind_raveled_around_bl, uniq_gridind_raveled_around_bl.max()+1), label, out_q2), name='process-{0:0d}-{1}-illumination'.format(job_ind, label))
pjob1.start()
pjob2.start()
pjobs1.append(pjob1)
pjobs2.append(pjob2)
for p in xrange(len(pjobs1)): # Unpack the gridded visibility and aperture illumination information from the pool output
outdict = out_q1.get()
label = outdict.keys()[0]
self.grid_mapper[cpol]['labels'][label]['Vf'] = outdict[label]
outdict = out_q2.get()
label = outdict.keys()[0]
self.grid_mapper[cpol]['labels'][label]['illumination'] = outdict[label]
for pjob in pjobs1:
pjob1.join()
for pjob in pjobs2:
pjob2.join()
del out_q1, out_q2
if verbose:
progress.update(ijob+1)
if verbose:
progress.finish()
elif pp_method == 'pool': ## Using MP.Pool.map(): Can be faster if parallelizing is not memory intensive
list_of_gridind_raveled_around_bl = []
list_of_bl_grid_values = []
list_of_bl_Vf_contribution = []
list_of_bl_illumination = []
list_of_uniq_gridind_raveled_around_bl = []
list_of_bl_labels = []
for j in xrange(self.grid_mapper[cpol]['bl']['uniq_ind_all'].size): # re-determine gridded visibilities due to each baseline
label = self.ordered_labels[self.grid_mapper[cpol]['bl']['uniq_ind_all'][j]]
if self.grid_mapper[cpol]['bl']['rev_ind_all'][j] < self.grid_mapper[cpol]['bl']['rev_ind_all'][j+1]:
self.grid_mapper[cpol]['labels'][label] = {}
self.grid_mapper[cpol]['labels'][label]['twts'] = twts[bl_labels.index(label)]
# self.grid_mapper[cpol]['labels'][label]['flag'] = self.interferometers[label].crosspol.flag[cpol]
select_bl_ind = self.grid_mapper[cpol]['bl']['rev_ind_all'][self.grid_mapper[cpol]['bl']['rev_ind_all'][j]:self.grid_mapper[cpol]['bl']['rev_ind_all'][j+1]]
gridind_raveled_around_bl = self.grid_mapper[cpol]['grid']['ind_all'][select_bl_ind]
uniq_gridind_raveled_around_bl = NP.unique(gridind_raveled_around_bl)
self.grid_mapper[cpol]['labels'][label]['gridind'] = uniq_gridind_raveled_around_bl
list_of_bl_labels += [label]
list_of_gridind_raveled_around_bl += [gridind_raveled_around_bl]
list_of_uniq_gridind_raveled_around_bl += [NP.append(uniq_gridind_raveled_around_bl, uniq_gridind_raveled_around_bl.max()+1)]
list_of_bl_Vf_contribution += [contributed_bl_grid_Vf[select_bl_ind]]
list_of_bl_illumination += [self.grid_mapper[cpol]['bl']['illumination'][select_bl_ind]]
pool = MP.Pool(processes=nproc)
list_of_bl_grid_values = pool.map(baseline_grid_mapping_arg_splitter, IT.izip(list_of_gridind_raveled_around_bl, list_of_bl_Vf_contribution, list_of_uniq_gridind_raveled_around_bl))
pool.close()
pool.join()
for label,grid_values in IT.izip(list_of_bl_labels, list_of_bl_grid_values): # Unpack the gridded visibility information from the pool output
self.grid_mapper[cpol]['labels'][label]['Vf'] = grid_values
if nproc is not None:
pool = MP.Pool(processes=nproc)
else:
pool = MP.Pool()
list_of_bl_grid_values = pool.map(baseline_grid_mapping_arg_splitter, IT.izip(list_of_gridind_raveled_around_bl, list_of_bl_illumination, list_of_uniq_gridind_raveled_around_bl))
pool.close()
pool.join()
for label,grid_values in IT.izip(list_of_bl_labels, list_of_bl_grid_values): # Unpack the gridded visibility and aperture illumination information from the pool output
self.grid_mapper[cpol]['labels'][label]['illumination'] = grid_values
del list_of_bl_grid_values, list_of_gridind_raveled_around_bl, list_of_bl_Vf_contribution, list_of_bl_illumination, list_of_uniq_gridind_raveled_around_bl, list_of_bl_labels
else:
raise ValueError('Parallel processing method specified by input parameter ppmethod has to be "pool" or "queue"')
else: # Use serial processing over baselines to determine baseline-grid mapping of gridded aperture illumination and visibilities
if verbose:
progress = PGB.ProgressBar(widgets=[PGB.Percentage(), PGB.Bar(marker='-', left=' |', right='| '), PGB.Counter(), '/{0:0d} Baselines '.format(self.grid_mapper[cpol]['bl']['uniq_ind_all'].size), PGB.ETA()], maxval=self.grid_mapper[cpol]['bl']['uniq_ind_all'].size).start()
for j in xrange(self.grid_mapper[cpol]['bl']['uniq_ind_all'].size):
label = self.ordered_labels[self.grid_mapper[cpol]['bl']['uniq_ind_all'][j]]
if self.grid_mapper[cpol]['bl']['rev_ind_all'][j] < self.grid_mapper[cpol]['bl']['rev_ind_all'][j+1]:
select_bl_ind = self.grid_mapper[cpol]['bl']['rev_ind_all'][self.grid_mapper[cpol]['bl']['rev_ind_all'][j]:self.grid_mapper[cpol]['bl']['rev_ind_all'][j+1]]
self.grid_mapper[cpol]['labels'][label] = {}
self.grid_mapper[cpol]['labels'][label]['twts'] = twts[bl_labels.index(label)]
# self.grid_mapper[cpol]['labels'][label]['flag'] = self.interferometers[label].crosspol.flag[cpol]
if mapping == 'weighted':
gridind_raveled_around_bl = self.grid_mapper[cpol]['grid']['ind_all'][select_bl_ind]
uniq_gridind_raveled_around_bl = NP.unique(gridind_raveled_around_bl)
self.grid_mapper[cpol]['labels'][label]['gridind'] = uniq_gridind_raveled_around_bl
self.grid_mapper[cpol]['labels'][label]['Vf'] = OPS.binned_statistic(gridind_raveled_around_bl, contributed_bl_grid_Vf[select_bl_ind].real, statistic='sum', bins=NP.append(uniq_gridind_raveled_around_bl, uniq_gridind_raveled_around_bl.max()+1))[0]
self.grid_mapper[cpol]['labels'][label]['Vf'] = self.grid_mapper[cpol]['labels'][label]['Vf'].astype(NP.complex64)
self.grid_mapper[cpol]['labels'][label]['Vf'] += 1j * OPS.binned_statistic(gridind_raveled_around_bl, contributed_bl_grid_Vf[select_bl_ind].imag, statistic='sum', bins=NP.append(uniq_gridind_raveled_around_bl, uniq_gridind_raveled_around_bl.max()+1))[0]
self.grid_mapper[cpol]['labels'][label]['illumination'] = OPS.binned_statistic(gridind_raveled_around_bl, self.grid_mapper[cpol]['bl']['illumination'][select_bl_ind].real, statistic='sum', bins=NP.append(uniq_gridind_raveled_around_bl, uniq_gridind_raveled_around_bl.max()+1))[0]
self.grid_mapper[cpol]['labels'][label]['illumination'] = self.grid_mapper[cpol]['labels'][label]['illumination'].astype(NP.complex64)
self.grid_mapper[cpol]['labels'][label]['illumination'] += 1j * OPS.binned_statistic(gridind_raveled_around_bl, self.grid_mapper[cpol]['bl']['illumination'][select_bl_ind].imag, statistic='sum', bins=NP.append(uniq_gridind_raveled_around_bl, uniq_gridind_raveled_around_bl.max()+1))[0]
else:
self.grid_mapper[cpol]['labels'][label]['gridind'] = self.grid_mapper[cpol]['grid']['ind_all'][select_bl_ind]
self.grid_mapper[cpol]['labels'][label]['Vf'] = contributed_bl_grid_Vf[select_bl_ind]
self.grid_mapper[cpol]['labels'][label]['illumination'] = self.grid_mapper[cpol]['bl']['illumination'][select_bl_ind]
if verbose:
progress.update(j+1)
if verbose:
progress.finish()
else: # Only re-determine gridded visibilities
if verbose:
progress = PGB.ProgressBar(widgets=[PGB.Percentage(), PGB.Bar(marker='-', left=' |', right='| '), PGB.Counter(), '/{0:0d} Frequency channels '.format(self.f.size), PGB.ETA()], maxval=self.f.size).start()
for i in xrange(self.f.size): # Only re-estimate visibilities contributed by baselines
bl_refwts = self.grid_mapper[cpol]['refwts'][self.grid_mapper[cpol]['refind'][i]]
bl_Vf = Vf[self.grid_mapper[cpol]['bl']['ind_freq'][i],i]
if i == 0:
contributed_bl_grid_Vf = bl_refwts * bl_Vf
else:
contributed_bl_grid_Vf = NP.append(contributed_bl_grid_Vf, bl_refwts * bl_Vf)
if verbose:
progress.update(i+1)
if verbose:
progress.finish()
if parallel and (mapping == 'weighted'): # Use parallel processing
if nproc is None:
nproc = max(MP.cpu_count()-1, 1)
else:
nproc = min(nproc, max(MP.cpu_count()-1, 1))
if pp_method == 'queue': ## Use MP.Queue(): useful for memory intensive parallelizing but can be slow
num_bl = self.grid_mapper[cpol]['bl']['uniq_ind_all'].size
job_chunk_begin = range(0,num_bl,nproc)
if verbose:
progress = PGB.ProgressBar(widgets=[PGB.Percentage(), PGB.Bar(marker='-', left=' |', right='| '), PGB.Counter(), '/{0:0d} job chunks '.format(len(job_chunk_begin)), PGB.ETA()], maxval=len(job_chunk_begin)).start()
for ijob, job_start in enumerate(job_chunk_begin):
pjobs = []
out_q = MP.Queue()
for job_ind in xrange(job_start, min(job_start+nproc, num_bl)): # Start the parallel processes and store the outputs in a queue
label = self.ordered_labels[self.grid_mapper[cpol]['bl']['uniq_ind_all'][job_ind]]
self.grid_mapper[cpol]['labels'][label]['twts'] = twts[bl_labels.index(label)]
if self.grid_mapper[cpol]['bl']['rev_ind_all'][job_ind] < self.grid_mapper[cpol]['bl']['rev_ind_all'][job_ind+1]:
select_bl_ind = self.grid_mapper[cpol]['bl']['rev_ind_all'][self.grid_mapper[cpol]['bl']['rev_ind_all'][job_ind]:self.grid_mapper[cpol]['bl']['rev_ind_all'][job_ind+1]]
gridind_raveled_around_bl = self.grid_mapper[cpol]['grid']['ind_all'][select_bl_ind]
uniq_gridind_raveled_around_bl = self.grid_mapper[cpol]['labels'][label]['gridind']
pjob = MP.Process(target=baseline_grid_mapper, args=(gridind_raveled_around_bl, contributed_bl_grid_Vf[select_bl_ind], NP.append(uniq_gridind_raveled_around_bl, uniq_gridind_raveled_around_bl.max()+1), label, out_q), name='process-{0:0d}-{1}-visibility'.format(job_ind, label))
pjob.start()
pjobs.append(pjob)
for p in xrange(len(pjobs)): # Unpack the gridded visibility information from the queue
outdict = out_q.get()
label = outdict.keys()[0]
self.grid_mapper[cpol]['labels'][label]['Vf'] = outdict[label]
for pjob in pjobs:
pjob.join()
del out_q
if verbose:
progress.update(ijob+1)
if verbose:
progress.finish()
else: ## Use MP.Pool.map(): Can be faster if parallelizing is not memory intensive
list_of_gridind_raveled_around_bl = []
list_of_bl_Vf_contribution = []
list_of_uniq_gridind_raveled_around_bl = []
list_of_bl_labels = []
for j in xrange(self.grid_mapper[cpol]['bl']['uniq_ind_all'].size): # re-determine gridded visibilities due to each baseline
if self.grid_mapper[cpol]['bl']['rev_ind_all'][j] < self.grid_mapper[cpol]['bl']['rev_ind_all'][j+1]:
select_bl_ind = self.grid_mapper[cpol]['bl']['rev_ind_all'][self.grid_mapper[cpol]['bl']['rev_ind_all'][j]:self.grid_mapper[cpol]['bl']['rev_ind_all'][j+1]]
label = self.ordered_labels[self.grid_mapper[cpol]['bl']['uniq_ind_all'][j]]
self.grid_mapper[cpol]['labels'][label]['twts'] = twts[bl_labels.index(label)]
gridind_raveled_around_bl = self.grid_mapper[cpol]['grid']['ind_all'][select_bl_ind]
uniq_gridind_raveled_around_bl = NP.unique(gridind_raveled_around_bl)
list_of_bl_labels += [label]
list_of_gridind_raveled_around_bl += [gridind_raveled_around_bl]
list_of_uniq_gridind_raveled_around_bl += [NP.append(uniq_gridind_raveled_around_bl, uniq_gridind_raveled_around_bl.max()+1)]
list_of_bl_Vf_contribution += [contributed_bl_grid_Vf[select_bl_ind]]
if nproc is None:
nproc = max(MP.cpu_count()-1, 1)
else:
nproc = min(nproc, max(MP.cpu_count()-1, 1))
pool = MP.Pool(processes=nproc)
list_of_grid_Vf = pool.map(baseline_grid_mapping_arg_splitter, IT.izip(list_of_gridind_raveled_around_bl, list_of_bl_Vf_contribution, list_of_uniq_gridind_raveled_around_bl))
pool.close()
pool.join()
for label,grid_Vf in IT.izip(list_of_bl_labels, list_of_grid_Vf): # Unpack the gridded visibility information from the pool output
self.grid_mapper[cpol]['labels'][label]['Vf'] = grid_Vf
del list_of_gridind_raveled_around_bl, list_of_grid_Vf, list_of_bl_Vf_contribution, list_of_uniq_gridind_raveled_around_bl, list_of_bl_labels
else: # use serial processing
if verbose:
progress = PGB.ProgressBar(widgets=[PGB.Percentage(), PGB.Bar(marker='-', left=' |', right='| '), PGB.Counter(), '/{0:0d} Baselines '.format(self.grid_mapper[cpol]['bl']['uniq_ind_all'].size), PGB.ETA()], maxval=self.grid_mapper[cpol]['bl']['uniq_ind_all'].size).start()
for j in xrange(self.grid_mapper[cpol]['bl']['uniq_ind_all'].size): # re-determine gridded visibilities due to each baseline
if self.grid_mapper[cpol]['bl']['rev_ind_all'][j] < self.grid_mapper[cpol]['bl']['rev_ind_all'][j+1]:
select_bl_ind = self.grid_mapper[cpol]['bl']['rev_ind_all'][self.grid_mapper[cpol]['bl']['rev_ind_all'][j]:self.grid_mapper[cpol]['bl']['rev_ind_all'][j+1]]
label = self.ordered_labels[self.grid_mapper[cpol]['bl']['uniq_ind_all'][j]]
self.grid_mapper[cpol]['labels'][label]['twts'] = twts[bl_labels.index(label)]
self.grid_mapper[cpol]['labels'][label]['Vf'] = {}
if mapping == 'weighted':
gridind_raveled_around_bl = self.grid_mapper[cpol]['grid']['ind_all'][select_bl_ind]
uniq_gridind_raveled_around_bl = self.grid_mapper[cpol]['labels'][label]['gridind']
# uniq_gridind_raveled_around_bl = NP.unique(gridind_raveled_around_bl)
self.grid_mapper[cpol]['labels'][label]['Vf'] = OPS.binned_statistic(gridind_raveled_around_bl, contributed_bl_grid_Vf[select_bl_ind].real, statistic='sum', bins=NP.append(uniq_gridind_raveled_around_bl, uniq_gridind_raveled_around_bl.max()+1))[0]
self.grid_mapper[cpol]['labels'][label]['Vf'] = self.grid_mapper[cpol]['labels'][label]['Vf'].astype(NP.complex64)
self.grid_mapper[cpol]['labels'][label]['Vf'] += 1j * OPS.binned_statistic(gridind_raveled_around_bl, contributed_bl_grid_Vf[select_bl_ind].imag, statistic='sum', bins=NP.append(uniq_gridind_raveled_around_bl, uniq_gridind_raveled_around_bl.max()+1))[0]
else:
self.grid_mapper[cpol]['labels'][label]['Vf'] = contributed_bl_grid_Vf[select_bl_ind]
if verbose:
progress.update(j+1)
if verbose:
progress.finish()
############################################################################
def grid_convolve_new(self, pol=None, normalize=False, method='NN',
distNN=NP.inf, identical_interferometers=True,
cal_loop=False, gridfunc_freq=None, wts_change=False,
parallel=False, nproc=None, pp_method='pool',
verbose=True):
"""
------------------------------------------------------------------------
Routine to project the complex illumination power pattern and the
visibilities on the grid from the interferometer array
Inputs:
pol [String] The polarization to be gridded. Can be set to 'P1'
or 'P2'. If set to None, gridding for all the polarizations
is performed. Default = None
normalize [Boolean] Default = False. If set to True, the gridded
weights are divided by the sum of weights so that the gridded
weights add up to unity. (Need to work on normaliation)
method [string] The gridding method to be used in applying the
interferometer weights on to the interferometer array grid.
Accepted values are 'NN' (nearest neighbour - default), 'CS'
(cubic spline), or 'BL' (Bi-linear). In case of applying grid
weights by 'NN' method, an optional distance upper bound for
the nearest neighbour can be provided in the parameter distNN
to prune the search and make it efficient. Currently, only
the nearest neighbour method is operational.
distNN [scalar] A positive value indicating the upper bound on
distance to the nearest neighbour in the gridding process. It
has units of distance, the same units as the interferometer
attribute location and interferometer array attribute gridx
and gridy. Default is NP.inf (infinite distance). It will be
internally converted to have same units as interferometer
attributes wtspos (units in number of wavelengths). To ensure
all relevant pixels in the grid, the search distance used
internally will be a fraction more than distNN
identical_interferometers
[boolean] indicates if all interferometer elements are to be
treated as identical. If True (default), they are identical
and their gridding kernels are identical. If False, they are
not identical and each one has its own gridding kernel.
cal_loop [boolean] If True, the calibration loop is assumed to be ON
and hence the calibrated electric fields are set in the
calibration loop. If False (default), the calibration loop is
assumed to be OFF and the current electric fields are assumed
to be the calibrated data to be mapped to the grid
via gridding convolution.
gridfunc_freq
[String scalar] If set to None (not provided) or to 'scale'
assumes that attribute wtspos is given for a
reference frequency which need to be scaled for the frequency
channels. Will be ignored if the number of elements of list
in this attribute under the specific polarization are the
same as the number of frequency channels.
wts_change [boolean] indicates if weights and/or their lcoations have
changed from the previous intergration or snapshot.
Default=False means they have not changed. In such a case the
interferometer-to-grid mapping and grid illumination pattern do not
have to be determined, and mapping and values from the
previous snapshot can be used. If True, a new mapping has to
be determined.
parallel [boolean] specifies if parallelization is to be invoked.
False (default) means only serial processing
nproc [integer] specifies number of independent processes to spawn.
Default = None, means automatically determines the number of
process cores in the system and use one less than that to
avoid locking the system for other processes. Applies only
if input parameter 'parallel' (see above) is set to True.
If nproc is set to a value more than the number of process
cores in the system, it will be reset to number of process
cores in the system minus one to avoid locking the system out
for other processes
pp_method [string] specifies if the parallelization method is handled
automatically using multirocessing pool or managed manually
by individual processes and collecting results in a queue.
The former is specified by 'pool' (default) and the latter
by 'queue'. These are the two allowed values. The pool method
has easier bookkeeping and can be fast if the computations
not expected to be memory bound. The queue method is more
suited for memory bound processes but can be slower or
inefficient in terms of CPU management.
verbose [boolean] If True, prints diagnostic and progress messages.
If False (default), suppress printing such messages.
------------------------------------------------------------------------
"""
eps = 1.0e-10
if pol is None:
pol = ['P1', 'P2']
elif not isinstance(pol, list):
pol = [pol]
if not self.grid_ready:
self.grid()
du = self.gridu[0,1] - self.gridu[0,0]
dv = self.gridv[1,0] - self.gridv[0,0]
wavelength = FCNST.c / self.f
min_lambda = NP.abs(wavelength).min()
rmaxNN = 0.5 * NP.sqrt(du**2 + dv**2) * min_lambda
krn = {}
crosspol = ['P11', 'P12', 'P21', 'P22']
for cpol in crosspol:
krn[cpol] = None
if cpol in pol:
bl_dict = self.baseline_vectors(pol=cpol, flag=None, sort=True)
self.ordered_labels = bl_dict['labels']
bl_xy = bl_dict['baselines'][:,:2] # n_bl x 2
n_bl = bl_xy.shape[0]
Vf_dict = self.get_visibilities(cpol, flag=None, tselect=-1, fselect=None, bselect=None, datapool='avg', sort=True)
Vf = Vf_dict['visibilities'].astype(NP.complex64) # (n_ts=1) x n_bl x nchan
Vf = NP.squeeze(Vf, axis=0) # n_bl x nchan
if Vf.shape[0] != n_bl:
raise ValueError('Encountered unexpected behavior. Need to debug.')
bl_labels = Vf_dict['labels']
twts = Vf_dict['twts'] # (n_ts=1) x n_bl x (nchan=1)
twts = NP.squeeze(twts, axis=(0,2)) # n_bl
if verbose:
print 'Gathered interferometer data for gridding convolution for timestamp {0}'.format(self.timestamp)
if wts_change or (not self.grid_mapper[cpol]['all_bl2grid']):
self.grid_mapper[cpol]['per_bl2grid'] = []
self.grid_mapper[cpol]['all_bl2grid'] = {}
gridlocs = NP.hstack((self.gridu.reshape(-1,1), self.gridv.reshape(-1,1)))
if gridfunc_freq == 'scale':
grid_xy = gridlocs[NP.newaxis,:,:] * wavelength.reshape(-1,1,1) # nchan x nv x nu
wl = NP.ones(gridlocs.shape[0])[NP.newaxis,:] * wavelength.reshape(-1,1)
grid_xy = grid_xy.reshape(-1,2)
wl = wl.reshape(-1)
indNN_list, blind, fvu_gridind = LKP.find_NN(bl_xy, grid_xy, distance_ULIM=2.0*distNN, flatten=True, parallel=False)
dxy = grid_xy[fvu_gridind,:] - bl_xy[blind,:]
fvu_gridind_unraveled = NP.unravel_index(fvu_gridind, (self.f.size,)+self.gridu.shape) # f-v-u order since temporary grid was created as nchan x nv x nu
self.grid_mapper[cpol]['all_bl2grid']['blind'] = NP.copy(blind)
self.grid_mapper[cpol]['all_bl2grid']['u_gridind'] = NP.copy(fvu_gridind_unraveled[2])
self.grid_mapper[cpol]['all_bl2grid']['v_gridind'] = NP.copy(fvu_gridind_unraveled[1])
self.grid_mapper[cpol]['all_bl2grid']['f_gridind'] = NP.copy(fvu_gridind_unraveled[0])
self.grid_mapper[cpol]['all_bl2grid']['indNN_list'] = copy.deepcopy(indNN_list)
self.grid_mapper[cpol]['all_bl2grid']['twts'] = copy.deepcopy(twts)
if identical_interferometers:
arbitrary_interferometer_aperture = self.interferometers.itervalues().next().aperture
krn = arbitrary_interferometer_aperture.compute(dxy, wavelength=wl[fvu_gridind], pol=cpol, rmaxNN=rmaxNN, load_lookup=False)
else:
# This block #1 is one way to go about per interferometer
for bi,gi in enumerate(indNN_list):
if len(gi) > 0:
label = self.ordered_labels[bi]
ind = NP.asarray(gi)
diffxy = grid_xy[ind,:].reshape(-1,2) - bl_xy[bi,:].reshape(-1,2)
krndict = self.interferometers[label].aperture.compute(diffxy, wavelength=wl[ind], pol=cpol, rmaxNN=rmaxNN, load_lookup=False)
if krn[cpol] is None:
krn[cpol] = NP.copy(krndict[cpol])
else:
krn[cpol] = NP.append(krn[cpol], krndict[cpol])
# # This block #2 is another way equivalent to above block #1
# uniq_blind = NP.unique(blind)
# blhist, blbe, blbn, blri = OPS.binned_statistic(blind, statistic='count', bins=NP.append(uniq_blind, uniq_blind.max()+1))
# for i,ublind in enumerate(uniq_blind):
# label = self.ordered_labels[ublind]
# ind = blri[blri[i]:blri[i+1]]
# krndict = self.interferometers[label].aperture.compute(dxy[ind,:], wavelength=wl[ind], pol=cpol, rmaxNN=rmaxNN, load_lookup=False)
# if krn[cpol] is None:
# krn[cpol] = NP.copy(krndict[cpol])
# else:
# krn[cpol] = NP.append(krn[cpol], krndict[cpol])
self.grid_mapper[cpol]['all_bl2grid']['illumination'] = NP.copy(krn[cpol])
else: # Weights do not scale with frequency (needs serious development)
pass
# Determine weights that can normalize sum of kernel per interferometer per frequency to unity
# per_bl_per_freq_norm_wts = NP.ones(blind.size, dtype=NP.complex64)
per_bl_per_freq_norm_wts = NP.zeros(blind.size, dtype=NP.complex64)
runsum = 0
for bi,gi in enumerate(indNN_list):
if len(gi) > 0:
fvu_ind = NP.asarray(gi)
unraveled_fvu_ind = NP.unravel_index(fvu_ind, (self.f.size,)+self.gridu.shape)
f_ind = unraveled_fvu_ind[0]
v_ind = unraveled_fvu_ind[1]
u_ind = unraveled_fvu_ind[2]
chanhist, chanbe, chanbn, chanri = OPS.binned_statistic(f_ind, statistic='count', bins=NP.arange(self.f.size+1))
for ci in xrange(self.f.size):
if chanhist[ci] > 0.0:
select_chan_ind = chanri[chanri[ci]:chanri[ci+1]]
per_bl_per_freq_kernel_sum = NP.sum(krn[cpol][runsum:runsum+len(gi)][select_chan_ind])
per_bl_per_freq_norm_wts[runsum:runsum+len(gi)][select_chan_ind] = 1.0 / per_bl_per_freq_kernel_sum
per_bl2grid_info = {}
per_bl2grid_info['label'] = self.ordered_labels[bi]
per_bl2grid_info['twts'] = twts[bi]
per_bl2grid_info['f_gridind'] = NP.copy(f_ind)
per_bl2grid_info['u_gridind'] = NP.copy(u_ind)
per_bl2grid_info['v_gridind'] = NP.copy(v_ind)
# per_bl2grid_info['fvu_gridind'] = NP.copy(gi)
per_bl2grid_info['per_bl_per_freq_norm_wts'] = per_bl_per_freq_norm_wts[runsum:runsum+len(gi)]
per_bl2grid_info['illumination'] = krn[cpol][runsum:runsum+len(gi)]
self.grid_mapper[cpol]['per_bl2grid'] += [copy.deepcopy(per_bl2grid_info)]
runsum += len(gi)
self.grid_mapper[cpol]['all_bl2grid']['per_bl_per_freq_norm_wts'] = NP.copy(per_bl_per_freq_norm_wts)
# Determine the gridded electric fields
Vf_on_grid = Vf[(self.grid_mapper[cpol]['all_bl2grid']['blind'], self.grid_mapper[cpol]['all_bl2grid']['f_gridind'])]
self.grid_mapper[cpol]['all_bl2grid']['Vf'] = copy.deepcopy(Vf_on_grid)
runsum = 0
for bi,gi in enumerate(self.grid_mapper[cpol]['all_bl2grid']['indNN_list']):
if len(gi) > 0:
self.grid_mapper[cpol]['per_bl2grid'][bi]['Vf'] = Vf_on_grid[runsum:runsum+len(gi)]
runsum += len(gi)
############################################################################
def genMappingMatrix(self, pol=None, normalize=True, method='NN',
distNN=NP.inf, identical_interferometers=True,
gridfunc_freq=None, wts_change=False, parallel=False,
nproc=None, verbose=True):
"""
------------------------------------------------------------------------
Routine to construct sparse interferometer-to-grid mapping matrix that
will be used in projecting illumination and visibilities from the
array of interferometers onto the grid. It has elements very common to
grid_convolve_new()
Inputs:
pol [String] The polarization to be gridded. Can be set to 'P11',
'P12', 'P21', or 'P2'. If set to None, gridding for all the
polarizations is performed. Default = None
normalize [Boolean] Default = False. If set to True, the gridded
weights are divided by the sum of weights so that the gridded
weights add up to unity. (Need to work on normaliation)
method [string] The gridding method to be used in applying the
interferometer weights on to the interferometer array grid.
Accepted values are 'NN' (nearest neighbour - default), 'CS'
(cubic spline), or 'BL' (Bi-linear). In case of applying grid
weights by 'NN' method, an optional distance upper bound for
the nearest neighbour can be provided in the parameter distNN
to prune the search and make it efficient. Currently, only
the nearest neighbour method is operational.
distNN [scalar] A positive value indicating the upper bound on
distance to the nearest neighbour in the gridding process. It
has units of distance, the same units as the interferometer
attribute location and interferometer array attribute gridx
and gridy. Default is NP.inf (infinite distance). It will be
internally converted to have same units as interferometer
attributes wtspos (units in number of wavelengths). To ensure
all relevant pixels in the grid, the search distance used
internally will be a fraction more than distNN
identical_interferometers
[boolean] indicates if all interferometer elements are to be
treated as identical. If True (default), they are identical
and their gridding kernels are identical. If False, they are
not identical and each one has its own gridding kernel.
gridfunc_freq
[String scalar] If set to None (not provided) or to 'scale'
assumes that attribute wtspos is given for a
reference frequency which need to be scaled for the frequency
channels. Will be ignored if the number of elements of list
in this attribute under the specific polarization are the
same as the number of frequency channels.
wts_change [boolean] indicates if weights and/or their lcoations have
changed from the previous intergration or snapshot.
Default=False means they have not changed. In such a case the
interferometer-to-grid mapping and grid illumination pattern
do not have to be determined, and mapping and values from the
previous snapshot can be used. If True, a new mapping has to
be determined.
parallel [boolean] specifies if parallelization is to be invoked.
False (default) means only serial processing
nproc [integer] specifies number of independent processes to spawn.
Default = None, means automatically determines the number of
process cores in the system and use one less than that to
avoid locking the system for other processes. Applies only
if input parameter 'parallel' (see above) is set to True.
If nproc is set to a value more than the number of process
cores in the system, it will be reset to number of process
cores in the system minus one to avoid locking the system out
for other processes
verbose [boolean] If True, prints diagnostic and progress messages.
If False (default), suppress printing such messages.
NOTE: Although certain portions are parallelizable, the overheads in
these processes seem to make it worse than serial processing. It is
advisable to stick to serialized version unless testing with larger
data sets clearly indicates otherwise.
------------------------------------------------------------------------
"""
if pol is None:
pol = ['P1', 'P2']
elif not isinstance(pol, list):
pol = [pol]
if not self.grid_ready:
self.grid()
du = self.gridu[0,1] - self.gridu[0,0]
dv = self.gridv[1,0] - self.gridv[0,0]
wavelength = FCNST.c / self.f
min_lambda = NP.abs(wavelength).min()
rmaxNN = 0.5 * NP.sqrt(du**2 + dv**2) * min_lambda
krn = {}
self.bl2grid_mapper = {}
crosspol = ['P11', 'P12', 'P21', 'P22']
for cpol in crosspol:
krn[cpol] = None
self.bl2grid_mapper[cpol] = None
if cpol in pol:
bl_dict = self.baseline_vectors(pol=cpol, flag=None, sort=True)
self.ordered_labels = bl_dict['labels']
bl_xy = bl_dict['baselines'][:,:2] # n_bl x 2
n_bl = bl_xy.shape[0]
if verbose:
print 'Gathered interferometer data for gridding convolution for timestamp {0}'.format(self.timestamp)
if wts_change or (not self.grid_mapper[cpol]['all_bl2grid']):
self.grid_mapper[cpol]['per_bl2grid'] = []
self.grid_mapper[cpol]['all_bl2grid'] = {}
gridlocs = NP.hstack((self.gridu.reshape(-1,1), self.gridv.reshape(-1,1)))
if gridfunc_freq == 'scale':
grid_xy = gridlocs[NP.newaxis,:,:] * wavelength.reshape(-1,1,1) # nchan x nv x nu
wl = NP.ones(gridlocs.shape[0])[NP.newaxis,:] * wavelength.reshape(-1,1)
grid_xy = grid_xy.reshape(-1,2)
wl = wl.reshape(-1)
indNN_list, blind, fvu_gridind = LKP.find_NN(bl_xy, grid_xy, distance_ULIM=2.0*distNN, flatten=True, parallel=False)
dxy = grid_xy[fvu_gridind,:] - bl_xy[blind,:]
fvu_gridind_unraveled = NP.unravel_index(fvu_gridind, (self.f.size,)+self.gridu.shape) # f-v-u order since temporary grid was created as nchan x nv x nu
self.grid_mapper[cpol]['all_bl2grid']['blind'] = NP.copy(blind)
self.grid_mapper[cpol]['all_bl2grid']['u_gridind'] = NP.copy(fvu_gridind_unraveled[2])
self.grid_mapper[cpol]['all_bl2grid']['v_gridind'] = NP.copy(fvu_gridind_unraveled[1])
self.grid_mapper[cpol]['all_bl2grid']['f_gridind'] = NP.copy(fvu_gridind_unraveled[0])
# self.grid_mapper[cpol]['all_bl2grid']['indNN_list'] = copy.deepcopy(indNN_list)
if identical_interferometers:
arbitrary_interferometer_aperture = self.interferometers.itervalues().next().aperture
krn = arbitrary_interferometer_aperture.compute(dxy, wavelength=wl[fvu_gridind], pol=cpol, rmaxNN=rmaxNN, load_lookup=False)
else:
# This block #1 is one way to go about per interferometer
for ai,gi in enumerate(indNN_list):
if len(gi) > 0:
label = self.ordered_labels[ai]
ind = NP.asarray(gi)
diffxy = grid_xy[ind,:].reshape(-1,2) - bl_xy[ai,:].reshape(-1,2)
krndict = self.interferometers[label].aperture.compute(diffxy, wavelength=wl[ind], pol=cpol, rmaxNN=rmaxNN, load_lookup=False)
if krn[cpol] is None:
krn[cpol] = NP.copy(krndict[cpol])
else:
krn[cpol] = NP.append(krn[cpol], krndict[cpol])
# # This block #2 is another way equivalent to above block #1
# uniq_blind = NP.unique(blind)
# blhist, blbe, blbn, blri = OPS.binned_statistic(blind, statistic='count', bins=NP.append(uniq_blind, uniq_blind.max()+1))
# for i,ublind in enumerate(uniq_blind):
# label = self.ordered_labels[ublind]
# ind = blri[blri[i]:blri[i+1]]
# krndict = self.interferometers[label].aperture.compute(dxy[ind,:], wavelength=wl[ind], pol=cpol, rmaxNN=rmaxNN, load_lookup=False)
# if krn[cpol] is None:
# krn[cpol] = NP.copy(krndict[cpol])
# else:
# krn[cpol] = NP.append(krn[cpol], krndict[cpol])
self.grid_mapper[cpol]['all_bl2grid']['illumination'] = NP.copy(krn[cpol])
else: # Weights do not scale with frequency (needs serious development)
pass
# Determine weights that can normalize sum of kernel per interferometer per frequency to unity
per_bl_per_freq_norm_wts = NP.zeros(blind.size, dtype=NP.complex64)
# per_bl_per_freq_norm_wts = NP.ones(blind.size, dtype=NP.complex64)
if parallel or (nproc is not None):
list_of_val = []
list_of_rowcol_tuple = []
else:
spval = []
sprow = []
spcol = []
runsum = 0
if verbose:
progress = PGB.ProgressBar(widgets=[PGB.Percentage(), PGB.Bar(marker='-', left=' |', right='| '), PGB.Counter(), '/{0:0d} Baselines '.format(n_bl), PGB.ETA()], maxval=n_bl).start()
for bi,gi in enumerate(indNN_list):
if len(gi) > 0:
fvu_ind = NP.asarray(gi)
unraveled_fvu_ind = NP.unravel_index(fvu_ind, (self.f.size,)+self.gridu.shape)
f_ind = unraveled_fvu_ind[0]
v_ind = unraveled_fvu_ind[1]
u_ind = unraveled_fvu_ind[2]
chanhist, chanbe, chanbn, chanri = OPS.binned_statistic(f_ind, statistic='count', bins=NP.arange(self.f.size+1))
for ci in xrange(self.f.size):
if chanhist[ci] > 0.0:
select_chan_ind = chanri[chanri[ci]:chanri[ci+1]]
per_bl_per_freq_kernel_sum = NP.sum(krn[cpol][runsum:runsum+len(gi)][select_chan_ind])
per_bl_per_freq_norm_wts[runsum:runsum+len(gi)][select_chan_ind] = 1.0 / per_bl_per_freq_kernel_sum
per_bl2grid_info = {}
per_bl2grid_info['label'] = self.ordered_labels[bi]
per_bl2grid_info['f_gridind'] = NP.copy(f_ind)
per_bl2grid_info['u_gridind'] = NP.copy(u_ind)
per_bl2grid_info['v_gridind'] = NP.copy(v_ind)
# per_bl2grid_info['fvu_gridind'] = NP.copy(gi)
per_bl2grid_info['per_bl_per_freq_norm_wts'] = per_bl_per_freq_norm_wts[runsum:runsum+len(gi)]
per_bl2grid_info['illumination'] = krn[cpol][runsum:runsum+len(gi)]
self.grid_mapper[cpol]['per_bl2grid'] += [copy.deepcopy(per_bl2grid_info)]
runsum += len(gi)
# determine the sparse interferometer-to-grid mapping matrix pre-requisites
val = per_bl2grid_info['per_bl_per_freq_norm_wts']*per_bl2grid_info['illumination']
vuf_gridind_unraveled = (per_bl2grid_info['v_gridind'],per_bl2grid_info['u_gridind'],per_bl2grid_info['f_gridind'])
vuf_gridind_raveled = NP.ravel_multi_index(vuf_gridind_unraveled, (self.gridu.shape+(self.f.size,)))
if (not parallel) and (nproc is None):
spval += val.tolist()
sprow += vuf_gridind_raveled.tolist()
spcol += (per_bl2grid_info['f_gridind'] + bi*self.f.size).tolist()
else:
list_of_val += [per_bl2grid_info['per_bl_per_freq_norm_wts']*per_bl2grid_info['illumination']]
list_of_rowcol_tuple += [(vuf_gridind_raveled, per_bl2grid_info['f_gridind'])]
if verbose:
progress.update(bi+1)
if verbose:
progress.finish()
# determine the sparse interferometer-to-grid mapping matrix
if parallel or (nproc is not None):
list_of_shapes = [(self.gridu.size*self.f.size, self.f.size)] * n_bl
if nproc is None:
nproc = max(MP.cpu_count()-1, 1)
else:
nproc = min(nproc, max(MP.cpu_count()-1, 1))
pool = MP.Pool(processes=nproc)
list_of_spmat = pool.map(genMatrixMapper_arg_splitter, IT.izip(list_of_val, list_of_rowcol_tuple, list_of_shapes))
self.bl2grid_mapper[cpol] = SpM.hstack(list_of_spmat, format='csr')
else:
spval = NP.asarray(spval)
sprowcol = (NP.asarray(sprow), NP.asarray(spcol))
self.bl2grid_mapper[cpol] = SpM.csr_matrix((spval, sprowcol), shape=(self.gridu.size*self.f.size, n_bl*self.f.size))
self.grid_mapper[cpol]['all_bl2grid']['per_bl_per_freq_norm_wts'] = NP.copy(per_bl_per_freq_norm_wts)
############################################################################
def applyMappingMatrix(self, pol=None, verbose=True):
"""
------------------------------------------------------------------------
Constructs the grid of complex illumination and visibilities
using the sparse baseline-to-grid mapping matrix. Intended to serve as a
"matrix" alternative to make_grid_cube_new()
Inputs:
pol [String] The polarization to be gridded. Can be set to 'P11',
'P12', 'P21', or 'P22'. If set to None, gridding for all the
polarizations is performed. Default=None
verbose [boolean] If True, prints diagnostic and progress messages.
If False (default), suppress printing such messages.
------------------------------------------------------------------------
"""
if pol is None:
pol = ['P11', 'P12', 'P21', 'P22']
pol = NP.unique(NP.asarray(pol))
for cpol in pol:
if verbose:
print 'Gridding aperture illumination and visibilities for polarization {0} ...'.format(cpol)
if cpol not in ['P11', 'P12', 'P21', 'P22']:
raise ValueError('Invalid specification for input parameter pol')
Vf_dict = self.get_visibilities(cpol, flag=None, tselect=-1, fselect=None, bselect=None, datapool='avg', sort=True)
Vf = Vf_dict['visibilities'].astype(NP.complex64) # (n_ts=1) x n_bl x nchan
Vf = NP.squeeze(Vf, axis=0) # n_bl x nchan
twts = Vf_dict['twts'] # (n_ts=1) x n_ant x 1
twts = NP.squeeze(twts, axis=0) # n_ant x 1
unflagged = twts > 0.0
unflagged = unflagged.astype(int)
Vf = Vf * unflagged # applies antenna flagging, n_ant x nchan
wts = unflagged * NP.ones(self.f.size).reshape(1,-1) # n_ant x nchan
wts[NP.isnan(Vf)] = 0.0
Vf[NP.isnan(Vf)] = 0.0
Vf = Vf.ravel()
wts = wts.ravel()
sparse_Vf = SpM.csr_matrix(Vf)
sparse_wts = SpM.csr_matrix(wts)
# Store as sparse matrices
self.grid_illumination[cpol] = self.bl2grid_mapper[cpol].dot(sparse_wts.T)
self.grid_Vf[cpol] = self.bl2grid_mapper[cpol].dot(sparse_Vf.T)
# # Store as dense matrices
# self.grid_illumination[cpol] = self.bl2grid_mapper[cpol].dot(wts).reshape(self.gridu.shape+(self.f.size,))
# self.grid_Vf[cpol] = self.bl2grid_mapper[cpol].dot(Vf).reshape(self.gridu.shape+(self.f.size,))
if verbose:
print 'Gridded aperture illumination and electric fields for polarization {0} from {1:0d} unflagged contributing antennas'.format(cpol, NP.sum(unflagged).astype(int))
############################################################################
def make_grid_cube(self, pol=None, verbose=True):
"""
------------------------------------------------------------------------
Constructs the grid of complex power illumination and visibilities using
the gridding information determined for every baseline. Flags are taken
into account while constructing this grid.
Inputs:
pol [String] The polarization to be gridded. Can be set to 'P11',
'P12', 'P21' or 'P22'. If set to None, gridding for all the
polarizations is performed. Default = None
verbose [boolean] If True, prints diagnostic and progress messages.
If False (default), suppress printing such messages.
------------------------------------------------------------------------
"""
if pol is None:
pol = ['P11', 'P12', 'P21', 'P22']
pol = NP.unique(NP.asarray(pol))
for cpol in pol:
if verbose:
print 'Gridding aperture illumination and visibilities for polarization {0} ...'.format(cpol)
if cpol not in ['P11', 'P12', 'P21', 'P22']:
raise ValueError('Invalid specification for input parameter pol')
if cpol not in self._bl_contribution:
raise KeyError('Key {0} not found in attribute _bl_contribution'.format(cpol))
self.grid_illumination[cpol] = NP.zeros((self.gridu.shape + (self.f.size,)), dtype=NP.complex_)
self.grid_Vf[cpol] = NP.zeros((self.gridu.shape + (self.f.size,)), dtype=NP.complex_)
labels = self.grid_mapper[cpol]['labels'].keys()
if verbose:
progress = PGB.ProgressBar(widgets=[PGB.Percentage(), PGB.Bar(marker='-', left=' |', right='| '), PGB.Counter(), '/{0:0d} Antennas '.format(len(labels)), PGB.ETA()], maxval=len(labels)).start()
loopcount = 0
num_unflagged = 0
sum_twts = 0.0
for bllabel, blinfo in self.grid_mapper[cpol]['labels'].iteritems():
# if not self.interferometers[bllabel].crosspol.flag[cpol]:
if blinfo['twts'] > 0.0:
num_unflagged += 1
sum_twts += blinfo['twts']
gridind_unraveled = NP.unravel_index(blinfo['gridind'], self.gridu.shape+(self.f.size,))
# self.grid_illumination[cpol][gridind_unraveled] += blinfo['illumination'] * blinfo['twts']
# self.grid_Vf[cpol][gridind_unraveled] += blinfo['Vf'] * blinfo['twts']
self.grid_illumination[cpol][gridind_unraveled] += blinfo['illumination']
self.grid_Vf[cpol][gridind_unraveled] += blinfo['Vf']
progress.update(loopcount+1)
loopcount += 1
progress.finish()
# self.grid_Vf[cpol] *= num_unflagged/sum_twts
if verbose:
print 'Gridded aperture illumination and visibilities for polarization {0} from {1:0d} unflagged contributing baselines'.format(cpol, num_unflagged)
############################################################################
def make_grid_cube_new(self, pol=None, verbose=True):
"""
------------------------------------------------------------------------
Constructs the grid of complex power illumination and visibilities using
the gridding information determined for every baseline. Flags are taken
into account while constructing this grid.
Inputs:
pol [String] The polarization to be gridded. Can be set to 'P11',
'P12', 'P21' or 'P22'. If set to None, gridding for all the
polarizations is performed. Default = None
verbose [boolean] If True, prints diagnostic and progress messages.
If False (default), suppress printing such messages.
------------------------------------------------------------------------
"""
if pol is None:
pol = ['P11', 'P12', 'P21', 'P22']
pol = NP.unique(NP.asarray(pol))
for cpol in pol:
if verbose:
print 'Gridding aperture illumination and visibilities for polarization {0} ...'.format(cpol)
if cpol not in ['P11', 'P12', 'P21', 'P22']:
raise ValueError('Invalid specification for input parameter pol')
if cpol not in self._bl_contribution:
raise KeyError('Key {0} not found in attribute _bl_contribution'.format(cpol))
self.grid_illumination[cpol] = NP.zeros((self.gridu.shape + (self.f.size,)), dtype=NP.complex_)
self.grid_Vf[cpol] = NP.zeros((self.gridu.shape + (self.f.size,)), dtype=NP.complex_)
nlabels = len(self.grid_mapper[cpol]['per_bl2grid'])
loopcount = 0
num_unflagged = 0
sum_twts = 0.0
if verbose:
progress = PGB.ProgressBar(widgets=[PGB.Percentage(), PGB.Bar(marker='-', left=' |', right='| '), PGB.Counter(), '/{0:0d} Antennas '.format(nlabels), PGB.ETA()], maxval=nlabels).start()
for bi, per_bl2grid_info in enumerate(self.grid_mapper[cpol]['per_bl2grid']):
bllabel = per_bl2grid_info['label']
if per_bl2grid_info['twts'] > 0.0:
num_unflagged += 1
sum_twts += per_bl2grid_info['twts']
vuf_gridind_unraveled = (per_bl2grid_info['v_gridind'],per_bl2grid_info['u_gridind'],per_bl2grid_info['f_gridind'])
self.grid_illumination[cpol][vuf_gridind_unraveled] += per_bl2grid_info['per_bl_per_freq_norm_wts'] * per_bl2grid_info['illumination']
self.grid_Vf[cpol][vuf_gridind_unraveled] += per_bl2grid_info['per_bl_per_freq_norm_wts'] * per_bl2grid_info['Vf'] * per_bl2grid_info['illumination']
# self.grid_illumination[cpol][vuf_gridind_unraveled] += per_bl2grid_info['per_bl_per_freq_norm_wts'] * per_bl2grid_info['illumination'] * per_bl2grid_info['twts']
# self.grid_Vf[cpol][vuf_gridind_unraveled] += per_bl2grid_info['per_bl_per_freq_norm_wts'] * per_bl2grid_info['Vf'] * per_bl2grid_info['twts']
if verbose:
progress.update(loopcount+1)
loopcount += 1
if verbose:
progress.finish()
# self.grid_illumination[cpol] *= num_unflagged/sum_twts
# self.grid_Vf[cpol] *= num_unflagged/sum_twts
if verbose:
print 'Gridded aperture illumination and visibilities for polarization {0} from {1:0d} unflagged contributing baselines'.format(cpol, num_unflagged)
############################################################################
def quick_beam_synthesis(self, pol=None):
"""
------------------------------------------------------------------------
A quick generator of synthesized beam using interferometer array grid
illumination pattern using the center frequency. Not intended to be used
rigorously but rather for comparison purposes and making quick plots
Inputs:
pol [String] The polarization of the synthesized beam. Can be set
to 'P11', 'P12', 'P21' or 'P2'. If set to None, synthesized beam
for all the polarizations are generated. Default=None
Outputs:
Dictionary with the following keys and information:
'syn_beam' [numpy array] synthesized beam of same size as that of the
interferometer array grid. It is FFT-shifted to place the
origin at the center of the array. The peak value of the
synthesized beam is fixed at unity
'grid_power_illumination'
[numpy array] complex grid illumination obtained from
inverse fourier transform of the synthesized beam in
'syn_beam' and has size same as that of the interferometer
array grid. It is FFT-shifted to have the origin at the
center. The sum of this array is set to unity to match the
peak of the synthesized beam
'l' [numpy vector] x-values of the direction cosine grid
corresponding to x-axis (axis=1) of the synthesized beam
'm' [numpy vector] y-values of the direction cosine grid
corresponding to y-axis (axis=0) of the synthesized beam
------------------------------------------------------------------------
"""
if not self.grid_ready:
raise ValueError('Need to perform gridding of the antenna array before an equivalent UV grid can be simulated')
if pol is None:
pol = ['P11', 'P12', 'P21', 'P22']
elif isinstance(pol, str):
if pol in ['P11', 'P12', 'P21', 'P22']:
pol = [pol]
else:
raise ValueError('Invalid polarization specified')
elif isinstance(pol, list):
p = [cpol for cpol in pol if cpol in ['P11', 'P12', 'P21', 'P22']]
if len(p) == 0:
raise ValueError('Invalid polarization specified')
pol = p
else:
raise TypeError('Input keyword pol must be string, list or set to None')
pol = sorted(pol)
for cpol in pol:
if self.grid_illumination[cpol] is None:
raise ValueError('Grid illumination for the specified polarization is not determined yet. Must use make_grid_cube()')
chan = NP.argmin(NP.abs(self.f - self.f0))
orig_syn_beam_in_uv = NP.empty(self.gridu.shape+(len(pol),), dtype=NP.complex)
for pind, cpol in enumerate(pol):
orig_syn_beam_in_uv[:,:,pind] = self.grid_illumination[cpol][:,:,chan]
# # Pad it with zeros to be twice the size
# padded_syn_beam_in_uv = NP.pad(orig_syn_beam_in_uv, ((0,orig_syn_beam_in_uv.shape[0]),(0,orig_syn_beam_in_uv.shape[1]),(0,0)), mode='constant', constant_values=0)
# # The NP.roll statements emulate a fftshift but by 1/4 of the size of the padded array
# padded_syn_beam_in_uv = NP.roll(padded_syn_beam_in_uv, -orig_syn_beam_in_uv.shape[0]/2, axis=0)
# padded_syn_beam_in_uv = NP.roll(padded_syn_beam_in_uv, -orig_syn_beam_in_uv.shape[1]/2, axis=1)
# Pad it with zeros on either side to be twice the size
padded_syn_beam_in_uv = NP.pad(orig_syn_beam_in_uv, ((orig_syn_beam_in_uv.shape[0]/2,orig_syn_beam_in_uv.shape[0]/2),(orig_syn_beam_in_uv.shape[1]/2,orig_syn_beam_in_uv.shape[1]/2),(0,0)), mode='constant', constant_values=0)
# Shift to be centered
padded_syn_beam_in_uv = NP.fft.ifftshift(padded_syn_beam_in_uv)
# Compute the synthesized beam. It is at a finer resolution due to padding
syn_beam = NP.fft.fft2(padded_syn_beam_in_uv, axes=(0,1))
# Select only the real part, equivalent to adding conjugate baselines
syn_beam = 2 * syn_beam.real
syn_beam /= syn_beam.max()
# Inverse Fourier Transform to obtain real and symmetric uv-grid illumination
syn_beam_in_uv = NP.fft.ifft2(syn_beam, axes=(0,1))
# shift the array to be centered
syn_beam_in_uv = NP.fft.ifftshift(syn_beam_in_uv, axes=(0,1))
# Discard pads at either end and select only the central values of original size
syn_beam_in_uv = syn_beam_in_uv[orig_syn_beam_in_uv.shape[0]/2:orig_syn_beam_in_uv.shape[0]/2+orig_syn_beam_in_uv.shape[0],orig_syn_beam_in_uv.shape[1]/2:orig_syn_beam_in_uv.shape[1]/2+orig_syn_beam_in_uv.shape[1],:]
syn_beam = NP.fft.fftshift(syn_beam[::2,::2,:], axes=(0,1)) # Downsample by factor 2 to get native resolution and shift to be centered
du = self.gridu[0,1] - self.gridu[0,0]
dv = self.gridv[1,0] - self.gridv[0,0]
l = DSP.spectax(self.gridu.shape[1], resolution=du, shift=True)
m = DSP.spectax(self.gridv.shape[0], resolution=dv, shift=True)
return {'syn_beam': syn_beam, 'grid_power_illumination': syn_beam_in_uv, 'l': l, 'm': m}
############################################################################
def grid_convolve_old(self, pol=None, antpairs=None, unconvolve_existing=False,
normalize=False, method='NN', distNN=NP.inf, tol=None,
maxmatch=None):
"""
------------------------------------------------------------------------
Routine to project the visibility illumination pattern and the
visibilities on the grid. It can operate on the entire antenna array or
incrementally project the visibilities and illumination patterns from
specific antenna pairs on to an already existing grid.
Inputs:
pol [String] The polarization to be gridded. Can be set to 'P1'
or 'P2'. If set to None, gridding for both 'P1' and 'P2'
is performed. Default = None
ants [instance of class AntennaArray, single instance or list of
instances of class Antenna, or a dictionary holding instances
of class Antenna] If a dictionary is provided, the keys
should be the antenna labels and the values should be
instances of class Antenna. If a list is provided, it should
be a list of valid instances of class Antenna. These
instance(s) of class Antenna will be merged to the existing
grid contained in the instance of AntennaArray class. If ants
is not provided (set to None), the gridding operations will
be performed on the entire set of antennas contained in the
instance of class AntennaArray. Default = None.
unconvolve_existing
[Boolean] Default = False. If set to True, the effects of
gridding convolution contributed by the antenna(s) specified
will be undone before updating the antenna measurements on
the grid, if the antenna(s) is/are already found to in the
set of antennas held by the instance of AntennaArray. If
False and if one or more antenna instances specified are
already found to be held in the instance of class
AntennaArray, the code will stop raising an error indicating
the gridding operation cannot proceed.
normalize [Boolean] Default = False. If set to True, the gridded
weights are divided by the sum of weights so that the gridded
weights add up to unity.
method [string] The gridding method to be used in applying the
antenna weights on to the antenna array grid. Accepted values
are 'NN' (nearest neighbour - default), 'CS' (cubic spline),
or 'BL' (Bi-linear). In case of applying grid weights by 'NN'
method, an optional distance upper bound for the nearest
neighbour can be provided in the parameter distNN to prune
the search and make it efficient
distNN [scalar] A positive value indicating the upper bound on
distance to the nearest neighbour in the gridding process.
It has units of distance, the same units as the antenna
attribute location and antenna array attribute gridx and
gridy. Default is NP.inf (infinite distance). It will be
internally converted to have same units as antenna attributes
wtspos (units in number of wavelengths)
maxmatch [scalar] A positive value indicating maximum number of input
locations in the antenna grid to be assigned. Default = None.
If set to None, all the antenna array grid elements specified
are assigned values for each antenna. For instance, to have
only one antenna array grid element to be populated per
antenna, use maxmatch=1.
tol [scalar] If set, only lookup data with abs(val) > tol will be
considered for nearest neighbour lookup. Default = None
implies all lookup values will be considered for nearest
neighbour determination. tol is to be interpreted as a
minimum value considered as significant in the lookup table.
------------------------------------------------------------------------
"""
eps = 1.0e-10
if not self.grid_ready:
self.grid()
if (pol is None) or (pol == 'P11'):
if antpairs is not None:
if isinstance(antpairs, Interferometer):
antpairs = [antpairs]
if isinstance(antpairs, (dict, InterferometerArray)):
# Check if these interferometers are new or old and compatible
for key in antpairs:
if isinstance(antpairs[key], Interferometer): # required if antpairs is a dictionary and not instance of InterferometerArray
if key in self.interferometers:
if unconvolve_existing: # Effects on the grid of interferometers already existing must be removed
if self.interferometers[key]._gridinfo['P11']: # if gridding info is not empty
for i in range(len(self.f)):
self.grid_unconvolve(antpairs[key].label)
else:
raise KeyError('Interferometer {0} already found to exist in the dictionary of interferometers but cannot proceed grid_convolve() without unconvolving first.'.format(antpairs[key].label))
else:
del antpairs[key] # remove the dictionary element since it is not an Interferometer instance
for key in antpairs:
if not antpairs[key].crosspol.flag['P11']:
for i in range(len(self.f)):
if method == 'NN':
if antpairs[key].wtspos_scale['P11'] is None:
reflocs = antpairs[key].wtspos['P11'][i] + (self.f[i]/FCNST.c) * NP.asarray([antpairs[key].location.x, antpairs[key].location.y]).reshape(1,-1)
inplocs = NP.hstack((self.gridu.reshape(-1,1), self.gridv.reshape(-1,1)))
ibind, nnval = LKP.lookup_1NN(reflocs, antpairs[key].wts['P11'][i], inplocs,
distance_ULIM=distNN*self.f[i]/FCNST.c,
remove_oob=True, tol=tol, maxmatch=maxmatch)[:2]
roi_ind = NP.unravel_index(ibind, self.gridu.shape)
if normalize:
nnval /= NP.sum(nnval)
elif antpairs[key].wtspos_scale['P11'] == 'scale':
if i == 0: # Determine some parameters only for zeroth channel if scaling is set
reflocs = antpairs[key].wtspos['P11'][0] + (self.f[0]/FCNST.c) * NP.asarray([antpairs[key].location.x, antpairs[key].location.y]).reshape(1,-1)
inplocs = NP.hstack((self.gridu.reshape(-1,1), self.gridv.reshape(-1,1)))
ibind, nnval = LKP.lookup_1NN(reflocs, antpairs[key].wts['P11'][0], inplocs,
distance_ULIM=distNN*self.f[0]/FCNST.c,
remove_oob=True, tol=tol, maxmatch=maxmatch)[:2]
roi_ind = NP.unravel_index(ibind, self.gridu.shape)
if normalize:
nnval /= NP.sum(nnval)
else:
raise ValueError('Invalid scale option specified. Aborting grid_convolve().')
self.grid_illumination['P11'][roi_ind+(i+NP.zeros(ibind.size, dtype=NP.int),)] += nnval
self.grid_Vf['P11'][roi_ind+(i+NP.zeros(ibind.size, dtype=NP.int),)] += antpairs[key].crosspol.Vf['P11'][i] * nnval
else:
if antpairs[key].wtspos_scale['P11'] is None:
grid_illumination['P11'] = GRD.conv_grid2d(antpairs[key].location.x * (self.f[i]/FCNST.c),
antpairs[key].location.y * (self.f[i]/FCNST.c),
antpairs[key].wtspos['P11'][i][:,0],
antpairs[key].wtspos['P11'][i][:,1],
antpairs[key].wts['P11'][i],
self.gridu,
self.gridv,
method=method)
grid_illumination['P11'] = grid_illumination['P11'].reshape(self.gridu.shape)
if normalize:
grid_illumination['P11'] = grid_illumination['P11'] / NP.sum(grid_illumination['P11'])
roi_ind = NP.where(NP.abs(grid_illumination['P11']) >= eps)
elif antpairs[key].wtspos_scale['P11'] == 'scale':
if i == 0: # Determine some parameters only for zeroth channel if scaling is set
grid_illumination['P11'] = GRD.conv_grid2d(antpairs[key].location.x * (self.f[0]/FCNST.c),
antpairs[key].location.y * (self.f[0]/FCNST.c),
antpairs[key].wtspos['P11'][0][:,0],
antpairs[key].wtspos['P11'][0][:,1],
antpairs[key].wts['P11'][0],
self.gridu,
self.gridv,
method=method)
grid_illumination['P11'] = grid_illumination['P11'].reshape(self.gridu.shape)
if normalize:
grid_illumination['P11'] = grid_illumination['P11'] / NP.sum(grid_illumination['P11'])
roi_ind = NP.where(NP.abs(grid_illumination['P11']) >= eps)
else:
raise ValueError('Invalid scale option specified. Aborting grid_convolve().')
self.grid_illumination['P11'][:,:,i] += grid_illumination['P11']
self.grid_Vf['P11'][:,:,i] += antpairs[key].crosspol.Vf['P11'][i] * grid_illumination['P11']
if key in self.interferometers:
if i not in self.interferometers[key]._gridinfo['P11']:
self.interferometers[key]._gridinfo['P11'] = {} # Create an empty dictionary for each channel to hold grid info
self.interferometers[key]._gridinfo['P11'][i]['f'] = self.f[i]
self.interferometers[key]._gridinfo['P11'][i]['flag'] = False
self.interferometers[key]._gridinfo['P11'][i]['gridxy_ind'] = zip(*roi_ind)
self.interferometers[key].wtspos_scale['P11'] = antpairs[key].wtspos_scale['P11']
if method == 'NN':
self.interferometers[key]._gridinfo['P11'][i]['illumination'] = nnval
self.interferometers[key]._gridinfo['P11'][i]['Vf'] = antpairs[key].crosspol.Vf['P11'][i] * nnval
else:
self.interferometers[key]._gridinfo['P11'][i]['illumination'] = grid_illumination['P11'][roi_ind]
self.interferometers[key]._gridinfo['P11'][i]['Vf'] = antpairs[key].crosspol.Vf['P11'][i] * grid_illumination['P11'][roi_ind]
elif isinstance(antpairs, list):
# Check if these interferometers are new or old and compatible
for key in range(len(antpairs)):
if isinstance(antpairs[key], Interferometer): # required if antpairs is a dictionary and not instance of InterferometerArray
if antpairs[key].label in self.interferometers:
if unconvolve_existing: # Effects on the grid of interferometers already existing must be removed
if self.interferometers[antpairs[key].label]._gridinfo['P11']: # if gridding info is not empty
for i in range(len(self.f)):
self.grid_unconvolve(antpairs[key].label)
else:
raise KeyError('Interferometer {0} already found to exist in the dictionary of interferometers but cannot proceed grid_convolve() without unconvolving first.'.format(antpairs[key].label))
else:
del antpairs[key] # remove the dictionary element since it is not an Interferometer instance
for key in range(len(antpairs)):
if not antpairs[key].crosspol.flag['P11']:
for i in range(len(self.f)):
if method == 'NN':
if antpairs[key].wtspos_scale['P11'] is None:
reflocs = antpairs[key].wtspos['P11'][i] + (self.f[i]/FCNST.c) * NP.asarray([antpairs[key].location.x, antpairs[key].location.y]).reshape(1,-1)
inplocs = NP.hstack((self.gridu.reshape(-1,1), self.gridv.reshape(-1,1)))
ibind, nnval = LKP.lookup_1NN(reflocs, antpairs[key].wts['P11'][i], inplocs,
distance_ULIM=distNN*self.f[i]/FCNST.c,
remove_oob=True, tol=tol, maxmatch=maxmatch)[:2]
roi_ind = NP.unravel_index(ibind, self.gridu.shape)
if normalize:
nnval /= NP.sum(nnval)
elif antpairs[key].wtspos_scale['P11'] == 'scale':
if i == 0: # Determine some parameters only for zeroth channel if scaling is set
reflocs = antpairs[key].wtspos['P11'][0] + (self.f[0]/FCNST.c) * NP.asarray([antpairs[key].location.x, antpairs[key].location.y]).reshape(1,-1)
inplocs = NP.hstack((self.gridu.reshape(-1,1), self.gridv.reshape(-1,1)))
ibind, nnval = LKP.lookup_1NN(reflocs, antpairs[key].wts['P11'][0], inplocs,
distance_ULIM=distNN*self.f[0]/FCNST.c,
remove_oob=True, tol=tol, maxmatch=maxmatch)[:2]
roi_ind = NP.unravel_index(ibind, self.gridu.shape)
if normalize:
nnval /= NP.sum(nnval)
else:
raise ValueError('Invalid scale option specified. Aborting grid_convolve().')
self.grid_illumination['P11'][roi_ind+(i+NP.zeros(ibind.size, dtype=NP.int),)] += nnval
self.grid_Vf['P11'][roi_ind+(i+NP.zeros(ibind.size, dtype=NP.int),)] += antpairs[key].crosspol.Vf['P11'][i] * nnval
else:
if antpairs[key].wtspos_scale['P11'] is None:
grid_illumination['P11'] = GRD.conv_grid2d(antpairs[key].location.x * (self.f[i]/FCNST.c),
antpairs[key].location.y * (self.f[i]/FCNST.c),
antpairs[key].wtspos['P11'][i][:,0],
antpairs[key].wtspos['P11'][i][:,1],
antpairs[key].wts['P11'][i],
self.gridu,
self.gridv,
method=method)
grid_illumination['P11'] = grid_illumination['P11'].reshape(self.gridu.shape)
if normalize:
grid_illumination['P11'] = grid_illumination['P11'] / NP.sum(grid_illumination['P11'])
roi_ind = NP.where(NP.abs(grid_illumination['P11']) >= eps)
elif antpairs[key].wtspos_scale['P11'] == 'scale':
if i == 0: # Determine some parameters only for zeroth channel if scaling is set
grid_illumination['P11'] = GRD.conv_grid2d(antpairs[key].location.x * (self.f[0]/FCNST.c),
antpairs[key].location.y * (self.f[0]/FCNST.c),
antpairs[key].wtspos['P11'][0][:,0],
antpairs[key].wtspos['P11'][0][:,1],
antpairs[key].wts['P11'][0],
self.gridu,
self.gridv,
method=method)
grid_illumination['P11'] = grid_illumination['P11'].reshape(self.gridu.shape)
if normalize:
grid_illumination['P11'] = grid_illumination['P11'] / NP.sum(grid_illumination['P11'])
roi_ind = NP.where(NP.abs(grid_illumination['P11']) >= eps)
else:
raise ValueError('Invalid scale option specified. Aborting grid_convolve().')
self.grid_illumination['P11'][:,:,i] += grid_illumination['P11']
self.grid_Vf['P11'][:,:,i] += antpairs[key].crosspol.Vf['P11'][i] * grid_illumination['P11']
if antpairs[key].label in self.interferometers:
if i not in self.interferometers[key]._gridinfo['P11']:
self.interferometers[key]._gridinfo['P11'] = {} # Create an empty dictionary for each channel to hold grid info
self.interferometers[antpairs[key].label]._gridinfo['P11'][i]['f'] = self.f[i]
self.interferometers[antpairs[key].label]._gridinfo['P11'][i]['flag'] = False
self.interferometers[antpairs[key].label]._gridinfo['P11'][i]['gridxy_ind'] = zip(*roi_ind)
self.interferometers[key].wtspos_scale['P11'] = antpairs[key].wtspos_scale['P11']
if method == 'NN':
self.interferometers[antpairs[key].label]._gridinfo['P11'][i]['illumination'] = nnval
self.interferometers[antpairs[key].label]._gridinfo['P11'][i]['Vf'] = antpairs[key].crosspol.Vf['P11'][i] * nnval
else:
self.interferometers[antpairs[key].label]._gridinfo['P11'][i]['illumination'] = grid_illumination['P11'][roi_ind]
self.interferometers[antpairs[key].label]._gridinfo['P11'][i]['Vf'] = antpairs[key].crosspol.Vf['P11'][i] * grid_illumination['P11'][roi_ind]
else:
raise TypeError('antpairs must be an instance of InterferometerArray, a dictionary of Interferometer instances, a list of Interferometer instances or an Interferometer instance.')
else:
self.grid_illumination['P11'] = NP.zeros((self.gridu.shape[0],
self.gridu.shape[1],
len(self.f)),
dtype=NP.complex_)
self.grid_Vf['P11'] = NP.zeros((self.gridu.shape[0],
self.gridu.shape[1],
len(self.f)), dtype=NP.complex_)
for key in self.interferometers:
if not self.interferometers[key].crosspol.flag['P11']:
for i in range(len(self.f)):
if method == 'NN':
if self.interferometers[key].wtspos_scale['P11'] is None:
reflocs = self.interferometers[key].wtspos['P11'][i] + (self.f[i]/FCNST.c) * NP.asarray([self.interferometers[key].location.x, self.interferometers[key].location.y]).reshape(1,-1)
inplocs = NP.hstack((self.gridu.reshape(-1,1), self.gridv.reshape(-1,1)))
ibind, nnval = LKP.lookup_1NN(reflocs, self.interferometers[key].wts['P11'][i], inplocs,
distance_ULIM=distNN*self.f[i]/FCNST.c,
remove_oob=True, tol=tol, maxmatch=maxmatch)[:2]
roi_ind = NP.unravel_index(ibind, self.gridu.shape)
if normalize:
nnval /= NP.sum(nnval)
elif self.interferometers[key].wtspos_scale['P11'] == 'scale':
if i == 0: # Determine some parameters only for zeroth channel if scaling is set
reflocs = self.interferometers[key].wtspos['P11'][0] + (self.f[0]/FCNST.c) * NP.asarray([self.interferometers[key].location.x, self.interferometers[key].location.y]).reshape(1,-1)
inplocs = NP.hstack((self.gridu.reshape(-1,1), self.gridv.reshape(-1,1)))
ibind, nnval = LKP.lookup_1NN(reflocs, self.interferometers[key].wts['P11'][0], inplocs,
distance_ULIM=distNN*self.f[0]/FCNST.c,
remove_oob=True, tol=tol, maxmatch=maxmatch)[:2]
roi_ind = NP.unravel_index(ibind, self.gridu.shape)
if normalize:
nnval /= NP.sum(nnval)
else:
raise ValueError('Invalid scale option specified. Aborting grid_convolve().')
self.grid_illumination['P11'][roi_ind+(i+NP.zeros(ibind.size, dtype=NP.int),)] += nnval
self.grid_Vf['P11'][roi_ind+(i+NP.zeros(ibind.size, dtype=NP.int),)] += self.interferometers[key].crosspol.Vf['P11'][i] * nnval
else:
if self.interferometers[key].wtspos_scale['P11'] is None:
grid_illumination['P11'] = GRD.conv_grid2d(self.interferometers[key].location.x * (self.f[i]/FCNST.c),
self.interferometers[key].location.y * (self.f[i]/FCNST.c),
self.interferometers[key].wtspos['P11'][i][:,0],
self.interferometers[key].wtspos['P11'][i][:,1],
self.interferometers[key].wts['P11'][i],
self.gridu,
self.gridv,
method=method)
grid_illumination['P11'] = grid_illumination['P11'].reshape(self.gridu.shape)
if normalize:
grid_illumination['P11'] = grid_illumination['P11'] / NP.sum(grid_illumination['P11'])
roi_ind = NP.where(NP.abs(grid_illumination['P11']) >= eps)
elif self.interferometers[key].wtspos_scale['P11'] == 'scale':
if i == 0:
grid_illumination['P11'] = GRD.conv_grid2d(self.interferometers[key].location.x * (self.f[0]/FCNST.c),
self.interferometers[key].location.y * (self.f[0]/FCNST.c),
self.interferometers[key].wtspos['P11'][0][:,0],
self.interferometers[key].wtspos['P11'][0][:,1],
self.interferometers[key].wts['P11'][0],
self.gridu,
self.gridv,
method=method)
grid_illumination['P11'] = grid_illumination['P11'].reshape(self.gridu.shape)
if normalize:
grid_illumination['P11'] = grid_illumination['P11'] / NP.sum(grid_illumination['P11'])
roi_ind = NP.where(NP.abs(grid_illumination['P11']) >= eps)
else:
raise ValueError('Invalid scale option specified. Aborting grid_convolve().')
self.grid_illumination['P11'][:,:,i] += grid_illumination['P11']
self.grid_Vf['P11'][:,:,i] += self.interferometers[key].crosspol.Vf['P11'][i] * grid_illumination['P11']
self.interferometers[key]._gridinfo['P11'][i] = {} # Create a nested dictionary to hold channel info
self.interferometers[key]._gridinfo['P11'][i]['f'] = self.f[i]
self.interferometers[key]._gridinfo['P11'][i]['flag'] = False
self.interferometers[key]._gridinfo['P11'][i]['gridxy_ind'] = zip(*roi_ind)
if method == 'NN':
self.interferometers[key]._gridinfo['P11'][i]['illumination'] = nnval
self.interferometers[key]._gridinfo['P11'][i]['Vf'] = self.interferometers[key].crosspol.Vf['P11'][i] * nnval
else:
self.interferometers[key]._gridinfo['P11'][i]['illumination'] = grid_illumination['P11'][roi_ind]
self.interferometers[key]._gridinfo['P11'][i]['Vf'] = self.interferometers[key].crosspol.Vf['P11'][i] * grid_illumination['P11'][roi_ind]
if (pol is None) or (pol == 'P22'):
if antpairs is not None:
if isinstance(antpairs, Interferometer):
antpairs = [antpairs]
if isinstance(antpairs, (dict, InterferometerArray)):
# Check if these interferometers are new or old and compatible
for key in antpairs:
if isinstance(antpairs[key], Interferometer): # required if antpairs is a dictionary and not instance of InterferometerArray
if key in self.interferometers:
if unconvolve_existing: # Effects on the grid of interferometers already existing must be removed
if self.interferometers[key]._gridinfo_P22: # if gridding info is not empty
for i in range(len(self.f)):
self.grid_unconvolve(antpairs[key].label)
else:
raise KeyError('Interferometer {0} already found to exist in the dictionary of interferometers but cannot proceed grid_convolve() without unconvolving first.'.format(antpairs[key].label))
else:
del antpairs[key] # remove the dictionary element since it is not an Interferometer instance
for key in antpairs:
if not antpairs[key].crosspol.flag_P22:
for i in range(len(self.f)):
if method == 'NN':
if antpairs[key].wtspos_P22_scale is None:
reflocs = antpairs[key].wtspos_P22[i] + (self.f[i]/FCNST.c) * NP.asarray([antpairs[key].location.x, antpairs[key].location.y]).reshape(1,-1)
inplocs = (self.f[i]/FCNST.c) * NP.hstack((self.gridu.reshape(-1,1), self.gridv.reshape(-1,1)))
ibind, nnval = LKP.lookup_1NN(reflocs, antpairs[key].wts_P22[i], inplocs,
distance_ULIM=distNN*self.f[i]/FCNST.c,
remove_oob=True, tol=tol, maxmatch=maxmatch)[:2]
roi_ind = NP.unravel_index(ibind, self.gridu.shape)
if normalize:
nnval /= NP.sum(nnval)
elif antpairs[key].wtspos_P22_scale == 'scale':
if i == 0: # Determine some parameters only for zeroth channel if scaling is set
reflocs = antpairs[key].wtspos_P22[0] + (self.f[0]/FCNST.c) * NP.asarray([antpairs[key].location.x, antpairs[key].location.y]).reshape(1,-1)
inplocs = (self.f[0]/FCNST.c) * NP.hstack((self.gridu.reshape(-1,1), self.gridv.reshape(-1,1)))
ibind, nnval = LKP.lookup_1NN(reflocs, antpairs[key].wts_P22[0], inplocs,
distance_ULIM=distNN*self.f[0]/FCNST.c,
remove_oob=True, tol=tol, maxmatch=maxmatch)[:2]
roi_ind = NP.unravel_index(ibind, self.gridu.shape)
if normalize:
nnval /= NP.sum(nnval)
else:
raise ValueError('Invalid scale option specified. Aborting grid_convolve().')
self.grid_illumination_P22[roi_ind+(i+NP.zeros(ibind.size, dtype=NP.int),)] += nnval
self.grid_Vf_P22[roi_ind+(i+NP.zeros(ibind.size, dtype=NP.int),)] += antpairs[key].crosspol.Vf_P22[i] * nnval
else:
if antpairs[key].wtspos_P22_scale is None:
grid_illumination_P22 = GRD.conv_grid2d(antpairs[key].location.x * (self.f[i]/FCNST.c),
antpairs[key].location.y * (self.f[i]/FCNST.c),
antpairs[key].wtspos_P22[i][:,0],
antpairs[key].wtspos_P22[i][:,1],
antpairs[key].wts_P22[i],
self.gridu * (self.f[i]/FCNST.c),
self.gridv * (self.f[i]/FCNST.c),
method=method)
grid_illumination_P22 = grid_illumination_P22.reshape(self.gridu.shape)
if normalize:
grid_illumination_P22 = grid_illumination_P22 / NP.sum(grid_illumination_P22)
roi_ind = NP.where(NP.abs(grid_illumination_P22) >= eps)
elif antpairs[key].wtspos_P22_scale == 'scale':
if i == 0: # Determine some parameters only for zeroth channel if scaling is set
grid_illumination_P22 = GRD.conv_grid2d(antpairs[key].location.x * (self.f[0]/FCNST.c),
antpairs[key].location.y * (self.f[0]/FCNST.c),
antpairs[key].wtspos_P22[0][:,0],
antpairs[key].wtspos_P22[0][:,1],
antpairs[key].wts_P22[0],
self.gridu * (self.f[0]/FCNST.c),
self.gridv * (self.f[0]/FCNST.c),
method=method)
grid_illumination_P22 = grid_illumination_P22.reshape(self.gridu.shape)
if normalize:
grid_illumination_P22 = grid_illumination_P22 / NP.sum(grid_illumination_P22)
roi_ind = NP.where(NP.abs(grid_illumination_P22) >= eps)
else:
raise ValueError('Invalid scale option specified. Aborting grid_convolve().')
self.grid_illumination_P22[:,:,i] += grid_illumination_P22
self.grid_Vf_P22[:,:,i] += antpairs[key].crosspol.Vf_P22[i] * grid_illumination_P22
if key in self.interferometers:
if i not in self.interferometers[key]._gridinfo_P22:
self.interferometers[key]._gridinfo_P22 = {} # Create an empty dictionary for each channel to hold grid info
self.interferometers[key]._gridinfo_P22[i]['f'] = self.f[i]
self.interferometers[key]._gridinfo_P22[i]['flag'] = False
self.interferometers[key]._gridinfo_P22[i]['gridxy_ind'] = zip(*roi_ind)
self.interferometers[key].wtspos_P22_scale = antpairs[key].wtspos_P22_scale
if method == 'NN':
self.interferometers[key]._gridinfo_P22[i]['illumination'] = nnval
self.interferometers[key]._gridinfo_P22[i]['Vf'] = antpairs[key].crosspol.Vf_P22[i] * nnval
else:
self.interferometers[key]._gridinfo_P22[i]['illumination'] = grid_illumination_P22[roi_ind]
self.interferometers[key]._gridinfo_P22[i]['Vf'] = antpairs[key].crosspol.Vf_P22[i] * grid_illumination_P22[roi_ind]
elif isinstance(antpairs, list):
# Check if these interferometers are new or old and compatible
for key in range(len(antpairs)):
if isinstance(antpairs[key], Interferometer): # required if antpairs is a dictionary and not instance of InterferometerArray
if antpairs[key].label in self.interferometers:
if unconvolve_existing: # Effects on the grid of interferometers already existing must be removed
if self.interferometers[antpairs[key].label]._gridinfo_P22: # if gridding info is not empty
for i in range(len(self.f)):
self.grid_unconvolve(antpairs[key].label)
else:
raise KeyError('Interferometer {0} already found to exist in the dictionary of interferometers but cannot proceed grid_convolve() without unconvolving first.'.format(antpairs[key].label))
else:
del antpairs[key] # remove the dictionary element since it is not an Interferometer instance
for key in range(len(antpairs)):
if not antpairs[key].crosspol.flag_P22:
for i in range(len(self.f)):
if method == 'NN':
if antpairs[key].wtspos_P22_scale is None:
reflocs = antpairs[key].wtspos_P22[i] + (self.f[i]/FCNST.c) * NP.asarray([antpairs[key].location.x, antpairs[key].location.y]).reshape(1,-1)
inplocs = (self.f[i]/FCNST.c) * NP.hstack((self.gridu.reshape(-1,1), self.gridv.reshape(-1,1)))
ibind, nnval = LKP.lookup_1NN(reflocs, antpairs[key].wts_P22[i], inplocs,
distance_ULIM=distNN*self.f[i]/FCNST.c,
remove_oob=True, tol=tol, maxmatch=maxmatch)[:2]
roi_ind = NP.unravel_index(ibind, self.gridu.shape)
if normalize:
nnval /= NP.sum(nnval)
elif antpairs[key].wtspos_P22_scale == 'scale':
if i == 0: # Determine some parameters only for zeroth channel if scaling is set
reflocs = antpairs[key].wtspos_P22[0] + (self.f[0]/FCNST.c) * NP.asarray([antpairs[key].location.x, antpairs[key].location.y]).reshape(1,-1)
inplocs = (self.f[0]/FCNST.c) * NP.hstack((self.gridu.reshape(-1,1), self.gridv.reshape(-1,1)))
ibind, nnval = LKP.lookup_1NN(reflocs, antpairs[key].wts_P22[0], inplocs,
distance_ULIM=distNN*self.f[0]/FCNST.c,
remove_oob=True, tol=tol, maxmatch=maxmatch)[:2]
roi_ind = NP.unravel_index(ibind, self.gridu.shape)
if normalize:
nnval /= NP.sum(nnval)
else:
raise ValueError('Invalid scale option specified. Aborting grid_convolve().')
self.grid_illumination_P22[roi_ind+(i+NP.zeros(ibind.size, dtype=NP.int),)] += nnval
self.grid_Vf_P22[roi_ind+(i+NP.zeros(ibind.size, dtype=NP.int),)] += antpairs[key].crosspol.Vf_P22[i] * nnval
else:
if antpairs[key].wtspos_P22_scale is None:
grid_illumination_P22 = GRD.conv_grid2d(antpairs[key].location.x * (self.f[i]/FCNST.c),
antpairs[key].location.y * (self.f[i]/FCNST.c),
antpairs[key].wtspos_P22[i][:,0],
antpairs[key].wtspos_P22[i][:,1],
antpairs[key].wts_P22[i],
self.gridu * (self.f[i]/FCNST.c),
self.gridv * (self.f[i]/FCNST.c),
method=method)
grid_illumination_P22 = grid_illumination_P22.reshape(self.gridu.shape)
if normalize:
grid_illumination_P22 = grid_illumination_P22 / NP.sum(grid_illumination_P22)
roi_ind = NP.where(NP.abs(grid_illumination_P22) >= eps)
elif antpairs[key].wtspos_P22_scale == 'scale':
if i == 0: # Determine some parameters only for zeroth channel if scaling is set
grid_illumination_P22 = GRD.conv_grid2d(antpairs[key].location.x * (self.f[0]/FCNST.c),
antpairs[key].location.y * (self.f[0]/FCNST.c),
antpairs[key].wtspos_P22[0][:,0],
antpairs[key].wtspos_P22[0][:,1],
antpairs[key].wts_P22[0],
self.gridu * (self.f[0]/FCNST.c),
self.gridv * (self.f[0]/FCNST.c),
method=method)
grid_illumination_P22 = grid_illumination_P22.reshape(self.gridu.shape)
if normalize:
grid_illumination_P22 = grid_illumination_P22 / NP.sum(grid_illumination_P22)
roi_ind = NP.where(NP.abs(grid_illumination_P22) >= eps)
else:
raise ValueError('Invalid scale option specified. Aborting grid_convolve().')
self.grid_illumination_P22[:,:,i] += grid_illumination_P22
self.grid_Vf_P22[:,:,i] += antpairs[key].crosspol.Vf_P22[i] * grid_illumination_P22
if antpairs[key].label in self.interferometers:
if i not in self.interferometers[key]._gridinfo_P22:
self.interferometers[key]._gridinfo_P22 = {} # Create an empty dictionary for each channel to hold grid info
self.interferometers[antpairs[key].label]._gridinfo_P22[i]['f'] = self.f[i]
self.interferometers[antpairs[key].label]._gridinfo_P22[i]['flag'] = False
self.interferometers[antpairs[key].label]._gridinfo_P22[i]['gridxy_ind'] = zip(*roi_ind)
self.interferometers[key].wtspos_P22_scale = antpairs[key].wtspos_P22_scale
if method == 'NN':
self.interferometers[antpairs[key].label]._gridinfo_P22[i]['illumination'] = nnval
self.interferometers[antpairs[key].label]._gridinfo_P22[i]['Vf'] = antpairs[key].crosspol.Vf_P22[i] * nnval
else:
self.interferometers[antpairs[key].label]._gridinfo_P22[i]['illumination'] = grid_illumination_P22[roi_ind]
self.interferometers[antpairs[key].label]._gridinfo_P22[i]['Vf'] = antpairs[key].crosspol.Vf_P22[i] * grid_illumination_P22[roi_ind]
else:
raise TypeError('antpairs must be an instance of InterferometerArray, a dictionary of Interferometer instances, a list of Interferometer instances or an Interferometer instance.')
else:
self.grid_illumination_P22 = NP.zeros((self.gridu.shape[0],
self.gridu.shape[1],
len(self.f)),
dtype=NP.complex_)
self.grid_Vf_P22 = NP.zeros((self.gridu.shape[0],
self.gridu.shape[1],
len(self.f)), dtype=NP.complex_)
for key in self.interferometers:
if not self.interferometers[key].crosspol.flag_P22:
for i in range(len(self.f)):
if method == 'NN':
if self.interferometers[key].wtspos_P22_scale is None:
reflocs = self.interferometers[key].wtspos_P22[i] + (self.f[i]/FCNST.c) * NP.asarray([self.interferometers[key].location.x, self.interferometers[key].location.y]).reshape(1,-1)
inplocs = (self.f[i]/FCNST.c) * NP.hstack((self.gridu.reshape(-1,1), self.gridv.reshape(-1,1)))
ibind, nnval = LKP.lookup_1NN(reflocs, self.interferometers[key].wts_P22[i], inplocs,
distance_ULIM=distNN*self.f[i]/FCNST.c,
remove_oob=True, tol=tol, maxmatch=maxmatch)[:2]
roi_ind = NP.unravel_index(ibind, self.gridu.shape)
if normalize:
nnval /= NP.sum(nnval)
elif self.interferometers[key].wtspos_P22_scale == 'scale':
if i == 0: # Determine some parameters only for zeroth channel if scaling is set
reflocs = self.interferometers[key].wtspos_P22[0] + (self.f[0]/FCNST.c) * NP.asarray([self.interferometers[key].location.x, self.interferometers[key].location.y]).reshape(1,-1)
inplocs = (self.f[0]/FCNST.c) * NP.hstack((self.gridu.reshape(-1,1), self.gridv.reshape(-1,1)))
ibind, nnval = LKP.lookup_1NN(reflocs, self.interferometers[key].wts_P22[0], inplocs,
distance_ULIM=distNN*self.f[0]/FCNST.c,
remove_oob=True, tol=tol, maxmatch=maxmatch)[:2]
roi_ind = NP.unravel_index(ibind, self.gridu.shape)
if normalize:
nnval /= NP.sum(nnval)
else:
raise ValueError('Invalid scale option specified. Aborting grid_convolve().')
self.grid_illumination_P22[roi_ind+(i+NP.zeros(ibind.size, dtype=NP.int),)] += nnval
self.grid_Vf_P22[roi_ind+(i+NP.zeros(ibind.size, dtype=NP.int),)] += self.interferometers[key].crosspol.Vf_P22[i] * nnval
else:
if self.interferometers[key].wtspos_P22_scale is None:
grid_illumination_P22 = GRD.conv_grid2d(self.interferometers[key].location.x * (self.f[i]/FCNST.c),
self.interferometers[key].location.y * (self.f[i]/FCNST.c),
self.interferometers[key].wtspos_P22[i][:,0],
self.interferometers[key].wtspos_P22[i][:,1],
self.interferometers[key].wts_P22[i],
self.gridu * (self.f[i]/FCNST.c),
self.gridv * (self.f[i]/FCNST.c),
method=method)
grid_illumination_P22 = grid_illumination_P22.reshape(self.gridu.shape)
if normalize:
grid_illumination_P22 = grid_illumination_P22 / NP.sum(grid_illumination_P22)
roi_ind = NP.where(NP.abs(grid_illumination_P22) >= eps)
elif self.interferometers[key].wtspos_P22_scale == 'scale':
if i == 0:
grid_illumination_P22 = GRD.conv_grid2d(self.interferometers[key].location.x * (self.f[0]/FCNST.c),
self.interferometers[key].location.y * (self.f[0]/FCNST.c),
self.interferometers[key].wtspos_P22[0][:,0],
self.interferometers[key].wtspos_P22[0][:,1],
self.interferometers[key].wts_P22[0],
self.gridu * (self.f[0]/FCNST.c),
self.gridv * (self.f[0]/FCNST.c),
method=method)
grid_illumination_P22 = grid_illumination_P22.reshape(self.gridu.shape)
if normalize:
grid_illumination_P22 = grid_illumination_P22 / NP.sum(grid_illumination_P22)
roi_ind = NP.where(NP.abs(grid_illumination_P22) >= eps)
else:
raise ValueError('Invalid scale option specified. Aborting grid_convolve().')
self.grid_illumination_P22[:,:,i] += grid_illumination_P22
self.grid_Vf_P22[:,:,i] += self.interferometers[key].crosspol.Vf_P22[i] * grid_illumination_P22
self.interferometers[key]._gridinfo_P22[i] = {} # Create a nested dictionary to hold channel info
self.interferometers[key]._gridinfo_P22[i]['f'] = self.f[i]
self.interferometers[key]._gridinfo_P22[i]['flag'] = False
self.interferometers[key]._gridinfo_P22[i]['gridxy_ind'] = zip(*roi_ind)
if method == 'NN':
self.interferometers[key]._gridinfo_P22[i]['illumination'] = nnval
self.interferometers[key]._gridinfo_P22[i]['Vf'] = self.interferometers[key].crosspol.Vf_P22[i] * nnval
else:
self.interferometers[key]._gridinfo_P22[i]['illumination'] = grid_illumination_P22[roi_ind]
self.interferometers[key]._gridinfo_P22[i]['Vf'] = self.interferometers[key].crosspol.Vf_P22[i] * grid_illumination_P22[roi_ind]
############################################################################
def grid_unconvolve(self, antpairs, pol=None):
"""
------------------------------------------------------------------------
[Needs to be re-written]
Routine to de-project the visibility illumination pattern and the
visibilities on the grid. It can operate on the entire interferometer
array or incrementally de-project the visibilities and illumination
patterns of specific antenna pairs from an already existing grid.
Inputs:
antpairs [instance of class InterferometerArray, single instance or
list of instances of class Interferometer, or a dictionary
holding instances of class Interferometer] If a dictionary
is provided, the keys should be the interferometer labels
and the values should be instances of class Interferometer.
If a list is provided, it should be a list of valid
instances of class Interferometer. These instance(s) of
class Interferometer will be merged to the existing grid
contained in the instance of InterferometerArray class. If
any of the interferoemters are not found to be in the
already existing set of interferometers, an exception is
raised accordingly and code execution stops.
pol [String] The polarization to be gridded. Can be set to
'P11', 'P12', 'P21', or 'P22'. If set to None, gridding for
all polarizations is performed. Default=None.
------------------------------------------------------------------------
"""
try:
antpairs
except NameError:
raise NameError('No antenna pair(s) supplied.')
if (pol is None) or (pol == 'P11'):
if isinstance(ants, (Interferometer, str)):
antpairs = [antpairs]
if isinstance(antpairs, (dict, InterferometerArray)):
# Check if these interferometers are new or old and compatible
for key in antpairs:
if isinstance(antpairs[key], Interferometer): # required if antpairs is a dictionary and not instance of InterferometerArray
if key in self.interferometers:
if self.interferometers[key]._gridinfo_P11: # if gridding info is not empty
for i in range(len(self.f)):
xind, yind = zip(*self.interferometers[key]._gridinfo_P11[i]['gridxy_ind'])
self.grid_illumination_P11[xind, yind, i] -= self.interferometers[key]._gridinfo_P11[i]['illumination']
self.grid_Vf_P11[xind, yind, i] -= self.interferometers[key]._gridinfo_P11[i]['Vf']
self.interferometers[key]._gridinfo_P11 = {}
else:
raise KeyError('Interferometer {0} not found to exist in the dictionary of interferometers.'.format(antpairs[key].label))
elif isinstance(antpairs, list):
# Check if these interferometers are new or old and compatible
for key in range(len(antpairs)):
if isinstance(antpairs[key], Interferometer): # required if antpairs is a dictionary and not instance of InterferometerArray
if antpairs[key].label in self.interferometers:
if self.interferometers[antpairs[key].label]._gridinfo_P11: # if gridding info is not empty
for i in range(len(self.f)):
xind, yind = zip(*self.interferometers[antpairs[key].label]._gridinfo_P11[i]['gridxy_ind'])
self.grid_illumination_P11[xind, yind, i] -= self.interferometers[antpairs[key].label]._gridinfo_P11[i]['illumination']
self.grid_Vf_P11[xind, yind, i] -= self.interferometers[antpairs[key].label]._gridinfo_P11[i]['Vf']
self.interferometers[antpairs[key].label]._gridinfo_P11 = {}
else:
raise KeyError('Interferometer {0} not found to exist in the dictionary of interferometers.'.format(antpairs[key].label))
elif isinstance(antpairs[key], str):
if antpairs[key] in self.interferometers:
if self.interferometers[antpairs[key]]._gridinfo_P11: # if gridding info is not empty
for i in range(len(self.f)):
xind, yind = zip(*self.interferometers[antpairs[key]]._gridinfo_P11[i]['gridxy_ind'])
self.grid_illumination_P11[xind, yind, i] -= self.interferometers[antpairs[key]]._gridinfo_P11[i]['illumination']
self.grid_Vf_P11[xind, yind, i] -= self.interferometers[antpairs[key]]._gridinfo_P11[i]['Vf']
self.interferometers[antpairs[key]]._gridinfo_P11 = {}
else:
raise KeyError('Interferometer {0} not found to exist in the dictionary of interferometers.'.format(antpairs[key]))
else:
raise TypeError('antpairs must be an instance of class InterferometerArray, a list of instances of class Interferometer, a dictionary of instances of class Interferometer or a list of antenna labels.')
else:
raise TypeError('antpairs must be an instance of InterferometerArray, a dictionary of Interferometer instances, a list of Interferometer instances, an Interferometer instance, or a list of antenna labels.')
if (pol is None) or (pol == 'P22'):
if isinstance(ants, (Interferometer, str)):
antpairs = [antpairs]
if isinstance(antpairs, (dict, InterferometerArray)):
# Check if these interferometers are new or old and compatible
for key in antpairs:
if isinstance(antpairs[key], Interferometer): # required if antpairs is a dictionary and not instance of InterferometerArray
if key in self.interferometers:
if self.interferometers[key]._gridinfo_P22: # if gridding info is not empty
for i in range(len(self.f)):
xind, yind = zip(*self.interferometers[key]._gridinfo_P22[i]['gridxy_ind'])
self.grid_illumination_P22[xind, yind, i] -= self.interferometers[key]._gridinfo_P22[i]['illumination']
self.grid_Vf_P22[xind, yind, i] -= self.interferometers[key]._gridinfo_P22[i]['Vf']
self.interferometers[key]._gridinfo_P22 = {}
else:
raise KeyError('Interferometer {0} not found to exist in the dictionary of interferometers.'.format(antpairs[key].label))
elif isinstance(antpairs, list):
# Check if these interferometers are new or old and compatible
for key in range(len(antpairs)):
if isinstance(antpairs[key], Interferometer): # required if antpairs is a dictionary and not instance of InterferometerArray
if antpairs[key].label in self.interferometers:
if self.interferometers[antpairs[key].label]._gridinfo_P22: # if gridding info is not empty
for i in range(len(self.f)):
xind, yind = zip(*self.interferometers[antpairs[key].label]._gridinfo_P22[i]['gridxy_ind'])
self.grid_illumination_P22[xind, yind, i] -= self.interferometers[antpairs[key].label]._gridinfo_P22[i]['illumination']
self.grid_Vf_P22[xind, yind, i] -= self.interferometers[antpairs[key].label]._gridinfo_P22[i]['Vf']
self.interferometers[antpairs[key].label]._gridinfo_P22 = {}
else:
raise KeyError('Interferometer {0} not found to exist in the dictionary of interferometers.'.format(antpairs[key].label))
elif isinstance(antpairs[key], str):
if antpairs[key] in self.interferometers:
if self.interferometers[antpairs[key]]._gridinfo_P22: # if gridding info is not empty
for i in range(len(self.f)):
xind, yind = zip(*self.interferometers[antpairs[key]]._gridinfo_P22[i]['gridxy_ind'])
self.grid_illumination_P22[xind, yind, i] -= self.interferometers[antpairs[key]]._gridinfo_P22[i]['illumination']
self.grid_Vf_P22[xind, yind, i] -= self.interferometers[antpairs[key]]._gridinfo_P22[i]['Vf']
self.interferometers[antpairs[key]]._gridinfo_P22 = {}
else:
raise KeyError('Interferometer {0} not found to exist in the dictionary of interferometers.'.format(antpairs[key]))
else:
raise TypeError('antpairs must be an instance of class InterferometerArray, a list of instances of class Interferometer, a dictionary of instances of class Interferometer or a list of antenna labels.')
else:
raise TypeError('antpairs must be an instance of InterferometerArray, a dictionary of Interferometer instances, a list of Interferometer instances, an Interferometer instance, or a list of antenna labels.')
if (pol is None) or (pol == 'P12'):
if isinstance(ants, (Interferometer, str)):
antpairs = [antpairs]
if isinstance(antpairs, (dict, InterferometerArray)):
# Check if these interferometers are new or old and compatible
for key in antpairs:
if isinstance(antpairs[key], Interferometer): # required if antpairs is a dictionary and not instance of InterferometerArray
if key in self.interferometers:
if self.interferometers[key]._gridinfo_P12: # if gridding info is not empty
for i in range(len(self.f)):
xind, yind = zip(*self.interferometers[key]._gridinfo_P12[i]['gridxy_ind'])
self.grid_illumination_P12[xind, yind, i] -= self.interferometers[key]._gridinfo_P12[i]['illumination']
self.grid_Vf_P12[xind, yind, i] -= self.interferometers[key]._gridinfo_P12[i]['Vf']
self.interferometers[key]._gridinfo_P12 = {}
else:
raise KeyError('Interferometer {0} not found to exist in the dictionary of interferometers.'.format(antpairs[key].label))
elif isinstance(antpairs, list):
# Check if these interferometers are new or old and compatible
for key in range(len(antpairs)):
if isinstance(antpairs[key], Interferometer): # required if antpairs is a dictionary and not instance of InterferometerArray
if antpairs[key].label in self.interferometers:
if self.interferometers[antpairs[key].label]._gridinfo_P12: # if gridding info is not empty
for i in range(len(self.f)):
xind, yind = zip(*self.interferometers[antpairs[key].label]._gridinfo_P12[i]['gridxy_ind'])
self.grid_illumination_P12[xind, yind, i] -= self.interferometers[antpairs[key].label]._gridinfo_P12[i]['illumination']
self.grid_Vf_P12[xind, yind, i] -= self.interferometers[antpairs[key].label]._gridinfo_P12[i]['Vf']
self.interferometers[antpairs[key].label]._gridinfo_P12 = {}
else:
raise KeyError('Interferometer {0} not found to exist in the dictionary of interferometers.'.format(antpairs[key].label))
elif isinstance(antpairs[key], str):
if antpairs[key] in self.interferometers:
if self.interferometers[antpairs[key]]._gridinfo_P12: # if gridding info is not empty
for i in range(len(self.f)):
xind, yind = zip(*self.interferometers[antpairs[key]]._gridinfo_P12[i]['gridxy_ind'])
self.grid_illumination_P12[xind, yind, i] -= self.interferometers[antpairs[key]]._gridinfo_P12[i]['illumination']
self.grid_Vf_P12[xind, yind, i] -= self.interferometers[antpairs[key]]._gridinfo_P12[i]['Vf']
self.interferometers[antpairs[key]]._gridinfo_P12 = {}
else:
raise KeyError('Interferometer {0} not found to exist in the dictionary of interferometers.'.format(antpairs[key]))
else:
raise TypeError('antpairs must be an instance of class InterferometerArray, a list of instances of class Interferometer, a dictionary of instances of class Interferometer or a list of antenna labels.')
else:
raise TypeError('antpairs must be an instance of InterferometerArray, a dictionary of Interferometer instances, a list of Interferometer instances, an Interferometer instance, or a list of antenna labels.')
if (pol is None) or (pol == 'P21'):
if isinstance(ants, (Interferometer, str)):
antpairs = [antpairs]
if isinstance(antpairs, (dict, InterferometerArray)):
# Check if these interferometers are new or old and compatible
for key in antpairs:
if isinstance(antpairs[key], Interferometer): # required if antpairs is a dictionary and not instance of InterferometerArray
if key in self.interferometers:
if self.interferometers[key]._gridinfo_P21: # if gridding info is not empty
for i in range(len(self.f)):
xind, yind = zip(*self.interferometers[key]._gridinfo_P21[i]['gridxy_ind'])
self.grid_illumination_P21[xind, yind, i] -= self.interferometers[key]._gridinfo_P21[i]['illumination']
self.grid_Vf_P21[xind, yind, i] -= self.interferometers[key]._gridinfo_P21[i]['Vf']
self.interferometers[key]._gridinfo_P21 = {}
else:
raise KeyError('Interferometer {0} not found to exist in the dictionary of interferometers.'.format(antpairs[key].label))
elif isinstance(antpairs, list):
# Check if these interferometers are new or old and compatible
for key in range(len(antpairs)):
if isinstance(antpairs[key], Interferometer): # required if antpairs is a dictionary and not instance of InterferometerArray
if antpairs[key].label in self.interferometers:
if self.interferometers[antpairs[key].label]._gridinfo_P21: # if gridding info is not empty
for i in range(len(self.f)):
xind, yind = zip(*self.interferometers[antpairs[key].label]._gridinfo_P21[i]['gridxy_ind'])
self.grid_illumination_P21[xind, yind, i] -= self.interferometers[antpairs[key].label]._gridinfo_P21[i]['illumination']
self.grid_Vf_P21[xind, yind, i] -= self.interferometers[antpairs[key].label]._gridinfo_P21[i]['Vf']
self.interferometers[antpairs[key].label]._gridinfo_P21 = {}
else:
raise KeyError('Interferometer {0} not found to exist in the dictionary of interferometers.'.format(antpairs[key].label))
elif isinstance(antpairs[key], str):
if antpairs[key] in self.interferometers:
if self.interferometers[antpairs[key]]._gridinfo_P21: # if gridding info is not empty
for i in range(len(self.f)):
xind, yind = zip(*self.interferometers[antpairs[key]]._gridinfo_P21[i]['gridxy_ind'])
self.grid_illumination_P21[xind, yind, i] -= self.interferometers[antpairs[key]]._gridinfo_P21[i]['illumination']
self.grid_Vf_P21[xind, yind, i] -= self.interferometers[antpairs[key]]._gridinfo_P21[i]['Vf']
self.interferometers[antpairs[key]]._gridinfo_P21 = {}
else:
raise KeyError('Interferometer {0} not found to exist in the dictionary of interferometers.'.format(antpairs[key]))
else:
raise TypeError('antpairs must be an instance of class InterferometerArray, a list of instances of class Interferometer, a dictionary of instances of class Interferometer or a list of antenna labels.')
else:
raise TypeError('antpairs must be an instance of InterferometerArray, a dictionary of Interferometer instances, a list of Interferometer instances, an Interferometer instance, or a list of antenna labels.')
############################################################################
def update_flags(self, dictflags=None, stack=True, verify=False):
"""
------------------------------------------------------------------------
Updates all flags in the interferometer array followed by any flags that
need overriding through inputs of specific flag information
Inputs:
dictflags [dictionary] contains flag information overriding after
default flag updates are determined. Baseline based flags
are given as further dictionaries with each under under a
key which is the same as the interferometer label. Flags for
each baseline are specified as a dictionary holding boolean
flags for each of the four cross-polarizations which are
stored under keys 'P11', 'P12', 'P21', and 'P22'. An absent
key just means it is not a part of the update. Flag
information under each baseline must be of same type as
input parameter flags in member function update_flags() of
class CrossPolInfo
stack [boolean] If True (default), appends the updated flag to the
end of the stack of flags as a function of timestamp. If
False, updates the last flag in the stack with the updated
flag and does not append
verify [boolean] If True, verify and update the flags, if necessary.
Visibilities are checked for NaN values and if found, the
flag in the corresponding polarization is set to True.
Default=False.
------------------------------------------------------------------------
"""
for label in self.interferometers:
self.interferometers[label].update_flags(stack=stack, verify=verify)
if dictflags is not None: # Performs flag overriding. Use stack=False
if not isinstance(dictflags, dict):
raise TypeError('Input parameter dictflags must be a dictionary')
for label in dictflags:
if label in self.interferometers:
self.interferometers[label].update_flags(flags=dictflags[label], stack=False, verify=True)
############################################################################
def update(self, interferometer_level_updates=None,
antenna_level_updates=None, do_correlate=None, parallel=False,
nproc=None, verbose=False):
"""
------------------------------------------------------------------------
Updates the interferometer array instance with newer attribute values.
Can also be used to add and/or remove interferometers with/without
affecting the existing grid.
Inputs:
antenna_level_updates
[Dictionary] Provides update information on individual
antennas and antenna array as a whole. Should be of same
type as input parameter updates in member function update()
of class AntennaArray. It consists of information updates
under the following principal keys:
'antenna_array': Consists of updates for the AntennaArray
instance. This is a dictionary which consists of
the following keys:
'timestamp' Unique identifier of the time
series. It is optional to set this
to a scalar. If not given, no
change is made to the existing
timestamp attribute
'do_grid' [boolean] If set to True, create
or recreate a grid. To be
specified when the antenna
locations are updated.
'antennas': Holds a list of dictionaries consisting of
updates for individual antennas. Each element
in the list contains update for one antenna.
For each of these dictionaries, one of the keys
is 'label' which indicates an antenna label. If
absent, the code execution stops by throwing an
exception. The other optional keys and the
information they hold are listed below:
'action' [String scalar] Indicates the type
of update operation. 'add' adds
the Antenna instance to the
AntennaArray instance. 'remove'
removes the antenna from the
antenna array instance. 'modify'
modifies the antenna attributes in
the antenna array instance. This
key has to be set. No default.
'grid_action' [Boolean] If set to True, will
apply the grdding operations
(grid(), grid_convolve(), and
grid_unconvolve()) appropriately
according to the value of the
'action' key. If set to None or
False, gridding effects will
remain unchanged. Default=None
(=False).
'antenna' [instance of class Antenna]
Updated Antenna class instance.
Can work for action key 'remove'
even if not set (=None) or set to
an empty string '' as long as
'label' key is specified.
'gridpol' [Optional. String scalar]
Initiates the specified action on
polarization 'P1' or 'P2'. Can be
set to 'P1' or 'P2'. If not
provided (=None), then the
specified action applies to both
polarizations. Default = None.
'Et' [Optional. Dictionary] Complex
Electric field time series under
two polarizations which are under
keys 'P1' and 'P2'. Is used only
if set and if 'action' key value
is set to 'modify'.
Default = None.
'stack' [boolean] If True (default),
appends the updated flag and data
to the end of the stack as a
function of timestamp. If False,
updates the last flag and data in
the stack and does not append
't' [Optional. Numpy array] Time axis
of the time series. Is used only
if set and if 'action' key value
is set to 'modify'. Default=None.
'timestamp' [Optional. Scalar] Unique
identifier of the time series. Is
used only if set and if 'action'
key value is set to 'modify'.
Default = None.
'location' [Optional. instance of GEOM.Point
class]
Antenna location in the local ENU
coordinate system. Used only if
set and if 'action' key value is
set to 'modify'. Default = None.
'aperture' [instance of class
APR.Aperture] aperture
information for the antenna. Read
docstring of class
Aperture for details
'wtsinfo' [Optional. Dictionary]
See description in Antenna class
member function update(). Is used
only if set and if 'action' key
value is set to 'modify'.
Default = None.
'flags' [Optional. Dictionary] holds
boolean flags for each of the 2
polarizations which are stored
under keys 'P1' and 'P2'.
Default=None means no updates for
flags. If True, that polarization
will be flagged. If not set
(=None), the previous or default
flag status will continue to
apply. If set to False, the
antenna status will be updated to
become unflagged.
'gridfunc_freq'
[Optional. String scalar] Read the
description of inputs to Antenna
class member function update(). If
set to None (not provided), this
attribute is determined based on
the size of wtspos_P1 and
wtspos_P2. It is applicable only
when 'action' key is set to
'modify'. Default = None.
'delaydict' [Dictionary] contains information
on delay compensation to be
applied to the fourier transformed
electric fields under each
polarization which are stored
under keys 'P1' and 'P2'. Default
is None (no delay compensation to
be applied). Refer to the
docstring of member function
delay_compensation() of class
PolInfo for more details.
'ref_freq' [Optional. Scalar] Positive value
(in Hz) of reference frequency
(used if gridfunc_freq is set to
'scale') at which wtspos_P1 and
wtspos_P2 in wtsinfo_P1 and
wtsinfo_P2, respectively, are
provided. If set to None, the
reference frequency already set in
antenna array instance remains
unchanged. Default = None.
'pol_type' [Optional. String scalar] 'Linear'
or 'Circular'. Used only when
action key is set to 'modify'. If
not provided, then the previous
value remains in effect.
Default = None.
'norm_wts' [Optional. Boolean] Default=False.
If set to True, the gridded
weights are divided by the sum of
weights so that the gridded
weights add up to unity. This is
used only when grid_action keyword
is set when action keyword is set
to 'add' or 'modify'
'gridmethod' [Optional. String] Indicates
gridding method. It accepts the
following values 'NN' (nearest
neighbour), 'BL' (Bi-linear
interpolation), and'CS' (Cubic
Spline interpolation).
Default='NN'
'distNN' [Optional. Scalar] Indicates the
upper bound on distance for a
nearest neighbour search if the
value of 'gridmethod' is set to
'NN'. The units are of physical
distance, the same as what is
used for antenna locations.
Default = NP.inf
'maxmatch' [scalar] A positive value
indicating maximum number of input
locations in the antenna grid to
be assigned. Default = None. If
set to None, all the antenna array
grid elements specified are
assigned values for each antenna.
For instance, to have only one
antenna array grid element to be
populated per antenna, use
maxmatch=1.
'tol' [scalar] If set, only lookup data
with abs(val) > tol will be
considered for nearest neighbour
lookup. Default = None implies
all lookup values will be
considered for nearest neighbour
determination. tol is to be
interpreted as a minimum value
considered as significant in the
lookup table.
interferometer_level_updates
[Dictionary] Consists of information updates for individual
interferoemters and interferometer array as a whole under
the following principal keys:
'interferometer_array': Consists of updates for the
InterferometerArray instance. This is a
dictionary which consists of the following keys:
'timestamp': Unique identifier of the time
series. It is optional to set this to a
scalar. If not given, no change is made
to the existing timestamp attribute
'interferometers': Holds a list of dictionaries where
element consists of updates for individual
interferometers. Each dictionary must contain a
key 'label' which indicates an interferometer
label. If absent, the code execution stops by
throwing an exception. The other optional keys
and the information they hold are listed below:
'action' [String scalar] Indicates the type
of update operation. 'add' adds
the Interferometer instance to the
InterferometerArray instance.
'remove' removes the
interferometer from the
interferometer array instance.
'modify' modifies the
interferometer attributes in the
interferometer array instance.
This key has to be set. No default
'grid_action' [Boolean] If set to True, will
apply the grdding operations
(grid(), grid_convolve(), and
grid_unconvolve()) appropriately
according to the value of the
'action' key. If set to None or
False, gridding effects will
remain unchanged. Default=None
(=False).
'interferometer'
[instance of class Interferometer]
Updated Interferometer class
instance. Can work for action key
'remove' even if not set (=None)
or set to an empty string '' as
long as 'label' key is specified.
'gridpol' [Optional. String scalar]
Initiates the specified action on
polarization 'P11' or 'P22'. Can
be set to 'P11' or 'P22'. If not
provided (=None), then the
specified action applies to both
polarizations. Default = None.
'Vt' [Optional. Dictionary] Complex
visibility time series for each
of the four cross-polarization
specified as keys 'P11', 'P12',
'P21' and 'P22'. Is used only if
set and if 'action' key value is
set to 'modify'. Default = None.
't' [Optional. Numpy array] Time axis
of the time series. Is used only
if set and if 'action' key value
is set to 'modify'. Default=None.
'timestamp' [Optional. Scalar] Unique
identifier of the time series. Is
used only if set and if 'action'
key value is set to 'modify'.
Default = None.
'stack' [boolean] If True (default),
appends the updated flag and data
to the end of the stack as a
function of timestamp. If False,
updates the last flag and data in
the stack and does not append
'location' [Optional. instance of GEOM.Point
class] Interferometer location in
the local ENU coordinate system.
Used only if set and if 'action'
key value is set to 'modify'.
Default=None.
'aperture' [instance of class
APR.Aperture] aperture
information for the
interferometer. Read docstring of
class Aperture for details
'wtsinfo' [Optional. Dictionary] See
description in Interferometer
class member function update().
Is used only if set and if
'action' key value is set to
'modify'. Default = None.
'flags' [Optional. Dictionary] holds
boolean flags for each of the 4
cross-polarizations which are
stored under keys 'P11', 'P12',
'P21' and 'P2'. Default=None means
no updates for flags. If True,
that polarization will be flagged.
If not set (=None), the previous
or default flag status will
continue to apply. If set to
False, the antenna status will be
updated to become unflagged.
'gridfunc_freq'
[Optional. String scalar] Read the
description of inputs to
Interferometer class member
function update(). If set to None
(not provided), this attribute is
determined based on the size of
wtspos under each polarization.
It is applicable only when
'action' key is set to 'modify'.
Default = None.
'ref_freq' [Optional. Scalar] Positive value
(in Hz) of reference frequency
(used if gridfunc_freq is set to
'scale') at which wtspos in
wtsinfo are provided. If set to
None, the reference frequency
already set in interferometer
array instance remains unchanged.
Default = None.
'pol_type' [Optional. String scalar] 'Linear'
or 'Circular'. Used only when
action key is set to 'modify'. If
not provided, then the previous
value remains in effect.
Default = None.
'norm_wts' [Optional. Boolean] Default=False.
If set to True, the gridded
weights are divided by the sum of
weights so that the gridded
weights add up to unity. This is
used only when grid_action keyword
is set when action keyword is set
to 'add' or 'modify'
'gridmethod' [Optional. String] Indicates
gridding method. It accepts the
following values 'NN' (nearest
neighbour), 'BL' (Bi-linear
interpolation), and'CS' (Cubic
Spline interpolation).
Default='NN'
'distNN' [Optional. Scalar] Indicates the
upper bound on distance for a
nearest neighbour search if the
value of 'gridmethod' is set to
'NN'. The units are of physical
distance, the same as what is
used for interferometer locations.
Default = NP.inf
'maxmatch' [scalar] A positive value
indicating maximum number of input
locations in the interferometer
grid to be assigned. Default=None.
If set to None, all the
interferometer array grid elements
specified are assigned values for
each interferometer. For instance,
to have only one interferometer
array grid element to be populated
per interferometer, use maxmatch=1
'tol' [scalar] If set, only lookup data
with abs(val) > tol will be
considered for nearest neighbour
lookup. Default = None implies
all lookup values will be
considered for nearest neighbour
determination. tol is to be
interpreted as a minimum value
considered as significant in the
lookup table.
do_correlate
[string] Indicates whether correlation operation is to be
performed after updates. Accepted values are 'FX' (for FX
operation) and 'XF' (for XF operation). Default=None means
no correlating operation is to be performed after updates.
parallel [boolean] specifies if parallelization is to be invoked.
False (default) means only serial processing
nproc [integer] specifies number of independent processes to
spawn. Default = None, means automatically determines the
number of process cores in the system and use one less than
that to avoid locking the system for other processes.
Applies only if input parameter 'parallel' (see above) is
set to True. If nproc is set to a value more than the number
of process cores in the system, it will be reset to number
of process cores in the system minus one to avoid locking
the system out for other processes
verbose [Boolean] Default = False. If set to True, prints some
diagnotic or progress messages.
------------------------------------------------------------------------
"""
if antenna_level_updates is not None:
if verbose:
print 'Updating antenna array...'
self.antenna_array.update(updates=antenna_level_updates)
if verbose:
print 'Updated antenna array. Refreshing interferometer flags from antenna flags...'
self.update_flags(dictflags=None, stack=False, verify=False) # Update interferometer flags using antenna level flags
if verbose:
print 'Refreshed interferometer flags. Refreshing antenna pairs...'
self.refresh_antenna_pairs()
if verbose:
print 'Refreshed antenna pairs...'
if verbose:
print 'Updating interferometer array ...'
self.timestamp = self.antenna_array.timestamp
self.t = self.antenna_array.t
if interferometer_level_updates is not None:
if not isinstance(interferometer_level_updates, dict):
raise TypeError('Input parameter interferometer_level_updates must be a dictionary')
if 'interferometers' in interferometer_level_updates:
if not isinstance(interferometer_level_updates['interferometers'], list):
interferometer_level_updates['interferometers'] = [interferometer_level_updates['interferometers']]
if parallel:
list_of_interferometer_updates = []
list_of_interferometers = []
if verbose:
progress = PGB.ProgressBar(widgets=[PGB.Percentage(), PGB.Bar(marker='-', left=' |', right='| '), PGB.Counter(), '/{0:0d} Interferometers '.format(len(interferometer_level_updates['interferometers'])), PGB.ETA()], maxval=len(interferometer_level_updates['interferometers'])).start()
loopcount = 0
for dictitem in interferometer_level_updates['interferometers']:
if not isinstance(dictitem, dict):
raise TypeError('Interferometer_Level_Updates to {0} instance should be provided in the form of a list of dictionaries.'.format(self.__class__.__name__))
elif 'label' not in dictitem:
raise KeyError('No interferometer label specified in the dictionary item to be updated.')
if 'action' not in dictitem:
raise KeyError('No action specified for update. Action key should be set to "add", "remove" or "modify".')
elif dictitem['action'] == 'add':
if dictitem['label'] in self.interferometers:
if verbose:
print 'Interferometer {0} for adding already exists in current instance of {1}. Skipping over to the next item to be updated.'.format(dictitem['label'], self.__class__.__name__)
else:
if verbose:
print 'Adding interferometer {0}...'.format(dictitem['label'])
self.add_interferometers(dictitem['interferometer'])
if 'grid_action' in dictitem:
self.grid_convolve(pol=dictitem['gridpol'], antpairs=dictitem['interferometer'], unconvolve_existing=False)
elif dictitem['action'] == 'remove':
if dictitem['label'] not in self.interferometers:
if verbose:
print 'Interferometer {0} for removal not found in current instance of {1}. Skipping over to the next item to be updated.'.format(dictitem['label'], self.__class__.__name__)
else:
if verbose:
print 'Removing interferometer {0}...'.format(dictitem['label'])
if 'grid_action' in dictitem:
self.grid_unconvolve(dictitem['label'], dictitem['gridpol'])
self.remove_interferometers(dictitem['label'])
elif dictitem['action'] == 'modify':
if dictitem['label'] not in self.interferometers:
if verbose:
print 'Interferometer {0} for modification not found in current instance of {1}. Skipping over to the next item to be updated.'.format(dictitem['label'], self.__class__.__name__)
else:
if verbose:
print 'Modifying interferometer {0}...'.format(dictitem['label'])
if 'Vt' not in dictitem: dictitem['Vt']=None
if 't' not in dictitem: dictitem['t']=None
if 'timestamp' not in dictitem: dictitem['timestamp']=None
if 'location' not in dictitem: dictitem['location']=None
if 'wtsinfo' not in dictitem: dictitem['wtsinfo']=None
if 'flags' not in dictitem: dictitem['flags']=None
if 'stack' not in dictitem: dictitem['stack']=False
if 'gridfunc_freq' not in dictitem: dictitem['gridfunc_freq']=None
if 'ref_freq' not in dictitem: dictitem['ref_freq']=None
if 'pol_type' not in dictitem: dictitem['pol_type']=None
if 'norm_wts' not in dictitem: dictitem['norm_wts']=False
if 'gridmethod' not in dictitem: dictitem['gridmethod']='NN'
if 'distNN' not in dictitem: dictitem['distNN']=NP.inf
if 'maxmatch' not in dictitem: dictitem['maxmatch']=None
if 'tol' not in dictitem: dictitem['tol']=None
if 'do_correlate' not in dictitem: dictitem['do_correlate']=None
if 'aperture' not in dictitem: dictitem['aperture']=None
if not parallel:
# self.interferometers[dictitem['label']].update_old(dictitem['label'], dictitem['Vt'], dictitem['t'], dictitem['timestamp'], dictitem['location'], dictitem['wtsinfo'], dictitem['flags'], dictitem['gridfunc_freq'], dictitem['ref_freq'], dictitem['do_correlate'], verbose)
self.interferometers[dictitem['label']].update(dictitem, verbose)
else:
list_of_interferometers += [self.interferometers[dictitem['label']]]
list_of_interferometer_updates += [dictitem]
if 'gric_action' in dictitem:
self.grid_convolve(pol=dictitem['gridpol'], antpairs=dictitem['interferometer'], unconvolve_existing=True, normalize=dictitem['norm_wts'], method=dictitem['gridmethod'], distNN=dictitem['distNN'], tol=dictitem['tol'], maxmatch=dictitem['maxmatch'])
else:
raise ValueError('Update action should be set to "add", "remove" or "modify".')
if verbose:
progress.update(loopcount+1)
loopcount += 1
if verbose:
progress.finish()
if parallel:
if nproc is None:
nproc = max(MP.cpu_count()-1, 1)
else:
nproc = min(nproc, max(MP.cpu_count()-1, 1))
pool = MP.Pool(processes=nproc)
updated_interferometers = pool.map(unwrap_interferometer_update, IT.izip(list_of_interferometers, list_of_interferometer_updates))
pool.close()
pool.join()
# Necessary to make the returned and updated interferometers current, otherwise they stay unrelated
for interferometer in updated_interferometers:
self.interferometers[interferometer.label] = interferometer
del updated_interferometers
################################################################################
class Image(object):
"""
----------------------------------------------------------------------------
Class to manage image information and processing pertaining to the class
holding antenna array or interferometer array information.
[Docstring is outdated. Needs to be updated definitely]
Attributes:
timestamp: [Scalar] String or float representing the timestamp for the
current attributes
f: [vector] Frequency channels (in Hz)
f0: [Scalar] Positive value for the center frequency in Hz.
autocorr_wts_vuf
[dictionary] dictionary with polarization keys 'P1' and 'P2.
Under each key is a matrix of size nt x nv x nu x nchan
autocorr_data_vuf
[dictionary] dictionary with polarization keys 'P1' and 'P2.
Under each key is a matrix of size nt x nv x nu x nchan
where nt=1, nt=n_timestamps, or nt=n_tavg if datapool is set
to 'current', 'stack' or 'avg' respectively
gridx_P1 [Numpy array] x-locations of the grid lattice for P1
polarization
gridy_P1 [Numpy array] y-locations of the grid lattice for P1
polarization
gridx_P2 [Numpy array] x-locations of the grid lattice for P2
polarization
gridy_P2 [Numpy array] y-locations of the grid lattice for P2
polarization
grid_illumination_P1
[Numpy array] Electric field illumination for P1 polarization
on the grid. Could be complex. Same size as the grid
grid_illumination_P2
[Numpy array] Electric field illumination for P2 polarization
on the grid. Could be complex. Same size as the grid
grid_Ef_P1 [Numpy array] Complex Electric field of polarization P1
projected on the grid.
grid_Ef_P2 [Numpy array] Complex Electric field of polarization P2
projected on the grid.
holograph_PB_P1
[Numpy array] Complex holographic electric field pattern on sky
for polarization P1. Obtained by inverse fourier transforming
grid_illumination_P1. It is 3-dimensional (third dimension is
the frequency axis)
holograph_P1 [Numpy array] Complex holographic image cube for polarization
P1 obtained by inverse fourier transforming Ef_P1
PB_P1 [Numpy array] Power pattern of the antenna obtained by squaring
the absolute value of holograph_PB_P1. It is 3-dimensional
(third dimension is the frequency axis)
lf_P1 [Numpy array] 3D grid of l-axis in the direction cosines
coordinate system corresponding to polarization P1, the third
axis being along frequency.
mf_P1 [Numpy array] 3D grid of m-axis in the direction cosines
coordinate system corresponding to polarization P1, the third
axis being along frequency.
img_P1 [Numpy array] 3D image cube obtained by squaring the absolute
value of holograph_P1. The third dimension is along frequency.
holograph_PB_P2
[Numpy array] Complex holographic electric field pattern on sky
for polarization P2. Obtained by inverse fourier transforming
grid_illumination_P2. It is 3-dimensional (third dimension is
the frequency axis)
holograph_P2 [Numpy array] Complex holographic image cube for polarization
P2 obtained by inverse fourier transforming Ef_P2
PB_P2 [Numpy array] Power pattern of the antenna obtained by squaring
the absolute value of holograph_PB_P2. It is 3-dimensional
(third dimension is the frequency axis)
lf_P2 [Numpy array] 3D grid of l-axis in the direction cosines
coordinate system corresponding to polarization P2, the third
axis being along frequency.
mf_P2 [Numpy array] 3D grid of m-axis in the direction cosines
coordinate system corresponding to polarization P2, the third
axis being along frequency.
img_P2 [Numpy array] 3D image cube obtained by squaring the absolute
value of holograph_P2. The third dimension is along frequency.
extfile [string] external filename under which images and associated
info will be stored
Member Functions:
__init__() Initializes an instance of class Image which manages
information and processing of images from data obtained by an
antenna array. It can be initialized either by values in an
instance of class AntennaArray, by values in a fits file
containing information about the antenna array, or to defaults.
imagr() Imaging engine that performs inverse fourier transforms of
appropriate electric field quantities associated with the
antenna array.
stack() Stacks current images and UV-grid information onto a stack
accumulate_inplace()
Accumulates (adds) in-place the image, synthesized beam,
gridded visibilities and aperture plane weights in the
external file.
reset_extfile()
Reset/initialize the extfile under specified datapool(s)
accumulate() Accumulates and averages gridded quantities that are
statistically stationary such as images and visibilities
average() Averages the image, synthesized beam, gridded visibilities,
aperture plane weights, autocorrelation data and weights in
the external file.
evalAutoCorr()
Evaluate sum of auto-correlations of all antenna weights on
the UV-plane.
evalPowerPattern()
Evaluate power pattern for the antenna from its zero-centered
cross-correlated footprint
getStats() Get statistics from images from inside specified boxes
save() Saves the image information to disk
Read the member function docstrings for more details
----------------------------------------------------------------------------
"""
def __init__(self, f0=None, f=None, pol=None, antenna_array=None,
interferometer_array=None, infile=None, timestamp=None,
extfile=None, verbose=True):
"""
------------------------------------------------------------------------
Initializes an instance of class Image which manages information and
processing of images from data obtained by an antenna array or
interferometer array. It can be initialized either by values in an
instance of class AntennaArray, by values in an instance of class
InterferometerArray, or by values in a fits file containing information
about the antenna array or interferometer array, or to defaults.
Class attributes initialized are:
timestamp, f, f0, gridx_P1, gridy_P1, grid_illumination_P1, grid_Ef_P1,
holograph_P1, holograph_PB_P1, img_P1, PB_P1, lf_P1, mf_P1, gridx_P1,
gridy_P1, grid_illumination_P1, grid_Ef_P1, holograph_P1,
holograph_PB_P1, img_P1, PB_P1, lf_P1, mf_P1, autocorr_wts_vuf,
autocorr_data_vuf, extfile
Read docstring of class Image for details on these attributes.
------------------------------------------------------------------------
"""
if verbose:
print '\nInitializing an instance of class Image...\n'
print '\tVerifying for compatible arguments...'
if timestamp is not None:
self.timestamp = timestamp
if verbose:
print '\t\tInitialized time stamp.'
self.timestamps = []
self.tbinsize = None
if f0 is not None:
self.f0 = f0
if verbose:
print '\t\tInitialized center frequency.'
if f is not None:
self.f = NP.asarray(f)
if verbose:
print '\t\tInitialized frequency channels.'
self.measured_type = None
self.antenna_array = None
self.interferometer_array = None
self.autocorr_set = False
self.autocorr_removed = False
if (infile is None) and (antenna_array is None) and (interferometer_array is None):
self.extfile = None
self.gridx_P1 = None
self.gridy_P1 = None
self.grid_illumination_P1 = None
self.grid_Ef_P1 = None
self.holograph_P1 = None
self.holograph_PB_P1 = None
self.img_P1 = None
self.PB_P1 = None
self.lf_P1 = None
self.mf_P1 = None
self.gridx_P2 = None
self.gridy_P2 = None
self.grid_illumination_P2 = None
self.grid_Ef_P2 = None
self.holograph_P2 = None
self.holograph_PB_P2 = None
self.img_P2 = None
self.PB_P2 = None
self.lf_P2 = None
self.mf_P2 = None
if verbose:
print '\t\tInitialized gridx_P1, gridy_P1, grid_illumination_P1, and grid_Ef_P1'
print '\t\tInitialized lf_P1, mf_P1, holograph_PB_P1, PB_P1, holograph_P1, and img_P1'
print '\t\tInitialized gridx_P2, gridy_P2, grid_illumination_P2, and grid_Ef_P2'
print '\t\tInitialized lf_P2, mf_P2, holograph_PB_P2, PB_P2, holograph_P2, and img_P2'
print '\t\tInitialized extfile'
if (infile is not None) and (antenna_array is not None):
raise ValueError('Both gridded data file and antenna array information are specified. One and only one of these should be specified. Cannot initialize an instance of class Image.')
if (infile is not None) and (interferometer_array is not None):
raise ValueError('Both gridded data file and interferometer array information are specified. One and only one of these should be specified. Cannot initialize an instance of class Image.')
if (antenna_array is not None) and (interferometer_array is not None):
raise ValueError('Both antenna array and interferometer array information are specified. One and only one of these should be specified. Cannot initialize an instance of class Image.')
if verbose:
print '\tArguments verified for initialization.'
if infile is not None:
if verbose:
print '\tInitializing from input file...'
try:
hdulist = fits.open(infile)
except IOError:
raise IOError('File not found. Image instance not initialized.')
except EOFError:
raise EOFError('EOF encountered. File cannot be read. Image instance not initialized.')
else:
extnames = [hdu.header['EXTNAME'] for hdu in hdulist]
if verbose:
print '\t\tFITS file opened successfully. The extensions have been read.'
if 'FREQ' in extnames:
self.f = hdulist['FREQ'].data
if verbose:
print '\t\t\tInitialized frequency channels.'
else:
raise KeyError('Frequency information unavailable in the input file.')
if 'f0' in hdulist[0].header:
self.f0 = hdulist[0].header['f0']
if verbose:
print '\t\t\tInitialized center frequency to {0} Hz from FITS header.'.format(self.f0)
else:
self.f0 = self.f[int(len(self.f)/2)]
if verbose:
print '\t\t\tNo center frequency found in FITS header. Setting it to \n\t\t\t\tthe center of frequency channels: {0} Hz'.format(self.f0)
if 'tobs' in hdulist[0].header:
self.timestamp = hdulist[0].header['tobs']
if verbose:
print '\t\t\tInitialized time stamp.'
if (pol is None) or (pol == 'P1'):
if verbose:
print '\n\t\t\tWorking on polarization P1...'
if ('GRIDX_P1' not in extnames) or ('GRIDY_P1' not in extnames) or ('GRID_ILLUMINATION_P1_REAL' not in extnames) or ('GRID_ILLUMINATION_P1_IMAG' not in extnames) or ('GRID_EF_P1_REAL' not in extnames) or ('GRID_EF_P1_IMAG' not in extnames):
raise KeyError('One or more pieces of gridding information is missing in the input file for polarization P1. Verify the file contains appropriate data.')
self.gridx_P1 = hdulist['GRIDX_P1'].data
self.gridy_P1 = hdulist['GRIDY_P1'].data
self.grid_illumination_P1 = hdulist['GRID_ILLUMINATION_P1_REAL'].data + 1j * hdulist['GRID_ILLUMINATION_P1_IMAG'].data
self.grid_Ef_P1 = hdulist['GRID_EF_P1_REAL'].data + 1j * hdulist['GRID_EF_P1_IMAG'].data
self.holograph_P1 = None
self.img_P1 = None
self.holograph_PB_P1 = None
self.PB_P1 = None
self.lf_P1 = None
self.mf_P1 = None
if verbose:
print '\t\t\tInitialized gridx_P1, gridy_P1, grid_illumination_P1, and grid_Ef_P1'
print '\t\t\tInitialized lf_P1, mf_P1, holograph_PB_P1, PB_P1, holograph_P1, and img_P1'
if (pol is None) or (pol == 'P2'):
if verbose:
print '\n\t\t\tWorking on polarization P2...'
if ('GRIDX_P2' not in extnames) or ('GRIDY_P2' not in extnames) or ('GRID_ILLUMINATION_P2_REAL' not in extnames) or ('GRID_ILLUMINATION_P2_IMAG' not in extnames) or ('GRID_EF_P2_REAL' not in extnames) or ('GRID_EF_P2_IMAG' not in extnames):
raise KeyError('One or more pieces of gridding information is missing in the input file for polarization P2. Verify the file contains appropriate data.')
self.gridx_P2 = hdulist['GRIDX_P2'].data
self.gridy_P2 = hdulist['GRIDY_P2'].data
self.grid_illumination_P2 = hdulist['GRID_ILLUMINATION_P2_REAL'].data + 1j * hdulist['GRID_ILLUMINATION_P2_IMAG'].data
self.grid_Ef_P2 = hdulist['GRID_EF_P2_REAL'].data + 1j * hdulist['GRID_EF_P2_IMAG'].data
self.holograph_P2 = None
self.img_P2 = None
self.holograph_PB_P2 = None
self.PB_P2 = None
self.lf_P2 = None
self.mf_P2 = None
if verbose:
print '\t\t\tInitialized gridx_P2, gridy_P2, grid_illumination_P2, and grid_Ef_P2'
print '\t\t\tInitialized lf_P2, mf_P2, holograph_PB_P2, PB_P2, holograph_P2, and img_P2'
hdulist.close()
if verbose:
print '\t\tClosed input FITS file.'
self.grid_illumination = {}
self.holimg = {}
self.holbeam = {}
self.img = {}
self.beam = {}
self.pbeam = {}
self.gridl = {}
self.gridm = {}
self.grid_wts = {}
self.grid_Ef = {}
self.grid_Vf = {}
self.holimg_stack = {}
self.holbeam_stack = {}
self.img_stack = {}
self.beam_stack = {}
self.grid_illumination_stack = {}
self.grid_vis_stack = {}
self.img_avg = {}
self.beam_avg = {}
self.grid_vis_avg = {}
self.grid_illumination_avg = {}
self.wts_vuf = {}
self.vis_vuf = {}
self.twts = {}
self.autocorr_wts_vuf = {}
self.autocorr_data_vuf = {}
self.nzsp_grid_vis_avg = {}
self.nzsp_grid_illumination_avg = {}
self.nzsp_wts_vuf = {}
self.nzsp_vis_vuf = {}
self.nzsp_img_avg = {}
self.nzsp_beam_avg = {}
self.nzsp_img = {}
self.nzsp_beam = {}
if antenna_array is not None:
if verbose:
print '\tInitializing from an instance of class AntennaArray...'
if isinstance(antenna_array, AntennaArray):
self.f = antenna_array.f
if verbose:
print '\t\tInitialized frequency channels.'
self.f0 = antenna_array.f0
if verbose:
print '\t\tInitialized center frequency to {0} Hz from antenna array info.'.format(self.f0)
self.timestamp = antenna_array.timestamp
if verbose:
print '\t\tInitialized time stamp to {0} from antenna array info.'.format(self.timestamp)
if pol is None:
pol = ['P1', 'P2']
pol = NP.unique(NP.asarray(pol))
self.gridu, self.gridv = antenna_array.gridu, antenna_array.gridv
for apol in ['P1', 'P2']:
self.holimg[apol] = None
self.holbeam[apol] = None
self.img[apol] = None
self.beam[apol] = None
self.grid_illumination[apol] = None
self.grid_Ef[apol] = None
self.grid_wts[apol] = None
self.holimg_stack[apol] = None
self.holbeam_stack[apol] = None
self.img_stack[apol] = None
self.beam_stack[apol] = None
self.grid_illumination_stack[apol] = None
self.grid_vis_stack[apol] = None
self.grid_vis_avg[apol] = None
self.grid_illumination_avg[apol] = None
self.img_avg[apol] = None
self.beam_avg[apol] = None
self.twts[apol] = None
self.wts_vuf[apol] = None
self.vis_vuf[apol] = None
self.autocorr_wts_vuf[apol] = None
self.autocorr_data_vuf[apol] = None
self.nzsp_grid_vis_avg[apol] = None
self.nzsp_grid_illumination_avg[apol] = None
self.nzsp_wts_vuf[apol] = None
self.nzsp_vis_vuf[apol] = None
self.nzsp_img_avg[apol] = None
self.nzsp_beam_avg[apol] = None
self.nzsp_img[apol] = None
self.nzsp_beam[apol] = None
self.pbeam[apol] = None
self.antenna_array = antenna_array
self.measured_type = 'E-field'
if verbose:
print '\t\tInitialized gridded attributes for image object'
else:
raise TypeError('antenna_array is not an instance of class AntennaArray. Cannot initiate instance of class Image.')
if extfile is not None:
if not isinstance(extfile, str):
raise TypeError('Input extfile name must be a string')
self.extfile = extfile
with h5py.File(self.extfile, 'w') as fext:
hdr_group = fext.create_group('header')
hdr_group['f'] = self.f
hdr_group['f'].attrs['units'] = 'Hz'
hdr_group['f0'] = self.f0
hdr_group['f0'].attrs['units'] = 'Hz'
hdr_group['pol'] = pol
if verbose:
print '\t\tInitialized extfile'
if interferometer_array is not None:
if verbose:
print '\tInitializing from an instance of class InterferometerArray...'
if isinstance(interferometer_array, InterferometerArray):
self.f = interferometer_array.f
if verbose:
print '\t\tInitialized frequency channels.'
self.f0 = interferometer_array.f0
if verbose:
print '\t\tInitialized center frequency to {0} Hz from interferometer array info.'.format(self.f0)
self.timestamp = interferometer_array.timestamp
if verbose:
print '\t\tInitialized time stamp to {0} from interferometer array info.'.format(self.timestamp)
if pol is None:
pol = ['P11', 'P12', 'P21', 'P22']
pol = NP.unique(NP.asarray(pol))
self.gridu, self.gridv = interferometer_array.gridu, interferometer_array.gridv
for cpol in ['P11', 'P12', 'P21', 'P22']:
self.holimg[cpol] = None
self.holbeam[cpol] = None
self.img[cpol] = None
self.beam[cpol] = None
self.grid_illumination[cpol] = None
self.grid_Vf[cpol] = None
self.grid_wts[cpol] = None
self.holimg_stack[cpol] = None
self.holbeam_stack[cpol] = None
self.img_stack[cpol] = None
self.beam_stack[cpol] = None
self.grid_illumination_stack[cpol] = None
self.grid_vis_stack[cpol] = None
self.grid_vis_avg[cpol] = None
self.grid_illumination_avg[cpol] = None
self.img_avg[cpol] = None
self.beam_avg[cpol] = None
self.twts[cpol] = None
self.wts_vuf[cpol] = None
self.vis_vuf[cpol] = None
self.autocorr_wts_vuf[cpol] = None
self.nzsp_grid_vis_avg[cpol] = None
self.nzsp_grid_illumination_avg[cpol] = None
self.nzsp_wts_vuf[cpol] = None
self.nzsp_vis_vuf[cpol] = None
self.nzsp_img_avg[cpol] = None
self.nzsp_beam_avg[cpol] = None
self.nzsp_img[cpol] = None
self.nzsp_beam[cpol] = None
self.pbeam[cpol] = None
self.interferometer_array = interferometer_array
self.measured_type = 'visibility'
if verbose:
print '\t\tInitialized gridded attributes for image object'
else:
raise TypeError('interferometer_array is not an instance of class InterferometerArray. Cannot initiate instance of class Image.')
if verbose:
print '\nSuccessfully initialized an instance of class Image\n'
############################################################################
def reset(self, verbose=True):
"""
------------------------------------------------------------------------
Reset some grid level attributes of image object to init values
Inputs:
verbose [boolean] If True (default), prints diagnostic and progress
messages. If False, suppress printing such messages.
The attributes reset to init values are grid_illumination, holbeam,
grid_Vf, grid_Ef, interferometer_array, antenna_array, holimg, gridl,
gridm, img, beam, grid_wts
------------------------------------------------------------------------
"""
if verbose:
print 'Resetting grid level attributes of image object...'
self.antenna_array = None
self.interferometer_array = None
self.timestamp = None
self.grid_illumination = {}
self.holimg = {}
self.holbeam = {}
self.img = {}
self.beam = {}
self.gridl = {}
self.gridm = {}
self.grid_wts = {}
self.grid_Ef = {}
self.grid_Vf = {}
self.wts_vuf = {}
self.vis_vuf = {}
if self.measured_type == 'E-field':
for apol in ['P1', 'P2']:
self.holimg[apol] = None
self.holbeam[apol] = None
self.img[apol] = None
self.beam[apol] = None
self.grid_illumination[apol] = None
self.grid_Ef[apol] = None
self.grid_wts[apol] = None
self.wts_vuf[apol] = None
self.vis_vuf[apol] = None
else:
for cpol in ['P11', 'P12', 'P21', 'P22']:
self.holimg[cpol] = None
self.holbeam[cpol] = None
self.img[cpol] = None
self.beam[cpol] = None
self.grid_illumination[cpol] = None
self.grid_Vf[cpol] = None
self.grid_wts[cpol] = None
self.wts_vuf[cpol] = None
self.vis_vuf[cpol] = None
############################################################################
def update(self, antenna_array=None, interferometer_array=None, reset=True,
verbose=True):
"""
------------------------------------------------------------------------
Updates the image object with newer instance of class AntennaArray or
InterferometerArray
Inputs:
antenna_array [instance of class AntennaArray] Update the image object
with this new instance of class AntennaArray (if attribute
measured_type is 'E-field')
interferometer_array
[instance of class InterferometerArray] Update the image
object with this new instance of class InterferometerArray
(if attribute measured_type is 'visibility')
reset [boolean] if set to True (default), resets some of the
image object attribtues by calling member function reset()
verbose [boolean] If True (default), prints diagnostic and progress
messages. If False, suppress printing such messages.
------------------------------------------------------------------------
"""
if not isinstance(reset, bool):
raise TypeError('reset keyword must be of boolean type')
if not isinstance(verbose, bool):
raise TypeError('verbose keyword must be of boolean type')
if self.measured_type == 'E-field':
if antenna_array is not None:
if isinstance(antenna_array, AntennaArray):
if reset:
self.reset(verbose=verbose)
self.gridu, self.gridv = antenna_array.gridu, antenna_array.gridv
self.antenna_array = antenna_array
else:
raise TypeError('Input antenna_array must be an instance of class AntennaArray')
self.timestamp = antenna_array.timestamp
if verbose:
print 'Updated antenna array attributes of the image instance'
else:
if interferometer_array is not None:
if isinstance(interferometer_array, InterferometerArray):
if reset:
self.reset(verbose=verbose)
self.gridu, self.gridv = interferometer_array.gridu, interferometer_array.gridv
self.interferometer_array = interferometer_array
else:
raise TypeError('Input interferometer_array must be an instance of class InterferometerArray')
self.timestamp = interferometer_array.timestamp
if verbose:
print 'Updated interferometer array attributes of the image instance'
############################################################################
def imagr(self, pol=None, weighting='natural', pad=0, stack=True,
grid_map_method='sparse', cal_loop=False, nproc=None,
verbose=True):
"""
------------------------------------------------------------------------
Imaging engine that performs inverse fourier transforms of appropriate
electric fields or visibilities associated with the antenna array or
interferometer array respectively.
Keyword Inputs:
pol [string] indicates which polarization information to be
imaged. Allowed values are 'P1', 'P2' or None (default). If
None, both polarizations are imaged.
weighting [string] indicates weighting scheme. Default='natural'.
Accepted values are 'natural' and 'uniform'
pad [integer] indicates the amount of padding before imaging.
In case of MOFF imaging the output image will be of size
2**(pad+1) times the size of the antenna array grid along u-
and v-axes. In case of FX imaging, the output image will be of
size 2**pad times the size of interferometer array grid along
u- and v-axes. Value must not be negative. Default=0 (implies
padding by factor 2 along u- and v-axes for MOFF, and no
padding for FX)
stack [boolean] If True (default), stacks the imaged and uv-gridded
data to the stack for batch processing later. If False, it
will accumulate these in-place
grid_map_method
[string] Accepted values are 'regular' and 'sparse' (default).
If 'regular' it applies the regular grid mapping while
'sparse' applies the grid mapping based on sparse matrix
methods
cal_loop [boolean] Applicable only in case when attribute
measured_type is set to 'E-field' (MOFF imaging) and
grid_map_method is set to 'sparse'. If True, the calibration
loop is assumed to be ON and hence the calibrated electric
fields are used in imaging. If False (default), the
calibration loop is assumed to be OFF and the current stream
of electric fields are assumed to be the calibrated data to
be mapped to the grid
nproc [integer] specifies number of independent processes to spawn.
Default = None, means automatically determines the number of
process cores in the system and use one less than that to
avoid locking the system for other processes. Applies only
if input parameter 'parallel' (see above) is set to True.
If nproc is set to a value more than the number of process
cores in the system, it will be reset to number of process
cores in the system minus one to avoid locking the system out
for other processes
verbose [boolean] If True (default), prints diagnostic and progress
messages. If False, suppress printing such messages.
------------------------------------------------------------------------
"""
if verbose:
print '\nPreparing to image...\n'
if self.f is None:
raise ValueError('Frequency channels have not been initialized. Cannot proceed with imaging.')
if self.measured_type is None:
raise ValueError('Measured type is unknown.')
if not isinstance(pad, int):
raise TypeError('Input keyword pad must be an integer')
elif pad < 0:
raise ValueError('Input keyword pad must not be negative')
du = self.gridu[0,1] - self.gridu[0,0]
dv = self.gridv[1,0] - self.gridv[0,0]
grid_shape = self.gridu.shape
if self.measured_type == 'E-field':
if pol is None: pol = ['P1', 'P2']
pol = NP.unique(NP.asarray(pol)).tolist()
for apol in pol:
if apol in ['P1', 'P2']:
if grid_map_method == 'regular':
self.antenna_array.make_grid_cube_new(pol=apol, verbose=verbose)
elif grid_map_method == 'sparse':
self.antenna_array.applyMappingMatrix(pol=apol, cal_loop=cal_loop, verbose=verbose)
else:
raise ValueError('Invalid value specified for input parameter grid_map_method')
self.grid_wts[apol] = NP.zeros(self.gridu.shape+(self.f.size,))
if apol in self.antenna_array.grid_illumination:
if SpM.issparse(self.antenna_array.grid_illumination[apol]):
self.grid_illumination[apol] = self.antenna_array.grid_illumination[apol].A.reshape(self.gridu.shape+(self.f.size,))
self.grid_Ef[apol] = self.antenna_array.grid_Ef[apol].A.reshape(self.gridu.shape+(self.f.size,))
else:
self.grid_illumination[apol] = self.antenna_array.grid_illumination[apol]
self.grid_Ef[apol] = self.antenna_array.grid_Ef[apol]
if verbose: print 'Preparing to Inverse Fourier Transform...'
if weighting == 'uniform':
self.grid_wts[apol][NP.abs(self.grid_illumination[apol]) > 0.0] = 1.0/NP.abs(self.grid_illumination[apol][NP.abs(self.grid_illumination[apol]) > 0.0])
else:
self.grid_wts[apol][NP.abs(self.grid_illumination[apol]) > 0.0] = 1.0
sum_wts = NP.sum(NP.abs(self.grid_wts[apol] * self.grid_illumination[apol]), axis=(0,1), keepdims=True)
if nproc is None:
nproc = max(MP.cpu_count()-1, 1)
else:
nproc = min(nproc, max(MP.cpu_count()-1, 1))
if nproc > 1:
s_list = [(2**(pad+1) * self.gridu.shape[0], 2**(pad+1) * self.gridv.shape[1])] * nproc
axes_list = [(0,1)] * nproc
for qty in ['psf', 'image']:
if qty == 'psf':
qtylist = NP.array_split(self.grid_wts[apol]*self.grid_illumination[apol], nproc, axis=2)
else:
qtylist = NP.array_split(self.grid_wts[apol]*self.grid_Ef[apol], nproc, axis=2)
pool = MP.Pool(processes=nproc)
outqtylist = pool.map(DSP.unwrap_FFT2D, IT.izip(qtylist, s_list, axes_list))
pool.close()
pool.join()
if qty == 'psf':
syn_beam = NP.concatenate(tuple(outqtylist), axis=2)
else:
dirty_image = NP.concatenate(tuple(outqtylist), axis=2)
del outqtylist
else:
syn_beam = NP.fft.fft2(self.grid_wts[apol]*self.grid_illumination[apol], s=[2**(pad+1) * self.gridu.shape[0], 2**(pad+1) * self.gridv.shape[1]], axes=(0,1))
dirty_image = NP.fft.fft2(self.grid_wts[apol]*self.grid_Ef[apol], s=[2**(pad+1) * self.gridu.shape[0], 2**(pad+1) * self.gridv.shape[1]], axes=(0,1))
self.gridl, self.gridm = NP.meshgrid(NP.fft.fftshift(NP.fft.fftfreq(2**(pad+1) * self.gridu.shape[1], du)), NP.fft.fftshift(NP.fft.fftfreq(2**(pad+1) * self.gridv.shape[0], dv)))
self.holbeam[apol] = NP.fft.fftshift(syn_beam/sum_wts, axes=(0,1))
self.holimg[apol] = NP.fft.fftshift(dirty_image/sum_wts, axes=(0,1))
syn_beam = NP.abs(syn_beam)**2
sum_wts2 = sum_wts**2
dirty_image = NP.abs(dirty_image)**2
self.beam[apol] = NP.fft.fftshift(syn_beam/sum_wts2, axes=(0,1))
self.img[apol] = NP.fft.fftshift(dirty_image/sum_wts2, axes=(0,1))
if nproc > 1:
s_list = [None] * nproc
axes_list = [(0,1)] * nproc
for qty in ['wts', 'vis']:
if qty == 'wts':
qtylist = NP.array_split(syn_beam/sum_wts2, nproc, axis=2)
else:
qtylist = NP.array_split(dirty_image/sum_wts2, nproc, axis=2)
pool = MP.Pool(processes=nproc)
outqtylist = pool.map(DSP.unwrap_IFFT2D, IT.izip(qtylist, s_list, axes_list))
pool.close()
pool.join()
qty_vuf = NP.concatenate(tuple(outqtylist), axis=2)
qty_vuf = NP.fft.ifftshift(qty_vuf, axes=(0,1)) # Shift array to be centered
if qty == 'wts':
self.wts_vuf[apol] = qty_vuf[qty_vuf.shape[0]/2-self.gridv.shape[0]:qty_vuf.shape[0]/2+self.gridv.shape[0], qty_vuf.shape[1]/2-self.gridu.shape[1]:qty_vuf.shape[1]/2+self.gridu.shape[1], :]
else:
self.vis_vuf[apol] = qty_vuf[qty_vuf.shape[0]/2-self.gridv.shape[0]:qty_vuf.shape[0]/2+self.gridv.shape[0], qty_vuf.shape[1]/2-self.gridu.shape[1]:qty_vuf.shape[1]/2+self.gridu.shape[1], :]
else:
qty_vuf = NP.fft.ifft2(syn_beam/sum_wts2, axes=(0,1)) # Inverse FT
qty_vuf = NP.fft.ifftshift(qty_vuf, axes=(0,1)) # Shift array to be centered
# self.wts_vuf[apol] = qty_vuf[self.gridv.shape[0]:3*self.gridv.shape[0],self.gridu.shape[1]:3*self.gridu.shape[1],:]
self.wts_vuf[apol] = qty_vuf[qty_vuf.shape[0]/2-self.gridv.shape[0]:qty_vuf.shape[0]/2+self.gridv.shape[0], qty_vuf.shape[1]/2-self.gridu.shape[1]:qty_vuf.shape[1]/2+self.gridu.shape[1], :]
qty_vuf = NP.fft.ifft2(dirty_image/sum_wts2, axes=(0,1)) # Inverse FT
qty_vuf = NP.fft.ifftshift(qty_vuf, axes=(0,1)) # Shift array to be centered
self.vis_vuf[apol] = qty_vuf[qty_vuf.shape[0]/2-self.gridv.shape[0]:qty_vuf.shape[0]/2+self.gridv.shape[0], qty_vuf.shape[1]/2-self.gridu.shape[1]:qty_vuf.shape[1]/2+self.gridu.shape[1], :]
if self.measured_type == 'visibility':
if pol is None: pol = ['P11', 'P12', 'P21', 'P22']
pol = NP.unique(NP.asarray(pol)).tolist()
for cpol in pol:
if cpol in ['P11', 'P12', 'P21', 'P22']:
if grid_map_method == 'regular':
self.interferometer_array.make_grid_cube_new(verbose=verbose, pol=cpol)
elif grid_map_method == 'sparse':
self.interferometer_array.applyMappingMatrix(pol=cpol, verbose=verbose)
else:
raise ValueError('Invalid value specified for input parameter grid_map_method')
self.grid_wts[cpol] = NP.zeros(self.gridu.shape+(self.f.size,))
if cpol in self.interferometer_array.grid_illumination:
if SpM.issparse(self.interferometer_array.grid_illumination[cpol]):
self.grid_illumination[cpol] = self.interferometer_array.grid_illumination[cpol].A.reshape(self.gridu.shape+(self.f.size,))
self.grid_Vf[cpol] = self.interferometer_array.grid_Vf[cpol].A.reshape(self.gridu.shape+(self.f.size,))
else:
self.grid_illumination[cpol] = self.interferometer_array.grid_illumination[cpol]
self.grid_Vf[cpol] = self.interferometer_array.grid_Vf[cpol]
if verbose: print 'Preparing to Inverse Fourier Transform...'
if weighting == 'uniform':
self.grid_wts[cpol][NP.abs(self.grid_illumination[cpol]) > 0.0] = 1.0/NP.abs(self.grid_illumination[cpol][NP.abs(self.grid_illumination[cpol]) > 0.0])
else:
self.grid_wts[cpol][NP.abs(self.grid_illumination[cpol]) > 0.0] = 1.0
sum_wts = NP.sum(NP.abs(self.grid_wts[cpol] * self.grid_illumination[cpol]), axis=(0,1), keepdims=True)
padded_syn_beam_in_uv = NP.pad(self.grid_wts[cpol]*self.grid_illumination[cpol], (((2**pad-1)*self.gridv.shape[0]/2,(2**pad-1)*self.gridv.shape[0]/2),((2**pad-1)*self.gridu.shape[1]/2,(2**pad-1)*self.gridu.shape[1]/2),(0,0)), mode='constant', constant_values=0)
padded_grid_Vf = NP.pad(self.grid_wts[cpol]*self.grid_Vf[cpol], (((2**pad-1)*self.gridv.shape[0]/2,(2**pad-1)*self.gridv.shape[0]/2),((2**pad-1)*self.gridu.shape[1]/2,(2**pad-1)*self.gridu.shape[1]/2),(0,0)), mode='constant', constant_values=0)
self.gridl, self.gridm = NP.meshgrid(NP.fft.fftshift(NP.fft.fftfreq(2**pad * grid_shape[1], du)), NP.fft.fftshift(NP.fft.fftfreq(2**pad * grid_shape[0], dv)))
# Shift to be centered
padded_syn_beam_in_uv = NP.fft.ifftshift(padded_syn_beam_in_uv, axes=(0,1))
padded_grid_Vf = NP.fft.ifftshift(padded_grid_Vf, axes=(0,1))
# Compute the synthesized beam. It is at a finer resolution due to padding
syn_beam = NP.fft.fft2(padded_syn_beam_in_uv, axes=(0,1))
dirty_image = NP.fft.fft2(padded_grid_Vf, axes=(0,1))
# Select only the real part, equivalent to adding conjugate baselines
dirty_image = dirty_image.real
syn_beam = syn_beam.real
self.beam[cpol] = NP.fft.fftshift(syn_beam/sum_wts, axes=(0,1))
self.img[cpol] = NP.fft.fftshift(dirty_image/sum_wts, axes=(0,1))
qty_vuf = NP.fft.ifft2(syn_beam/sum_wts, axes=(0,1)) # Inverse FT
qty_vuf = NP.fft.ifftshift(qty_vuf, axes=(0,1)) # Shift array to be centered
# self.wts_vuf[cpol] = qty_vuf[self.gridv.shape[0]/2:3*self.gridv.shape[0]/2,self.gridu.shape[1]/2:3*self.gridu.shape[1]/2,:]
self.wts_vuf[cpol] = qty_vuf[qty_vuf.shape[0]/2-self.gridv.shape[0]/2:qty_vuf.shape[0]/2+self.gridv.shape[0]/2, qty_vuf.shape[1]/2-self.gridu.shape[1]/2:qty_vuf.shape[1]/2+self.gridu.shape[1]/2,:]
qty_vuf = NP.fft.ifft2(dirty_image/sum_wts, axes=(0,1)) # Inverse FT
qty_vuf = NP.fft.ifftshift(qty_vuf, axes=(0,1)) # Shift array to be centered
# self.vis_vuf[cpol] = qty_vuf[self.gridv.shape[0]/2:3*self.gridv.shape[0]/2,self.gridu.shape[1]/2:3*self.gridu.shape[1]/2,:]
self.vis_vuf[cpol] = qty_vuf[qty_vuf.shape[0]/2-self.gridv.shape[0]/2:qty_vuf.shape[0]/2+self.gridv.shape[0]/2, qty_vuf.shape[1]/2-self.gridu.shape[1]/2:qty_vuf.shape[1]/2+self.gridu.shape[1]/2,:]
nan_ind = NP.where(self.gridl**2 + self.gridm**2 > 1.0)
# nan_ind_unraveled = NP.unravel_index(nan_ind, self.gridl.shape)
# self.beam[cpol][nan_ind_unraveled,:] = NP.nan
# self.img[cpol][nan_ind_unraveled,:] = NP.nan
if verbose:
print 'Successfully imaged.'
# self.evalAutoCorr(datapool='current', forceeval=False)
with h5py.File(self.extfile, 'a') as fext:
if 'image-plane' not in fext:
planes = ['image-plane', 'aperture-plane']
arraytypes = ['stack', 'accumulate', 'avg']
reim_list = ['real', 'imag']
for p in pol:
dset = fext.create_dataset('twts/{0}'.format(p), data=NP.zeros(1), dtype='f4')
for plane in planes:
if plane == 'image-plane':
for arraytype in arraytypes:
if arraytype == 'avg':
tdt = h5py.special_dtype(vlen=NP.dtype('f8'))
tshape = (1,)
else:
tdt = 'f8'
tshape = (0,)
tdset = fext.create_dataset('{0}/{1}/timestamps'.format(plane,arraytype), shape=tshape, maxshape=(None,), dtype=tdt)
qtytypes = ['image', 'psf']
for lm in ['l', 'm']:
if '{0}/{1}'.format(plane, lm) not in fext:
if lm == 'l':
vect = self.gridl[0,:]
l_ind = NP.where(NP.abs(vect) <= 1.05)[0]
dset = fext.create_dataset('{0}/{1}_ind'.format(plane, lm), data=l_ind)
dset = fext.create_dataset('{0}/{1}'.format(plane, lm), data=vect[l_ind])
else:
vect = self.gridm[:,0]
m_ind = NP.where(NP.abs(vect) <= 1.05)[0]
dset = fext.create_dataset('{0}/{1}_ind'.format(plane, lm), data=m_ind)
dset = fext.create_dataset('{0}/{1}'.format(plane, lm), data=vect[m_ind])
else:
dset = fext['{0}/{1}_ind'.format(plane, lm)]
if lm == 'l':
l_ind = dset.value
else:
m_ind = dset.value
else:
qtytypes = ['xcorr', 'acorr']
subqtytypes = ['vals', 'wts']
for qtytype in qtytypes:
for arraytype in arraytypes:
if arraytype == 'avg':
tdt = h5py.special_dtype(vlen=NP.dtype('f8'))
tshape = (1,)
else:
tdt = 'f8'
tshape = (0,)
tdset = fext.create_dataset('{0}/{1}/{2}/timestamps'.format(plane,qtytype,arraytype), shape=tshape, maxshape=(None,), dtype=tdt)
for uv in ['u', 'v']:
if '{0}/{1}'.format(plane, uv) not in fext:
if uv == 'u':
vect = self.gridu[0,:]
else:
vect = self.gridv[:,0]
dset = fext.create_dataset('{0}/{1}'.format(plane, uv), data=vect)
for qtytype in qtytypes:
for arraytype in arraytypes:
for p in pol:
if plane == 'image-plane':
if arraytype == 'stack':
dset = fext.create_dataset('{0}/{1}/{2}/{3}'.format(plane,qtytype,arraytype,p), data=NP.full((1,self.f.size,m_ind.size,l_ind.size), NP.nan), maxshape=(None,self.f.size,m_ind.size,l_ind.size), chunks=(1,1,m_ind.size,l_ind.size), dtype='f8', compression='gzip', compression_opts=9)
elif arraytype == 'accumulate':
dset = fext.create_dataset('{0}/{1}/{2}/{3}'.format(plane,qtytype,arraytype,p), data=NP.zeros((self.f.size,m_ind.size,l_ind.size)), maxshape=(self.f.size,m_ind.size,l_ind.size), chunks=(1,m_ind.size,l_ind.size), dtype='f8', compression='gzip', compression_opts=9)
elif arraytype == 'avg':
dset = fext.create_dataset('{0}/{1}/{2}/{3}'.format(plane,qtytype,arraytype,p), data=NP.full((1,self.f.size,m_ind.size,l_ind.size), NP.nan), maxshape=(None,self.f.size,m_ind.size,l_ind.size), chunks=(1,1,m_ind.size,l_ind.size), dtype='f8', compression='gzip', compression_opts=9)
else:
idxdt = h5py.special_dtype(vlen=NP.dtype('i8'))
valdt = h5py.special_dtype(vlen=NP.dtype('f8'))
for rowcol in ['freqind', 'ij']:
dset = fext.create_dataset('{0}/{1}/{2}/{3}/{4}'.format(plane,qtytype,rowcol,arraytype,p), shape=(1,), maxshape=(None,), dtype=idxdt, compression='gzip', compression_opts=9)
for subqty in subqtytypes:
for reim in reim_list:
dset = fext.create_dataset('{0}/{1}/{2}/{3}/{4}/{5}'.format(plane,qtytype,subqty,arraytype,p,reim), shape=(1,), maxshape=(None,), dtype=valdt, compression='gzip', compression_opts=9)
# Call stack() if required
if stack:
self.stack(pol=pol)
else:
self.accumulate_inplace(pol=pol)
############################################################################
def stack(self, pol=None):
"""
------------------------------------------------------------------------
Stacks current images and UV-grid information onto a stack
Inputs:
pol [string] indicates which polarization information to be saved.
Allowed values are 'P1', 'P2' in case of MOFF or 'P11', 'P12',
'P21', 'P22' in case of FX or None (default). If None,
information on all polarizations appropriate for MOFF or FX
are stacked
------------------------------------------------------------------------
"""
if self.timestamp not in self.timestamps:
if pol is None:
if self.measured_type == 'E-field':
pol = ['P1', 'P2']
else:
pol = ['P11', 'P12', 'P21', 'P22']
elif isinstance(pol, str):
pol = [pol]
elif isinstance(pol, list):
p = [item for item in pol if item in ['P1', 'P2', 'P11', 'P12', 'P21', 'P22']]
pol = p
else:
raise TypeError('Input pol must be a string or list specifying polarization(s)')
if self.extfile is not None:
with h5py.File(self.extfile, 'a') as fext:
planes = ['image-plane', 'aperture-plane']
arraytypes = ['stack']
reim_list = ['real', 'imag']
for plane in planes:
if plane == 'image-plane':
for arraytype in arraytypes:
tdset = fext['{0}/{1}/timestamps'.format(plane,arraytype)]
tdset.resize(tdset.size+1, axis=0)
tdset[-1:] = self.timestamp
qtytypes = ['image', 'psf']
for lm in ['l', 'm']:
dset = fext['{0}/{1}_ind'.format(plane, lm)]
if lm == 'l':
l_ind = dset.value
else:
m_ind = dset.value
mlf_ind = NP.ix_(m_ind, l_ind, NP.arange(self.f.size)) # m (row) first
else:
qtytypes = ['xcorr']
subqtytypes = ['vals', 'wts']
for qtytype in qtytypes:
for arraytype in arraytypes:
tdset = fext['{0}/{1}/{2}/timestamps'.format(plane,qtytype,arraytype)]
tdset.resize(tdset.size+1, axis=0)
tdset[-1:] = self.timestamp
for qtytype in qtytypes:
for arraytype in arraytypes:
for p in pol:
if plane == 'image-plane':
dset = fext['{0}/{1}/{2}/{3}'.format(plane,qtytype,arraytype,p)]
if NP.any(NP.isnan(dset.value)):
if NP.sum(NP.isnan(dset.value)) != dset.size:
raise ValueError('Inconsistent number of NaN found')
else:
dset.resize(dset.shape[0]+1, axis=0)
if qtytype == 'image':
dset[-1:] = NP.rollaxis(self.img[p][mlf_ind], 2, start=0)
elif qtytype == 'psf':
dset[-1:] = NP.rollaxis(self.beam[p][mlf_ind], 2, start=0)
else:
wts_vuf = NP.rollaxis(self.wts_vuf[p], 2, start=0)
xcorr_shape_3D = wts_vuf.shape
wts_vuf = wts_vuf.reshape(wts_vuf.shape[0], -1)
xcorr_shape_2D = wts_vuf.shape
sprow, spcol = NP.where(NP.abs(wts_vuf) > 1e-10)
vis_vuf = NP.rollaxis(self.vis_vuf[p], 2,start=0)
vis_vuf = vis_vuf.reshape(vis_vuf.shape[0], -1)
if '{0}/{1}/shape2D/{2}/{3}'.format(plane,qtytype,arraytype,p) not in fext:
dset = fext.create_dataset('{0}/{1}/shape2D/{2}/{3}'.format(plane,qtytype,arraytype,p), data=NP.asarray(xcorr_shape_2D))
if '{0}/{1}/shape3D/{2}/{3}'.format(plane,qtytype,arraytype,p) not in fext:
dset = fext.create_dataset('{0}/{1}/shape3D/{2}/{3}'.format(plane,qtytype,arraytype,p), data=NP.asarray(xcorr_shape_3D))
for rowcol in ['freqind', 'ij']:
dset = fext['{0}/{1}/{2}/{3}/{4}'.format(plane,qtytype,rowcol,arraytype,p)]
if dset[-1].size > 0:
dset.resize(dset.shape[0]+1, axis=0)
if rowcol == 'freqind':
dset[-1] = NP.copy(sprow)
else:
dset[-1] = NP.copy(spcol)
for subqty in subqtytypes:
for reim in ['real', 'imag']:
dset = fext['{0}/{1}/{2}/{3}/{4}/{5}'.format(plane,qtytype,subqty,arraytype,p,reim)]
if dset[-1].size > 0:
dset.resize(dset.shape[0]+1, axis=0)
if subqty == 'wts':
if reim == 'real':
dset[-1] = NP.copy(wts_vuf[sprow,spcol].real)
else:
dset[-1] = NP.copy(wts_vuf[sprow,spcol].imag)
else:
if reim == 'real':
dset[-1] = NP.copy(vis_vuf[sprow,spcol].real)
else:
dset[-1] = NP.copy(vis_vuf[sprow,spcol].imag)
for p in pol:
dset = fext['twts/{0}'.format(p)]
dset[...] += 1.0
else:
for p in pol:
if self.img_stack[p] is None:
self.img_stack[p] = self.img[p][NP.newaxis,:,:,:]
self.beam_stack[p] = self.beam[p][NP.newaxis,:,:,:]
self.grid_illumination_stack[p] = self.wts_vuf[p][NP.newaxis,:,:,:]
self.grid_vis_stack[p] = self.vis_vuf[p][NP.newaxis,:,:,:]
else:
self.img_stack[p] = NP.concatenate((self.img_stack[p], self.img[p][NP.newaxis,:,:,:]), axis=0)
self.beam_stack[p] = NP.concatenate((self.beam_stack[p], self.beam[p][NP.newaxis,:,:,:]), axis=0)
self.grid_illumination_stack[p] = NP.concatenate((self.grid_illumination_stack[p], self.wts_vuf[p][NP.newaxis,:,:,:]), axis=0)
self.grid_vis_stack[p] = NP.concatenate((self.grid_vis_stack[p], self.vis_vuf[p][NP.newaxis,:,:,:]), axis=0)
if self.measured_type == 'E-field':
if self.holimg_stack[p] is None:
self.holimg_stack[p] = self.holimg[p][NP.newaxis,:,:,:]
self.holbeam_stack[p] = self.holbeam[p][NP.newaxis,:,:,:]
else:
self.holimg_stack[p] = NP.concatenate((self.holimg_stack[p], self.holimg[p][NP.newaxis,:,:,:]), axis=0)
self.holbeam_stack[p] = NP.concatenate((self.holbeam_stack[p], self.holbeam[p][NP.newaxis,:,:,:]), axis=0)
self.timestamps += [self.timestamp]
############################################################################
def accumulate_inplace(self, pol=None, verbose=True):
"""
------------------------------------------------------------------------
Accumulates (adds) in-place the image, synthesized beam, gridded
visibilities and aperture plane weights in the external file.
Inputs:
pol [string] indicates which polarization information to be saved.
Allowed values are 'P1', 'P2' in case of MOFF or 'P11', 'P12',
'P21', 'P22' in case of FX or None (default). If None,
information on all polarizations appropriate for MOFF or FX
are accumulated
verbose [boolean] If True (default), prints diagnostic and progress
messages. If False, suppress printing such messages.
------------------------------------------------------------------------
"""
if self.timestamp not in self.timestamps:
if pol is None:
if self.measured_type == 'E-field':
pol = ['P1', 'P2']
else:
pol = ['P11', 'P12', 'P21', 'P22']
elif isinstance(pol, str):
pol = [pol]
elif isinstance(pol, list):
p = [item for item in pol if item in ['P1', 'P2', 'P11', 'P12', 'P21', 'P22']]
pol = p
else:
raise TypeError('Input pol must be a string or list specifying polarization(s)')
if self.extfile is not None:
with h5py.File(self.extfile, 'a') as fext:
planes = ['image-plane', 'aperture-plane']
arraytypes = ['accumulate']
reim_list = ['real', 'imag']
for plane in planes:
if plane == 'image-plane':
for arraytype in arraytypes:
tdset = fext['{0}/{1}/timestamps'.format(plane,arraytype)]
tdset.resize(tdset.size+1, axis=0)
tdset[-1] = self.timestamp
qtytypes = ['image', 'psf']
for lm in ['l', 'm']:
dset = fext['{0}/{1}_ind'.format(plane, lm)]
if lm == 'l':
l_ind = dset.value
else:
m_ind = dset.value
mlf_ind = NP.ix_(m_ind, l_ind, NP.arange(self.f.size)) # m (row) first
else:
qtytypes = ['xcorr']
subqtytypes = ['wts', 'vals']
for qtytype in qtytypes:
for arraytype in arraytypes:
tdset = fext['{0}/{1}/{2}/timestamps'.format(plane,qtytype,arraytype)]
tdset.resize(tdset.size+1, axis=0)
tdset[-1] = self.timestamp
for qtytype in qtytypes:
for arraytype in arraytypes:
for p in pol:
if plane == 'image-plane':
dset = fext['{0}/{1}/{2}/{3}'.format(plane,qtytype,arraytype,p)]
if qtytype == 'image':
dset[...] += NP.rollaxis(self.img[p][mlf_ind], 2, start=0)
else:
dset[...] += NP.rollaxis(self.beam[p][mlf_ind], 2, start=0)
else:
new_wts_vuf = NP.rollaxis(self.wts_vuf[p], 2, start=0)
xcorr_shape_3D = new_wts_vuf.shape
new_wts_vuf = new_wts_vuf.reshape(new_wts_vuf.shape[0], -1)
xcorr_shape_2D = new_wts_vuf.shape
new_sprow, new_spcol = NP.where(NP.abs(new_wts_vuf) > 1e-10)
new_vis_vuf = NP.rollaxis(self.vis_vuf[p], 2,start=0)
new_vis_vuf = new_vis_vuf.reshape(new_vis_vuf.shape[0], -1)
new_csc_wts_vuf = SpM.csc_matrix((new_wts_vuf[new_sprow,new_spcol], (new_sprow, new_spcol)), shape=xcorr_shape_2D)
new_csc_vis_vuf = SpM.csc_matrix((new_vis_vuf[new_sprow,new_spcol], (new_sprow, new_spcol)), shape=xcorr_shape_2D)
if '{0}/{1}/shape2D/{2}/{3}'.format(plane,qtytype,arraytype,p) not in fext:
dset = fext.create_dataset('{0}/{1}/shape2D/{2}/{3}'.format(plane,qtytype,arraytype,p), data=NP.asarray(xcorr_shape_2D))
if '{0}/{1}/shape3D/{2}/{3}'.format(plane,qtytype,arraytype,p) not in fext:
dset = fext.create_dataset('{0}/{1}/shape3D/{2}/{3}'.format(plane,qtytype,arraytype,p), data=NP.asarray(xcorr_shape_3D))
for rowcol in ['freqind', 'ij']:
dset = fext['{0}/{1}/{2}/{3}/{4}'.format(plane,qtytype,rowcol,arraytype,p)]
if dset[-1].size == 0:
if rowcol == 'freqind':
dset[-1] = NP.copy(new_sprow)
else:
dset[-1] = NP.copy(new_spcol)
else:
if rowcol == 'freqind':
acc_sprow = NP.copy(dset[-1])
else:
acc_spcol = NP.copy(dset[-1])
for subqty in subqtytypes:
for reim in ['real', 'imag']:
dset = fext['{0}/{1}/{2}/{3}/{4}/{5}'.format(plane,qtytype,subqty,arraytype,p,reim)]
if dset[-1].size == 0:
if subqty == 'wts':
if reim == 'real':
dset[-1] = NP.copy(new_wts_vuf[new_sprow, new_spcol].real)
else:
dset[-1] = NP.copy(new_wts_vuf[new_sprow, new_spcol].imag)
else:
if reim == 'real':
dset[-1] = NP.copy(new_vis_vuf[new_sprow, new_spcol].real)
else:
dset[-1] = NP.copy(new_vis_vuf[new_sprow, new_spcol].imag)
just_set = True
else:
if reim == 'real':
acc_qty = dset[-1].astype(NP.complex128)
else:
acc_qty += 1j * dset[-1]
just_set = False
if (dset[-1].size > 0) and not just_set:
acc_spmat = SpM.csc_matrix((acc_qty, (acc_sprow, acc_spcol)), shape=xcorr_shape_2D)
if subqty == 'wts':
acc_spmat += new_csc_wts_vuf
new_acc_sprow, new_acc_spcol = NP.where((NP.abs(acc_spmat) > 1e-10).toarray())
for rowcol in ['freqind', 'ij']:
dset = fext['{0}/{1}/{2}/{3}/{4}'.format(plane,qtytype,rowcol,arraytype,p)]
if rowcol == 'freqind':
dset[-1] = NP.copy(new_acc_sprow)
else:
dset[-1] = NP.copy(new_acc_spcol)
else:
acc_spmat += new_csc_vis_vuf
for reim in ['real', 'imag']:
dset = fext['{0}/{1}/{2}/{3}/{4}/{5}'.format(plane,qtytype,subqty,arraytype,p,reim)]
if reim == 'real':
dset[-1] = acc_spmat[new_acc_sprow, new_acc_spcol].real.A.ravel()
else:
dset[-1] = acc_spmat[new_acc_sprow, new_acc_spcol].imag.A.ravel()
for p in pol:
dset = fext['twts/{0}'.format(p)]
dset[...] += 1.0
self.timestamps += [self.timestamp]
if verbose:
print '\nIn-place accumulation of image, beam, visibility, and synthesis aperture weights completed for timestamp {0:.7f}.\n'.format(self.timestamp)
############################################################################
def average(self, pol=None, datapool='accumulate', autocorr_op='rmfit',
verbose=True):
"""
------------------------------------------------------------------------
Averages the image, synthesized beam, gridded visibilities, aperture
plane weights, autocorrelation data and weights in the external file,
with optional removal of autocorrelation weights and data.
Inputs:
pol [string] indicates which polarization information to be saved.
Allowed values are 'P1', 'P2' in case of MOFF or 'P11', 'P12',
'P21', 'P22' in case of FX or None (default). If None,
information on all polarizations appropriate for MOFF or FX
are accumulated
datapool
[string] Data pool from which values will be used in the
averaging. Accepted values are 'accumulate' (default) and
'stack'.
autocorr_op
[string] indicates if autocorrelation weights and data are to
be removed. Accepted values are 'rmfit' (fit and remove an
estimate of autocorr weights and data), 'mask' (mask the
footprint of autocorr weights to zero) , and 'none' (keep the
autocorr weights and data without any modification).
Default='rmfit'.
verbose [boolean] If True (default), prints diagnostic and progress
messages. If False, suppress printing such messages.
------------------------------------------------------------------------
"""
if pol is None:
if self.measured_type == 'E-field':
pol = ['P1', 'P2']
else:
pol = ['P11', 'P12', 'P21', 'P22']
elif isinstance(pol, str):
pol = [pol]
elif isinstance(pol, list):
p = [item for item in pol if item in ['P1', 'P2', 'P11', 'P12', 'P21', 'P22']]
pol = p
else:
raise TypeError('Input pol must be a string or list specifying polarization(s)')
if not isinstance(datapool, str):
raise TypeError('Input datapool must be a string')
else:
if datapool.lower() not in ['accumulate', 'stack']:
raise ValueError('Inout datapool value not accepted')
if not isinstance(autocorr_op, str):
raise TypeError('Input autocorr_op must be a string')
if autocorr_op.lower() not in ['rmfit', 'mask', 'none']:
raise ValueError('Invalid value specified for input autocorr_op')
if self.extfile is not None:
with h5py.File(self.extfile, 'a') as fext:
plane = 'aperture-plane'
reim_list = ['real', 'imag']
qtytypes = ['xcorr']
subqtytypes = ['wts', 'vals']
for qtytype in qtytypes:
tdset = fext['{0}/{1}/avg/timestamps'.format(plane,qtytype)]
if tdset[-1].size > 0:
tdset.resize(tdset.size+1, axis=0)
tdset[-1] = fext['{0}/{1}/{2}/timestamps'.format(plane,qtytype,datapool)].value
for p in pol:
if '{0}/{1}/shape2D/{2}/{3}'.format(plane,qtytype,datapool,p) not in fext:
raise KeyError('Key {0}/{1}/shape2D/{2}/{3} not found in external file')
else:
shape2D_dset = fext['{0}/{1}/shape2D/{2}/{3}'.format(plane,qtytype,datapool,p)]
shape2D = shape2D_dset.value
freqind_list = [arr for arr in fext['{0}/{1}/freqind/{2}/{3}'.format(plane,qtytype,datapool,p)]]
ijind_list = [arr for arr in fext['{0}/{1}/ij/{2}/{3}'.format(plane,qtytype,datapool,p)]]
for subqty in subqtytypes:
spmat = SpM.csc_matrix(tuple(shape2D), dtype=NP.complex128) # Create empty sparse matrix
for tind in range(len(freqind_list)):
for reim in reim_list:
dset = fext['{0}/{1}/{2}/{3}/{4}/{5}'.format(plane,qtytype,subqty,datapool,p,reim)][tind]
if reim == 'real':
spmat += SpM.csc_matrix((dset, (freqind_list[tind], ijind_list[tind])), shape=spmat.shape)
else:
spmat += 1j*SpM.csc_matrix((dset, (freqind_list[tind], ijind_list[tind])), shape=spmat.shape)
spmat /= fext['twts/{0}'.format(p)].value[0] # Average the accumulated sparse matrix
if autocorr_op in ['rmfit', 'mask']:
shape2D_auto = fext['{0}/acorr/shape2D/avg/{1}'.format(plane,p)].value
if not NP.array_equal(shape2D_auto,shape2D):
raise ValueError('Xcorr and Acorr shapes not equal')
sprow_auto = fext['{0}/acorr/freqind/avg/{1}'.format(plane,p)][-1]
spcol_auto = fext['{0}/acorr/ij/avg/{1}'.format(plane,p)][-1]
spmat_auto = SpM.csc_matrix(tuple(shape2D_auto), dtype=NP.complex128)
for reim in reim_list:
dset = fext['{0}/acorr/{1}/avg/{2}/{3}'.format(plane,subqty,p,reim)]
if reim == 'real':
spmat_auto += SpM.csc_matrix((dset[-1], (sprow_auto, spcol_auto)), shape=shape2D_auto)
else:
spmat_auto += 1j * SpM.csc_matrix((dset[-1], (sprow_auto, spcol_auto)), shape=shape2D_auto)
if autocorr_op.lower() == 'mask':
spmat -= SpM.csc_matrix((spmat[sprow_auto, spcol_auto].A.ravel(), (sprow_auto, spcol_auto)), shape=shape2D) # Force pixels present in auto footprint to zero
else:
spmat = spmat.A - (spmat[:,int(NP.floor(0.5*shape2D[1]))] / spmat_auto[:,int(NP.floor(0.5*shape2D[1]))]).A * spmat_auto.A # Force zero spacing pixel to match and then subtract the auto footprint, now a dense matrix
if subqty == 'wts':
sprow, spcol = NP.where((NP.abs(spmat) > 1e-10).toarray())
for rowcol in ['freqind', 'ij']:
rc_dset = fext['{0}/{1}/{2}/avg/{3}'.format(plane,qtytype,rowcol,p)]
if rc_dset[-1].size > 0:
rc_dset.resize(rc_dset.size+1, axis=0)
if rowcol == 'freqind':
rc_dset[-1] = NP.copy(sprow)
else:
rc_dset[-1] = NP.copy(spcol)
for reim in reim_list:
avg_dset = fext['{0}/{1}/{2}/avg/{3}/{4}'.format(plane,qtytype,subqty,p,reim)]
if avg_dset[-1].size > 0:
avg_dset.resize(avg_dset.size+1, axis=0)
if reim == 'real':
avg_dset[-1] = NP.copy(spmat[sprow,spcol].A.real.ravel())
else:
avg_dset[-1] = NP.copy(spmat[sprow,spcol].A.imag.ravel())
plane = 'image-plane'
tdset = fext['{0}/avg/timestamps'.format(plane)]
if tdset[-1].size > 0:
tdset.resize(tdset.size+1, axis=0)
tdset[-1] = fext['{0}/{1}/timestamps'.format(plane,datapool)].value
qtytypes = ['psf', 'image']
for qtytype in qtytypes:
for p in pol:
if autocorr_op.lower() == 'none':
dset = fext['{0}/{1}/{2}/{3}'.format(plane,qtytype,datapool,p)]
if datapool == 'stack':
qty_fml = NP.mean(dset.value, axis=0) # Average across time
else:
qty_fml = dset.value / fext['twts/{0}'.format(p)].value[0] # Average across time
else:
for lm in ['l', 'm']:
dset = fext['{0}/{1}_ind'.format(plane, lm)]
if lm == 'l':
l_ind = dset.value
else:
m_ind = dset.value
fml_ind = NP.ix_(NP.arange(self.f.size), m_ind, l_ind) # m (row) first
shape2D = fext['aperture-plane/xcorr/shape2D/{0}/{1}'.format(datapool,p)].value
shape3D = fext['aperture-plane/xcorr/shape3D/{0}/{1}'.format(datapool,p)].value
for rowcol in ['freqind', 'ij']:
dset = fext['aperture-plane/xcorr/{0}/avg/{1}'.format(rowcol,p)]
if rowcol == 'freqind':
sprow = dset[-1]
else:
spcol = dset[-1]
if qtytype == 'psf':
apqty = 'wts'
else:
apqty = 'vals'
for reim in reim_list:
dset = fext['aperture-plane/xcorr/{0}/avg/{1}/{2}'.format(apqty,p,reim)]
if reim == 'real':
spmat = SpM.csc_matrix((dset[-1], (sprow, spcol)), shape=shape2D, dtype=NP.complex128)
else:
spmat += 1j * SpM.csc_matrix((dset[-1], (sprow, spcol)), shape=shape2D, dtype=NP.complex128)
mat = spmat.A.reshape(shape3D)
if apqty == 'wts':
sum_wts = NP.sum(mat, axis=(1,2), keepdims=True)
qty_fml = NP.fft.fftshift(NP.fft.fft2(NP.fft.ifftshift(mat, axes=(1,2)), axes=(1,2)), axes=(1,2)) / sum_wts
if NP.abs(qty_fml.imag).max() > 1e-10:
raise ValueError('Significant imaginary component found in the image-plane quantity.')
qty_fml = qty_fml[fml_ind].real
dset = fext['{0}/{1}/avg/{2}'.format(plane,qtytype,p)]
if NP.any(NP.isnan(dset.value)):
if NP.sum(NP.isnan(dset.value)) != dset.size:
raise ValueError('Inconsistent number of NaN found')
else:
dset.resize(dset.shape[0]+1, axis=0)
dset[-1] = qty_fml
############################################################################
def reset_extfile(self, datapool=None):
"""
------------------------------------------------------------------------
Reset/initialize the extfile under specified datapool(s)
datapool
[None or string or list] Data pool which will be reset or
initialized in the external file. Accepted values are
'accumulate' and 'stack'. If set to None (default), both
'accumulate' and 'stack' datapools will be reset/initialized in
the external file
------------------------------------------------------------------------
"""
if datapool is None:
datapool = ['accumulate', 'stack']
elif isinstance(datapool, 'str'):
if datapool not in ['accumulate', 'stack']:
raise ValueError('Value "{0}" in input datapool not accepted.'.format(datapool))
datapool = [datapool]
elif isinstance(datapool, list):
for item in datapool:
if not isinstance(item, str):
raise TypeError('Item in datapool must be a string')
if item not in ['accumulate', 'stack']:
raise ValueError('Value "{0}" in input datapool not accepted.'.format(item))
else:
raise TypeError('Input datapool has invalid type')
pol = ['P1', 'P2']
if self.extfile is not None:
with h5py.File(self.extfile, 'a') as fext:
planes = ['image-plane', 'aperture-plane']
reim_list = ['real', 'imag']
for p in pol:
try:
dset = fext['twts/{0}'.format(p)]
dset[...] = NP.zeros(1)
except KeyError:
pass
for plane in planes:
if plane == 'image-plane':
qtytypes = ['image', 'psf']
for arraytype in datapool:
tdset = fext['{0}/{1}/timestamps'.format(plane,arraytype)]
tdset.resize(0, axis=0)
else:
qtytypes = ['xcorr', 'acorr']
subqtytypes = ['vals', 'wts']
for qtytype in qtytypes:
for arraytype in datapool:
tdset = fext['{0}/{1}/{2}/timestamps'.format(plane,qtytype,arraytype)]
tdset.resize(0, axis=0)
for qtytype in qtytypes:
for arraytype in datapool:
for p in pol:
if plane == 'image-plane':
try:
dset = fext['{0}/{1}/{2}/{3}'.format(plane,qtytype,arraytype,p)]
if arraytype == 'stack':
dset.resize(1, axis=0)
dset[-1] = NP.full((dset.shape[1], dset.shape[2], dset.shape[3]), NP.nan)
elif arraytype == 'accumulate':
dset[...] = NP.full(dset.shape, 0.0)
except KeyError:
pass
else:
for rowcol in ['freqind', 'ij']:
try:
dset = fext['{0}/{1}/{2}/{3}/{4}'.format(plane,qtytype,rowcol,arraytype,p)]
dset.resize(1, axis=0)
dset[-1] = NP.asarray([])
except KeyError:
pass
for subqty in subqtytypes:
for reim in reim_list:
try:
dset = fext['{0}/{1}/{2}/{3}/{4}/{5}'.format(plane,qtytype,subqty,arraytype,p,reim)]
dset.resize(1, axis=0)
dset[-1] = NP.asarray([])
except KeyError:
pass
############################################################################
def accumulate(self, tbinsize=None, verbose=True):
"""
------------------------------------------------------------------------
Accumulates and averages gridded quantities that are statistically
stationary such as images and visibilities
Input:
tbinsize [scalar or dictionary] Contains bin size of timestamps while
averaging. Default = None means gridded quantities over all
timestamps are averaged. If scalar, the same (positive) value
applies to all polarizations. If dictionary, timestamp bin size
(positive) is provided under each key 'P11', 'P12', 'P21',
'P22'. If any of the keys is missing the gridded quantities
for that polarization are averaged over all timestamps.
verbose [boolean] If True (default), prints diagnostic and progress
messages. If False, suppress printing such messages.
------------------------------------------------------------------------
"""
if self.measured_type == 'E-field':
pol = ['P1', 'P2']
else:
pol = ['P11', 'P12', 'P21', 'P22']
timestamps = NP.asarray(self.timestamps).astype(NP.float)
twts = {}
img_acc = {}
beam_acc = {}
grid_vis_acc = {}
grid_illumination_acc = {}
for p in pol:
img_acc[p] = None
beam_acc[p] = None
grid_vis_acc[p] = None
grid_illumination_acc[p] = None
twts[p] = []
if tbinsize is None: # Average across all timestamps
for p in pol:
if self.img_stack[p] is not None:
img_acc[p] = NP.nansum(self.img_stack[p], axis=0, keepdims=True)
beam_acc[p] = NP.nansum(self.beam_stack[p], axis=0, keepdims=True)
grid_vis_acc[p] = NP.nansum(self.grid_vis_stack[p], axis=0, keepdims=True)
grid_illumination_acc[p] = NP.nansum(self.grid_illumination_stack[p], axis=0, keepdims=True)
twts[p] = NP.asarray(len(self.timestamps)).reshape(-1,1,1,1)
self.tbinsize = tbinsize
elif isinstance(tbinsize, (int, float)): # Apply same time bin size to all polarizations
eps = 1e-10
tbins = NP.arange(timestamps.min(), timestamps.max(), tbinsize)
tbins = NP.append(tbins, timestamps.max()+eps)
for p in pol:
counts, tbin_edges, tbinnum, ri = OPS.binned_statistic(timestamps, statistic='count', bins=tbins)
for binnum in range(counts.size):
ind = ri[ri[binnum]:ri[binnum+1]]
twts[p] += [counts]
if img_acc[p] is None:
if self.img_stack[p] is not None:
img_acc[p] = NP.nansum(self.img_stack[p][ind,:,:,:], axis=0, keepdims=True)
beam_acc[p] = NP.nansum(self.beam_stack[p][ind,:,:,:], axis=0, keepdims=True)
grid_vis_acc[p] = NP.nansum(self.grid_vis_stack[p][ind,:,:,:], axis=0, keepdims=True)
grid_illumination_acc[p] = NP.nansum(self.grid_illumination_stack[p][ind,:,:,:], axis=0, keepdims=True)
else:
if self.img_stack[p] is not None:
img_acc[p] = NP.vstack((img_acc[p], NP.nansum(self.img_stack[p][ind,:,:,:], axis=0, keepdims=True)))
beam_acc[p] = NP.vstack((beam_acc[p], NP.nansum(self.beam_stack[p][ind,:,:,:], axis=0, keepdims=True)))
grid_vis_acc[p] = NP.vstack((grid_vis_acc[p], NP.nansum(self.grid_vis_stack[p][ind,:,:,:], axis=0, keepdims=True)))
grid_illumination_acc[p] = NP.vstack((grid_illumination_acc[p], NP.nansum(self.grid_illumination_stack[p][ind,:,:,:], axis=0, keepdims=True)))
twts[p] = NP.asarray(twts[p]).astype(NP.float).reshape(-1,1,1,1)
self.tbinsize = tbinsize
elif isinstance(tbinsize, dict): # Apply different time binsizes to corresponding polarizations
tbsize = {}
for p in pol:
if p not in tbinsize:
if self.img_stack[p] is not None:
img_acc[p] = NP.nansum(self.img_stack[p], axis=0, keepdims=True)
beam_acc[p] = NP.nansum(self.beam_stack[p], axis=0, keepdims=True)
grid_vis_acc[p] = NP.nansum(self.grid_vis_stack[p], axis=0, keepdims=True)
grid_illumination_acc[p] = NP.nansum(self.grid_illumination_stack[p], axis=0, keepdims=True)
twts[p] = NP.asarray(len(self.timestamps)).reshape(-1,1,1,1)
tbsize[p] = None
elif isinstance(tbinsize[p], (int,float)):
eps = 1e-10
tbins = NP.arange(timestamps.min(), timestamps.max(), tbinsize[p])
tbins = NP.append(tbins, timestamps.max()+eps)
counts, tbin_edges, tbinnum, ri = OPS.binned_statistic(timestamps, statistic='count', bins=tbins)
for binnum in range(counts.size):
ind = ri[ri[binnum]:ri[binnum+1]]
twts[p] += [counts]
if img_acc[p] is None:
if self.img_stack[p] is not None:
img_acc[p] = NP.nansum(self.img_stack[p][ind,:,:,:], axis=0, keepdims=True)
beam_acc[p] = NP.nansum(self.beam_stack[p][ind,:,:,:], axis=0, keepdims=True)
grid_vis_acc[p] = NP.nansum(self.grid_vis_stack[p][ind,:,:,:], axis=0, keepdims=True)
grid_illumination_acc[p] = NP.nansum(self.grid_illumination_stack[p][ind,:,:,:], axis=0, keepdims=True)
else:
if self.img_stack[p] is not None:
img_acc[p] = NP.vstack((img_acc[p], NP.nansum(self.img_stack[p][ind,:,:,:], axis=0, keepdims=True)))
beam_acc[p] = NP.vstack((beam_acc[p], NP.nansum(self.beam_stack[p][ind,:,:,:], axis=0, keepdims=True)))
grid_vis_acc[p] = NP.vstack((grid_vis_acc[p], NP.nansum(self.grid_vis_stack[p][ind,:,:,:], axis=0, keepdims=True)))
grid_illumination_acc[p] = NP.vstack((grid_illumination_acc[p], NP.nansum(self.grid_illumination_stack[p][ind,:,:,:], axis=0, keepdims=True)))
twts[p] = NP.asarray(twts[p]).astype(NP.float).reshape(-1,1,1,1)
tbsize[p] = tbinsize[p]
else:
if self.img_stack[p] is not None:
img_acc[p] = NP.nansum(self.img_stack[p], axis=0, keepdims=True)
beam_acc[p] = NP.nansum(self.beam_stack[p], axis=0, keepdims=True)
grid_vis_acc[p] = NP.nansum(self.grid_vis_stack[p], axis=0, keepdims=True)
grid_illumination_acc[p] = NP.nansum(self.grid_illumination_stack[p], axis=0, keepdims=True)
twts[p] = NP.asarray(len(self.timestamps)).reshape(-1,1,1,1)
tbsize[p] = None
self.tbinsize = tbsize
# Compute the averaged grid quantities from the accumulated versions
for p in pol:
if img_acc[p] is not None:
self.img_avg[p] = img_acc[p] / twts[p]
self.beam_avg[p] = beam_acc[p] / twts[p]
self.grid_vis_avg[p] = grid_vis_acc[p] / twts[p]
self.grid_illumination_avg[p] = grid_illumination_acc[p] / twts[p]
self.twts = twts
############################################################################
def evalAutoCorr(self, pol=None, datapool='avg', forceeval_autowts=False,
forceeval_autocorr=True, nproc=None, save=True,
verbose=True):
"""
------------------------------------------------------------------------
Evaluate sum of auto-correlations of all antenna weights on the
UV-plane.
Inputs:
pol [string] indicates which polarization information to be saved.
Allowed values are 'P1', 'P2' in case of MOFF. If None,
information on all polarizations appropriate for MOFF are
evaluated
datapool [string] Specifies whether data to be used in determining the
auto-correlation the E-fields to be used come from
'stack', 'current', or 'avg' (default). Squared electric
fields will be used if set to 'current' or 'stack', and
averaged squared electric fields if set to 'avg'
forceeval_autowts
[boolean] When set to False (default) the auto-correlation
weights in the UV plane is not evaluated if it was already
evaluated earlier. If set to True, it will be forcibly
evaluated independent of whether they were already evaluated
or not
forceeval_autocorr
[boolean] When set to False (default) the auto-correlation
data in the UV plane is not evaluated if it was already
evaluated earlier. If set to True, it will be forcibly
evaluated independent of whether they were already evaluated
or not
nproc [integer] specifies number of independent processes to spawn.
Default = None, means automatically determines the number of
process cores in the system and use one less than that to
avoid locking the system for other processes. Applies only
if input parameter 'parallel' (see above) is set to True.
If nproc is set to a value more than the number of process
cores in the system, it will be reset to number of process
cores in the system minus one to avoid locking the system out
for other processes
save [boolean] If True (default), save the autocorrelation weights
and data if an external file exists. It only applies when
datapool='avg', otherwise it does not save to external file.
verbose [boolean] When set to True (default), print diagnostic
messages, otherwise suppress messages
------------------------------------------------------------------------
"""
if pol is None:
pol = ['P1', 'P2']
elif isinstance(pol, str):
pol = [pol]
elif isinstance(pol, list):
p = [item for item in pol if item in ['P1', 'P2']]
pol = p
else:
raise TypeError('Input pol must be a string or list specifying polarization(s)')
if not isinstance(forceeval_autowts, bool):
raise TypeError('Input forceeval_autowts must be boolean')
if not isinstance(forceeval_autocorr, bool):
raise TypeError('Input forceeval_autocorr must be boolean')
if not isinstance(save, bool):
raise TypeError('Input save must be boolean')
if forceeval_autowts or forceeval_autocorr or (not self.autocorr_set):
self.autocorr_wts_vuf, self.autocorr_data_vuf = self.antenna_array.makeAutoCorrCube(pol=pol, datapool=datapool, tbinsize=self.tbinsize, forceeval_autowts=forceeval_autowts, forceeval_autocorr=forceeval_autocorr, nproc=nproc)
self.autocorr_set = True
if verbose:
print 'Determined auto-correlation weights and data...'
if save:
if datapool == 'avg':
if self.extfile is not None:
with h5py.File(self.extfile, 'a') as fext:
planes = ['aperture-plane']
arraytypes = ['avg']
reim_list = ['real', 'imag']
for plane in planes:
if plane == 'aperture-plane':
qtytypes = ['acorr']
subqtytypes = ['wts', 'vals']
for qtytype in qtytypes:
for arraytype in arraytypes:
if arraytype == 'avg':
tdset = fext['{0}/{1}/{2}/timestamps'.format(plane,qtytype,arraytype)]
if (tdset.size == 1) and (tdset[-1].size == 0):
tdset[-1] = NP.asarray(self.timestamps)
else:
prev_max_tstamp = tdset[-1].max()
if (len(self.timestamps)>tdset[-1].size) or (max(self.timestamps)>tdset[-1].max()):
tstamps = NP.asarray(self.timestamps)
nearest_ind = NP.argmin(NP.abs(tstamps - tdset[-1].max()))
new_tstamps = tstamps[nearest_ind+1:]
tdset.resize(tdset.size+1, axis=0)
tdset[-1] = NP.copy(new_tstamps)
for p in pol:
if plane == 'aperture-plane':
wts_vuf = NP.rollaxis(NP.squeeze(self.autocorr_wts_vuf[p]), 2, start=0)
acorr_shape_3D = wts_vuf.shape
wts_vuf = wts_vuf.reshape(wts_vuf.shape[0], -1)
acorr_shape_2D = wts_vuf.shape
sprow, spcol = NP.where(NP.abs(wts_vuf) > 1e-10)
vis_vuf = NP.rollaxis(NP.squeeze(self.autocorr_data_vuf[p]), 2,start=0)
vis_vuf = vis_vuf.reshape(vis_vuf.shape[0], -1)
if '{0}/{1}/shape2D/{2}/{3}'.format(plane,qtytype,arraytype,p) not in fext:
dset = fext.create_dataset('{0}/{1}/shape2D/{2}/{3}'.format(plane,qtytype,arraytype,p), data=NP.asarray(acorr_shape_2D))
if '{0}/{1}/shape3D/{2}/{3}'.format(plane,qtytype,arraytype,p) not in fext:
dset = fext.create_dataset('{0}/{1}/shape3D/{2}/{3}'.format(plane,qtytype,arraytype,p), data=NP.asarray(acorr_shape_3D))
for rowcol in ['freqind', 'ij']:
dset = fext['{0}/{1}/{2}/{3}/{4}'.format(plane,qtytype,rowcol,arraytype,p)]
if dset[-1].size > 0:
dset.resize(dset.shape[0]+1, axis=0)
if rowcol == 'freqind':
dset[-1] = NP.copy(sprow)
else:
dset[-1] = NP.copy(spcol)
for subqty in subqtytypes:
for reim in ['real', 'imag']:
dset = fext['{0}/{1}/{2}/{3}/{4}/{5}'.format(plane,qtytype,subqty,arraytype,p,reim)]
if dset[-1].size > 0:
dset.resize(dset.shape[0]+1, axis=0)
if subqty == 'wts':
if reim == 'real':
dset[-1] = NP.copy(wts_vuf[sprow,spcol].real)
else:
dset[-1] = NP.copy(wts_vuf[sprow,spcol].imag)
else:
if reim == 'real':
dset[-1] = NP.copy(vis_vuf[sprow,spcol].real)
else:
dset[-1] = NP.copy(vis_vuf[sprow,spcol].imag)
############################################################################
def evalPowerPattern(self, pad=0, skypos=None, datapool='avg'):
"""
------------------------------------------------------------------------
Evaluate power pattern for the antenna from its zero-centered
cross-correlated footprint
Input:
datapool
[string] Specifies whether weights to be used in determining
the power pattern come from 'stack', 'current', or 'avg'
(default).
skypos [numpy array] Positions on sky at which power pattern is
to be esimated. It is a 2- or 3-column numpy array in
direction cosine coordinates. It must be of size nsrc x 2
or nsrc x 3. If set to None (default), the power pattern is
estimated over a grid on the sky. If a numpy array is
specified, then power pattern at the given locations is
estimated.
pad [integer] indicates the amount of padding before estimating
power pattern image. Applicable only when attribute
measured_type is set to 'E-field' (MOFF imaging). The output
image of the power pattern will be of size 2**pad-1 times the
size of the antenna array grid along u- and v-axes. Value must
not be negative. Default=0 (implies no padding). pad=1 implies
padding by factor 2 along u- and v-axes for MOFF
Outputs:
pbinfo is a dictionary with the following keys and values:
'pb' [dictionary] Dictionary with keys 'P1' and 'P2' for
polarization. Under each key is a numpy array of estimated
power patterns. If skypos was set to None, the numpy array is
3D masked array of size nm x nl x nchan. The mask is based on
which parts of the grid are valid direction cosine coordinates
on the sky. If skypos was a numpy array denoting specific sky
locations, the value in this key is a 2D numpy array of size
nsrc x nchan
'llocs' [None or numpy array] If the power pattern estimated is a grid
(if input skypos was set to None), it contains the l-locations
of the grid on the sky. If input skypos was not set to None,
the value under this key is set to None
'mlocs' [None or numpy array] If the power pattern estimated is a grid
(if input skypos was set to None), it contains the m-locations
of the grid on the sky. If input skypos was not set to None,
the value under this key is set to None
------------------------------------------------------------------------
"""
if not isinstance(pad, int):
raise TypeError('Input keyword pad must be an integer')
if datapool not in ['recent', 'stack', 'avg']:
raise ValueError('Invalid value specified for input datapool')
self.antenna_array.evalAllAntennaPairCorrWts()
centered_crosscorr_wts_vuf = self.antenna_array.makeCrossCorrWtsCube()
du = self.antenna_array.gridu[0,1] - self.antenna_array.gridu[0,0]
dv = self.antenna_array.gridv[1,0] - self.antenna_array.gridv[0,0]
ulocs = du*(NP.arange(2*self.antenna_array.gridu.shape[1])-self.antenna_array.gridu.shape[1])
vlocs = dv*(NP.arange(2*self.antenna_array.gridv.shape[0])-self.antenna_array.gridv.shape[0])
pol = ['P1', 'P2']
pbinfo = {'pb': {}}
for p in pol:
pb = evalApertureResponse(centered_crosscorr_wts_vuf[p], ulocs, vlocs, pad=pad, skypos=skypos)
pbinfo['pb'][p] = pb['pb']
pbinfo['llocs'] = pb['llocs']
pbinfo['mlocs'] = pb['mlocs']
return pbinfo
############################################################################
def removeAutoCorr(self, lkpinfo=None, forceeval=False, datapool='avg',
pad=0):
"""
------------------------------------------------------------------------
Remove auto-correlation of single antenna weights with itself from the
UV-plane.
Inputs:
lkpinfo [dictionary] consists of weights information for each of
the polarizations under polarization keys. Each of
the values under the keys is a string containing the full
path to a filename that contains the positions and
weights for the aperture illumination in the form of
a lookup table as columns (x-loc [float], y-loc
[float], wts[real], wts[imag if any]). In this case, the
lookup is for auto-corrlation of antenna weights. It only
applies when the antenna aperture class is set to
lookup-based kernel estimation instead of a functional form
forceeval [boolean] When set to False (default) the auto-correlation in
the UV plane is not evaluated if it was already evaluated
earlier. If set to True, it will be forcibly evaluated
independent of whether they were already evaluated or not
datapool [string] When set to 'avg' (or None) (default),
auto-correlations from antennas (zero-spacing with a width)
are removed from the averaged data set. If set to 'current',
the latest timestamp is used in subtracting the zero-spacing
visibilities information
pad [integer] indicates the amount of padding before imaging.
Applicable only when attribute measured_type is set to
'E-field' (MOFF imaging). The output image will be of size
2**pad-1 times the size of the antenna array grid along u-
and v-axes. Value must not be negative. Default=0 (implies no
padding of the auto-correlated footprint). pad=1 implies
padding by factor 2 along u- and v-axes for MOFF
------------------------------------------------------------------------
"""
if self.measured_type == 'E-field':
if forceeval or (not self.autocorr_removed):
if isinstance(datapool, str):
if datapool is None: datapool = 'avg'
if datapool not in ['avg', 'current']:
raise ValueError('Input keywrod datapool must be set to "avg" or "current"')
else:
raise TypeError('Input keyword data pool must be a string')
if forceeval or (not self.autocorr_set):
self.evalAutoCorr(forceeval=forceeval)
# self.evalAutoCorr(lkpinfo=lkpinfo, forceeval=forceeval)
autocorr_wts_vuf = copy.deepcopy(self.autocorr_wts_vuf)
autocorr_data_vuf = copy.deepcopy(self.autocorr_data_vuf)
pol = ['P1', 'P2']
for p in pol:
if datapool == 'avg':
if self.grid_illumination_avg[p] is not None:
vis_vuf = NP.copy(self.grid_vis_avg[p])
wts_vuf = NP.copy(self.grid_illumination_avg[p])
# autocorr_wts_vuf[p] = autocorr_wts_vuf[p][NP.newaxis,:,:,:]
vis_vuf = vis_vuf - (vis_vuf[:,self.gridv.shape[0],self.gridu.shape[1],:][:,NP.newaxis,NP.newaxis,:] / autocorr_data_vuf[p][:,self.gridv.shape[0],self.gridu.shape[1],:][:,NP.newaxis,NP.newaxis,:]) * autocorr_data_vuf[p]
wts_vuf = wts_vuf - (wts_vuf[:,self.gridv.shape[0],self.gridu.shape[1],:][:,NP.newaxis,NP.newaxis,:] / autocorr_wts_vuf[p][:,self.gridv.shape[0],self.gridu.shape[1],:][:,NP.newaxis,NP.newaxis,:]) * autocorr_wts_vuf[p]
sum_wts = NP.sum(wts_vuf, axis=(1,2), keepdims=True)
padded_wts_vuf = NP.pad(wts_vuf, ((0,0),((2**pad-1)*self.gridv.shape[0],(2**pad-1)*self.gridv.shape[0]),((2**pad-1)*self.gridu.shape[1],(2**pad-1)*self.gridu.shape[1]),(0,0)), mode='constant', constant_values=0)
padded_wts_vuf = NP.fft.ifftshift(padded_wts_vuf, axes=(1,2))
wts_lmf = NP.fft.fft2(padded_wts_vuf, axes=(1,2)) / sum_wts
if NP.abs(wts_lmf.imag).max() > 1e-10:
raise ValueError('Significant imaginary component found in the synthesized beam.')
self.nzsp_beam_avg[p] = NP.fft.fftshift(wts_lmf.real, axes=(1,2))
padded_vis_vuf = NP.pad(vis_vuf, ((0,0),((2**pad-1)*self.gridv.shape[0],(2**pad-1)*self.gridv.shape[0]),((2**pad-1)*self.gridu.shape[1],(2**pad-1)*self.gridu.shape[1]),(0,0)), mode='constant', constant_values=0)
padded_vis_vuf = NP.fft.ifftshift(padded_vis_vuf, axes=(1,2))
vis_lmf = NP.fft.fft2(padded_vis_vuf, axes=(1,2)) / sum_wts
if NP.abs(vis_lmf.imag).max() > 1e-10:
raise ValueError('Significant imaginary component found in the synthesized dirty image.')
self.nzsp_img_avg[p] = NP.fft.fftshift(vis_lmf.real, axes=(1,2))
self.nzsp_grid_vis_avg[p] = vis_vuf
self.nzsp_grid_illumination_avg[p] = wts_vuf
else:
if self.wts_vuf[p] is not None:
vis_vuf = NP.copy(self.vis_vuf[p])
wts_vuf = NP.copy(self.wts_vuf[p])
vis_vuf = vis_vuf - (vis_vuf[self.gridv.shape[0],self.gridu.shape[1],:].reshape(1,1,self.f.size) / autocorr_data_vuf[p][self.gridv.shape[0],self.gridu.shape[1],:].reshape(1,1,self.f.size)) * autocorr_data_vuf[p]
wts_vuf = wts_vuf - (wts_vuf[self.gridv.shape[0],self.gridu.shape[1],:].reshape(1,1,self.f.size) / autocorr_wts_vuf[p][self.gridv.shape[0],self.gridu.shape[1],:].reshape(1,1,self.f.size)) * autocorr_wts_vuf[p]
sum_wts = NP.sum(wts_vuf, axis=(0,1), keepdims=True)
padded_wts_vuf = NP.pad(wts_vuf, (((2**pad-1)*self.gridv.shape[0],(2**pad-1)*self.gridv.shape[0]),((2**pad-1)*self.gridu.shape[1],(2**pad-1)*self.gridu.shape[1]),(0,0)), mode='constant', constant_values=0)
padded_wts_vuf = NP.fft.ifftshift(padded_wts_vuf, axes=(0,1))
wts_lmf = NP.fft.fft2(padded_wts_vuf, axes=(0,1)) / sum_wts
if NP.abs(wts_lmf.imag).max() > 1e-10:
raise ValueError('Significant imaginary component found in the synthesized beam.')
self.nzsp_beam[p] = NP.fft.fftshift(wts_lmf.real, axes=(0,1))
padded_vis_vuf = NP.pad(vis_vuf, (((2**pad-1)*self.gridv.shape[0],(2**pad-1)*self.gridv.shape[0]),((2**pad-1)*self.gridu.shape[1],(2**pad-1)*self.gridu.shape[1]),(0,0)), mode='constant', constant_values=0)
padded_vis_vuf = NP.fft.ifftshift(padded_vis_vuf, axes=(0,1))
vis_lmf = NP.fft.fft2(padded_vis_vuf, axes=(0,1)) / sum_wts
if NP.abs(vis_lmf.imag).max() > 1e-10:
raise ValueError('Significant imaginary component found in the synthesized dirty image.')
self.nzsp_img[p] = NP.fft.fftshift(vis_lmf.real, axes=(0,1))
self.nzsp_wts_vuf[p] = wts_vuf
self.nzsp_vis_vuf[p] = vis_vuf
self.autocorr_removed = True
else:
print 'Antenna auto-correlations have been removed already'
############################################################################
def getStats(self, box_type='square', box_center=None, box_size=None,
rms_box_scale_factor=10.0, coords='physical', datapool='avg'):
"""
------------------------------------------------------------------------
Get statistics from images from inside specified boxes
NEEDS FURTHER DEVELOPMENT !!!
Inputs:
box_type [string] Shape of box. Accepted values are 'square'
(default) and 'circle' on the celestial plane. In 3D the
the box will be a cube or cylinder.
box_center [list] Center locations of boxes specified as a list one for
each box. The centers will have units as specified in input
coords. Each element must be another list, tuple or numpy
array of two or three elements. The first element refers to
the x-coordinate of the box center, the second refers to
y-coordinate of the box center. The third element (optional)
refers to the center of frequency around which the 3D box
must be placed. If third element is not specified, it will
be assumed to be center of the band. If coords is set to
'physical', these three elements will have units of dircos,
dircos and frequency (Hz). If coords is set to 'index',
these three elements must be indices of the three axes.
box_size [list] Sizes of boxes specified as a list one for each box.
Number of elements in this list will be equal to that in
input box_center. They will have 'physical' (dircos,
frequency in Hz) or 'index' units as specified in the input
coords. Each element in the list is a one- or two-element
list, tuple or numpy array. The first element is size of the
box in the celestial plane (size of square if box_type is set
to 'square', diameter of circle if box_type is set to
'circle'). The second element (optional) is size along
frequency axis. If second element is not specified, it will
be assumed to be the entire band.
rms_box_scale_factor
[scalar] Size scale on celestial plane used to determine
the box to determine the rms statistic. Must be positive.
For instance, the box size used to find the rms will use a
box that is rms_box_scale_factor times the box size on each
side used for determining the peak. Default = 10.0
coords [string] String specifying coordinates of box_center and
box_size. If set to 'physical' (default) the box_center
will have units of [dircos, dircos, frequency in Hz
(optional)] and box_size will have units of [dircos,
frequency in Hz (optional)]. If set to 'index', box_center
will have units of [index, index, index (optional)] and
box_size will have units of [number of pixels, number of
frequency channels].
datapool [string] String specifying type of image on which the
statistics will be estimated. Accepted values are 'avg'
(default), 'stack' and 'current'. These represent
time-averaged, stacked and recent images respectively
Outputs:
outstats [list] List of dictionaries one for each element in input
box_center. Each dictionary consists of the following keys
'P1' and 'P2' for the two polarizations. Under each of
these keys is another dictionary with the following keys and
values:
'peak-spectrum'
[list of numpy arrays] List of Numpy arrays
with peak value in each frequency channel. This array
is of size nchan. Length of the list is equal to the
number of timestamps as determined by input datapool.
If input datapool is set to 'current', the list will
contain one numpy array of size nchan. If datapool is
set to 'avg' or 'stack', the list will contain n_t
number of numpy arrays one for each processed
timestamp
'peak-avg'
[list] Average of each numpy array in the list under
key 'peak-spectrum'. It will have n_t elements where
n_t is the number of timestamps as determined by
input datapool
'nn-spectrum'
[list] Frequency spectrum of the nearest neighbour
pixel relative to the box center.
'mad' [list] Median Absolute Deviation(s) in
the box determined by input rms_box_scale_factor.
If input datapool is set to 'current', it will be a
one-element list, but if set to 'avg' or 'stack', it
will be a list one for each timestamp in the image
------------------------------------------------------------------------
"""
if box_type not in ['square', 'circle']:
raise ValueError('Input box_type must be specified as "square" or "circle"')
if box_center is None:
raise ValueError('Input box_center must be specified')
if box_size is None:
raise ValueError('Input box_size must be specified')
if coords not in ['physical', 'index']:
raise ValueError('Input coords must be specified as "physical" or "index"')
if datapool not in ['avg', 'current', 'stack']:
raise ValueError('Input datappol must be specified as "avg", "current" or "stack"')
if not isinstance(box_center, list):
raise TypeError('Input box_center must be a list')
if not isinstance(box_size, list):
raise TypeError('Input box_size must be a list')
if len(box_center) != len(box_size):
raise ValueError('Lengths of box_center and box_size must be equal')
if isinstance(rms_box_scale_factor, (int,float)):
rms_box_scale_factor = float(rms_box_scale_factor)
if rms_box_scale_factor <= 0.0:
raise ValueError('Input rms_box_scale_factor must be positive')
else:
raise TypeError('Input rms_box_scale_factor must be a scalar')
bandwidth = (self.f[1] - self.f[0]) * self.f.size
lfgrid = self.gridl[:,:,NP.newaxis] * NP.ones(self.f.size).reshape(1,1,-1) # nm x nl x nchan
mfgrid = self.gridm[:,:,NP.newaxis] * NP.ones(self.f.size).reshape(1,1,-1) # nm x nl x nchan
fgrid = NP.ones_like(self.gridl)[:,:,NP.newaxis] * self.f.reshape(1,1,-1) # nm x nl x nchan
outstats = []
for i in xrange(len(box_center)):
stats = {}
bc = NP.asarray(box_center[i]).reshape(-1)
bs = NP.asarray(box_size[i]).reshape(-1)
if (bc.size < 2) or (bc.size > 3):
raise ValueError('Each box center must have two or three elements')
if (bs.size < 1) or (bs.size > 2):
raise ValueError('Each box size must have one or two elements')
if bc.size == 2:
if coords == 'physical':
bc = NP.hstack((bc, NP.mean(self.f)))
else:
bc = NP.hstack((bc, self.f.size/2))
if bs.size == 1:
if coords == 'physical':
bs = NP.hstack((bs, bandwidth))
else:
bs = NP.hstack((bs, self.f.size))
if coords == 'physical':
if NP.sum(bc[:2]**2) > 1.0:
raise ValueError('Invalid dirction cosines specified')
if (bc[2] < self.f.min()) or (bc[2] > self.f.max()):
raise ValueError('Invalid frequency specified in input box_center')
else:
if (bc[0] < 0) or (bc[1] < 0) or (bc[0] > self.gridl.shape[1]) or (bc[1] > self.gridl.shape[0]):
raise ValueError('Invalid box center specified')
if bc[2] > self.f.size:
bc[2] = self.f.size
if coords == 'physical':
nn_ind2d = NP.argmin(NP.abs((lfgrid[:,:,0] - bc[0])**2 + (mfgrid[:,:,0] - bc[1])**2))
unraveled_nn_ind2d = NP.unravel_index(nn_ind2d, self.gridl.shape)
unraveled_nn_ind3d = (NP.asarray([unraveled_nn_ind2d[0]]*self.f.size), NP.asarray([unraveled_nn_ind2d[1]]*self.f.size), NP.arange(self.f.size))
if box_type == 'square':
ind3d = (NP.abs(lfgrid - bc[0]) <= 0.5*bs[0]) & (NP.abs(mfgrid - bc[1]) <= 0.5*bs[0]) & (NP.abs(fgrid - bc[2]) <= 0.5*bs[1])
ind3d_rmsbox = (NP.abs(lfgrid - bc[0]) <= 0.5*rms_box_scale_factor*bs[0]) & (NP.abs(mfgrid - bc[1]) <= 0.5*rms_box_scale_factor*bs[0]) & (NP.abs(fgrid - bc[2]) <= 0.5*bs[1])
else:
ind3d = (NP.sqrt(NP.abs(lfgrid - bc[0])**2 + NP.abs(mfgrid - bc[0])**2) <= 0.5*bs[0]) & (NP.abs(fgrid - bc[2]) <= 0.5*bs[1])
ind3d_rmsbox = (NP.sqrt(NP.abs(lfgrid - bc[0])**2 + NP.abs(mfgrid - bc[0])**2) <= 0.5*rms_box_scale_factor*bs[0]) & (NP.abs(fgrid - bc[2]) <= 0.5*bs[1])
msk = NP.logical_not(ind3d)
msk_rms = NP.logical_not(ind3d_rmsbox)
for apol in ['P1', 'P2']:
stats[apol] = {'peak-spectrum': [], 'peak-avg': [], 'mad': [], 'nn-spectrum': [], 'nn-avg': []}
if datapool == 'current':
if self.nzsp_img[apol] is not None:
img_masked = MA.array(self.nzsp_img[apol], mask=msk)
stats[apol]['peak-spectrum'] += [NP.amax(NP.abs(img_masked), axis=(0,1))]
stats[apol]['peak-avg'] += [NP.mean(stats[apol]['peak-spectrum'])]
stats[apol]['nn-spectrum'] += [NP.abs(img_masked[unraveled_nn_ind3d])]
stats[apol]['nn-avg'] += [NP.mean(stats[apol]['nn-spectrum'])]
img_masked = MA.array(self.nzsp_img[apol], mask=msk_rms)
mdn = NP.median(img_masked[~img_masked.mask])
absdev = NP.abs(img_masked - mdn)
stats[apol]['mad'] += [NP.median(absdev[~absdev.mask])]
else:
if datapool == 'avg':
if self.nzsp_img_avg[apol] is not None:
for ti in range(self.nzsp_img_avg[apol].shape[0]):
img_masked = MA.array(self.nzsp_img_avg[apol][ti,...], mask=msk)
stats[apol]['peak-spectrum'] += [NP.amax(NP.abs(img_masked), axis=(0,1))]
stats[apol]['peak-avg'] += [NP.mean(stats[apol]['peak-spectrum'][ti])]
stats[apol]['nn-spectrum'] += [NP.abs(img_masked[unraveled_nn_ind3d])]
stats[apol]['nn-avg'] += [NP.mean(stats[apol]['nn-spectrum'][ti])]
img_masked = MA.array(self.nzsp_img_avg[apol][ti,...], mask=msk_rms)
mdn = NP.median(img_masked[~img_masked.mask])
absdev = NP.abs(img_masked - mdn)
stats[apol]['mad'] += [NP.median(absdev[~absdev.mask])]
else:
if self.img_stack[apol] is not None:
for ti in range(self.img_stack[apol].shape[0]):
img_masked = MA.array(self.img_stack[apol][ti,...], mask=msk)
stats[apol]['peak-spectrum'] += [NP.amax(NP.abs(img_masked), axis=(0,1))]
stats[apol]['peak-avg'] += [NP.mean(stats[apol]['peak-spectrum'][ti])]
stats[apol]['nn-spectrum'] += [NP.abs(img_masked[unraveled_nn_ind3d])]
stats[apol]['nn-avg'] += [NP.mean(stats[apol]['nn-spectrum'][ti])]
img_masked = MA.array(self.img_stack[apol][ti,...], mask=msk_rms)
mdn = NP.median(img_masked[~img_masked.mask])
absdev = NP.abs(img_masked - mdn)
stats[apol]['mad'] += [NP.median(absdev[~absdev.mask])]
outstats += [stats]
else:
pass
return outstats
############################################################################
def save(self, imgfile, pol=None, overwrite=False, verbose=True):
"""
------------------------------------------------------------------------
Saves the image information to disk.
Input:
imgfile [string] Image filename with full path. Will be appended
with '.fits' extension
Keyword Input(s):
pol [string] indicates which polarization information to be
saved. Allowed values are 'P1', 'P2' or None (default). If
None, information on both polarizations are saved.
overwrite [boolean] True indicates overwrite even if a file already
exists. Default = False (does not overwrite)
verbose [boolean] If True (default), prints diagnostic and progress
messages. If False, suppress printing such messages.
------------------------------------------------------------------------
"""
try:
imgfile
except NameError:
raise NameError('No filename provided. Aborting Image.save()')
filename = imgfile + '.fits'
if verbose:
print '\nSaving image information...'
hdulst = []
hdulst += [fits.PrimaryHDU()]
hdulst[0].header['f0'] = (self.f0, 'Center frequency (Hz)')
hdulst[0].header['tobs'] = (self.timestamp, 'Timestamp associated with observation.')
hdulst[0].header['EXTNAME'] = 'PRIMARY'
if verbose:
print '\tCreated a primary HDU.'
hdulst += [fits.ImageHDU(self.f, name='FREQ')]
if verbose:
print '\t\tCreated an extension HDU of {0:0d} frequency channels'.format(len(self.f))
if (pol is None) or (pol == 'P1'):
if verbose:
print '\tWorking on polarization P1...'
if self.lf_P1 is not None:
hdulst += [fits.ImageHDU(self.lf_P1, name='grid_lf_P1')]
if verbose:
print '\t\tCreated an extension HDU of l-coordinates of grid of size: {0[0]} \n\t\t\tfor each of the {0[1]} frequency channels'.format(self.lf_P1.shape)
if self.mf_P1 is not None:
hdulst += [fits.ImageHDU(self.mf_P1, name='grid_mf_P1')]
if verbose:
print '\t\tCreated an extension HDU of m-coordinates of grid of size: {0[0]} \n\t\t\tfor each of the {0[1]} frequency channels'.format(self.mf_P1.shape)
if self.holograph_PB_P1 is not None:
hdulst += [fits.ImageHDU(self.holograph_PB_P1.real, name='holograph_PB_P1_real')]
hdulst += [fits.ImageHDU(self.holograph_PB_P1.imag, name='holograph_PB_P1_imag')]
if verbose:
print "\t\tCreated separate extension HDUs of grid's voltage reception pattern spectra\n\t\t\twith size {0[0]}x{0[1]}x{0[2]} for real and imaginary parts.".format(self.holograph_PB_P1.shape)
if self.holograph_P1 is not None:
hdulst += [fits.ImageHDU(self.holograph_P1.real, name='holograph_P1_real')]
hdulst += [fits.ImageHDU(self.holograph_P1.imag, name='holograph_P1_imag')]
if verbose:
print "\t\tCreated separate extension HDUs of grid's voltage holograph spectra of \n\t\t\tsize {0[0]}x{0[1]}x{0[2]} for real and imaginary parts.".format(self.holograph_P1.shape)
if (pol is None) or (pol == 'P2'):
if verbose:
print '\tWorking on polarization P2...'
if self.lf_P2 is not None:
hdulst += [fits.ImageHDU(self.lf_P2, name='grid_lf_P2')]
if verbose:
print '\t\tCreated an extension HDU of l-coordinates of grid of size: {0[0]} \n\t\t\tfor each of the {0[1]} frequency channels'.format(self.lf_P2.shape)
if self.mf_P2 is not None:
hdulst += [fits.ImageHDU(self.mf_P2, name='grid_mf_P2')]
if verbose:
print '\t\tCreated an extension HDU of m-coordinates of grid of size: {0[0]} \n\t\t\tfor each of the {0[1]} frequency channels'.format(self.mf_P2.shape)
if self.holograph_PB_P2 is not None:
hdulst += [fits.ImageHDU(self.holograph_PB_P2.real, name='holograph_PB_P2_real')]
hdulst += [fits.ImageHDU(self.holograph_PB_P2.imag, name='holograph_PB_P2_imag')]
if verbose:
print "\t\tCreated separate extension HDUs of grid's voltage reception pattern spectra\n\t\t\twith size {0[0]}x{0[1]}x{0[2]} for real and imaginary parts.".format(self.holograph_PB_P2.shape)
if self.holograph_P2 is not None:
hdulst += [fits.ImageHDU(self.holograph_P2.real, name='holograph_P2_real')]
hdulst += [fits.ImageHDU(self.holograph_P2.imag, name='holograph_P2_imag')]
if verbose:
print "\t\tCreated separate extension HDUs of grid's voltage holograph spectra of \n\t\t\tsize {0[0]}x{0[1]}x{0[2]} for real and imaginary parts.".format(self.holograph_P2.shape)
if verbose:
print '\tNow writing FITS file to disk:\n\t\t{0}'.format(filename)
hdu = fits.HDUList(hdulst)
hdu.writeto(filename, clobber=overwrite)
if verbose:
print '\tImage information written successfully to FITS file on disk:\n\t\t{0}\n'.format(filename)
################################################################################
class PolInfo(object):
"""
----------------------------------------------------------------------------
Class to manage polarization information of an antenna.
Attributes:
Et [dictionary] holds measured complex electric field time series
under 2 polarizations which are stored under keys 'P1', and 'P2'
Ef [dictionary] holds complex electric field spectra under 2
polarizations which are stored under keys 'P1', and 'P2'. The
length of the spectra is twice that of the time series.
flag [dictionary] holds boolean flags for each of the 2 polarizations
which are stored under keys 'P1', and 'P2'. Default=True means
that polarization is flagged.
Member functions:
__init__(): Initializes an instance of class PolInfo
__str__(): Prints a summary of current attributes.
FT(): Perform a Fourier transform of an Electric field time series
after doubling the length of the sequence with zero padding
(in order to be identical to what would be obtained from a
XF operation)
update_flags() Updates the flags based on current inputs and verifies and
updates flags based on current values of the electric field.
update(): Updates the electric field time series and spectra, and
flags for different polarizations
delay_compensation():
Routine to apply delay compensation to Electric field
spectra through additional phase. This assumes that the
spectra have already been made
Read the member function docstrings for details.
----------------------------------------------------------------------------
"""
def __init__(self, nsamples=1):
"""
------------------------------------------------------------------------
Initialize the PolInfo Class which manages polarization information of
an antenna.
Class attributes initialized are:
Et, Ef, flag
Read docstring of class PolInfo for details on these attributes.
------------------------------------------------------------------------
"""
self.Et = {}
self.Ef = {}
self.flag = {}
if not isinstance(nsamples, int):
raise TypeError('nsamples must be an integer')
elif nsamples <= 0:
nsamples = 1
for pol in ['P1', 'P2']:
self.Et[pol] = NP.empty(nsamples, dtype=NP.complex64)
self.Ef[pol] = NP.empty(2*nsamples, dtype=NP.complex64)
self.Et[pol].fill(NP.nan)
self.Ef[pol].fill(NP.nan)
self.flag[pol] = True
############################################################################
def __str__(self):
return ' Instance of class "{0}" in module "{1}" \n flag (P1): {2} \n flag (P2): {3} '.format(self.__class__.__name__, self.__module__, self.flag['P1'], self.flag['P2'])
############################################################################
def FT(self, pol=None):
"""
------------------------------------------------------------------------
Perform a Fourier transform of an Electric field time series after
doubling the length of the sequence with zero padding (in order to be
identical to what would be obtained from a XF operation)
Keyword Input(s):
pol [scalar or list] polarization to be Fourier transformed. Set
to 'P1' and/or 'P2'. If None (default) provided, time series
of both polarizations are Fourier transformed.
------------------------------------------------------------------------
"""
if pol is None:
pol = ['P1', 'P2']
for p in pol:
if p in ['P1', 'P2']:
Et = NP.pad(self.Et[p], [(0,0), (0,self.Et[p].shape[1])], 'constant', constant_values=(0,0))
self.Ef[p] = DSP.FT1D(Et, ax=0, use_real=False, inverse=False, shift=True)
else:
raise ValueError('polarization string "{0}" unrecognized. Verify inputs. Aborting {1}.{2}()'.format(p, self.__class__.__name__, 'FT'))
############################################################################
def delay_compensation(self, delaydict):
"""
------------------------------------------------------------------------
Routine to apply delay compensation to Electric field spectra through
additional phase. This assumes that the spectra have already been made
Keyword input(s):
delaydict [dictionary] contains one or both polarization keys, namely,
'P1' and 'P2'. The value under each of these keys is another
dictionary with the following keys and values:
'frequencies': scalar, list or numpy vector specifying the
frequencie(s) (in Hz) for which delays are specified.
If a scalar is specified, the delays are assumed to
be frequency independent and the delays are assumed
to be valid for all frequencies. If a vector is
specified, it must be of same size as the delays and
as the number of samples in the electric field
timeseries. These frequencies are assumed to match
those of the electric field spectrum. No default.
'delays': list or numpy vector specifying the delays (in
seconds) at the respective frequencies which are to
be compensated through additional phase in the
electric field spectrum. Must be of same size as
frequencies and the size of the electric field
timeseries. No default.
'fftshifted': boolean scalar indicating if the frequencies
provided have already been fft-shifted. If True
(default) or this key is absent, the frequencies are
assumed to have been fft-shifted. If False, they have
to be fft-shifted before applying the delay
compensation to rightly align with the fft-shifted
electric field spectrum computed in member function
FT().
------------------------------------------------------------------------
"""
try:
delaydict
except NameError:
raise NameError('Delay information must be supplied for delay correction in the dictionary delaydict.')
if not isinstance(delaydict, dict):
raise TypeError('delaydict must be a dictionary')
for pol in delaydict:
if pol not in ['P1','P2']:
raise ValueError('Invalid specification for polarization')
if 'delays' in delaydict[pol]:
if NP.asarray(delaydict[pol]['delays']).size == 1:
delays = delaydict[pol]['delays'] + NP.zeros(self.Et[pol].size)
else:
if (NP.asarray(delaydict[pol]['delays']).size == self.Et[pol].size):
delays = NP.asarray(delaydict[pol]['delays']).ravel()
else:
raise IndexError('Size of delays in delaydict must be equal to 1 or match that of the timeseries.')
if 'frequencies' in delaydict[pol]:
frequencies = NP.asarray(delaydict[pol]['frequencies']).ravel()
if frequencies.size != self.Et[pol].size:
raise IndexError('Size of frequencies must match that of the Electric field time series.')
else:
raise KeyError('Key "frequencies" not found in dictionary delaydict[{0}] holding delay information.'.format(pol))
temp_phases = 2 * NP.pi * delays * frequencies
# Convert phases to fft-shifted arrangement based on key "fftshifted" in delaydict
if 'fftshifted' in delaydict[pol]:
if not isinstance(delaydict[pol]['fftshifted'], bool):
raise TypeError('Value under key "fftshifted" must be boolean')
if not delaydict[pol]['fftshifted']:
temp_phases = NP.fft.fftshift(temp_phases)
# Expand the size to account for the fact that the Fourier transform of the timeseries is obtained after zero padding
phases = NP.empty(2*frequencies.size)
phases[0::2] = temp_phases
phases[1::2] = temp_phases
self.Ef[pol] *= NP.exp(1j * phases.reshape(1,-1))
## INSERT FEATURE: yet to modify the timeseries after application of delay compensation ##
############################################################################
def update_flags(self, flags=None, verify=False):
"""
------------------------------------------------------------------------
Updates the flags based on current inputs and verifies and updates flags
based on current values of the electric field.
Inputs:
flags [dictionary] holds boolean flags for each of the 2
polarizations which are stored under keys 'P1', and 'P2'.
Default=None means no new flagging to be applied. If
the value under the polarization key is True, it is to be
flagged and if False, it is to be unflagged.
verify [boolean] If True, verify and update the flags, if necessary.
Electric fields are checked for NaN values and if found, the
flag in the corresponding polarization is set to True.
Default=False.
Flag verification and re-updating happens if flags is set to None or if
verify is set to True.
------------------------------------------------------------------------
"""
# if not isinstance(stack, bool):
# raise TypeError('Input keyword stack must be of boolean type')
if not isinstance(verify, bool):
raise TypeError('Input keyword verify must be of boolean type')
if flags is not None:
if not isinstance(flags, dict):
raise TypeError('Input parameter flags must be a dictionary')
for pol in ['P1', 'P2']:
if pol in flags:
if isinstance(flags[pol], bool):
self.flag[pol] = flags[pol]
else:
raise TypeError('flag values must be boolean')
# Perform flag verification and re-update current flags
if verify or (flags is None):
for pol in ['P1', 'P2']:
if NP.any(NP.isnan(self.Et[pol])) and NP.any(NP.isnan(self.Ef[pol])):
self.flag[pol] = True
############################################################################
def update(self, Et=None, Ef=None, flags=None, delaydict=None,
verify=False):
"""
------------------------------------------------------------------------
Updates the electric field time series and spectra, and flags for
different polarizations
Inputs:
Et [dictionary] holds time series under 2 polarizations which are
stored under keys 'P1', and 'P2'. Default=None implies no updates
for Et.
Ef [dictionary] holds spectra under 2 polarizations which are
stored under keys 'P1', and 'P2'. Default=None implies no updates
for Ef.
flag [dictionary] holds boolean flags for each of the 2 polarizations
which are stored under keys 'P1', and 'P2'. Default=None means
no updates for flags.
delaydict
[dictionary] contains one or both polarization keys, namely,
'P1' and 'P2'. The value under each of these keys is another
dictionary with the following keys and values:
'frequencies': scalar, list or numpy vector specifying the
frequencie(s) (in Hz) for which delays are specified.
If a scalar is specified, the delays are assumed to be
frequency independent and the delays are assumed to be
valid for all frequencies. If a vector is specified,
it must be of same size as the delays and as the
number of samples in the electric field timeseries.
These frequencies are assumed to match those of the
electric field spectrum. No default.
'delays': list or numpy vector specifying the delays (in
seconds) at the respective frequencies which are to be
compensated through additional phase in the electric
field spectrum. Must be of same size as frequencies
and the size of the electric field timeseries. No
default.
'fftshifted': boolean scalar indicating if the frequencies
provided have already been fft-shifted. If True
(default) or this key is absent, the frequencies are
assumed to have been fft-shifted. If False, they have
to be fft-shifted before applying the delay
compensation to rightly align with the fft-shifted
electric field spectrum computed in member function
FT().
verify [boolean] If True, verify and update the flags, if necessary.
Electric fields are checked for NaN values and if found, the
flag in the corresponding polarization is set to True.
Default=False.
------------------------------------------------------------------------
"""
current_flags = copy.deepcopy(self.flag)
if flags is None:
flags = copy.deepcopy(current_flags)
# if flags is not None:
# self.update_flags(flags)
if Et is not None:
if isinstance(Et, dict):
for pol in ['P1', 'P2']:
if pol in Et:
self.Et[pol] = Et[pol]
if NP.any(NP.isnan(Et[pol])):
# self.Et[pol] = NP.nan
flags[pol] = True
# self.flag[pol] = True
self.FT() # Update the spectrum
else:
raise TypeError('Input parameter Et must be a dictionary')
if Ef is not None:
if isinstance(Ef, dict):
for pol in ['P1', 'P2']:
if pol in Ef:
self.Ef[pol] = Ef[pol]
if NP.any(NP.isnan(Ef[pol])):
# self.Ef[pol] = NP.nan
flags[pol] = True
# self.flag[pol] = True
else:
raise TypeError('Input parameter Ef must be a dictionary')
if delaydict is not None:
self.delay_compensation(delaydict)
# Verify and update flags
self.update_flags(flags=flags, verify=verify)
################################################################################
class Antenna(object):
"""
----------------------------------------------------------------------------
Class to manage individual antenna information.
Attributes:
label: [Scalar] A unique identifier (preferably a string) for the
antenna.
typetag [scalar or string] Tag (integer or string) to identify antenna
type. Will be used in determining if the antenna array is made
of identical antennas or not
latitude: [Scalar] Latitude of the antenna's location.
longitude: [Scalar] Longitude of the antenna's location.
location: [Instance of GEOM.Point class] The location of the antenna in
local East, North, Up coordinate system.
timestamp: [Scalar] String or float representing the timestamp for the
current attributes
timestamps [list] list of all timestamps to be held in the stack
t: [vector] The time axis for the time series of electric fields
f: [vector] Frequency axis obtained by a Fourier Transform of
the electric field time series. Same length as attribute t
f0: [Scalar] Center frequency in Hz.
antpol: [Instance of class PolInfo] polarization information for the
antenna. Read docstring of class PolInfo for details
aperture [Instance of class APR.Aperture] aperture information
for the antenna. Read docstring of class Aperture for
details
Et_stack [dictionary] holds a stack of complex electric field time series
measured at various time stamps under 2 polarizations which are
stored under keys 'P1' and 'P2'
Ef_stack [dictionary] holds a stack of complex electric field spectra
measured at various time stamps under 2 polarizations which are
stored under keys 'P1' and 'P2'
flag_stack
[dictionary] holds a stack of flags appropriate for different
time stamps as a numpy array under 2 polarizations which are
stored under keys 'P1' and 'P2'
wts: [dictionary] The gridding weights for antenna. Different
polarizations 'P1' and 'P2' form the keys
of this dictionary. These values are in general complex. Under
each key, the values are maintained as a list of numpy vectors,
where each vector corresponds to a frequency channel. See
wtspos_scale for more requirements.
wtspos [dictionary] two-dimensional locations of the gridding weights
in wts for each polarization under keys 'P1' and 'P2'. The
locations are in ENU coordinate system as a list of 2-column
numpy arrays. Each 2-column array in the list is the position
of the gridding weights for a corresponding frequency
channel. The size of the list must be the same as wts and the
number of channels. Units are in number of wavelengths. See
wtspos_scale for more requirements.
wtspos_scale [dictionary] The scaling of weights is specified for each
polarization under one of the keys 'P1' and 'P2'.
The values under these keys can be either None (default) or
'scale'. If None, numpy vectors in wts and wtspos under
corresponding keys are provided for each frequency channel. If
set to 'scale' wts and wtspos contain a list of only one
numpy array corresponding to a reference frequency. This is
scaled internally to correspond to the first channel.
The gridding positions are correspondingly scaled to all the
frequency channels.
blc [2-element numpy array] Bottom Left corner where the
antenna contributes non-zero weight to the grid. Same
for all polarizations
trc [2-element numpy array] Top right corner where the
antenna contributes non-zero weight to the grid. Same
for all polarizations
Member Functions:
__init__(): Initializes an instance of class Antenna
__str__(): Prints a summary of current attributes
channels(): Computes the frequency channels from a temporal Fourier
Transform
FT() Computes the Fourier transform of the time series of the
antennas in the antenna array to compute the visibility
spectra. Read docstring of member function FT() of class
PolInfo
FT_pp() Computes the Fourier transform of the time series of the
antennas in the antenna array to compute the visibility
spectra. Read docstring of member function FT() of class
PolInfo. Differs from FT() member function in that here
an instance of class Antenna is returned and is mainly used
in case of parallel processing and is not meant to be
accessed directly by the user. Use FT() for all other pruposes.
update_flags()
Updates flags for polarizations provided as input parameters
update(): Updates the antenna instance with newer attribute values
Updates the electric field spectrum and timeseries. It also
applies Fourier transform if timeseries is updated
update_pp() Wrapper for member function update() and returns the updated
instance of this class. Mostly intended to be used when
parallel processing is applicable and not to be used directly.
Use update() instead when updates are to be applied directly.
get_E_fields()
Returns the electric fields based on selection criteria on
timestamp flags, timestamps and frequency channel indices and
the type of data (most recent or stacked electric fields)
evalGridIllumination()
Evaluate antenna illumination function on a specified grid
save(): Saves the antenna information to disk. Needs serious
development.
Read the member function docstrings for details.
----------------------------------------------------------------------------
"""
def __init__(self, label, typetag, latitude, longitude, location,
center_freq, nsamples=1, aperture=None):
"""
------------------------------------------------------------------------
Initialize the Antenna Class which manages an antenna's information
Class attributes initialized are:
label, latitude, longitude, location, pol, t, timestamp, f0, f, wts,
wtspos, wtspos_scale, blc, trc, timestamps, antpol, Et_stack, Ef_stack,
flag_stack, aperture, typetag
Read docstring of class Antenna for details on these attributes.
------------------------------------------------------------------------
"""
try:
label
except NameError:
raise NameError('Antenna label must be provided.')
try:
typetag
except NameError:
raise NameError('Antenna type tag must be provided.')
if not isinstance(typetag, (int,str)):
raise TypeError('Antenna type tag must be an integer or string')
try:
latitude
except NameError:
latitude = 0.0
try:
longitude
except NameError:
longitude = 0.0
try:
location
except NameError:
self.location = GEOM.Point()
try:
center_freq
except NameError:
raise NameError('Center frequency must be provided.')
self.label = label
self.typetag = typetag
self.latitude = latitude
self.longitude = longitude
if isinstance(location, GEOM.Point):
self.location = location
elif isinstance(location, (list, tuple, NP.ndarray)):
self.location = GEOM.Point(location)
else:
raise TypeError('Antenna position must be a 3-element tuple or an instance of GEOM.Point')
if aperture is not None:
if isinstance(aperture, APR.Aperture):
if len(aperture.pol) != 2:
raise ValueError('Antenna aperture must contain dual polarization types')
self.aperture = aperture
else:
raise TypeError('aperture must be an instance of class Aperture found in module {0}'.format(APR.__name__))
else:
self.aperture = APR.Aperture(pol_type='dual')
self.antpol = PolInfo(nsamples=nsamples)
self.t = 0.0
self.timestamp = 0.0
self.timestamps = []
self.f0 = center_freq
self.f = self.f0
self.Et_stack = {}
self.Ef_stack = {}
self.flag_stack = {}
self.wts = {}
self.wtspos = {}
self.wtspos_scale = {}
self._gridinfo = {}
for pol in ['P1', 'P2']:
self.Et_stack[pol] = None
self.Ef_stack[pol] = None
self.flag_stack[pol] = NP.asarray([])
self.wtspos[pol] = []
self.wts[pol] = []
self.wtspos_scale[pol] = None
self._gridinfo[pol] = {}
self.blc = NP.asarray([self.location.x, self.location.y]).reshape(1,-1)
self.trc = NP.asarray([self.location.x, self.location.y]).reshape(1,-1)
############################################################################
def __str__(self):
return ' Instance of class "{0}" in module "{1}" \n label: {2} \n typetag: {3} \n location: {4}'.format(self.__class__.__name__, self.__module__, self.label, self.typetag, self.location.__str__())
############################################################################
def channels(self):
"""
------------------------------------------------------------------------
Computes the frequency channels from a temporal Fourier Transform
Output(s):
Frequencies corresponding to channels obtained by a Fourier Transform
of the time series.
------------------------------------------------------------------------
"""
return DSP.spectax(2*self.t.size, self.t[1]-self.t[0], shift=True)
############################################################################
def FT(self, pol=None):
"""
------------------------------------------------------------------------
Computes the Fourier transform of the time series of the antennas in the
antenna array to compute the visibility spectra. Read docstring of
member function FT() of class PolInfo
Inputs:
pol [scalar or list] Scalar string or list of strings specifying
polarization. Accepted values are 'P1' and/or 'P2'. Default=None
means both time series of electric fields of both polarizations
are Fourier transformed
# stack [boolean] If set to True, perform Fourier transform on the
# timestamp-stacked electric field time series. Default = False
------------------------------------------------------------------------
"""
self.antpol.FT(pol=pol)
############################################################################
def FT_pp(self, pol=None):
"""
------------------------------------------------------------------------
Computes the Fourier transform of the time series of the antennas in the
antenna array to compute the visibility spectra. Read docstring of
member function FT() of class PolInfo. Differs from FT() member function
in that here an instance of class Antenna is returned and is mainly used
in case of parallel processing and is not meant to be accessed directly
by the user. Use FT() for all other pruposes.
Inputs:
pol [scalar or list] Scalar string or list of strings specifying
polarization. Accepted values are 'P1' and/or 'P2'. Default=None
means both time series of electric fields of both polarizations
are Fourier transformed
# stack [boolean] If set to True, perform Fourier transform on the
# timestamp-stacked electric field time series. Default = False
Outputs:
Instance of class Antenna
------------------------------------------------------------------------
"""
self.antpol.FT(pol=pol)
return self
############################################################################
def update_flags(self, flags=None, stack=False, verify=True):
"""
------------------------------------------------------------------------
Updates flags for antenna polarizations. Invokes member function
update_flags() of class PolInfo
Inputs:
flags [dictionary] boolean flags for each of the 2 polarizations
of the antenna which are stored under keys 'P1' and 'P2',
Default=None means no updates for flags.
stack [boolean] If True (default), appends the updated flag to the
end of the stack of flags as a function of timestamp. If False,
updates the last flag in the stack with the updated flag and
does not append
verify [boolean] If True, verify and update the flags, if necessary.
Electric fields are checked for NaN values and if found, the
flag in the corresponding polarization is set to True.
Default=True
------------------------------------------------------------------------
"""
# By default carry over the flags from previous timestamp
if flags is None:
flags = copy.deepcopy(self.antpol.flag)
self.antpol.update_flags(flags=flags, verify=verify)
# Stack on to last value or update last value in stack
for pol in ['P1', 'P2']:
if stack is True:
self.flag_stack[pol] = NP.append(self.flag_stack[pol], self.antpol.flag[pol])
else:
if self.flag_stack[pol].size == 0:
self.flag_stack[pol] = NP.asarray(self.antpol.flag[pol]).reshape(-1)
else:
self.flag_stack[pol][-1] = self.antpol.flag[pol]
self.flag_stack[pol] = self.flag_stack[pol].astype(NP.bool)
############################################################################
def update(self, update_dict=None, verbose=True):
"""
------------------------------------------------------------------------
Updates the antenna instance with newer attribute values. Updates
the electric field spectrum and timeseries. It also applies Fourier
transform if timeseries is updated
Inputs:
update_dict [dictionary] contains the following keys and values:
label [Scalar] A unique identifier (preferably a string) for
the antenna. Default=None means no update to apply
typetag [scalar or string] Antenna type identifier (integer or
preferably string) which will be used in determining if
all antennas in the antenna array are identical
latitude [Scalar] Latitude of the antenna's location. Default=None
means no update to apply
location [Instance of GEOM.Point class] The location of the
antenna in local East, North, Up (ENU) coordinate system.
Default=None means no update to apply
timestamp [Scalar] String or float representing the timestamp for
the current attributes. Default=None means no update to
apply
t [vector] The time axis for the electric field time
series. Default=None means no update to apply
flags [dictionary] holds boolean flags for each of the 2
polarizations which are stored under keys 'P1' and 'P22'.
Default=None means no updates for flags.
Et [dictionary] holds time series under 2 polarizations
which are stored under keys 'P1' and 'P22'. Default=None
implies no updates for Et.
Ef [dictionary] holds spectrum under 2 polarizations
which are stored under keys 'P1' and 'P22'. Default=None
implies no updates for Ef.
aperture [instance of class APR.Aperture] aperture
information for the antenna. Read docstring of class
Aperture for details
wtsinfo [dictionary] consists of weights information for each of
the two polarizations under keys 'P1' and 'P2'. Each of
the values under the keys is a list of dictionaries.
Length of list is equal to the number of frequency
channels or one (equivalent to setting wtspos_scale to
'scale'.). The list is indexed by the frequency channel
number. Each element in the list consists of a dictionary
corresponding to that frequency channel. Each dictionary
consists of these items with the following keys:
wtspos [2-column Numpy array, optional] u- and v-
positions for the gridding weights. Units
are in number of wavelengths.
wts [Numpy array] Complex gridding weights. Size
is equal to the number of rows in wtspos
above
orientation [scalar] Orientation (in radians) of the
wtspos coordinate system relative to the
local ENU coordinate system. It is measured
North of East.
lookup [string] If set, refers to a file location
containing the wtspos and wts information
above as columns (x-loc [float], y-loc
[float], wts[real], wts[imag if any]). If
set, wtspos and wts information are obtained
from this lookup table and the wtspos and wts
keywords in the dictionary are ignored. Note
that wtspos values are obtained after
dividing x- and y-loc lookup values by the
wavelength
gridfunc_freq
[String scalar] If set to None (not provided) or to
'scale' assumes that wtspos in wtsinfo are given for a
reference frequency which need to be scaled for the
frequency channels. Will be ignored if the list of
dictionaries under the polarization keys in wtsinfo have
number of elements equal to the number of frequency
channels.
ref_freq [Scalar] Positive value (in Hz) of reference frequency
(used if gridfunc_freq is set to None or 'scale') at
which wtspos is provided. If set to None, ref_freq is
assumed to be equal to the center frequency in the class
Antenna's attribute.
delaydict [Dictionary] contains information on delay compensation
to be applied to the fourier transformed electric fields
under each polarization which are stored under keys 'P1'
and 'P2'. Default is None (no delay compensation to be
applied). Refer to the docstring of member function
delay_compensation() of class PolInfo for more details.
stack [boolean] If True (default), appends the updated flag
and data to the end of the stack as a function of
timestamp. If False, updates the last flag and data in
the stack and does not append
verify [boolean] If True, verify and update the flags, if
necessary. Electric fields are checked for NaN values and
if found, the flag in the corresponding polarization is
set to True. Default=True
verbose [boolean] If True, prints diagnostic and progress messages.
If False (default), suppress printing such messages.
------------------------------------------------------------------------
"""
label = None
typetag = None
location = None
timestamp = None
t = None
flags = None
stack = False
verify_flags = True
Et = None
Ef = None
wtsinfo = None
gridfunc_freq = None
ref_freq = None
delaydict = None
aperture = None
if update_dict is not None:
if not isinstance(update_dict, dict):
raise TypeError('Input parameter containing updates must be a dictionary')
if 'label' in update_dict: label = update_dict['label']
if 'typetag' in update_dict: typetag = update_dict['typetag']
if 'location' in update_dict: location = update_dict['location']
if 'timestamp' in update_dict: timestamp = update_dict['timestamp']
if 't' in update_dict: t = update_dict['t']
if 'Et' in update_dict: Et = update_dict['Et']
if 'Ef' in update_dict: Ef = update_dict['Ef']
if 'flags' in update_dict: flags = update_dict['flags']
if 'stack' in update_dict: stack = update_dict['stack']
if 'verify_flags' in update_dict: verify_flags = update_dict['verify_flags']
if 'wtsinfo' in update_dict: wtsinfo = update_dict['wtsinfo']
if 'gridfunc_freq' in update_dict: gridfunc_freq = update_dict['gridfunc_freq']
if 'ref_freq' in update_dict: ref_freq = update_dict['ref_freq']
if 'delaydict' in update_dict: delaydict = update_dict['delaydict']
if 'aperture' in update_dict: aperture = update_dict['aperture']
if label is not None: self.label = label
if typetag is not None: self.typetag = typetag
if location is not None: self.location = location
if timestamp is not None:
self.timestamp = timestamp
self.timestamps += [copy.deepcopy(timestamp)]
if t is not None:
self.t = t
self.f = self.f0 + self.channels()
# Updates, Et, Ef, delays, flags and verifies flags
if (Et is not None) or (Ef is not None) or (delaydict is not None) or (flags is not None):
self.antpol.update(Et=Et, Ef=Ef, delaydict=delaydict, flags=flags, verify=verify_flags)
# Stack flags and data
self.update_flags(flags=None, stack=stack, verify=True)
for pol in ['P1', 'P2']:
if self.Et_stack[pol] is None:
self.Et_stack[pol] = copy.deepcopy(self.antpol.Et[pol].reshape(1,-1))
self.Ef_stack[pol] = copy.deepcopy(self.antpol.Ef[pol].reshape(1,-1))
else:
if stack:
self.Et_stack[pol] = NP.vstack((self.Et_stack[pol], self.antpol.Et[pol].reshape(1,-1)))
self.Ef_stack[pol] = NP.vstack((self.Ef_stack[pol], self.antpol.Ef[pol].reshape(1,-1)))
else:
self.Et_stack[pol][-1,:] = copy.deepcopy(self.antpol.Et[pol].reshape(1,-1))
self.Ef_stack[pol][-1,:] = copy.deepcopy(self.antpol.Ef[pol].reshape(1,-1))
blc_orig = NP.copy(self.blc)
trc_orig = NP.copy(self.trc)
eps = 1e-6
if aperture is not None:
if isinstance(aperture, APR.Aperture):
self.aperture = copy.deepcopy(aperture)
else:
raise TypeError('Update for aperture must be an instance of class Aperture.')
if wtsinfo is not None:
if not isinstance(wtsinfo, dict):
raise TypeError('Input parameter wtsinfo must be a dictionary.')
self.wtspos = {}
self.wts = {}
self.wtspos_scale = {}
angles = []
max_wtspos = []
for pol in ['P1', 'P2']:
self.wts[pol] = []
self.wtspos[pol] = []
self.wtspos_scale[pol] = None
if pol in wtsinfo:
if len(wtsinfo[pol]) == len(self.f):
angles += [elem['orientation'] for elem in wtsinfo[pol]]
for i in xrange(len(self.f)):
rotation_matrix = NP.asarray([[NP.cos(-angles[i]), NP.sin(-angles[i])],
[-NP.sin(-angles[i]), NP.cos(-angles[i])]])
if ('lookup' not in wtsinfo[pol][i]) or (wtsinfo[pol][i]['lookup'] is None):
self.wts[pol] += [wtsinfo[pol][i]['wts']]
wtspos = wtsinfo[pol][i]['wtspos']
else:
lookupdata = LKP.read_lookup(wtsinfo[pol][i]['lookup'])
wtspos = NP.hstack((lookupdata[0].reshape(-1,1),lookupdata[1].reshape(-1,1))) * (self.f[i]/FCNST.c)
self.wts[pol] += [lookupdata[2]]
self.wtspos[pol] += [ NP.dot(NP.asarray(wtspos), rotation_matrix.T) ]
max_wtspos += [NP.amax(NP.abs(self.wtspos[pol][-1]), axis=0)]
elif len(wtsinfo[pol]) == 1:
if (gridfunc_freq is None) or (gridfunc_freq == 'scale'):
self.wtspos_scale[pol] = 'scale'
if ref_freq is None:
ref_freq = self.f0
angles = wtsinfo[pol][0]['orientation']
rotation_matrix = NP.asarray([[NP.cos(-angles), NP.sin(-angles)],
[-NP.sin(-angles), NP.cos(-angles)]])
if ('lookup' not in wtsinfo[pol][0]) or (wtsinfo[pol][0]['lookup'] is None):
self.wts[pol] += [ wtsinfo[pol][0]['wts'] ]
wtspos = wtsinfo[pol][0]['wtspos']
else:
lookupdata = LKP.read_lookup(wtsinfo[pol][0]['lookup'])
wtspos = NP.hstack((lookupdata[0].reshape(-1,1),lookupdata[1].reshape(-1,1))) * (ref_freq/FCNST.c)
self.wts[pol] += [lookupdata[2]]
self.wtspos[pol] += [ (self.f[0]/ref_freq) * NP.dot(NP.asarray(wtspos), rotation_matrix.T) ]
max_wtspos += [NP.amax(NP.abs(self.wtspos[pol][-1]), axis=0)]
else:
raise ValueError('gridfunc_freq must be set to None, "scale" or "noscale".')
self.blc = NP.asarray([self.location.x, self.location.y]).reshape(1,-1) - FCNST.c/self.f.min() * NP.amin(NP.abs(self.wtspos[pol][0]), 0)
self.trc = NP.asarray([self.location.x, self.location.y]).reshape(1,-1) + FCNST.c/self.f.min() * NP.amax(NP.abs(self.wtspos[pol][0]), 0)
else:
raise ValueError('Number of elements in wtsinfo for {0} is incompatible with the number of channels.'.format(pol))
max_wtspos = NP.amax(NP.asarray(max_wtspos).reshape(-1,blc_orig.size), axis=0)
self.blc = NP.asarray([self.location.x, self.location.y]).reshape(1,-1) - FCNST.c/self.f.min() * max_wtspos
self.trc = NP.asarray([self.location.x, self.location.y]).reshape(1,-1) + FCNST.c/self.f.min() * max_wtspos
if (NP.abs(NP.linalg.norm(blc_orig)-NP.linalg.norm(self.blc)) > eps) or (NP.abs(NP.linalg.norm(trc_orig)-NP.linalg.norm(self.trc)) > eps):
if verbose:
print 'Grid corner(s) of antenna {0} have changed. Should re-grid the antenna array.'.format(self.label)
############################################################################
def update_pp(self, update_dict=None, verbose=True):
"""
------------------------------------------------------------------------
Wrapper for member function update() and returns the updated instance
of this class. Mostly intended to be used when parallel processing is
applicable and not to be used directly. Use update() instead when
updates are to be applied directly.
See member function update() for details on inputs.
------------------------------------------------------------------------
"""
self.update(update_dict=update_dict, verbose=verbose)
return self
############################################################################
def get_E_fields(self, pol, flag=None, tselect=None, fselect=None,
datapool=None):
"""
------------------------------------------------------------------------
Returns the electric fields based on selection criteria on timestamp
flags, timestamps and frequency channel indices and the type of data
(most recent or stacked electric fields)
Inputs:
pol [string] select baselines of this polarization that are either
flagged or unflagged as specified by input parameter flag.
Allowed values are 'P1' and 'P2'. Only one of these values
must be specified.
flag [boolean] If False, return electric fields of unflagged
timestamps, or if True return flagged ones. Default=None means
all electric fields independent of flagging are returned. This
flagging refers to that along the timestamp axis under each
polarization
tselect [scalar, list, numpy array] timestamp index for electric
fields selection. For most recent electric fields, it must be
set to -1. For all other selections, indices in tselect must
be in the valid range of indices along time axis for stacked
electric fields. Default=None means most recent data is
selected.
fselect [scalar, list, numpy array] frequency channel index for
electric field spectrum selection. Indices must be in the
valid range of indices along the frequency axis for
electric fields. Default=None selects all frequency channels
datapool [string] denotes the data pool from which electric fields are
to be selected. Accepted values are 'current', 'stack', and
None (default, same as 'current'). If set to None or
'current', the value in tselect is ignored and only
electric fields of the most recent timestamp are selected. If
set to None or 'current' the attribute Ef_stack is checked
first and if unavailable, attribute antpol.Ef is used. For
'stack', attribute Ef_stack respectively
Output:
outdict [dictionary] consists of electric fields information under the
following keys:
'label' [string] antenna label
'pol' [string] polarization string, one of 'P1' or
'P2'
'E-fields' [numpy array] selected electric fields spectra
with dimensions n_ts x nchan which
are in time-frequency order. If no electric
fields are found satisfying the selection
criteria, the value under this key is set to
None.
'twts' [numpy array of boolean] weights corresponding
to the time axis in the selected electric
fields. A zero weight indicates unflagged
electric fields were not found for that
timestamp. A non-zero weight indicates how
many unflagged electric fields were found for
that timestamp. If no electric fields are found
satisfying the selection criteria, the value
under this key is set to None.
------------------------------------------------------------------------
"""
try:
pol
except NameError:
raise NameError('Input parameter pol must be specified.')
if not isinstance(pol, str):
raise TypeError('Input parameter must be a string')
if pol not in ['P1', 'P2']:
raise ValueError('Invalid specification for input parameter pol')
if datapool is None:
n_timestamps = 1
datapool = 'current'
elif datapool == 'stack':
n_timestamps = len(self.timestamps)
elif datapool == 'current':
n_timestamps = 1
else:
raise ValueError('Invalid datapool specified')
if tselect is None:
tsind = NP.asarray(-1).reshape(-1) # Selects most recent data
elif isinstance(tselect, (int, float, list, NP.ndarray)):
tsind = NP.asarray(tselect).ravel()
tsind = tsind.astype(NP.int)
if tsind.size == 1:
if (tsind < -1) or (tsind >= n_timestamps):
tsind = NP.asarray(-1).reshape(-1)
else:
if NP.any(tsind < 0) or NP.any(tsind >= n_timestamps):
raise IndexError('Timestamp indices outside available range for the specified datapool')
else:
raise TypeError('tselect must be None, integer, float, list or numpy array for visibilities selection')
if fselect is None:
chans = NP.arange(self.f.size) # Selects all channels
elif isinstance(fselect, (int, float, list, NP.ndarray)):
chans = NP.asarray(fselect).ravel()
chans = chans.astype(NP.int)
if NP.any(chans < 0) or NP.any(chans >= self.f.size):
raise IndexError('Channel indices outside available range')
else:
raise TypeError('fselect must be None, integer, float, list or numpy array for visibilities selection')
select_ind = NP.ix_(tsind, chans)
outdict = {}
outdict['pol'] = pol
outdict['twts'] = None
outdict['label'] = self.label
outdict['E-fields'] = None
if datapool == 'current':
if self.Ef_stack[pol] is not None:
outdict['E-fields'] = self.Ef_stack[pol][-1,chans].reshape(1,chans.size)
outdict['twts'] = NP.logical_not(NP.asarray(self.flag_stack[pol][-1]).astype(NP.bool).reshape(-1)).astype(NP.float)
else:
outdict['E-fields'] = self.antpol.Ef[pol][chans].reshape(1,chans.size)
outdict['twts'] = NP.logical_not(NP.asarray(self.antpol.flag[pol]).astype(NP.bool).reshape(-1)).astype(NP.float)
else:
if self.Ef_stack[pol] is not None:
outdict['E-fields'] = self.Ef_stack[pol][select_ind].reshape(tsind.size,chans.size)
outdict['twts'] = NP.logical_not(NP.asarray(self.flag_stack[pol][tsind]).astype(NP.bool).reshape(-1)).astype(NP.float)
else:
raise ValueError('Attribute Ef_stack has not been initialized to obtain electric fields from. Consider running method stack()')
return outdict
############################################################################
def evalGridIllumination(self, uvlocs=None, xy_center=None):
"""
------------------------------------------------------------------------
Evaluate antenna illumination function on a specified grid
Inputs:
uvlocs [tuple] 2-element tuple where first and second elements
are numpy arrays that contain u- and v-locations
respectively. Default=None means determine u- and v-
locations from attributes blc and trc
xy_center [tuple, list or numpy array] 2-element list, tuple or numpy
array denoting x- and y-locations of center of antenna.
Default=None means use the x- and y-locations of the
antenna
Outputs:
antenna_grid_wts_vuf
[scipy sparse array] Complex antenna illumination weights
placed on the specified grid. When expanded it will be of
size nv x nu x nchan
------------------------------------------------------------------------
"""
if xy_center is None:
xy_center = NP.asarray([self.location.x, self.location.y])
elif isinstance(xy_center, (list,tuple,NP.ndarray)):
xy_center = NP.asarray(xy_center)
if xy_center.size != 2:
raise ValueError('Input xy_center must be a two-element numpy array')
xy_center = xy_center.ravel()
else:
raise TypeError('Input xy_center must be a numpy array')
wavelength = FCNST.c / self.f
min_wl = NP.abs(wavelength).min()
uvspacing = 0.5
if uvlocs is None:
blc = self.blc - xy_center
trc = self.trc - xy_center
trc = NP.amax(NP.abs(NP.vstack((blc, trc))), axis=0).ravel() / min_wl
blc = -1 * trc
gridu, gridv = GRD.grid_2d([(blc[0], trc[0]), (blc[1], trc[1])], pad=0.0, spacing=uvspacing, pow2=True)
du = gridu[0,1] - gridu[0,0]
dv = gridv[1,0] - gridv[0,0]
elif isinstance(uvlocs, tuple):
if len(uvlocs) != 2:
raise ValueError('Input uvlocs must be a two-element tuple')
ulocs, vlocs = uvlocs
if not isinstance(ulocs, NP.ndarray):
raise TypeError('Elements in input tuple uvlocs must be a numpy array')
if not isinstance(vlocs, NP.ndarray):
raise TypeError('Elements in input tuple uvlocs must be a numpy array')
ulocs = ulocs.ravel()
vlocs = vlocs.ravel()
du = ulocs[1] - ulocs[0]
dv = vlocs[1] - vlocs[0]
gridu, gridv = NP.meshgrid(ulocs, vlocs)
else:
raise TypeError('Input uvlocs must be a two-element tuple')
rmaxNN = 0.5 * NP.sqrt(du**2 + dv**2) * min_wl
gridx = gridu[:,:,NP.newaxis] * wavelength.reshape(1,1,-1)
gridy = gridv[:,:,NP.newaxis] * wavelength.reshape(1,1,-1)
gridxy = NP.hstack((gridx.reshape(-1,1), gridy.reshape(-1,1)))
wl = NP.ones(gridu.shape)[:,:,NP.newaxis] * wavelength.reshape(1,1,-1)
max_aprtr_size = max([NP.sqrt(self.aperture.xmax['P1']**2 + NP.sqrt(self.aperture.ymax['P1']**2)), NP.sqrt(self.aperture.xmax['P2']**2 + NP.sqrt(self.aperture.ymax['P2']**2)), self.aperture.rmax['P1'], self.aperture.rmax['P2']])
distNN = 2.0 * max_aprtr_size
indNN_list, blind, vuf_gridind = LKP.find_NN(xy_center.reshape(1,-1), gridxy, distance_ULIM=distNN, flatten=True, parallel=False)
dxy = gridxy[vuf_gridind,:]
unraveled_vuf_ind = NP.unravel_index(vuf_gridind, gridu.shape+(self.f.size,))
unraveled_vu_ind = (unraveled_vuf_ind[0], unraveled_vuf_ind[1])
raveled_vu_ind = NP.ravel_multi_index(unraveled_vu_ind, (gridu.shape[0], gridu.shape[1]))
antenna_grid_wts_vuf = {}
pol = ['P1', 'P2']
for p in pol:
krn = self.aperture.compute(dxy, wavelength=wl.ravel()[vuf_gridind], pol=p, rmaxNN=rmaxNN, load_lookup=False)
krn_sparse = SpM.csr_matrix((krn[p], (raveled_vu_ind,)+(unraveled_vuf_ind[2],)), shape=(gridu.size,)+(self.f.size,), dtype=NP.complex64)
krn_sparse_sumuv = krn_sparse.sum(axis=0)
krn_sparse_norm = krn_sparse.A / krn_sparse_sumuv.A
sprow = raveled_vu_ind
spcol = unraveled_vuf_ind[2]
spval = krn_sparse_norm[(sprow,)+(spcol,)]
antenna_grid_wts_vuf[p] = SpM.csr_matrix((spval, (sprow,)+(spcol,)), shape=(gridu.size,)+(self.f.size,), dtype=NP.complex64)
return antenna_grid_wts_vuf
################################################################################
class AntennaArray(object):
"""
----------------------------------------------------------------------------
Class to manage collective information on a group of antennas.
Attributes:
antennas: [Dictionary] Dictionary consisting of keys which hold instances
of class Antenna. The keys themselves are identical to the
label attributes of the antenna instances they hold.
latitude [Scalar] Latitude of the antenna array location.
longitude [Scalar] Longitude of the antenna array location.
blc [2-element Numpy array] The coordinates of the bottom left
corner of the array of antennas
trc [2-element Numpy array] The coordinates of the top right
corner of the array of antennas
grid_blc [2-element Numpy array] The coordinates of the bottom left
corner of the grid constructed for the array of antennas.
This may differ from blc due to any extra padding during the
gridding process.
grid_trc [2-element Numpy array] The coordinates of the top right
corner of the grid constructed for the array of antennas
This may differ from trc due to any extra padding during the
gridding process.
grid_ready [boolean] True if the grid has been created, False otherwise
gridu [Numpy array] u-locations of the grid lattice stored as 2D
array. It is the same for all frequencies and hence no third
dimension for the spectral axis.
gridv [Numpy array] v-locations of the grid lattice stored as 2D
array. It is the same for all frequencies and hence no third
dimension for the spectral axis.
antenna_autowts_set
[boolean] Indicates if auto-correlation of antenna-wise weights
have been determined (True) or not (False).
antenna_crosswts_set
[boolean] Indicates if zero-centered cross-correlation of
antenna pair weights have been determined (True) or not (False)
auto_corr_data
[dictionary] holds antenna auto-correlation of complex electric
field spectra. It is under keys 'current', 'stack' and 'avg'
for the current, stacked and time-averaged auto-correlations.
Under eack of these keys is another dictionary with two keys
'P1' and 'P2' for the two polarizations. Under each of these
polarization keys is a dictionary with the following keys
and values:
'labels' [list of strings] Contains a list of antenna
labels
'E-fields' [numpy array] Contains time-averaged
auto-correlation of antenna electric fields. It is
of size n_tavg x nant x nchan
'twts' [numpy array] Contains number of unflagged electric
field spectra used in the averaging of antenna
auto-correlation spectra. It is of size
n_tavg x nant x 1
pairwise_typetag_crosswts_vuf
[dictionary] holds grid illumination wts (centered on grid
origin) obtained from cross-correlation of antenna pairs that
belong to their respective typetags. Tuples of typetag pairs
form the keys. Under each key is another dictionary with
keys 'last_updated', and 'P1' and 'P2' for each polarization.
Under 'last_updated' it stores the timestamp when the last
update took place for this typetag pair. Under each of the
polarization keys is a complex numpy array of size
nv x nu x nchan. It is obtained by correlating the aperture
illumination weights of one antenna type with the complex
conjugate of another.
antennas_center
[Numpy array] geometrical center of the antenna array locations
as a 2-element array of x- and y-values of the center. This is
not the center of mass of the antenna locations but simply the
mid-point between the extreme x- and y- coordinates of the
antennas
grid_illumination
[dictionary] Electric field illumination of antenna aperture
for each polarization held under keys 'P1' and 'P2'. Could be
complex. Stored as numpy arrays in the form of cubes with
same dimensions as gridu or gridv in the transverse (first two
dimensions) and the depth along the third dimension (spectral
axis) is equal to number of frequency channels
grid_Ef [dictionary] Complex Electric field projected on the grid
for each polarization under the keys 'P1' and P2'. Stored as
numpy arrays in the form of cubes with same dimensions as gridu
or gridv in the transverse (first two dimensions) and the depth
along the third dimension (spectral axis) is equal to number of
frequency channels.
f [Numpy array] Frequency channels (in Hz)
f0 [Scalar] Center frequency of the observing band (in Hz)
typetags [dictionary] Dictionary containing keys which are unique
antenna type tags. Under each of these type tag keys is a
set of antenna labels denoting antennas that are of that type
pairwise_typetags
[dictionary] Dictionary containing keys which are unique
pairwise combination (tuples) of antenna type tags. Under each
of these pairwise type tag keys is a dictionary with two keys
'auto' and 'cross' each of which contains a set of pairwise
(tuple) antenna labels denoting the antenna pairs that are of
that type. Under 'auto' are tuples with same antennas while
under 'cross' it contains antenna pairs in which the antennas
are not the same. The 'auto' key exists only when antenna
type tag tuple contains both antennas of same type.
antenna_pair_to_typetag
[dictionary] Dictionary containing antenna pair keys and the
corresponding values are typetag pairs.
timestamp: [Scalar] String or float representing the timestamp for the
current attributes
timestamps [list] list of all timestamps to be held in the stack
tbinsize [scalar or dictionary] Contains bin size of timestamps while
averaging after stacking. Default = None means all antenna
E-field auto-correlation spectra over all timestamps are
averaged. If scalar, the same (positive) value applies to all
polarizations. If dictionary, timestamp bin size (positive) in
seconds is provided under each key 'P1' and 'P2'. If any of
the keys is missing the auto-correlated antenna E-field spectra
for that polarization are averaged over all timestamps.
grid_mapper [dictionary] antenna-to-grid mapping information for each of
four polarizations under keys 'P1' and 'P2'. Under each
polarization, it is a dictionary with values under the following
keys:
'refind' [list] each element in the list corresponds to a
sequential frequency channel and is another list
with indices to the lookup locations that map to
the grid locations (indices in 'gridind') for this
frequency channel. These indices index the array
in 'refwts'
'gridind' [list] each element in the list corresponds to a
sequential frequency channel and is another list
with indices to the grid locations that map to
the lookup locations (indices in 'refind') for
this frequency channel.
'refwts' [numpy array] antenna weights of size
n_ant x n_wts flattened to be a vector. Indices in
'refind' index to this array. Currently only valid
when lookup weights scale with frequency.
'labels' [dictionary] contains mapping information from
antenna (specified by key which is the
antenna label). The value under each label
key is another dictionary with the following keys
and information:
'twts' [scalar] if positive, indicates
the number of timestamps that
have gone into the measurement of Ef
made by the antenna under the
specific polarization. If zero, it
indicates no unflagged timestamp data
was found for the antenna and will
not contribute to the complex grid
illumination and electric fields
'gridind' [numpy vector] one-dimensional index
into the three-dimensional grid
locations where the antenna
contributes illumination and
electric fields. The one-dimensional
indices are obtained using numpy's
multi_ravel_index() using the grid
shape, n_u x n_v x nchan
'illumination' [numpy vector] complex grid
illumination contributed by the
antenna to different grid
locations in 'gridind'. It is
mapped to the grid as specified by
indices in key 'gridind'
'Ef' [numpy vector] complex grid
electric fields contributed by the
antenna. It is mapped to the
grid as specified by indices in
key 'gridind'
'ant' [dictionary] dictionary with information on
contribution of all antenna lookup weights. This
contains another dictionary with the following
keys:
'ind_freq' [list] each element in the list is
for a frequency channel and
consists of a numpy vector which
consists of indices of the
contributing antennas
'ind_all' [numpy vector] consists of numpy
vector which consists of indices
of the contributing antennas
for all frequencies appended
together. Effectively, this is just
values in 'ind_freq' of all
frequencies appended together.
'uniq_ind_all' [numpy vector] consists of numpy
vector which consists of unique
indices of contributing antennas
for all frequencies.
'rev_ind_all' [numpy vector] reverse indices of
'ind_all' with reference to bins of
'uniq_ind_all'
'illumination' [numpy vector] complex grid
illumination weights contributed by
each antenna (including associated
kernel weight locations) and has a
size equal to that in 'ind_all'
'grid' [dictionary] contains information about populated
portions of the grid. It consists of values in the
following keys:
'ind_all' [numpy vector] indices of all grid
locations raveled to one dimension
from three dimensions of size
n_u x n_v x nchan
'per_ant2grid'
[list] each element in the list is a dictionary
corresponding to an antenna with information on
its mapping and contribution to the grid. Each
dictionary has the following keys and values:
'label' [string] antenna label
'f_gridind' [numpy array] mapping information
with indices to the frequency axis
of the grid
'u_gridind' [numpy array] mapping information
with indices to the u-axis
of the grid. Must be of same size
as array under 'f_gridind'
'v_gridind' [numpy array] mapping information
with indices to the v-axis
of the grid. Must be of same size
as array under 'f_gridind'
'per_ant_per_freq_norm_wts'
[numpy array] mapping information
on the (complex) normalizing
multiplicative factor required to
make the sum of illumination/weights
per antenna per frequency on the
grid equal to unity. Must be of same
size as array under 'f_gridind'
'illumination' [numpy array] Complex aperture
illumination/weights contributed
by the antenna onto the grid. The
grid pixels to which it contributes
is given by 'f_gridind', 'u_gridind',
'v_gridind'. Must be of same size
as array under 'f_gridind'
'Ef' [numpy array] Complex electric fields
contributed by the antenna onto the
grid. The grid pixels to which it
contributes is given by 'f_gridind',
'u_gridind', 'v_gridind'. Must be of
same size as array under 'f_gridind'
'all_ant2grid'
[dictionary] contains the combined information of
mapping of all antennas to the grid. It consists of
the following keys and values:
'antind' [numpy array] all antenna indices (to
attribute ordered labels) that map to
the uvf-grid
'u_gridind' [numpy array] all indices to the
u-axis of the uvf-grid mapped to by
all antennas whose indices are given
in key 'antind'. Must be of same size
as the array under key 'antind'
'v_gridind' [numpy array] all indices to the
v-axis of the uvf-grid mapped to by
all antennas whose indices are given
in key 'antind'. Must be of same size
as the array under key 'antind'
'f_gridind' [numpy array] all indices to the
f-axis of the uvf-grid mapped to by
all antennas whose indices are given
in key 'antind'. Must be of same size
as the array under key 'antind'
'indNN_list' [list of lists] Each item in the top
level list corresponds to an antenna
in the same order as in the attribute
ordered_labels. Each of these items
is another list consisting of the
unraveled grid indices it contributes
to. The unraveled indices are what
are used to obtain the u-, v- and f-
indices in the grid using a
conversion assuming f is the
first axis, v is the second and u is
the third
'illumination' [numpy array] complex values of
aperture illumination contributed by
all antennas to the grid. The antenna
indices are in 'antind' and the grid
indices are in 'u_gridind',
'v_gridind' and 'f_gridind'. Must be
of same size as these indices
'per_ant_per_freq_norm_wts'
[numpy array] mapping information
on the (complex) normalizing
multiplicative factor required to
make the sum of illumination/weights
per antenna per frequency on the
grid equal to unity. This is appended
for all antennas together. Must be of
same size as array under
'illumination'
'Ef' [numpy array] Complex electric fields
contributed by all antennas onto the
grid. The grid pixels to which it
contributes is given by 'f_gridind',
'u_gridind', 'v_gridind'. Must be of
same size as array under 'f_gridind'
and 'illumination'
ant2grid_mapper
[sparse matrix] contains the antenna array to grid mapping
information in sparse matrix format. When converted to a dense
array, it will have dimensions nrows equal to size of the 3D
cube and ncols equal to number of electric field spectra of all
antennas over all channels. In other words,
nrows = nu x nv x nchan and ncols = n_ant x nchan. Dot product
of this matrix with flattened electric field spectra or antenna
weights will give the 3D cubes of gridded electric fields and
antenna array illumination respectively
Member Functions:
__init__() Initializes an instance of class AntennaArray which
manages information about an array of antennas.
__str__() Prints a summary of current attributes
__add__() Operator overloading for adding antenna(s)
__radd__() Operator overloading for adding antenna(s)
__sub__() Operator overloading for removing antenna(s)
pairTypetags() Combine antenna typetags to create pairwise typetags for
antenna pairs and update attribute pairwise_typetags
add_antennas() Routine to add antenna(s) to the antenna array instance.
A wrapper for operator overloading __add__() and
__radd__()
remove_antennas() Routine to remove antenna(s) from the antenna array
instance. A wrapper for operator overloading __sub__()
grid() Routine to produce a grid based on the antenna array
grid_convolve() Routine to project the electric field illumination pattern
and the electric fields on the grid. It can operate on the
entire antenna array or incrementally project the electric
fields and illumination patterns from specific antennas on
to an already existing grid.
grid_convolve_new()
Routine to project the electric field illumination pattern
and the electric fields on the grid.
genMappingMatrix()
Routine to construct sparse antenna-to-grid mapping matrix
that will be used in projecting illumination and electric
fields from the array of antennas onto the grid. It has
elements very common to grid_convolve_new()
applyMappingMatrix()
Constructs the grid of complex field illumination and
electric fields using the sparse antenna-to-grid mapping
matrix. Intended to serve as a "matrix" alternative to
make_grid_cube_new()
grid_unconvolve() Routine to de-project the electric field illumination
pattern and the electric fields on the grid. It can
operate on the entire antenna array or incrementally
de-project the electric fields and illumination patterns
from specific antennas from an already existing grid.
get_E_fields() Routine to return the antenna labels, time-based weight
flags and electric fields (sorted by antenna label if
specified) based on selection criteria specified by flags,
timestamps, frequency channels, labels and data pool (most
recent or stack)
make_grid_cube() Constructs the grid of complex field illumination and
electric fields using the gridding information determined
for every antenna. Flags are taken into account while
constructing this grid.
make_grid_cube_new()
Constructs the grid of complex field illumination and
electric fields using the gridding information determined
for every antenna. Flags are taken into account while
constructing this grid.
evalAntennaPairCorrWts()
Evaluate correlation of pair of antenna illumination
weights on grid. It will be computed only if it was not
computed or stored in attribute
pairwise_typetag_crosswts_vuf earlier
evalAntennaPairPBeam()
Evaluate power pattern response on sky of an antenna pair
avgAutoCorr() Accumulates and averages auto-correlation of electric
fields of individual antennas under each polarization
evalAutoCorr() Estimates antenna-wise E-field auto-correlations under
both polarizations. It can be for the msot recent
timestamp, stacked or averaged along timestamps.
evalAntennaAutoCorrWts()
Evaluate auto-correlation of aperture illumination of
each antenna on the UVF-plane
evalAllAntennaPairCorrWts()
Evaluate zero-centered cross-correlation of aperture
illumination of each antenna pair on the UVF-plane
makeAutoCorrCube()
Constructs the grid of antenna aperture illumination
auto-correlation using the gridding information
determined for every antenna. Flags are taken into
account while constructing this grid
makeCrossCorrWtsCube()
Constructs the grid of zero-centered cross-correlation
of antenna aperture pairs using the gridding information
determined for every antenna. Flags are taken into account
while constructing this grid
quick_beam_synthesis()
A quick generator of synthesized beam using antenna array
field illumination pattern using the center frequency. Not
intended to be used rigorously but rather for comparison
purposes and making quick plots
update(): Updates the antenna array instance with newer attribute
values
save(): Saves the antenna array information to disk.
Read the member function docstrings for details.
----------------------------------------------------------------------------
"""
def __init__(self, antenna_array=None):
"""
------------------------------------------------------------------------
Initialize the AntennaArray Class which manages information about an
array of antennas.
Class attributes initialized are:
antennas, blc, trc, gridu, gridv, grid_ready, timestamp,
grid_illumination, grid_Ef, f, f0, t, ordered_labels, grid_mapper,
antennas_center, latitude, longitude, tbinsize, auto_corr_data,
antenna_autowts_set, typetags, pairwise_typetags, antenna_crosswts_set,
pairwise_typetag_crosswts_vuf, antenna_pair_to_typetag
Read docstring of class AntennaArray for details on these attributes.
Inputs:
antenna_array
[Instance of class AntennaArray, dictionary holding
instance(s) instance(s) of class Antenna, list of instances
of class Antenna, or a single instance of class Antenna]
Read docstring of member funtion __add__() for more details
on this input. If provided, this will be used to initialize
the instance.
------------------------------------------------------------------------
"""
self.antennas = {}
self.blc = NP.zeros(2)
self.trc = NP.zeros(2)
self.grid_blc = NP.zeros(2)
self.grid_trc = NP.zeros(2)
self.gridu, self.gridv = None, None
self.antennas_center = NP.zeros(2, dtype=NP.float).reshape(1,-1)
self.grid_ready = False
self.grid_illumination = {}
self.grid_Ef = {}
self.caldata = {}
self.latitude = None
self.longitude = None
self.f = None
self.f0 = None
self.t = None
self.timestamp = None
self.timestamps = []
self.typetags = {}
self.pairwise_typetags = {}
self.antenna_pair_to_typetag = {}
self.auto_corr_data = {}
self.pairwise_typetag_crosswts_vuf = {}
self.antenna_autowts_set = False
self.antenna_crosswts_set = False
self._ant_contribution = {}
self.ordered_labels = [] # Usually output from member function baseline_vectors() or get_visibilities()
self.grid_mapper = {}
self.ant2grid_mapper = {} # contains the sparse mapping matrix
for pol in ['P1', 'P2']:
self.grid_mapper[pol] = {}
self.grid_mapper[pol]['labels'] = {}
self.grid_mapper[pol]['refind'] = []
# self.grid_mapper[pol]['ant_ind'] = []
self.grid_mapper[pol]['gridind'] = []
self.grid_mapper[pol]['refwts'] = None
self.grid_mapper[pol]['ant'] = {}
self.grid_mapper[pol]['ant']['ind_freq'] = []
self.grid_mapper[pol]['ant']['ind_all'] = None
self.grid_mapper[pol]['ant']['uniq_ind_all'] = None
self.grid_mapper[pol]['ant']['rev_ind_all'] = None
self.grid_mapper[pol]['ant']['illumination'] = None
self.grid_mapper[pol]['grid'] = {}
self.grid_mapper[pol]['grid']['ind_all'] = None
self.grid_mapper[pol]['per_ant2grid'] = []
self.grid_mapper[pol]['all_ant2grid'] = {}
self.grid_illumination[pol] = None
self.grid_Ef[pol] = None
self._ant_contribution[pol] = {}
self.caldata[pol] = None
self.ant2grid_mapper[pol] = None
if antenna_array is not None:
self += antenna_array
self.f = NP.copy(self.antennas.itervalues().next().f)
self.f0 = NP.copy(self.antennas.itervalues().next().f0)
self.t = NP.copy(self.antennas.itervalues().next().t)
if self.latitude is None:
self.latitude = NP.copy(self.antennas.itervalues().next().latitude)
self.longitude = NP.copy(self.antennas.itervalues().next().longitude)
self.timestamp = copy.deepcopy(self.antennas.itervalues().next().timestamp)
self.timestamps += [copy.deepcopy(self.timestamp)]
############################################################################
def __add__(self, others):
"""
------------------------------------------------------------------------
Operator overloading for adding antenna(s)
Inputs:
others [Instance of class AntennaArray, dictionary holding
instance(s) of class Antenna, list of instances of class
Antenna, or a single instance of class Antenna] If a
dictionary is provided, the keys should be the antenna
labels and the values should be instances of class Antenna.
If a list is provided, it should be a list of valid instances
of class Antenna. These instance(s) of class Antenna will be
added to the existing instance of AntennaArray class.
------------------------------------------------------------------------
"""
retval = self
if isinstance(others, AntennaArray):
# for k,v in others.antennas.items():
for k,v in others.antennas.iteritems():
if k in retval.antennas:
print "Antenna {0} already included in the list of antennas.".format(k)
print "For updating, use the update() method. Ignoring antenna {0}".format(k)
else:
retval.antennas[k] = v
if v.typetag not in retval.typetags:
retval.typetags[v.typetag] = {v.label}
else:
retval.typetags[v.typetag].add(v.label)
print 'Antenna "{0}" added to the list of antennas.'.format(k)
if retval.latitude is None:
retval.latitude = others.latitude
retval.longitude = others.longitude
elif isinstance(others, dict):
# for item in others.values():
for item in others.itervalues():
if isinstance(item, Antenna):
if item.label in retval.antennas:
print "Antenna {0} already included in the list of antennas.".format(item.label)
print "For updating, use the update() method. Ignoring antenna {0}".format(item.label)
else:
retval.antennas[item.label] = item
if item.typetag not in retval.typetags:
retval.typetags[item.typetag] = {item.label}
else:
retval.typetags[item.typetag].add(item.label)
print 'Antenna "{0}" added to the list of antennas.'.format(item.label)
if retval.latitude is None:
retval.latitude = item.latitude
retval.longitude = item.longitude
elif isinstance(others, list):
for i in range(len(others)):
if isinstance(others[i], Antenna):
if others[i].label in retval.antennas:
print "Antenna {0} already included in the list of antennas.".format(others[i].label)
print "For updating, use the update() method. Ignoring antenna {0}".format(others[i].label)
else:
retval.antennas[others[i].label] = others[i]
if others[i].typetag not in retval.typetags:
retval.typetags[others[i].typetag] = {others[i].label}
else:
retval.typetags[others[i].typetag].add(others[i].label)
print 'Antenna "{0}" added to the list of antennas.'.format(others[i].label)
else:
print 'Element \# {0} is not an instance of class Antenna.'.format(i)
if retval.latitude is None:
retval.latitude = others[i].latitude
retval.longitude = others[i].longitude
elif isinstance(others, Antenna):
if others.label in retval.antennas:
print "Antenna {0} already included in the list of antennas.".format(others.label)
print "For updating, use the update() method. Ignoring antenna {0}".format(others.label)
else:
retval.antennas[others.label] = others
if others.typetag not in retval.typetags:
retval.typetags[others.typetag] = {others.label}
else:
retval.typetags[others.typetag].add(others.label)
print 'Antenna "{0}" added to the list of antennas.'.format(others.label)
if retval.latitude is None:
retval.latitude = others.latitude
retval.longitude = others.longitude
else:
print 'Input(s) is/are not instance(s) of class Antenna.'
return retval
############################################################################
def __radd__(self, others):
"""
------------------------------------------------------------------------
Operator overloading for adding antenna(s)
Inputs:
others [Instance of class AntennaArray, dictionary holding
instance(s) of class Antenna, list of instances of class
Antenna, or a single instance of class Antenna] If a
dictionary is provided, the keys should be the antenna
labels and the values should be instances of class Antenna.
If a list is provided, it should be a list of valid
instances of class Antenna. These instance(s) of class
Antenna will be added to the existing instance of
AntennaArray class.
------------------------------------------------------------------------
"""
return self.__add__(others)
############################################################################
def __sub__(self, others):
"""
------------------------------------------------------------------------
Operator overloading for removing antenna(s)
Inputs:
others [Instance of class AntennaArray, dictionary holding
instance(s) of class Antenna, list of instances of class
Antenna, list of strings containing antenna labels or a
single instance of class Antenna] If a dictionary is
provided, the keys should be the antenna labels and the
values should be instances of class Antenna. If a list is
provided, it should be a list of valid instances of class
Antenna. These instance(s) of class Antenna will be removed
from the existing instance of AntennaArray class.
------------------------------------------------------------------------
"""
retval = self
if isinstance(others, dict):
for item in others.values():
if isinstance(item, Antenna):
if item.label not in retval.antennas:
print "Antenna {0} does not exist in the list of antennas.".format(item.label)
else:
del retval.antennas[item.label]
retval.typetags[item.typetag].remove(item.label)
print 'Antenna "{0}" removed from the list of antennas.'.format(item.label)
elif isinstance(others, list):
for i in range(0,len(others)):
if isinstance(others[i], str):
if others[i] in retval.antennas:
retval.typetags[retval.antennas[others[i]].typetag].remove(others[i])
del retval.antennas[others[i]]
print 'Antenna {0} removed from the list of antennas.'.format(others[i])
elif isinstance(others[i], Antenna):
if others[i].label in retval.antennas:
retval.typetags[others[i].typetag].remove(others[i].label)
del retval.antennas[others[i].label]
print 'Antenna {0} removed from the list of antennas.'.format(others[i].label)
else:
print "Antenna {0} does not exist in the list of antennas.".format(others[i].label)
else:
print 'Element \# {0} has no matches in the list of antennas.'.format(i)
elif others in retval.antennas:
retval.typetags[retval.antennas[others].typetag].remove(others)
del retval.antennas[others]
print 'Antenna "{0}" removed from the list of antennas.'.format(others)
elif isinstance(others, Antenna):
if others.label in retval.antennas:
retval.typetags[others.typetag].remove(others.label)
del retval.antennas[others.label]
print 'Antenna "{0}" removed from the list of antennas.'.format(others.label)
else:
print "Antenna {0} does not exist in the list of antennas.".format(others.label)
else:
print 'No matches found in existing list of antennas.'
return retval
############################################################################
def add_antennas(self, A=None):
"""
------------------------------------------------------------------------
Routine to add antenna(s) to the antenna array instance. A wrapper for
operator overloading __add__() and __radd__()
Inputs:
A [Instance of class AntennaArray, dictionary holding
instance(s) of class Antenna, list of instances of class
Antenna, or a single instance of class Antenna] If a
dictionary is provided, the keys should be the antenna
labels and the values should be instances of class Antenna.
If a list is provided, it should be a list of valid
instances of class Antenna. These instance(s) of class
Antenna will be added to the existing instance of
AntennaArray class.
------------------------------------------------------------------------
"""
if A is None:
print 'No antenna(s) supplied.'
elif isinstance(A, (list, Antenna)):
self = self.__add__(A)
else:
print 'Input(s) is/are not instance(s) of class Antenna.'
############################################################################
def remove_antennas(self, A=None):
"""
------------------------------------------------------------------------
Routine to remove antenna(s) from the antenna array instance. A wrapper
for operator overloading __sub__()
Inputs:
A [Instance of class AntennaArray, dictionary holding
instance(s) of class Antenna, list of instances of class
Antenna, or a single instance of class Antenna] If a
dictionary is provided, the keys should be the antenna
labels and the values should be instances of class Antenna.
If a list is provided, it should be a list of
valid instances of class Antenna. These instance(s) of class
Antenna will be removed from the existing instance of
AntennaArray class.
------------------------------------------------------------------------
"""
if A is None:
print 'No antenna specified for removal.'
else:
self = self.__sub__(A)
############################################################################
def pairTypetags(self):
"""
------------------------------------------------------------------------
Combine antenna typetags to create pairwise typetags for antenna pairs
and update attribute pairwise_typetags
------------------------------------------------------------------------
"""
typekeys = self.typetags.keys()
pairwise_typetags = {}
for i in range(len(typekeys)):
labels1 = list(self.typetags[typekeys[i]])
for j in range(i,len(typekeys)):
labels2 = list(self.typetags[typekeys[j]])
pairwise_typetags[(typekeys[i],typekeys[j])] = {}
if i == j:
pairwise_typetags[(typekeys[i],typekeys[j])]['auto'] = set([(l1,l1) for l1 in labels1])
pairwise_typetags[(typekeys[i],typekeys[j])]['cross'] = set([(l1,l2) for i1,l1 in enumerate(labels1) for i2,l2 in enumerate(labels2) if i1 < i2])
else:
pairwise_typetags[(typekeys[i],typekeys[j])]['cross'] = set([(l1,l2) for l1 in labels1 for l2 in labels2])
self.pairwise_typetags = pairwise_typetags
self.antenna_pair_to_typetag = {}
for k,val in pairwise_typetags.iteritems():
for subkey in val:
for v in list(val[subkey]):
self.antenna_pair_to_typetag[v] = k
############################################################################
def antenna_positions(self, pol=None, flag=False, sort=True,
centering=False):
"""
------------------------------------------------------------------------
Routine to return the antenna label and position vectors (sorted by
antenna label if specified)
Keyword Inputs:
pol [string] select positions of this polarization that are either
flagged or unflagged as specified by input parameter flag.
Allowed values are 'P1' and 'P2'. Default=None.
This means all positions are returned irrespective of the flags
flag [boolean] If False, return unflagged positions, otherwise
return flagged ones. Default=None means return all positions
independent of flagging or polarization
sort [boolean] If True, returned antenna information is sorted
by antenna label. Default = True.
centering
[boolean] If False (default), does not subtract the mid-point
between the bottom left corner and the top right corner. If
True, subtracts the mid-point and makes it the origin
Output:
outdict [dictionary] Output consists of a dictionary with the following
keys and information:
'labels': list of strings of antenna labels
'positions': position vectors of antennas (3-column
array)
------------------------------------------------------------------------
"""
if not isinstance(sort, bool):
raise TypeError('sort keyword has to be a Boolean value.')
if flag is not None:
if not isinstance(flag, bool):
raise TypeError('flag keyword has to be a Boolean value.')
if pol is None:
if sort: # sort by antenna label
xyz = NP.asarray([[self.antennas[label].location.x, self.antennas[label].location.y, self.antennas[label].location.z] for label in sorted(self.antennas.keys())])
labels = sorted(self.antennas.keys())
else:
xyz = NP.asarray([[self.antennas[label].location.x, self.antennas[label].location.y, self.antennas[label].location.z] for label in self.antennas.keys()])
labels = self.antennas.keys()
else:
if not isinstance(pol, str):
raise TypeError('Input parameter must be a string')
if pol not in ['P1', 'P2']:
raise ValueError('Invalid specification for input parameter pol')
if sort: # sort by antenna label
if flag is None: # get all positions
xyz = NP.asarray([[self.antennas[label].location.x, self.antennas[label].location.y, self.antennas[label].location.z] for label in sorted(self.antennas.keys())])
labels = sorted(self.antennas.keys())
else:
if flag: # get flagged positions
xyz = NP.asarray([[self.antennas[label].location.x, self.antennas[label].location.y, self.antennas[label].location.z] for label in sorted(self.antennas.keys()) if self.antennas[label].antpol.flag[pol]])
labels = [label for label in sorted(self.antennas.keys()) if self.antennas[label].antpol.flag[pol]]
else: # get unflagged positions
xyz = NP.asarray([[self.antennas[label].location.x, self.antennas[label].location.y, self.antennas[label].location.z] for label in sorted(self.antennas.keys()) if not self.antennas[label].antpol.flag[pol]])
labels = [label for label in sorted(self.antennas.keys()) if not self.antennas[label].antpol.flag[pol]]
else: # no sorting
if flag is None: # get all positions
xyz = NP.asarray([[self.antennas[label].location.x, self.antennas[label].location.y, self.antennas[label].location.z] for label in self.antennas.keys()])
labels = [label for label in self.antennas.keys()]
else:
if flag: # get flagged positions
xyz = NP.asarray([[self.antennas[label].location.x, self.antennas[label].location.y, self.antennas[label].location.z] for label in self.antennas.keys() if self.antennas[label].antpol.flag[pol]])
labels = [label for label in self.antennas.keys() if self.antennas[label].antpol.flag[pol]]
else: # get unflagged positions
xyz = NP.asarray([[self.antennas[label].location.x, self.antennas[label].location.y, self.antennas[label].location.z] for label in self.antennas.keys() if not self.antennas[label].antpol.flag[pol]])
labels = [label for label in self.antennas.keys() if not self.antennas[label].antpol.flag[pol]]
if centering:
xyzcenter = 0.5 * (NP.amin(xyz, axis=0, keepdims=True) + NP.amax(xyz, axis=0, keepdims=True))
xyz = xyz - xyzcenter
self.antennas_center = xyzcenter[0,:2].reshape(1,-1)
outdict = {}
outdict['labels'] = labels
outdict['positions'] = xyz
return outdict
############################################################################
def get_E_fields_old(self, pol, flag=False, sort=True):
"""
------------------------------------------------------------------------
Routine to return the antenna label and Electric fields (sorted by
antenna label if specified)
Keyword Inputs:
pol [string] select antenna positions of this polarization that are
either flagged or unflagged as specified by input parameter
flag. Allowed values are 'P1' and 'P22'. Only one of these
values must be specified.
flag [boolean] If False, return electric fields of unflagged
antennas, otherwise return flagged ones. Default=None means
all electric fields independent of flagging are returned.
sort [boolean] If True, returned antenna information is sorted
by antenna label. Default = True.
Output:
outdict [dictionary] Output consists of a dictionary with the following
keys and information:
'labels': Contains a numpy array of strings of antenna
labels
'E-fields': measured electric fields (n_ant x nchan array)
------------------------------------------------------------------------
"""
try:
pol
except NameError:
raise NameError('Input parameter pol must be specified.')
if not isinstance(pol, str):
raise TypeError('Input parameter must be a string')
if not pol in ['P1', 'P2']:
raise ValueError('Invalid specification for input parameter pol')
if not isinstance(sort, bool):
raise TypeError('sort keyword has to be a Boolean value.')
if flag is not None:
if not isinstance(flag, bool):
raise TypeError('flag keyword has to be a Boolean value.')
if sort: # sort by first antenna label
if flag is None: # get all antenna positions
efields = NP.asarray([self.antennas[label].antpol.Ef[pol] for label in sorted(self.antennas.keys(), key=lambda tup: tup[0])])
labels = [label for label in sorted(self.antennas.keys(), key=lambda tup: tup[0])]
else:
if flag: # get flagged antenna positions
efields = NP.asarray([self.antennas[label].antpol.Ef[pol] for label in sorted(self.antennas.keys(), key=lambda tup: tup[0]) if self.antennas[label].antpol.flag[pol]])
labels = [label for label in sorted(self.antennas.keys(), key=lambda tup: tup[0]) if self.antennas[label].antpol.flag[pol]]
else: # get unflagged antenna positions
efields = NP.asarray([self.antennas[label].antpol.Ef[pol] for label in sorted(self.antennas.keys(), key=lambda tup: tup[0]) if not self.antennas[label].antpol.flag[pol]])
labels = [label for label in sorted(self.antennas.keys(), key=lambda tup: tup[0]) if not self.antennas[label].antpol.flag[pol]]
else: # no sorting
if flag is None:
efields = NP.asarray([self.antennas[label].antpol.Ef[pol] for label in self.antennas.keys()])
labels = [label for label in self.antennas.keys()]
else:
if flag: # get flagged antenna positions
efields = NP.asarray([self.antennas[label].antpol.Ef[pol] for label in self.antennas.keys() if self.antennas[label].antpol.flag[pol]])
labels = [label for label in self.antennas.keys() if self.antennas[label].antpol.flag[pol]]
else: # get unflagged antenna positions
efields = NP.asarray([self.antennas[label].antpol.Ef[pol] for label in self.antennas.keys() if not self.antennas[label].antpol.flag[pol]])
labels = [label for label in sorted(self.antennas.keys(), key=lambda tup: tup[0]) if not self.antennas[label].antpol.flag[pol]]
outdict = {}
outdict['labels'] = labels
outdict['E-fields'] = efields
return outdict
############################################################################
def get_E_fields(self, pol, flag=None, tselect=None, fselect=None,
aselect=None, datapool=None, sort=True):
"""
------------------------------------------------------------------------
Routine to return the antenna labels, time-based weight flags and
electric fields (sorted by antenna label if specified) based on
selection criteria specified by flags, timestamps, frequency channels,
labels and data pool (most recent or stack)
Keyword Inputs:
pol [string] select baselines of this polarization that are either
flagged or unflagged as specified by input parameter flag.
Allowed values are 'P1' and 'P2'. Only one of these values
must be specified.
flag [boolean] If False, return electric fields of unflagged
antennas, otherwise return flagged ones. Default=None means
all electric fields independent of flagging are returned.
tselect [scalar, list, numpy array] timestamp index for electric
fields selection. For most recent electric fields, it must
be set to -1. For all other selections, indices in tselect
must be in the valid range of indices along time axis for
stacked electric fields. Default=None means most recent data
is selected.
fselect [scalar, list, numpy array] frequency channel index for
electric fields selection. Indices must be in the valid range
of indices along the frequency axis for electric fields.
Default=None selects all frequency channels
aselect [list of strings] labels of antennas to select. If set
to None (default) all antennas are selected.
datapool [string] denotes the data pool from which electric fields are
to be selected. Accepted values are 'current', 'stack' and
None (default, same as 'current'). If set to None or
'current', the value in tselect is ignored and only
electric fields of the most recent timestamp are selected. If
set to None or 'current' the attribute Ef_stack is checked
first and if unavailable, attribute antpol.Ef is used. For
'stack' attribute Ef_stack is used
sort [boolean] If True, returned antenna information is sorted
by antenna label. Default = True.
Output:
outdict [dictionary] Output consists of a dictionary with the following
keys and information:
'labels' [list of strings] Contains a list of antenna
labels
'E-fields' [list or numpy array] antenna electric fields
under the specified polarization. In general,
it is a list of numpy arrays where each
array in the list corresponds to
an individual antenna and the size of
each numpy array is n_ts x nchan. If input
keyword flag is set to None, the electric
fields are rearranged into a numpy array of
size n_ts x n_ant x nchan.
'twts' [list or numpy array] weights along time axis
under the specified polarization. In general
it is a list of numpy arrays where each array
in the list corresponds to an individual
antenna and the size of each array is n_ts x 1.
If input keyword flag is set to None, the
time weights are rearranged into a numpy array
of size n_ts x n_ant x 1
------------------------------------------------------------------------
"""
if not isinstance(sort, bool):
raise TypeError('sort keyword has to be a Boolean value.')
if aselect is None:
labels = self.antennas.keys()
elif isinstance(aselect, list):
labels = [label for label in aselect if label in self.antennas]
if sort:
labels = sorted(labels)
efinfo = [self.antennas[label].get_E_fields(pol, flag=flag, tselect=tselect, fselect=fselect, datapool=datapool) for label in labels]
outdict = {}
outdict['labels'] = labels
outdict['twts'] = [einfo['twts'] for einfo in efinfo]
outdict['E-fields'] = [einfo['E-fields'] for einfo in efinfo]
if flag is None:
outdict['E-fields'] = NP.swapaxes(NP.asarray(outdict['E-fields']), 0, 1)
outdict['twts'] = NP.swapaxes(NP.asarray(outdict['twts']), 0, 1)
outdict['twts'] = outdict['twts'][:,:,NP.newaxis]
return outdict
############################################################################
def avgAutoCorr(self, pol=None, tbinsize=None):
"""
------------------------------------------------------------------------
Accumulates and averages auto-correlation of electric fields of
individual antennas under each polarization
Inputs:
pol [String] The polarization to be averaged. Can be set to 'P1' or
'P2'. If set to None, averaging for all the polarizations is
performed. Default=None
tbinsize [scalar or dictionary] Contains bin size of timestamps while
averaging. Default = None means all antenna E-field
auto-correlation spectra over all timestamps are averaged. If
scalar, the same (positive) value applies to all polarizations.
If dictionary, timestamp bin size (positive) in seconds is
provided under each key 'P1' and 'P2'. If any of the keys is
missing the auto-correlated antenna E-field spectra for that
polarization are averaged over all timestamps.
------------------------------------------------------------------------
"""
timestamps = NP.asarray(self.timestamps).astype(NP.float)
twts = {}
auto_corr_data = {}
if pol is None:
pol = ['P1', 'P2']
pol = NP.unique(NP.asarray(pol))
for p in pol:
Ef_info = self.get_E_fields(p, flag=None, tselect=NP.arange(len(self.timestamps)), fselect=None, aselect=None, datapool='stack', sort=True)
twts[p] = []
auto_corr_data[p] = {}
if tbinsize is None: # Average across all timestamps
auto_corr_data[p]['E-fields'] = NP.nansum(NP.abs(Ef_info['E-fields'])**2, axis=0, keepdims=True)
auto_corr_data[p]['twts'] = NP.sum(Ef_info['twts'], axis=0, keepdims=True).astype(NP.float)
auto_corr_data[p]['labels'] = Ef_info['labels']
self.tbinsize = tbinsize
elif isinstance(tbinsize, (int,float)): # Apply same time bin size to all polarizations
split_ind = NP.arange(timestamps.min()+tbinsize, timstamps.max(), tbinsize)
twts_split = NP.array_split(Ef_info['twts'], split_ind, axis=0)
Ef_split = NP.array_split(Ef_info['E-fields'], split_ind, axis=0)
for i in xrange(split_ind.size):
if 'E-fields' not in auto_corr_data[p]:
auto_corr_data[p]['E-fields'] = NP.nansum(NP.abs(Ef_info['E-fields'])**2, axis=0, keepdims=True)
auto_corr_data[p]['twts'] = NP.sum(Ef_info['twts'], axis=0, keepdims=True).astype(NP.float)
else:
auto_corr_data[p]['E-fields'] = NP.vstack((auto_corr_data[p]['E-fields'], NP.nansum(NP.abs(Ef_info['E-fields'])**2, axis=0, keepdims=True)))
auto_corr_data[p]['twts'] = NP.vstack((auto_corr_data[p]['twts'], NP.sum(Ef_info['twts'], axis=0, keepdims=True))).astype(NP.float)
auto_corr_data[p]['labels'] = Ef_info['labels']
self.tbinsize = tbinsize
elif isinstance(tbinsize, dict):
tbsize = {}
if p not in tbinsize:
auto_corr_data[p]['E-fields'] = NP.nansum(NP.abs(Ef_info['E-fields'])**2, axis=0, keepdims=True)
auto_corr_data[p]['twts'] = NP.sum(Ef_info['twts'], axis=0, keepdims=True).astype(NP.float)
tbsize[p] = None
elif tbinsize[p] is None:
auto_corr_data[p]['E-fields'] = NP.nansum(NP.abs(Ef_info['E-fields'])**2, axis=0, keepdims=True)
auto_corr_data[p]['twts'] = NP.sum(Ef_info['twts'], axis=0, keepdims=True).astype(NP.float)
tbsize[p] = None
elif isinstance(tbinsize[p], (int,float)):
split_ind = NP.arange(timestamps.min()+tbinsize, timstamps.max(), tbinsize)
twts_split = NP.array_split(Ef_info['twts'], split_ind, axis=0)
Ef_split = NP.array_split(Ef_info['E-fields'], split_ind, axis=0)
for i in xrange(split_ind.size):
if 'E-fields' not in auto_corr_data[p]:
auto_corr_data[p]['E-fields'] = NP.nansum(NP.abs(Ef_info['E-fields'])**2, axis=0, keepdims=True)
auto_corr_data[p]['twts'] = NP.sum(Ef_info['twts'], axis=0, keepdims=True).astype(NP.float)
else:
auto_corr_data[p]['E-fields'] = NP.vstack((auto_corr_data[p]['E-fields'], NP.nansum(NP.abs(Ef_info['E-fields'])**2, axis=0, keepdims=True)))
auto_corr_data[p]['twts'] = NP.vstack((auto_corr_data[p]['twts'], NP.sum(Ef_info['twts'], axis=0, keepdims=True))).astype(NP.float)
tbsize[pol] = tbinsize[pol]
else:
raise ValueError('Input tbinsize is invalid')
auto_corr_data[p]['labels'] = Ef_info['labels']
self.tbinsize = tbsize
else:
raise ValueError('Input tbinsize is invalid')
auto_corr_data[p]['E-fields'] = NP.nan_to_num(auto_corr_data[p]['E-fields'] / auto_corr_data[p]['twts']) # nan_to_num() just in case there are NaN
self.auto_corr_data['avg'] = auto_corr_data
############################################################################
def evalAutoCorr(self, pol=None, datapool=None, tbinsize=None):
"""
------------------------------------------------------------------------
Estimates antenna-wise E-field auto-correlations under both
polarizations. It can be for the most recent timestamp, stacked or
averaged along timestamps.
Inputs:
pol [String] The polarization for which auto-correlation is to be
estimated. Can be set to 'P1' or 'P2'. If set to None,
auto-correlation is estimated for all the polarizations.
Default=None
datapool [string] denotes the data pool from which electric fields are
to be selected. Accepted values are 'current', 'stack', avg' or
None (default, same as 'current'). If set to None or
'current', the value in tselect is ignored and only
electric fields of the most recent timestamp are selected. If
set to 'avg', the auto-correlations from the stack are
averaged along the timestamps using time bin size specified
in tbinsize
tbinsize [scalar or dictionary] Contains bin size of timestamps while
averaging. Will be used only if datapool is set to 'avg'.
Default = None means all antenna E-field
auto-correlation spectra over all timestamps are averaged. If
scalar, the same (positive) value applies to all polarizations.
If dictionary, timestamp bin size (positive) in seconds is
provided under each key 'P1' and 'P2'. If any of the keys is
missing the auto-correlated antenna E-field spectra for that
polarization are averaged over all timestamps.
------------------------------------------------------------------------
"""
if datapool not in [None, 'current', 'stack', 'avg']:
raise ValueError('Input datapool must be set to None, "current", "stack" or "avg"')
if pol is None:
pol = ['P1', 'P2']
pol = NP.unique(NP.asarray(pol))
if datapool in [None, 'current']:
self.auto_corr_data['current'] = {}
for p in pol:
Ef_info = self.get_E_fields(p, flag=None, tselect=-1, fselect=None, aselect=None, datapool='current', sort=True)
Ef_info['E-fields'] = NP.abs(Ef_info['E-fields'])**2
self.auto_corr_data['current'][p] = Ef_info
if datapool in [None, 'stack']:
self.auto_corr_data['stack'] = {}
for p in pol:
Ef_info = self.get_E_fields(p, flag=None, tselect=NP.arange(len(self.timestamps)), fselect=None, aselect=None, datapool='stack', sort=True)
Ef_info['E-fields'] = NP.abs(Ef_info['E-fields'])**2
self.auto_corr_data['stack'][p] = Ef_info
if datapool in [None, 'avg']:
self.avgAutoCorr(pol=pol, tbinsize=tbinsize)
############################################################################
def FT(self, pol=None, parallel=False, nproc=None):
"""
------------------------------------------------------------------------
Computes the Fourier transform of the time series of the antennas in the
antenna array to compute the visibility spectra
------------------------------------------------------------------------
"""
if not parallel:
for label in self.antennas:
self.antennas[label].FX()
elif parallel or (nproc is not None):
if nproc is None:
nproc = max(MP.cpu_count()-1, 1)
else:
nproc = min(nproc, max(MP.cpu_count()-1, 1))
pool = MP.Pool(processes=nproc)
updated_antennas = pool.map(unwrap_antenna_FT, IT.izip(self.antennas.values()))
pool.close()
pool.join()
for antenna in updated_antennas:
self.antennas[antenna.label] = antenna
del updated_antennas
############################################################################
def grid(self, uvspacing=0.5, xypad=None, pow2=True):
"""
------------------------------------------------------------------------
Routine to produce a grid based on the antenna array
Inputs:
uvspacing [Scalar] Positive value indicating the maximum uv-spacing
desirable at the lowest wavelength (max frequency).
Default = 0.5
xypad [List] Padding to be applied around the antenna locations
before forming a grid. Units in meters. List elements should
be positive. If it is a one-element list, the element is
applicable to both x and y axes. If list contains three or
more elements, only the first two elements are considered
one for each axis. Default = None.
pow2 [Boolean] If set to True, the grid is forced to have a size
a next power of 2 relative to the actual sie required. If
False, gridding is done with the appropriate size as
determined by uvspacing. Default = True.
------------------------------------------------------------------------
"""
if self.f is None:
self.f = self.antennas.itervalues().next().f
if self.f0 is None:
self.f0 = self.antennas.itervalues().next().f0
wavelength = FCNST.c / self.f
min_lambda = NP.abs(wavelength).min()
# Change itervalues() to values() when porting to Python 3.x
# May have to change *blc and *trc with zip(*blc) and zip(*trc) when using Python 3.x
blc = NP.asarray([[self.antennas[label].blc[0,0], self.antennas[label].blc[0,1]] for label in self.antennas]).reshape(-1,2)
trc = NP.asarray([[self.antennas[label].trc[0,0], self.antennas[label].trc[0,1]] for label in self.antennas]).reshape(-1,2)
xycenter = 0.5 * (NP.amin(blc, axis=0, keepdims=True) + NP.amax(trc, axis=0, keepdims=True))
blc = blc - xycenter
trc = trc - xycenter
self.trc = NP.amax(NP.abs(NP.vstack((blc, trc))), axis=0).ravel() / min_lambda
self.blc = -1 * self.trc
self.antennas_center = xycenter
if xypad is None:
xypad = 0.0
self.gridu, self.gridv = GRD.grid_2d([(self.blc[0], self.trc[0]), (self.blc[1], self.trc[1])], pad=xypad/min_lambda, spacing=uvspacing, pow2=True)
self.grid_blc = NP.asarray([self.gridu.min(), self.gridv.min()])
self.grid_trc = NP.asarray([self.gridu.max(), self.gridv.max()])
self.grid_ready = True
############################################################################
def grid_convolve(self, pol=None, ants=None, unconvolve_existing=False,
normalize=False, method='NN', distNN=NP.inf, tol=None,
maxmatch=None, identical_antennas=True, cal_loop=False,
gridfunc_freq=None, mapping='weighted', wts_change=False,
parallel=False, nproc=None, pp_method='pool',
verbose=True):
"""
------------------------------------------------------------------------
Routine to project the complex illumination field pattern and the
electric fields on the grid. It can operate on the entire antenna array
or incrementally project the electric fields and complex illumination
field patterns from specific antennas on to an already existing grid.
(The latter is not implemented yet)
Inputs:
pol [String] The polarization to be gridded. Can be set to 'P1'
or 'P2'. If set to None, gridding for all the polarizations
is performed. Default = None
ants [instance of class AntennaArray, single instance or list
of instances of class Antenna, or a dictionary holding
instances of class Antenna] If a dictionary is provided,
the keys should be the antenna labels and the values
should be instances of class Antenna. If a list is
provided, it should be a list of valid instances of class
Antenna. These instance(s) of class Antenna will
be merged to the existing grid contained in the instance of
AntennaArray class. If ants is not provided (set to
None), the gridding operations will be performed on the
set of antennas contained in the instance of class
entire AntennaArray. Default = None.
unconvolve_existing
[Boolean] Default = False. If set to True, the effects of
gridding convolution contributed by the antenna(s)
specified will be undone before updating the antenna
measurements on the grid, if the antenna(s) is/are
already found to in the set of antennas held by the
instance of AntennaArray. If False and if one or more
antenna instances specified are already found to be held
in the instance of class AntennaArray, the code will stop
raising an error indicating the gridding oepration cannot
proceed.
normalize [Boolean] Default = False. If set to True, the gridded
weights are divided by the sum of weights so that the gridded
weights add up to unity. (Need to work on normaliation)
method [string] The gridding method to be used in applying the
antenna weights on to the antenna array grid.
Accepted values are 'NN' (nearest neighbour - default), 'CS'
(cubic spline), or 'BL' (Bi-linear). In case of applying grid
weights by 'NN' method, an optional distance upper bound for
the nearest neighbour can be provided in the parameter distNN
to prune the search and make it efficient. Currently, only
the nearest neighbour method is operational.
distNN [scalar] A positive value indicating the upper bound on
distance to the nearest neighbour in the gridding process. It
has units of distance, the same units as the antenna
attribute location and antenna array attribute gridx
and gridy. Default is NP.inf (infinite distance). It will be
internally converted to have same units as antenna
attributes wtspos (units in number of wavelengths)
maxmatch [scalar] A positive value indicating maximum number of input
locations in the antenna grid to be assigned. Default = None.
If set to None, all the antenna array grid elements specified
are assigned values for each antenna. For instance, to have
only one antenna array grid element to be populated per
antenna, use maxmatch=1.
tol [scalar] If set, only lookup data with abs(val) > tol will be
considered for nearest neighbour lookup. Default=None implies
all lookup values will be considered for nearest neighbour
determination. tol is to be interpreted as a minimum value
considered as significant in the lookup table.
identical_antennas
[boolean] indicates if all antenna elements are to be
treated as identical. If True (default), they are identical
and their gridding kernels are identical. If False, they are
not identical and each one has its own gridding kernel.
cal_loop [boolean] If True, the calibration loop is assumed to be ON
and hence the calibrated electric fields are set in the
calibration loop. If False (default), the calibration loop is
assumed to be OFF and the current electric fields are assumed
to be the calibrated data to be mapped to the grid
via gridding convolution.
gridfunc_freq
[String scalar] If set to None (not provided) or to 'scale'
assumes that attribute wtspos is given for a
reference frequency which need to be scaled for the frequency
channels. Will be ignored if the number of elements of list
in this attribute under the specific polarization are the
same as the number of frequency channels.
mapping [string] indicates the type of mapping between antenna
locations and the grid locations. Allowed values are
'sampled' and 'weighted' (default). 'sampled' means only the
antenna measurement closest ot a grid location contributes to
that grid location, whereas, 'weighted' means that all the
antennas contribute in a weighted fashion to their nearest
grid location. The former is faster but possibly discards
antenna data whereas the latter is slower but includes all
data along with their weights.
wts_change [boolean] indicates if weights and/or their lcoations have
changed from the previous intergration or snapshot.
Default=False means they have not changed. In such a case the
antenna-to-grid mapping and grid illumination pattern do not
have to be determined, and mapping and values from the
previous snapshot can be used. If True, a new mapping has to
be determined.
parallel [boolean] specifies if parallelization is to be invoked.
False (default) means only serial processing
nproc [integer] specifies number of independent processes to spawn.
Default = None, means automatically determines the number of
process cores in the system and use one less than that to
avoid locking the system for other processes. Applies only
if input parameter 'parallel' (see above) is set to True.
If nproc is set to a value more than the number of process
cores in the system, it will be reset to number of process
cores in the system minus one to avoid locking the system out
for other processes
pp_method [string] specifies if the parallelization method is handled
automatically using multirocessing pool or managed manually
by individual processes and collecting results in a queue.
The former is specified by 'pool' (default) and the latter
by 'queue'. These are the two allowed values. The pool method
has easier bookkeeping and can be fast if the computations
not expected to be memory bound. The queue method is more
suited for memory bound processes but can be slower or
inefficient in terms of CPU management.
verbose [boolean] If True, prints diagnostic and progress messages.
If False (default), suppress printing such messages.
------------------------------------------------------------------------
"""
eps = 1.0e-10
if pol is None:
pol = ['P1', 'P2']
elif not isinstance(pol, list):
pol = [pol]
if not self.grid_ready:
self.grid()
antpol = ['P1', 'P2']
for apol in antpol:
if apol in pol:
if ants is not None:
if isinstance(ants, Antenna):
ants = [ants]
if isinstance(ants, (dict, AntennaArray)):
# Check if these antennas are new or old and compatible
for key in ants:
if isinstance(ants[key], Antenna): # required if ants is a dictionary and not instance of AntennaArray
if key in self.antennas:
if unconvolve_existing: # Effects on the grid of antennas already existing must be removed
if self.antennas[key]._gridinfo[apol]: # if gridding info is not empty
for i in range(len(self.f)):
self.grid_unconvolve(ants[key].label)
else:
raise KeyError('Antenna {0} already found to exist in the dictionary of antennas but cannot proceed grid_convolve() without unconvolving first.'.format(ants[key].label))
else:
del ants[key] # remove the dictionary element since it is not an Antenna instance
if identical_antennas and (gridfunc_freq == 'scale'):
ant_dict = self.antenna_positions(pol=apol, flag=False, sort=True, centering=True)
ant_xy = ant_dict['positions'][:,:2]
self.ordered_labels = ant_dict['labels']
n_ant = ant_xy.shape[0]
Ef_dict = self.get_E_fields_old(apol, flag=False, sort=True)
Ef = Ef_dict['E-fields'].astype(NP.complex64)
# Since antennas are identical, read from first antenna, since wtspos are scaled with frequency, read from first frequency channel
wtspos_xy = ants[0].wtspos[apol][0] * FCNST.c/self.f[0]
wts = ants[0].wts[apol][0]
n_wts = wts.size
reflocs_xy = ant_xy[:,NP.newaxis,:] + wtspos_xy[NP.newaxis,:,:]
refwts_xy = wts.reshape(1,-1) * NP.ones((n_ant,1))
reflocs_xy = reflocs_xy.reshape(-1,ant_xy.shape[1])
refwts_xy = refwts_xy.reshape(-1,1).astype(NP.complex64)
reflocs_uv = reflocs_xy[:,NP.newaxis,:] * self.f.reshape(1,-1,1) / FCNST.c
refwts_uv = refwts_xy * NP.ones((1,self.f.size))
reflocs_uv = reflocs_uv.reshape(-1,ant_xy.shape[1])
refwts_uv = refwts_uv.reshape(-1,1).ravel()
inplocs = NP.hstack((self.gridu.reshape(-1,1), self.gridv.reshape(-1,1)))
ibind, nnval = LKP.lookup_1NN(reflocs_uv, refwts_uv, inplocs,
distance_ULIM=distNN*self.f.max()/FCNST.c,
remove_oob=True, tol=tol, maxmatch=maxmatch)[:2]
else:
ant_dict = self.antenna_positions(pol=apol, flag=None, sort=True, centering=True)
self.ordered_labels = ant_dict['labels']
ant_xy = ant_dict['positions'][:,:2] # n_ant x 2
n_ant = ant_xy.shape[0]
# Ef_dict = self.get_E_fields(apol, flag=None, sort=True)
# Ef = Ef_dict['E-fields'].astype(NP.complex64) # n_ant x nchan
if not cal_loop:
self.caldata[apol] = self.get_E_fields(apol, flag=None, tselect=-1, fselect=None, aselect=None, datapool='current', sort=True)
else:
if self.caldata[apol] is None:
self.caldata[apol] = self.get_E_fields(apol, flag=None, tselect=-1, fselect=None, aselect=None, datapool='current', sort=True)
Ef = self.caldata[apol]['E-fields'].astype(NP.complex64) # (n_ts=1) x n_ant x nchan
Ef = NP.squeeze(Ef, axis=0) # n_ant x nchan
if Ef.shape[0] != n_ant:
raise ValueError('Encountered unexpected behavior. Need to debug.')
ant_labels = self.caldata[apol]['labels']
twts = self.caldata[apol]['twts'] # (n_ts=1) x n_ant x (nchan=1)
twts = NP.squeeze(twts, axis=(0,2)) # n_ant
if verbose:
print 'Gathered antenna data for gridding convolution for timestamp {0}'.format(self.timestamp)
if wts_change or (not self.grid_mapper[apol]['labels']):
if gridfunc_freq == 'scale':
if identical_antennas:
wts_tol = 1e-6
# Since antennas are identical, read from first antenna, since wtspos are scaled with frequency, read from first frequency channel
wtspos_xy = self.antennas.itervalues().next().wtspos[apol][0] * FCNST.c/self.f[0]
wts = self.antennas.itervalues().next().wts[apol][0].astype(NP.complex64)
wtspos_xy = wtspos_xy[NP.abs(wts) >= wts_tol, :]
wts = wts[NP.abs(wts) >= wts_tol]
n_wts = wts.size
reflocs_xy = ant_xy[:,NP.newaxis,:] + wtspos_xy[NP.newaxis,:,:] # n_ant x n_wts x 2
refwts = wts.reshape(1,-1) * NP.ones((n_ant,1)) # n_ant x n_wts
else:
for i,label in enumerate(self.ordered_labels):
ant_wtspos = self.antennas[label].wtspos[apol][0]
ant_wts = self.antennas[label].wts[apol][0].astype(NP.complex64)
if i == 0:
wtspos = ant_wtspos[NP.newaxis,:,:] # 1 x n_wts x 2
refwts = ant_wts.reshape(1,-1) # 1 x n_wts
else:
wtspos = NP.vstack((wtspos, ant_wtspos[NP.newaxis,:,:])) # n_ant x n_wts x 2
refwts = NP.vstack((refwts, ant_wts.reshape(1,-1))) # n_ant x n_wts
reflocs_xy = ant_xy[:,NP.newaxis,:] + wtspos * FCNST.c/self.f[0] # n_ant x n_wts x 2
reflocs_xy = reflocs_xy.reshape(-1,ant_xy.shape[1]) # (n_ant x n_wts) x 2
refwts = refwts.ravel()
self.grid_mapper[apol]['refwts'] = NP.copy(refwts.ravel()) # (n_ant x n_wts)
else: # Weights do not scale with frequency (needs serious development)
pass
gridlocs = NP.hstack((self.gridu.reshape(-1,1), self.gridv.reshape(-1,1)))
contributed_ant_grid_Ef = None
if parallel: # Use parallelization over frequency to determine gridding convolution
if nproc is None:
nproc = max(MP.cpu_count()-1, 1)
else:
nproc = min(nproc, max(MP.cpu_count()-1, 1))
if pp_method == 'queue': ## Use MP.Queue(): useful for memory intensive parallelizing but can be slow
job_chunk_begin = range(0,self.f.size,nproc)
if verbose:
progress = PGB.ProgressBar(widgets=[PGB.Percentage(), PGB.Bar(marker='-', left=' |', right='| '), PGB.Counter(), '/{0:0d} job chunks '.format(len(job_chunk_begin)), PGB.ETA()], maxval=len(job_chunk_begin)).start()
for ijob, job_start in enumerate(job_chunk_begin):
pjobs = []
out_q = MP.Queue()
for job_ind in xrange(job_start, min(job_start+nproc, self.f.size)): # Start the processes and store outputs in the queue
if mapping == 'weighted':
pjob = MP.Process(target=LKP.find_1NN_pp, args=(gridlocs, reflocs_xy * self.f[job_ind]/FCNST.c, job_ind, out_q, distNN*self.f.max()/FCNST.c, True), name='process-{0:0d}-channel-{1:0d}'.format(job_ind-job_start, job_ind))
else:
pjob = MP.Process(target=LKP.find_1NN_pp, args=(reflocs_xy * self.f[job_ind]/FCNST.c, gridlocs, job_ind, out_q, distNN*self.f.max()/FCNST.c, True), name='process-{0:0d}-channel-{1:0d}'.format(job_ind-job_start, job_ind))
pjob.start()
pjobs.append(pjob)
for p in xrange(len(pjobs)): # Unpack the queue output
outdict = out_q.get()
chan = outdict.keys()[0]
if mapping == 'weighted':
refind, gridind = outdict[chan]['inpind'], outdict[chan]['refind']
else:
gridind, refind = outdict[chan]['inpind'], outdict[chan]['refind']
self.grid_mapper[apol]['refind'] += [refind]
self.grid_mapper[apol]['gridind'] += [gridind]
ant_ind, lkp_ind = NP.unravel_index(refind, (n_ant, n_wts))
self.grid_mapper[apol]['ant']['ind_freq'] += [ant_ind]
gridind_unraveled = NP.unravel_index(gridind, self.gridu.shape) + (chan+NP.zeros(gridind.size,dtype=int),)
gridind_raveled = NP.ravel_multi_index(gridind_unraveled, self.gridu.shape+(self.f.size,))
if self.grid_mapper[apol]['ant']['ind_all'] is None:
self.grid_mapper[apol]['ant']['ind_all'] = NP.copy(ant_ind)
self.grid_mapper[apol]['ant']['illumination'] = refwts[refind]
contributed_ant_grid_Ef = refwts[refind] * Ef[ant_ind,chan]
self.grid_mapper[apol]['grid']['ind_all'] = NP.copy(gridind_raveled)
else:
self.grid_mapper[apol]['ant']['ind_all'] = NP.append(self.grid_mapper[apol]['ant']['ind_all'], ant_ind)
self.grid_mapper[apol]['ant']['illumination'] = NP.append(self.grid_mapper[apol]['ant']['illumination'], refwts[refind])
contributed_ant_grid_Ef = NP.append(contributed_ant_grid_Ef, refwts[refind] * Ef[ant_ind,chan])
self.grid_mapper[apol]['grid']['ind_all'] = NP.append(self.grid_mapper[apol]['grid']['ind_all'], gridind_raveled)
for pjob in pjobs:
pjob.join()
del out_q
if verbose:
progress.update(ijob+1)
if verbose:
progress.finish()
elif pp_method == 'pool': ## Using MP.Pool.map(): Can be faster if parallelizing is not memory intensive
list_of_gridlocs = [gridlocs] * self.f.size
list_of_reflocs = [reflocs_xy * f/FCNST.c for f in self.f]
list_of_dist_NN = [distNN*self.f.max()/FCNST.c] * self.f.size
list_of_remove_oob = [True] * self.f.size
pool = MP.Pool(processes=nproc)
if mapping == 'weighted':
list_of_NNout = pool.map(find_1NN_arg_splitter, IT.izip(list_of_gridlocs, list_of_reflocs, list_of_dist_NN, list_of_remove_oob))
else:
list_of_NNout = pool.map(find_1NN_arg_splitter, IT.izip(list_of_reflocs, list_of_gridlocs, list_of_dist_NN, list_of_remove_oob))
pool.close()
pool.join()
for chan, NNout in enumerate(list_of_NNout): # Unpack the pool output
if mapping == 'weighted':
refind, gridind = NNout[0], NNout[1]
else:
gridind, refind = NNout[0], NNout[1]
self.grid_mapper[apol]['refind'] += [refind]
self.grid_mapper[apol]['gridind'] += [gridind]
ant_ind, lkp_ind = NP.unravel_index(refind, (n_ant, n_wts))
self.grid_mapper[apol]['ant']['ind_freq'] += [ant_ind]
gridind_unraveled = NP.unravel_index(gridind, self.gridu.shape) + (chan+NP.zeros(gridind.size,dtype=int),)
gridind_raveled = NP.ravel_multi_index(gridind_unraveled, self.gridu.shape+(self.f.size,))
if chan == 0:
self.grid_mapper[apol]['ant']['ind_all'] = NP.copy(ant_ind)
self.grid_mapper[apol]['ant']['illumination'] = refwts[refind]
contributed_ant_grid_Ef = refwts[refind] * Ef[ant_ind,chan]
self.grid_mapper[apol]['grid']['ind_all'] = NP.copy(gridind_raveled)
else:
self.grid_mapper[apol]['ant']['ind_all'] = NP.append(self.grid_mapper[apol]['ant']['ind_all'], ant_ind)
self.grid_mapper[apol]['ant']['illumination'] = NP.append(self.grid_mapper[apol]['ant']['illumination'], refwts[refind])
contributed_ant_grid_Ef = NP.append(contributed_ant_grid_Ef, refwts[refind] * Ef[ant_ind,chan])
self.grid_mapper[apol]['grid']['ind_all'] = NP.append(self.grid_mapper[apol]['grid']['ind_all'], gridind_raveled)
else:
raise ValueError('Parallel processing method specified by input parameter ppmethod has to be "pool" or "queue"')
else: # Use serial processing over frequency to determine gridding convolution
if verbose:
progress = PGB.ProgressBar(widgets=[PGB.Percentage(), PGB.Bar(marker='-', left=' |', right='| '), PGB.Counter(), '/{0:0d} Frequency channels '.format(self.f.size), PGB.ETA()], maxval=self.f.size).start()
for i in xrange(self.f.size):
if mapping == 'weighted':
refind, gridind = LKP.find_1NN(gridlocs, reflocs_xy * self.f[i]/FCNST.c,
distance_ULIM=distNN*self.f.max()/FCNST.c,
remove_oob=True)[:2]
else:
gridind, refind = LKP.find_1NN(reflocs_xy * self.f[i]/FCNST.c, gridlocs,
distance_ULIM=distNN*self.f.max()/FCNST.c,
remove_oob=True)[:2]
self.grid_mapper[apol]['refind'] += [refind]
self.grid_mapper[apol]['gridind'] += [gridind]
ant_ind, lkp_ind = NP.unravel_index(refind, (n_ant, n_wts))
self.grid_mapper[apol]['ant']['ind_freq'] += [ant_ind]
gridind_unraveled = NP.unravel_index(gridind, self.gridu.shape) + (i+NP.zeros(gridind.size,dtype=int),)
gridind_raveled = NP.ravel_multi_index(gridind_unraveled, self.gridu.shape+(self.f.size,))
if i == 0:
self.grid_mapper[apol]['ant']['ind_all'] = NP.copy(ant_ind)
self.grid_mapper[apol]['ant']['illumination'] = refwts[refind]
contributed_ant_grid_Ef = refwts[refind] * Ef[ant_ind,i]
self.grid_mapper[apol]['grid']['ind_all'] = NP.copy(gridind_raveled)
else:
self.grid_mapper[apol]['ant']['ind_all'] = NP.append(self.grid_mapper[apol]['ant']['ind_all'], ant_ind)
self.grid_mapper[apol]['ant']['illumination'] = NP.append(self.grid_mapper[apol]['ant']['illumination'], refwts[refind])
contributed_ant_grid_Ef = NP.append(contributed_ant_grid_Ef, refwts[refind] * Ef[ant_ind,i])
self.grid_mapper[apol]['grid']['ind_all'] = NP.append(self.grid_mapper[apol]['grid']['ind_all'], gridind_raveled)
if verbose:
progress.update(i+1)
if verbose:
progress.finish()
self.grid_mapper[apol]['ant']['uniq_ind_all'] = NP.unique(self.grid_mapper[apol]['ant']['ind_all'])
self.grid_mapper[apol]['ant']['rev_ind_all'] = OPS.binned_statistic(self.grid_mapper[apol]['ant']['ind_all'], statistic='count', bins=NP.append(self.grid_mapper[apol]['ant']['uniq_ind_all'], self.grid_mapper[apol]['ant']['uniq_ind_all'].max()+1))[3]
if parallel and (mapping == 'weighted'): # Use parallel processing over antennas to determine antenna-grid mapping of gridded aperture illumination and electric fields
if nproc is None:
nproc = max(MP.cpu_count()-1, 1)
else:
nproc = min(nproc, max(MP.cpu_count()-1, 1))
if pp_method == 'queue': ## Use MP.Queue(): useful for memory intensive parallelizing but can be slow
num_ant = self.grid_mapper[apol]['ant']['uniq_ind_all'].size
job_chunk_begin = range(0,num_ant,nproc)
if verbose:
progress = PGB.ProgressBar(widgets=[PGB.Percentage(), PGB.Bar(marker='-', left=' |', right='| '), PGB.Counter(), '/{0:0d} job chunks '.format(len(job_chunk_begin)), PGB.ETA()], maxval=len(job_chunk_begin)).start()
for ijob, job_start in enumerate(job_chunk_begin):
pjobs1 = []
pjobs2 = []
out_q1 = MP.Queue()
out_q2 = MP.Queue()
for job_ind in xrange(job_start, min(job_start+nproc, num_ant)): # Start the parallel processes and store the output in the queue
label = self.ordered_labels[self.grid_mapper[apol]['ant']['uniq_ind_all'][job_ind]]
if self.grid_mapper[apol]['ant']['rev_ind_all'][job_ind] < self.grid_mapper[apol]['ant']['rev_ind_all'][job_ind+1]:
self.grid_mapper[apol]['labels'][label] = {}
self.grid_mapper[apol]['labels'][label]['twts'] = twts[ant_labels.index(label)]
# self.grid_mapper[apol]['labels'][label]['flag'] = self.antennas[label].antpol.flag[apol]
select_ant_ind = self.grid_mapper[apol]['ant']['rev_ind_all'][self.grid_mapper[apol]['ant']['rev_ind_all'][job_ind]:self.grid_mapper[apol]['ant']['rev_ind_all'][job_ind+1]]
gridind_raveled_around_ant = self.grid_mapper[apol]['grid']['ind_all'][select_ant_ind]
uniq_gridind_raveled_around_ant = NP.unique(gridind_raveled_around_ant)
self.grid_mapper[apol]['labels'][label]['gridind'] = uniq_gridind_raveled_around_ant
pjob1 = MP.Process(target=antenna_grid_mapper, args=(gridind_raveled_around_ant, contributed_ant_grid_Ef[select_ant_ind], NP.append(uniq_gridind_raveled_around_ant, uniq_gridind_raveled_around_ant.max()+1), label, out_q1), name='process-{0:0d}-{1}-E-field'.format(job_ind, label))
pjob2 = MP.Process(target=antenna_grid_mapper, args=(gridind_raveled_around_ant, self.grid_mapper[apol]['ant']['illumination'][select_ant_ind], NP.append(uniq_gridind_raveled_around_ant, uniq_gridind_raveled_around_ant.max()+1), label, out_q2), name='process-{0:0d}-{1}-illumination'.format(job_ind, label))
pjob1.start()
pjob2.start()
pjobs1.append(pjob1)
pjobs2.append(pjob2)
for p in xrange(len(pjobs1)): # Unpack the E-fields and aperture illumination information from the pool output
outdict = out_q1.get()
label = outdict.keys()[0]
self.grid_mapper[apol]['labels'][label]['Ef'] = outdict[label]
outdict = out_q2.get()
label = outdict.keys()[0]
self.grid_mapper[apol]['labels'][label]['illumination'] = outdict[label]
for pjob in pjobs1:
pjob1.join()
for pjob in pjobs2:
pjob2.join()
del out_q1, out_q2
if verbose:
progress.update(ijob+1)
if verbose:
progress.finish()
elif pp_method == 'pool': ## Using MP.Pool.map(): Can be faster if parallelizing is not memory intensive
list_of_gridind_raveled_around_ant = []
list_of_ant_grid_values = []
list_of_ant_Ef_contribution = []
list_of_ant_illumination = []
list_of_uniq_gridind_raveled_around_ant = []
list_of_ant_labels = []
for j in xrange(self.grid_mapper[apol]['ant']['uniq_ind_all'].size): # re-determine gridded electric fields due to each antenna
label = self.ordered_labels[self.grid_mapper[apol]['ant']['uniq_ind_all'][j]]
if self.grid_mapper[apol]['ant']['rev_ind_all'][j] < self.grid_mapper[apol]['ant']['rev_ind_all'][j+1]:
self.grid_mapper[apol]['labels'][label] = {}
self.grid_mapper[apol]['labels'][label]['twts'] = twts[ant_labels.index(label)]
# self.grid_mapper[apol]['labels'][label]['flag'] = self.antennas[label].antpol.flag[apol]
select_ant_ind = self.grid_mapper[apol]['ant']['rev_ind_all'][self.grid_mapper[apol]['ant']['rev_ind_all'][j]:self.grid_mapper[apol]['ant']['rev_ind_all'][j+1]]
gridind_raveled_around_ant = self.grid_mapper[apol]['grid']['ind_all'][select_ant_ind]
uniq_gridind_raveled_around_ant = NP.unique(gridind_raveled_around_ant)
self.grid_mapper[apol]['labels'][label]['gridind'] = uniq_gridind_raveled_around_ant
list_of_ant_labels += [label]
list_of_gridind_raveled_around_ant += [gridind_raveled_around_ant]
list_of_uniq_gridind_raveled_around_ant += [NP.append(uniq_gridind_raveled_around_ant, uniq_gridind_raveled_around_ant.max()+1)]
list_of_ant_Ef_contribution += [contributed_ant_grid_Ef[select_ant_ind]]
list_of_ant_illumination += [self.grid_mapper[apol]['ant']['illumination'][select_ant_ind]]
pool = MP.Pool(processes=nproc)
list_of_ant_grid_values = pool.map(antenna_grid_mapping_arg_splitter, IT.izip(list_of_gridind_raveled_around_ant, list_of_ant_Ef_contribution, list_of_uniq_gridind_raveled_around_ant))
pool.close()
pool.join()
for label,grid_values in IT.izip(list_of_ant_labels, list_of_ant_grid_values): # Unpack the gridded visibility information from the pool output
self.grid_mapper[apol]['labels'][label]['Ef'] = grid_values
if nproc is not None:
pool = MP.Pool(processes=nproc)
else:
pool = MP.Pool()
list_of_ant_grid_values = pool.map(antenna_grid_mapping_arg_splitter, IT.izip(list_of_gridind_raveled_around_ant, list_of_ant_illumination, list_of_uniq_gridind_raveled_around_ant))
pool.close()
pool.join()
for label,grid_values in IT.izip(list_of_ant_labels, list_of_ant_grid_values): # Unpack the gridded visibility and aperture illumination information from the pool output
self.grid_mapper[apol]['labels'][label]['illumination'] = grid_values
del list_of_ant_grid_values, list_of_gridind_raveled_around_ant, list_of_ant_Ef_contribution, list_of_ant_illumination, list_of_uniq_gridind_raveled_around_ant, list_of_ant_labels
else:
raise ValueError('Parallel processing method specified by input parameter ppmethod has to be "pool" or "queue"')
else: # Use serial processing over antennas to determine antenna-grid mapping of gridded aperture illumination and electric fields
if verbose:
progress = PGB.ProgressBar(widgets=[PGB.Percentage(), PGB.Bar(marker='-', left=' |', right='| '), PGB.Counter(), '/{0:0d} Antennas '.format(self.grid_mapper[apol]['ant']['uniq_ind_all'].size), PGB.ETA()], maxval=self.grid_mapper[apol]['ant']['uniq_ind_all'].size).start()
for j in xrange(self.grid_mapper[apol]['ant']['uniq_ind_all'].size):
label = self.ordered_labels[self.grid_mapper[apol]['ant']['uniq_ind_all'][j]]
if self.grid_mapper[apol]['ant']['rev_ind_all'][j] < self.grid_mapper[apol]['ant']['rev_ind_all'][j+1]:
select_ant_ind = self.grid_mapper[apol]['ant']['rev_ind_all'][self.grid_mapper[apol]['ant']['rev_ind_all'][j]:self.grid_mapper[apol]['ant']['rev_ind_all'][j+1]]
self.grid_mapper[apol]['labels'][label] = {}
self.grid_mapper[apol]['labels'][label]['twts'] = twts[ant_labels.index(label)]
# self.grid_mapper[apol]['labels'][label]['flag'] = self.antennas[label].antpol.flag[apol]
if mapping == 'weighted':
gridind_raveled_around_ant = self.grid_mapper[apol]['grid']['ind_all'][select_ant_ind]
uniq_gridind_raveled_around_ant = NP.unique(gridind_raveled_around_ant)
self.grid_mapper[apol]['labels'][label]['gridind'] = uniq_gridind_raveled_around_ant
self.grid_mapper[apol]['labels'][label]['Ef'] = OPS.binned_statistic(gridind_raveled_around_ant, contributed_ant_grid_Ef[select_ant_ind].real, statistic='sum', bins=NP.append(uniq_gridind_raveled_around_ant, uniq_gridind_raveled_around_ant.max()+1))[0]
self.grid_mapper[apol]['labels'][label]['Ef'] = self.grid_mapper[apol]['labels'][label]['Ef'].astype(NP.complex64)
self.grid_mapper[apol]['labels'][label]['Ef'] += 1j * OPS.binned_statistic(gridind_raveled_around_ant, contributed_ant_grid_Ef[select_ant_ind].imag, statistic='sum', bins=NP.append(uniq_gridind_raveled_around_ant, uniq_gridind_raveled_around_ant.max()+1))[0]
self.grid_mapper[apol]['labels'][label]['illumination'] = OPS.binned_statistic(gridind_raveled_around_ant, self.grid_mapper[apol]['ant']['illumination'][select_ant_ind].real, statistic='sum', bins=NP.append(uniq_gridind_raveled_around_ant, uniq_gridind_raveled_around_ant.max()+1))[0]
self.grid_mapper[apol]['labels'][label]['illumination'] = self.grid_mapper[apol]['labels'][label]['illumination'].astype(NP.complex64)
self.grid_mapper[apol]['labels'][label]['illumination'] += 1j * OPS.binned_statistic(gridind_raveled_around_ant, self.grid_mapper[apol]['ant']['illumination'][select_ant_ind].imag, statistic='sum', bins=NP.append(uniq_gridind_raveled_around_ant, uniq_gridind_raveled_around_ant.max()+1))[0]
else:
self.grid_mapper[apol]['labels'][label]['gridind'] = self.grid_mapper[apol]['grid']['ind_all'][select_ant_ind]
self.grid_mapper[apol]['labels'][label]['Ef'] = contributed_ant_grid_Ef[select_ant_ind]
self.grid_mapper[apol]['labels'][label]['illumination'] = self.grid_mapper[apol]['ant']['illumination'][select_ant_ind]
if verbose:
progress.update(j+1)
if verbose:
progress.finish()
else: # Only re-determine gridded electric fields
if verbose:
progress = PGB.ProgressBar(widgets=[PGB.Percentage(), PGB.Bar(marker='-', left=' |', right='| '), PGB.Counter(), '/{0:0d} Frequency channels '.format(self.f.size), PGB.ETA()], maxval=self.f.size).start()
for i in xrange(self.f.size): # Only re-estimate electric fields contributed by antennas
ant_refwts = self.grid_mapper[apol]['refwts'][self.grid_mapper[apol]['refind'][i]]
ant_Ef = Ef[self.grid_mapper[apol]['ant']['ind_freq'][i],i]
if i == 0:
contributed_ant_grid_Ef = ant_refwts * ant_Ef
else:
contributed_ant_grid_Ef = NP.append(contributed_ant_grid_Ef, ant_refwts * ant_Ef)
if verbose:
progress.update(i+1)
if verbose:
progress.finish()
if parallel and (mapping == 'weighted'): # Use parallel processing
if nproc is None:
nproc = max(MP.cpu_count()-1, 1)
else:
nproc = min(nproc, max(MP.cpu_count()-1, 1))
if pp_method == 'queue': ## Use MP.Queue(): useful for memory intensive parallelizing but can be slow
num_ant = self.grid_mapper[apol]['ant']['uniq_ind_all'].size
job_chunk_begin = range(0,num_ant,nproc)
if verbose:
progress = PGB.ProgressBar(widgets=[PGB.Percentage(), PGB.Bar(marker='-', left=' |', right='| '), PGB.Counter(), '/{0:0d} job chunks '.format(len(job_chunk_begin)), PGB.ETA()], maxval=len(job_chunk_begin)).start()
for ijob, job_start in enumerate(job_chunk_begin):
pjobs = []
out_q = MP.Queue()
for job_ind in xrange(job_start, min(job_start+nproc, num_ant)): # Start the parallel processes and store the outputs in a queue
label = self.ordered_labels[self.grid_mapper[apol]['ant']['uniq_ind_all'][job_ind]]
self.grid_mapper[apol]['labels'][label]['twts'] = twts[ant_labels.index(label)]
if self.grid_mapper[apol]['ant']['rev_ind_all'][job_ind] < self.grid_mapper[apol]['ant']['rev_ind_all'][job_ind+1]:
select_ant_ind = self.grid_mapper[apol]['ant']['rev_ind_all'][self.grid_mapper[apol]['ant']['rev_ind_all'][job_ind]:self.grid_mapper[apol]['ant']['rev_ind_all'][job_ind+1]]
gridind_raveled_around_ant = self.grid_mapper[apol]['grid']['ind_all'][select_ant_ind]
uniq_gridind_raveled_around_ant = self.grid_mapper[apol]['labels'][label]['gridind']
pjob = MP.Process(target=antenna_grid_mapper, args=(gridind_raveled_around_ant, contributed_ant_grid_Ef[select_ant_ind], NP.append(uniq_gridind_raveled_around_ant, uniq_gridind_raveled_around_ant.max()+1), label, out_q), name='process-{0:0d}-{1}-E-field'.format(job_ind, label))
pjob.start()
pjobs.append(pjob)
for p in xrange(len(pjobs)): # Unpack the gridded visibility information from the queue
outdict = out_q.get()
label = outdict.keys()[0]
self.grid_mapper[apol]['labels'][label]['Ef'] = outdict[label]
for pjob in pjobs:
pjob.join()
del out_q
if verbose:
progress.update(ijob+1)
if verbose:
progress.finish()
else: ## Use MP.Pool.map(): Can be faster if parallelizing is not memory intensive
list_of_gridind_raveled_around_ant = []
list_of_ant_Ef_contribution = []
list_of_uniq_gridind_raveled_around_ant = []
list_of_ant_labels = []
for j in xrange(self.grid_mapper[apol]['ant']['uniq_ind_all'].size): # re-determine gridded electric fields due to each antenna
if self.grid_mapper[apol]['ant']['rev_ind_all'][j] < self.grid_mapper[apol]['ant']['rev_ind_all'][j+1]:
select_ant_ind = self.grid_mapper[apol]['ant']['rev_ind_all'][self.grid_mapper[apol]['ant']['rev_ind_all'][j]:self.grid_mapper[apol]['ant']['rev_ind_all'][j+1]]
label = self.ordered_labels[self.grid_mapper[apol]['ant']['uniq_ind_all'][j]]
self.grid_mapper[apol]['labels'][label]['twts'] = twts[ant_labels.index(label)]
gridind_raveled_around_ant = self.grid_mapper[apol]['grid']['ind_all'][select_ant_ind]
uniq_gridind_raveled_around_ant = NP.unique(gridind_raveled_around_ant)
list_of_ant_labels += [label]
list_of_gridind_raveled_around_ant += [gridind_raveled_around_ant]
list_of_uniq_gridind_raveled_around_ant += [NP.append(uniq_gridind_raveled_around_ant, uniq_gridind_raveled_around_ant.max()+1)]
list_of_ant_Ef_contribution += [contributed_ant_grid_Ef[select_ant_ind]]
if nproc is None:
nproc = max(MP.cpu_count()-1, 1)
else:
nproc = min(nproc, max(MP.cpu_count()-1, 1))
pool = MP.Pool(processes=nproc)
list_of_grid_Ef = pool.map(antenna_grid_mapping_arg_splitter, IT.izip(list_of_gridind_raveled_around_ant, list_of_ant_Ef_contribution, list_of_uniq_gridind_raveled_around_ant))
pool.close()
pool.join()
for label,grid_Ef in IT.izip(list_of_ant_labels, list_of_grid_Ef): # Unpack the gridded visibility information from the pool output
self.grid_mapper[apol]['labels'][label]['Ef'] = grid_Ef
del list_of_gridind_raveled_around_ant, list_of_grid_Ef, list_of_ant_Ef_contribution, list_of_uniq_gridind_raveled_around_ant, list_of_ant_labels
else: # use serial processing
if verbose:
progress = PGB.ProgressBar(widgets=[PGB.Percentage(), PGB.Bar(marker='-', left=' |', right='| '), PGB.Counter(), '/{0:0d} Antennas '.format(self.grid_mapper[apol]['ant']['uniq_ind_all'].size), PGB.ETA()], maxval=self.grid_mapper[apol]['ant']['uniq_ind_all'].size).start()
for j in xrange(self.grid_mapper[apol]['ant']['uniq_ind_all'].size): # re-determine gridded electric fields due to each antenna
if self.grid_mapper[apol]['ant']['rev_ind_all'][j] < self.grid_mapper[apol]['ant']['rev_ind_all'][j+1]:
select_ant_ind = self.grid_mapper[apol]['ant']['rev_ind_all'][self.grid_mapper[apol]['ant']['rev_ind_all'][j]:self.grid_mapper[apol]['ant']['rev_ind_all'][j+1]]
label = self.ordered_labels[self.grid_mapper[apol]['ant']['uniq_ind_all'][j]]
self.grid_mapper[apol]['labels'][label]['twts'] = twts[ant_labels.index(label)]
self.grid_mapper[apol]['labels'][label]['Ef'] = {}
if mapping == 'weighted':
gridind_raveled_around_ant = self.grid_mapper[apol]['grid']['ind_all'][select_ant_ind]
uniq_gridind_raveled_around_ant = self.grid_mapper[apol]['labels'][label]['gridind']
# uniq_gridind_raveled_around_ant = NP.unique(gridind_raveled_around_ant)
self.grid_mapper[apol]['labels'][label]['Ef'] = OPS.binned_statistic(gridind_raveled_around_ant, contributed_ant_grid_Ef[select_ant_ind].real, statistic='sum', bins=NP.append(uniq_gridind_raveled_around_ant, uniq_gridind_raveled_around_ant.max()+1))[0]
self.grid_mapper[apol]['labels'][label]['Ef'] = self.grid_mapper[apol]['labels'][label]['Ef'].astype(NP.complex64)
self.grid_mapper[apol]['labels'][label]['Ef'] += 1j * OPS.binned_statistic(gridind_raveled_around_ant, contributed_ant_grid_Ef[select_ant_ind].imag, statistic='sum', bins=NP.append(uniq_gridind_raveled_around_ant, uniq_gridind_raveled_around_ant.max()+1))[0]
else:
self.grid_mapper[apol]['labels'][label]['Ef'] = contributed_ant_grid_Ef[select_ant_ind]
if verbose:
progress.update(j+1)
if verbose:
progress.finish()
############################################################################
def grid_convolve_new(self, pol=None, normalize=False, method='NN',
distNN=NP.inf, identical_antennas=True,
cal_loop=False, gridfunc_freq=None, wts_change=False,
parallel=False, nproc=None, pp_method='pool',
verbose=True):
"""
------------------------------------------------------------------------
Routine to project the complex illumination field pattern and the
electric fields on the grid from the antenna array
Inputs:
pol [String] The polarization to be gridded. Can be set to 'P1'
or 'P2'. If set to None, gridding for all the polarizations
is performed. Default = None
normalize [Boolean] Default = False. If set to True, the gridded
weights are divided by the sum of weights so that the gridded
weights add up to unity. (Need to work on normaliation)
method [string] The gridding method to be used in applying the
antenna weights on to the antenna array grid.
Accepted values are 'NN' (nearest neighbour - default), 'CS'
(cubic spline), or 'BL' (Bi-linear). In case of applying grid
weights by 'NN' method, an optional distance upper bound for
the nearest neighbour can be provided in the parameter distNN
to prune the search and make it efficient. Currently, only
the nearest neighbour method is operational.
distNN [scalar] A positive value indicating the upper bound on
distance to the nearest neighbour in the gridding process. It
has units of distance, the same units as the antenna
attribute location and antenna array attribute gridx
and gridy. Default is NP.inf (infinite distance). It will be
internally converted to have same units as antenna
attributes wtspos (units in number of wavelengths). To ensure
all relevant pixels in the grid, the search distance used
internally will be a fraction more than distNN
identical_antennas
[boolean] indicates if all antenna elements are to be
treated as identical. If True (default), they are identical
and their gridding kernels are identical. If False, they are
not identical and each one has its own gridding kernel.
cal_loop [boolean] If True, the calibration loop is assumed to be ON
and hence the calibrated electric fields are set in the
calibration loop. If False (default), the calibration loop is
assumed to be OFF and the current electric fields are assumed
to be the calibrated data to be mapped to the grid
via gridding convolution.
gridfunc_freq
[String scalar] If set to None (not provided) or to 'scale'
assumes that attribute wtspos is given for a
reference frequency which need to be scaled for the frequency
channels. Will be ignored if the number of elements of list
in this attribute under the specific polarization are the
same as the number of frequency channels.
wts_change [boolean] indicates if weights and/or their lcoations have
changed from the previous intergration or snapshot.
Default=False means they have not changed. In such a case the
antenna-to-grid mapping and grid illumination pattern do not
have to be determined, and mapping and values from the
previous snapshot can be used. If True, a new mapping has to
be determined.
parallel [boolean] specifies if parallelization is to be invoked.
False (default) means only serial processing
nproc [integer] specifies number of independent processes to spawn.
Default = None, means automatically determines the number of
process cores in the system and use one less than that to
avoid locking the system for other processes. Applies only
if input parameter 'parallel' (see above) is set to True.
If nproc is set to a value more than the number of process
cores in the system, it will be reset to number of process
cores in the system minus one to avoid locking the system out
for other processes
pp_method [string] specifies if the parallelization method is handled
automatically using multirocessing pool or managed manually
by individual processes and collecting results in a queue.
The former is specified by 'pool' (default) and the latter
by 'queue'. These are the two allowed values. The pool method
has easier bookkeeping and can be fast if the computations
not expected to be memory bound. The queue method is more
suited for memory bound processes but can be slower or
inefficient in terms of CPU management.
verbose [boolean] If True, prints diagnostic and progress messages.
If False (default), suppress printing such messages.
------------------------------------------------------------------------
"""
if pol is None:
pol = ['P1', 'P2']
elif not isinstance(pol, list):
pol = [pol]
if not self.grid_ready:
self.grid()
du = self.gridu[0,1] - self.gridu[0,0]
dv = self.gridv[1,0] - self.gridv[0,0]
wavelength = FCNST.c / self.f
min_lambda = NP.abs(wavelength).min()
rmaxNN = 0.5 * NP.sqrt(du**2 + dv**2) * min_lambda
krn = {}
antpol = ['P1', 'P2']
for apol in antpol:
krn[apol] = None
if apol in pol:
ant_dict = self.antenna_positions(pol=apol, flag=None, sort=True, centering=True)
self.ordered_labels = ant_dict['labels']
ant_xy = ant_dict['positions'][:,:2] # n_ant x 2
n_ant = ant_xy.shape[0]
if not cal_loop:
self.caldata[apol] = self.get_E_fields(apol, flag=None, tselect=-1, fselect=None, aselect=None, datapool='current', sort=True)
else:
if self.caldata[apol] is None:
self.caldata[apol] = self.get_E_fields(apol, flag=None, tselect=-1, fselect=None, aselect=None, datapool='current', sort=True)
Ef = self.caldata[apol]['E-fields'].astype(NP.complex64) # (n_ts=1) x n_ant x nchan
Ef = NP.squeeze(Ef, axis=0) # n_ant x nchan
if Ef.shape[0] != n_ant:
raise ValueError('Encountered unexpected behavior. Need to debug.')
ant_labels = self.caldata[apol]['labels']
twts = self.caldata[apol]['twts'] # (n_ts=1) x n_ant x (nchan=1)
twts = NP.squeeze(twts, axis=(0,2)) # n_ant
if verbose:
print 'Gathered antenna data for gridding convolution for timestamp {0}'.format(self.timestamp)
if wts_change or (not self.grid_mapper[apol]['all_ant2grid']):
self.grid_mapper[apol]['per_ant2grid'] = []
self.grid_mapper[apol]['all_ant2grid'] = {}
gridlocs = NP.hstack((self.gridu.reshape(-1,1), self.gridv.reshape(-1,1)))
if gridfunc_freq == 'scale':
grid_xy = gridlocs[NP.newaxis,:,:] * wavelength.reshape(-1,1,1) # nchan x nv x nu
wl = NP.ones(gridlocs.shape[0])[NP.newaxis,:] * wavelength.reshape(-1,1)
grid_xy = grid_xy.reshape(-1,2)
wl = wl.reshape(-1)
indNN_list, antind, fvu_gridind = LKP.find_NN(ant_xy, grid_xy, distance_ULIM=2.0*distNN, flatten=True, parallel=False)
dxy = grid_xy[fvu_gridind,:] - ant_xy[antind,:]
fvu_gridind_unraveled = NP.unravel_index(fvu_gridind, (self.f.size,)+self.gridu.shape) # f-v-u order since temporary grid was created as nchan x nv x nu
self.grid_mapper[apol]['all_ant2grid']['antind'] = NP.copy(antind)
self.grid_mapper[apol]['all_ant2grid']['u_gridind'] = NP.copy(fvu_gridind_unraveled[2])
self.grid_mapper[apol]['all_ant2grid']['v_gridind'] = NP.copy(fvu_gridind_unraveled[1])
self.grid_mapper[apol]['all_ant2grid']['f_gridind'] = NP.copy(fvu_gridind_unraveled[0])
self.grid_mapper[apol]['all_ant2grid']['indNN_list'] = copy.deepcopy(indNN_list)
if identical_antennas:
arbitrary_antenna_aperture = self.antennas.itervalues().next().aperture
krn = arbitrary_antenna_aperture.compute(dxy, wavelength=wl[fvu_gridind], pol=apol, rmaxNN=rmaxNN, load_lookup=False)
else:
# This block #1 is one way to go about per antenna
for ai,gi in enumerate(indNN_list):
if len(gi) > 0:
label = self.ordered_labels[ai]
ind = NP.asarray(gi)
diffxy = grid_xy[ind,:].reshape(-1,2) - ant_xy[ai,:].reshape(-1,2)
krndict = self.antennas[label].aperture.compute(diffxy, wavelength=wl[ind], pol=apol, rmaxNN=rmaxNN, load_lookup=False)
if krn[apol] is None:
krn[apol] = NP.copy(krndict[apol])
else:
krn[apol] = NP.append(krn[apol], krndict[apol])
# # This block #2 is another way equivalent to above block #1
# uniq_antind = NP.unique(antind)
# anthist, antbe, antbn, antri = OPS.binned_statistic(antind, statistic='count', bins=NP.append(uniq_antind, uniq_antind.max()+1))
# for i,uantind in enumerate(uniq_antind):
# label = self.ordered_labels[uantind]
# ind = antri[antri[i]:antri[i+1]]
# krndict = self.antennas[label].aperture.compute(dxy[ind,:], wavelength=wl[ind], pol=apol, rmaxNN=rmaxNN, load_lookup=False)
# if krn[apol] is None:
# krn[apol] = NP.copy(krndict[apol])
# else:
# krn[apol] = NP.append(krn[apol], krndict[apol])
self.grid_mapper[apol]['all_ant2grid']['illumination'] = NP.copy(krn[apol])
else: # Weights do not scale with frequency (needs serious development)
pass
# Determine weights that can normalize sum of kernel per antenna per frequency to unity
per_ant_per_freq_norm_wts = NP.zeros(antind.size, dtype=NP.complex64)
# per_ant_per_freq_norm_wts = NP.ones(antind.size, dtype=NP.complex64)
runsum = 0
for ai,gi in enumerate(indNN_list):
if len(gi) > 0:
fvu_ind = NP.asarray(gi)
unraveled_fvu_ind = NP.unravel_index(fvu_ind, (self.f.size,)+self.gridu.shape)
f_ind = unraveled_fvu_ind[0]
v_ind = unraveled_fvu_ind[1]
u_ind = unraveled_fvu_ind[2]
chanhist, chanbe, chanbn, chanri = OPS.binned_statistic(f_ind, statistic='count', bins=NP.arange(self.f.size+1))
for ci in xrange(self.f.size):
if chanhist[ci] > 0.0:
select_chan_ind = chanri[chanri[ci]:chanri[ci+1]]
per_ant_per_freq_kernel_sum = NP.sum(krn[apol][runsum:runsum+len(gi)][select_chan_ind])
per_ant_per_freq_norm_wts[runsum:runsum+len(gi)][select_chan_ind] = 1.0 / per_ant_per_freq_kernel_sum
per_ant2grid_info = {}
per_ant2grid_info['label'] = self.ordered_labels[ai]
per_ant2grid_info['f_gridind'] = NP.copy(f_ind)
per_ant2grid_info['u_gridind'] = NP.copy(u_ind)
per_ant2grid_info['v_gridind'] = NP.copy(v_ind)
# per_ant2grid_info['fvu_gridind'] = NP.copy(gi)
per_ant2grid_info['per_ant_per_freq_norm_wts'] = per_ant_per_freq_norm_wts[runsum:runsum+len(gi)]
per_ant2grid_info['illumination'] = krn[apol][runsum:runsum+len(gi)]
self.grid_mapper[apol]['per_ant2grid'] += [copy.deepcopy(per_ant2grid_info)]
runsum += len(gi)
self.grid_mapper[apol]['all_ant2grid']['per_ant_per_freq_norm_wts'] = NP.copy(per_ant_per_freq_norm_wts)
# Determine the gridded electric fields
Ef_on_grid = Ef[(self.grid_mapper[apol]['all_ant2grid']['antind'], self.grid_mapper[apol]['all_ant2grid']['f_gridind'])]
self.grid_mapper[apol]['all_ant2grid']['Ef'] = copy.deepcopy(Ef_on_grid)
runsum = 0
for ai,gi in enumerate(self.grid_mapper[apol]['all_ant2grid']['indNN_list']):
if len(gi) > 0:
self.grid_mapper[apol]['per_ant2grid'][ai]['Ef'] = Ef_on_grid[runsum:runsum+len(gi)]
runsum += len(gi)
############################################################################
def genMappingMatrix(self, pol=None, normalize=True, method='NN',
distNN=NP.inf, identical_antennas=True,
gridfunc_freq=None, wts_change=False, parallel=False,
nproc=None, verbose=True):
"""
------------------------------------------------------------------------
Routine to construct sparse antenna-to-grid mapping matrix that will be
used in projecting illumination and electric fields from the array of
antennas onto the grid. It has elements very common to
grid_convolve_new()
Inputs:
pol [String] The polarization to be gridded. Can be set to 'P1'
or 'P2'. If set to None, gridding for all the polarizations
is performed. Default = None
normalize [Boolean] Default = False. If set to True, the gridded
weights are divided by the sum of weights so that the gridded
weights add up to unity. (Need to work on normalization)
method [string] The gridding method to be used in applying the
antenna weights on to the antenna array grid.
Accepted values are 'NN' (nearest neighbour - default), 'CS'
(cubic spline), or 'BL' (Bi-linear). In case of applying grid
weights by 'NN' method, an optional distance upper bound for
the nearest neighbour can be provided in the parameter distNN
to prune the search and make it efficient. Currently, only
the nearest neighbour method is operational.
distNN [scalar] A positive value indicating the upper bound on
distance to the nearest neighbour in the gridding process. It
has units of distance, the same units as the antenna
attribute location and antenna array attribute gridx
and gridy. Default is NP.inf (infinite distance). It will be
internally converted to have same units as antenna
attributes wtspos (units in number of wavelengths). To ensure
all relevant pixels in the grid, the search distance used
internally will be a fraction more than distNN
identical_antennas
[boolean] indicates if all antenna elements are to be
treated as identical. If True (default), they are identical
and their gridding kernels are identical. If False, they are
not identical and each one has its own gridding kernel.
gridfunc_freq
[String scalar] If set to None (not provided) or to 'scale'
assumes that attribute wtspos is given for a
reference frequency which need to be scaled for the frequency
channels. Will be ignored if the number of elements of list
in this attribute under the specific polarization are the
same as the number of frequency channels.
wts_change [boolean] indicates if weights and/or their lcoations have
changed from the previous intergration or snapshot.
Default=False means they have not changed. In such a case the
antenna-to-grid mapping and grid illumination pattern do not
have to be determined, and mapping and values from the
previous snapshot can be used. If True, a new mapping has to
be determined.
parallel [boolean] specifies if parallelization is to be invoked.
False (default) means only serial processing
nproc [integer] specifies number of independent processes to spawn.
Default = None, means automatically determines the number of
process cores in the system and use one less than that to
avoid locking the system for other processes. Applies only
if input parameter 'parallel' (see above) is set to True.
If nproc is set to a value more than the number of process
cores in the system, it will be reset to number of process
cores in the system minus one to avoid locking the system out
for other processes
verbose [boolean] If True, prints diagnostic and progress messages.
If False (default), suppress printing such messages.
NOTE: Although certain portions are parallelizable, the overheads in
these processes seem to make it worse than serial processing. It is
advisable to stick to serialized version unless testing with larger
data sets clearly indicates otherwise.
------------------------------------------------------------------------
"""
if pol is None:
pol = ['P1', 'P2']
elif not isinstance(pol, list):
pol = [pol]
if not self.grid_ready:
self.grid()
du = self.gridu[0,1] - self.gridu[0,0]
dv = self.gridv[1,0] - self.gridv[0,0]
wavelength = FCNST.c / self.f
min_lambda = NP.abs(wavelength).min()
rmaxNN = 0.5 * NP.sqrt(du**2 + dv**2) * min_lambda
krn = {}
# self.ant2grid_mapper = {}
antpol = ['P1', 'P2']
for apol in antpol:
krn[apol] = None
# self.ant2grid_mapper[apol] = None
if apol in pol:
ant_dict = self.antenna_positions(pol=apol, flag=None, sort=True, centering=True)
self.ordered_labels = ant_dict['labels']
ant_xy = ant_dict['positions'][:,:2] # n_ant x 2
n_ant = ant_xy.shape[0]
if verbose:
print 'Gathered antenna data for gridding convolution for timestamp {0}'.format(self.timestamp)
if wts_change or (not self.grid_mapper[apol]['all_ant2grid']):
self.ant2grid_mapper[apol] = None
self.grid_mapper[apol]['per_ant2grid'] = []
self.grid_mapper[apol]['all_ant2grid'] = {}
gridlocs = NP.hstack((self.gridu.reshape(-1,1), self.gridv.reshape(-1,1)))
if gridfunc_freq == 'scale':
grid_xy = gridlocs[NP.newaxis,:,:] * wavelength.reshape(-1,1,1) # nchan x nv x nu
wl = NP.ones(gridlocs.shape[0])[NP.newaxis,:] * wavelength.reshape(-1,1)
grid_xy = grid_xy.reshape(-1,2)
wl = wl.reshape(-1)
indNN_list, antind, fvu_gridind = LKP.find_NN(ant_xy, grid_xy, distance_ULIM=2.0*distNN, flatten=True, parallel=False)
dxy = grid_xy[fvu_gridind,:] - ant_xy[antind,:]
fvu_gridind_unraveled = NP.unravel_index(fvu_gridind, (self.f.size,)+self.gridu.shape) # f-v-u order since temporary grid was created as nchan x nv x nu
self.grid_mapper[apol]['all_ant2grid']['antind'] = NP.copy(antind)
self.grid_mapper[apol]['all_ant2grid']['u_gridind'] = NP.copy(fvu_gridind_unraveled[2])
self.grid_mapper[apol]['all_ant2grid']['v_gridind'] = NP.copy(fvu_gridind_unraveled[1])
self.grid_mapper[apol]['all_ant2grid']['f_gridind'] = NP.copy(fvu_gridind_unraveled[0])
# self.grid_mapper[apol]['all_ant2grid']['indNN_list'] = copy.deepcopy(indNN_list)
if identical_antennas:
arbitrary_antenna_aperture = self.antennas.itervalues().next().aperture
krn = arbitrary_antenna_aperture.compute(dxy, wavelength=wl[fvu_gridind], pol=apol, rmaxNN=rmaxNN, load_lookup=False)
else:
# This block #1 is one way to go about per antenna
for ai,gi in enumerate(indNN_list):
if len(gi) > 0:
label = self.ordered_labels[ai]
ind = NP.asarray(gi)
diffxy = grid_xy[ind,:].reshape(-1,2) - ant_xy[ai,:].reshape(-1,2)
krndict = self.antennas[label].aperture.compute(diffxy, wavelength=wl[ind], pol=apol, rmaxNN=rmaxNN, load_lookup=False)
if krn[apol] is None:
krn[apol] = NP.copy(krndict[apol])
else:
krn[apol] = NP.append(krn[apol], krndict[apol])
# # This block #2 is another way equivalent to above block #1
# uniq_antind = NP.unique(antind)
# anthist, antbe, antbn, antri = OPS.binned_statistic(antind, statistic='count', bins=NP.append(uniq_antind, uniq_antind.max()+1))
# for i,uantind in enumerate(uniq_antind):
# label = self.ordered_labels[uantind]
# ind = antri[antri[i]:antri[i+1]]
# krndict = self.antennas[label].aperture.compute(dxy[ind,:], wavelength=wl[ind], pol=apol, rmaxNN=rmaxNN, load_lookup=False)
# if krn[apol] is None:
# krn[apol] = NP.copy(krndict[apol])
# else:
# krn[apol] = NP.append(krn[apol], krndict[apol])
self.grid_mapper[apol]['all_ant2grid']['illumination'] = NP.copy(krn[apol])
else: # Weights do not scale with frequency (needs serious development)
pass
# Determine weights that can normalize sum of kernel per antenna per frequency to unity
per_ant_per_freq_norm_wts = NP.zeros(antind.size, dtype=NP.complex64)
# per_ant_per_freq_norm_wts = NP.ones(antind.size, dtype=NP.complex64)
if parallel or (nproc is not None):
list_of_val = []
list_of_rowcol_tuple = []
else:
spval = []
sprow = []
spcol = []
runsum = 0
if verbose:
progress = PGB.ProgressBar(widgets=[PGB.Percentage(), PGB.Bar(marker='-', left=' |', right='| '), PGB.Counter(), '/{0:0d} Antennas '.format(n_ant), PGB.ETA()], maxval=n_ant).start()
for ai,gi in enumerate(indNN_list):
if len(gi) > 0:
fvu_ind = NP.asarray(gi)
unraveled_fvu_ind = NP.unravel_index(fvu_ind, (self.f.size,)+self.gridu.shape)
f_ind = unraveled_fvu_ind[0]
v_ind = unraveled_fvu_ind[1]
u_ind = unraveled_fvu_ind[2]
chanhist, chanbe, chanbn, chanri = OPS.binned_statistic(f_ind, statistic='count', bins=NP.arange(self.f.size+1))
for ci in xrange(self.f.size):
if chanhist[ci] > 0.0:
select_chan_ind = chanri[chanri[ci]:chanri[ci+1]]
per_ant_per_freq_kernel_sum = NP.sum(krn[apol][runsum:runsum+len(gi)][select_chan_ind])
per_ant_per_freq_norm_wts[runsum:runsum+len(gi)][select_chan_ind] = 1.0 / per_ant_per_freq_kernel_sum
per_ant2grid_info = {}
per_ant2grid_info['label'] = self.ordered_labels[ai]
per_ant2grid_info['f_gridind'] = NP.copy(f_ind)
per_ant2grid_info['u_gridind'] = NP.copy(u_ind)
per_ant2grid_info['v_gridind'] = NP.copy(v_ind)
# per_ant2grid_info['fvu_gridind'] = NP.copy(gi)
per_ant2grid_info['per_ant_per_freq_norm_wts'] = per_ant_per_freq_norm_wts[runsum:runsum+len(gi)]
per_ant2grid_info['illumination'] = krn[apol][runsum:runsum+len(gi)]
self.grid_mapper[apol]['per_ant2grid'] += [copy.deepcopy(per_ant2grid_info)]
runsum += len(gi)
# determine the sparse interferometer-to-grid mapping matrix pre-requisites
val = per_ant2grid_info['per_ant_per_freq_norm_wts']*per_ant2grid_info['illumination']
vuf_gridind_unraveled = (per_ant2grid_info['v_gridind'],per_ant2grid_info['u_gridind'],per_ant2grid_info['f_gridind'])
vuf_gridind_raveled = NP.ravel_multi_index(vuf_gridind_unraveled, (self.gridu.shape+(self.f.size,)))
if (not parallel) and (nproc is None):
spval += val.tolist()
sprow += vuf_gridind_raveled.tolist()
spcol += (per_ant2grid_info['f_gridind'] + ai*self.f.size).tolist()
else:
list_of_val += [per_ant2grid_info['per_ant_per_freq_norm_wts']*per_ant2grid_info['illumination']]
list_of_rowcol_tuple += [(vuf_gridind_raveled, per_ant2grid_info['f_gridind'])]
if verbose:
progress.update(ai+1)
if verbose:
progress.finish()
# determine the sparse interferometer-to-grid mapping matrix
if parallel or (nproc is not None):
list_of_shapes = [(self.gridu.size*self.f.size, self.f.size)] * n_ant
if nproc is None:
nproc = max(MP.cpu_count()-1, 1)
else:
nproc = min(nproc, max(MP.cpu_count()-1, 1))
pool = MP.Pool(processes=nproc)
list_of_spmat = pool.map(genMatrixMapper_arg_splitter, IT.izip(list_of_val, list_of_rowcol_tuple, list_of_shapes))
self.ant2grid_mapper[apol] = SpM.hstack(list_of_spmat, format='csr')
else:
spval = NP.asarray(spval)
sprowcol = (NP.asarray(sprow), NP.asarray(spcol))
self.ant2grid_mapper[apol] = SpM.csr_matrix((spval, sprowcol), shape=(self.gridu.size*self.f.size, n_ant*self.f.size))
self.grid_mapper[apol]['all_ant2grid']['per_ant_per_freq_norm_wts'] = NP.copy(per_ant_per_freq_norm_wts)
############################################################################
def applyMappingMatrix(self, pol=None, cal_loop=False, verbose=True):
"""
------------------------------------------------------------------------
Constructs the grid of complex field illumination and electric fields
using the sparse antenna-to-grid mapping matrix. Intended to serve as a
"matrix" alternative to make_grid_cube_new()
Inputs:
pol [String] The polarization to be gridded. Can be set to 'P1' or
'P2'. If set to None, gridding for all the polarizations is
performed. Default=None
cal_loop
[boolean] If True, the calibration loop is assumed to be ON
and hence the calibrated electric fields are set in the
calibration loop. If False (default), the calibration loop is
assumed to be OFF and the current electric fields are assumed
to be the calibrated data to be mapped to the grid
via gridding convolution.
verbose [boolean] If True, prints diagnostic and progress messages.
If False (default), suppress printing such messages.
------------------------------------------------------------------------
"""
if pol is None:
pol = ['P1', 'P2']
pol = NP.unique(NP.asarray(pol))
for apol in pol:
if verbose:
print 'Gridding aperture illumination and electric fields for polarization {0} ...'.format(apol)
if apol not in ['P1', 'P2']:
raise ValueError('Invalid specification for input parameter pol')
if not cal_loop:
self.caldata[apol] = self.get_E_fields(apol, flag=None, tselect=-1, fselect=None, aselect=None, datapool='current', sort=True)
else:
if self.caldata[apol] is None:
self.caldata[apol] = self.get_E_fields(apol, flag=None, tselect=-1, fselect=None, aselect=None, datapool='current', sort=True)
Ef = self.caldata[apol]['E-fields'].astype(NP.complex64) # (n_ts=1) x n_ant x nchan
Ef = NP.squeeze(Ef, axis=0) # n_ant x nchan
twts = self.caldata[apol]['twts'] # (n_ts=1) x n_ant x 1
twts = NP.squeeze(twts, axis=0) # n_ant x 1
Ef = Ef * twts # applies antenna flagging, n_ant x nchan
wts = twts * NP.ones(self.f.size).reshape(1,-1) # n_ant x nchan
wts[NP.isnan(Ef)] = 0.0
Ef[NP.isnan(Ef)] = 0.0
Ef = Ef.ravel()
wts = wts.ravel()
sparse_Ef = SpM.csr_matrix(Ef)
sparse_wts = SpM.csr_matrix(wts)
# Store as sparse matrices
self.grid_illumination[apol] = self.ant2grid_mapper[apol].dot(sparse_wts.T)
self.grid_Ef[apol] = self.ant2grid_mapper[apol].dot(sparse_Ef.T)
# # Store as dense matrices
# self.grid_illumination[apol] = self.ant2grid_mapper[apol].dot(wts).reshape(self.gridu.shape+(self.f.size,))
# self.grid_Ef[apol] = self.ant2grid_mapper[apol].dot(Ef).reshape(self.gridu.shape+(self.f.size,))
if verbose:
print 'Gridded aperture illumination and electric fields for polarization {0} from {1:0d} unflagged contributing antennas'.format(apol, NP.sum(twts).astype(int))
############################################################################
def make_grid_cube(self, pol=None, verbose=True):
"""
------------------------------------------------------------------------
Constructs the grid of complex field illumination and electric fields
using the gridding information determined for every antenna. Flags are
taken into account while constructing this grid.
Inputs:
pol [String] The polarization to be gridded. Can be set to 'P1' or
'P2'. If set to None, gridding for all the polarizations is
performed. Default=None
verbose [boolean] If True, prints diagnostic and progress messages.
If False (default), suppress printing such messages.
------------------------------------------------------------------------
"""
if pol is None:
pol = ['P1', 'P2']
pol = NP.unique(NP.asarray(pol))
for apol in pol:
if verbose:
print 'Gridding aperture illumination and electric fields for polarization {0} ...'.format(apol)
if apol not in ['P1', 'P2']:
raise ValueError('Invalid specification for input parameter pol')
if apol not in self._ant_contribution:
raise KeyError('Key {0} not found in attribute _ant_contribution'.format(apol))
self.grid_illumination[apol] = NP.zeros((self.gridu.shape + (self.f.size,)), dtype=NP.complex_)
self.grid_Ef[apol] = NP.zeros((self.gridu.shape + (self.f.size,)), dtype=NP.complex_)
labels = self.grid_mapper[apol]['labels'].keys()
if verbose:
progress = PGB.ProgressBar(widgets=[PGB.Percentage(), PGB.Bar(marker='-', left=' |', right='| '), PGB.Counter(), '/{0:0d} Antennas '.format(len(labels)), PGB.ETA()], maxval=len(labels)).start()
loopcount = 0
num_unflagged = 0
# while loopcount < len(labels):
# antinfo = self.grid_mapper[apol]['labels'].itervalues().next()
for antlabel, antinfo in self.grid_mapper[apol]['labels'].iteritems():
if not self.antennas[antlabel].antpol.flag[apol]:
num_unflagged += 1
gridind_unraveled = NP.unravel_index(antinfo['gridind'], self.gridu.shape+(self.f.size,))
self.grid_illumination[apol][gridind_unraveled] += antinfo['illumination']
self.grid_Ef[apol][gridind_unraveled] += antinfo['Ef']
if verbose:
progress.update(loopcount+1)
loopcount += 1
if verbose:
progress.finish()
if verbose:
print 'Gridded aperture illumination and electric fields for polarization {0} from {1:0d} unflagged contributing antennas'.format(apol, num_unflagged)
############################################################################
def make_grid_cube_new(self, pol=None, verbose=True):
"""
------------------------------------------------------------------------
Constructs the grid of complex field illumination and electric fields
using the gridding information determined for every antenna. Flags are
taken into account while constructing this grid.
Inputs:
pol [String] The polarization to be gridded. Can be set to 'P1' or
'P2'. If set to None, gridding for all the polarizations is
performed. Default=None
verbose [boolean] If True, prints diagnostic and progress messages.
If False (default), suppress printing such messages.
------------------------------------------------------------------------
"""
if pol is None:
pol = ['P1', 'P2']
pol = NP.unique(NP.asarray(pol))
for apol in pol:
if verbose:
print 'Gridding aperture illumination and electric fields for polarization {0} ...'.format(apol)
if apol not in ['P1', 'P2']:
raise ValueError('Invalid specification for input parameter pol')
if apol not in self._ant_contribution:
raise KeyError('Key {0} not found in attribute _ant_contribution'.format(apol))
self.grid_illumination[apol] = NP.zeros((self.gridu.shape + (self.f.size,)), dtype=NP.complex_)
self.grid_Ef[apol] = NP.zeros((self.gridu.shape + (self.f.size,)), dtype=NP.complex_)
nlabels = len(self.grid_mapper[apol]['per_ant2grid'])
loopcount = 0
num_unflagged = 0
if verbose:
progress = PGB.ProgressBar(widgets=[PGB.Percentage(), PGB.Bar(marker='-', left=' |', right='| '), PGB.Counter(), '/{0:0d} Antennas '.format(nlabels), PGB.ETA()], maxval=nlabels).start()
for ai,per_ant2grid_info in enumerate(self.grid_mapper[apol]['per_ant2grid']):
antlabel = per_ant2grid_info['label']
if not self.antennas[antlabel].antpol.flag[apol]:
num_unflagged += 1
vuf_gridind_unraveled = (per_ant2grid_info['v_gridind'],per_ant2grid_info['u_gridind'],per_ant2grid_info['f_gridind'])
self.grid_illumination[apol][vuf_gridind_unraveled] += per_ant2grid_info['per_ant_per_freq_norm_wts'] * per_ant2grid_info['illumination']
self.grid_Ef[apol][vuf_gridind_unraveled] += per_ant2grid_info['per_ant_per_freq_norm_wts'] * per_ant2grid_info['Ef'] * per_ant2grid_info['illumination']
if verbose:
progress.update(loopcount+1)
loopcount += 1
if verbose:
progress.finish()
if verbose:
print 'Gridded aperture illumination and electric fields for polarization {0} from {1:0d} unflagged contributing antennas'.format(apol, num_unflagged)
############################################################################
def evalAntennaPairCorrWts(self, label1, label2=None, forceeval=False):
"""
------------------------------------------------------------------------
Evaluate correlation of pair of antenna illumination weights on grid.
It will be computed only if it was not computed or stored in attribute
pairwise_typetag_crosswts_vuf earlier
Inputs:
label1 [string] Label of first antenna. Must be specified (no default)
label2 [string] Label of second antenna. If specified as None
(default), it will be set equal to label1 in which case the
auto-correlation of antenna weights is evaluated
forceeval
[boolean] When set to False (default) the correlation in
the UV plane is not evaluated if it was already evaluated
earlier. If set to True, it will be forcibly evaluated
independent of whether they were already evaluated or not
------------------------------------------------------------------------
"""
try:
label1
except NameError:
raise NameError('Input label1 must be specified')
if label1 not in self.antennas:
raise KeyError('Input label1 not found in current instance of class AntennaArray')
if label2 is None:
label2 = label1
if label2 not in self.antennas:
raise KeyError('Input label2 not found in current instance of class AntennaArray')
if (label1, label2) in self.antenna_pair_to_typetag:
typetag_pair = self.antenna_pair_to_typetag[(label1,label2)]
elif (label2, label1) in self.antenna_pair_to_typetag:
typetag_pair = self.antenna_pair_to_typetag[(label2,label1)]
else:
raise KeyError('Antenna pair not found in attribute antenna_pair_to_type. Needs debugging')
do_update = False
typetag1, typetag2 = typetag_pair
if forceeval or (typetag_pair not in self.pairwise_typetag_crosswts_vuf):
if forceeval:
if typetag_pair not in self.pairwise_typetag_crosswts_vuf:
do_update = True
else:
if 'last_updated' not in self.pairwise_typetag_crosswts_vuf[typetag_pair]:
do_update = True
else:
if self.timestamp - self.pairwise_typetag_crosswts_vuf[typetag_pair]['last_updated'] > 1e-10:
do_update = True
if typetag_pair not in self.pairwise_typetag_crosswts_vuf:
do_update = True
if do_update:
pol = ['P1', 'P2']
self.pairwise_typetag_crosswts_vuf[typetag_pair] = {}
self.pairwise_typetag_crosswts_vuf[typetag_pair]['last_updated'] = self.timestamp
du = self.gridu[0,1] - self.gridu[0,0]
dv = self.gridv[1,0] - self.gridv[0,0]
if (typetag1 == typetag2) and (self.antennas[label1].aperture.kernel_type['P1'] == 'func') and (self.antennas[label1].aperture.kernel_type['P2'] == 'func'):
gridu, gridv = NP.meshgrid(du*(NP.arange(2*self.gridu.shape[1])-self.gridu.shape[1]), dv*(NP.arange(2*self.gridu.shape[0])-self.gridu.shape[0]))
wavelength = FCNST.c / self.f
min_lambda = NP.abs(wavelength).min()
rmaxNN = 0.5 * NP.sqrt(du**2 + dv**2) * min_lambda
gridx = gridu[:,:,NP.newaxis] * wavelength.reshape(1,1,-1)
gridy = gridv[:,:,NP.newaxis] * wavelength.reshape(1,1,-1)
gridxy = NP.hstack((gridx.reshape(-1,1), gridy.reshape(-1,1)))
wl = NP.ones(gridu.shape)[:,:,NP.newaxis] * wavelength.reshape(1,1,-1)
ant_aprtr = copy.deepcopy(self.antennas[label1].aperture)
pol_type = 'dual'
kerntype = ant_aprtr.kernel_type
shape = ant_aprtr.shape
kernshapeparms = {p: {'xmax': ant_aprtr.xmax[p], 'ymax': ant_aprtr.ymax[p], 'rmax': ant_aprtr.rmax[p], 'rmin': ant_aprtr.rmin[p], 'rotangle': ant_aprtr.rotangle[p]} for p in pol}
for p in pol:
if shape[p] == 'rect':
shape[p] = 'auto_convolved_rect'
elif shape[p] == 'square':
shape[p] = 'auto_convolved_square'
elif shape[p] == 'circular':
shape[p] = 'auto_convolved_circular'
else:
raise ValueError('Aperture kernel footprint shape - {0} - currently unsupported'.format(shape[p]))
aprtr = APR.Aperture(pol_type=pol_type, kernel_type=kerntype,
shape=shape, parms=kernshapeparms,
lkpinfo=None, load_lookup=True)
max_aprtr_size = max([NP.sqrt(aprtr.xmax['P1']**2 + NP.sqrt(aprtr.ymax['P1']**2)), NP.sqrt(aprtr.xmax['P2']**2 + NP.sqrt(aprtr.ymax['P2']**2)), aprtr.rmax['P1'], aprtr.rmax['P2']])
distNN = 2.0 * max_aprtr_size
indNN_list, blind, vuf_gridind = LKP.find_NN(NP.zeros(2).reshape(1,-1), gridxy, distance_ULIM=distNN, flatten=True, parallel=False)
dxy = gridxy[vuf_gridind,:]
unraveled_vuf_ind = NP.unravel_index(vuf_gridind, gridu.shape+(self.f.size,))
unraveled_vu_ind = (unraveled_vuf_ind[0], unraveled_vuf_ind[1])
raveled_vu_ind = NP.ravel_multi_index(unraveled_vu_ind, (gridu.shape[0], gridu.shape[1]))
for p in pol:
krn = aprtr.compute(dxy, wavelength=wl.ravel()[vuf_gridind], pol=p, rmaxNN=rmaxNN, load_lookup=False)
krn_sparse = SpM.csr_matrix((krn[p], (raveled_vu_ind,)+(unraveled_vuf_ind[2],)), shape=(gridu.size,)+(self.f.size,), dtype=NP.complex64)
krn_sparse_sumuv = krn_sparse.sum(axis=0)
krn_sparse_norm = krn_sparse.A / krn_sparse_sumuv.A
sprow = raveled_vu_ind
spcol = unraveled_vuf_ind[2]
spval = krn_sparse_norm[(sprow,)+(spcol,)]
self.pairwise_typetag_crosswts_vuf[typetag_pair][p] = SpM.csr_matrix((spval, (sprow,)+(spcol,)), shape=(gridu.size,)+(self.f.size,), dtype=NP.complex64)
else:
ulocs = du*(NP.arange(2*self.gridu.shape[1])-self.gridu.shape[1])
vlocs = dv*(NP.arange(2*self.gridu.shape[0])-self.gridu.shape[0])
antenna_grid_wts_vuf_1 = self.antennas[label1].evalGridIllumination(uvlocs=(ulocs, vlocs), xy_center=NP.zeros(2))
shape_tuple = (vlocs.size, ulocs.size) + (self.f.size,)
eps = 1e-10
if label1 == label2:
for p in pol:
sum_wts1 = antenna_grid_wts_vuf_1[p].sum(axis=0).A
sum_wts = NP.abs(sum_wts1)**2
antpair_beam = NP.abs(NP.fft.fft2(antenna_grid_wts_vuf_1[p].toarray().reshape(shape_tuple), axes=(0,1)))**2
antpair_grid_wts_vuf = NP.fft.ifft2(antpair_beam/sum_wts[NP.newaxis,:,:], axes=(0,1)) # Inverse FFT
antpair_grid_wts_vuf = NP.fft.ifftshift(antpair_grid_wts_vuf, axes=(0,1))
antpair_grid_wts_vuf[NP.abs(antpair_grid_wts_vuf) < eps] = 0.0
self.pairwise_typetag_crosswts_vuf[typetag_pair][p] = SpM.csr_matrix(antpair_grid_wts_vuf.reshape(-1,self.f.size))
else:
antenna_grid_wts_vuf_2 = self.antennas[label2].evalGridIllumination(uvlocs=(ulocs, vlocs), xy_center=NP.zeros(2))
for p in pol:
sum_wts1 = antenna_grid_wts_vuf_1[p].sum(axis=0).A
sum_wts2 = antenna_grid_wts_vuf_2[p].sum(axis=0).A
sum_wts = sum_wts1 * sum_wts2.conj()
antpair_beam = NP.fft.fft2(antenna_grid_wts_vuf_1[p].toarray().reshape(shape_tuple), axes=(0,1)) * NP.fft.fft2(antenna_grid_wts_vuf_1[p].toarray().reshape(shape_tuple).conj(), axes=(0,1))
antpair_grid_wts_vuf = NP.fft.ifft2(antpair_beam/sum_wts[NP.newaxis,:,:], axes=(0,1)) # Inverse FFT
antpair_grid_wts_vuf = NP.fft.ifftshift(antpair_grid_wts_vuf, axes=(0,1))
antpair_grid_wts_vuf[NP.abs(antpair_grid_wts_vuf) < eps] = 0.0
self.pairwise_typetag_crosswts_vuf[typetag_pair][p] = SpM.csr_matrix(antpair_grid_wts_vuf.reshape(-1,self.f.size))
else:
print 'Specified antenna pair correlation weights have already been evaluated'
############################################################################
def evalAntennaAutoCorrWts(self, forceeval=False):
"""
------------------------------------------------------------------------
Evaluate auto-correlation of aperture illumination of each antenna on
the UVF-plane
Inputs:
forceeval [boolean] When set to False (default) the auto-correlation in
the UV plane is not evaluated if it was already evaluated
earlier. If set to True, it will be forcibly evaluated
independent of whether they were already evaluated or not
------------------------------------------------------------------------
"""
if forceeval or (not self.antenna_autowts_set):
self.antenna_autowts_set = False
for antkey in self.antennas:
self.evalAntennaPairCorrWts(antkey, label2=None, forceeval=forceeval)
self.antenna_autowts_set = True
############################################################################
def evalAllAntennaPairCorrWts(self, forceeval=False):
"""
------------------------------------------------------------------------
Evaluate zero-centered cross-correlation of aperture illumination of
each antenna pair on the UVF-plane
Inputs:
forceeval [boolean] When set to False (default) the zero-centered
cross-correlation of antenna illumination weights on
the UV plane is not evaluated if it was already evaluated
earlier. If set to True, it will be forcibly evaluated
independent of whether they were already evaluated or not
------------------------------------------------------------------------
"""
if forceeval or (not self.antenna_crosswts_set):
for label_pair in self.antenna_pair_to_typetag:
label1, label2 = label_pair
self.evalAntennaPairCorrWts(label1, label2=label2, forceeval=forceeval)
self.antenna_crosswts_set = True
############################################################################
def makeAutoCorrCube(self, pol=None, data=None, datapool='stack',
tbinsize=None, forceeval_autowts=False,
forceeval_autocorr=False, nproc=None, verbose=True):
"""
------------------------------------------------------------------------
Constructs the grid of antenna aperture illumination auto-correlation
using the gridding information determined for every antenna. Flags are
taken into account while constructing this grid
Inputs:
pol [String] The polarization to be gridded. Can be set to 'P1' or
'P2'. If set to None, gridding for all the polarizations is
performed. Default=None
data [dictionary] dictionary containing data that will be used to
determine the auto-correlations of antennas. This will be used
only if input datapool is set to 'custom'. It consists of the
following keys and information:
'labels' Contains a numpy array of strings of antenna
labels
'data' auto-correlated electric fields
(n_ant x nchan array)
datapool
[string] Specifies whether data to be used in determining the
auto-correlation the E-fields to be used come from
'stack' (default), 'current', 'avg' or 'custom'. If set to
'custom', the data provided in input data will be used.
Otherwise squared electric fields will be used if set to
'current' or 'stack', and averaged squared electric fields if
set to 'avg'
tbinsize
[scalar or dictionary] Contains bin size of timestamps while
averaging. Only used when datapool is set to 'avg' and if the
attribute auto_corr_data does not contain the key 'avg'. In
that case, default = None means all antenna E-field
auto-correlation spectra over all timestamps are averaged. If
scalar, the same (positive) value applies to all polarizations.
If dictionary, timestamp bin size (positive) in seconds is
provided under each key 'P1' and 'P2'. If any of the keys is
missing the auto-correlated antenna E-field spectra for that
polarization are averaged over all timestamps.
forceeval_autowts
[boolean] When set to False (default) the auto-correlation
weights in the UV plane is not evaluated if it was already
evaluated earlier. If set to True, it will be forcibly evaluated
independent of whether they were already evaluated or not
forceeval_autocorr
[boolean] When set to False (default) the auto-correlation
data in the UV plane is not evaluated if it was already
evaluated earlier. If set to True, it will be forcibly
evaluated independent of whether they were already evaluated
or not
nproc [integer] specifies number of independent processes to spawn.
Default = None, means automatically determines the number of
process cores in the system and use one less than that to
avoid locking the system for other processes. Applies only
if input parameter 'parallel' (see above) is set to True.
If nproc is set to a value more than the number of process
cores in the system, it will be reset to number of process
cores in the system minus one to avoid locking the system out
for other processes
verbose [boolean] If True, prints diagnostic and progress messages.
If False (default), suppress printing such messages.
Outputs:
Tuple (autocorr_wts_cube, autocorr_data_cube). autocorr_wts_cube is a
dictionary with polarization keys 'P1' and 'P2. Under each key is a
matrix of size nt x nv x nu x nchan. autocorr_data_cube is also a
dictionary with polarization keys 'P1' and 'P2. Under each key is a
matrix of size nt x nv x nu x nchan where nt=1, nt=n_timestamps,
or nt=n_tavg if datapool is set to 'current', 'stack' or 'avg'
respectively
------------------------------------------------------------------------
"""
if pol is None:
pol = ['P1', 'P2']
pol = NP.unique(NP.asarray(pol))
if datapool not in ['stack', 'current', 'avg', 'custom']:
raise ValueError('Input datapool must be set to "stack" or "current"')
if not isinstance(forceeval_autowts, bool):
raise TypeError('Input forceeval_autowts must be boolean')
if not isinstance(forceeval_autocorr, bool):
raise TypeError('Input forceeval_autocorr must be boolean')
self.evalAntennaAutoCorrWts(forceeval=forceeval_autowts)
data_info = {}
if datapool in ['current', 'stack', 'avg']:
if datapool not in self.auto_corr_data:
self.evalAutoCorr(pol=pol, datapool=datapool, tbinsize=tbinsize)
for apol in pol:
data_info[apol] = {'labels': self.auto_corr_data[datapool][apol]['labels'], 'twts': self.auto_corr_data[datapool][apol]['twts'], 'data': NP.nan_to_num(self.auto_corr_data[datapool][apol]['E-fields'])}
else:
if not isinstance(data, dict):
raise TypeError('Input data must be a dictionary')
for apol in pol:
if apol not in data:
raise KeyError('Key {)} not found in input data'.format(apol))
if not isinstance(data[apol], dict):
raise TypeError('Value under polarization key "{0}" under input data must be a dictionary'.format(apol))
if ('labels' not in data[apol]) or ('data' not in data[apol]):
raise KeyError('Keys "labels" and "data" not found under input data[{0}]'.format(apol))
autocorr_wts_cube = {p: None for p in ['P1', 'P2']}
autocorr_data_cube = {p: None for p in ['P1', 'P2']}
for apol in pol:
if verbose:
print 'Gridding auto-correlation of aperture illumination and electric fields for polarization {0} ...'.format(apol)
if apol not in ['P1', 'P2']:
raise ValueError('Invalid specification for input parameter pol')
if nproc is None:
nproc = max(MP.cpu_count()-1, 1)
else:
nproc = min(nproc, max(MP.cpu_count()-1, 1))
if nproc > 1:
list_antind = []
list_antkey = []
list_typetag_pair = []
list_shape_tuple = []
list_sparse_crosswts_vuf = []
list_twts = []
list_acorr_data = []
for antind, antkey in enumerate(data_info[apol]['labels']):
typetag_pair = self.antenna_pair_to_typetag[(antkey,antkey)]
list_shape_tuple += [tuple(2*NP.asarray(self.gridu.shape))+(self.f.size,)]
list_sparse_crosswts_vuf += [self.pairwise_typetag_crosswts_vuf[typetag_pair][apol]]
list_twts += [data_info[apol]['twts'][:,antind,:]]
list_acorr_data += [data_info[apol]['data'][:,antind,:]]
for qty in ['wts', 'data']:
pool = MP.Pool(processes=nproc)
if qty == 'wts':
outqtylist = pool.map(unwrap_multidim_product, IT.izip(list_sparse_crosswts_vuf, list_twts, [1.0]*len(data_info[apol]['labels']), list_shape_tuple))
else:
outqtylist = pool.map(unwrap_multidim_product, IT.izip(list_sparse_crosswts_vuf, list_twts, list_acorr_data, list_shape_tuple))
pool.close()
pool.join()
if qty == 'wts':
autocorr_wts_cube[apol] = NP.sum(NP.array(outqtylist), axis=0)
else:
autocorr_data_cube[apol] = NP.sum(NP.array(outqtylist), axis=0)
del outqtylist
else: # Serial processing of autocorr accumulation into cube
progress = PGB.ProgressBar(widgets=[PGB.Percentage(), PGB.Bar(marker='-', left=' |', right='| '), PGB.Counter(), '/{0:0d} Antennas '.format(len(data_info[apol]['labels'])), PGB.ETA()], maxval=len(data_info[apol]['labels'])).start()
for antind, antkey in enumerate(data_info[apol]['labels']):
typetag_pair = self.antenna_pair_to_typetag[(antkey,antkey)] # auto pair
shape_tuple = tuple(2*NP.asarray(self.gridu.shape))+(self.f.size,)
if autocorr_wts_cube[apol] is None:
autocorr_wts_cube[apol] = self.pairwise_typetag_crosswts_vuf[typetag_pair][apol].toarray().reshape(shape_tuple)[NP.newaxis,:,:,:] * data_info[apol]['twts'][:,antind,:][:,NP.newaxis,NP.newaxis,:] # nt x nv x nu x nchan
autocorr_data_cube[apol] = self.pairwise_typetag_crosswts_vuf[typetag_pair][apol].toarray().reshape(shape_tuple)[NP.newaxis,:,:,:] * data_info[apol]['twts'][:,antind,:][:,NP.newaxis,NP.newaxis,:] * data_info[apol]['data'][:,antind,:][:,NP.newaxis,NP.newaxis,:] # nt x nv x nu x nchan
else:
autocorr_wts_cube[apol] += self.pairwise_typetag_crosswts_vuf[typetag_pair][apol].toarray().reshape(shape_tuple)[NP.newaxis,:,:,:] * data_info[apol]['twts'][:,antind,:][:,NP.newaxis,NP.newaxis,:] # nt x nv x nu x nchan
autocorr_data_cube[apol] += self.pairwise_typetag_crosswts_vuf[typetag_pair][apol].toarray().reshape(shape_tuple)[NP.newaxis,:,:,:] * data_info[apol]['twts'][:,antind,:][:,NP.newaxis,NP.newaxis,:] * data_info[apol]['data'][:,antind,:][:,NP.newaxis,NP.newaxis,:] # nt x nv x nu x nchan
progress.update(antind+1)
progress.finish()
sum_wts = NP.sum(data_info[apol]['twts'], axis=1) # nt x 1
autocorr_wts_cube[apol] = NP.nan_to_num(autocorr_wts_cube[apol] / sum_wts[:,NP.newaxis,NP.newaxis,:]) # nt x nv x nu x nchan, nan_to_num() just in case there are NaN
autocorr_data_cube[apol] = NP.nan_to_num(autocorr_data_cube[apol] / sum_wts[:,NP.newaxis,NP.newaxis,:]) # nt x nv x nu x nchan, nan_to_num() just in case there are NaN
return (autocorr_wts_cube, autocorr_data_cube)
############################################################################
def makeCrossCorrWtsCube(self, pol=None, data=None, datapool='stack',
verbose=True):
"""
------------------------------------------------------------------------
Constructs the grid of zero-centered cross-correlation of antenna
aperture pairs using the gridding information determined for every
antenna. Flags are taken into account while constructing this grid
Inputs:
pol [String] The polarization to be gridded. Can be set to 'P1' or
'P2'. If set to None, gridding for all the polarizations is
performed. Default=None
datapool
[string] Specifies whether flags that come from data to be
used in determining the zero-centered cross-correlation come
from 'stack' (default), 'current', or 'avg'.
verbose [boolean] If True, prints diagnostic and progress messages.
If False (default), suppress printing such messages.
Outputs:
centered_crosscorr_wts_vuf is a dictionary with polarization keys
'P1' and 'P2. Under each key is a sparse matrix of size
(nv x nu) x nchan.
------------------------------------------------------------------------
"""
if pol is None:
pol = ['P1', 'P2']
pol = NP.unique(NP.asarray(pol))
if datapool not in ['stack', 'current', 'avg', 'custom']:
raise ValueError('Input datapool must be set to "stack" or "current"')
if not self.antenna_crosswts_set:
self.evalAllAntennaPairCorrWts()
centered_crosscorr_wts_cube = {p: None for p in ['P1', 'P2']}
for apol in pol:
if verbose:
print 'Gridding centered cross-correlation of aperture illumination for polarization {0} ...'.format(apol)
if apol not in ['P1', 'P2']:
raise ValueError('Invalid specification for input parameter pol')
for typetag_pair in self.pairwise_typetags:
if 'cross' in self.pairwise_typetags[typetag_pair]:
n_bl = len(self.pairwise_typetags[typetag_pair]['cross'])
if centered_crosscorr_wts_cube[apol] is None:
centered_crosscorr_wts_cube[apol] = n_bl * self.pairwise_typetag_crosswts_vuf[typetag_pair][apol]
else:
centered_crosscorr_wts_cube[apol] += n_bl * self.pairwise_typetag_crosswts_vuf[typetag_pair][apol]
return centered_crosscorr_wts_cube
############################################################################
def evalAntennaPairPBeam(self, typetag_pair=None, label_pair=None,
pad=0, skypos=None):
"""
------------------------------------------------------------------------
Evaluate power pattern response on sky of an antenna pair
Inputs:
typetag_pair
[dictionary] dictionary with two keys '1' and '2' denoting
the antenna typetag. At least one of them must be specified.
If one of them is not specified, it is assumed to be the
same as the other. Only one of the inputs typetag_pair or
label_pair must be set
label_pair [dictionary] dictionary with two keys '1' and '2' denoting
the antenna label. At least one of them must be specified.
If one of them is not specified, it is assumed to be the
same as the other. Only one of the inputs typetag_pair or
label_pair must be set
pad [integer] indicates the amount of padding before estimating
power pattern. Applicable only when skypos is set to None.
The output power pattern will be of size 2**pad-1 times the
size of the UV-grid along l- and m-axes. Value must
not be negative. Default=0 (implies no padding). pad=1
implies padding by factor 2 along u- and v-axes
skypos [numpy array] Positions on sky at which power pattern is
to be esimated. It is a 2- or 3-column numpy array in
direction cosine coordinates. It must be of size nsrc x 2
or nsrc x 3. If set to None (default), the power pattern is
estimated over a grid on the sky. If a numpy array is
specified, then power pattern at the given locations is
estimated.
Outputs:
pbinfo is a dictionary with the following keys and values:
'pb' [dictionary] Dictionary with keys 'P1' and 'P2' for
polarization. Under each key is a numpy array of estimated
power patterns. If skypos was set to None, the numpy array is
3D masked array of size nm x nl x nchan. The mask is based on
which parts of the grid are valid direction cosine coordinates
on the sky. If skypos was a numpy array denoting specific sky
locations, the value in this key is a 2D numpy array of size
nsrc x nchan
'llocs' [None or numpy array] If the power pattern estimated is a grid
(if input skypos was set to None), it contains the l-locations
of the grid on the sky. If input skypos was not set to None,
the value under this key is set to None
'mlocs' [None or numpy array] If the power pattern estimated is a grid
(if input skypos was set to None), it contains the m-locations
of the grid on the sky. If input skypos was not set to None,
the value under this key is set to None
------------------------------------------------------------------------
"""
if (typetag_pair is None) and (label_pair is None):
raise ValueError('One of the inputs typetag_pair or label_pair must be specified')
elif (typetag_pair is not None) and (label_pair is not None):
raise ValueError('Only one of the inputs typetag_pair or label_pair must be specified')
if typetag_pair is not None:
if ('1' not in typetag_pair) and ('2' not in typetag_pair):
raise KeyError('Required keys not found in input typetag_pair')
elif ('1' not in typetag_pair) and ('2' in typetag_pair):
typetag_pair['1'] = typetag_pair['2']
elif ('1' in typetag_pair) and ('2' not in typetag_pair):
typetag_pair['2'] = typetag_pair['1']
typetag_tuple = (typetag_pair['1'], typetag_pair['2'])
if typetag_tuple not in self.pairwise_typetags:
if typetag_tuple[::-1] not in self.pairwise_typetags:
raise KeyError('typetag pair not found in antenna cross weights')
else:
typetag_tuple = typetag_tuple[::-1]
if 'auto' in self.pairwise_typetags[typetag_tuple]:
label1, label2 = list(self.pairwise_typetags[typetag_tuple]['auto'])[0]
else:
label1, label2 = list(self.pairwise_typetags[typetag_tuple]['cross'])[0]
else:
if ('1' not in label_pair) and ('2' not in label_pair):
raise KeyError('Required keys not found in input label_pair')
elif ('1' not in label_pair) and ('2' in label_pair):
label_pair['1'] = label_pair['2']
elif ('1' in label_pair) and ('2' not in label_pair):
label_pair['2'] = label_pair['1']
label1 = label_pair['1']
label2 = label_pair['2']
label_tuple = (label1, label2)
if label_tuple not in self.antenna_pair_to_typetag:
if label_tuple[::-1] not in self.antenna_pair_to_typetag:
raise KeyError('label pair not found in antenna pairs')
else:
label_tuple = label_tuple[::-1]
label1, label2 = label_tuple
typetag_tuple = self.antenna_pair_to_typetag[label_tuple]
if typetag_tuple not in self.pairwise_typetag_crosswts_vuf:
self.evalAntennaPairCorrWts(label1, label2=label2)
centered_crosscorr_wts_vuf = self.pairwise_typetag_crosswts_vuf[typetag_tuple]
du = self.gridu[0,1] - self.gridu[0,0]
dv = self.gridv[1,0] - self.gridv[0,0]
ulocs = du*(NP.arange(2*self.gridu.shape[1])-self.gridu.shape[1])
vlocs = dv*(NP.arange(2*self.gridv.shape[0])-self.gridv.shape[0])
pol = ['P1', 'P2']
pbinfo = {'pb': {}}
for p in pol:
pb = evalApertureResponse(centered_crosscorr_wts_vuf[p], ulocs, vlocs, pad=pad, skypos=skypos)
pbinfo['pb'][p] = pb['pb']
pbinfo['llocs'] = pb['llocs']
pbinfo['mlocs'] = pb['mlocs']
return pbinfo
############################################################################
def quick_beam_synthesis(self, pol=None, keep_zero_spacing=True):
"""
------------------------------------------------------------------------
A quick generator of synthesized beam using antenna array field
illumination pattern using the center frequency. Not intended to be used
rigorously but rather for comparison purposes and making quick plots
Inputs:
pol [String] The polarization of the synthesized beam. Can be set
to 'P1' or 'P2'. If set to None, synthesized beam for all the
polarizations are generated. Default=None
keep_zero_spacing
[boolean] If set to True (default), keep the zero spacing in
uv-plane grid illumination and as a result the average value
of the synthesized beam could be non-zero. If False, the zero
spacing is forced to zero by removing the average value fo the
synthesized beam
Outputs:
Dictionary with the following keys and information:
'syn_beam' [numpy array] synthesized beam of size twice as that of the
antenna array grid. It is FFT-shifted to place the
origin at the center of the array. The peak value of the
synthesized beam is fixed at unity
'grid_power_illumination'
[numpy array] complex grid illumination obtained from
inverse fourier transform of the synthesized beam in
'syn_beam' and has size twice as that of the antenna
array grid. It is FFT-shifted to have the origin at the
center. The sum of this array is set to unity to match the
peak of the synthesized beam
'l' [numpy vector] x-values of the direction cosine grid
corresponding to x-axis (axis=1) of the synthesized beam
'm' [numpy vector] y-values of the direction cosine grid
corresponding to y-axis (axis=0) of the synthesized beam
------------------------------------------------------------------------
"""
if not self.grid_ready:
raise ValueError('Need to perform gridding of the antenna array before an equivalent UV grid can be simulated')
if pol is None:
pol = ['P1', 'P2']
elif isinstance(pol, str):
if pol in ['P1', 'P2']:
pol = [pol]
else:
raise ValueError('Invalid polarization specified')
elif isinstance(pol, list):
p = [apol for apol in pol if apol in ['P1', 'P2']]
if len(p) == 0:
raise ValueError('Invalid polarization specified')
pol = p
else:
raise TypeError('Input keyword pol must be string, list or set to None')
pol = sorted(pol)
for apol in pol:
if self.grid_illumination[apol] is None:
raise ValueError('Grid illumination for the specified polarization is not determined yet. Must use make_grid_cube()')
chan = NP.argmin(NP.abs(self.f - self.f0))
grid_field_illumination = NP.empty(self.gridu.shape+(len(pol),), dtype=NP.complex)
for pind, apol in enumerate(pol):
grid_field_illumination[:,:,pind] = self.grid_illumination[apol][:,:,chan]
syn_beam = NP.fft.fft2(grid_field_illumination, s=[4*self.gridu.shape[0], 4*self.gridv.shape[1]], axes=(0,1))
syn_beam = NP.abs(syn_beam)**2
if not keep_zero_spacing:
dclevel = NP.sum(syn_beam, axis=(0,1), keepdims=True) / (1.0*syn_beam.size/len(pol))
syn_beam = syn_beam - dclevel
syn_beam /= syn_beam.max() # Normalize to get unit peak for PSF
syn_beam_in_uv = NP.fft.ifft2(syn_beam, axes=(0,1)) # Inverse FT
du = self.gridu[0,1] - self.gridu[0,0]
dv = self.gridv[1,0] - self.gridv[0,0]
# if not keep_zero_spacing: # Filter out the interferometer aperture kernel footprint centered on zero
# l4 = DSP.spectax(4*self.gridu.shape[1], resolution=du, shift=False)
# m4 = DSP.spectax(4*self.gridv.shape[0], resolution=dv, shift=False)
# u4 = DSP.spectax(l4.size, resolution=l4[1]-l4[0], shift=False)
# v4 = DSP.spectax(m4.size, resolution=m4[1]-m4[0], shift=False)
# gridu4, gridv4 = NP.meshgrid(u4,v4)
# gridxy4 = NP.hstack((gridu4.reshape(-1,1), gridv4.reshape(-1,1))) * FCNST.c/self.f[chan]
# # assume identical antennas
# aperture = self.antennas.itervalues().next().aperture
# zero_vind = []
# zero_uind = []
# zero_pind = []
# for pi,apol in enumerate(pol):
# if aperture.kernel_type[apol] == 'func':
# if aperture.shape[apol] == 'circular':
# z_ind = NP.where(NP.sqrt(NP.sum(gridxy4**2, axis=1)) <= 2*aperture.rmax[apol])[0]
# else:
# rotang = aperture.rotangle[apol]
# rotmat = NP.asarray([[NP.cos(-rotang), -NP.sin(-rotang)],
# [NP.sin(-rotang), NP.cos(-rotang)]])
# gridxy4 = NP.dot(gridxy4, rotmat.T)
# if aperture.shape[apol] == 'square':
# z_ind = NP.where(NP.logical_and(NP.abs(gridxy4[:,0]) <= 2*aperture.xmax[apol], NP.abs(gridxy4[:,1]) <= 2*aperture.xmax[apol]))[0]
# else:
# z_ind = NP.where(NP.logical_and(NP.abs(gridxy4[:,0]) <= 2*aperture.xmax[apol], NP.abs(gridxy4[:,1]) <= 2*aperture.ymax[apol]))[0]
# z_vind, z_uind = NP.unravel_index(z_ind, gridu4.shape)
# zero_vind += z_vind.tolist()
# zero_uind += z_uind.tolist()
# zero_pind += [pi]*z_vind.size
# zero_vind = NP.asarray(zero_vind).ravel()
# zero_uind = NP.asarray(zero_uind).ravel()
# zero_pind = NP.asarray(zero_pind).ravel()
# syn_beam_in_uv[(zero_vind, zero_uind, zero_pind)] = 0.0
# syn_beam = NP.fft.fft2(syn_beam_in_uv, axes=(0,1)) # FT
# if NP.abs(syn_beam.imag).max() > 1e-10:
# raise ValueError('Synthesized beam after zero spacing aperture removal has significant imaginary component')
# else:
# syn_beam = syn_beam.real
# norm_factor = 1.0 / syn_beam.max()
# syn_beam *= norm_factor # Normalize to get unit peak for PSF
# syn_beam_in_uv *= norm_factor # Normalize to get unit peak for PSF
# shift the array to be centered
syn_beam_in_uv = NP.fft.ifftshift(syn_beam_in_uv, axes=(0,1)) # Shift array to be centered
# Discard pads at either end and select only the central values of twice the original size
syn_beam_in_uv = syn_beam_in_uv[grid_field_illumination.shape[0]:3*grid_field_illumination.shape[0],grid_field_illumination.shape[1]:3*grid_field_illumination.shape[1],:]
syn_beam = NP.fft.fftshift(syn_beam[::2,::2,:], axes=(0,1)) # Downsample by factor 2 to get native resolution and shift to be centered
l = DSP.spectax(2*self.gridu.shape[1], resolution=du, shift=True)
m = DSP.spectax(2*self.gridv.shape[0], resolution=dv, shift=True)
return {'syn_beam': syn_beam, 'grid_power_illumination': syn_beam_in_uv, 'l': l, 'm': m}
############################################################################
def quick_beam_synthesis_new(self, pol=None, keep_zero_spacing=True):
"""
------------------------------------------------------------------------
A quick generator of synthesized beam using antenna array field
illumination pattern using the center frequency. Not intended to be used
rigorously but rather for comparison purposes and making quick plots
Inputs:
pol [String] The polarization of the synthesized beam. Can be set
to 'P1' or 'P2'. If set to None, synthesized beam for all the
polarizations are generated. Default=None
keep_zero_spacing
[boolean] If set to True (default), keep the zero spacing in
uv-plane grid illumination and as a result the average value
of the synthesized beam could be non-zero. If False, the zero
spacing is forced to zero by removing the average value fo the
synthesized beam
Outputs:
Dictionary with the following keys and information:
'syn_beam' [numpy array] synthesized beam of size twice as that of the
antenna array grid. It is FFT-shifted to place the
origin at the center of the array. The peak value of the
synthesized beam is fixed at unity
'grid_power_illumination'
[numpy array] complex grid illumination obtained from
inverse fourier transform of the synthesized beam in
'syn_beam' and has size twice as that of the antenna
array grid. It is FFT-shifted to have the origin at the
center. The sum of this array is set to unity to match the
peak of the synthesized beam
'l' [numpy vector] x-values of the direction cosine grid
corresponding to x-axis (axis=1) of the synthesized beam
'm' [numpy vector] y-values of the direction cosine grid
corresponding to y-axis (axis=0) of the synthesized beam
------------------------------------------------------------------------
"""
if not self.grid_ready:
raise ValueError('Need to perform gridding of the antenna array before an equivalent UV grid can be simulated')
if pol is None:
pol = ['P1', 'P2']
elif isinstance(pol, str):
if pol in ['P1', 'P2']:
pol = [pol]
else:
raise ValueError('Invalid polarization specified')
elif isinstance(pol, list):
p = [apol for apol in pol if apol in ['P1', 'P2']]
if len(p) == 0:
raise ValueError('Invalid polarization specified')
pol = p
else:
raise TypeError('Input keyword pol must be string, list or set to None')
pol = sorted(pol)
for apol in pol:
if self.grid_illumination[apol] is None:
raise ValueError('Grid illumination for the specified polarization is not determined yet. Must use make_grid_cube()')
chan = NP.argmin(NP.abs(self.f - self.f0))
grid_field_illumination = NP.empty(self.gridu.shape+(len(pol),), dtype=NP.complex)
for pind, apol in enumerate(pol):
grid_field_illumination[:,:,pind] = self.grid_illumination[apol][:,:,chan]
syn_beam = NP.fft.fft2(grid_field_illumination, s=[4*self.gridu.shape[0], 4*self.gridv.shape[1]], axes=(0,1))
syn_beam = NP.abs(syn_beam)**2
# if not keep_zero_spacing:
# dclevel = NP.sum(syn_beam, axis=(0,1), keepdims=True) / (1.0*syn_beam.size/len(pol))
# syn_beam = syn_beam - dclevel
syn_beam /= syn_beam.max() # Normalize to get unit peak for PSF
syn_beam_in_uv = NP.fft.ifft2(syn_beam, axes=(0,1)) # Inverse FT
norm_factor = 1.0
du = self.gridu[0,1] - self.gridu[0,0]
dv = self.gridv[1,0] - self.gridv[0,0]
if not keep_zero_spacing: # Filter out the interferometer aperture kernel footprint centered on zero
l4 = DSP.spectax(4*self.gridu.shape[1], resolution=du, shift=False)
m4 = DSP.spectax(4*self.gridv.shape[0], resolution=dv, shift=False)
u4 = DSP.spectax(l4.size, resolution=l4[1]-l4[0], shift=False)
v4 = DSP.spectax(m4.size, resolution=m4[1]-m4[0], shift=False)
gridu4, gridv4 = NP.meshgrid(u4,v4)
gridxy4 = NP.hstack((gridu4.reshape(-1,1), gridv4.reshape(-1,1))) * FCNST.c/self.f[chan]
# assume identical antennas
aperture = self.antennas.itervalues().next().aperture
zero_vind = []
zero_uind = []
zero_pind = []
for pi,apol in enumerate(pol):
if aperture.kernel_type[apol] == 'func':
if aperture.shape[apol] == 'circular':
z_ind = NP.where(NP.sqrt(NP.sum(gridxy4**2, axis=1)) <= 2*aperture.rmax[apol])[0]
else:
rotang = aperture.rotangle[apol]
rotmat = NP.asarray([[NP.cos(-rotang), -NP.sin(-rotang)],
[NP.sin(-rotang), NP.cos(-rotang)]])
gridxy4 = NP.dot(gridxy4, rotmat.T)
if aperture.shape[apol] == 'square':
z_ind = NP.where(NP.logical_and(NP.abs(gridxy4[:,0]) <= 2*aperture.xmax[apol], NP.abs(gridxy4[:,1]) <= 2*aperture.xmax[apol]))[0]
else:
z_ind = NP.where(NP.logical_and(NP.abs(gridxy4[:,0]) <= 2*aperture.xmax[apol], NP.abs(gridxy4[:,1]) <= 2*aperture.ymax[apol]))[0]
z_vind, z_uind = NP.unravel_index(z_ind, gridu4.shape)
zero_vind += z_vind.tolist()
zero_uind += z_uind.tolist()
zero_pind += [pi]*z_vind.size
zero_vind = NP.asarray(zero_vind).ravel()
zero_uind = NP.asarray(zero_uind).ravel()
zero_pind = NP.asarray(zero_pind).ravel()
syn_beam_in_uv[(zero_vind, zero_uind, zero_pind)] = 0.0
syn_beam = NP.fft.fft2(syn_beam_in_uv, axes=(0,1)) # FT
if NP.abs(syn_beam.imag).max() > 1e-10:
raise ValueError('Synthesized beam after zero spacing aperture removal has significant imaginary component')
else:
syn_beam = syn_beam.real
norm_factor = 1.0 / syn_beam.max()
syn_beam *= norm_factor # Normalize to get unit peak for PSF
syn_beam_in_uv *= norm_factor # Normalize to get unit peak for PSF
# shift the array to be centered
syn_beam_in_uv = NP.fft.ifftshift(syn_beam_in_uv, axes=(0,1)) # Shift array to be centered
# Discard pads at either end and select only the central values of twice the original size
syn_beam_in_uv = syn_beam_in_uv[grid_field_illumination.shape[0]:3*grid_field_illumination.shape[0],grid_field_illumination.shape[1]:3*grid_field_illumination.shape[1],:]
syn_beam = NP.fft.fftshift(syn_beam[::2,::2,:], axes=(0,1)) # Downsample by factor 2 to get native resolution and shift to be centered
l = DSP.spectax(2*self.gridu.shape[1], resolution=du, shift=True)
m = DSP.spectax(2*self.gridv.shape[0], resolution=dv, shift=True)
return {'syn_beam': syn_beam, 'grid_power_illumination': syn_beam_in_uv, 'l': l, 'm': m}
############################################################################
def update_flags(self, dictflags=None, stack=True, verify=False):
"""
------------------------------------------------------------------------
Updates all flags in the antenna array followed by any flags that
need overriding through inputs of specific flag information
Inputs:
dictflags [dictionary] contains flag information overriding after
default flag updates are determined. Antenna based flags are
given as further dictionaries with each under under a key
which is the same as the antenna label. Flags for each
antenna are specified as a dictionary holding boolean flags
for each of the two polarizations which are stored under
keys 'P1' and 'P2'. An absent key just means it is not a
part of the update. Flag information under each antenna must
be of same type as input parameter flags in member function
update_flags() of class PolInfo
stack [boolean] If True (default), appends the updated flag to the
end of the stack of flags as a function of timestamp. If
False, updates the last flag in the stack with the updated
flag and does not append
verify [boolean] If True, verify and update the flags, if necessary.
Electric fields are checked for NaN values and if found, the
flag in the corresponding polarization is set to True.
Default=False.
------------------------------------------------------------------------
"""
for label in self.antennas:
self.antennas[label].update_flags(stack=stack, verify=verify)
if dictflags is not None: # Performs flag overriding. Use stack=False
if not isinstance(dictflags, dict):
raise TypeError('Input parameter dictflags must be a dictionary')
for label in dictflags:
if label in self.antennas:
self.antennas[label].update_flags(flags=dictflags[label], stack=False, verify=True)
############################################################################
def update(self, updates=None, parallel=False, nproc=None, verbose=False):
"""
------------------------------------------------------------------------
Updates the antenna array instance with newer attribute values. Can also
be used to add and/or remove antennas with/without affecting the
existing grid.
Inputs:
updates [Dictionary] Consists of information updates under the
following principal keys:
'antenna_array': Consists of updates for the AntennaArray
instance. This is a dictionary which consists of
the following keys:
'timestamp' Unique identifier of the time
series. It is optional to set this
to a scalar. If not given, no
change is made to the existing
timestamp attribute
'do_grid' [boolean] If set to True, create
or recreate a grid. To be
specified when the antenna
locations are updated.
'antennas': Holds a list of dictionaries consisting of
updates for individual antennas. Each element
in the list contains update for one antenna.
For each of these dictionaries, one of the keys
is 'label' which indicates an antenna label. If
absent, the code execution stops by throwing an
exception. The other optional keys and the
information they hold are listed below:
'action' [String scalar] Indicates the type
of update operation. 'add' adds
the Antenna instance to the
AntennaArray instance. 'remove'
removes the antenna from the
antenna array instance. 'modify'
modifies the antenna attributes in
the antenna array instance. This
key has to be set. No default.
'grid_action' [Boolean] If set to True, will
apply the grdding operations
(grid(), grid_convolve(), and
grid_unconvolve()) appropriately
according to the value of the
'action' key. If set to None or
False, gridding effects will
remain unchanged. Default=None
(=False).
'antenna' [instance of class Antenna]
Updated Antenna class instance.
Can work for action key 'remove'
even if not set (=None) or set to
an empty string '' as long as
'label' key is specified.
'gridpol' [Optional. String scalar]
Initiates the specified action on
polarization 'P1' or 'P2'. Can be
set to 'P1' or 'P2'. If not
provided (=None), then the
specified action applies to both
polarizations. Default = None.
'Et' [Optional. Dictionary] Complex
Electric field time series under
two polarizations which are under
keys 'P1' and 'P2'. Is used only
if set and if 'action' key value
is set to 'modify'.
Default = None.
'Ef' [Optional. Dictionary] Complex
Electric field spectra under
two polarizations which are under
keys 'P1' and 'P2'. Is used only
if set and if 'action' key value
is set to 'modify'.
Default = None.
'stack' [boolean] If True (default),
appends the updated flag and data
to the end of the stack as a
function of timestamp. If False,
updates the last flag and data in
the stack and does not append
't' [Optional. Numpy array] Time axis
of the time series. Is used only
if set and if 'action' key value
is set to 'modify'. Default=None.
'timestamp' [Optional. Scalar] Unique
identifier of the time series. Is
used only if set and if 'action'
key value is set to 'modify'.
Default = None.
'location' [Optional. instance of GEOM.Point
class]
Antenna location in the local ENU
coordinate system. Used only if
set and if 'action' key value is
set to 'modify'. Default = None.
'aperture' [instance of class
APR.Aperture] aperture
information for the antenna. Read
docstring of class
Aperture for details
'wtsinfo' [Optional. Dictionary]
See description in Antenna class
member function update(). Is used
only if set and if 'action' key
value is set to 'modify'.
Default = None.
'flags' [Optional. Dictionary] holds
boolean flags for each of the 2
polarizations which are stored
under keys 'P1' and 'P2'.
Default=None means no updates for
flags. If True, that polarization
will be flagged. If not set
(=None), the previous or default
flag status will continue to
apply. If set to False, the
antenna status will be updated to
become unflagged.
'gridfunc_freq'
[Optional. String scalar] Read the
description of inputs to Antenna
class member function update(). If
set to None (not provided), this
attribute is determined based on
the size of wtspos under each
polarization. It is applicable
only when 'action' key is set to
'modify'. Default = None.
'delaydict' [Dictionary] contains information
on delay compensation to be
applied to the fourier transformed
electric fields under each
polarization which are stored
under keys 'P1' and 'P2'.
Default=None (no delay
compensation to be applied). Refer
to the docstring of member
function delay_compensation() of
class PolInfo for more details.
'ref_freq' [Optional. Scalar] Positive value
(in Hz) of reference frequency
(used if gridfunc_freq is set to
'scale') at which wtspos in
wtsinfo are provided. If set to
None, the reference frequency
already set in antenna array
instance remains unchanged.
Default = None.
'pol_type' [Optional. String scalar] 'Linear'
or 'Circular'. Used only when
action key is set to 'modify'. If
not provided, then the previous
value remains in effect.
Default = None.
'norm_wts' [Optional. Boolean] Default=False.
If set to True, the gridded
weights are divided by the sum of
weights so that the gridded
weights add up to unity. This is
used only when grid_action keyword
is set when action keyword is set
to 'add' or 'modify'
'gridmethod' [Optional. String] Indicates
gridding method. It accepts the
following values 'NN' (nearest
neighbour), 'BL' (Bi-linear
interpolation), and'CS' (Cubic
Spline interpolation).
Default='NN'
'distNN' [Optional. Scalar] Indicates the
upper bound on distance for a
nearest neighbour search if the
value of 'gridmethod' is set to
'NN'. The units are of physical
distance, the same as what is
used for antenna locations.
Default = NP.inf
'maxmatch' [scalar] A positive value
indicating maximum number of input
locations in the antenna grid to
be assigned. Default = None. If
set to None, all the antenna array
grid elements specified are
assigned values for each antenna.
For instance, to have only one
antenna array grid element to be
populated per antenna, use
maxmatch=1.
'tol' [scalar] If set, only lookup data
with abs(val) > tol will be
considered for nearest neighbour
lookup. Default = None implies
all lookup values will be
considered for nearest neighbour
determination. tol is to be
interpreted as a minimum value
considered as significant in the
lookup table.
parallel [boolean] specifies if parallelization is to be invoked.
False (default) means only serial processing
nproc [integer] specifies number of independent processes to spawn.
Default = None, means automatically determines the number of
process cores in the system and use one less than that to
avoid locking the system for other processes. Applies only
if input parameter 'parallel' (see above) is set to True.
If nproc is set to a value more than the number of process
cores in the system, it will be reset to number of process
cores in the system minus one to avoid locking the system out
for other processes
verbose [Boolean] Default = False. If set to True, prints some
diagnotic or progress messages.
------------------------------------------------------------------------
"""
if updates is not None:
if not isinstance(updates, dict):
raise TypeError('Input parameter updates must be a dictionary')
if 'antennas' in updates: # contains updates at level of individual antennas
if not isinstance(updates['antennas'], list):
updates['antennas'] = [updates['antennas']]
if parallel:
list_of_antenna_updates = []
list_of_antennas = []
for dictitem in updates['antennas']:
if not isinstance(dictitem, dict):
raise TypeError('Updates to {0} instance should be provided in the form of a list of dictionaries.'.format(self.__class__.__name__))
elif 'label' not in dictitem:
raise KeyError('No antenna label specified in the dictionary item to be updated.')
if 'action' not in dictitem:
raise KeyError('No action specified for update. Action key should be set to "add", "remove" or "modify".')
elif dictitem['action'] == 'add':
if dictitem['label'] in self.antennas:
if verbose:
print 'Antenna {0} for adding already exists in current instance of {1}. Skipping over to the next item to be updated.'.format(dictitem['label'], self.__class__.__name__)
else:
if verbose:
print 'Adding antenna {0}...'.format(dictitem['label'])
self.add_antennas(dictitem['antenna'])
if 'grid_action' in dictitem:
self.grid_convolve(pol=dictitem['gridpol'], ants=dictitem['antenna'], unconvolve_existing=False)
elif dictitem['action'] == 'remove':
if dictitem['label'] not in self.antennas:
if verbose:
print 'Antenna {0} for removal not found in current instance of {1}. Skipping over to the next item to be updated.'.format(dictitem['label'], self.__class__.__name__)
else:
if verbose:
print 'Removing antenna {0}...'.format(dictitem['label'])
if 'grid_action' in dictitem:
self.grid_unconvolve(dictitem['label'], dictitem['gridpol'])
self.remove_antennas(dictitem['label'])
elif dictitem['action'] == 'modify':
if dictitem['label'] not in self.antennas:
if verbose:
print 'Antenna {0} for modification not found in current instance of {1}. Skipping over to the next item to be updated.'.format(dictitem['label'], self.__class__.__name__)
else:
if verbose:
print 'Modifying antenna {0}...'.format(dictitem['label'])
if 'Ef' not in dictitem: dictitem['Ef']=None
if 'Et' not in dictitem: dictitem['Et']=None
if 't' not in dictitem: dictitem['t']=None
if 'timestamp' not in dictitem: dictitem['timestamp']=None
if 'location' not in dictitem: dictitem['location']=None
if 'wtsinfo' not in dictitem: dictitem['wtsinfo']=None
if 'flags' not in dictitem: dictitem['flags']=None
if 'stack' not in dictitem: dictitem['stack']=True
if 'gridfunc_freq' not in dictitem: dictitem['gridfunc_freq']=None
if 'ref_freq' not in dictitem: dictitem['ref_freq']=None
if 'pol_type' not in dictitem: dictitem['pol_type']=None
if 'norm_wts' not in dictitem: dictitem['norm_wts']=False
if 'gridmethod' not in dictitem: dictitem['gridmethod']='NN'
if 'distNN' not in dictitem: dictitem['distNN']=NP.inf
if 'maxmatch' not in dictitem: dictitem['maxmatch']=None
if 'tol' not in dictitem: dictitem['tol']=None
if 'delaydict' not in dictitem: dictitem['delaydict']=None
if 'aperture' not in dictitem: dictitem['aperture']=None
if not parallel:
self.antennas[dictitem['label']].update(dictitem, verbose)
else:
list_of_antennas += [self.antennas[dictitem['label']]]
list_of_antenna_updates += [dictitem]
if 'grid_action' in dictitem:
self.grid_convolve(pol=dictitem['gridpol'], ants=dictitem['antenna'], unconvolve_existing=True, normalize=dictitem['norm_wts'], method=dictitem['gridmethod'], distNN=dictitem['distNN'], tol=dictitem['tol'], maxmatch=dictitem['maxmatch'])
else:
raise ValueError('Update action should be set to "add", "remove" or "modify".')
if parallel:
if nproc is None:
nproc = max(MP.cpu_count()-1, 1)
else:
nproc = min(nproc, max(MP.cpu_count()-1, 1))
pool = MP.Pool(processes=nproc)
updated_antennas = pool.map(unwrap_antenna_update, IT.izip(list_of_antennas, list_of_antenna_updates))
pool.close()
pool.join()
# Necessary to make the returned and updated antennas current, otherwise they stay unrelated
for antenna in updated_antennas:
self.antennas[antenna.label] = antenna
del updated_antennas
if 'antenna_array' in updates: # contains updates at 'antenna array' level
if not isinstance(updates['antenna_array'], dict):
raise TypeError('Input parameter in updates for antenna array must be a dictionary with key "antenna_array"')
if 'timestamp' in updates['antenna_array']:
self.timestamp = updates['antenna_array']['timestamp']
self.timestamps += [copy.deepcopy(self.timestamp)] # Stacks new timestamp
if 'do_grid' in updates['antenna_array']:
if isinstance(updates['antenna_array']['do_grid'], boolean):
self.grid()
else:
raise TypeError('Value in key "do_grid" inside key "antenna_array" of input dictionary updates must be boolean.')
self.t = self.antennas.itervalues().next().t # Update time axis
self.f = self.antennas.itervalues().next().f # Update frequency axis
self.update_flags(stack=False, verify=True) # Refreshes current flags, no stacking
################################################################################
|
var searchData=
[
['actors',['Actors',['../namespacedroid_1_1_runtime_1_1_prototyping_1_1_actors.html',1,'droid::Runtime::Prototyping']]],
['actuators',['Actuators',['../namespacedroid_1_1_runtime_1_1_prototyping_1_1_actuators.html',1,'droid::Runtime::Prototyping']]],
['boundingbox',['BoundingBox',['../namespacedroid_1_1_runtime_1_1_prototyping_1_1_sensors_1_1_bounding_box.html',1,'droid.Runtime.Prototyping.Sensors.BoundingBox'],['../namespacedroid_1_1_runtime_1_1_utilities_1_1_enums_1_1_bounding_box.html',1,'droid.Runtime.Utilities.Enums.BoundingBox']]],
['boundingboxes',['BoundingBoxes',['../namespacedroid_1_1_runtime_1_1_utilities_1_1_game_objects_1_1_bounding_boxes.html',1,'droid::Runtime::Utilities::GameObjects']]],
['camera',['Camera',['../namespacedroid_1_1_runtime_1_1_prototyping_1_1_sensors_1_1_camera.html',1,'droid::Runtime::Prototyping::Sensors']]],
['camera360',['Camera360',['../namespacedroid_1_1_runtime_1_1_utilities_1_1_game_objects_1_1_neodroid_camera_1_1_experimental_1_1_camera360.html',1,'droid::Runtime::Utilities::GameObjects::NeodroidCamera::Experimental']]],
['canvas',['Canvas',['../namespacedroid_1_1_runtime_1_1_prototyping_1_1_displayers_1_1_canvas.html',1,'droid::Runtime::Prototyping::Displayers']]],
['cells',['Cells',['../namespacedroid_1_1_runtime_1_1_prototyping_1_1_displayers_1_1_cells.html',1,'droid::Runtime::Prototyping::Displayers']]],
['childsensors',['ChildSensors',['../namespacedroid_1_1_runtime_1_1_utilities_1_1_game_objects_1_1_child_sensors.html',1,'droid::Runtime::Utilities::GameObjects']]],
['configurables',['Configurables',['../namespacedroid_1_1_runtime_1_1_prototyping_1_1_configurables.html',1,'droid::Runtime::Prototyping']]],
['deprecated',['Deprecated',['../namespacedroid_1_1_runtime_1_1_messaging_1_1_f_b_s_1_1_deprecated.html',1,'droid.Runtime.Messaging.FBS.Deprecated'],['../namespacedroid_1_1_runtime_1_1_prototyping_1_1_sensors_1_1_camera_1_1_deprecated.html',1,'droid.Runtime.Prototyping.Sensors.Camera.Deprecated']]],
['displayables',['Displayables',['../namespacedroid_1_1_runtime_1_1_messaging_1_1_messages_1_1_displayables.html',1,'droid::Runtime::Messaging::Messages']]],
['displayers',['Displayers',['../namespacedroid_1_1_runtime_1_1_prototyping_1_1_displayers.html',1,'droid::Runtime::Prototyping']]],
['drawing',['Drawing',['../namespacedroid_1_1_runtime_1_1_utilities_1_1_misc_1_1_drawing.html',1,'droid::Runtime::Utilities::Misc']]],
['droid',['droid',['../namespacedroid.html',1,'droid'],['../namespacedroid_1_1_runtime_1_1_utilities_1_1_game_objects_1_1_status_displayer_1_1_event_recipients_1_1droid.html',1,'droid.Runtime.Utilities.GameObjects.StatusDisplayer.EventRecipients.droid']]],
['enums',['Enums',['../namespacedroid_1_1_runtime_1_1_utilities_1_1_enums.html',1,'droid::Runtime::Utilities']]],
['environments',['Environments',['../namespacedroid_1_1_runtime_1_1_environments.html',1,'droid::Runtime']]],
['evaluation',['Evaluation',['../namespacedroid_1_1_runtime_1_1_prototyping_1_1_evaluation.html',1,'droid::Runtime::Prototyping']]],
['eventrecipients',['EventRecipients',['../namespacedroid_1_1_runtime_1_1_utilities_1_1_game_objects_1_1_status_displayer_1_1_event_recipients.html',1,'droid::Runtime::Utilities::GameObjects::StatusDisplayer']]],
['experimental',['Experimental',['../namespacedroid_1_1_runtime_1_1_environments_1_1_experimental.html',1,'droid.Runtime.Environments.Experimental'],['../namespacedroid_1_1_runtime_1_1_managers_1_1_experimental.html',1,'droid.Runtime.Managers.Experimental'],['../namespacedroid_1_1_runtime_1_1_messaging_1_1_experimental.html',1,'droid.Runtime.Messaging.Experimental'],['../namespacedroid_1_1_runtime_1_1_prototyping_1_1_configurables_1_1_experimental.html',1,'droid.Runtime.Prototyping.Configurables.Experimental'],['../namespacedroid_1_1_runtime_1_1_prototyping_1_1_sensors_1_1_experimental.html',1,'droid.Runtime.Prototyping.Sensors.Experimental'],['../namespacedroid_1_1_runtime_1_1_prototyping_1_1_sensors_1_1_rays_1_1_experimental.html',1,'droid.Runtime.Prototyping.Sensors.Rays.Experimental'],['../namespacedroid_1_1_runtime_1_1_utilities_1_1_game_objects_1_1_bounding_boxes_1_1_experimental.html',1,'droid.Runtime.Utilities.GameObjects.BoundingBoxes.Experimental'],['../namespacedroid_1_1_runtime_1_1_utilities_1_1_game_objects_1_1_neodroid_camera_1_1_experimental.html',1,'droid.Runtime.Utilities.GameObjects.NeodroidCamera.Experimental']]],
['extensions',['Extensions',['../namespacedroid_1_1_runtime_1_1_utilities_1_1_misc_1_1_extensions.html',1,'droid::Runtime::Utilities::Misc']]],
['fbs',['FBS',['../namespacedroid_1_1_runtime_1_1_messaging_1_1_f_b_s.html',1,'droid::Runtime::Messaging']]],
['gameobjects',['GameObjects',['../namespacedroid_1_1_runtime_1_1_utilities_1_1_game_objects.html',1,'droid::Runtime::Utilities']]],
['grasping',['Grasping',['../namespacedroid_1_1_runtime_1_1_utilities_1_1_misc_1_1_grasping.html',1,'droid::Runtime::Utilities::Misc']]],
['grid',['Grid',['../namespacedroid_1_1_runtime_1_1_prototyping_1_1_sensors_1_1_grid.html',1,'droid.Runtime.Prototyping.Sensors.Grid'],['../namespacedroid_1_1_runtime_1_1_utilities_1_1_misc_1_1_grid.html',1,'droid.Runtime.Utilities.Misc.Grid']]],
['gridworld',['GridWorld',['../namespacedroid_1_1_runtime_1_1_prototyping_1_1_displayers_1_1_grid_world.html',1,'droid::Runtime::Prototyping::Displayers']]],
['interfaces',['Interfaces',['../namespacedroid_1_1_runtime_1_1_interfaces.html',1,'droid::Runtime']]],
['internalreactions',['InternalReactions',['../namespacedroid_1_1_runtime_1_1_internal_reactions.html',1,'droid::Runtime']]],
['internals',['Internals',['../namespacedroid_1_1_runtime_1_1_prototyping_1_1_internals.html',1,'droid::Runtime::Prototyping']]],
['managers',['Managers',['../namespacedroid_1_1_runtime_1_1_managers.html',1,'droid::Runtime']]],
['messages',['Messages',['../namespacedroid_1_1_runtime_1_1_messaging_1_1_messages.html',1,'droid::Runtime::Messaging']]],
['messaging',['Messaging',['../namespacedroid_1_1_runtime_1_1_messaging.html',1,'droid::Runtime']]],
['misc',['Misc',['../namespacedroid_1_1_runtime_1_1_utilities_1_1_misc.html',1,'droid::Runtime::Utilities']]],
['neodroid',['Neodroid',['../namespacedroid_1_1_runtime_1_1_utilities_1_1_game_objects_1_1_status_displayer_1_1_event_recipients_1_1droid_1_1_neodroid.html',1,'droid::Runtime::Utilities::GameObjects::StatusDisplayer::EventRecipients::droid']]],
['neodroidcamera',['NeodroidCamera',['../namespacedroid_1_1_runtime_1_1_utilities_1_1_game_objects_1_1_neodroid_camera.html',1,'droid::Runtime::Utilities::GameObjects']]],
['obsolete',['Obsolete',['../namespacedroid_1_1_runtime_1_1_utilities_1_1_game_objects_1_1_neodroid_camera_1_1_segmentation_1_1_obsolete.html',1,'droid::Runtime::Utilities::GameObjects::NeodroidCamera::Segmentation']]],
['occupancy',['Occupancy',['../namespacedroid_1_1_runtime_1_1_prototyping_1_1_sensors_1_1_occupancy.html',1,'droid::Runtime::Prototyping::Sensors']]],
['orientation',['Orientation',['../namespacedroid_1_1_runtime_1_1_utilities_1_1_misc_1_1_orientation.html',1,'droid::Runtime::Utilities::Misc']]],
['particles',['Particles',['../namespacedroid_1_1_runtime_1_1_prototyping_1_1_actuators_1_1_particles.html',1,'droid::Runtime::Prototyping::Actuators']]],
['pb',['PB',['../namespacedroid_1_1_runtime_1_1_messaging_1_1_experimental_1_1_p_b.html',1,'droid::Runtime::Messaging::Experimental']]],
['plotting',['Plotting',['../namespacedroid_1_1_runtime_1_1_utilities_1_1_game_objects_1_1_plotting.html',1,'droid::Runtime::Utilities::GameObjects']]],
['procedural',['Procedural',['../namespacedroid_1_1_runtime_1_1_utilities_1_1_misc_1_1_procedural.html',1,'droid::Runtime::Utilities::Misc']]],
['prototyping',['Prototyping',['../namespacedroid_1_1_runtime_1_1_prototyping.html',1,'droid::Runtime']]],
['rays',['Rays',['../namespacedroid_1_1_runtime_1_1_prototyping_1_1_sensors_1_1_rays.html',1,'droid::Runtime::Prototyping::Sensors']]],
['rigidbody',['Rigidbody',['../namespacedroid_1_1_runtime_1_1_prototyping_1_1_sensors_1_1_rigidbody.html',1,'droid::Runtime::Prototyping::Sensors']]],
['runtime',['Runtime',['../namespacedroid_1_1_runtime.html',1,'droid']]],
['sampling',['Sampling',['../namespacedroid_1_1_runtime_1_1_utilities_1_1_sampling.html',1,'droid::Runtime::Utilities']]],
['scatterplots',['ScatterPlots',['../namespacedroid_1_1_runtime_1_1_prototyping_1_1_displayers_1_1_scatter_plots.html',1,'droid::Runtime::Prototyping::Displayers']]],
['scriptableobjects',['ScriptableObjects',['../namespacedroid_1_1_runtime_1_1_utilities_1_1_scriptable_objects.html',1,'droid::Runtime::Utilities']]],
['searchableenum',['SearchableEnum',['../namespacedroid_1_1_runtime_1_1_utilities_1_1_misc_1_1_searchable_enum.html',1,'droid::Runtime::Utilities::Misc']]],
['segmentation',['Segmentation',['../namespacedroid_1_1_runtime_1_1_prototyping_1_1_sensors_1_1_camera_1_1_deprecated_1_1_segmentation.html',1,'droid.Runtime.Prototyping.Sensors.Camera.Deprecated.Segmentation'],['../namespacedroid_1_1_runtime_1_1_utilities_1_1_game_objects_1_1_neodroid_camera_1_1_segmentation.html',1,'droid.Runtime.Utilities.GameObjects.NeodroidCamera.Segmentation']]],
['sensors',['Sensors',['../namespacedroid_1_1_runtime_1_1_prototyping_1_1_sensors.html',1,'droid::Runtime::Prototyping']]],
['serialisabledictionary',['SerialisableDictionary',['../namespacedroid_1_1_runtime_1_1_utilities_1_1_scriptable_objects_1_1_serialisable_dictionary.html',1,'droid::Runtime::Utilities::ScriptableObjects']]],
['statevalidation',['StateValidation',['../namespacedroid_1_1_runtime_1_1_prototyping_1_1_internals_1_1_state_validation.html',1,'droid::Runtime::Prototyping::Internals']]],
['statusdisplayer',['StatusDisplayer',['../namespacedroid_1_1_runtime_1_1_utilities_1_1_game_objects_1_1_status_displayer.html',1,'droid::Runtime::Utilities::GameObjects']]],
['structs',['Structs',['../namespacedroid_1_1_runtime_1_1_utilities_1_1_structs.html',1,'droid::Runtime::Utilities']]],
['synthesis',['Synthesis',['../namespacedroid_1_1_runtime_1_1_utilities_1_1_game_objects_1_1_neodroid_camera_1_1_synthesis.html',1,'droid::Runtime::Utilities::GameObjects::NeodroidCamera']]],
['tasks',['Tasks',['../namespacedroid_1_1_runtime_1_1_prototyping_1_1_evaluation_1_1_tasks.html',1,'droid::Runtime::Prototyping::Evaluation']]],
['transform',['Transform',['../namespacedroid_1_1_runtime_1_1_prototyping_1_1_sensors_1_1_transform.html',1,'droid::Runtime::Prototyping::Sensors']]],
['unsorted',['Unsorted',['../namespacedroid_1_1_runtime_1_1_utilities_1_1_game_objects_1_1_status_displayer_1_1_event_recipie7894e3945ef0ce7c38426306c60fde2d.html',1,'droid::Runtime::Utilities::GameObjects::StatusDisplayer::EventRecipients::droid::Neodroid::Utilities']]],
['unused',['Unused',['../namespacedroid_1_1_runtime_1_1_utilities_1_1_game_objects_1_1_bounding_boxes_1_1_experimental_1_1_unused.html',1,'droid.Runtime.Utilities.GameObjects.BoundingBoxes.Experimental.Unused'],['../namespacedroid_1_1_runtime_1_1_utilities_1_1_scriptable_objects_1_1_unused.html',1,'droid.Runtime.Utilities.ScriptableObjects.Unused']]],
['utilities',['Utilities',['../namespacedroid_1_1_runtime_1_1_utilities.html',1,'droid.Runtime.Utilities'],['../namespacedroid_1_1_runtime_1_1_utilities_1_1_game_objects_1_1_status_displayer_1_1_event_recipieac117b565ccca0d5f9f0e446a3034727.html',1,'droid.Runtime.Utilities.GameObjects.StatusDisplayer.EventRecipients.droid.Neodroid.Utilities']]],
['wheelcollideractuator',['WheelColliderActuator',['../namespacedroid_1_1_runtime_1_1_prototyping_1_1_actuators_1_1_wheel_collider_actuator.html',1,'droid::Runtime::Prototyping::Actuators']]]
];
|
function autoreload_subscribe() {
Genie.WebChannels.sendMessageTo("autoreload", "subscribe");
console.log("Autoreloading ready");
}
setTimeout(autoreload_subscribe, 2000);
Genie.WebChannels.messageHandlers.push(function(event) {
if ( event.data == "autoreload:full" ) {
location.reload(true);
}
}); |
#
# (C) Copyright 2015-2018 by Rocky Bernstein
# (C) Copyright 2000-2002 by hartmut Goebel <[email protected]>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 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/>.
"""
byte-code verification
"""
from __future__ import print_function
import operator, sys
import xdis.std as dis
from subprocess import call
import uncompyle6
from uncompyle6.scanner import (Token as ScannerToken, get_scanner)
from uncompyle6 import PYTHON3
from xdis.code import iscode
from xdis.magics import PYTHON_MAGIC_INT
from xdis.load import load_file, load_module
from xdis.util import pretty_flags
# FIXME: DRY
if PYTHON3:
truediv = operator.truediv
from functools import reduce
else:
truediv = operator.div
def code_equal(a, b):
return a.co_code == b.co_code
BIN_OP_FUNCS = {
'BINARY_POWER': operator.pow,
'BINARY_MULTIPLY': operator.mul,
'BINARY_DIVIDE': truediv,
'BINARY_FLOOR_DIVIDE': operator.floordiv,
'BINARY_TRUE_DIVIDE': operator.truediv,
'BINARY_MODULO' : operator.mod,
'BINARY_ADD': operator.add,
'BINARY_SUBRACT': operator.sub,
'BINARY_LSHIFT': operator.lshift,
'BINARY_RSHIFT': operator.rshift,
'BINARY_AND': operator.and_,
'BINARY_XOR': operator.xor,
'BINARY_OR': operator.or_,
}
JUMP_OPS = None
# --- exceptions ---
class VerifyCmpError(Exception):
pass
class CmpErrorConsts(VerifyCmpError):
"""Exception to be raised when consts differ."""
def __init__(self, name, index):
self.name = name
self.index = index
def __str__(self):
return 'Compare Error within Consts of %s at index %i' % \
(repr(self.name), self.index)
class CmpErrorConstsType(VerifyCmpError):
"""Exception to be raised when consts differ."""
def __init__(self, name, index):
self.name = name
self.index = index
def __str__(self):
return 'Consts type differ in %s at index %i' % \
(repr(self.name), self.index)
class CmpErrorConstsLen(VerifyCmpError):
"""Exception to be raised when length of co_consts differs."""
def __init__(self, name, consts1, consts2):
self.name = name
self.consts = (consts1, consts2)
def __str__(self):
return 'Consts length differs in %s:\n\n%i:\t%s\n\n%i:\t%s\n\n' % \
(repr(self.name),
len(self.consts[0]), repr(self.consts[0]),
len(self.consts[1]), repr(self.consts[1]))
class CmpErrorCode(VerifyCmpError):
"""Exception to be raised when code differs."""
def __init__(self, name, index, token1, token2, tokens1, tokens2):
self.name = name
self.index = index
self.token1 = token1
self.token2 = token2
self.tokens = [tokens1, tokens2]
def __str__(self):
s = reduce(lambda s, t: "%s%-37s\t%-37s\n" % (s, t[0], t[1]),
list(map(lambda a, b: (a, b),
self.tokens[0],
self.tokens[1])),
'Code differs in %s\n' % str(self.name))
return ('Code differs in %s at offset %s [%s] != [%s]\n\n' %
(repr(self.name), self.index,
repr(self.token1), repr(self.token2))) + s
class CmpErrorCodeLen(VerifyCmpError):
"""Exception to be raised when code length differs."""
def __init__(self, name, tokens1, tokens2):
self.name = name
self.tokens = [tokens1, tokens2]
def __str__(self):
return reduce(lambda s, t: "%s%-37s\t%-37s\n" % (s, t[0], t[1]),
list(map(lambda a, b: (a, b),
self.tokens[0],
self.tokens[1])),
'Code len differs in %s\n' % str(self.name))
class CmpErrorMember(VerifyCmpError):
"""Exception to be raised when other members differ."""
def __init__(self, name, member, data1, data2):
self.name = name
self.member = member
self.data = (data1, data2)
def __str__(self):
return 'Member %s differs in %s:\n\t%s\n\t%s\n' % \
(repr(self.member), repr(self.name),
repr(self.data[0]), repr(self.data[1]))
# --- compare ---
# these members are ignored
__IGNORE_CODE_MEMBERS__ = ['co_filename', 'co_firstlineno', 'co_lnotab', 'co_stacksize', 'co_names']
def cmp_code_objects(version, is_pypy, code_obj1, code_obj2, verify,
name=''):
"""
Compare two code-objects.
This is the main part of this module.
"""
# print code_obj1, type(code_obj2)
assert iscode(code_obj1), \
"cmp_code_object first object type is %s, not code" % type(code_obj1)
assert iscode(code_obj2), \
"cmp_code_object second object type is %s, not code" % type(code_obj2)
# print dir(code_obj1)
if isinstance(code_obj1, object):
# new style classes (Python 2.2)
# assume _both_ code objects to be new stle classes
assert dir(code_obj1) == dir(code_obj2)
else:
# old style classes
assert dir(code_obj1) == code_obj1.__members__
assert dir(code_obj2) == code_obj2.__members__
assert code_obj1.__members__ == code_obj2.__members__
if name == '__main__':
name = code_obj1.co_name
else:
name = '%s.%s' % (name, code_obj1.co_name)
if name == '.?': name = '__main__'
if isinstance(code_obj1, object) and code_equal(code_obj1, code_obj2):
# use the new style code-classes' __cmp__ method, which
# should be faster and more sophisticated
# if this compare fails, we use the old routine to
# find out, what exactly is nor equal
# if this compare succeds, simply return
# return
pass
if isinstance(code_obj1, object):
members = [x for x in dir(code_obj1) if x.startswith('co_')]
else:
members = dir(code_obj1)
members.sort() # ; members.reverse()
tokens1 = None
for member in members:
if member in __IGNORE_CODE_MEMBERS__ or verify != 'verify':
pass
elif member == 'co_code':
if verify != 'strong':
continue
scanner = get_scanner(version, is_pypy, show_asm=False)
global JUMP_OPS
JUMP_OPS = list(scan.JUMP_OPS) + ['JUMP_BACK']
# use changed Token class
# We (re)set this here to save exception handling,
# which would get confusing.
scanner.setTokenClass(Token)
try:
# ingest both code-objects
tokens1, customize = scanner.ingest(code_obj1)
del customize # save memory
tokens2, customize = scanner.ingest(code_obj2)
del customize # save memory
finally:
scanner.resetTokenClass() # restore Token class
targets1 = dis.findlabels(code_obj1.co_code)
tokens1 = [t for t in tokens1 if t.kind != 'COME_FROM']
tokens2 = [t for t in tokens2 if t.kind != 'COME_FROM']
i1 = 0; i2 = 0
offset_map = {}; check_jumps = {}
while i1 < len(tokens1):
if i2 >= len(tokens2):
if len(tokens1) == len(tokens2) + 2 \
and tokens1[-1].kind == 'RETURN_VALUE' \
and tokens1[-2].kind == 'LOAD_CONST' \
and tokens1[-2].pattr is None \
and tokens1[-3].kind == 'RETURN_VALUE':
break
else:
raise CmpErrorCodeLen(name, tokens1, tokens2)
offset_map[tokens1[i1].offset] = tokens2[i2].offset
for idx1, idx2, offset2 in check_jumps.get(tokens1[i1].offset, []):
if offset2 != tokens2[i2].offset:
raise CmpErrorCode(name, tokens1[idx1].offset, tokens1[idx1],
tokens2[idx2], tokens1, tokens2)
if tokens1[i1].kind != tokens2[i2].kind:
if tokens1[i1].kind == 'LOAD_CONST' == tokens2[i2].kind:
i = 1
while tokens1[i1+i].kind == 'LOAD_CONST':
i += 1
if tokens1[i1+i].kind.startswith(('BUILD_TUPLE', 'BUILD_LIST')) \
and i == int(tokens1[i1+i].kind.split('_')[-1]):
t = tuple([ elem.pattr for elem in tokens1[i1:i1+i] ])
if t != tokens2[i2].pattr:
raise CmpErrorCode(name, tokens1[i1].offset, tokens1[i1],
tokens2[i2], tokens1, tokens2)
i1 += i + 1
i2 += 1
continue
elif i == 2 and tokens1[i1+i].kind == 'ROT_TWO' and tokens2[i2+1].kind == 'UNPACK_SEQUENCE_2':
i1 += 3
i2 += 2
continue
elif i == 2 and tokens1[i1+i].kind in BIN_OP_FUNCS:
f = BIN_OP_FUNCS[tokens1[i1+i].kind]
if f(tokens1[i1].pattr, tokens1[i1+1].pattr) == tokens2[i2].pattr:
i1 += 3
i2 += 1
continue
elif tokens1[i1].kind == 'UNARY_NOT':
if tokens2[i2].kind == 'POP_JUMP_IF_TRUE':
if tokens1[i1+1].kind == 'POP_JUMP_IF_FALSE':
i1 += 2
i2 += 1
continue
elif tokens2[i2].kind == 'POP_JUMP_IF_FALSE':
if tokens1[i1+1].kind == 'POP_JUMP_IF_TRUE':
i1 += 2
i2 += 1
continue
elif tokens1[i1].kind in ('JUMP_FORWARD', 'JUMP_BACK') \
and tokens1[i1-1].kind == 'RETURN_VALUE' \
and tokens2[i2-1].kind in ('RETURN_VALUE', 'RETURN_END_IF') \
and int(tokens1[i1].offset) not in targets1:
i1 += 1
continue
elif tokens1[i1].kind == 'JUMP_BACK' and tokens2[i2].kind == 'CONTINUE':
# FIXME: should make sure that offset is inside loop, not outside of it
i1 += 2
i2 += 2
continue
elif tokens1[i1].kind == 'JUMP_FORWARD' and tokens2[i2].kind == 'JUMP_BACK' \
and tokens1[i1+1].kind == 'JUMP_BACK' and tokens2[i2+1].kind == 'JUMP_BACK' \
and int(tokens1[i1].pattr) == int(tokens1[i1].offset) + 3:
if int(tokens1[i1].pattr) == int(tokens1[i1+1].offset):
i1 += 2
i2 += 2
continue
elif tokens1[i1].kind == 'LOAD_NAME' and tokens2[i2].kind == 'LOAD_CONST' \
and tokens1[i1].pattr == 'None' and tokens2[i2].pattr is None:
pass
elif tokens1[i1].kind == 'LOAD_GLOBAL' and tokens2[i2].kind == 'LOAD_NAME' \
and tokens1[i1].pattr == tokens2[i2].pattr:
pass
elif tokens1[i1].kind == 'LOAD_ASSERT' and tokens2[i2].kind == 'LOAD_NAME' \
and tokens1[i1].pattr == tokens2[i2].pattr:
pass
elif (tokens1[i1].kind == 'RETURN_VALUE' and
tokens2[i2].kind == 'RETURN_END_IF'):
pass
elif (tokens1[i1].kind == 'BUILD_TUPLE_0' and
tokens2[i2].pattr == ()):
pass
else:
raise CmpErrorCode(name, tokens1[i1].offset, tokens1[i1],
tokens2[i2], tokens1, tokens2)
elif tokens1[i1].kind in JUMP_OPS and tokens1[i1].pattr != tokens2[i2].pattr:
if tokens1[i1].kind == 'JUMP_BACK':
dest1 = int(tokens1[i1].pattr)
dest2 = int(tokens2[i2].pattr)
if offset_map[dest1] != dest2:
raise CmpErrorCode(name, tokens1[i1].offset, tokens1[i1],
tokens2[i2], tokens1, tokens2)
else:
# import pdb; pdb.set_trace()
try:
dest1 = int(tokens1[i1].pattr)
if dest1 in check_jumps:
check_jumps[dest1].append((i1, i2, dest2))
else:
check_jumps[dest1] = [(i1, i2, dest2)]
except:
pass
i1 += 1
i2 += 1
del tokens1, tokens2 # save memory
elif member == 'co_consts':
# partial optimization can make the co_consts look different,
# so we'll just compare the code consts
codes1 = ( c for c in code_obj1.co_consts if hasattr(c, 'co_consts') )
codes2 = ( c for c in code_obj2.co_consts if hasattr(c, 'co_consts') )
for c1, c2 in zip(codes1, codes2):
cmp_code_objects(version, is_pypy, c1, c2, verify,
name=name)
elif member == 'co_flags':
flags1 = code_obj1.co_flags
flags2 = code_obj2.co_flags
if is_pypy:
# For PYPY for now we don't care about PYPY_SOURCE_IS_UTF8:
flags2 &= ~0x0100 # PYPY_SOURCE_IS_UTF8
# We also don't care about COROUTINE or GENERATOR for now
flags1 &= ~0x000000a0
flags2 &= ~0x000000a0
if flags1 != flags2:
raise CmpErrorMember(name, 'co_flags',
pretty_flags(flags1),
pretty_flags(flags2))
else:
# all other members must be equal
if getattr(code_obj1, member) != getattr(code_obj2, member):
raise CmpErrorMember(name, member,
getattr(code_obj1, member),
getattr(code_obj2, member))
class Token(ScannerToken):
"""Token class with changed semantics for 'cmp()'."""
def __cmp__(self, o):
t = self.kind # shortcut
if t == 'BUILD_TUPLE_0' and o.kind == 'LOAD_CONST' and o.pattr == ():
return 0
if t == 'COME_FROM' == o.kind:
return 0
if t == 'PRINT_ITEM_CONT' and o.kind == 'PRINT_ITEM':
return 0
if t == 'RETURN_VALUE' and o.kind == 'RETURN_END_IF':
return 0
if t == 'JUMP_IF_FALSE_OR_POP' and o.kind == 'POP_JUMP_IF_FALSE':
return 0
if JUMP_OPS and t in JUMP_OPS:
# ignore offset
return t == o.kind
return (t == o.kind) or self.pattr == o.pattr
def __repr__(self):
return '%s %s (%s)' % (str(self.kind), str(self.attr),
repr(self.pattr))
def __str__(self):
return '%s\t%-17s %r' % (self.offset, self.kind, self.pattr)
def compare_code_with_srcfile(pyc_filename, src_filename, verify):
"""Compare a .pyc with a source code file. If everything is okay, None
is returned. Otherwise a string message describing the mismatch is returned.
"""
(version, timestamp, magic_int, code_obj1, is_pypy,
source_size) = load_module(pyc_filename)
if magic_int != PYTHON_MAGIC_INT:
msg = ("Can't compare code - Python is running with magic %s, but code is magic %s "
% (PYTHON_MAGIC_INT, magic_int))
return msg
try:
code_obj2 = load_file(src_filename)
except SyntaxError as e:
# src_filename can be the first of a group sometimes
return str(e).replace(src_filename, pyc_filename)
cmp_code_objects(version, is_pypy, code_obj1, code_obj2, verify)
if verify == 'verify-run':
try:
retcode = call("%s %s" % (sys.executable, src_filename), shell=True)
if retcode != 0:
return "Child was terminated by signal %d" % retcode
pass
except OSError as e:
return "Execution failed: %s" % e
pass
return None
def compare_files(pyc_filename1, pyc_filename2, verify):
"""Compare two .pyc files."""
(version1, timestamp, magic_int1, code_obj1, is_pypy,
source_size) = uncompyle6.load_module(pyc_filename1)
(version2, timestamp, magic_int2, code_obj2, is_pypy,
source_size) = uncompyle6.load_module(pyc_filename2)
if (magic_int1 != magic_int2) and verify == 'verify':
verify = 'weak_verify'
cmp_code_objects(version1, is_pypy, code_obj1, code_obj2, verify)
if __name__ == '__main__':
t1 = Token('LOAD_CONST', None, 'code_object _expandLang', 52)
t2 = Token('LOAD_CONST', -421, 'code_object _expandLang', 55)
print(repr(t1))
print(repr(t2))
print(t1.kind == t2.kind, t1.attr == t2.attr)
|
from pprint import pprint
from dataset.utils.parser import CodeParser
from dataset.utils.test import (LANGUAGES, SO_FILES_MAP)
LANG = 'python'
parser = CodeParser(so_file=SO_FILES_MAP[LANG], language=LANG)
# code = \
# """
# def sum_of_list(arr_, idx = 0):
# arr_len = len(arr_)
# if idx == arr_len:
# return 0
# else:
# return arr_[idx] + sum_of_list(arr_, idx + 1)
# """
"""
{0: {'children': [1], 'parent': None, 'type': 'module'},
1: {'children': [2, 3, 4, 13, 14], 'parent': 0, 'type': 'function_definition'},
2: {'parent': 1, 'type': 'Keyword', 'value': 'def'},
3: {'parent': 1, 'type': 'identifier', 'value': 'sum_of_list'},
4: {'children': [5, 6, 7, 8, 12], 'parent': 1, 'type': 'parameters'},
5: {'parent': 4, 'type': 'LeftParenOp', 'value': '('},
6: {'parent': 4, 'type': 'identifier', 'value': 'arr_'},
7: {'parent': 4, 'type': 'CommaOp', 'value': ','},
8: {'children': [9, 10, 11], 'parent': 4, 'type': 'default_parameter'},
9: {'parent': 8, 'type': 'identifier', 'value': 'idx'},
10: {'parent': 8, 'type': 'AsgnOp', 'value': '='},
11: {'parent': 8, 'type': 'integer', 'value': '0'},
12: {'parent': 4, 'type': 'LeftParenOp', 'value': ')'},
13: {'parent': 1, 'type': 'ColonOp', 'value': ':'},
14: {'children': [15, 27], 'parent': 1, 'type': 'block'},
15: {'children': [16], 'parent': 14, 'type': 'expression_statement'},
16: {'children': [17, 19, 20], 'parent': 15, 'type': 'assignment'},
17: {'children': [18], 'parent': 16, 'type': 'expression_list'},
18: {'parent': 17, 'type': 'identifier', 'value': 'arr_len'},
19: {'parent': 16, 'type': 'AsgnOp', 'value': '='},
20: {'children': [21], 'parent': 16, 'type': 'expression_list'},
21: {'children': [22, 23], 'parent': 20, 'type': 'call'},
22: {'parent': 21, 'type': 'identifier', 'value': 'len'},
23: {'children': [24, 25, 26], 'parent': 21, 'type': 'argument_list'},
24: {'parent': 23, 'type': 'LeftParenOp', 'value': '('},
25: {'parent': 23, 'type': 'identifier', 'value': 'arr_'},
26: {'parent': 23, 'type': 'LeftParenOp', 'value': ')'},
27: {'children': [28, 29, 33, 34, 39], 'parent': 14, 'type': 'if_statement'},
28: {'parent': 27, 'type': 'Keyword', 'value': 'if'},
29: {'children': [30, 31, 32], 'parent': 27, 'type': 'comparison_operator'},
30: {'parent': 29, 'type': 'identifier', 'value': 'idx'},
31: {'parent': 29, 'type': 'EqualOp', 'value': '=='},
32: {'parent': 29, 'type': 'identifier', 'value': 'arr_len'},
33: {'parent': 27, 'type': 'ColonOp', 'value': ':'},
34: {'children': [35], 'parent': 27, 'type': 'block'},
35: {'children': [36, 37], 'parent': 34, 'type': 'return_statement'},
36: {'parent': 35, 'type': 'Keyword', 'value': 'return'},
37: {'children': [38], 'parent': 35, 'type': 'expression_list'},
38: {'parent': 37, 'type': 'integer', 'value': '0'},
39: {'children': [40, 41, 42], 'parent': 27, 'type': 'else_clause'},
40: {'parent': 39, 'type': 'Keyword', 'value': 'else'},
41: {'parent': 39, 'type': 'ColonOp', 'value': ':'},
42: {'children': [43], 'parent': 39, 'type': 'block'},
43: {'children': [44, 45], 'parent': 42, 'type': 'return_statement'},
44: {'parent': 43, 'type': 'Keyword', 'value': 'return'},
45: {'children': [46], 'parent': 43, 'type': 'expression_list'},
46: {'children': [47, 52, 53], 'parent': 45, 'type': 'binary_operator'},
47: {'children': [48, 49, 50, 51], 'parent': 46, 'type': 'subscript'},
48: {'parent': 47, 'type': 'identifier', 'value': 'arr_'},
49: {'parent': 47, 'type': 'LeftBracketOp', 'value': '['},
50: {'parent': 47, 'type': 'identifier', 'value': 'idx'},
51: {'parent': 47, 'type': 'RightBracketOp', 'value': ']'},
52: {'parent': 46, 'type': 'AddOp', 'value': '+'},
53: {'children': [54, 55], 'parent': 46, 'type': 'call'},
54: {'parent': 53, 'type': 'identifier', 'value': 'sum_of_list'},
55: {'children': [56, 57, 58, 59, 63], 'parent': 53, 'type': 'argument_list'},
56: {'parent': 55, 'type': 'LeftParenOp', 'value': '('},
57: {'parent': 55, 'type': 'identifier', 'value': 'arr_'},
58: {'parent': 55, 'type': 'CommaOp', 'value': ','},
59: {'children': [60, 61, 62], 'parent': 55, 'type': 'binary_operator'},
60: {'parent': 59, 'type': 'identifier', 'value': 'idx'},
61: {'parent': 59, 'type': 'AddOp', 'value': '+'},
62: {'parent': 59, 'type': 'integer', 'value': '1'},
63: {'parent': 55, 'type': 'LeftParenOp', 'value': ')'}}
"""
# code = \
# """
# def remove(array, e):
# return filter(lambda x: x != e, array)
# """.strip()
"""
{0: {'children': [1], 'parent': None, 'type': 'module'},
1: {'children': [2, 3, 4, 10, 11], 'parent': 0, 'type': 'function_definition'},
2: {'parent': 1, 'type': 'Keyword', 'value': 'def'},
3: {'parent': 1, 'type': 'identifier', 'value': 'remove'},
4: {'children': [5, 6, 7, 8, 9], 'parent': 1, 'type': 'parameters'},
5: {'parent': 4, 'type': 'LeftParenOp', 'value': '('},
6: {'parent': 4, 'type': 'identifier', 'value': 'array'},
7: {'parent': 4, 'type': 'CommaOp', 'value': ','},
8: {'parent': 4, 'type': 'identifier', 'value': 'e'},
9: {'parent': 4, 'type': 'LeftParenOp', 'value': ')'},
10: {'parent': 1, 'type': 'ColonOp', 'value': ':'},
11: {'children': [12], 'parent': 1, 'type': 'block'},
12: {'children': [13, 14], 'parent': 11, 'type': 'return_statement'},
13: {'parent': 12, 'type': 'Keyword', 'value': 'return'},
14: {'children': [15], 'parent': 12, 'type': 'expression_list'},
15: {'children': [16, 17], 'parent': 14, 'type': 'call'},
16: {'parent': 15, 'type': 'identifier', 'value': 'filter'},
17: {'children': [18, 19, 28, 29, 30], 'parent': 15, 'type': 'argument_list'},
18: {'parent': 17, 'type': 'LeftParenOp', 'value': '('},
19: {'children': [20, 21, 23, 24], 'parent': 17, 'type': 'lambda'},
20: {'parent': 19, 'type': 'Keyword', 'value': 'lambda'},
21: {'children': [22], 'parent': 19, 'type': 'lambda_parameters'},
22: {'parent': 21, 'type': 'identifier', 'value': 'x'},
23: {'parent': 19, 'type': 'ColonOp', 'value': ':'},
24: {'children': [25, 26, 27], 'parent': 19, 'type': 'comparison_operator'},
25: {'parent': 24, 'type': 'identifier', 'value': 'x'},
26: {'parent': 24, 'type': 'InequalOp', 'value': '!='},
27: {'parent': 24, 'type': 'identifier', 'value': 'e'},
28: {'parent': 17, 'type': 'CommaOp', 'value': ','},
29: {'parent': 17, 'type': 'identifier', 'value': 'array'},
30: {'parent': 17, 'type': 'LeftParenOp', 'value': ')'}}
"""
code = \
"""
def fib(n):
if n <= 2:
return n
else:
return fib(n - 1) + fib(n - 2)
""".strip()
"""
{0: {'children': [1], 'parent': None, 'type': 'module'},
1: {'children': [2, 3, 4, 8, 9], 'parent': 0, 'type': 'function_definition'},
2: {'parent': 1, 'type': 'Keyword', 'value': 'def'},
3: {'parent': 1, 'type': 'identifier', 'value': 'fib'},
4: {'children': [5, 6, 7], 'parent': 1, 'type': 'parameters'},
5: {'parent': 4, 'type': 'LeftParenOp', 'value': '('},
6: {'parent': 4, 'type': 'identifier', 'value': 'n'},
7: {'parent': 4, 'type': 'LeftParenOp', 'value': ')'},
8: {'parent': 1, 'type': 'ColonOp', 'value': ':'},
9: {'children': [10], 'parent': 1, 'type': 'block'},
10: {'children': [11, 12, 16, 17, 22], 'parent': 9, 'type': 'if_statement'},
11: {'parent': 10, 'type': 'Keyword', 'value': 'if'},
12: {'children': [13, 14, 15], 'parent': 10, 'type': 'comparison_operator'},
13: {'parent': 12, 'type': 'identifier', 'value': 'n'},
14: {'parent': 12, 'type': 'LEOp', 'value': '<='},
15: {'parent': 12, 'type': 'integer', 'value': '2'},
16: {'parent': 10, 'type': 'ColonOp', 'value': ':'},
17: {'children': [18], 'parent': 10, 'type': 'block'},
18: {'children': [19, 20], 'parent': 17, 'type': 'return_statement'},
19: {'parent': 18, 'type': 'Keyword', 'value': 'return'},
20: {'children': [21], 'parent': 18, 'type': 'expression_list'},
21: {'parent': 20, 'type': 'identifier', 'value': 'n'},
22: {'children': [23, 24, 25], 'parent': 10, 'type': 'else_clause'},
23: {'parent': 22, 'type': 'Keyword', 'value': 'else'},
24: {'parent': 22, 'type': 'ColonOp', 'value': ':'},
25: {'children': [26], 'parent': 22, 'type': 'block'},
26: {'children': [27, 28], 'parent': 25, 'type': 'return_statement'},
27: {'parent': 26, 'type': 'Keyword', 'value': 'return'},
28: {'children': [29], 'parent': 26, 'type': 'expression_list'},
29: {'children': [30, 39, 40], 'parent': 28, 'type': 'binary_operator'},
30: {'children': [31, 32], 'parent': 29, 'type': 'call'},
31: {'parent': 30, 'type': 'identifier', 'value': 'fib'},
32: {'children': [33, 34, 38], 'parent': 30, 'type': 'argument_list'},
33: {'parent': 32, 'type': 'LeftParenOp', 'value': '('},
34: {'children': [35, 36, 37], 'parent': 32, 'type': 'binary_operator'},
35: {'parent': 34, 'type': 'identifier', 'value': 'n'},
36: {'parent': 34, 'type': 'SubOp', 'value': '-'},
37: {'parent': 34, 'type': 'integer', 'value': '1'},
38: {'parent': 32, 'type': 'LeftParenOp', 'value': ')'},
39: {'parent': 29, 'type': 'AddOp', 'value': '+'},
40: {'children': [41, 42], 'parent': 29, 'type': 'call'},
41: {'parent': 40, 'type': 'identifier', 'value': 'fib'},
42: {'children': [43, 44, 48], 'parent': 40, 'type': 'argument_list'},
43: {'parent': 42, 'type': 'LeftParenOp', 'value': '('},
44: {'children': [45, 46, 47], 'parent': 42, 'type': 'binary_operator'},
45: {'parent': 44, 'type': 'identifier', 'value': 'n'},
46: {'parent': 44, 'type': 'SubOp', 'value': '-'},
47: {'parent': 44, 'type': 'integer', 'value': '2'},
48: {'parent': 42, 'type': 'LeftParenOp', 'value': ')'}}
"""
if __name__ == '__main__':
ast = parser.parse(code)
pprint(ast)
|
export default {
navTheme: 'dark', // 菜单的主题 content: dark or light
layout: 'sidemenu', // 菜单的布局,值为 sidemenu 菜单显示在左侧,值为 topmenu 菜单显示在顶部
contentWidth: 'Fluid', // 内容的布局 Fixed 为定宽到1200px ,Fluid 为流式布局
fixedHeader: false, // 固定页头
autoHideHeader: false, // 下滑时自动隐藏页头
fixSiderbar: false, // 固定菜单
sysName: 'cjet-admin' //系统名称
}
|
# coding=utf-8
# *** WARNING: this file was generated by the Pulumi SDK Generator. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, Sequence, Union
from ... import _utilities, _tables
from . import outputs
__all__ = [
'GetVirtualNetworkPeeringResult',
'AwaitableGetVirtualNetworkPeeringResult',
'get_virtual_network_peering',
]
@pulumi.output_type
class GetVirtualNetworkPeeringResult:
"""
Peerings in a virtual network resource.
"""
def __init__(__self__, allow_forwarded_traffic=None, allow_gateway_transit=None, allow_virtual_network_access=None, etag=None, id=None, name=None, peering_state=None, provisioning_state=None, remote_address_space=None, remote_virtual_network=None, use_remote_gateways=None):
if allow_forwarded_traffic and not isinstance(allow_forwarded_traffic, bool):
raise TypeError("Expected argument 'allow_forwarded_traffic' to be a bool")
pulumi.set(__self__, "allow_forwarded_traffic", allow_forwarded_traffic)
if allow_gateway_transit and not isinstance(allow_gateway_transit, bool):
raise TypeError("Expected argument 'allow_gateway_transit' to be a bool")
pulumi.set(__self__, "allow_gateway_transit", allow_gateway_transit)
if allow_virtual_network_access and not isinstance(allow_virtual_network_access, bool):
raise TypeError("Expected argument 'allow_virtual_network_access' to be a bool")
pulumi.set(__self__, "allow_virtual_network_access", allow_virtual_network_access)
if etag and not isinstance(etag, str):
raise TypeError("Expected argument 'etag' to be a str")
pulumi.set(__self__, "etag", etag)
if id and not isinstance(id, str):
raise TypeError("Expected argument 'id' to be a str")
pulumi.set(__self__, "id", id)
if name and not isinstance(name, str):
raise TypeError("Expected argument 'name' to be a str")
pulumi.set(__self__, "name", name)
if peering_state and not isinstance(peering_state, str):
raise TypeError("Expected argument 'peering_state' to be a str")
pulumi.set(__self__, "peering_state", peering_state)
if provisioning_state and not isinstance(provisioning_state, str):
raise TypeError("Expected argument 'provisioning_state' to be a str")
pulumi.set(__self__, "provisioning_state", provisioning_state)
if remote_address_space and not isinstance(remote_address_space, dict):
raise TypeError("Expected argument 'remote_address_space' to be a dict")
pulumi.set(__self__, "remote_address_space", remote_address_space)
if remote_virtual_network and not isinstance(remote_virtual_network, dict):
raise TypeError("Expected argument 'remote_virtual_network' to be a dict")
pulumi.set(__self__, "remote_virtual_network", remote_virtual_network)
if use_remote_gateways and not isinstance(use_remote_gateways, bool):
raise TypeError("Expected argument 'use_remote_gateways' to be a bool")
pulumi.set(__self__, "use_remote_gateways", use_remote_gateways)
@property
@pulumi.getter(name="allowForwardedTraffic")
def allow_forwarded_traffic(self) -> Optional[bool]:
"""
Whether the forwarded traffic from the VMs in the remote virtual network will be allowed/disallowed.
"""
return pulumi.get(self, "allow_forwarded_traffic")
@property
@pulumi.getter(name="allowGatewayTransit")
def allow_gateway_transit(self) -> Optional[bool]:
"""
If gateway links can be used in remote virtual networking to link to this virtual network.
"""
return pulumi.get(self, "allow_gateway_transit")
@property
@pulumi.getter(name="allowVirtualNetworkAccess")
def allow_virtual_network_access(self) -> Optional[bool]:
"""
Whether the VMs in the linked virtual network space would be able to access all the VMs in local Virtual network space.
"""
return pulumi.get(self, "allow_virtual_network_access")
@property
@pulumi.getter
def etag(self) -> Optional[str]:
"""
A unique read-only string that changes whenever the resource is updated.
"""
return pulumi.get(self, "etag")
@property
@pulumi.getter
def id(self) -> Optional[str]:
"""
Resource ID.
"""
return pulumi.get(self, "id")
@property
@pulumi.getter
def name(self) -> Optional[str]:
"""
The name of the resource that is unique within a resource group. This name can be used to access the resource.
"""
return pulumi.get(self, "name")
@property
@pulumi.getter(name="peeringState")
def peering_state(self) -> Optional[str]:
"""
The status of the virtual network peering. Possible values are 'Initiated', 'Connected', and 'Disconnected'.
"""
return pulumi.get(self, "peering_state")
@property
@pulumi.getter(name="provisioningState")
def provisioning_state(self) -> Optional[str]:
"""
The provisioning state of the resource.
"""
return pulumi.get(self, "provisioning_state")
@property
@pulumi.getter(name="remoteAddressSpace")
def remote_address_space(self) -> Optional['outputs.AddressSpaceResponse']:
"""
The reference of the remote virtual network address space.
"""
return pulumi.get(self, "remote_address_space")
@property
@pulumi.getter(name="remoteVirtualNetwork")
def remote_virtual_network(self) -> Optional['outputs.SubResourceResponse']:
"""
The reference of the remote virtual network. The remote virtual network can be in the same or different region (preview). See here to register for the preview and learn more (https://docs.microsoft.com/en-us/azure/virtual-network/virtual-network-create-peering).
"""
return pulumi.get(self, "remote_virtual_network")
@property
@pulumi.getter(name="useRemoteGateways")
def use_remote_gateways(self) -> Optional[bool]:
"""
If remote gateways can be used on this virtual network. If the flag is set to true, and allowGatewayTransit on remote peering is also true, virtual network will use gateways of remote virtual network for transit. Only one peering can have this flag set to true. This flag cannot be set if virtual network already has a gateway.
"""
return pulumi.get(self, "use_remote_gateways")
class AwaitableGetVirtualNetworkPeeringResult(GetVirtualNetworkPeeringResult):
# pylint: disable=using-constant-test
def __await__(self):
if False:
yield self
return GetVirtualNetworkPeeringResult(
allow_forwarded_traffic=self.allow_forwarded_traffic,
allow_gateway_transit=self.allow_gateway_transit,
allow_virtual_network_access=self.allow_virtual_network_access,
etag=self.etag,
id=self.id,
name=self.name,
peering_state=self.peering_state,
provisioning_state=self.provisioning_state,
remote_address_space=self.remote_address_space,
remote_virtual_network=self.remote_virtual_network,
use_remote_gateways=self.use_remote_gateways)
def get_virtual_network_peering(resource_group_name: Optional[str] = None,
virtual_network_name: Optional[str] = None,
virtual_network_peering_name: Optional[str] = None,
opts: Optional[pulumi.InvokeOptions] = None) -> AwaitableGetVirtualNetworkPeeringResult:
"""
Peerings in a virtual network resource.
:param str resource_group_name: The name of the resource group.
:param str virtual_network_name: The name of the virtual network.
:param str virtual_network_peering_name: The name of the virtual network peering.
"""
__args__ = dict()
__args__['resourceGroupName'] = resource_group_name
__args__['virtualNetworkName'] = virtual_network_name
__args__['virtualNetworkPeeringName'] = virtual_network_peering_name
if opts is None:
opts = pulumi.InvokeOptions()
if opts.version is None:
opts.version = _utilities.get_version()
__ret__ = pulumi.runtime.invoke('azure-nextgen:network/v20180101:getVirtualNetworkPeering', __args__, opts=opts, typ=GetVirtualNetworkPeeringResult).value
return AwaitableGetVirtualNetworkPeeringResult(
allow_forwarded_traffic=__ret__.allow_forwarded_traffic,
allow_gateway_transit=__ret__.allow_gateway_transit,
allow_virtual_network_access=__ret__.allow_virtual_network_access,
etag=__ret__.etag,
id=__ret__.id,
name=__ret__.name,
peering_state=__ret__.peering_state,
provisioning_state=__ret__.provisioning_state,
remote_address_space=__ret__.remote_address_space,
remote_virtual_network=__ret__.remote_virtual_network,
use_remote_gateways=__ret__.use_remote_gateways)
|
(window.webpackJsonp=window.webpackJsonp||[]).push([[8],{198:function(e,t,a){"use strict";a.r(t);var n=a(0),r=a.n(n),c=a(222),l=a(203),i=a(202);t.default=function(){return r.a.createElement(l.a,null,r.a.createElement(i.a,{title:"Page two"}),r.a.createElement("h1",null,"Hi from the second page"),r.a.createElement("p",null,"Welcome to page 2"),r.a.createElement(c.a,{to:"/"},"Go back to the homepage"))}},201:function(e,t,a){"use strict";a.d(t,"a",function(){return c}),a.d(t,"i",function(){return l}),a.d(t,"g",function(){return i}),a.d(t,"d",function(){return s}),a.d(t,"h",function(){return o}),a.d(t,"f",function(){return u}),a.d(t,"e",function(){return m}),a.d(t,"b",function(){return d}),a.d(t,"c",function(){return p});var n=a(0),r=a.n(n),c=function(){return r.a.createElement("svg",{className:"svg-icon",viewBox:"0 0 20 20"},r.a.createElement("path",{fill:"none",d:"M16.254,3.399h-0.695V3.052c0-0.576-0.467-1.042-1.041-1.042c-0.576,0-1.043,0.467-1.043,1.042v0.347H6.526V3.052c0-0.576-0.467-1.042-1.042-1.042S4.441,2.476,4.441,3.052v0.347H3.747c-0.768,0-1.39,0.622-1.39,1.39v11.813c0,0.768,0.622,1.39,1.39,1.39h12.507c0.768,0,1.391-0.622,1.391-1.39V4.789C17.645,4.021,17.021,3.399,16.254,3.399z M14.17,3.052c0-0.192,0.154-0.348,0.348-0.348c0.191,0,0.348,0.156,0.348,0.348v0.347H14.17V3.052z M5.136,3.052c0-0.192,0.156-0.348,0.348-0.348S5.831,2.86,5.831,3.052v0.347H5.136V3.052z M16.949,16.602c0,0.384-0.311,0.694-0.695,0.694H3.747c-0.384,0-0.695-0.311-0.695-0.694V7.568h13.897V16.602z M16.949,6.874H3.052V4.789c0-0.383,0.311-0.695,0.695-0.695h12.507c0.385,0,0.695,0.312,0.695,0.695V6.874z M5.484,11.737c0.576,0,1.042-0.467,1.042-1.042c0-0.576-0.467-1.043-1.042-1.043s-1.042,0.467-1.042,1.043C4.441,11.271,4.908,11.737,5.484,11.737z M5.484,10.348c0.192,0,0.347,0.155,0.347,0.348c0,0.191-0.155,0.348-0.347,0.348s-0.348-0.156-0.348-0.348C5.136,10.503,5.292,10.348,5.484,10.348z M14.518,11.737c0.574,0,1.041-0.467,1.041-1.042c0-0.576-0.467-1.043-1.041-1.043c-0.576,0-1.043,0.467-1.043,1.043C13.475,11.271,13.941,11.737,14.518,11.737z M14.518,10.348c0.191,0,0.348,0.155,0.348,0.348c0,0.191-0.156,0.348-0.348,0.348c-0.193,0-0.348-0.156-0.348-0.348C14.17,10.503,14.324,10.348,14.518,10.348z M14.518,15.212c0.574,0,1.041-0.467,1.041-1.043c0-0.575-0.467-1.042-1.041-1.042c-0.576,0-1.043,0.467-1.043,1.042C13.475,14.745,13.941,15.212,14.518,15.212z M14.518,13.822c0.191,0,0.348,0.155,0.348,0.347c0,0.192-0.156,0.348-0.348,0.348c-0.193,0-0.348-0.155-0.348-0.348C14.17,13.978,14.324,13.822,14.518,13.822z M10,15.212c0.575,0,1.042-0.467,1.042-1.043c0-0.575-0.467-1.042-1.042-1.042c-0.576,0-1.042,0.467-1.042,1.042C8.958,14.745,9.425,15.212,10,15.212z M10,13.822c0.192,0,0.348,0.155,0.348,0.347c0,0.192-0.156,0.348-0.348,0.348s-0.348-0.155-0.348-0.348C9.653,13.978,9.809,13.822,10,13.822z M5.484,15.212c0.576,0,1.042-0.467,1.042-1.043c0-0.575-0.467-1.042-1.042-1.042s-1.042,0.467-1.042,1.042C4.441,14.745,4.908,15.212,5.484,15.212z M5.484,13.822c0.192,0,0.347,0.155,0.347,0.347c0,0.192-0.155,0.348-0.347,0.348s-0.348-0.155-0.348-0.348C5.136,13.978,5.292,13.822,5.484,13.822z M10,11.737c0.575,0,1.042-0.467,1.042-1.042c0-0.576-0.467-1.043-1.042-1.043c-0.576,0-1.042,0.467-1.042,1.043C8.958,11.271,9.425,11.737,10,11.737z M10,10.348c0.192,0,0.348,0.155,0.348,0.348c0,0.191-0.156,0.348-0.348,0.348s-0.348-0.156-0.348-0.348C9.653,10.503,9.809,10.348,10,10.348z"}))},l=function(){return r.a.createElement("svg",{className:"svg-icon",viewBox:"0 0 20 20"},r.a.createElement("path",{d:"M17.218,2.268L2.477,8.388C2.13,8.535,2.164,9.05,2.542,9.134L9.33,10.67l1.535,6.787c0.083,0.377,0.602,0.415,0.745,0.065l6.123-14.74C17.866,2.46,17.539,2.134,17.218,2.268 M3.92,8.641l11.772-4.89L9.535,9.909L3.92,8.641z M11.358,16.078l-1.268-5.613l6.157-6.157L11.358,16.078z"}))},i=function(){return r.a.createElement("svg",{className:"svg-icon",viewBox:"0 0 20 20"},r.a.createElement("path",{d:"M10,1.375c-3.17,0-5.75,2.548-5.75,5.682c0,6.685,5.259,11.276,5.483,11.469c0.152,0.132,0.382,0.132,0.534,0c0.224-0.193,5.481-4.784,5.483-11.469C15.75,3.923,13.171,1.375,10,1.375 M10,17.653c-1.064-1.024-4.929-5.127-4.929-10.596c0-2.68,2.212-4.861,4.929-4.861s4.929,2.181,4.929,4.861C14.927,12.518,11.063,16.627,10,17.653 M10,3.839c-1.815,0-3.286,1.47-3.286,3.286s1.47,3.286,3.286,3.286s3.286-1.47,3.286-3.286S11.815,3.839,10,3.839 M10,9.589c-1.359,0-2.464-1.105-2.464-2.464S8.641,4.661,10,4.661s2.464,1.105,2.464,2.464S11.359,9.589,10,9.589"}))},s=function(){return r.a.createElement("svg",{className:"svg-icon",viewBox:"0 0 20 20"},r.a.createElement("path",{d:"M17.388,4.751H2.613c-0.213,0-0.389,0.175-0.389,0.389v9.72c0,0.216,0.175,0.389,0.389,0.389h14.775c0.214,0,0.389-0.173,0.389-0.389v-9.72C17.776,4.926,17.602,4.751,17.388,4.751 M16.448,5.53L10,11.984L3.552,5.53H16.448zM3.002,6.081l3.921,3.925l-3.921,3.925V6.081z M3.56,14.471l3.914-3.916l2.253,2.253c0.153,0.153,0.395,0.153,0.548,0l2.253-2.253l3.913,3.916H3.56z M16.999,13.931l-3.921-3.925l3.921-3.925V13.931z"}))},o=function(){return r.a.createElement("svg",{className:"svg-icon",viewBox:"0 0 20 20"},r.a.createElement("path",{fill:"none",d:"M10,15.654c-0.417,0-0.754,0.338-0.754,0.754S9.583,17.162,10,17.162s0.754-0.338,0.754-0.754S10.417,15.654,10,15.654z M14.523,1.33H5.477c-0.833,0-1.508,0.675-1.508,1.508v14.324c0,0.833,0.675,1.508,1.508,1.508h9.047c0.833,0,1.508-0.675,1.508-1.508V2.838C16.031,2.005,15.356,1.33,14.523,1.33z M15.277,17.162c0,0.416-0.338,0.754-0.754,0.754H5.477c-0.417,0-0.754-0.338-0.754-0.754V2.838c0-0.417,0.337-0.754,0.754-0.754h9.047c0.416,0,0.754,0.337,0.754,0.754V17.162zM13.77,2.838H6.23c-0.417,0-0.754,0.337-0.754,0.754v10.555c0,0.416,0.337,0.754,0.754,0.754h7.539c0.416,0,0.754-0.338,0.754-0.754V3.592C14.523,3.175,14.186,2.838,13.77,2.838z M13.77,13.77c0,0.208-0.169,0.377-0.377,0.377H6.607c-0.208,0-0.377-0.169-0.377-0.377V3.969c0-0.208,0.169-0.377,0.377-0.377h6.785c0.208,0,0.377,0.169,0.377,0.377V13.77z"}))},u=function(){return r.a.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 38 38",stroke:"#fff"},r.a.createElement("g",{fill:"none",fillRule:"evenodd"},r.a.createElement("g",{transform:"translate(1 1)",strokeWidth:"2"},r.a.createElement("circle",{strokeOpacity:".5",cx:"18",cy:"18",r:"18"}),r.a.createElement("path",{d:"M36 18c0-9.94-8.06-18-18-18",transform:"rotate(193.225 18 18)"},r.a.createElement("animateTransform",{attributeName:"transform",type:"rotate",from:"0 18 18",to:"360 18 18",dur:"1s",repeatCount:"indefinite"})))))},m=function(){return r.a.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",version:"1.1",viewBox:"0 0 32 32"},r.a.createElement("path",{d:"M4,10h24c1.104,0,2-0.896,2-2s-0.896-2-2-2H4C2.896,6,2,6.896,2,8S2.896,10,4,10z M28,14H4c-1.104,0-2,0.896-2,2 s0.896,2,2,2h24c1.104,0,2-0.896,2-2S29.104,14,28,14z M28,22H4c-1.104,0-2,0.896-2,2s0.896,2,2,2h24c1.104,0,2-0.896,2-2 S29.104,22,28,22z"}))},d=function(){return r.a.createElement("svg",{className:"svg-icon",viewBox:"0 0 20 20"},r.a.createElement("path",{fill:"none",d:"M8.388,10.049l4.76-4.873c0.303-0.31,0.297-0.804-0.012-1.105c-0.309-0.304-0.803-0.293-1.105,0.012L6.726,9.516c-0.303,0.31-0.296,0.805,0.012,1.105l5.433,5.307c0.152,0.148,0.35,0.223,0.547,0.223c0.203,0,0.406-0.08,0.559-0.236c0.303-0.309,0.295-0.803-0.012-1.104L8.388,10.049z"}))},p=function(){return r.a.createElement("svg",{className:"svg-icon",viewBox:"0 0 20 20"},r.a.createElement("path",{fill:"none",d:"M11.611,10.049l-4.76-4.873c-0.303-0.31-0.297-0.804,0.012-1.105c0.309-0.304,0.803-0.293,1.105,0.012l5.306,5.433c0.304,0.31,0.296,0.805-0.012,1.105L7.83,15.928c-0.152,0.148-0.35,0.223-0.547,0.223c-0.203,0-0.406-0.08-0.559-0.236c-0.303-0.309-0.295-0.803,0.012-1.104L11.611,10.049z"}))}},202:function(e,t,a){"use strict";var n=a(212),r=a(0),c=a.n(r),l=a(205),i=a.n(l);function s(e){var t=e.description,a=e.lang,r=e.meta,l=e.title,s=e.image,o=n.data.site,u=t||o.siteMetadata.description,m=s||o.siteMetadata.logo;return c.a.createElement(i.a,{htmlAttributes:{lang:a},title:l,titleTemplate:l===o.siteMetadata.title?l:"%s | "+o.siteMetadata.title,meta:[{name:"description",content:u},{property:"og:title",content:l},{property:"og:description",content:u},{property:"og:type",content:"website"},{name:"twitter:card",content:"summary"},{name:"twitter:creator",content:o.siteMetadata.author},{name:"twitter:title",content:l},{name:"twitter:description",content:u},{name:"og:image",content:m}].concat(r)})}s.defaultProps={lang:"en",meta:[],description:""},t.a=s},203:function(e,t,a){"use strict";var n=a(0),r=a.n(n),c=a(206),l=a(205),i=a.n(l);var s=function(){var e=c.data;return r.a.createElement(i.a,{bodyAttributes:{class:e.site.siteMetadata.darkmode?"dark-mode":""}},r.a.createElement("link",{rel:"icon",href:e.site.siteMetadata.icon,type:"image/png"}),r.a.createElement("link",{rel:"stylesheet",type:"text/css",href:"https://cdn.jsdelivr.net/gh/akzhy/trunk/dist/trunk.min.css"}),r.a.createElement("link",{href:"https://fonts.googleapis.com/css?family=Work+Sans:800|Poppins&display=swap",rel:"stylesheet"}))},o=a(217),u=(a(49),a(38),a(207)),m=a(19).globalHistory.location.pathname;function d(e){var t=e.data,a={href:t.url,className:"/"+m===t.url?"active":"",title:t.name};return r.a.createElement("li",null,r.a.createElement("a",a,r.a.createElement("span",null,t.name)))}"/"!==m&&(m=(m=m.split("/"))[1]);var p=function(){var e=u.data.site.siteMetadata.navLinks,t=[];return e.forEach(function(e,a){t.push(r.a.createElement(d,{key:e.url+"-"+a,data:e}))}),r.a.createElement("ul",{className:"navbar-links"},t)},v=a(204),f=a(209),h=function(){var e=f.data;return r.a.createElement("img",{className:"logo",src:e.site.siteMetadata.logo,alt:e.site.siteMetadata.title})},g=a(201);a(218);function E(e){if(void 0===e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return e}function M(){return r.a.createElement("div",{className:"sidebar-contents"},r.a.createElement("div",{className:"logo"},r.a.createElement("a",{href:"/"},r.a.createElement(h,null))),r.a.createElement("div",{className:"links text-secondary"},r.a.createElement(p,null)),r.a.createElement("div",{className:"social-links"},r.a.createElement(v.a,null)))}var b=function(e){var t,a;function n(t){var a;return(a=e.call(this,t)||this).state={navbarPlaceholderHeight:100,sidebarOpen:!1},a.onSetSidebarOpen=a.onSetSidebarOpen.bind(E(a)),a.menuOpen=a.menuOpen.bind(E(a)),a}a=e,(t=n).prototype=Object.create(a.prototype),t.prototype.constructor=t,t.__proto__=a;var c=n.prototype;return c.onSetSidebarOpen=function(e){this.setState({sidebarOpen:e})},c.menuOpen=function(e){e.preventDefault(),this.onSetSidebarOpen(!0)},c.componentDidMount=function(){this.changeNavbarPlaceholderHeight();var e=this.nav.querySelector(".logo"),t=this;e.addEventListener("load",function(){t.changeNavbarPlaceholderHeight()}),this.changeNavbarHeight()},c.changeNavbarHeight=function(){window.addEventListener("scroll",function(){this.scrollY>0?document.querySelector("nav").classList.add("scrolled"):document.querySelector("nav").classList.remove("scrolled")})},c.changeNavbarPlaceholderHeight=function(){var e=document.querySelector("nav").offsetHeight;this.setState({navbarPlaceholderHeight:e})},c.render=function(){var e=this,t=this.props.placeholder;return r.a.createElement(r.a.Fragment,null,r.a.createElement(o.a,{sidebar:r.a.createElement(M,null),open:this.state.sidebarOpen,onSetOpen:this.onSetSidebarOpen,sidebarClassName:"sidebar-content",styles:{sidebar:{zIndex:101,position:"fixed"},overlay:{zIndex:100},dragHandle:{position:"fixed",zIndex:"99999"}}},r.a.createElement("span",null)),r.a.createElement("nav",{className:"text-secondary",ref:function(t){return e.nav=t}},r.a.createElement("a",{href:"#mobilenav",id:"menu-open",onClick:this.menuOpen},r.a.createElement("span",{className:"icon"},r.a.createElement(g.e,null))),r.a.createElement("a",{href:"/"},r.a.createElement(h,null)),r.a.createElement(p,null)),t&&r.a.createElement("div",{className:"navbar-placeholder",style:{height:this.state.navbarPlaceholderHeight+"px"}}))},n}(r.a.Component),w=a(210),y=a(211);function N(e){var t=e.data,a={href:t.url,title:t.name};return r.a.createElement("li",null,r.a.createElement("a",a,r.a.createElement("span",null,t.name)))}var S=function(){var e=y.data.site.siteMetadata.footerLinks,t=[];return e.forEach(function(e,a){t.push(r.a.createElement(N,{key:e.url+"-"+a,data:e}))}),r.a.createElement("ul",{className:"navbar-links"},t)},z=(a(219),function(){var e=w.data;return r.a.createElement("footer",{className:"footer"},r.a.createElement("div",{className:"container"},r.a.createElement("div",{className:"logo"},r.a.createElement("a",{href:"/",title:e.site.siteMetadata.title},r.a.createElement(h,null))),r.a.createElement("div",{className:"navlinks text-secondary"},r.a.createElement(p,null)),r.a.createElement("div",{className:"navlinks text-secondary",style:{marginTop:"20px"}},r.a.createElement(S,null)),r.a.createElement("p",{className:"text-primary f-d"},"Copyright © ",e.site.siteMetadata.title," ",(new Date).getFullYear())))});t.a=function(e){var t=e.placeholder,a=e.children;return r.a.createElement(r.a.Fragment,null,r.a.createElement(s,null),r.a.createElement(b,{placeholder:void 0===t||t}),r.a.createElement("div",{className:"wrapper"},a),r.a.createElement(z,null))}},204:function(e,t,a){"use strict";a(49);var n=a(208),r=a(0),c=a.n(r);function l(e){var t=e.data;return c.a.createElement("li",null,c.a.createElement("a",{href:t.url,title:t.name},c.a.createElement("img",{src:t.icon,alt:t.name})))}t.a=function(){var e=n.data.site.siteMetadata.social,t=[];return e.forEach(function(e,a){t.push(c.a.createElement(l,{key:e.url+"-"+e.icon+"-"+a,data:e}))}),c.a.createElement("ul",{className:"social-links"},t)}},206:function(e){e.exports=JSON.parse('{"data":{"site":{"siteMetadata":{"darkmode":true,"icon":"/images/icon.png"}}}}')},207:function(e){e.exports=JSON.parse('{"data":{"site":{"siteMetadata":{"navLinks":[{"name":"HOME","url":"/"},{"name":"ABOUT","url":"/about"},{"name":"SKILLS","url":"/skills"},{"name":"BLOG","url":"/blog"},{"name":"CONTACT","url":"/contact"}]}}}}')},208:function(e){e.exports=JSON.parse('{"data":{"site":{"siteMetadata":{"social":[{"name":"Twitter","url":"https://twitter.com/iamaldrew","icon":"/images/Twitter.svg"},{"name":"Instagram","url":"https://www.instagram.com/iamaldrew","icon":"/images/Instagram.svg"},{"name":"LinkedIn","url":"https://www.linkedin.com/in/aldren-bobiles","icon":"/images/LinkedIn.svg"},{"name":"GitHub","url":"https://github.com/iamaldren","icon":"/images/GitHub.svg"}]}}}}')},209:function(e){e.exports=JSON.parse('{"data":{"site":{"siteMetadata":{"title":"Aldren Bobiles","logo":"/images/logo.png"}}}}')},210:function(e){e.exports=JSON.parse('{"data":{"site":{"siteMetadata":{"title":"Aldren Bobiles"}}}}')},211:function(e){e.exports=JSON.parse('{"data":{"site":{"siteMetadata":{"footerLinks":[{"name":"PRIVACY POLICY","url":"/privacy-policy"}]}}}}')},212:function(e){e.exports=JSON.parse('{"data":{"site":{"siteMetadata":{"title":"Aldren Bobiles","description":"(This is a Work in Progress)","author":"@iamaldren","logo":"/images/logo.png"}}}}')},215:function(e,t,a){var n;e.exports=(n=a(223))&&n.default||n},222:function(e,t,a){"use strict";a.d(t,"b",function(){return o});var n=a(0),r=a.n(n),c=a(66),l=a.n(c);a.d(t,"a",function(){return l.a});a(215),a(7).default.enqueue;var i=r.a.createContext({});function s(e){var t=e.staticQueryData,a=e.data,n=e.query,c=e.render,l=a?a.data:t[n]&&t[n].data;return r.a.createElement(r.a.Fragment,null,l&&c(l),!l&&r.a.createElement("div",null,"Loading (StaticQuery)"))}var o=function(e){var t=e.data,a=e.query,n=e.render,c=e.children;return r.a.createElement(i.Consumer,null,function(e){return r.a.createElement(s,{data:t,query:a,render:n||c,staticQueryData:e})})}},223:function(e,t,a){"use strict";a.r(t);a(18);var n=a(0),r=a.n(n),c=a(92);t.default=function(e){var t=e.location,a=e.pageResources;return a?r.a.createElement(c.a,Object.assign({location:t,pageResources:a},a.json)):null}}}]);
//# sourceMappingURL=component---src-pages-page-2-js-5a5e84d761537a4c596e.js.map |
describe('Nodes Detail Page', function () {
beforeEach(function () {
cy.configureCluster({
mesos: '1-task-healthy',
nodeHealth: true
})
});
context('Navigate to node detail page', function () {
it('navigates to node detail page', function () {
cy.visitUrl({url: '/nodes', identify: true, fakeAnalytics: true});
var nodeName;
cy.get('tr a').eq(0).should(function ($row) {
nodeName = $row[0].textContent;
}).click();
cy.hash().should('match', /nodes\/[a-zA-Z0-9-]+/);
cy.get('.page-content h1').should(function ($title) {
expect($title).to.contain(nodeName);
});
});
it('shows error in node detail page when node is invalid [10a]', function () {
cy.visitUrl({url: '/nodes/INVALID_NODE', identify: true, fakeAnalytics: true});
cy.hash().should('match', /nodes\/INVALID_NODE/);
cy.get('.page-content h3').should(function ($title) {
expect($title).to.contain('Error finding node');
});
});
});
});
|
// ecma.js
import commonJs from './common-js'
console.log('Requiring a CommonJS'
+ ' from ecma:')
console.log(commonJs)
// The default import
// using the import keyword 🙏🏾
// 2018+ JavaScript <3 |
import sys
import asyncio
import warnings
from . import hdrs
from .errors import HttpProcessingError, ClientDisconnectedError
from .websocket import do_handshake, Message, WebSocketError
from .websocket_client import MsgType, closedMessage
from .web_exceptions import (
HTTPBadRequest, HTTPMethodNotAllowed, HTTPInternalServerError)
from .web_reqrep import StreamResponse
__all__ = ('WebSocketResponse', 'MsgType')
PY_35 = sys.version_info >= (3, 5)
THRESHOLD_CONNLOST_ACCESS = 5
class WebSocketResponse(StreamResponse):
def __init__(self, *,
timeout=10.0, autoclose=True, autoping=True, protocols=()):
super().__init__(status=101)
self._protocols = protocols
self._protocol = None
self._writer = None
self._reader = None
self._closed = False
self._closing = False
self._conn_lost = 0
self._close_code = None
self._loop = None
self._waiting = False
self._exception = None
self._timeout = timeout
self._autoclose = autoclose
self._autoping = autoping
@asyncio.coroutine
def prepare(self, request):
# make pre-check to don't hide it by do_handshake() exceptions
resp_impl = self._start_pre_check(request)
if resp_impl is not None:
return resp_impl
parser, protocol, writer = self._pre_start(request)
resp_impl = yield from super().prepare(request)
self._post_start(request, parser, protocol, writer)
return resp_impl
def _pre_start(self, request):
try:
status, headers, parser, writer, protocol = do_handshake(
request.method, request.headers, request.transport,
self._protocols)
except HttpProcessingError as err:
if err.code == 405:
raise HTTPMethodNotAllowed(
request.method, [hdrs.METH_GET], body=b'')
elif err.code == 400:
raise HTTPBadRequest(text=err.message, headers=err.headers)
else: # pragma: no cover
raise HTTPInternalServerError() from err
if self.status != status:
self.set_status(status)
for k, v in headers:
self.headers[k] = v
self.force_close()
return parser, protocol, writer
def _post_start(self, request, parser, protocol, writer):
self._reader = request._reader.set_parser(parser)
self._writer = writer
self._protocol = protocol
self._loop = request.app.loop
def start(self, request):
warnings.warn('use .prepare(request) instead', DeprecationWarning)
# make pre-check to don't hide it by do_handshake() exceptions
resp_impl = self._start_pre_check(request)
if resp_impl is not None:
return resp_impl
parser, protocol, writer = self._pre_start(request)
resp_impl = super().start(request)
self._post_start(request, parser, protocol, writer)
return resp_impl
def can_prepare(self, request):
if self._writer is not None:
raise RuntimeError('Already started')
try:
_, _, _, _, protocol = do_handshake(
request.method, request.headers, request.transport,
self._protocols)
except HttpProcessingError:
return False, None
else:
return True, protocol
def can_start(self, request):
warnings.warn('use .can_prepare(request) instead', DeprecationWarning)
return self.can_prepare(request)
@property
def closed(self):
return self._closed
@property
def close_code(self):
return self._close_code
@property
def protocol(self):
return self._protocol
def exception(self):
return self._exception
def ping(self, message='b'):
if self._writer is None:
raise RuntimeError('Call .prepare() first')
if self._closed:
raise RuntimeError('websocket connection is closing')
self._writer.ping(message)
def pong(self, message='b'):
# unsolicited pong
if self._writer is None:
raise RuntimeError('Call .prepare() first')
if self._closed:
raise RuntimeError('websocket connection is closing')
self._writer.pong(message)
def send_str(self, data):
if self._writer is None:
raise RuntimeError('Call .prepare() first')
if self._closed:
raise RuntimeError('websocket connection is closing')
if not isinstance(data, str):
raise TypeError('data argument must be str (%r)' % type(data))
self._writer.send(data, binary=False)
def send_bytes(self, data):
if self._writer is None:
raise RuntimeError('Call .prepare() first')
if self._closed:
raise RuntimeError('websocket connection is closing')
if not isinstance(data, (bytes, bytearray, memoryview)):
raise TypeError('data argument must be byte-ish (%r)' %
type(data))
self._writer.send(data, binary=True)
@asyncio.coroutine
def wait_closed(self): # pragma: no cover
warnings.warn(
'wait_closed() coroutine is deprecated. use close() instead',
DeprecationWarning)
return (yield from self.close())
@asyncio.coroutine
def write_eof(self):
if self._eof_sent:
return
if self._resp_impl is None:
raise RuntimeError("Response has not been started")
yield from self.close()
self._eof_sent = True
@asyncio.coroutine
def close(self, *, code=1000, message=b''):
if self._writer is None:
raise RuntimeError('Call .prepare() first')
if not self._closed:
self._closed = True
try:
self._writer.close(code, message)
except (asyncio.CancelledError, asyncio.TimeoutError):
self._close_code = 1006
raise
except Exception as exc:
self._close_code = 1006
self._exception = exc
return True
if self._closing:
return True
while True:
try:
msg = yield from asyncio.wait_for(
self._reader.read(),
timeout=self._timeout, loop=self._loop)
except asyncio.CancelledError:
self._close_code = 1006
raise
except Exception as exc:
self._close_code = 1006
self._exception = exc
return True
if msg.tp == MsgType.close:
self._close_code = msg.data
return True
else:
return False
@asyncio.coroutine
def receive(self):
if self._reader is None:
raise RuntimeError('Call .prepare() first')
if self._waiting:
raise RuntimeError('Concurrent call to receive() is not allowed')
self._waiting = True
try:
while True:
if self._closed:
self._conn_lost += 1
if self._conn_lost >= THRESHOLD_CONNLOST_ACCESS:
raise RuntimeError('WebSocket connection is closed.')
return closedMessage
try:
msg = yield from self._reader.read()
except (asyncio.CancelledError, asyncio.TimeoutError):
raise
except WebSocketError as exc:
self._close_code = exc.code
yield from self.close(code=exc.code)
return Message(MsgType.error, exc, None)
except ClientDisconnectedError:
self._closed = True
self._close_code = 1006
return Message(MsgType.close, None, None)
except Exception as exc:
self._exception = exc
self._closing = True
self._close_code = 1006
yield from self.close()
return Message(MsgType.error, exc, None)
if msg.tp == MsgType.close:
self._closing = True
self._close_code = msg.data
if not self._closed and self._autoclose:
yield from self.close()
return msg
elif not self._closed:
if msg.tp == MsgType.ping and self._autoping:
self._writer.pong(msg.data)
elif msg.tp == MsgType.pong and self._autoping:
continue
else:
return msg
finally:
self._waiting = False
@asyncio.coroutine
def receive_msg(self):
warnings.warn(
'receive_msg() coroutine is deprecated. use receive() instead',
DeprecationWarning)
return (yield from self.receive())
@asyncio.coroutine
def receive_str(self):
msg = yield from self.receive()
if msg.tp != MsgType.text:
raise TypeError(
"Received message {}:{!r} is not str".format(msg.tp, msg.data))
return msg.data
@asyncio.coroutine
def receive_bytes(self):
msg = yield from self.receive()
if msg.tp != MsgType.binary:
raise TypeError(
"Received message {}:{!r} is not bytes".format(msg.tp,
msg.data))
return msg.data
def write(self, data):
raise RuntimeError("Cannot call .write() for websocket")
if PY_35:
@asyncio.coroutine
def __aiter__(self):
return self
@asyncio.coroutine
def __anext__(self):
msg = yield from self.receive()
if msg.tp == MsgType.close:
raise StopAsyncIteration # NOQA
return msg
|
import Ember from 'ember';
import RSVP from 'rsvp';
const { computed } = Ember;
export default Ember.Mixin.create({
showDropzone: computed.or('draggingOver', 'processingDrop'),
dragEnter() {
this.set('draggingOver', true);
},
dragOver(evt) {
evt.preventDefault();
},
drop(evt) {
evt.preventDefault();
this.set('draggingOver', false);
this.processDrops(evt.originalEvent);
},
readFile(file) {
const reader = new FileReader();
return new RSVP.Promise(resolve => {
reader.onloadend = resolve;
reader.readAsText(file);
});
},
readJSONFile(file) {
return this.readFile(file).then(read => {
try {
return RSVP.resolve(JSON.parse(read.target.result));
} catch (err) {
return RSVP.reject(err);
}
});
},
readTextFile(file) {
return this.readFile(file).then(read => {
try {
return RSVP.resolve(read.target.result);
} catch (err) {
return RSVP.reject(err);
}
});
},
processDrops: Ember.K,
readTemplates(dataTransfer) {
const files = Array.from(dataTransfer.files).filter(isJSONFile);
const reads = files.map(file => this.readJSONFile(file));
return RSVP.all(reads);
},
readMarkdownFiles(dataTransfer) {
const files = Array.from(dataTransfer.files).filter(isMarkdownFile);
const reads = files.map(file => this.readTextFile(file));
return RSVP.all(reads);
}
});
function isCanvasFile({ name }) {
return name.split('.').pop() === 'canvas';
}
function isMarkdownFile({ name }) {
return ['md', 'markdown'].includes(name.split('.').pop());
}
function isJSONFile(file) {
return file.type === 'application/json' || isCanvasFile(file);
}
|
console.log(module.exports) // já existe um objeto criado module.exports que é o principal
console.log(module.exports === this) // os outros estão referenciados para adicionar a ele
console.log(module.exports === exports)
this.a = 1
exports.b = 2
module.exports.c = 3
console.log(exports)
exports = null // mas se tentarem sobrepor o objeto module.exports o seu referencial é quem muda
console.log(exports)
console.log(module.exports)
exports = {
nome: 'Teste'
}
console.log(exports)
console.log(module.exports)
exports.d = 4 // e passam a ter um objeto próprio não mais fazendo referência a module.exports
console.log(exports)
console.log(module.exports)
module.exports = {publico: true} // apenas sendo possível alterar o objeto base através de module.exports
console.log(exports)
console.log(module.exports) |
from app import db
from collections import namedtuple, Counter
from enum import Enum, auto
from typing import Optional, List, Set
Ship = namedtuple('Ship', ['name', 'symbol', 'size'])
symbol_to_ship = {
'C': Ship('Carrier', 'C', 5),
'B': Ship('Battleship', 'B', 4),
'R': Ship('Cruiser', 'R', 3),
'S': Ship('Submarine', 'S', 3),
'D': Ship('Destroyer', 'D', 2)
}
class Board(db.Model):
SIZE = 10
HIT, MISS, SUNK = '+', '-', 'x'
ACTIONS = {HIT, MISS, SUNK}
NO_ACTION = '.'
__tablename__ = 'boards'
id = db.Column(db.Integer, primary_key=True)
starting_grid = db.Column(db.String(100))
grid = db.Column(db.String(100))
player = db.relationship('Player', back_populates='board')
player_id = db.Column(db.Integer, db.ForeignKey('players.id'))
def __init__(self, starting_grid: str):
self.validate_starting_grid(starting_grid)
super().__init__(starting_grid=starting_grid,
grid=starting_grid)
def enemy_view(self) -> str:
"""How enemy views this board."""
if self.no_ships(): return self.grid
return ''.join([self.grid[xy] if self.grid[xy] in Board.ACTIONS else ' ' for xy in range(Board.SIZE * Board.SIZE)])
def can_shoot_at(self, x: int, y: int) -> bool:
"""Is it legal to shoot at field."""
xy = self._to_1d(x, y)
return self.grid[xy] == self.starting_grid[xy]
def shoot(self, x: int, y: int) -> str:
"""Shoot at a field and return string with a result.
Returns:
Result of an action as string
- Miss
- Hit {ship_name}
- Sunk {ship_name}
Raises:
ValueError if action can't take place on this field (x,y was already shot at).
"""
if not self.can_shoot_at(x, y): raise ValueError(f"Field ({x}, {y}) was already acted upon.")
xy = self._to_1d(x, y)
if self.grid[xy] == Board.NO_ACTION:
self.grid = self.grid[:xy] + self.MISS + self.grid[xy + 1:]
return 'Miss'
else:
symbol = self.grid[xy]
self.grid = self.grid[:xy] + self.HIT + self.grid[xy + 1:]
if symbol in self.grid:
return f'Hit {symbol_to_ship[symbol].name}'
else:
self.grid = ''.join([self.grid[i] if self.starting_grid[i] != symbol else self.SUNK for i in range(Board.SIZE * Board.SIZE)])
return f'Sunk {symbol_to_ship[symbol].name}'
def no_ships(self) -> bool:
"""All ships sunk?"""
return set(self.grid) <= Board.ACTIONS | set(Board.NO_ACTION)
def remaining_ships(self) -> Set[str]:
"""Return set of symbols of remaining ships."""
return set(self.grid) & set(symbol_to_ship.keys())
def sunk_ships(self) -> Set[str]:
"""Return set of symbols of sunk ships."""
return set(symbol_to_ship.keys()) - self.remaining_ships()
@staticmethod
def _to_1d(x: int, y: int) -> int: return y*Board.SIZE + x
@staticmethod
def grid_as_matrix(grid) -> List[str]:
"""Transforms grid into 2d representation."""
return [grid[i:i + Board.SIZE] for i in range(0, len(grid), Board.SIZE)]
@staticmethod
def validate_starting_grid(grid: str):
"""Raises ValueError if grid is not valid starting grid.
Valid starting grid has:
- len == 100
- only ships and empty fields
- ships are of valid sizes
- ships are placed horizontally or vertically
Raises:
ValueError if one of the conditions is not True.
"""
counter = Counter(grid)
if len(grid) != Board.SIZE * Board.SIZE:
raise ValueError(f"Grid has to be of length 100.")
for _, v in symbol_to_ship.items():
if v.size != counter[v.symbol]:
raise ValueError(f"Grid has ships of illegal sizes.")
if set(grid) != (set(symbol_to_ship.keys()) | set(Board.NO_ACTION)):
raise ValueError(f"Grid has more than ships and empty fields.")
for symbol, s in symbol_to_ship.items():
g = Board.grid_as_matrix(grid)
row, col = divmod(grid.index(symbol), Board.SIZE)
symbols_in_row = g[row].count(symbol)
if symbols_in_row == 1: # must be vertically placed
g = [''.join(r) for r in zip(*g)] # transposing matrix to make horizontal placement out of vertical
for r in range(Board.SIZE):
if symbol in g[r]:
row, col = r, g[r].index(symbol) # new row, col pair of a first symbol
break
if col + s.size > Board.SIZE or g[row][col:col+s.size] != symbol * s.size:
raise ValueError(f"Ship {s.symbol} is not placed correctly.")
class Player(db.Model):
"""Player ties name and board together."""
__tablename__ = 'players'
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(50))
board = db.relationship('Board', back_populates='player', uselist=False)
game_id = db.Column(db.Integer, db.ForeignKey('games.id'))
game = db.relationship('Game', back_populates='players')
class Game(db.Model):
"""Game is an object which couples players and their actions.
When both players are in game, they shoot in turns until one of the players have no ships.
Once the game is finished no player can shoot.
At first game is in State.NEW. After another player joins in, it is in State.PLAYING. When one of the players have
no ships left it switches to State.FINISHED.
"""
class State(Enum):
NEW = auto()
PLAYING = auto()
FINISHED = auto()
__tablename__ = 'games'
id = db.Column(db.Integer, primary_key=True)
state = db.Column(db.Enum(State))
players = db.relationship('Player', back_populates='game', order_by='Player.id')
current_idx = db.Column(db.Integer)
def __init__(self):
super().__init__()
self.state = self.State.NEW
@property
def current(self):
return self.players[self.current_idx] if len(self.players) else None
@property
def other(self):
return self.players[(self.current_idx + 1) % 2] if len(self.players) == 2 else None
def join(self, player: Player):
"""Join new player to the game."""
if self.state != self.State.NEW:
raise ValueError(f"Can't join players when game is not in state NEW. State={self.state}")
if self.current_idx is None:
self.current_idx = 0
elif self.players[self.current_idx].id is None:
raise ValueError("No database id for current player - commit first.")
elif self.players[self.current_idx].id == player.id:
raise ValueError("Player can't join the same game twice.")
else:
self.state = self.State.PLAYING
player.game = self
def shoot(self, player_name: str, x: int, y: int) -> str:
"""Try to shoot as player.
Returns:
Action result as a string.
Raises:
ValueError if shot cannot be taken.
"""
if self.state != self.State.PLAYING:
raise ValueError(f"Game is in state '{self.state}' - can't shoot.")
if self.current.name != player_name:
raise ValueError(f"It's '{self.current.name}' turn")
result = self.other.board.shoot(x, y)
if self.other.board.no_ships():
self.state = self.State.FINISHED
else:
self.current_idx = (self.current_idx + 1) % 2
return result
def winner(self) -> Optional[Player]:
return self.current if self.state == self.State.FINISHED else None
def save_to_db(self):
db.session.add(self)
db.session.commit()
@staticmethod
def get_new_game():
g = Game.query.filter_by(state=Game.State.NEW).first()
if g is None:
g = Game()
return g |
import Cascader from './cascader.vue';
export default Cascader; |
/**
* Copyright © 2015 Magento. All rights reserved.
* See COPYING.txt for license details.
*/
//require([
// 'jquery',
// 'bootstrap/js/bootstrap.min'
//], function ($) {
//});
require([
'jquery',
'mage/smart-keyboard-handler',
'mage/mage',
'mage/ie-class-fixer',
'domReady!'
], function ($, keyboardHandler) {
'use strict';
$(document).ready(function(){
$('.cart-summary').mage('sticky', {
container: '#maincontent'
});
$('.panel.header .header.links').clone().appendTo('#store\\.links');
});
keyboardHandler.apply();
});
/******************** Init Parallax ***********************/
require([
'jquery',
'js/jquery.stellar.min'
], function ($) {
$(document).ready(function(){
$(window).stellar({
responsive: true,
scrollProperty: 'scroll',
parallaxElements: false,
horizontalScrolling: false,
horizontalOffset: 0,
verticalOffset: 0
});
});
});
require([
'jquery'
], function ($) {
(function() {
var ev = new $.Event('classadded'),
orig = $.fn.addClass;
$.fn.addClass = function() {
$(this).trigger(ev, arguments);
return orig.apply(this, arguments);
}
})();
$.fn.extend({
scrollToMe: function(){
if($(this).length){
var top = $(this).offset().top - 100;
$('html,body').animate({scrollTop: top}, 300);
}
},
scrollToJustMe: function(){
if($(this).length){
var top = jQuery(this).offset().top;
$('html,body').animate({scrollTop: top}, 300);
}
}
});
$(document).ready(function(){
var windowScroll_t;
$(window).scroll(function(){
clearTimeout(windowScroll_t);
windowScroll_t = setTimeout(function(){
if(jQuery(this).scrollTop() > 100){
$('#totop').fadeIn();
}else{
$('#totop').fadeOut();
}
}, 500);
});
$('#totop').off("click").on("click",function(){
$('html, body').animate({scrollTop: 0}, 600);
});
if ($('body').hasClass('checkout-cart-index')) {
if ($('#co-shipping-method-form .fieldset.rates').length > 0 && $('#co-shipping-method-form .fieldset.rates :checked').length === 0) {
$('#block-shipping').on('collapsiblecreate', function () {
$('#block-shipping').collapsible('forceActivate');
});
}
}
$(".products-grid .weltpixel-quickview").each(function(){
$(this).appendTo($(this).parent().parent().children(".product-item-photo"));
});
$(".word-rotate").each(function() {
var $this = $(this),
itemsWrapper = $(this).find(".word-rotate-items"),
items = itemsWrapper.find("> span"),
firstItem = items.eq(0),
firstItemClone = firstItem.clone(),
itemHeight = 0,
currentItem = 1,
currentTop = 0;
itemHeight = firstItem.height();
itemsWrapper.append(firstItemClone);
$this
.height(itemHeight)
.addClass("active");
setInterval(function() {
currentTop = (currentItem * itemHeight);
itemsWrapper.animate({
top: -(currentTop) + "px"
}, 300, function() {
currentItem++;
if(currentItem > items.length) {
itemsWrapper.css("top", 0);
currentItem = 1;
}
});
}, 2000);
});
$(".top-links-icon").off("click").on("click", function(e){
if($(this).parent().children("ul.links").hasClass("show")) {
$(this).parent().children("ul.links").removeClass("show");
} else {
$(this).parent().children("ul.links").addClass("show");
}
e.stopPropagation();
});
$(".top-links-icon").parent().click(function(e){
e.stopPropagation();
});
$(".search-toggle-icon").click(function(e){
if($(this).parent().children(".block-search").hasClass("show")) {
$(this).parent().children(".block-search").removeClass("show");
} else {
$(this).parent().children(".block-search").addClass("show");
}
e.stopPropagation();
});
$(".search-toggle-icon").parent().click(function(e){
e.stopPropagation();
});
$("html,body").click(function(){
$(".search-toggle-icon").parent().children(".block-search").removeClass("show");
$(".top-links-icon").parent().children("ul.links").removeClass("show");
});
/********************* Qty Holder **************************/
$(document).on("click", ".qtyplus", function(e) {
// Stop acting like a button
e.preventDefault();
// Get its current value
var currentVal = parseInt($(this).parents('form').find('input[name="qty"]').val());
// If is not undefined
if (!isNaN(currentVal)) {
// Increment
$(this).parents('form').find('input[name="qty"]').val(currentVal + 1);
} else {
// Otherwise put a 0 there
$(this).parents('form').find('input[name="qty"]').val(0);
}
});
// This button will decrement the value till 0
$(document).on("click", ".qtyminus", function(e) {
// Stop acting like a button
e.preventDefault();
// Get the field name
fieldName = $(this).attr('field');
// Get its current value
var currentVal = parseInt($(this).parents('form').find('input[name="qty"]').val());
// If it isn't undefined or its greater than 0
if (!isNaN(currentVal) && currentVal > 0) {
// Decrement one
$(this).parents('form').find('input[name="qty"]').val(currentVal - 1);
} else {
// Otherwise put a 0 there
$(this).parents('form').find('input[name="qty"]').val(0);
}
});
$(".qty-inc").unbind('click').click(function(){
if($(this).parents('.field.qty').find("input.input-text.qty").is(':enabled')){
$(this).parents('.field.qty').find("input.input-text.qty").val((+$(this).parents('.field.qty').find("input.input-text.qty").val() + 1) || 0);
$(this).parents('.field.qty').find("input.input-text.qty").trigger('change');
$(this).focus();
}
});
$(".qty-dec").unbind('click').click(function(){
if($(this).parents('.field.qty').find("input.input-text.qty").is(':enabled')){
$(this).parents('.field.qty').find("input.input-text.qty").val(($(this).parents('.field.qty').find("input.input-text.qty").val() - 1 > 0) ? ($(this).parents('.field.qty').find("input.input-text.qty").val() - 1) : 0);
$(this).parents('.field.qty').find("input.input-text.qty").trigger('change');
$(this).focus();
}
});
/********** Fullscreen Slider ************/
var s_width = $(window).outerWidth();
var s_height = $(window).outerHeight();
var s_ratio = s_width/s_height;
var v_width=320;
var v_height=240;
var v_ratio = v_width/v_height;
$(".full-screen-slider div.item").css("position","relative");
$(".full-screen-slider div.item").css("overflow","hidden");
$(".full-screen-slider div.item").width(s_width);
$(".full-screen-slider div.item").height(s_height);
$(".full-screen-slider div.item > video").css("position","absolute");
$(".full-screen-slider div.item > video").bind("loadedmetadata",function(){
v_width = this.videoWidth;
v_height = this.videoHeight;
v_ratio = v_width/v_height;
if(s_ratio>=v_ratio){
$(this).width(s_width);
$(this).height("");
$(this).css("left","0px");
$(this).css("top",(s_height-s_width/v_width*v_height)/2+"px");
}else{
$(this).width("");
$(this).height(s_height);
$(this).css("left",(s_width-s_height/v_height*v_width)/2+"px");
$(this).css("top","0px");
}
$(this).get(0).play();
});
if($(".page-header").hasClass("type10")) {
if(s_width >= 992){
$(".navigation").addClass("side-megamenu")
} else {
$(".navigation").removeClass("side-megamenu")
}
}
$(window).resize(function(){
s_width = $(window).innerWidth();
s_height = $(window).innerHeight();
s_ratio = s_width/s_height;
$(".full-screen-slider div.item").width(s_width);
$(".full-screen-slider div.item").height(s_height);
$(".full-screen-slider div.item > video").each(function(){
if(s_ratio>=v_ratio){
$(this).width(s_width);
$(this).height("");
$(this).css("left","0px");
$(this).css("top",(s_height-s_width/v_width*v_height)/2+"px");
}else{
$(this).width("");
$(this).height(s_height);
$(this).css("left",(s_width-s_height/v_height*v_width)/2+"px");
$(this).css("top","0px");
}
});
if($(".page-header").hasClass("type10")) {
if(s_width >= 992){
$(".navigation").addClass("side-megamenu")
} else {
$(".navigation").removeClass("side-megamenu")
}
}
});
var breadcrumb_pos_top = 0;
$(window).scroll(function(){
if(!$("body").hasClass("cms-index-index")){
var side_header_height = $(".page-header.type10, .page-header.type22").innerHeight();
var window_height = $(window).height();
if(side_header_height-window_height<$(window).scrollTop()){
if(!$(".page-header.type10, .page-header.type22").hasClass("fixed-bottom"))
$(".page-header.type10, .page-header.type22").addClass("fixed-bottom");
}
if(side_header_height-window_height>=$(window).scrollTop()){
if($(".page-header.type10, .page-header.type22").hasClass("fixed-bottom"))
$(".page-header.type10, .page-header.type22").removeClass("fixed-bottom");
}
}
if($("body.side-header .page-wrapper > .breadcrumbs").length){
if(!$("body.side-header .page-wrapper > .breadcrumbs").hasClass("fixed-position")){
breadcrumb_pos_top = $("body.side-header .page-wrapper > .breadcrumbs").offset().top;
if($("body.side-header .page-wrapper > .breadcrumbs").offset().top<$(window).scrollTop()){
$("body.side-header .page-wrapper > .breadcrumbs").addClass("fixed-position");
}
}else{
if($(window).scrollTop()<=1){
$("body.side-header .page-wrapper > .breadcrumbs").removeClass("fixed-position");
}
}
}
});
});
});
require([
'jquery',
'js/jquery.lazyload'
], function ($) {
$(document).ready(function(){
$("img.porto-lazyload:not(.porto-lazyload-loaded)").lazyload({effect:"fadeIn"});
if ($('.porto-lazyload:not(.porto-lazyload-loaded)').closest('.owl-carousel').length) {
$('.porto-lazyload:not(.porto-lazyload-loaded)').closest('.owl-carousel').on('changed.owl.carousel', function() {
$(this).find('.porto-lazyload:not(.porto-lazyload-loaded)').trigger('appear');
});
$('.porto-lazyload:not(.porto-lazyload-loaded)').closest('.owl-carousel').on('initialized.owl.carousel', function() {
$(this).find('.porto-lazyload:not(.porto-lazyload-loaded)').trigger('appear');
});
}
window.setTimeout(function(){
$('.sidebar-filterproducts').find('.porto-lazyload:not(.porto-lazyload-loaded)').trigger('appear');
},500);
});
}); |
import o from"./LockPage.38f42d3b.js";import{u as e}from"./lock.da1b51d8.js";import{k as t,f as a,K as r,o as s,n,Q as d,X as c,T as m}from"./vendor.9d9efc92.js";import"./index.734d8392.js";import"./header.d801b988.js";var u=t({name:"Lock",components:{LockPage:o},setup(){const o=e();return{getIsLock:a((()=>{var e,t;return null!=(t=null==(e=null==o?void 0:o.getLockInfo)?void 0:e.isLock)&&t}))}}});u.render=function(o,e,t,a,u,f){const i=r("LockPage");return s(),n(m,{name:"fade-bottom",mode:"out-in"},{default:d((()=>[o.getIsLock?(s(),n(i,{key:0})):c("",!0)])),_:1})};export default u;
|
# -*- coding: utf-8 -*- #
# Copyright 2017 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.
"""Command for updating interconnects."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.api_lib.compute import base_classes
from googlecloudsdk.api_lib.compute.interconnects import client
from googlecloudsdk.calliope import base
from googlecloudsdk.command_lib.compute.interconnects import flags
from googlecloudsdk.command_lib.util.args import labels_util
def _ArgsCommon(cls, parser, support_labels=False):
"""Shared arguments for update commands."""
cls.INTERCONNECT_ARG = flags.InterconnectArgument()
cls.INTERCONNECT_ARG.AddArgument(parser, operation_type='update')
parser.add_argument(
'--description',
help='An optional, textual description for the interconnect.')
flags.AddAdminEnabledForUpdate(parser)
flags.AddNocContactEmail(parser)
flags.AddRequestedLinkCountForUpdate(parser)
if support_labels:
labels_util.AddUpdateLabelsFlags(parser)
@base.ReleaseTracks(base.ReleaseTrack.GA)
class Update(base.UpdateCommand):
"""Update a Google Compute Engine interconnect.
*{command}* is used to update interconnects. An interconnect represents a
single specific connection between Google and the customer.
"""
INTERCONNECT_ARG = None
@classmethod
def Args(cls, parser):
_ArgsCommon(cls, parser)
def Collection(self):
return 'compute.interconnects'
def _DoRun(self, args, support_labels=False):
holder = base_classes.ComputeApiHolder(self.ReleaseTrack())
ref = self.INTERCONNECT_ARG.ResolveAsResource(args, holder.resources)
interconnect = client.Interconnect(ref, compute_client=holder.client)
labels = None
label_fingerprint = None
if support_labels:
labels_diff = labels_util.Diff.FromUpdateArgs(args)
if labels_diff.MayHaveUpdates():
old_interconnect = interconnect.Describe()
labels = labels_diff.Apply(
holder.client.messages.Interconnect.LabelsValue,
old_interconnect.labels).GetOrNone()
if labels is not None:
label_fingerprint = old_interconnect.labelFingerprint
return interconnect.Patch(
description=args.description,
interconnect_type=None,
requested_link_count=args.requested_link_count,
link_type=None,
admin_enabled=args.admin_enabled,
noc_contact_email=args.noc_contact_email,
location=None,
labels=labels,
label_fingerprint=label_fingerprint
)
def Run(self, args):
self._DoRun(args)
@base.ReleaseTracks(base.ReleaseTrack.ALPHA, base.ReleaseTrack.BETA)
class UpdateLabels(Update):
"""Update a Google Compute Engine interconnect.
*{command}* is used to update interconnects. An interconnect represents a
single specific connection between Google and the customer.
"""
@classmethod
def Args(cls, parser):
_ArgsCommon(cls, parser, support_labels=True)
def Run(self, args):
self._DoRun(args, support_labels=True)
|
import warnings
from chainer.backends import cuda
from chainer.functions.array import broadcast
from chainer.functions.array import reshape
from chainer.functions.normalization import batch_normalization
def group_normalization(x, groups, gamma, beta, eps=1e-5):
"""Group normalization function.
This function implements a "group normalization"
which divides the channels into groups and computes within each group
the mean and variance, then normalize by these statistics,
scales and shifts them.
Args:
x (:class:`~chainer.Variable` or :class:`numpy.ndarray` or \
:class:`cupy.ndarray`): Batch tensors.
First dimension of this value must be the size of minibatch and
second dimension must be the number of channels.
Moreover, this value must have one or more following dimensions,
such as height and width.
groups (int):
The number of channel groups.
This value must be a divisor of the number of channels.
gamma (~chainer.Variable): Scaling parameter.
beta (~chainer.Variable): Shifting parameter.
eps (float): Epsilon value for numerical stability of normalization.
Returns:
~chainer.Variable: The output variable which has the same shape
as :math:`x`.
See: `Group Normalization <https://arxiv.org/abs/1803.08494>`_
"""
if x.ndim <= 2:
raise ValueError('Input dimension must be grater than 2, '
'including batch size dimension '
'(first dimension).')
if not isinstance(groups, int):
raise TypeError('Argument: \'groups\' type must be (int).')
xp = cuda.get_array_module(x)
batch_size, channels = x.shape[:2]
original_shape = x.shape
if channels % groups != 0:
raise ValueError('Argument: \'groups\' must be a divisor '
'of the number of channel.')
# By doing this reshaping, calling batch_normalization function becomes
# equivalent to Group Normalization.
# And redundant dimension is added in order to utilize ideep64/cuDNN.
x = reshape.reshape(x, (1, batch_size * groups, -1, 1))
with cuda.get_device_from_array(x.array):
dummy_gamma = xp.ones(batch_size * groups).astype(xp.float32)
dummy_beta = xp.zeros(batch_size * groups).astype(xp.float32)
with warnings.catch_warnings():
warnings.simplefilter("ignore")
x = batch_normalization.batch_normalization(
x, dummy_gamma, dummy_beta, eps=eps)
x = reshape.reshape(x, original_shape)
target_shape = [1, channels] + [1] * (x.ndim - 2)
gamma_broadcast = broadcast.broadcast_to(
reshape.reshape(gamma, target_shape), x.shape)
beta_broadcast = broadcast.broadcast_to(
reshape.reshape(beta, target_shape), x.shape)
return x * gamma_broadcast + beta_broadcast
|
/* abre e fecha o menu quando clicar no icone: hamburguer e x */
const nav = document.querySelector('#header nav')
const toggle = document.querySelectorAll('nav .toggle')
for (const element of toggle) {
element.addEventListener('click', function () {
nav.classList.toggle('show')
})
}
/* quando clicar em um item do menu, esconder o menu */
const links = document.querySelectorAll('nav ul li a')
for (const link of links) {
link.addEventListener('click', function () {
nav.classList.remove('show')
})
}
/* mudar o header da página quando der scroll */
const header = document.querySelector('#header')
const navHeight = header.offsetHeight
function changeHeaderWhenScroll() {
if (window.scrollY >= navHeight) {
// scroll é maior que a altura do header
header.classList.add('scroll')
} else {
// menor que a altura do header
header.classList.remove('scroll')
}
}
/* Testimonials carousel slider swiper */
const swiper = new Swiper('.swiper-container', {
slidesPerView: 1,
pagination: {
el: '.swiper-pagination'
},
mousewheel: true,
keyboard: true,
breakpoints: {
767: {
slidesPerView: 2,
setWrapperSize: true
}
}
})
/* ScrollReveal: Mostrar elementos quando der scroll na página */
const scrollReveal = ScrollReveal({
origin: 'top',
distance: '30px',
duration: 700,
reset: true
})
scrollReveal.reveal(
`#home .image, #home .text,
#about .image, #about .text,
#services header, #services .card,
#testimonials header, #testimonials .testimonials
#contact .text, #contact .links,
footer .brand, footer .social
`,
{ interval: 100 }
)
/* Botão voltar para o topo */
const backToTopButton = document.querySelector('.back-to-top')
function backToTop() {
if (window.scrollY >= 560) {
backToTopButton.classList.add('show')
} else {
backToTopButton.classList.remove('show')
}
}
/* Menu ativo conforme a seção visível na página */
const sections = document.querySelectorAll('main section[id]')
function activateMenuAtCurrentSection() {
const checkpoint = window.pageYOffset + (window.innerHeight / 8) * 4
for (const section of sections) {
const sectionTop = section.offsetTop
const sectionHeight = section.offsetHeight
const sectionId = section.getAttribute('id')
const checkpointStart = checkpoint >= sectionTop
const checkpointEnd = checkpoint <= sectionTop + sectionHeight
if (checkpointStart && checkpointEnd) {
document
.querySelector('nav ul li a[href*=' + sectionId + ']')
.classList.add('active')
} else {
document
.querySelector('nav ul li a[href*=' + sectionId + ']')
.classList.remove('active')
}
}
}
/* When Scroll */
window.addEventListener('scroll', function () {
changeHeaderWhenScroll()
backToTop()
activateMenuAtCurrentSection()
}) |
var chartDom_3 = document.getElementById('dist3');
var myChart_3 = echarts.init(chartDom_3);
var option_3;
$.get('https://monex-p.github.io/dashboard_prototype/data/payday_distribution_data.json', function (count_dict) {
$.get('https://monex-p.github.io/dashboard_prototype/data/payday_default_data.json', function (pd_dict) {
var attribute_name = Object.keys(count_dict)[2]
option_3 = {
title: {
text: attribute_name,
// left: 'center',
textStyle: { color: '#ffffff' , fontSize: 15}
},
tooltip: {
trigger: 'axis',
axisPointer:{
type: 'shadow'
},
formatter: function (params){
return params[0].name + '<br/>' + "Number of Loans: " + params[0].value + '<br/>'
+ "Default Odd: " + params[1].value;
}
},
grid: {
left: '3%',
right: '3%',
top: '15%',
bottom: '3%',
containLabel: true
},
xAxis: {
type: 'category',
axisLabel: {
color: '#ffffff'
},
data: Object.keys(count_dict[attribute_name])
},
yAxis: [{
type: 'value',
splitLine: {
lineStyle: {
color: '#36344E'
},
show: true
},
axisLabel: {
color: '#ffffff'
}
},
{
type: 'value',
splitLine: {
show: false
},
axisLabel: { color: '#ffffff' }
}],
series: [{
data: Object.values(count_dict[attribute_name]),
type: 'bar'
},
{
type: 'line',
data: Object.values(pd_dict[attribute_name]),
yAxisIndex: 1
}]
};
myChart_3.setOption(option_3);
});
});
option_3 && myChart_3.setOption(option_3);
|
import { storiesOf } from '@storybook/vue';
import DateRangePicker from './DateRangePicker';
import readme from './README.md';
storiesOf('Picker', module)
.add('Date Range', () => ({
components: { DateRangePicker },
template: `
<DateRangePicker
:maxRangeLength="365"
exceedLengthErrorMsg="時間區間不可超過一年"
></DateRangePicker>
`,
}), { notes: readme }); |
import torch
import torch.nn as nn
from .py_utils import TopPool, BottomPool, LeftPool, RightPool
from .py_utils.utils import convolution, residual, corner_pool
from .py_utils.losses import CornerNet_Loss
from .py_utils.modules import hg_module, hg, hg_net
# 做池化层
def make_pool_layer(dim):
return nn.Sequential()
# 做hg层 [看样子和残差有关],modules是模块数目
def make_hg_layer(inp_dim, out_dim, modules):
layers = [residual(inp_dim, out_dim, stride=2)]
layers += [residual(out_dim, out_dim) for _ in range(1, modules)]
return nn.Sequential(*layers)
class model(hg_net):
def _pred_mod(self, dim):
return nn.Sequential(
convolution(3, 256, 256, with_bn=False),
nn.Conv2d(256, dim, (1, 1))
)
def _merge_mod(self):
return nn.Sequential(
nn.Conv2d(256, 256, (1, 1), bias=False),
nn.BatchNorm2d(256)
)
def __init__(self):
stacks = 2
pre = nn.Sequential(
# 为啥卷积核选择7啊
convolution(7, 3, 128, stride=2),
residual(128, 256, stride=2)
)
hg_mods = nn.ModuleList([
hg_module(
5, [256, 256, 384, 384, 384, 512], [2, 2, 2, 2, 2, 4],
# 这里初始化了一个空nn序列
make_pool_layer=make_pool_layer,
# 赋值上面的函数
make_hg_layer=make_hg_layer
) for _ in range(stacks)
])
# 依次出n个卷基层,n-1残差层
cnvs = nn.ModuleList([convolution(3, 256, 256) for _ in range(stacks)])
inters = nn.ModuleList([residual(256, 256) for _ in range(stacks - 1)])
# n-1 归一化层
cnvs_ = nn.ModuleList([self._merge_mod() for _ in range(stacks - 1)])
inters_ = nn.ModuleList([self._merge_mod() for _ in range(stacks - 1)])
# 上面几个模块我们依次放下来做forward
hgs = hg(pre, hg_mods, cnvs, inters, cnvs_, inters_)
# 新建细节的模块[corner的池化层]
tl_modules = nn.ModuleList([corner_pool(256, TopPool, LeftPool) for _ in range(stacks)])
br_modules = nn.ModuleList([corner_pool(256, BottomPool, RightPool) for _ in range(stacks)])
tl_heats = nn.ModuleList([self._pred_mod(80) for _ in range(stacks)])
br_heats = nn.ModuleList([self._pred_mod(80) for _ in range(stacks)])
for tl_heat, br_heat in zip(tl_heats, br_heats):
torch.nn.init.constant_(tl_heat[-1].bias, -2.19)
torch.nn.init.constant_(br_heat[-1].bias, -2.19)
tl_tags = nn.ModuleList([self._pred_mod(1) for _ in range(stacks)])
br_tags = nn.ModuleList([self._pred_mod(1) for _ in range(stacks)])
tl_offs = nn.ModuleList([self._pred_mod(2) for _ in range(stacks)])
br_offs = nn.ModuleList([self._pred_mod(2) for _ in range(stacks)])
super(model, self).__init__(
hgs, tl_modules, br_modules, tl_heats, br_heats,
tl_tags, br_tags, tl_offs, br_offs
)
self.loss = CornerNet_Loss(pull_weight=1e-1, push_weight=1e-1)
|
import './tariffService';
describe('tariffService', function () {
var $httpBackend,
tariffService,
tariffsGETResponse,
tariffsPUTResponse,
tariffsPOSTResponse,
categories,
result;
tariffsGETResponse = {
tariff_list: {
items: [
{
'created': '2015-05-29T12:33:59+00:00',
'deleted': null,
'default': true,
'services': [
{
'service': {
'service_id': 'm1.medium',
'mutable': false,
'measure': {
'measure_id': 'hour',
'localized_name': {
'ru': 'час',
'en': 'hour'
},
'measure_type': 'time'
},
'description': {
'ru': 'Наилучшее решение для среднего бизнеса',
'en': 'The best solution for middle business'
},
'deleted': null,
'category': {
'localized_name': {
'ru': 'Виртуальные машины',
'en': 'Virtual machine'
},
'category_id': 'vm'
},
'localized_name': {
'ru': 'Виртуальная машина m1.medium',
'en': 'Virtual machine m1.medium'
}
},
'price': '40.00000000000000000000'
}
],
'description': 'новый 1',
'mutable': false,
'parent_id': null,
'localized_name': {
'ru': 'новый1',
'en': 'new1'
},
'used': 29,
'tariff_id': 1,
'currency': 'USD'
}
]
}
};
result = [
{
'created': '2015-05-29T12:33:59+00:00',
'deleted': null,
'default': true,
'services': [
{
'service': {
'service_id': 'm1.medium',
'mutable': false,
'measure': {
'measure_id': 'hour',
'localized_name': {
'ru': 'час',
'en': 'hour'
},
'measure_type': 'time'
},
'description': {
'ru': 'Наилучшее решение для среднего бизнеса',
'en': 'The best solution for middle business'
},
'deleted': null,
'category': {
'localized_name': {
'ru': 'Виртуальные машины',
'en': 'Virtual machine'
},
'category_id': 'vm'
},
'localized_name': {
'ru': 'Виртуальная машина m1.medium',
'en': 'Virtual machine m1.medium'
}
},
'price': '40.00000000000000000000'
}
],
'description': 'новый 1',
'mutable': false,
'parent_id': null,
'localized_name': {
'ru': 'новый1',
'en': 'new1'
},
'used': 29,
'tariff_id': 1,
'currency': 'USD',
'users': 29,
'status': {localized_name: {en: 'Active', ru: 'Действующий'}, value: 'active'}
}
];
categories = [
{
'category_id': 'vm',
'localized_name': {
'ru': 'Виртуальные машины',
'en': 'Virtual machine'
},
'services': [
{
'localized_name': {
'ru': 'Виртуальная машина m1.small',
'en': 'Virtual machine m1.small'
},
'description': {
'ru': 'Cамая маленькая виртуалочка',
'en': 'The smallest virtual machine'
},
'measure': {
'measure_id': 'hour',
'measure_type': 'time',
'localized_name': {
'ru': 'час',
'en': 'hour'
}
},
'service_id': 'm1.small',
'price': '111.00000000000000000000',
'selected': true
}
]
},
{
'category_id': 'storage',
'localized_name': {
'ru': 'Хранение данных',
'en': 'Storage'
},
'services': [
{
'localized_name': {
'ru': 'Диск',
'en': 'Volume'
},
'description': {},
'measure': {
'measure_id': 'gigabyte*month',
'measure_type': 'time_quant',
'localized_name': {
'ru': 'Гб*месяц',
'en': 'Gb*month'
}
},
'service_id': 'storage.volume',
'price': 0,
'selected': false
}
]
}
];
tariffsPUTResponse = {
'tariff_info': {
'description': 'тест3',
'deleted': null,
'parent_id': null,
'localized_name': {
'ru': 'тест3',
'en': 'test3'
},
'default': null,
'tariff_id': 47,
'services': [
{
'service': {
'description': {
'ru': 'Cамая маленькая виртуалочка',
'en': 'The smallest virtual machine'
},
'deleted': null,
'localized_name': {
'ru': 'Виртуальная машина m1.small',
'en': 'Virtual machine m1.small'
},
'service_id': 'm1.small',
'measure': {
'measure_id': 'hour',
'measure_type': 'time',
'localized_name': {
'ru': 'час',
'en': 'hour'
}
},
'mutable': false,
'category': {
'category_id': 'vm',
'localized_name': {
'ru': 'Виртуальные машины',
'en': 'Virtual machine'
}
}
},
'price': '111.00'
}
],
'mutable': true,
'created': '2015-06-09T15:50:51+00:00',
'currency': 'RUB'
}
};
tariffsPOSTResponse = {
'tariff_info': {
'description': 'новый тариф',
'deleted': null,
'parent_id': null,
'localized_name': {
'ru': 'новый тариф',
'en': 'new tariff'
},
'default': null,
'tariff_id': 47,
'services': [
{
'service': {
'description': {
'ru': 'Cамая маленькая виртуалочка',
'en': 'The smallest virtual machine'
},
'deleted': null,
'localized_name': {
'ru': 'Виртуальная машина m1.small',
'en': 'Virtual machine m1.small'
},
'service_id': 'm1.small',
'measure': {
'measure_id': 'hour',
'measure_type': 'time',
'localized_name': {
'ru': 'час',
'en': 'hour'
}
},
'mutable': false,
'category': {
'category_id': 'vm',
'localized_name': {
'ru': 'Виртуальные машины',
'en': 'Virtual machine'
}
}
},
'price': '111.00'
}
],
'mutable': true,
'created': '2015-06-09T15:50:51+00:00',
'currency': 'RUB'
}
};
beforeEach(angular.mock.module('boss.tariffService'));
beforeEach(inject(function (_$httpBackend_, _tariffService_) {
$httpBackend = _$httpBackend_;
tariffService = _tariffService_;
}));
it('getList should return tariffs list with additional fields', function (done) {
$httpBackend.when('GET', '/tariff?show_used=true').respond(tariffsGETResponse);
tariffService.getList()
.then(function (res) {
var plain = res.map(item => {
return item.plain();
});
expect(plain).toEqual(result);
done();
});
$httpBackend.flush();
});
it('updateTariff should form services array correctly and send PUT request to backend', function (done) {
var tariff,
expectedPayload;
tariff = {
tariff_id: 47
};
expectedPayload = {
tariff: 47,
currency: null,
description: null,
localized_name: null,
services: [
{
service_id: 'm1.small',
price: '111.00000000000000000000'
}
]
};
$httpBackend.expectPUT('/tariff/47', expectedPayload).respond(tariffsPUTResponse);
tariffService.updateTariff(tariff, categories)
.finally(done);
$httpBackend.flush();
});
it('createTariff should form services array correctly and send POST request to backend', function (done) {
var tariff,
expectedPayload;
tariff = {
localized_name: {
ru: 'новый тариф',
en: 'new tariff'
},
description: 'новый тариф',
currency: 'RUB',
parent_id: null
};
expectedPayload = {
localized_name: {
ru: 'новый тариф',
en: 'new tariff'
},
description: 'новый тариф',
currency: 'RUB',
parent_id: null,
services: [
{
service_id: 'm1.small',
price: '111.00000000000000000000'
}
]
};
$httpBackend.expectPOST('/tariff', expectedPayload).respond(tariffsPOSTResponse);
tariffService.createTariff(tariff, categories)
.finally(done);
$httpBackend.flush();
});
});
|
from sys import maxsize
class Contact:
def __init__ (self,
firstname = None,
middlename = None,
lastname = None,
nickname = None,
title = None,
company = None,
company_address = None,
home_phone = None,
mobile_phone = None,
work_phone = None,
fax = None,
email1 = None,
email2 = None,
email3 = None,
homepage = None,
birth_date=None,
birth_day = None,
birth_month = None,
birth_year = None,
anniver_date=None,
anniver_day = None,
anniver_month = None,
anniver_year = None,
home_address = None,
home_phone2 = None,
notes = None,
id=None,
all_mail_from_home_page=None,
all_phones_from_home_page = None,
hash = None):
self.firstname = firstname
self.middlename = middlename
self.lastname = lastname
self.nickname = nickname
self.title = title
self.company = company
self.company_address = company_address
self.home_phone = home_phone
self.mobile_phone = mobile_phone
self.work_phone = work_phone
self.fax = fax
self.email1 = email1
self.email2 = email2
self.email3 = email3
self.homepage = homepage
self.birth_date = birth_date
self.birth_day = birth_day
self.birth_month = birth_month
self.birth_year = birth_year
self.anniver_date = anniver_date
self.anniver_day = anniver_day
self.anniver_month = anniver_month
self.anniver_year = anniver_year
self.home_address = home_address
self.home_phone2 = home_phone2
self.notes = notes
self.id = id
self.all_phones_from_home_page = all_phones_from_home_page
self.all_mail_from_home_page = all_mail_from_home_page
def str_or_no(string):
if (string is None) or (string == ""):
return ""
else:
return str(string)
#для строк, после которых следует перенос \n
def strn_or_no(string):
if (string is None) or (string == ""):
return ""
else:
return str(string) +'\n'
def hash_str(self):
self.hash = str_or_no(self.lastname) + str_or_no(self.firstname) + str_or_no(self.company_address) + \
strn_or_no(self.email1)+ strn_or_no(self.email2)+ str_or_no(self.email3)+ \
strn_or_no(self.home_phone) + strn_or_no(self.mobile_phone) + strn_or_no(self.work_phone) + str_or_no(self.fax)
if hash is None:
hash_str(self)
# self.hash = str_or_no(lastname) + str_or_no(firstname) + str_or_no(company_address) + \
# strn_or_no(email1)+ strn_or_no(email2)+ str_or_no(email3)+ \
# strn_or_no(home_phone) + strn_or_no(mobile_phone) + strn_or_no(work_phone) + str_or_no(fax)
else:
self.hash = hash
# изменение полей объекта Contact
def fill_contact_values(self, contact):
def hash_str(self):
self.hash = str_or_no(self.lastname) + str_or_no(self.firstname) + str_or_no(self.company_address) + \
strn_or_no(self.email1)+ strn_or_no(self.email2)+ str_or_no(self.email3)+ \
strn_or_no(self.home_phone) + strn_or_no(self.mobile_phone) + strn_or_no(self.work_phone) + str_or_no(self.fax)
def str_or_no(string):
if (string is None) or (string == ""):
return ""
else:
return str(string)
def strn_or_no(string):
if (string is None) or (string == ""):
return ""
else:
return str(string) +'\n'
def fill_contact_value(a, b):
if b is not None:
return b
else:
return a
self.firstname = fill_contact_value(self.firstname, contact.firstname)
self.middlename = fill_contact_value(self.middlename, contact.middlename)
self.lastname = fill_contact_value(self.lastname, contact.lastname)
self.nickname = fill_contact_value(self.nickname, contact.nickname)
self.title = fill_contact_value(self.title, contact.title)
self.company = fill_contact_value(self.company, contact.company)
self.company_address = fill_contact_value(self.company_address, contact.company_address)
self.home_phone = fill_contact_value(self.home_phone, contact.home_phone)
self.mobile_phone = fill_contact_value(self.mobile_phone, contact.mobile_phone)
self.work_phone = fill_contact_value(self.work_phone, contact.work_phone)
self.fax = fill_contact_value(self.fax, contact.fax)
self.email1 = fill_contact_value(self.email1, contact.email1)
self.email2 = fill_contact_value(self.email2, contact.email2)
self.email3 = fill_contact_value(self.email3, contact.email3)
self.homepage = fill_contact_value(self.homepage, contact.homepage)
# Birthday date
self.birth_day = fill_contact_value(self.birth_day, contact.birth_day)
self.birth_month = fill_contact_value(self.birth_month, contact.birth_month)
self.birth_year = fill_contact_value(self.birth_year, contact.birth_year)
# Anniversary date
self.anniver_day = fill_contact_value(self.anniver_day, contact.anniver_day)
self.anniver_month = fill_contact_value(self.anniver_month, contact.anniver_month)
self.anniver_year = fill_contact_value(self.anniver_year, contact.anniver_year)
self.home_address = fill_contact_value(self.home_address, contact.home_address)
self.home_phone2 = fill_contact_value(self.home_phone2, contact.home_phone2)
self.notes = fill_contact_value(self.notes, contact.notes)
hash_str(self)
#метод, задающий ключ для сортировки списка объектов Контакт
def id_or_max(self):
if self.id:
return int(self.id)
else:
return maxsize
# стандартный метод, определяющий вид вывода объекта на консоль
def __repr__(self):
return "%s:%s" % (self.id, self.lastname + ' ' + self.firstname)
# стандартный метод, определяющий правила сравнения объектов
def __eq__(self, other):
#return (self.id is None or other.id is None or self.id == other.id) and (self.hash == other.hash)
return (self.id is None or other.id is None or self.id == other.id) and (self.lastname == other.lastname) \
and (self.firstname == other.firstname)
|
import { checkSession, checkIsAlreadyConnected, checkPermission } from 'source/modules/Auth/router/middleware'
import { otherwise } from 'src/router'
import { signIn, recoverPassword, layout } from 'source/modules/Auth/components'
import { checkModified } from 'source/modules/General/router/middleware'
/**
* @param {AppRouter} $router
*/
export default ($router) => {
$router.group(otherwise, layout, (group) => {
group.route('', signIn, { name: 'sign-in', public: true })
group.route('/recover-password', recoverPassword, { name: 'recover-password', public: true })
})
// check user is logged in app
$router.beforeThis(otherwise, checkIsAlreadyConnected)
// check if there is modification
$router.beforeEach(checkModified)
// check the user session
$router.beforeEach(checkSession)
// check the permission to route
$router.beforeEach(checkPermission)
}
|
import io from 'socket.io-client';
export default class WebSocketClient {
constructor(uri ='/', {
path ='/',
forceNew =true,
transports = ['websocket','polling'],
autoConnect =false,
} = {}
){
this.client = io(uri,{path, forceNew,transports,autoConnect});
}
connect(){
this.client.open();
}
disconnect(){
this.client.close();
}
receive(eventName,callback){
console.log(eventName,'eventNameeventNamessss')
this.client.on(eventName,(data) => callback(
// transJson(data)
console.log(data,'服务器返回的内容')
)
);
}
send(eventName,data){
this.client.emit(eventName,data);
console.log(eventName,data,'服务器发送的的内容')
}
}
/**
* 将后台传过来的json字符串转换为object
* @param data
* @param callback
*/
function transJson(data){
let trans = data;
if(typeof data ==='string' && (data.indexOf('{') ===0 || data.indexOf('[') ===0)){
trans =JSON.parse(data);
}
return trans;
} |
/**
* material-design-lite - Material Design Components in CSS, JS and HTML
* @version v1.0.4
* @license Apache-2.0
* @copyright 2015 Google, Inc.
* @link https://github.com/google/material-design-lite
*/
!function(){"use strict";function e(e,s){if(e){if(s.element_.classList.contains(s.CssClasses_.MDL_JS_RIPPLE_EFFECT)){var t=document.createElement("span");t.classList.add(s.CssClasses_.MDL_RIPPLE_CONTAINER),t.classList.add(s.CssClasses_.MDL_JS_RIPPLE_EFFECT);var i=document.createElement("span");i.classList.add(s.CssClasses_.MDL_RIPPLE),t.appendChild(i),e.appendChild(t)}e.addEventListener("click",function(t){t.preventDefault();var i=e.href.split("#")[1],n=s.element_.querySelector("#"+i);s.resetTabState_(),s.resetPanelState_(),e.classList.add(s.CssClasses_.ACTIVE_CLASS),n.classList.add(s.CssClasses_.ACTIVE_CLASS)})}}function s(e,s,t,i){if(e){if(i.tabBar_.classList.contains(i.CssClasses_.JS_RIPPLE_EFFECT)){var n=document.createElement("span");n.classList.add(i.CssClasses_.RIPPLE_CONTAINER),n.classList.add(i.CssClasses_.JS_RIPPLE_EFFECT);var a=document.createElement("span");a.classList.add(i.CssClasses_.RIPPLE),n.appendChild(a),e.appendChild(n)}e.addEventListener("click",function(n){n.preventDefault();var a=e.href.split("#")[1],l=i.content_.querySelector("#"+a);i.resetTabState_(s),i.resetPanelState_(t),e.classList.add(i.CssClasses_.IS_ACTIVE),l.classList.add(i.CssClasses_.IS_ACTIVE)})}}window.componentHandler=function(){function e(e,s){for(var t=0;t<c.length;t++)if(c[t].className===e)return void 0!==s&&(c[t]=s),c[t];return!1}function s(e){var s=e.getAttribute("data-upgraded");return null===s?[""]:s.split(",")}function t(e,t){var i=s(e);return-1!==i.indexOf(t)}function i(s,t){if(void 0===s&&void 0===t)for(var a=0;a<c.length;a++)i(c[a].className,c[a].cssClass);else{var l=s;if(void 0===t){var o=e(l);o&&(t=o.cssClass)}for(var r=document.querySelectorAll("."+t),_=0;_<r.length;_++)n(r[_],l)}}function n(i,n){if(!("object"==typeof i&&i instanceof Element))throw new Error("Invalid argument provided to upgrade MDL element.");var a=s(i),l=[];if(n)t(i,n)||l.push(e(n));else{var o=i.classList;c.forEach(function(e){o.contains(e.cssClass)&&-1===l.indexOf(e)&&!t(i,e.className)&&l.push(e)})}for(var r,_=0,d=l.length;d>_;_++){if(r=l[_],!r)throw new Error("Unable to find a registered component for the given class.");a.push(r.className),i.setAttribute("data-upgraded",a.join(","));var h=new r.classConstructor(i);h[C]=r,p.push(h);for(var u=0,m=r.callbacks.length;m>u;u++)r.callbacks[u](i);r.widget&&(i[r.className]=h);var E=document.createEvent("Events");E.initEvent("mdl-componentupgraded",!0,!0),i.dispatchEvent(E)}}function a(e){Array.isArray(e)||(e="function"==typeof e.item?Array.prototype.slice.call(e):[e]);for(var s,t=0,i=e.length;i>t;t++)s=e[t],s instanceof HTMLElement&&(s.children.length>0&&a(s.children),n(s))}function l(s){var t={classConstructor:s.constructor,className:s.classAsString,cssClass:s.cssClass,widget:void 0===s.widget?!0:s.widget,callbacks:[]};if(c.forEach(function(e){if(e.cssClass===t.cssClass)throw new Error("The provided cssClass has already been registered.");if(e.className===t.className)throw new Error("The provided className has already been registered")}),s.constructor.prototype.hasOwnProperty(C))throw new Error("MDL component classes must not have "+C+" defined as a property.");var i=e(s.classAsString,t);i||c.push(t)}function o(s,t){var i=e(s);i&&i.callbacks.push(t)}function r(){for(var e=0;e<c.length;e++)i(c[e].className)}function _(e){for(var s=0;s<p.length;s++){var t=p[s];if(t.element_===e)return t}}function d(e){if(e&&e[C].classConstructor.prototype.hasOwnProperty(u)){e[u]();var s=p.indexOf(e);p.splice(s,1);var t=e.element_.getAttribute("data-upgraded").split(","),i=t.indexOf(e[C].classAsString);t.splice(i,1),e.element_.setAttribute("data-upgraded",t.join(","));var n=document.createEvent("Events");n.initEvent("mdl-componentdowngraded",!0,!0),e.element_.dispatchEvent(n)}}function h(e){var s=function(e){d(_(e))};if(e instanceof Array||e instanceof NodeList)for(var t=0;t<e.length;t++)s(e[t]);else{if(!(e instanceof Node))throw new Error("Invalid argument provided to downgrade MDL nodes.");s(e)}}var c=[],p=[],u="mdlDowngrade_",C="mdlComponentConfigInternal_";return{upgradeDom:i,upgradeElement:n,upgradeElements:a,upgradeAllRegistered:r,registerUpgradedCallback:o,register:l,downgradeElements:h}}(),window.addEventListener("load",function(){"classList"in document.createElement("div")&&"querySelector"in document&&"addEventListener"in window&&Array.prototype.forEach?(document.documentElement.classList.add("mdl-js"),componentHandler.upgradeAllRegistered()):componentHandler.upgradeElement=componentHandler.register=function(){}}),componentHandler.ComponentConfig,componentHandler.Component,Date.now||(Date.now=function(){return(new Date).getTime()});for(var t=["webkit","moz"],i=0;i<t.length&&!window.requestAnimationFrame;++i){var n=t[i];window.requestAnimationFrame=window[n+"RequestAnimationFrame"],window.cancelAnimationFrame=window[n+"CancelAnimationFrame"]||window[n+"CancelRequestAnimationFrame"]}if(/iP(ad|hone|od).*OS 6/.test(window.navigator.userAgent)||!window.requestAnimationFrame||!window.cancelAnimationFrame){var a=0;window.requestAnimationFrame=function(e){var s=Date.now(),t=Math.max(a+16,s);return setTimeout(function(){e(a=t)},t-s)},window.cancelAnimationFrame=clearTimeout}var l=function(e){this.element_=e,this.init()};window.MaterialButton=l,l.prototype.Constant_={},l.prototype.CssClasses_={RIPPLE_EFFECT:"mdl-js-ripple-effect",RIPPLE_CONTAINER:"mdl-button__ripple-container",RIPPLE:"mdl-ripple"},l.prototype.blurHandler_=function(e){e&&this.element_.blur()},l.prototype.disable=function(){this.element_.disabled=!0},l.prototype.enable=function(){this.element_.disabled=!1},l.prototype.init=function(){if(this.element_){if(this.element_.classList.contains(this.CssClasses_.RIPPLE_EFFECT)){var e=document.createElement("span");e.classList.add(this.CssClasses_.RIPPLE_CONTAINER),this.rippleElement_=document.createElement("span"),this.rippleElement_.classList.add(this.CssClasses_.RIPPLE),e.appendChild(this.rippleElement_),this.boundRippleBlurHandler=this.blurHandler_.bind(this),this.rippleElement_.addEventListener("mouseup",this.boundRippleBlurHandler),this.element_.appendChild(e)}this.boundButtonBlurHandler=this.blurHandler_.bind(this),this.element_.addEventListener("mouseup",this.boundButtonBlurHandler),this.element_.addEventListener("mouseleave",this.boundButtonBlurHandler)}},l.prototype.mdlDowngrade_=function(){this.rippleElement_&&this.rippleElement_.removeEventListener("mouseup",this.boundRippleBlurHandler),this.element_.removeEventListener("mouseup",this.boundButtonBlurHandler),this.element_.removeEventListener("mouseleave",this.boundButtonBlurHandler)},componentHandler.register({constructor:l,classAsString:"MaterialButton",cssClass:"mdl-js-button",widget:!0});var o=function(e){this.element_=e,this.init()};window.MaterialCheckbox=o,o.prototype.Constant_={TINY_TIMEOUT:.001},o.prototype.CssClasses_={INPUT:"mdl-checkbox__input",BOX_OUTLINE:"mdl-checkbox__box-outline",FOCUS_HELPER:"mdl-checkbox__focus-helper",TICK_OUTLINE:"mdl-checkbox__tick-outline",RIPPLE_EFFECT:"mdl-js-ripple-effect",RIPPLE_IGNORE_EVENTS:"mdl-js-ripple-effect--ignore-events",RIPPLE_CONTAINER:"mdl-checkbox__ripple-container",RIPPLE_CENTER:"mdl-ripple--center",RIPPLE:"mdl-ripple",IS_FOCUSED:"is-focused",IS_DISABLED:"is-disabled",IS_CHECKED:"is-checked",IS_UPGRADED:"is-upgraded"},o.prototype.onChange_=function(e){this.updateClasses_()},o.prototype.onFocus_=function(e){this.element_.classList.add(this.CssClasses_.IS_FOCUSED)},o.prototype.onBlur_=function(e){this.element_.classList.remove(this.CssClasses_.IS_FOCUSED)},o.prototype.onMouseUp_=function(e){this.blur_()},o.prototype.updateClasses_=function(){this.checkDisabled(),this.checkToggleState()},o.prototype.blur_=function(e){window.setTimeout(function(){this.inputElement_.blur()}.bind(this),this.Constant_.TINY_TIMEOUT)},o.prototype.checkToggleState=function(){this.inputElement_.checked?this.element_.classList.add(this.CssClasses_.IS_CHECKED):this.element_.classList.remove(this.CssClasses_.IS_CHECKED)},o.prototype.checkDisabled=function(){this.inputElement_.disabled?this.element_.classList.add(this.CssClasses_.IS_DISABLED):this.element_.classList.remove(this.CssClasses_.IS_DISABLED)},o.prototype.disable=function(){this.inputElement_.disabled=!0,this.updateClasses_()},o.prototype.enable=function(){this.inputElement_.disabled=!1,this.updateClasses_()},o.prototype.check=function(){this.inputElement_.checked=!0,this.updateClasses_()},o.prototype.uncheck=function(){this.inputElement_.checked=!1,this.updateClasses_()},o.prototype.init=function(){if(this.element_){this.inputElement_=this.element_.querySelector("."+this.CssClasses_.INPUT);var e=document.createElement("span");e.classList.add(this.CssClasses_.BOX_OUTLINE);var s=document.createElement("span");s.classList.add(this.CssClasses_.FOCUS_HELPER);var t=document.createElement("span");if(t.classList.add(this.CssClasses_.TICK_OUTLINE),e.appendChild(t),this.element_.appendChild(s),this.element_.appendChild(e),this.element_.classList.contains(this.CssClasses_.RIPPLE_EFFECT)){this.element_.classList.add(this.CssClasses_.RIPPLE_IGNORE_EVENTS),this.rippleContainerElement_=document.createElement("span"),this.rippleContainerElement_.classList.add(this.CssClasses_.RIPPLE_CONTAINER),this.rippleContainerElement_.classList.add(this.CssClasses_.RIPPLE_EFFECT),this.rippleContainerElement_.classList.add(this.CssClasses_.RIPPLE_CENTER),this.boundRippleMouseUp=this.onMouseUp_.bind(this),this.rippleContainerElement_.addEventListener("mouseup",this.boundRippleMouseUp);var i=document.createElement("span");i.classList.add(this.CssClasses_.RIPPLE),this.rippleContainerElement_.appendChild(i),this.element_.appendChild(this.rippleContainerElement_)}this.boundInputOnChange=this.onChange_.bind(this),this.boundInputOnFocus=this.onFocus_.bind(this),this.boundInputOnBlur=this.onBlur_.bind(this),this.boundElementMouseUp=this.onMouseUp_.bind(this),this.inputElement_.addEventListener("change",this.boundInputOnChange),this.inputElement_.addEventListener("focus",this.boundInputOnFocus),this.inputElement_.addEventListener("blur",this.boundInputOnBlur),this.element_.addEventListener("mouseup",this.boundElementMouseUp),this.updateClasses_(),this.element_.classList.add(this.CssClasses_.IS_UPGRADED)}},o.prototype.mdlDowngrade_=function(){this.rippleContainerElement_&&this.rippleContainerElement_.removeEventListener("mouseup",this.boundRippleMouseUp),this.inputElement_.removeEventListener("change",this.boundInputOnChange),this.inputElement_.removeEventListener("focus",this.boundInputOnFocus),this.inputElement_.removeEventListener("blur",this.boundInputOnBlur),this.element_.removeEventListener("mouseup",this.boundElementMouseUp)},componentHandler.register({constructor:o,classAsString:"MaterialCheckbox",cssClass:"mdl-js-checkbox",widget:!0});var r=function(e){this.element_=e,this.init()};window.MaterialIconToggle=r,r.prototype.Constant_={TINY_TIMEOUT:.001},r.prototype.CssClasses_={INPUT:"mdl-icon-toggle__input",JS_RIPPLE_EFFECT:"mdl-js-ripple-effect",RIPPLE_IGNORE_EVENTS:"mdl-js-ripple-effect--ignore-events",RIPPLE_CONTAINER:"mdl-icon-toggle__ripple-container",RIPPLE_CENTER:"mdl-ripple--center",RIPPLE:"mdl-ripple",IS_FOCUSED:"is-focused",IS_DISABLED:"is-disabled",IS_CHECKED:"is-checked"},r.prototype.onChange_=function(e){this.updateClasses_()},r.prototype.onFocus_=function(e){this.element_.classList.add(this.CssClasses_.IS_FOCUSED)},r.prototype.onBlur_=function(e){this.element_.classList.remove(this.CssClasses_.IS_FOCUSED)},r.prototype.onMouseUp_=function(e){this.blur_()},r.prototype.updateClasses_=function(){this.checkDisabled(),this.checkToggleState()},r.prototype.blur_=function(e){window.setTimeout(function(){this.inputElement_.blur()}.bind(this),this.Constant_.TINY_TIMEOUT)},r.prototype.checkToggleState=function(){this.inputElement_.checked?this.element_.classList.add(this.CssClasses_.IS_CHECKED):this.element_.classList.remove(this.CssClasses_.IS_CHECKED)},r.prototype.checkDisabled=function(){this.inputElement_.disabled?this.element_.classList.add(this.CssClasses_.IS_DISABLED):this.element_.classList.remove(this.CssClasses_.IS_DISABLED)},r.prototype.disable=function(){this.inputElement_.disabled=!0,this.updateClasses_()},r.prototype.enable=function(){this.inputElement_.disabled=!1,this.updateClasses_()},r.prototype.check=function(){this.inputElement_.checked=!0,this.updateClasses_()},r.prototype.uncheck=function(){this.inputElement_.checked=!1,this.updateClasses_()},r.prototype.init=function(){if(this.element_){if(this.inputElement_=this.element_.querySelector("."+this.CssClasses_.INPUT),this.element_.classList.contains(this.CssClasses_.JS_RIPPLE_EFFECT)){this.element_.classList.add(this.CssClasses_.RIPPLE_IGNORE_EVENTS),this.rippleContainerElement_=document.createElement("span"),this.rippleContainerElement_.classList.add(this.CssClasses_.RIPPLE_CONTAINER),this.rippleContainerElement_.classList.add(this.CssClasses_.JS_RIPPLE_EFFECT),this.rippleContainerElement_.classList.add(this.CssClasses_.RIPPLE_CENTER),this.boundRippleMouseUp=this.onMouseUp_.bind(this),this.rippleContainerElement_.addEventListener("mouseup",this.boundRippleMouseUp);var e=document.createElement("span");e.classList.add(this.CssClasses_.RIPPLE),this.rippleContainerElement_.appendChild(e),this.element_.appendChild(this.rippleContainerElement_)}this.boundInputOnChange=this.onChange_.bind(this),this.boundInputOnFocus=this.onFocus_.bind(this),this.boundInputOnBlur=this.onBlur_.bind(this),this.boundElementOnMouseUp=this.onMouseUp_.bind(this),this.inputElement_.addEventListener("change",this.boundInputOnChange),this.inputElement_.addEventListener("focus",this.boundInputOnFocus),this.inputElement_.addEventListener("blur",this.boundInputOnBlur),this.element_.addEventListener("mouseup",this.boundElementOnMouseUp),this.updateClasses_(),this.element_.classList.add("is-upgraded")}},r.prototype.mdlDowngrade_=function(){this.rippleContainerElement_&&this.rippleContainerElement_.removeEventListener("mouseup",this.boundRippleMouseUp),this.inputElement_.removeEventListener("change",this.boundInputOnChange),this.inputElement_.removeEventListener("focus",this.boundInputOnFocus),this.inputElement_.removeEventListener("blur",this.boundInputOnBlur),this.element_.removeEventListener("mouseup",this.boundElementOnMouseUp)},componentHandler.register({constructor:r,classAsString:"MaterialIconToggle",cssClass:"mdl-js-icon-toggle",widget:!0});var _=function(e){this.element_=e,this.init()};window.MaterialMenu=_,_.prototype.Constant_={TRANSITION_DURATION_SECONDS:.3,TRANSITION_DURATION_FRACTION:.8,CLOSE_TIMEOUT:150},_.prototype.Keycodes_={ENTER:13,ESCAPE:27,SPACE:32,UP_ARROW:38,DOWN_ARROW:40},_.prototype.CssClasses_={CONTAINER:"mdl-menu__container",OUTLINE:"mdl-menu__outline",ITEM:"mdl-menu__item",ITEM_RIPPLE_CONTAINER:"mdl-menu__item-ripple-container",RIPPLE_EFFECT:"mdl-js-ripple-effect",RIPPLE_IGNORE_EVENTS:"mdl-js-ripple-effect--ignore-events",RIPPLE:"mdl-ripple",IS_UPGRADED:"is-upgraded",IS_VISIBLE:"is-visible",IS_ANIMATING:"is-animating",BOTTOM_LEFT:"mdl-menu--bottom-left",BOTTOM_RIGHT:"mdl-menu--bottom-right",TOP_LEFT:"mdl-menu--top-left",TOP_RIGHT:"mdl-menu--top-right",UNALIGNED:"mdl-menu--unaligned"},_.prototype.init=function(){if(this.element_){var e=document.createElement("div");e.classList.add(this.CssClasses_.CONTAINER),this.element_.parentElement.insertBefore(e,this.element_),this.element_.parentElement.removeChild(this.element_),e.appendChild(this.element_),this.container_=e;var s=document.createElement("div");s.classList.add(this.CssClasses_.OUTLINE),this.outline_=s,e.insertBefore(s,this.element_);var t=this.element_.getAttribute("for"),i=null;t&&(i=document.getElementById(t),i&&(this.forElement_=i,i.addEventListener("click",this.handleForClick_.bind(this)),i.addEventListener("keydown",this.handleForKeyboardEvent_.bind(this))));var n=this.element_.querySelectorAll("."+this.CssClasses_.ITEM);this.boundItemKeydown=this.handleItemKeyboardEvent_.bind(this),this.boundItemClick=this.handleItemClick_.bind(this);for(var a=0;a<n.length;a++)n[a].addEventListener("click",this.boundItemClick),n[a].tabIndex="-1",n[a].addEventListener("keydown",this.boundItemKeydown);if(this.element_.classList.contains(this.CssClasses_.RIPPLE_EFFECT))for(this.element_.classList.add(this.CssClasses_.RIPPLE_IGNORE_EVENTS),a=0;a<n.length;a++){var l=n[a],o=document.createElement("span");o.classList.add(this.CssClasses_.ITEM_RIPPLE_CONTAINER);var r=document.createElement("span");r.classList.add(this.CssClasses_.RIPPLE),o.appendChild(r),l.appendChild(o),l.classList.add(this.CssClasses_.RIPPLE_EFFECT)}this.element_.classList.contains(this.CssClasses_.BOTTOM_LEFT)&&this.outline_.classList.add(this.CssClasses_.BOTTOM_LEFT),this.element_.classList.contains(this.CssClasses_.BOTTOM_RIGHT)&&this.outline_.classList.add(this.CssClasses_.BOTTOM_RIGHT),this.element_.classList.contains(this.CssClasses_.TOP_LEFT)&&this.outline_.classList.add(this.CssClasses_.TOP_LEFT),this.element_.classList.contains(this.CssClasses_.TOP_RIGHT)&&this.outline_.classList.add(this.CssClasses_.TOP_RIGHT),this.element_.classList.contains(this.CssClasses_.UNALIGNED)&&this.outline_.classList.add(this.CssClasses_.UNALIGNED),e.classList.add(this.CssClasses_.IS_UPGRADED)}},_.prototype.handleForClick_=function(e){if(this.element_&&this.forElement_){var s=this.forElement_.getBoundingClientRect(),t=this.forElement_.parentElement.getBoundingClientRect();this.element_.classList.contains(this.CssClasses_.UNALIGNED)||(this.element_.classList.contains(this.CssClasses_.BOTTOM_RIGHT)?(this.container_.style.right=t.right-s.right+"px",this.container_.style.top=this.forElement_.offsetTop+this.forElement_.offsetHeight+"px"):this.element_.classList.contains(this.CssClasses_.TOP_LEFT)?(this.container_.style.left=this.forElement_.offsetLeft+"px",this.container_.style.bottom=t.bottom-s.top+"px"):this.element_.classList.contains(this.CssClasses_.TOP_RIGHT)?(this.container_.style.right=t.right-s.right+"px",this.container_.style.bottom=t.bottom-s.top+"px"):(this.container_.style.left=this.forElement_.offsetLeft+"px",this.container_.style.top=this.forElement_.offsetTop+this.forElement_.offsetHeight+"px"))}this.toggle(e)},_.prototype.handleForKeyboardEvent_=function(e){if(this.element_&&this.container_&&this.forElement_){var s=this.element_.querySelectorAll("."+this.CssClasses_.ITEM+":not([disabled])");s&&s.length>0&&this.container_.classList.contains(this.CssClasses_.IS_VISIBLE)&&(e.keyCode===this.Keycodes_.UP_ARROW?(e.preventDefault(),s[s.length-1].focus()):e.keyCode===this.Keycodes_.DOWN_ARROW&&(e.preventDefault(),s[0].focus()))}},_.prototype.handleItemKeyboardEvent_=function(e){if(this.element_&&this.container_){var s=this.element_.querySelectorAll("."+this.CssClasses_.ITEM+":not([disabled])");if(s&&s.length>0&&this.container_.classList.contains(this.CssClasses_.IS_VISIBLE)){var t=Array.prototype.slice.call(s).indexOf(e.target);if(e.keyCode===this.Keycodes_.UP_ARROW)e.preventDefault(),t>0?s[t-1].focus():s[s.length-1].focus();else if(e.keyCode===this.Keycodes_.DOWN_ARROW)e.preventDefault(),s.length>t+1?s[t+1].focus():s[0].focus();else if(e.keyCode===this.Keycodes_.SPACE||e.keyCode===this.Keycodes_.ENTER){e.preventDefault();var i=new MouseEvent("mousedown");e.target.dispatchEvent(i),i=new MouseEvent("mouseup"),e.target.dispatchEvent(i),e.target.click()}else e.keyCode===this.Keycodes_.ESCAPE&&(e.preventDefault(),this.hide())}}},_.prototype.handleItemClick_=function(e){null!==e.target.getAttribute("disabled")?e.stopPropagation():(this.closing_=!0,window.setTimeout(function(e){this.hide(),this.closing_=!1}.bind(this),this.Constant_.CLOSE_TIMEOUT))},_.prototype.applyClip_=function(e,s){this.element_.style.clip=this.element_.classList.contains(this.CssClasses_.UNALIGNED)?null:this.element_.classList.contains(this.CssClasses_.BOTTOM_RIGHT)?"rect(0 "+s+"px 0 "+s+"px)":this.element_.classList.contains(this.CssClasses_.TOP_LEFT)?"rect("+e+"px 0 "+e+"px 0)":this.element_.classList.contains(this.CssClasses_.TOP_RIGHT)?"rect("+e+"px "+s+"px "+e+"px "+s+"px)":null},_.prototype.addAnimationEndListener_=function(){var e=function(){this.element_.removeEventListener("transitionend",e),this.element_.removeEventListener("webkitTransitionEnd",e),this.element_.classList.remove(this.CssClasses_.IS_ANIMATING)}.bind(this);this.element_.addEventListener("transitionend",e),this.element_.addEventListener("webkitTransitionEnd",e)},_.prototype.show=function(e){if(this.element_&&this.container_&&this.outline_){var s=this.element_.getBoundingClientRect().height,t=this.element_.getBoundingClientRect().width;this.container_.style.width=t+"px",this.container_.style.height=s+"px",this.outline_.style.width=t+"px",this.outline_.style.height=s+"px";for(var i=this.Constant_.TRANSITION_DURATION_SECONDS*this.Constant_.TRANSITION_DURATION_FRACTION,n=this.element_.querySelectorAll("."+this.CssClasses_.ITEM),a=0;a<n.length;a++){var l=null;l=this.element_.classList.contains(this.CssClasses_.TOP_LEFT)||this.element_.classList.contains(this.CssClasses_.TOP_RIGHT)?(s-n[a].offsetTop-n[a].offsetHeight)/s*i+"s":n[a].offsetTop/s*i+"s",n[a].style.transitionDelay=l}this.applyClip_(s,t),window.requestAnimationFrame(function(){this.element_.classList.add(this.CssClasses_.IS_ANIMATING),this.element_.style.clip="rect(0 "+t+"px "+s+"px 0)",this.container_.classList.add(this.CssClasses_.IS_VISIBLE)}.bind(this)),this.addAnimationEndListener_();var o=function(s){s===e||this.closing_||(document.removeEventListener("click",o),this.hide())}.bind(this);document.addEventListener("click",o)}},_.prototype.hide=function(){if(this.element_&&this.container_&&this.outline_){for(var e=this.element_.querySelectorAll("."+this.CssClasses_.ITEM),s=0;s<e.length;s++)e[s].style.transitionDelay=null;var t=this.element_.getBoundingClientRect().height,i=this.element_.getBoundingClientRect().width;this.element_.classList.add(this.CssClasses_.IS_ANIMATING),this.applyClip_(t,i),this.container_.classList.remove(this.CssClasses_.IS_VISIBLE),this.addAnimationEndListener_()}},_.prototype.toggle=function(e){this.container_.classList.contains(this.CssClasses_.IS_VISIBLE)?this.hide():this.show(e)},_.prototype.mdlDowngrade_=function(){for(var e=this.element_.querySelectorAll("."+this.CssClasses_.ITEM),s=0;s<e.length;s++)e[s].removeEventListener("click",this.boundItemClick),e[s].removeEventListener("keydown",this.boundItemKeydown)},componentHandler.register({constructor:_,classAsString:"MaterialMenu",cssClass:"mdl-js-menu",widget:!0});var d=function(e){this.element_=e,this.init()};window.MaterialProgress=d,d.prototype.Constant_={},d.prototype.CssClasses_={INDETERMINATE_CLASS:"mdl-progress__indeterminate"},d.prototype.setProgress=function(e){this.element_.classList.contains(this.CssClasses_.INDETERMINATE_CLASS)||(this.progressbar_.style.width=e+"%")},d.prototype.setBuffer=function(e){this.bufferbar_.style.width=e+"%",this.auxbar_.style.width=100-e+"%"},d.prototype.init=function(){if(this.element_){var e=document.createElement("div");e.className="progressbar bar bar1",this.element_.appendChild(e),this.progressbar_=e,e=document.createElement("div"),e.className="bufferbar bar bar2",this.element_.appendChild(e),this.bufferbar_=e,e=document.createElement("div"),e.className="auxbar bar bar3",this.element_.appendChild(e),this.auxbar_=e,this.progressbar_.style.width="0%",this.bufferbar_.style.width="100%",this.auxbar_.style.width="0%",this.element_.classList.add("is-upgraded")}},d.prototype.mdlDowngrade_=function(){for(;this.element_.firstChild;)this.element_.removeChild(this.element_.firstChild)},componentHandler.register({constructor:d,classAsString:"MaterialProgress",cssClass:"mdl-js-progress",widget:!0});var h=function(e){this.element_=e,this.init()};window.MaterialRadio=h,h.prototype.Constant_={TINY_TIMEOUT:.001},h.prototype.CssClasses_={IS_FOCUSED:"is-focused",IS_DISABLED:"is-disabled",IS_CHECKED:"is-checked",IS_UPGRADED:"is-upgraded",JS_RADIO:"mdl-js-radio",RADIO_BTN:"mdl-radio__button",RADIO_OUTER_CIRCLE:"mdl-radio__outer-circle",RADIO_INNER_CIRCLE:"mdl-radio__inner-circle",RIPPLE_EFFECT:"mdl-js-ripple-effect",RIPPLE_IGNORE_EVENTS:"mdl-js-ripple-effect--ignore-events",RIPPLE_CONTAINER:"mdl-radio__ripple-container",RIPPLE_CENTER:"mdl-ripple--center",RIPPLE:"mdl-ripple"},h.prototype.onChange_=function(e){for(var s=document.getElementsByClassName(this.CssClasses_.JS_RADIO),t=0;t<s.length;t++){var i=s[t].querySelector("."+this.CssClasses_.RADIO_BTN);i.getAttribute("name")===this.btnElement_.getAttribute("name")&&s[t].MaterialRadio.updateClasses_()}},h.prototype.onFocus_=function(e){this.element_.classList.add(this.CssClasses_.IS_FOCUSED)},h.prototype.onBlur_=function(e){this.element_.classList.remove(this.CssClasses_.IS_FOCUSED)},h.prototype.onMouseup_=function(e){this.blur_()},h.prototype.updateClasses_=function(){this.checkDisabled(),this.checkToggleState()},h.prototype.blur_=function(e){window.setTimeout(function(){this.btnElement_.blur()}.bind(this),this.Constant_.TINY_TIMEOUT)},h.prototype.checkDisabled=function(){this.btnElement_.disabled?this.element_.classList.add(this.CssClasses_.IS_DISABLED):this.element_.classList.remove(this.CssClasses_.IS_DISABLED)},h.prototype.checkToggleState=function(){this.btnElement_.checked?this.element_.classList.add(this.CssClasses_.IS_CHECKED):this.element_.classList.remove(this.CssClasses_.IS_CHECKED)},h.prototype.disable=function(){this.btnElement_.disabled=!0,this.updateClasses_()},h.prototype.enable=function(){this.btnElement_.disabled=!1,this.updateClasses_()},h.prototype.check=function(){this.btnElement_.checked=!0,this.updateClasses_()},h.prototype.uncheck=function(){this.btnElement_.checked=!1,this.updateClasses_()},h.prototype.init=function(){if(this.element_){this.btnElement_=this.element_.querySelector("."+this.CssClasses_.RADIO_BTN);var e=document.createElement("span");e.classList.add(this.CssClasses_.RADIO_OUTER_CIRCLE);var s=document.createElement("span");s.classList.add(this.CssClasses_.RADIO_INNER_CIRCLE),this.element_.appendChild(e),this.element_.appendChild(s);var t;if(this.element_.classList.contains(this.CssClasses_.RIPPLE_EFFECT)){this.element_.classList.add(this.CssClasses_.RIPPLE_IGNORE_EVENTS),t=document.createElement("span"),t.classList.add(this.CssClasses_.RIPPLE_CONTAINER),t.classList.add(this.CssClasses_.RIPPLE_EFFECT),t.classList.add(this.CssClasses_.RIPPLE_CENTER),t.addEventListener("mouseup",this.onMouseup_.bind(this));var i=document.createElement("span");i.classList.add(this.CssClasses_.RIPPLE),t.appendChild(i),this.element_.appendChild(t)}this.btnElement_.addEventListener("change",this.onChange_.bind(this)),this.btnElement_.addEventListener("focus",this.onFocus_.bind(this)),this.btnElement_.addEventListener("blur",this.onBlur_.bind(this)),this.element_.addEventListener("mouseup",this.onMouseup_.bind(this)),this.updateClasses_(),this.element_.classList.add(this.CssClasses_.IS_UPGRADED)}},componentHandler.register({constructor:h,classAsString:"MaterialRadio",cssClass:"mdl-js-radio",widget:!0});var c=function(e){this.element_=e,this.isIE_=window.navigator.msPointerEnabled,this.init()};window.MaterialSlider=c,c.prototype.Constant_={},c.prototype.CssClasses_={IE_CONTAINER:"mdl-slider__ie-container",SLIDER_CONTAINER:"mdl-slider__container",BACKGROUND_FLEX:"mdl-slider__background-flex",BACKGROUND_LOWER:"mdl-slider__background-lower",BACKGROUND_UPPER:"mdl-slider__background-upper",IS_LOWEST_VALUE:"is-lowest-value",IS_UPGRADED:"is-upgraded"},c.prototype.onInput_=function(e){this.updateValueStyles_()},c.prototype.onChange_=function(e){this.updateValueStyles_()},c.prototype.onMouseUp_=function(e){e.target.blur()},c.prototype.onContainerMouseDown_=function(e){if(e.target===this.element_.parentElement){e.preventDefault();var s=new MouseEvent("mousedown",{target:e.target,buttons:e.buttons,clientX:e.clientX,clientY:this.element_.getBoundingClientRect().y});this.element_.dispatchEvent(s)}},c.prototype.updateValueStyles_=function(e){var s=(this.element_.value-this.element_.min)/(this.element_.max-this.element_.min);0===s?this.element_.classList.add(this.CssClasses_.IS_LOWEST_VALUE):this.element_.classList.remove(this.CssClasses_.IS_LOWEST_VALUE),this.isIE_||(this.backgroundLower_.style.flex=s,this.backgroundLower_.style.webkitFlex=s,this.backgroundUpper_.style.flex=1-s,this.backgroundUpper_.style.webkitFlex=1-s)},c.prototype.disable=function(){this.element_.disabled=!0},c.prototype.enable=function(){this.element_.disabled=!1},c.prototype.change=function(e){"undefined"!=typeof e&&(this.element_.value=e),this.updateValueStyles_()},c.prototype.init=function(){if(this.element_){if(this.isIE_){var e=document.createElement("div");e.classList.add(this.CssClasses_.IE_CONTAINER),this.element_.parentElement.insertBefore(e,this.element_),this.element_.parentElement.removeChild(this.element_),e.appendChild(this.element_)}else{var s=document.createElement("div");s.classList.add(this.CssClasses_.SLIDER_CONTAINER),this.element_.parentElement.insertBefore(s,this.element_),this.element_.parentElement.removeChild(this.element_),s.appendChild(this.element_);var t=document.createElement("div");t.classList.add(this.CssClasses_.BACKGROUND_FLEX),s.appendChild(t),this.backgroundLower_=document.createElement("div"),this.backgroundLower_.classList.add(this.CssClasses_.BACKGROUND_LOWER),t.appendChild(this.backgroundLower_),this.backgroundUpper_=document.createElement("div"),this.backgroundUpper_.classList.add(this.CssClasses_.BACKGROUND_UPPER),t.appendChild(this.backgroundUpper_)}this.boundInputHandler=this.onInput_.bind(this),this.boundChangeHandler=this.onChange_.bind(this),this.boundMouseUpHandler=this.onMouseUp_.bind(this),this.boundContainerMouseDownHandler=this.onContainerMouseDown_.bind(this),this.element_.addEventListener("input",this.boundInputHandler),this.element_.addEventListener("change",this.boundChangeHandler),this.element_.addEventListener("mouseup",this.boundMouseUpHandler),this.element_.parentElement.addEventListener("mousedown",this.boundContainerMouseDownHandler),this.updateValueStyles_(),this.element_.classList.add(this.CssClasses_.IS_UPGRADED)}},c.prototype.mdlDowngrade_=function(){this.element_.removeEventListener("input",this.boundInputHandler),this.element_.removeEventListener("change",this.boundChangeHandler),this.element_.removeEventListener("mouseup",this.boundMouseUpHandler),this.element_.parentElement.removeEventListener("mousedown",this.boundContainerMouseDownHandler)},componentHandler.register({constructor:c,classAsString:"MaterialSlider",cssClass:"mdl-js-slider",widget:!0});var p=function(e){this.element_=e,this.init()};window.MaterialSpinner=p,p.prototype.Constant_={MDL_SPINNER_LAYER_COUNT:4},p.prototype.CssClasses_={MDL_SPINNER_LAYER:"mdl-spinner__layer",MDL_SPINNER_CIRCLE_CLIPPER:"mdl-spinner__circle-clipper",MDL_SPINNER_CIRCLE:"mdl-spinner__circle",MDL_SPINNER_GAP_PATCH:"mdl-spinner__gap-patch",MDL_SPINNER_LEFT:"mdl-spinner__left",MDL_SPINNER_RIGHT:"mdl-spinner__right"},p.prototype.createLayer=function(e){var s=document.createElement("div");s.classList.add(this.CssClasses_.MDL_SPINNER_LAYER),s.classList.add(this.CssClasses_.MDL_SPINNER_LAYER+"-"+e);var t=document.createElement("div");t.classList.add(this.CssClasses_.MDL_SPINNER_CIRCLE_CLIPPER),t.classList.add(this.CssClasses_.MDL_SPINNER_LEFT);var i=document.createElement("div");i.classList.add(this.CssClasses_.MDL_SPINNER_GAP_PATCH);var n=document.createElement("div");n.classList.add(this.CssClasses_.MDL_SPINNER_CIRCLE_CLIPPER),n.classList.add(this.CssClasses_.MDL_SPINNER_RIGHT);for(var a=[t,i,n],l=0;l<a.length;l++){var o=document.createElement("div");o.classList.add(this.CssClasses_.MDL_SPINNER_CIRCLE),a[l].appendChild(o)}s.appendChild(t),s.appendChild(i),s.appendChild(n),this.element_.appendChild(s)},p.prototype.stop=function(){this.element_.classList.remove("is-active")},p.prototype.start=function(){this.element_.classList.add("is-active")},p.prototype.init=function(){if(this.element_){for(var e=1;e<=this.Constant_.MDL_SPINNER_LAYER_COUNT;e++)this.createLayer(e);this.element_.classList.add("is-upgraded");
}},componentHandler.register({constructor:p,classAsString:"MaterialSpinner",cssClass:"mdl-js-spinner",widget:!0});var u=function(e){this.element_=e,this.init()};window.MaterialSwitch=u,u.prototype.Constant_={TINY_TIMEOUT:.001},u.prototype.CssClasses_={INPUT:"mdl-switch__input",TRACK:"mdl-switch__track",THUMB:"mdl-switch__thumb",FOCUS_HELPER:"mdl-switch__focus-helper",RIPPLE_EFFECT:"mdl-js-ripple-effect",RIPPLE_IGNORE_EVENTS:"mdl-js-ripple-effect--ignore-events",RIPPLE_CONTAINER:"mdl-switch__ripple-container",RIPPLE_CENTER:"mdl-ripple--center",RIPPLE:"mdl-ripple",IS_FOCUSED:"is-focused",IS_DISABLED:"is-disabled",IS_CHECKED:"is-checked"},u.prototype.onChange_=function(e){this.updateClasses_()},u.prototype.onFocus_=function(e){this.element_.classList.add(this.CssClasses_.IS_FOCUSED)},u.prototype.onBlur_=function(e){this.element_.classList.remove(this.CssClasses_.IS_FOCUSED)},u.prototype.onMouseUp_=function(e){this.blur_()},u.prototype.updateClasses_=function(){this.checkDisabled(),this.checkToggleState()},u.prototype.blur_=function(e){window.setTimeout(function(){this.inputElement_.blur()}.bind(this),this.Constant_.TINY_TIMEOUT)},u.prototype.checkDisabled=function(){this.inputElement_.disabled?this.element_.classList.add(this.CssClasses_.IS_DISABLED):this.element_.classList.remove(this.CssClasses_.IS_DISABLED)},u.prototype.checkToggleState=function(){this.inputElement_.checked?this.element_.classList.add(this.CssClasses_.IS_CHECKED):this.element_.classList.remove(this.CssClasses_.IS_CHECKED)},u.prototype.disable=function(){this.inputElement_.disabled=!0,this.updateClasses_()},u.prototype.enable=function(){this.inputElement_.disabled=!1,this.updateClasses_()},u.prototype.on=function(){this.inputElement_.checked=!0,this.updateClasses_()},u.prototype.off=function(){this.inputElement_.checked=!1,this.updateClasses_()},u.prototype.init=function(){if(this.element_){this.inputElement_=this.element_.querySelector("."+this.CssClasses_.INPUT);var e=document.createElement("div");e.classList.add(this.CssClasses_.TRACK);var s=document.createElement("div");s.classList.add(this.CssClasses_.THUMB);var t=document.createElement("span");if(t.classList.add(this.CssClasses_.FOCUS_HELPER),s.appendChild(t),this.element_.appendChild(e),this.element_.appendChild(s),this.boundMouseUpHandler=this.onMouseUp_.bind(this),this.element_.classList.contains(this.CssClasses_.RIPPLE_EFFECT)){this.element_.classList.add(this.CssClasses_.RIPPLE_IGNORE_EVENTS),this.rippleContainerElement_=document.createElement("span"),this.rippleContainerElement_.classList.add(this.CssClasses_.RIPPLE_CONTAINER),this.rippleContainerElement_.classList.add(this.CssClasses_.RIPPLE_EFFECT),this.rippleContainerElement_.classList.add(this.CssClasses_.RIPPLE_CENTER),this.rippleContainerElement_.addEventListener("mouseup",this.boundMouseUpHandler);var i=document.createElement("span");i.classList.add(this.CssClasses_.RIPPLE),this.rippleContainerElement_.appendChild(i),this.element_.appendChild(this.rippleContainerElement_)}this.boundChangeHandler=this.onChange_.bind(this),this.boundFocusHandler=this.onFocus_.bind(this),this.boundBlurHandler=this.onBlur_.bind(this),this.inputElement_.addEventListener("change",this.boundChangeHandler),this.inputElement_.addEventListener("focus",this.boundFocusHandler),this.inputElement_.addEventListener("blur",this.boundBlurHandler),this.element_.addEventListener("mouseup",this.boundMouseUpHandler),this.updateClasses_(),this.element_.classList.add("is-upgraded")}},u.prototype.mdlDowngrade_=function(){this.rippleContainerElement_&&this.rippleContainerElement_.removeEventListener("mouseup",this.boundMouseUpHandler),this.inputElement_.removeEventListener("change",this.boundChangeHandler),this.inputElement_.removeEventListener("focus",this.boundFocusHandler),this.inputElement_.removeEventListener("blur",this.boundBlurHandler),this.element_.removeEventListener("mouseup",this.boundMouseUpHandler)},componentHandler.register({constructor:u,classAsString:"MaterialSwitch",cssClass:"mdl-js-switch",widget:!0});var C=function(e){this.element_=e,this.init()};window.MaterialTabs=C,C.prototype.Constant_={},C.prototype.CssClasses_={TAB_CLASS:"mdl-tabs__tab",PANEL_CLASS:"mdl-tabs__panel",ACTIVE_CLASS:"is-active",UPGRADED_CLASS:"is-upgraded",MDL_JS_RIPPLE_EFFECT:"mdl-js-ripple-effect",MDL_RIPPLE_CONTAINER:"mdl-tabs__ripple-container",MDL_RIPPLE:"mdl-ripple",MDL_JS_RIPPLE_EFFECT_IGNORE_EVENTS:"mdl-js-ripple-effect--ignore-events"},C.prototype.initTabs_=function(){this.element_.classList.contains(this.CssClasses_.MDL_JS_RIPPLE_EFFECT)&&this.element_.classList.add(this.CssClasses_.MDL_JS_RIPPLE_EFFECT_IGNORE_EVENTS),this.tabs_=this.element_.querySelectorAll("."+this.CssClasses_.TAB_CLASS),this.panels_=this.element_.querySelectorAll("."+this.CssClasses_.PANEL_CLASS);for(var s=0;s<this.tabs_.length;s++)new e(this.tabs_[s],this);this.element_.classList.add(this.CssClasses_.UPGRADED_CLASS)},C.prototype.resetTabState_=function(){for(var e=0;e<this.tabs_.length;e++)this.tabs_[e].classList.remove(this.CssClasses_.ACTIVE_CLASS)},C.prototype.resetPanelState_=function(){for(var e=0;e<this.panels_.length;e++)this.panels_[e].classList.remove(this.CssClasses_.ACTIVE_CLASS)},C.prototype.init=function(){this.element_&&this.initTabs_()},componentHandler.register({constructor:C,classAsString:"MaterialTabs",cssClass:"mdl-js-tabs"});var m=function(e){this.element_=e,this.maxRows=this.Constant_.NO_MAX_ROWS,this.init()};window.MaterialTextfield=m,m.prototype.Constant_={NO_MAX_ROWS:-1,MAX_ROWS_ATTRIBUTE:"maxrows"},m.prototype.CssClasses_={LABEL:"mdl-textfield__label",INPUT:"mdl-textfield__input",IS_DIRTY:"is-dirty",IS_FOCUSED:"is-focused",IS_DISABLED:"is-disabled",IS_INVALID:"is-invalid",IS_UPGRADED:"is-upgraded"},m.prototype.onKeyDown_=function(e){var s=e.target.value.split("\n").length;13===e.keyCode&&s>=this.maxRows&&e.preventDefault()},m.prototype.onFocus_=function(e){this.element_.classList.add(this.CssClasses_.IS_FOCUSED)},m.prototype.onBlur_=function(e){this.element_.classList.remove(this.CssClasses_.IS_FOCUSED)},m.prototype.updateClasses_=function(){this.checkDisabled(),this.checkValidity(),this.checkDirty()},m.prototype.checkDisabled=function(){this.input_.disabled?this.element_.classList.add(this.CssClasses_.IS_DISABLED):this.element_.classList.remove(this.CssClasses_.IS_DISABLED)},m.prototype.checkValidity=function(){this.input_.validity.valid?this.element_.classList.remove(this.CssClasses_.IS_INVALID):this.element_.classList.add(this.CssClasses_.IS_INVALID)},m.prototype.checkDirty=function(){this.input_.value&&this.input_.value.length>0?this.element_.classList.add(this.CssClasses_.IS_DIRTY):this.element_.classList.remove(this.CssClasses_.IS_DIRTY)},m.prototype.disable=function(){this.input_.disabled=!0,this.updateClasses_()},m.prototype.enable=function(){this.input_.disabled=!1,this.updateClasses_()},m.prototype.change=function(e){e&&(this.input_.value=e),this.updateClasses_()},m.prototype.init=function(){this.element_&&(this.label_=this.element_.querySelector("."+this.CssClasses_.LABEL),this.input_=this.element_.querySelector("."+this.CssClasses_.INPUT),this.input_&&(this.input_.hasAttribute(this.Constant_.MAX_ROWS_ATTRIBUTE)&&(this.maxRows=parseInt(this.input_.getAttribute(this.Constant_.MAX_ROWS_ATTRIBUTE),10),isNaN(this.maxRows)&&(this.maxRows=this.Constant_.NO_MAX_ROWS)),this.boundUpdateClassesHandler=this.updateClasses_.bind(this),this.boundFocusHandler=this.onFocus_.bind(this),this.boundBlurHandler=this.onBlur_.bind(this),this.input_.addEventListener("input",this.boundUpdateClassesHandler),this.input_.addEventListener("focus",this.boundFocusHandler),this.input_.addEventListener("blur",this.boundBlurHandler),this.maxRows!==this.Constant_.NO_MAX_ROWS&&(this.boundKeyDownHandler=this.onKeyDown_.bind(this),this.input_.addEventListener("keydown",this.boundKeyDownHandler)),this.updateClasses_(),this.element_.classList.add(this.CssClasses_.IS_UPGRADED)))},m.prototype.mdlDowngrade_=function(){this.input_.removeEventListener("input",this.boundUpdateClassesHandler),this.input_.removeEventListener("focus",this.boundFocusHandler),this.input_.removeEventListener("blur",this.boundBlurHandler),this.boundKeyDownHandler&&this.input_.removeEventListener("keydown",this.boundKeyDownHandler)},componentHandler.register({constructor:m,classAsString:"MaterialTextfield",cssClass:"mdl-js-textfield",widget:!0});var E=function(e){this.element_=e,this.init()};window.MaterialTooltip=E,E.prototype.Constant_={},E.prototype.CssClasses_={IS_ACTIVE:"is-active"},E.prototype.handleMouseEnter_=function(e){e.stopPropagation();var s=e.target.getBoundingClientRect(),t=s.left+s.width/2,i=-1*(this.element_.offsetWidth/2);0>t+i?(this.element_.style.left=0,this.element_.style.marginLeft=0):(this.element_.style.left=t+"px",this.element_.style.marginLeft=i+"px"),this.element_.style.top=s.top+s.height+10+"px",this.element_.classList.add(this.CssClasses_.IS_ACTIVE),window.addEventListener("scroll",this.boundMouseLeaveHandler,!1),window.addEventListener("touchmove",this.boundMouseLeaveHandler,!1)},E.prototype.handleMouseLeave_=function(e){e.stopPropagation(),this.element_.classList.remove(this.CssClasses_.IS_ACTIVE),window.removeEventListener("scroll",this.boundMouseLeaveHandler),window.removeEventListener("touchmove",this.boundMouseLeaveHandler,!1)},E.prototype.init=function(){if(this.element_){var e=this.element_.getAttribute("for");e&&(this.forElement_=document.getElementById(e)),this.forElement_&&(this.forElement_.getAttribute("tabindex")||this.forElement_.setAttribute("tabindex","0"),this.boundMouseEnterHandler=this.handleMouseEnter_.bind(this),this.boundMouseLeaveHandler=this.handleMouseLeave_.bind(this),this.forElement_.addEventListener("mouseenter",this.boundMouseEnterHandler,!1),this.forElement_.addEventListener("click",this.boundMouseEnterHandler,!1),this.forElement_.addEventListener("blur",this.boundMouseLeaveHandler),this.forElement_.addEventListener("touchstart",this.boundMouseEnterHandler,!1),this.forElement_.addEventListener("mouseleave",this.boundMouseLeaveHandler))}},E.prototype.mdlDowngrade_=function(){this.forElement_&&(this.forElement_.removeEventListener("mouseenter",this.boundMouseEnterHandler,!1),this.forElement_.removeEventListener("click",this.boundMouseEnterHandler,!1),this.forElement_.removeEventListener("touchstart",this.boundMouseEnterHandler,!1),this.forElement_.removeEventListener("mouseleave",this.boundMouseLeaveHandler))},componentHandler.register({constructor:E,classAsString:"MaterialTooltip",cssClass:"mdl-tooltip"});var L=function(e){this.element_=e,this.init()};window.MaterialLayout=L,L.prototype.Constant_={MAX_WIDTH:"(max-width: 1024px)",TAB_SCROLL_PIXELS:100,MENU_ICON:"menu",CHEVRON_LEFT:"chevron_left",CHEVRON_RIGHT:"chevron_right"},L.prototype.Mode_={STANDARD:0,SEAMED:1,WATERFALL:2,SCROLL:3},L.prototype.CssClasses_={CONTAINER:"mdl-layout__container",HEADER:"mdl-layout__header",DRAWER:"mdl-layout__drawer",CONTENT:"mdl-layout__content",DRAWER_BTN:"mdl-layout__drawer-button",ICON:"material-icons",JS_RIPPLE_EFFECT:"mdl-js-ripple-effect",RIPPLE_CONTAINER:"mdl-layout__tab-ripple-container",RIPPLE:"mdl-ripple",RIPPLE_IGNORE_EVENTS:"mdl-js-ripple-effect--ignore-events",HEADER_SEAMED:"mdl-layout__header--seamed",HEADER_WATERFALL:"mdl-layout__header--waterfall",HEADER_SCROLL:"mdl-layout__header--scroll",FIXED_HEADER:"mdl-layout--fixed-header",OBFUSCATOR:"mdl-layout__obfuscator",TAB_BAR:"mdl-layout__tab-bar",TAB_CONTAINER:"mdl-layout__tab-bar-container",TAB:"mdl-layout__tab",TAB_BAR_BUTTON:"mdl-layout__tab-bar-button",TAB_BAR_LEFT_BUTTON:"mdl-layout__tab-bar-left-button",TAB_BAR_RIGHT_BUTTON:"mdl-layout__tab-bar-right-button",PANEL:"mdl-layout__tab-panel",HAS_DRAWER:"has-drawer",HAS_TABS:"has-tabs",HAS_SCROLLING_HEADER:"has-scrolling-header",CASTING_SHADOW:"is-casting-shadow",IS_COMPACT:"is-compact",IS_SMALL_SCREEN:"is-small-screen",IS_DRAWER_OPEN:"is-visible",IS_ACTIVE:"is-active",IS_UPGRADED:"is-upgraded",IS_ANIMATING:"is-animating",ON_LARGE_SCREEN:"mdl-layout--large-screen-only",ON_SMALL_SCREEN:"mdl-layout--small-screen-only"},L.prototype.contentScrollHandler_=function(){this.header_.classList.contains(this.CssClasses_.IS_ANIMATING)||(this.content_.scrollTop>0&&!this.header_.classList.contains(this.CssClasses_.IS_COMPACT)?(this.header_.classList.add(this.CssClasses_.CASTING_SHADOW),this.header_.classList.add(this.CssClasses_.IS_COMPACT),this.header_.classList.add(this.CssClasses_.IS_ANIMATING)):this.content_.scrollTop<=0&&this.header_.classList.contains(this.CssClasses_.IS_COMPACT)&&(this.header_.classList.remove(this.CssClasses_.CASTING_SHADOW),this.header_.classList.remove(this.CssClasses_.IS_COMPACT),this.header_.classList.add(this.CssClasses_.IS_ANIMATING)))},L.prototype.screenSizeHandler_=function(){this.screenSizeMediaQuery_.matches?this.element_.classList.add(this.CssClasses_.IS_SMALL_SCREEN):(this.element_.classList.remove(this.CssClasses_.IS_SMALL_SCREEN),this.drawer_&&this.drawer_.classList.remove(this.CssClasses_.IS_DRAWER_OPEN))},L.prototype.drawerToggleHandler_=function(){this.drawer_.classList.toggle(this.CssClasses_.IS_DRAWER_OPEN)},L.prototype.headerTransitionEndHandler_=function(){this.header_.classList.remove(this.CssClasses_.IS_ANIMATING)},L.prototype.headerClickHandler_=function(){this.header_.classList.contains(this.CssClasses_.IS_COMPACT)&&(this.header_.classList.remove(this.CssClasses_.IS_COMPACT),this.header_.classList.add(this.CssClasses_.IS_ANIMATING))},L.prototype.resetTabState_=function(e){for(var s=0;s<e.length;s++)e[s].classList.remove(this.CssClasses_.IS_ACTIVE)},L.prototype.resetPanelState_=function(e){for(var s=0;s<e.length;s++)e[s].classList.remove(this.CssClasses_.IS_ACTIVE)},L.prototype.init=function(){if(this.element_){var e=document.createElement("div");e.classList.add(this.CssClasses_.CONTAINER),this.element_.parentElement.insertBefore(e,this.element_),this.element_.parentElement.removeChild(this.element_),e.appendChild(this.element_);for(var t=this.element_.childNodes,i=0;i<t.length;i++){var n=t[i];n.classList&&n.classList.contains(this.CssClasses_.HEADER)&&(this.header_=n),n.classList&&n.classList.contains(this.CssClasses_.DRAWER)&&(this.drawer_=n),n.classList&&n.classList.contains(this.CssClasses_.CONTENT)&&(this.content_=n)}this.header_&&(this.tabBar_=this.header_.querySelector("."+this.CssClasses_.TAB_BAR));var a=this.Mode_.STANDARD;this.screenSizeMediaQuery_=window.matchMedia(this.Constant_.MAX_WIDTH),this.screenSizeMediaQuery_.addListener(this.screenSizeHandler_.bind(this)),this.screenSizeHandler_(),this.header_&&(this.header_.classList.contains(this.CssClasses_.HEADER_SEAMED)?a=this.Mode_.SEAMED:this.header_.classList.contains(this.CssClasses_.HEADER_WATERFALL)?(a=this.Mode_.WATERFALL,this.header_.addEventListener("transitionend",this.headerTransitionEndHandler_.bind(this)),this.header_.addEventListener("click",this.headerClickHandler_.bind(this))):this.header_.classList.contains(this.CssClasses_.HEADER_SCROLL)&&(a=this.Mode_.SCROLL,e.classList.add(this.CssClasses_.HAS_SCROLLING_HEADER)),a===this.Mode_.STANDARD?(this.header_.classList.add(this.CssClasses_.CASTING_SHADOW),this.tabBar_&&this.tabBar_.classList.add(this.CssClasses_.CASTING_SHADOW)):a===this.Mode_.SEAMED||a===this.Mode_.SCROLL?(this.header_.classList.remove(this.CssClasses_.CASTING_SHADOW),this.tabBar_&&this.tabBar_.classList.remove(this.CssClasses_.CASTING_SHADOW)):a===this.Mode_.WATERFALL&&(this.content_.addEventListener("scroll",this.contentScrollHandler_.bind(this)),this.contentScrollHandler_()));var l=function(e){e.preventDefault()};if(this.drawer_){var o=document.createElement("div");o.classList.add(this.CssClasses_.DRAWER_BTN),this.drawer_.classList.contains(this.CssClasses_.ON_LARGE_SCREEN)?o.classList.add(this.CssClasses_.ON_LARGE_SCREEN):this.drawer_.classList.contains(this.CssClasses_.ON_SMALL_SCREEN)&&o.classList.add(this.CssClasses_.ON_SMALL_SCREEN);var r=document.createElement("i");r.classList.add(this.CssClasses_.ICON),r.textContent=this.Constant_.MENU_ICON,o.appendChild(r),o.addEventListener("click",this.drawerToggleHandler_.bind(this)),this.element_.classList.add(this.CssClasses_.HAS_DRAWER),this.drawer_.addEventListener("mousewheel",l),this.element_.classList.contains(this.CssClasses_.FIXED_HEADER)?this.header_.insertBefore(o,this.header_.firstChild):this.element_.insertBefore(o,this.content_);var _=document.createElement("div");_.classList.add(this.CssClasses_.OBFUSCATOR),this.element_.appendChild(_),_.addEventListener("click",this.drawerToggleHandler_.bind(this)),_.addEventListener("mousewheel",l)}if(this.header_&&this.tabBar_){this.element_.classList.add(this.CssClasses_.HAS_TABS);var d=document.createElement("div");d.classList.add(this.CssClasses_.TAB_CONTAINER),this.header_.insertBefore(d,this.tabBar_),this.header_.removeChild(this.tabBar_);var h=document.createElement("div");h.classList.add(this.CssClasses_.TAB_BAR_BUTTON),h.classList.add(this.CssClasses_.TAB_BAR_LEFT_BUTTON);var c=document.createElement("i");c.classList.add(this.CssClasses_.ICON),c.textContent=this.Constant_.CHEVRON_LEFT,h.appendChild(c),h.addEventListener("click",function(){this.tabBar_.scrollLeft-=this.Constant_.TAB_SCROLL_PIXELS}.bind(this));var p=document.createElement("div");p.classList.add(this.CssClasses_.TAB_BAR_BUTTON),p.classList.add(this.CssClasses_.TAB_BAR_RIGHT_BUTTON);var u=document.createElement("i");u.classList.add(this.CssClasses_.ICON),u.textContent=this.Constant_.CHEVRON_RIGHT,p.appendChild(u),p.addEventListener("click",function(){this.tabBar_.scrollLeft+=this.Constant_.TAB_SCROLL_PIXELS}.bind(this)),d.appendChild(h),d.appendChild(this.tabBar_),d.appendChild(p);var C=function(){this.tabBar_.scrollLeft>0?h.classList.add(this.CssClasses_.IS_ACTIVE):h.classList.remove(this.CssClasses_.IS_ACTIVE),this.tabBar_.scrollLeft<this.tabBar_.scrollWidth-this.tabBar_.offsetWidth?p.classList.add(this.CssClasses_.IS_ACTIVE):p.classList.remove(this.CssClasses_.IS_ACTIVE)}.bind(this);this.tabBar_.addEventListener("scroll",C),C(),this.tabBar_.classList.contains(this.CssClasses_.JS_RIPPLE_EFFECT)&&this.tabBar_.classList.add(this.CssClasses_.RIPPLE_IGNORE_EVENTS);for(var m=this.tabBar_.querySelectorAll("."+this.CssClasses_.TAB),E=this.content_.querySelectorAll("."+this.CssClasses_.PANEL),L=0;L<m.length;L++)new s(m[L],m,E,this)}this.element_.classList.add(this.CssClasses_.IS_UPGRADED)}},componentHandler.register({constructor:L,classAsString:"MaterialLayout",cssClass:"mdl-js-layout"});var I=function(e){this.element_=e,this.init()};window.MaterialDataTable=I,I.prototype.Constant_={},I.prototype.CssClasses_={DATA_TABLE:"mdl-data-table",SELECTABLE:"mdl-data-table--selectable",IS_SELECTED:"is-selected",IS_UPGRADED:"is-upgraded"},I.prototype.selectRow_=function(e,s,t){return s?function(){e.checked?s.classList.add(this.CssClasses_.IS_SELECTED):s.classList.remove(this.CssClasses_.IS_SELECTED)}.bind(this):t?function(){var s,i;if(e.checked)for(s=0;s<t.length;s++)i=t[s].querySelector("td").querySelector(".mdl-checkbox"),i.MaterialCheckbox.check(),t[s].classList.add(this.CssClasses_.IS_SELECTED);else for(s=0;s<t.length;s++)i=t[s].querySelector("td").querySelector(".mdl-checkbox"),i.MaterialCheckbox.uncheck(),t[s].classList.remove(this.CssClasses_.IS_SELECTED)}.bind(this):void 0},I.prototype.createCheckbox_=function(e,s){var t=document.createElement("label");t.classList.add("mdl-checkbox"),t.classList.add("mdl-js-checkbox"),t.classList.add("mdl-js-ripple-effect"),t.classList.add("mdl-data-table__select");var i=document.createElement("input");return i.type="checkbox",i.classList.add("mdl-checkbox__input"),e?i.addEventListener("change",this.selectRow_(i,e)):s&&i.addEventListener("change",this.selectRow_(i,null,s)),t.appendChild(i),componentHandler.upgradeElement(t,"MaterialCheckbox"),t},I.prototype.init=function(){if(this.element_){var e=this.element_.querySelector("th"),s=this.element_.querySelector("tbody").querySelectorAll("tr");if(this.element_.classList.contains(this.CssClasses_.SELECTABLE)){var t=document.createElement("th"),i=this.createCheckbox_(null,s);t.appendChild(i),e.parentElement.insertBefore(t,e);for(var n=0;n<s.length;n++){var a=s[n].querySelector("td");if(a){var l=document.createElement("td"),o=this.createCheckbox_(s[n]);l.appendChild(o),s[n].insertBefore(l,a)}}}this.element_.classList.add(this.CssClasses_.IS_UPGRADED)}},componentHandler.register({constructor:I,classAsString:"MaterialDataTable",cssClass:"mdl-js-data-table"});var f=function(e){this.element_=e,this.init()};window.MaterialRipple=f,f.prototype.Constant_={INITIAL_SCALE:"scale(0.0001, 0.0001)",INITIAL_SIZE:"1px",INITIAL_OPACITY:"0.4",FINAL_OPACITY:"0",FINAL_SCALE:""},f.prototype.CssClasses_={RIPPLE_CENTER:"mdl-ripple--center",RIPPLE_EFFECT_IGNORE_EVENTS:"mdl-js-ripple-effect--ignore-events",RIPPLE:"mdl-ripple",IS_ANIMATING:"is-animating",IS_VISIBLE:"is-visible"},f.prototype.downHandler_=function(e){if(!this.rippleElement_.style.width&&!this.rippleElement_.style.height){var s=this.element_.getBoundingClientRect();this.boundHeight=s.height,this.boundWidth=s.width,this.rippleSize_=2*Math.sqrt(s.width*s.width+s.height*s.height)+2,this.rippleElement_.style.width=this.rippleSize_+"px",this.rippleElement_.style.height=this.rippleSize_+"px"}if(this.rippleElement_.classList.add(this.CssClasses_.IS_VISIBLE),"mousedown"===e.type&&this.ignoringMouseDown_)this.ignoringMouseDown_=!1;else{"touchstart"===e.type&&(this.ignoringMouseDown_=!0);var t=this.getFrameCount();if(t>0)return;this.setFrameCount(1);var i,n,a=e.currentTarget.getBoundingClientRect();if(0===e.clientX&&0===e.clientY)i=Math.round(a.width/2),n=Math.round(a.height/2);else{var l=e.clientX?e.clientX:e.touches[0].clientX,o=e.clientY?e.clientY:e.touches[0].clientY;i=Math.round(l-a.left),n=Math.round(o-a.top)}this.setRippleXY(i,n),this.setRippleStyles(!0),window.requestAnimationFrame(this.animFrameHandler.bind(this))}},f.prototype.upHandler_=function(e){e&&2!==e.detail&&this.rippleElement_.classList.remove(this.CssClasses_.IS_VISIBLE),window.setTimeout(function(){this.rippleElement_.classList.remove(this.CssClasses_.IS_VISIBLE)}.bind(this),0)},f.prototype.init=function(){if(this.element_){var e=this.element_.classList.contains(this.CssClasses_.RIPPLE_CENTER);this.element_.classList.contains(this.CssClasses_.RIPPLE_EFFECT_IGNORE_EVENTS)||(this.rippleElement_=this.element_.querySelector("."+this.CssClasses_.RIPPLE),this.frameCount_=0,this.rippleSize_=0,this.x_=0,this.y_=0,this.ignoringMouseDown_=!1,this.boundDownHandler=this.downHandler_.bind(this),this.element_.addEventListener("mousedown",this.boundDownHandler),this.element_.addEventListener("touchstart",this.boundDownHandler),this.boundUpHandler=this.upHandler_.bind(this),this.element_.addEventListener("mouseup",this.boundUpHandler),this.element_.addEventListener("mouseleave",this.boundUpHandler),this.element_.addEventListener("touchend",this.boundUpHandler),this.element_.addEventListener("blur",this.boundUpHandler),this.getFrameCount=function(){return this.frameCount_},this.setFrameCount=function(e){this.frameCount_=e},this.getRippleElement=function(){return this.rippleElement_},this.setRippleXY=function(e,s){this.x_=e,this.y_=s},this.setRippleStyles=function(s){if(null!==this.rippleElement_){var t,i,n,a="translate("+this.x_+"px, "+this.y_+"px)";s?(i=this.Constant_.INITIAL_SCALE,n=this.Constant_.INITIAL_SIZE):(i=this.Constant_.FINAL_SCALE,n=this.rippleSize_+"px",e&&(a="translate("+this.boundWidth/2+"px, "+this.boundHeight/2+"px)")),t="translate(-50%, -50%) "+a+i,this.rippleElement_.style.webkitTransform=t,this.rippleElement_.style.msTransform=t,this.rippleElement_.style.transform=t,s?this.rippleElement_.classList.remove(this.CssClasses_.IS_ANIMATING):this.rippleElement_.classList.add(this.CssClasses_.IS_ANIMATING)}},this.animFrameHandler=function(){this.frameCount_-->0?window.requestAnimationFrame(this.animFrameHandler.bind(this)):this.setRippleStyles(!1)})}},f.prototype.mdlDowngrade_=function(){this.element_.removeEventListener("mousedown",this.boundDownHandler),this.element_.removeEventListener("touchstart",this.boundDownHandler),this.element_.removeEventListener("mouseup",this.boundUpHandler),this.element_.removeEventListener("mouseleave",this.boundUpHandler),this.element_.removeEventListener("touchend",this.boundUpHandler),this.element_.removeEventListener("blur",this.boundUpHandler)},componentHandler.register({constructor:f,classAsString:"MaterialRipple",cssClass:"mdl-js-ripple-effect",widget:!1})}();
//# sourceMappingURL=material.min.js.map |
import React, { Fragment, useEffect } from 'react';
import PropTypes from 'prop-types';
import { connect } from 'react-redux';
import { Spin } from 'antd';
import {
getNotifications,
markAllReadNotifications,
clearAllNotifications,
} from '../../redux/actions/notification';
import NotificationItem from './NotificationItem';
const Notifications = ({
notification: { loading, notifications },
getNotifications,
markAllReadNotifications,
clearAllNotifications,
}) => {
useEffect(() => {
getNotifications();
// eslint-disable-next-line
}, []);
return (
<Fragment>
<div className='arrow-nav'></div>
<div className='notifications-title'>
Notifications
<span>
<span onClick={() => markAllReadNotifications()}>
Mark All as Read
</span>{' '}
<span onClick={() => clearAllNotifications()}>Clear All</span>
</span>
</div>
<ul className='notifications'>
{loading ? (
<li style={{ justifyContent: 'center' }}>
<Spin />
</li>
) : notifications.length > 0 ? (
notifications.map((notification) => (
<NotificationItem
key={notification._id}
notification={notification}
/>
))
) : (
<li>No notifications...</li>
)}
</ul>
</Fragment>
);
};
Notifications.propTypes = {
notification: PropTypes.object.isRequired,
getNotifications: PropTypes.func.isRequired,
markAllReadNotifications: PropTypes.func.isRequired,
clearAllNotifications: PropTypes.func.isRequired,
};
const mapStateToProps = (state) => ({
notification: state.notification,
});
export default connect(mapStateToProps, {
getNotifications,
markAllReadNotifications,
clearAllNotifications,
})(Notifications);
|
def process_2arrays(arr1, arr2):
s1,s2 = set(arr1), set(arr2)
return [len(s1 & s2), len(s1 ^ s2), len(s1 - s2), len(s2 - s1)] |
import * as React from 'react';
import wrapIcon from '../utils/wrapIcon';
const rawSvg = (iconProps) => {
const { className, primaryFill } = iconProps;
return React.createElement("svg", { width: 16, height: 16, viewBox: "0 0 16 16", xmlns: "http://www.w3.org/2000/svg", className: className },
React.createElement("path", { d: "M2.95 3.94a3.25 3.25 0 014.6 0l.44.46.45-.45a3.25 3.25 0 014.62 4.6l-4.69 4.69a.5.5 0 01-.7 0l-4.71-4.7a3.25 3.25 0 01-.01-4.6zm5.07 8.24l4.33-4.33c.87-.88.87-2.3-.01-3.18a2.25 2.25 0 00-3.2-.01l-.24.25a.5.5 0 01-.05.05L7.71 6.11l1.64 1.65c.2.2.2.5 0 .7l-1.5 1.5a.5.5 0 01-.7-.7L8.29 8.1 6.65 6.46a.5.5 0 010-.7l.64-.65-.46-.46a2.25 2.25 0 00-3.18 0c-.87.87-.87 2.3.01 3.17l4.36 4.36z", fill: primaryFill }));
};
const HeartBroken16Regular = wrapIcon(rawSvg({}), 'HeartBroken16Regular');
export default HeartBroken16Regular;
|
# Copyright 2019 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import re
"""Presubmit for build/util"""
USE_PYTHON3 = True
def _GetFilesToSkip(input_api):
files_to_skip = []
affected_files = input_api.change.AffectedFiles()
version_script_change = next(
(f for f in affected_files
if re.search('\\/version\\.py$|\\/version_test\\.py$', f.LocalPath())),
None)
if version_script_change is None:
files_to_skip.append('version_test\\.py$')
android_chrome_version_script_change = next(
(f for f in affected_files if re.search(
'\\/android_chrome_version\\.py$|'
'\\/android_chrome_version_test\\.py$', f.LocalPath())), None)
if android_chrome_version_script_change is None:
files_to_skip.append('android_chrome_version_test\\.py$')
return files_to_skip
def _GetPythonUnitTests(input_api, output_api):
# No need to test if files are unchanged
files_to_skip = _GetFilesToSkip(input_api)
return input_api.canned_checks.GetUnitTestsRecursively(
input_api,
output_api,
input_api.PresubmitLocalPath(),
files_to_check=['.*_test\\.py$'],
files_to_skip=files_to_skip,
run_on_python2=False,
run_on_python3=True,
skip_shebang_check=True)
def CommonChecks(input_api, output_api):
"""Presubmit checks run on both upload and commit.
"""
checks = []
checks.extend(_GetPythonUnitTests(input_api, output_api))
return input_api.RunTests(checks, False)
def CheckChangeOnUpload(input_api, output_api):
"""Presubmit checks on CL upload."""
return CommonChecks(input_api, output_api)
def CheckChangeOnCommit(input_api, output_api):
"""Presubmit checks on commit."""
return CommonChecks(input_api, output_api)
|
/**
* This file is part of Wizkers.io
*
* The MIT License (MIT)
* Copyright (c) 2016 Edouard Lafargue, [email protected]
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the Software
* is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
* WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR
* IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
/*
* Display output of Geiger counter in numeric format
* Geiger Link provides slightly different outputs from the Onyx, so
* we are using a different display for it:
*
* @author Edouard Lafargue, [email protected]
* All rights reserved.
*/
define(function(require) {
"use strict";
var $ = require('jquery'),
_ = require('underscore'),
Backbone = require('backbone'),
utils = require('app/utils'),
template = require('js/tpl/instruments/USBGeigerNumView.js');
return Backbone.View.extend({
initialize:function (options) {
this.sessionStartStamp = new Date().getTime();
this.maxreading = 0;
this.minreading = -1;
this.maxreading_2 = 0;
this.minreading_2 = -1;
this.valid = false;
this.validinit = false;
linkManager.on('input', this.showInput, this);
},
events: {
},
render:function () {
var self = this;
console.log('Main render of Onyx numeric view');
this.$el.html(template());
// We need to force the Live view to resize the map at this
// stage, becaure we just changed the size of the numview
if (instrumentManager.liveViewRef() && instrumentManager.liveViewRef().rsc) {
instrumentManager.liveViewRef().rsc();
};
return this;
},
onClose: function() {
console.log("Onyx numeric view closing...");
linkManager.off('input', this.showInput, this);
},
showInput: function(data) {
if (data.cpm) {
var cpm = parseFloat(data.cpm.value);
$('#livecpm', this.el).html(cpm.toFixed(0));
//$('#liveusvh', this.el).html((cpm*0.00294).toFixed(3) + " μSv/h");
if (data.cpm.valid)
$('#readingvalid', this.el).removeClass('label-danger').addClass('label-success').html('VALID');
else
$('#readingvalid', this.el).removeClass('label-success').addClass('label-danger').html('INVALID');
// Update statistics:
var sessionDuration = (new Date().getTime() - this.sessionStartStamp)/1000;
$('#sessionlength',this.el).html(utils.hms(sessionDuration));
if (cpm > this.maxreading) {
this.maxreading = cpm;
$('#maxreading', this.el).html(cpm);
}
if (cpm < this.minreading || this.minreading == -1) {
this.minreading = cpm;
$('#minreading', this.el).html(cpm);
}
if (data.cpm2) {
$('.dual_input', this.el).show();
cpm = parseFloat(data.cpm2.value);
$('#livecpm_2', this.el).html(cpm.toFixed(0));
//$('#liveusvh', this.el).html((cpm*0.00294).toFixed(3) + " μSv/h");
if (data.cpm2.valid)
$('#readingvalid_2', this.el).removeClass('label-danger').addClass('label-success').html('VALID');
else
$('#readingvalid_2', this.el).removeClass('label-success').addClass('label-danger').html('INVALID');
if (cpm > this.maxreading_2) {
this.maxreading_2 = cpm;
$('#maxreading_2', this.el).html(cpm);
}
if (cpm < this.minreading_2 || this.minreading_2 == -1) {
this.minreading_2 = cpm;
$('#minreading_2', this.el).html(cpm);
}
} else {
$('.dual_input', this.el).hide();
}
} else if (data.counts) {
$('#total_count', this.el).show();
var count = data.counts.input1; // Note: should be an integer in the json structure
var duration = data.counts.uptime/1000;
$('#total_pulse_count', this.el).html(count);
$('#pulse_count_duration', this.el).html(utils.hms(duration));
$('#pulse_count_avg',this.el).html((count/duration*60).toFixed(3) + " CPM");
if (data.counts.input2) {
count = data.counts.input2;
$('#total_pulse_count_2', this.el).html(count);
$('#pulse_count_avg_2',this.el).html((count/duration*60).toFixed(3) + " CPM");
}
}
},
});
}); |
const elm = document.getElementById('status');
const hudContainer = document.getElementById('top-right');
const currentLevelDisplay = hudContainer.querySelector('.levelHud')
const pointsDisplay = hudContainer.querySelector('.pointHud')
const speedDisplay = hudContainer.querySelector('.speedHud')
function showMessage(message){
if(elm === null)
return;
elm.textContent = message;
elm.style.display = 'block'
//setTimeout(hideMessage, 3000)
}
function hideMessage(){
if(elm === null)
return;
elm.style.display = 'none'
}
function updateLevel(lvl){
if(currentLevelDisplay === null)
return;
currentLevelDisplay.textContent = 'Level: ' + lvl;
}
function updateSpeed(moveSpeed){
if(speedDisplay === null)
return;
speedDisplay.textContent = 'Speed: ' + moveSpeed;
}
function updatePoints(pts){
if(pointsDisplay === null){
return;
}
pointsDisplay.textContent = 'Points: ' + Number(pts);
}
export {showMessage, hideMessage, updateLevel, updatePoints, updateSpeed}; |
// Licensed to Cloudera, Inc. under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. Cloudera, Inc. 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 $ from 'jquery';
import * as ko from 'knockout';
import {
assistErrorCallback,
cancelActiveRequest,
simpleGet,
simplePost,
successResponseIsError
} from './apiUtils';
import apiQueueManager from 'api/apiQueueManager';
import CancellablePromise from 'api/cancellablePromise';
import hueDebug from 'utils/hueDebug';
import huePubSub from 'utils/huePubSub';
import hueUtils from 'utils/hueUtils';
import { EXECUTION_STATUS } from 'apps/notebook2/execution/executable';
import * as URLS from './urls';
export const LINK_SHARING_PERMS = {
READ: 'read',
WRITE: 'write',
OFF: 'off'
};
/**
* Wrapper around the response from the Query API
*
* @param {string} sourceType
* @param {Object} response
*
* @constructor
*/
class QueryResult {
constructor(sourceType, compute, response) {
this.id = hueUtils.UUID();
this.type = response.result && response.result.type ? response.result.type : sourceType;
this.compute = compute;
this.status = response.status || 'running';
this.result = response.result || {};
this.result.type = 'table';
}
}
class ApiHelper {
constructor() {
this.queueManager = apiQueueManager;
this.cancelActiveRequest = cancelActiveRequest; // TODO: Remove when job_browser.mako is in webpack
huePubSub.subscribe('assist.clear.git.cache', () => {
$.totalStorage(this.getAssistCacheIdentifier({ sourceType: 'git' }), {});
});
huePubSub.subscribe('assist.clear.collections.cache', () => {
$.totalStorage(this.getAssistCacheIdentifier({ sourceType: 'collections' }), {});
});
huePubSub.subscribe('assist.clear.hbase.cache', () => {
$.totalStorage(this.getAssistCacheIdentifier({ sourceType: 'hbase' }), {});
});
huePubSub.subscribe('assist.clear.document.cache', () => {
$.totalStorage(this.getAssistCacheIdentifier({ sourceType: 'document' }), {});
});
const clearAllCaches = () => {
this.clearDbCache({
sourceType: 'hive',
clearAll: true
});
this.clearDbCache({
sourceType: 'impala',
clearAll: true
});
$.totalStorage(this.getAssistCacheIdentifier({ sourceType: 'hdfs' }), {});
$.totalStorage(this.getAssistCacheIdentifier({ sourceType: 'adls' }), {});
$.totalStorage(this.getAssistCacheIdentifier({ sourceType: 'abfs' }), {});
$.totalStorage(this.getAssistCacheIdentifier({ sourceType: 'git' }), {});
$.totalStorage(this.getAssistCacheIdentifier({ sourceType: 's3' }), {});
$.totalStorage(this.getAssistCacheIdentifier({ sourceType: 'collections' }), {});
$.totalStorage(this.getAssistCacheIdentifier({ sourceType: 'hbase' }), {});
$.totalStorage(this.getAssistCacheIdentifier({ sourceType: 'document' }), {});
};
huePubSub.subscribe('assist.clear.all.caches', clearAllCaches);
if (window.performance && window.performance.navigation) {
if (window.performance.navigation.type === 1 && location.href.indexOf('/metastore') !== -1) {
// Browser refresh of the metastore page
clearAllCaches();
}
}
}
clearStorageCache(sourceType) {
$.totalStorage(this.getAssistCacheIdentifier({ sourceType: sourceType }), {});
}
hasExpired(timestamp, cacheType) {
if (typeof hueDebug !== 'undefined' && typeof hueDebug.cacheTimeout !== 'undefined') {
return new Date().getTime() - timestamp > hueDebug.cacheTimeout;
}
return new Date().getTime() - timestamp > CACHEABLE_TTL[cacheType];
}
/**
*
* @param {Object} options
* @param {string} options.sourceType
* @param {string} options.url
* @param {boolean} options.refreshCache
* @param {string} [options.hash] - Optional hash to use as well as the url
* @param {Function} options.fetchFunction
* @param {Function} options.successCallback
* @param {string} [options.cacheType] - Possible values 'default'|'optimizer'. Default value 'default'
* @param {Object} [options.editor] - Ace editor
* @param {Object} [options.promise] - Optional promise that will be resolved if cached data exists
*/
fetchCached(options) {
const cacheIdentifier = this.getAssistCacheIdentifier(options);
const cachedData = $.totalStorage(cacheIdentifier) || {};
const cachedId = options.hash ? options.url + options.hash : options.url;
if (
options.refreshCache ||
typeof cachedData[cachedId] == 'undefined' ||
this.hasExpired(cachedData[cachedId].timestamp, options.cacheType || 'default')
) {
if (typeof options.editor !== 'undefined' && options.editor !== null) {
options.editor.showSpinner();
}
return options.fetchFunction(data => {
cachedData[cachedId] = {
timestamp: new Date().getTime(),
data: data
};
try {
$.totalStorage(cacheIdentifier, cachedData);
} catch (e) {}
});
} else {
if (options.promise) {
options.promise.resolve(cachedData[cachedId].data);
}
options.successCallback(cachedData[cachedId].data);
}
}
/**
* @param {string} sourceType
* @returns {string}
*/
getTotalStorageUserPrefix(sourceType) {
return sourceType + '_' + window.LOGGED_USERNAME + '_' + window.location.hostname;
}
/**
* @param {object} options
* @param {string} options.sourceType
* @param {string} [options.cacheType] - Default value 'default'
* @returns {string}
*/
getAssistCacheIdentifier(options) {
return (
'hue.assist.' +
(options.cacheType || 'default') +
'.' +
this.getTotalStorageUserPrefix(options.sourceType)
);
}
/**
*
* @param {string} owner - 'assist', 'viewModelA' etc.
* @param {string} id
* @param {*} [value] - Optional, undefined and null will remove the value
*/
setInTotalStorage(owner, id, value) {
try {
const cachedData =
$.totalStorage('hue.user.settings.' + this.getTotalStorageUserPrefix(owner)) || {};
if (typeof value !== 'undefined' && value !== null) {
cachedData[id] = value;
$.totalStorage('hue.user.settings.' + this.getTotalStorageUserPrefix(owner), cachedData, {
secure: window.location.protocol.indexOf('https') > -1
});
} else if (cachedData[id]) {
delete cachedData[id];
$.totalStorage('hue.user.settings.' + this.getTotalStorageUserPrefix(owner), cachedData, {
secure: window.location.protocol.indexOf('https') > -1
});
}
} catch (e) {}
}
/**
*
* @param {string} owner - 'assist', 'viewModelA' etc.
* @param {string} id
* @param {*} [defaultValue]
* @returns {*}
*/
getFromTotalStorage(owner, id, defaultValue) {
const cachedData =
$.totalStorage('hue.user.settings.' + this.getTotalStorageUserPrefix(owner)) || {};
return typeof cachedData[id] !== 'undefined' ? cachedData[id] : defaultValue;
}
/**
* @param {string} owner - 'assist', 'viewModelA' etc.
* @param {string} id
* @param {Observable} observable
* @param {*} [defaultValue] - Optional default value to use if not in total storage initially
*/
withTotalStorage(owner, id, observable, defaultValue, noInit) {
const cachedValue = this.getFromTotalStorage(owner, id, defaultValue);
if (!noInit && cachedValue !== 'undefined') {
observable(cachedValue);
}
observable.subscribe(newValue => {
if (owner === 'assist' && id === 'assist_panel_visible') {
huePubSub.publish('assist.forceRender');
}
this.setInTotalStorage(owner, id, newValue);
});
return observable;
}
/**
* @param {Object} data
* @param {Object} options
* @param {function} [options.successCallback]
*/
saveSnippetToFile(data, options) {
$.post(
URLS.SAVE_TO_FILE_API,
data,
result => {
if (typeof options.successCallback !== 'undefined') {
options.successCallback(result);
}
},
'json'
).fail(assistErrorCallback(options));
}
fetchUsersAndGroups(options) {
$.ajax({
method: 'GET',
url: '/desktop/api/users/autocomplete',
data: options.data || {},
contentType: 'application/json'
})
.done(response => {
options.successCallback(response);
})
.fail(response => {
options.errorCallback(response);
});
}
fetchUsersByIds(options) {
$.ajax({
method: 'GET',
url: '/desktop/api/users',
data: { userids: options.userids },
contentType: 'application/json'
})
.done(response => {
options.successCallback(response);
})
.fail(response => {
options.errorCallback(response);
});
}
/**
*
* @param {Object} options
* @param {string} options.location
* @param {boolean} [options.silenceErrors]
*/
fetchTopo(options) {
const url = URLS.TOPO_URL + options.location;
return simpleGet(url, undefined, options);
}
/**
*
* @param {Object} options
* @param {string[]} options.path
* @param {string} options.type - 's3', 'adls', 'abfs' or 'hdfs'
* @param {number} [options.offset]
* @param {number} [options.length]
* @param {boolean} [options.silenceErrors]
*/
fetchStoragePreview(options) {
let url;
if (options.type === 's3') {
url = URLS.S3_API_PREFIX;
} else if (options.type === 'adls') {
url = URLS.ADLS_API_PREFIX;
} else if (options.type === 'abfs') {
url = URLS.ABFS_API_PREFIX;
} else {
url = URLS.HDFS_API_PREFIX;
}
const clonedPath = options.path.concat();
if (clonedPath.length && clonedPath[0] === '/') {
clonedPath.shift();
}
url += clonedPath.join('/').replace(/#/g, '%23') + '?compression=none&mode=text';
url += '&offset=' + (options.offset || 0);
url += '&length=' + (options.length || 118784);
const deferred = $.Deferred();
$.ajax({
dataType: 'json',
url: url,
success: data => {
if (successResponseIsError(data)) {
deferred.reject(assistErrorCallback(options)(data));
} else {
deferred.resolve(data);
}
},
fail: deferred.reject
});
return deferred.promise();
}
/**
* @param {Object} options
* @param {Function} options.successCallback
* @param {Function} [options.errorCallback]
* @param {boolean} [options.silenceErrors]
* @param {Number} [options.timeout]
* @param {Object} [options.editor] - Ace editor
*
* @param {string[]} options.pathParts
* @param {number} [options.pageSize] - Default 500
* @param {number} [options.page] - Default 1
* @param {string} [options.filter]
*/
fetchHdfsPath(options) {
if (
options.pathParts.length > 0 &&
(options.pathParts[0] === '/' || options.pathParts[0] === '')
) {
options.pathParts.shift();
}
let url =
URLS.HDFS_API_PREFIX +
encodeURI(options.pathParts.join('/')) +
'?format=json&sortby=name&descending=false&pagesize=' +
(options.pageSize || 500) +
'&pagenum=' +
(options.page || 1);
if (options.filter) {
url += '&filter=' + options.filter;
}
const fetchFunction = storeInCache => {
if (options.timeout === 0) {
assistErrorCallback(options)({ status: -1 });
return;
}
return $.ajax({
dataType: 'json',
url: url,
timeout: options.timeout,
success: data => {
if (
!data.error &&
!successResponseIsError(data) &&
typeof data.files !== 'undefined' &&
data.files !== null
) {
if (data.files.length > 2 && !options.filter) {
storeInCache(data);
}
options.successCallback(data);
} else {
assistErrorCallback(options)(data);
}
}
})
.fail(assistErrorCallback(options))
.always(() => {
if (typeof options.editor !== 'undefined' && options.editor !== null) {
options.editor.hideSpinner();
}
});
};
return this.fetchCached(
$.extend({}, options, {
sourceType: 'hdfs',
url: url,
fetchFunction: fetchFunction
})
);
}
/**
* @param {Object} options
* @param {Function} options.successCallback
* @param {Function} [options.errorCallback]
* @param {boolean} [options.silenceErrors]
* @param {Number} [options.timeout]
* @param {Object} [options.editor] - Ace editor
*
* @param {string[]} options.pathParts
* @param {number} [options.pageSize] - Default 500
* @param {number} [options.page] - Default 1
* @param {string} [options.filter]
*/
fetchAdlsPath(options) {
options.pathParts.shift();
let url =
URLS.ADLS_API_PREFIX +
encodeURI(options.pathParts.join('/')) +
'?format=json&sortby=name&descending=false&pagesize=' +
(options.pageSize || 500) +
'&pagenum=' +
(options.page || 1);
if (options.filter) {
url += '&filter=' + options.filter;
}
const fetchFunction = storeInCache => {
if (options.timeout === 0) {
assistErrorCallback(options)({ status: -1 });
return;
}
return $.ajax({
dataType: 'json',
url: url,
timeout: options.timeout,
success: data => {
if (
!data.error &&
!successResponseIsError(data) &&
typeof data.files !== 'undefined' &&
data.files !== null
) {
if (data.files.length > 2 && !options.filter) {
storeInCache(data);
}
options.successCallback(data);
} else {
assistErrorCallback(options)(data);
}
}
})
.fail(assistErrorCallback(options))
.always(() => {
if (typeof options.editor !== 'undefined' && options.editor !== null) {
options.editor.hideSpinner();
}
});
};
return this.fetchCached(
$.extend({}, options, {
sourceType: 'adls',
url: url,
fetchFunction: fetchFunction
})
);
}
/**
* @param {Object} options
* @param {Function} options.successCallback
* @param {Function} [options.errorCallback]
* @param {boolean} [options.silenceErrors]
* @param {Number} [options.timeout]
* @param {Object} [options.editor] - Ace editor
*
* @param {string[]} options.pathParts
* @param {number} [options.pageSize] - Default 500
* @param {number} [options.page] - Default 1
* @param {string} [options.filter]
*/
fetchAbfsPath(options) {
let url =
URLS.ABFS_API_PREFIX +
encodeURI(options.pathParts.join('/')) +
'?format=json&sortby=name&descending=false&pagesize=' +
(options.pageSize || 500) +
'&pagenum=' +
(options.page || 1);
if (options.filter) {
url += '&filter=' + options.filter;
}
const fetchFunction = storeInCache => {
if (options.timeout === 0) {
assistErrorCallback(options)({ status: -1 });
return;
}
return $.ajax({
dataType: 'json',
url: url,
timeout: options.timeout,
success: data => {
if (
!data.error &&
!successResponseIsError(data) &&
typeof data.files !== 'undefined' &&
data.files !== null
) {
if (data.files.length > 2 && !options.filter) {
storeInCache(data);
}
options.successCallback(data);
} else {
assistErrorCallback(options)(data);
}
}
})
.fail(assistErrorCallback(options))
.always(() => {
if (typeof options.editor !== 'undefined' && options.editor !== null) {
options.editor.hideSpinner();
}
});
};
return this.fetchCached(
$.extend({}, options, {
sourceType: 'abfs',
url: url,
fetchFunction: fetchFunction
})
);
}
/**
* @param {Object} options
* @param {Function} options.successCallback
* @param {Function} [options.errorCallback]
* @param {boolean} [options.silenceErrors]
* @param {Number} [options.timeout]
*
* @param {string[]} options.pathParts
* @param {string} options.fileType
*/
fetchGitContents(options) {
const url =
URLS.GIT_API_PREFIX +
'?path=' +
encodeURI(options.pathParts.join('/')) +
'&fileType=' +
options.fileType;
const fetchFunction = storeInCache => {
if (options.timeout === 0) {
assistErrorCallback(options)({ status: -1 });
return;
}
$.ajax({
dataType: 'json',
url: url,
timeout: options.timeout,
success: data => {
if (!data.error && !successResponseIsError(data)) {
if (
data.fileType === 'dir' &&
typeof data.files !== 'undefined' &&
data.files !== null
) {
if (data.files.length > 2) {
storeInCache(data);
}
options.successCallback(data);
} else if (
data.fileType === 'file' &&
typeof data.content !== 'undefined' &&
data.content !== null
) {
options.successCallback(data);
}
} else {
assistErrorCallback(options)(data);
}
}
}).fail(assistErrorCallback(options));
};
this.fetchCached(
$.extend({}, options, {
sourceType: 'git',
url: url,
fetchFunction: fetchFunction
})
);
}
/**
* @param {Object} options
* @param {Function} options.successCallback
* @param {Function} [options.errorCallback]
* @param {boolean} [options.silenceErrors]
* @param {Number} [options.timeout]
* @param {Object} [options.editor] - Ace editor
*
* @param {string[]} options.pathParts
* @param {number} [options.pageSize] - Default 500
* @param {number} [options.page] - Default 1
* @param {string} [options.filter]
*/
fetchS3Path(options) {
options.pathParts.shift(); // remove the trailing /
let url =
URLS.S3_API_PREFIX +
encodeURI(options.pathParts.join('/')) +
'?format=json&sortby=name&descending=false&pagesize=' +
(options.pageSize || 500) +
'&pagenum=' +
(options.page || 1);
if (options.filter) {
url += '&filter=' + options.filter;
}
const fetchFunction = storeInCache => {
if (options.timeout === 0) {
assistErrorCallback(options)({ status: -1 });
return;
}
$.ajax({
dataType: 'json',
url: url,
timeout: options.timeout,
success: data => {
if (
!data.error &&
!successResponseIsError(data) &&
typeof data.files !== 'undefined' &&
data.files !== null
) {
if (data.files.length > 2 && !options.filter) {
storeInCache(data);
}
options.successCallback(data);
} else {
assistErrorCallback(options)(data);
}
}
})
.fail(assistErrorCallback(options))
.always(() => {
if (typeof options.editor !== 'undefined' && options.editor !== null) {
options.editor.hideSpinner();
}
});
};
this.fetchCached(
$.extend({}, options, {
sourceType: 's3',
url: url,
fetchFunction: fetchFunction
})
);
}
async fetchFavoriteApp(options) {
return new Promise((resolve, reject) => {
simpleGet('/desktop/api2/user_preferences/default_app')
.done(resolve)
.fail(reject);
});
}
async setFavoriteAppAsync(options) {
return new Promise((resolve, reject) => {
simplePost('/desktop/api2/user_preferences/default_app', options)
.done(resolve)
.fail(reject);
});
}
/**
* @param {Object} options
* @param {String} options.collectionName
* @param {String} options.fieldName
* @param {String} options.prefix
* @param {String} [options.engine]
* @param {Function} options.successCallback
* @param {Function} [options.alwaysCallback]
* @param {Number} [options.timeout]
*
*/
fetchDashboardTerms(options) {
if (options.timeout === 0) {
assistErrorCallback(options)({ status: -1 });
return;
}
$.ajax({
dataType: 'json',
url: URLS.DASHBOARD_TERMS_API,
type: 'POST',
data: {
collection: ko.mapping.toJSON({
id: '',
name: options.collectionName,
engine: options.engine || 'solr'
}),
analysis: ko.mapping.toJSON({
name: options.fieldName,
terms: {
prefix: options.prefix || ''
}
})
},
timeout: options.timeout,
success: data => {
if (!data.error && !successResponseIsError(data) && data.status === 0) {
options.successCallback(data);
} else {
assistErrorCallback(options)(data);
}
}
})
.fail(assistErrorCallback(options))
.always(options.alwaysCallback);
}
/**
* @param {Object} options
* @param {String} options.collectionName
* @param {String} options.fieldName
* @param {String} [options.engine]
* @param {Function} options.successCallback
* @param {Function} [options.alwaysCallback]
* @param {Number} [options.timeout]
*
*/
fetchDashboardStats(options) {
if (options.timeout === 0) {
assistErrorCallback(options)({ status: -1 });
return;
}
$.ajax({
dataType: 'json',
url: URLS.DASHBOARD_STATS_API,
type: 'POST',
data: {
collection: ko.mapping.toJSON({
id: '',
name: options.collectionName,
engine: options.engine || 'solr'
}),
analysis: ko.mapping.toJSON({
name: options.fieldName,
stats: {
facet: ''
}
}),
query: ko.mapping.toJSON({
qs: [{ q: '' }],
fqs: []
})
},
timeout: options.timeout,
success: data => {
if (!data.error && !successResponseIsError(data) && data.status === 0) {
options.successCallback(data);
} else if (data.status === 1) {
options.notSupportedCallback(data);
} else {
assistErrorCallback(options)(data);
}
}
})
.fail(assistErrorCallback(options))
.always(options.alwaysCallback);
}
/**
* @param {Object} options
* @param {Function} options.successCallback
* @param {Function} [options.errorCallback]
* @param {boolean} [options.silenceErrors]
* @param {Number} [options.timeout]
* @param {Object} [options.editor] - Ace editor
*/
fetchHBase(options) {
let suffix = 'getClusters';
if (options.parent.name !== '') {
suffix = 'getTableList/' + options.parent.name;
}
const url = URLS.HBASE_API_PREFIX + suffix;
const fetchFunction = storeInCache => {
if (options.timeout === 0) {
assistErrorCallback(options)({ status: -1 });
return;
}
$.ajax({
dataType: 'json',
url: url,
timeout: options.timeout,
success: data => {
if (!data.error && !successResponseIsError(data)) {
storeInCache(data);
options.successCallback(data);
} else {
assistErrorCallback(options)(data);
}
}
})
.fail(assistErrorCallback(options))
.always(() => {
if (typeof options.editor !== 'undefined' && options.editor !== null) {
options.editor.hideSpinner();
}
});
};
this.fetchCached(
$.extend({}, options, {
sourceType: 'hbase',
url: url,
fetchFunction: fetchFunction
})
);
}
/**
* @param {Object} options
* @param {Number} options.pastMs
* @param {Number} options.stepMs
*
* @return {Promise}
*/
fetchResourceStats(options) {
const queryMetric = metricName => {
const now = Date.now();
return simplePost('/metadata/api/prometheus/query', {
query: ko.mapping.toJSON(metricName),
start: Math.floor((now - options.pastMs) / 1000),
end: Math.floor(now / 1000),
step: options.stepMs / 1000
});
};
const combinedDeferred = $.Deferred();
$.when(
queryMetric('round((go_memstats_alloc_bytes / go_memstats_sys_bytes) * 100)'), // CPU percentage
queryMetric('round((go_memstats_alloc_bytes / go_memstats_sys_bytes) * 100)'), // Memory percentage
queryMetric('round((go_memstats_alloc_bytes / go_memstats_sys_bytes) * 100)'), // IO percentage
queryMetric('impala_queries_count{datawarehouse="' + options.clusterName + '"}'), // Sum of all queries in flight (currently total query executed for testing purpose)
queryMetric('impala_queries{datawarehouse="' + options.clusterName + '"}') // Queued queries
)
.done(() => {
const timestampIndex = {};
for (let j = 0; j < arguments.length; j++) {
const response = arguments[j];
if (response.data.result[0]) {
const values = response.data.result[0].values;
for (let i = 0; i < values.length; i++) {
if (!timestampIndex[values[i][0]]) {
timestampIndex[values[i][0]] = [values[i][0] * 1000, 0, 0, 0, 0, 0]; // Adjust back to milliseconds
}
timestampIndex[values[i][0]][j + 1] = parseFloat(values[i][1]);
}
}
}
const result = [];
Object.keys(timestampIndex).forEach(key => {
result.push(timestampIndex[key]);
});
result.sort((a, b) => {
return a[0] - b[0];
});
combinedDeferred.resolve(result);
})
.fail(combinedDeferred.reject);
return combinedDeferred.promise();
}
/**
* @param {Object} options
* @param {Function} [options.successCallback]
* @param {Function} [options.errorCallback]
* @param {boolean} [options.silenceErrors]
*/
fetchConfigurations(options) {
simpleGet(URLS.CONFIG_APPS_API, {}, options);
}
saveGlobalConfiguration(options) {
simplePost(
URLS.CONFIG_APPS_API,
{
configuration: ko.mapping.toJSON(options.configuration)
},
options
);
}
/**
* @param {Object} options
* @param {Function} [options.successCallback]
* @param {Function} [options.errorCallback]
* @param {boolean} [options.silenceErrors]
*
* @param {string} options.app
* @param {Object} options.properties
* @param {boolean} [options.isDefault]
* @param {Number} [options.groupId]
* @param {Number} [options.userId]
*/
saveConfiguration(options) {
simplePost(
URLS.CONFIG_SAVE_API,
{
app: options.app,
properties: ko.mapping.toJSON(options.properties),
is_default: options.isDefault,
group_id: options.groupId,
user_id: options.userId
},
options
);
}
/**
* @param {Object} options
* @param {Function} options.successCallback
* @param {Function} [options.errorCallback]
* @param {boolean} [options.silenceErrors]
*
* @param {string} [options.uuid]
*/
fetchDocuments(options) {
let id = '';
if (options.uuid) {
id += options.uuid;
}
if (options.type && options.type !== 'all') {
id += options.type;
}
let promise = this.queueManager.getQueued(URLS.DOCUMENTS_API, id);
const firstInQueue = typeof promise === 'undefined';
if (firstInQueue) {
promise = $.Deferred();
this.queueManager.addToQueue(promise, URLS.DOCUMENTS_API, id);
}
promise.done(options.successCallback).fail(assistErrorCallback(options));
if (!firstInQueue) {
return;
}
const data = {
uuid: options.uuid
};
if (options.type && options.type !== 'all') {
data.type = ['directory', options.type];
}
$.ajax({
url: URLS.DOCUMENTS_API,
data: data,
traditional: true,
success: data => {
if (!successResponseIsError(data)) {
promise.resolve(data);
} else {
promise.reject(data);
}
}
}).fail(promise.reject);
}
/**
* @param {Object} options
* @param {Function} options.successCallback
* @param {Function} [options.errorCallback]
* @param {boolean} [options.silenceErrors]
*
* @param {string} [options.path]
* @param {string} [options.query]
* @param {string} [options.type]
* @param {int} [options.page]
* @param {int} [options.limit]
*/
searchDocuments(options) {
return $.ajax({
url: URLS.DOCUMENTS_SEARCH_API,
data: {
uuid: options.uuid,
text: options.query,
type: options.type,
page: options.page,
limit: options.limit,
include_trashed: options.include_trashed
},
success: data => {
if (!successResponseIsError(data)) {
options.successCallback(data);
} else {
assistErrorCallback(options)(data);
}
}
}).fail(assistErrorCallback(options));
}
/**
* @param {Object} options
* @param {number} options.uuid
* @param {boolean} [options.dependencies]
* @param {boolean} [options.silenceErrors]
* @param {boolean} [options.fetchContents]
*
* @return {CancellablePromise}
*/
fetchDocument(options) {
const deferred = $.Deferred();
const request = $.ajax({
url: URLS.DOCUMENTS_API,
data: {
uuid: options.uuid,
data: !!options.fetchContents,
dependencies: options.dependencies
},
success: data => {
if (!successResponseIsError(data)) {
deferred.resolve(data);
} else {
deferred.reject(
assistErrorCallback({
silenceErrors: options.silenceErrors
})
);
}
}
}).fail(
assistErrorCallback({
silenceErrors: options.silenceErrors,
errorCallback: deferred.reject
})
);
return new CancellablePromise(deferred, request);
}
/**
* @param {Object} options
* @param {string} options.uuid
* @param {boolean} [options.silenceErrors]
* @param {boolean} [options.dependencies]
* @param {boolean} [options.fetchContents]
*
* @param options
* @return {Promise<unknown>}
*/
async fetchDocumentAsync(options) {
return new Promise((resolve, reject) => {
this.fetchDocument(options)
.done(resolve)
.fail(reject);
});
}
/**
* @param {Object} options
* @param {string} options.uuid
* @param {string} options.perm - See LINK_SHARING_PERMS
* @param {boolean} [options.silenceErrors]
*
* @param options
* @return {Promise<unknown>}
*/
async setLinkSharingPermsAsync(options) {
return new Promise((resolve, reject) => {
simplePost('/desktop/api2/doc/share/link', {
uuid: JSON.stringify(options.uuid),
perm: JSON.stringify(options.perm)
})
.done(resolve)
.fail(reject);
});
}
/**
* @param {Object} options
* @param {Function} options.successCallback
* @param {Function} [options.errorCallback]
* @param {boolean} [options.silenceErrors]
*
* @param {string} options.parentUuid
* @param {string} options.name
*/
createDocumentsFolder(options) {
simplePost(
URLS.DOCUMENTS_API + 'mkdir',
{
parent_uuid: ko.mapping.toJSON(options.parentUuid),
name: ko.mapping.toJSON(options.name)
},
options
);
}
/**
* @param {Object} options
* @param {Function} options.successCallback
* @param {Function} [options.errorCallback]
* @param {boolean} [options.silenceErrors]
*
* @param {string} options.uuid
* @param {string} options.name
*/
updateDocument(options) {
simplePost(
URLS.DOCUMENTS_API + 'update',
{
uuid: ko.mapping.toJSON(options.uuid),
name: options.name
},
options
);
}
/**
* @param {Object} options
* @param {Function} options.successCallback
* @param {Function} [options.errorCallback]
* @param {Function} [options.progressHandler]
* @param {boolean} [options.silenceErrors]
*
* @param {FormData} options.formData
*/
uploadDocument(options) {
$.ajax({
url: URLS.DOCUMENTS_API + 'import',
type: 'POST',
success: data => {
if (!successResponseIsError(data)) {
options.successCallback(data);
} else {
assistErrorCallback(options)(data);
}
},
xhr: () => {
const myXhr = $.ajaxSettings.xhr();
if (myXhr.upload && options.progressHandler) {
myXhr.upload.addEventListener('progress', options.progressHandler, false);
}
return myXhr;
},
dataType: 'json',
data: options.formData,
cache: false,
contentType: false,
processData: false
}).fail(assistErrorCallback(options));
}
/**
*
* @param {Function} options.successCallback
* @param {Function} [options.errorCallback]
* @param {boolean} [options.silenceErrors]
*
* @param {number} options.sourceId - The ID of the source document
* @param {number} options.destinationId - The ID of the target document
*/
moveDocument(options) {
simplePost(
URLS.DOCUMENTS_API + 'move',
{
source_doc_uuid: ko.mapping.toJSON(options.sourceId),
destination_doc_uuid: ko.mapping.toJSON(options.destinationId)
},
options
);
}
/**
* @param {Object} options
* @param {Function} options.successCallback
* @param {Function} [options.errorCallback]
* @param {boolean} [options.silenceErrors]
*
* @param {string} options.uuid
* @param {string} [options.skipTrash] - Default false
*/
deleteDocument(options) {
simplePost(
URLS.DOCUMENTS_API + 'delete',
{
uuid: ko.mapping.toJSON(options.uuid),
skip_trash: ko.mapping.toJSON(options.skipTrash || false)
},
options
);
}
/**
* @param {Object} options
* @param {Function} options.successCallback
* @param {Function} [options.errorCallback]
* @param {boolean} [options.silenceErrors]
*
* @param {string} options.uuid
*/
copyDocument(options) {
simplePost(
URLS.DOCUMENTS_API + 'copy',
{
uuid: ko.mapping.toJSON(options.uuid)
},
options
);
}
/**
* @param {Object} options
* @param {Function} options.successCallback
* @param {Function} [options.errorCallback]
* @param {boolean} [options.silenceErrors]
*
* @param {string} options.uuid
*/
restoreDocument(options) {
simplePost(
URLS.DOCUMENTS_API + 'restore',
{
uuids: ko.mapping.toJSON(options.uuids)
},
options
);
}
/**
*
* @param {Object} options
* @param {string} options.sourceType
* @param {string} [options.databaseName]
* @param {string} [options.tableName]
* @param {string} [options.cacheType] - Possible values 'default', 'optimizer. Default value 'default'
* @param {string[]} [options.fields]
* @param {boolean} [options.clearAll]
*/
clearDbCache(options) {
const cacheIdentifier = this.getAssistCacheIdentifier(options);
if (options.clearAll) {
$.totalStorage(cacheIdentifier, {});
} else {
let url = URLS.AUTOCOMPLETE_API_PREFIX;
if (options.databaseName) {
url += options.databaseName;
}
if (options.tableName) {
url += '/' + options.tableName;
}
if (options.fields) {
url += options.fields.length > 0 ? '/' + options.fields.join('/') : '';
}
const cachedData = $.totalStorage(cacheIdentifier) || {};
delete cachedData[url];
$.totalStorage(cacheIdentifier, cachedData);
}
}
/**
* @param {Object} options
* @param {string} options.sourceType
* @param {string} options.invalidate - 'invalidate' or 'invalidateAndFlush'
* @param {string[]} [options.path]
* @param {ContextCompute} [options.compute]
* @param {boolean} [options.silenceErrors]
*/
invalidateSourceMetadata(options) {
const deferred = $.Deferred();
if (
options.sourceType === 'impala' &&
(options.invalidate === 'invalidate' || options.invalidate === 'invalidateAndFlush')
) {
const data = {
flush_all: options.invalidate === 'invalidateAndFlush',
cluster: JSON.stringify(options.compute)
};
if (options.path && options.path.length > 0) {
data.database = options.path[0];
}
if (options.path && options.path.length > 1) {
data.table = options.path[1];
}
const request = simplePost(URLS.IMPALA_INVALIDATE_API, data, options)
.done(deferred.resolve)
.fail(deferred.reject);
return new CancellablePromise(deferred, request);
}
return deferred.resolve().promise();
}
/**
* @param {Object} options
* @param {string} options.sourceType
* @param {ContextCompute} options.compute
* @param {boolean} [options.silenceErrors]
* @param {number} [options.timeout]
*
* @param {string[]} [options.path] - The path to fetch
*
* @return {CancellablePromise}
*/
fetchSourceMetadata(options) {
const deferred = $.Deferred();
const isQuery = options.sourceType.indexOf('-query') !== -1;
const sourceType = isQuery ? options.sourceType.replace('-query', '') : options.sourceType;
const request = $.ajax({
type: 'POST',
url:
URLS.AUTOCOMPLETE_API_PREFIX + (isQuery ? options.path.slice(1) : options.path).join('/'),
data: {
notebook: {},
snippet: ko.mapping.toJSON({
type: sourceType,
source: isQuery ? 'query' : 'data'
}),
cluster: ko.mapping.toJSON(options.compute ? options.compute : '""')
},
timeout: options.timeout
})
.done(data => {
data.notFound =
data.status === 0 &&
data.code === 500 &&
data.error &&
(data.error.indexOf('Error 10001') !== -1 ||
data.error.indexOf('AnalysisException') !== -1);
data.hueTimestamp = Date.now();
// TODO: Display warning in autocomplete when an entity can't be found
// Hive example: data.error: [...] SemanticException [Error 10001]: Table not found default.foo
// Impala example: data.error: [...] AnalysisException: Could not resolve path: 'default.foo'
if (!data.notFound && successResponseIsError(data)) {
assistErrorCallback({
silenceErrors: options.silenceErrors,
errorCallback: deferred.reject
})(data);
} else {
deferred.resolve(data);
}
})
.fail(
assistErrorCallback({
silenceErrors: options.silenceErrors,
errorCallback: deferred.reject
})
);
return new CancellablePromise(deferred, request);
}
updateSourceMetadata(options) {
let url;
const data = {
source_type: options.sourceType
};
if (options.path.length === 1) {
url = '/metastore/databases/' + options.path[0] + '/alter';
data.properties = ko.mapping.toJSON(options.properties);
} else if (options.path.length === 2) {
url = '/metastore/table/' + options.path[0] + '/' + options.path[1] + '/alter';
if (options.properties) {
if (options.properties.comment) {
data.comment = options.properties.comment;
}
if (options.properties.name) {
data.new_table_name = options.properties.name;
}
}
} else if (options.path.length > 2) {
url = '/metastore/table/' + options.path[0] + '/' + options.path[1] + '/alter_column';
data.column = options.path.slice(2).join('.');
if (options.properties) {
if (options.properties.comment) {
data.comment = options.properties.comment;
}
if (options.properties.name) {
data.new_column_name = options.properties.name;
}
if (options.properties.type) {
data.new_column_type = options.properties.name;
}
if (options.properties.partitions) {
data.partition_spec = ko.mapping.toJSON(options.properties.partitions);
}
}
}
return simplePost(url, data, options);
}
/**
* Fetches the analysis for the given source and path
*
* @param {Object} options
* @param {boolean} [options.silenceErrors]
*
* @param {ContextCompute} options.compute
* @param {string} options.sourceType
* @param {string[]} options.path
*
* @return {CancellablePromise}
*/
fetchAnalysis(options) {
const deferred = $.Deferred();
let url = '/notebook/api/describe/' + options.path[0];
if (options.path.length > 1) {
url += '/' + options.path[1] + '/';
}
if (options.path.length > 2) {
url += 'stats/' + options.path.slice(2).join('/');
}
const data = {
format: 'json',
cluster: JSON.stringify(options.compute),
source_type: options.sourceType
};
const request = simplePost(url, data, {
silenceErrors: options.silenceErrors,
successCallback: response => {
if (options.path.length === 1) {
if (response.data) {
response.data.hueTimestamp = Date.now();
deferred.resolve(response.data);
} else {
deferred.reject();
}
} else {
deferred.resolve(response);
}
},
errorCallback: deferred.reject
});
return new CancellablePromise(deferred, request);
}
/**
* Fetches the partitions for the given path
*
* @param {Object} options
* @param {boolean} [options.silenceErrors]
*
* @param {string[]} options.path
* @param {ContextCompute} options.compute
*
* @return {CancellablePromise}
*/
fetchPartitions(options) {
const deferred = $.Deferred();
// TODO: No sourceType needed?
const request = $.post('/metastore/table/' + options.path.join('/') + '/partitions', {
format: 'json',
cluster: JSON.stringify(options.compute)
})
.done(response => {
if (!successResponseIsError(response)) {
if (!response) {
response = {};
}
response.hueTimestamp = Date.now();
deferred.resolve(response);
} else {
assistErrorCallback({
silenceErrors: options.silenceErrors,
errorCallback: deferred.reject
})(response);
}
})
.fail(response => {
// Don't report any partitions if it's not partitioned instead of error to prevent unnecessary calls
if (
response &&
response.responseText &&
response.responseText.indexOf('is not partitioned') !== -1
) {
deferred.resolve({
hueTimestamp: Date.now(),
partition_keys_json: [],
partition_values_json: []
});
} else {
assistErrorCallback({
silenceErrors: options.silenceErrors,
errorCallback: deferred.reject
})(response);
}
});
return new CancellablePromise(deferred, request);
}
/**
* Refreshes the analysis for the given source and path
*
* @param {Object} options
* @param {boolean} [options.silenceErrors]
*
* @param {string} options.sourceType
* @param {ContextCompute} options.compute
* @param {string[]} options.path
*
* @return {CancellablePromise}
*/
refreshAnalysis(options) {
if (options.path.length === 1) {
return this.fetchAnalysis(options);
}
const deferred = $.Deferred();
const promises = [];
const pollForAnalysis = (url, delay) => {
window.setTimeout(() => {
promises.push(
simplePost(url, undefined, {
silenceErrors: options.silenceErrors,
successCallback: data => {
promises.pop();
if (data.isSuccess) {
promises.push(
this.fetchAnalysis(options)
.done(deferred.resolve)
.fail(deferred.reject)
);
} else if (data.isFailure) {
deferred.reject(data);
} else {
pollForAnalysis(url, 1000);
}
},
errorCallback: deferred.reject
})
);
}, delay);
};
const url =
'/' +
(options.sourceType === 'hive' ? 'beeswax' : options.sourceType) +
'/api/analyze/' +
options.path.join('/') +
'/';
promises.push(
simplePost(url, undefined, {
silenceErrors: options.silenceErrors,
successCallback: data => {
promises.pop();
if (data.status === 0 && data.watch_url) {
pollForAnalysis(data.watch_url, 500);
} else {
deferred.reject();
}
},
errorCallback: deferred.reject
})
);
return new CancellablePromise(deferred, undefined, promises);
}
/**
* Checks the status for the given snippet ID
* Note: similar to notebook and search check_status.
*
* @param {Object} options
* @param {Object} options.notebookJson
* @param {Object} options.snippetJson
* @param {boolean} [options.silenceErrors]
*
* @return {CancellablePromise}
*/
whenAvailable(options) {
const deferred = $.Deferred();
const cancellablePromises = [];
let waitTimeout = -1;
deferred.fail(() => {
window.clearTimeout(waitTimeout);
});
const waitForAvailable = () => {
const request = simplePost(
'/notebook/api/check_status',
{
notebook: options.notebookJson,
snippet: options.snippetJson,
cluster: ko.mapping.toJSON(options.compute ? options.compute : '""')
},
{
silenceErrors: options.silenceErrors
}
)
.done(response => {
if (response && response.query_status && response.query_status.status) {
const status = response.query_status.status;
if (status === 'available') {
deferred.resolve(response.query_status);
} else if (status === 'running' || status === 'starting' || status === 'waiting') {
waitTimeout = window.setTimeout(() => {
waitForAvailable();
}, 500);
} else {
deferred.reject(response.query_status);
}
}
})
.fail(deferred.reject);
cancellablePromises.push(new CancellablePromise(request, request));
};
waitForAvailable();
return new CancellablePromise(deferred, undefined, cancellablePromises);
}
clearNotebookHistory(options) {
const data = {
notebook: options.notebookJson,
doc_type: options.docType,
is_notification_manager: options.isNotificationManager
};
return simplePost('/notebook/api/clear_history', data);
}
closeNotebook(options) {
const data = {
notebook: options.notebookJson,
editorMode: options.editorMode
};
return simplePost('/notebook/api/notebook/close', data);
}
/**
* Creates a new session
*
* @param {Object} options
* @param {String} options.type
* @param {Array<SessionProperty>} [options.properties] - Default []
* @return {Promise<Session>}
*/
async createSession(options) {
return new Promise((resolve, reject) => {
const data = {
session: JSON.stringify({ type: options.type, properties: options.properties || [] })
};
$.post({
url: '/notebook/api/create_session',
data: data
})
.done(data => {
if (data.status === 401) {
resolve({ auth: true, message: data.message });
} else if (successResponseIsError(data)) {
reject(assistErrorCallback(options)(data));
} else {
resolve(data.session);
}
})
.fail(assistErrorCallback(options));
});
}
closeSession(options) {
const data = {
session: JSON.stringify(options.session)
};
return simplePost('/notebook/api/close_session', data, options);
}
async checkStatus(options) {
return new Promise((resolve, reject) => {
const data = {
notebook: options.notebookJson
};
$.post({
url: '/notebook/api/check_status',
data: data
})
.done(data => {
// 0, -3 and other negative values have meaning for this endpoint
if (data && typeof data.status !== 'undefined') {
resolve(data);
} else if (successResponseIsError(data)) {
reject(assistErrorCallback(options)(data));
} else {
reject();
}
})
.fail(assistErrorCallback(options));
});
}
getExternalStatement(options) {
const data = {
notebook: options.notebookJson,
snippet: options.snippetJson
};
return simplePost('/notebook/api/get_external_statement', data);
}
fetchResultSize(options) {
const data = {
notebook: options.notebookJson,
snippet: options.snippetJson
};
return simplePost('/notebook/api/fetch_result_size', data);
}
getLogs(options) {
const data = {
notebook: options.notebookJson,
snippet: options.snippetJson,
from: options.from,
jobs: options.jobsJson,
full_log: options.fullLog,
operationId: options.executable.operationId
};
return simplePost('/notebook/api/get_logs', data);
}
async saveNotebook(options) {
const data = {
notebook: options.notebookJson,
editorMode: options.editorMode
};
return new Promise((resolve, reject) => {
simplePost('/notebook/api/notebook/save', data)
.then(resolve)
.catch(reject);
});
}
async getHistory(options) {
return new Promise((resolve, reject) => {
$.get('/notebook/api/get_history', {
doc_type: options.type,
limit: options.limit || 50,
page: options.page || 1,
doc_text: options.docFilter,
is_notification_manager: options.isNotificationManager
})
.done(data => {
if (successResponseIsError(data)) {
reject(assistErrorCallback(options)(data));
return;
}
resolve(data);
})
.fail(reject);
});
}
/**
* @typedef {Object} ExecutionHandle
* @property {string} guid
* @property {boolean} has_more_statements
* @property {boolean} has_result_set
* @property {Object} log_context
* @property {number} modified_row_count
* @property {number} operation_type
* @property {string} previous_statement_hash
* @property {string} secret
* @property {string} session_guid
* @property {string} statement
* @property {number} statement_id
* @property {number} statements_count
*/
/**
* API function to execute an SqlExecutable
*
* @param {Object} options
* @param {boolean} [options.silenceErrors]
* @param {SqlExecutable} options.executable
* @param {Session} options.session
*
* @return {Promise<ExecutionHandle>}
*/
async executeStatement(options) {
const executable = options.executable;
const url = URLS.EXECUTE_API_PREFIX + executable.executor.connector().dialect;
const promise = new Promise(async (resolve, reject) => {
let data = {};
if (executable.executor.snippet) {
// V1
// TODO: Refactor away the snippet, it currently works because snippet.statement is a computed from
// the active executable, but we n
data = {
notebook: await executable.executor.snippet.parentNotebook.toJson(),
snippet: executable.executor.snippet.toContextJson()
};
} else {
data = await executable.toContext();
}
data.executable = executable.toJson();
simplePost(url, data, options)
.done(response => {
const executeResponse = {};
if (response.handle) {
executeResponse.handle = response.handle;
executeResponse.handle.result = response.result;
} else {
reject('No handle in execute response');
return;
}
if (response.history_id) {
executeResponse.history = {
id: response.history_id,
uuid: response.history_uuid,
parentUuid: response.history_parent_uuid
};
}
resolve(executeResponse);
})
.fail(reject);
});
executable.addCancellable({
cancel: async () => {
try {
const handle = await promise;
if (options.executable.handle !== handle) {
options.executable.handle = handle;
}
await this.cancelStatement(options);
} catch (err) {
console.warn('Failed cancelling statement');
console.warn(err);
}
}
});
return promise;
}
/**
*
* @param {Object} options
* @param {Snippet} options.snippet
*
* @return {CancellablePromise<string>}
*/
async explainAsync(options) {
const data = {
notebook: await options.snippet.parentNotebook.toContextJson(),
snippet: options.snippet.toContextJson()
};
return new Promise((resolve, reject) => {
simplePost('/notebook/api/explain', data, options)
.done(response => {
resolve(response.explanation);
})
.fail(reject);
});
}
/**
*
* @param {Object} options
* @param {statement} options.statement
* @param {doc_type} options.doc_type
* @param {name} options.name
* @param {description} options.description
*
* @return {CancellablePromise<string>}
*/
async createGistAsync(options) {
const data = {
statement: options.statement,
doc_type: options.doc_type,
name: options.name,
description: options.description
};
return new Promise((resolve, reject) => {
simplePost(URLS.GIST_API + 'create', data, options)
.done(response => {
resolve(response.link);
})
.fail(reject);
});
}
/**
*
* @param {Object} options
* @param {boolean} [options.silenceErrors]
* @param {Executable} options.executable
*
* @return {CancellablePromise<string>}
*/
checkExecutionStatus(options) {
const deferred = $.Deferred();
const request = $.post({
url: '/notebook/api/check_status',
data: {
operationId: options.executable.operationId
}
})
.done(response => {
if (response && response.query_status) {
deferred.resolve(response.query_status);
} else if (response && response.status === -3) {
deferred.resolve({ status: EXECUTION_STATUS.expired });
} else {
deferred.resolve({ status: EXECUTION_STATUS.failed, message: response.message });
}
})
.fail(err => {
deferred.reject(assistErrorCallback(options)(err));
});
return new CancellablePromise(deferred, request);
}
/**
*
* @param {Object} options
* @param {boolean} [options.silenceErrors]
* @param {Executable} options.executable
* @param {number} [options.from]
* @param {Object[]} [options.jobs]
* @param {string} options.fullLog
*
* @return {Promise<?>}
*/
fetchLogs(options) {
return new Promise(async (resolve, reject) => {
const data = await options.executable.toContext();
data.full_log = options.fullLog;
data.jobs = options.jobs && JSON.stringify(options.jobs);
data.from = options.from || 0;
data.operationId = options.executable.operationId;
const request = simplePost('/notebook/api/get_logs', data, options)
.done(response => {
resolve({
logs: (response.status === 1 && response.message) || response.logs || '',
jobs: response.jobs || [],
isFullLogs: response.isFullLogs
});
})
.fail(reject);
options.executable.addCancellable({
cancel: () => {
cancelActiveRequest(request);
}
});
});
}
/**
*
* @param {Object} options
* @param {boolean} [options.silenceErrors]
* @param {SqlExecutable} options.executable
*
* @return {Promise}
*/
async cancelStatement(options) {
return new Promise(async (resolve, reject) => {
simplePost('/notebook/api/cancel_statement', await options.executable.toContext(), options)
.done(resolve)
.fail(reject);
});
}
/**
* @typedef {Object} ResultResponseMeta
* @property {string} comment
* @property {string} name
* @property {string} type
*/
/**
* @typedef {Object} ResultResponse
* @property {Object[]} data
* @property {boolean} has_more
* @property {boolean} isEscaped
* @property {ResultResponseMeta[]} meta
* @property {string} type
*/
/**
*
* @param {Object} options
* @param {boolean} [options.silenceErrors]
* @param {SqlExecutable} options.executable
* @param {number} options.rows
* @param {boolean} options.startOver
*
* @return {Promise<ResultResponse>}
*/
async fetchResults(options) {
return new Promise(async (resolve, reject) => {
const data = await options.executable.toContext();
data.rows = options.rows;
data.startOver = !!options.startOver;
const request = simplePost(
'/notebook/api/fetch_result_data',
data,
{
silenceErrors: options.silenceErrors,
dataType: 'text'
},
options
)
.done(response => {
const data = JSON.bigdataParse(response);
resolve(data.result);
})
.fail(reject);
options.executable.addCancellable({
cancel: () => {
cancelActiveRequest(request);
}
});
});
}
/**
*
* @param {Object} options
* @param {boolean} [options.silenceErrors]
* @param {Executable} options.executable
*
* @return {Promise<ResultResponse>}
*/
async fetchResultSize2(options) {
return new Promise(async (resolve, reject) => {
const request = simplePost(
'/notebook/api/fetch_result_size',
await options.executable.toContext(),
options
)
.done(response => {
resolve(response.result);
})
.fail(reject);
options.executable.addCancellable({
cancel: () => {
cancelActiveRequest(request);
}
});
});
}
/**
*
* @param {Object} options
* @param {boolean} [options.silenceErrors]
* @param {SqlExecutable} options.executable
*
* @return {Promise}
*/
async closeStatement(options) {
return new Promise(async (resolve, reject) => {
simplePost(
'/notebook/api/close_statement',
{
operationId: options.executable.operationId
},
options
)
.done(resolve)
.fail(reject);
});
}
/**
* Fetches samples for the given source and path
*
* @param {Object} options
* @param {boolean} [options.silenceErrors]
*
* @param {string} options.sourceType
* @param {ContextCompute} options.compute
* @param {number} [options.sampleCount] - Default 100
* @param {string[]} options.path
* @param {string} [options.operation] - Default 'default'
*
* @return {CancellablePromise}
*/
fetchSample(options) {
const deferred = $.Deferred();
const cancellablePromises = [];
let notebookJson = null;
let snippetJson = null;
const cancelQuery = () => {
if (notebookJson) {
simplePost(
'/notebook/api/cancel_statement',
{
notebook: notebookJson,
snippet: snippetJson,
cluster: ko.mapping.toJSON(options.compute ? options.compute : '""')
},
{ silenceErrors: options.silenceErrors }
);
}
};
simplePost(
URLS.SAMPLE_API_PREFIX + options.path.join('/'),
{
notebook: {},
snippet: JSON.stringify({
type: options.sourceType,
compute: options.compute
}),
async: true,
operation: '"' + (options.operation || 'default') + '"',
cluster: ko.mapping.toJSON(options.compute ? options.compute : '""')
},
{
silenceErrors: options.silenceErrors
}
)
.done(sampleResponse => {
const queryResult = new QueryResult(options.sourceType, options.compute, sampleResponse);
notebookJson = JSON.stringify({ type: options.sourceType });
snippetJson = JSON.stringify(queryResult);
if (sampleResponse && sampleResponse.rows) {
// Sync results
const data = { data: sampleResponse.rows, meta: sampleResponse.full_headers };
data.hueTimestamp = Date.now();
deferred.resolve(data);
} else {
cancellablePromises.push(
this.whenAvailable({
notebookJson: notebookJson,
snippetJson: snippetJson,
compute: options.compute,
silenceErrors: options.silenceErrors
})
.done(resultStatus => {
if (resultStatus) {
$.extend(true, queryResult.result, {
handle: resultStatus
});
}
const resultRequest = simplePost(
'/notebook/api/fetch_result_data',
{
notebook: notebookJson,
snippet: JSON.stringify(queryResult),
rows: options.sampleCount || 100,
startOver: 'false'
},
{
silenceErrors: options.silenceErrors
}
)
.done(sampleResponse => {
const data = (sampleResponse && sampleResponse.result) || {
data: [],
meta: []
};
data.hueTimestamp = Date.now();
deferred.resolve(data);
if (
window.CLOSE_SESSIONS[options.sourceType] &&
queryResult.result.handle &&
queryResult.result.handle.session_id
) {
this.closeSession({
session: {
type: options.sourceType,
id: queryResult.result.handle.session_id
}
});
}
})
.fail(deferred.reject);
cancellablePromises.push(resultRequest, resultRequest);
})
.fail(deferred.reject)
);
}
})
.fail(deferred.reject);
cancellablePromises.push({
cancel: cancelQuery
});
return new CancellablePromise(deferred, undefined, cancellablePromises);
}
/**
* Fetches a navigator entity for the given source and path
*
* @param {Object} options
* @param {boolean} [options.silenceErrors]
*
* @param {boolean} [options.isView] - Default false
* @param {string[]} options.path
*
* @return {CancellablePromise}
*/
fetchNavigatorMetadata(options) {
const deferred = $.Deferred();
let url = URLS.NAV_API.FIND_ENTITY;
if (options.path.length === 1) {
url += '?type=database&name=' + options.path[0];
} else if (options.path.length === 2) {
url +=
(options.isView ? '?type=view' : '?type=table') +
'&database=' +
options.path[0] +
'&name=' +
options.path[1];
} else if (options.path.length === 3) {
url +=
'?type=field&database=' +
options.path[0] +
'&table=' +
options.path[1] +
'&name=' +
options.path[2];
} else {
return new CancellablePromise($.Deferred().reject());
}
const request = simplePost(
url,
{
notebook: {},
snippet: ko.mapping.toJSON({
type: 'nav'
})
},
{
silenceErrors: options.silenceErrors,
successCallback: data => {
data = data.entity || data;
data.hueTimestamp = Date.now();
deferred.resolve(data);
},
errorCallback: deferred.reject
}
);
return new CancellablePromise(deferred, request);
}
/**
* Updates Navigator properties and custom metadata for the given entity
*
* @param {Object} options
* @param {string} options.identity - The identifier for the Navigator entity to update
* @param {Object} [options.properties]
* @param {Object} [options.modifiedCustomMetadata]
* @param {string[]} [options.deletedCustomMetadataKeys]
* @param {boolean} [options.silenceErrors]
*
* @return {Promise}
*/
updateNavigatorProperties(options) {
const data = { id: ko.mapping.toJSON(options.identity) };
if (options.properties) {
data.properties = ko.mapping.toJSON(options.properties);
}
if (options.modifiedCustomMetadata) {
data.modifiedCustomMetadata = ko.mapping.toJSON(options.modifiedCustomMetadata);
}
if (options.deletedCustomMetadataKeys) {
data.deletedCustomMetadataKeys = ko.mapping.toJSON(options.deletedCustomMetadataKeys);
}
return simplePost(URLS.NAV_API.UPDATE_PROPERTIES, data, options);
}
/**
* Lists all available navigator tags
*
* @param {Object} options
* @param {boolean} [options.silenceErrors]
*
* @return {CancellablePromise}
*/
fetchAllNavigatorTags(options) {
const deferred = $.Deferred();
const request = simplePost(URLS.NAV_API.LIST_TAGS, undefined, {
silenceErrors: options.silenceErrors,
successCallback: data => {
if (data && data.tags) {
deferred.resolve(data.tags);
} else {
deferred.resolve({});
}
},
errorCallback: deferred.reject
});
return new CancellablePromise(deferred, request);
}
addNavTags(entityId, tags) {
return simplePost(URLS.NAV_API.ADD_TAGS, {
id: ko.mapping.toJSON(entityId),
tags: ko.mapping.toJSON(tags)
});
}
deleteNavTags(entityId, tags) {
return simplePost(URLS.NAV_API.DELETE_TAGS, {
id: ko.mapping.toJSON(entityId),
tags: ko.mapping.toJSON(tags)
});
}
/**
* @param {Object} options
* @param {boolean} [options.silenceErrors]
* @param {ContextCompute} options.compute
* @param {string} options.queryId
* @return {CancellablePromise}
*/
fetchQueryExecutionAnalysis(options) {
//var url = '/metadata/api/workload_analytics/get_impala_query/';
const url = '/impala/api/query/alanize';
const deferred = $.Deferred();
let tries = 0;
const cancellablePromises = [];
const promise = new CancellablePromise(deferred, undefined, cancellablePromises);
const pollForAnalysis = () => {
if (tries === 10) {
deferred.reject();
return;
}
tries++;
cancellablePromises.pop(); // Remove the last one
cancellablePromises.push(
deferred,
simplePost(
url,
{
cluster: JSON.stringify(options.compute),
query_id: '"' + options.queryId + '"'
},
options
)
.done(response => {
if (response && response.data) {
deferred.resolve(response.data);
} else {
const timeout = window.setTimeout(() => {
pollForAnalysis();
}, 1000 + tries * 500); // TODO: Adjust once fully implemented;
promise.onCancel(() => {
window.clearTimeout(timeout);
});
}
})
.fail(deferred.reject)
);
};
pollForAnalysis();
return promise;
}
fixQueryExecutionAnalysis(options) {
const url = '/impala/api/query/alanize/fix';
const deferred = $.Deferred();
const request = simplePost(
url,
{
cluster: JSON.stringify(options.compute),
fix: JSON.stringify(options.fix),
start_time: options.start_time
},
{
silenceErrors: options.silenceErrors,
successCallback: response => {
if (response.status === 0) {
deferred.resolve(response.details);
} else {
deferred.reject();
}
},
errorCallback: deferred.reject
}
);
return new CancellablePromise(deferred, request);
}
fetchQueryExecutionStatistics(options) {
const url = '/impala/api/query/alanize/metrics';
const deferred = $.Deferred();
const request = simplePost(
url,
{
cluster: JSON.stringify(options.cluster),
query_id: '"' + options.queryId + '"'
},
{
silenceErrors: options.silenceErrors,
successCallback: response => {
if (response.status === 0) {
deferred.resolve(response.data);
} else {
deferred.reject();
}
},
errorCallback: deferred.reject
}
);
return new CancellablePromise(deferred, request);
}
/**
* @param {Object} options
* @param {boolean} [options.silenceErrors]
* @param {Connector} options.connector
* @return {Promise}
*/
fetchContextNamespaces(options) {
const url = '/desktop/api2/context/namespaces/' + options.connector.id;
return simpleGet(url, undefined, options);
}
/**
* @param {Object} options
* @param {boolean} [options.silenceErrors]
* @param {Connector} options.connector
* @return {Promise}
*/
fetchContextComputes(options) {
const url = '/desktop/api2/context/computes/' + options.connector.id;
return simpleGet(url, undefined, options);
}
/**
* @param {Object} options
* @param {boolean} [options.silenceErrors]
* @param {Connector} options.connector
* @return {Promise}
*/
fetchContextClusters(options) {
const url = '/desktop/api2/context/clusters/' + options.connector.id;
return simpleGet(url, undefined, options);
}
async fetchHueConfigAsync(options) {
return new Promise((resolve, reject) => {
$.get(URLS.GET_HUE_CONFIG_API)
.done(response => {
if (!response && response.status === -1) {
reject(response.message);
} else {
resolve(response);
}
})
.fail(reject);
});
}
getClusterConfig(data) {
return $.post(URLS.FETCH_CONFIG_API, data);
}
fetchHueDocsInteractive(query) {
const deferred = $.Deferred();
const request = $.post(URLS.INTERACTIVE_SEARCH_API, {
query_s: ko.mapping.toJSON(query),
limit: 50,
sources: '["documents"]'
})
.done(data => {
if (data.status === 0) {
deferred.resolve(data);
} else {
deferred.reject(data);
}
})
.fail(deferred.reject);
return new CancellablePromise(deferred, request);
}
fetchNavEntitiesInteractive(options) {
const deferred = $.Deferred();
const request = $.post(URLS.INTERACTIVE_SEARCH_API, {
query_s: ko.mapping.toJSON(options.query),
field_facets: ko.mapping.toJSON(options.facets || []),
limit: 50,
sources: '["sql", "hdfs", "s3"]'
})
.done(data => {
if (data.status === 0) {
deferred.resolve(data);
} else {
deferred.reject(data);
}
})
.fail(deferred.reject);
return new CancellablePromise(deferred, request);
}
searchEntities(options) {
const deferred = $.Deferred();
const request = simplePost(
URLS.SEARCH_API,
{
query_s: ko.mapping.toJSON(options.query),
limit: options.limit || 100,
raw_query: !!options.rawQuery,
sources: options.sources ? ko.mapping.toJSON(options.sources) : '["sql"]'
},
{
silenceErrors: options.silenceErrors,
successCallback: deferred.resolve,
errorCallback: deferred.reject
}
);
return new CancellablePromise(deferred, request);
}
/**
*
* @param {Object} options
* @param {string} options.statements
* @param {boolean} [options.silenceErrors]
*/
formatSql(options) {
const deferred = $.Deferred();
const request = simplePost(
URLS.FORMAT_SQL_API,
{
statements: options.statements
},
{
silenceErrors: options.silenceErrors,
successCallback: deferred.resolve,
errorCallback: deferred.reject
}
);
return new CancellablePromise(deferred, request);
}
/**
*
* @param {Object} options
* @param {string} options.statement
* @param {string} options.doc_type
* @param {string} options.name
* @param {string} options.description
* @param {boolean} [options.silenceErrors]
*/
createGist(options) {
const deferred = $.Deferred();
const request = simplePost(
URLS.GIST_API + 'create',
{
statement: options.statement,
doc_type: options.doc_type,
name: options.name,
description: options.description
},
{
silenceErrors: options.silenceErrors,
successCallback: deferred.resolve,
errorCallback: deferred.reject
}
);
return new CancellablePromise(deferred, request);
}
}
const apiHelper = new ApiHelper();
export default apiHelper;
|
#When run on (my) windows box, this builds and cleans everything in
#preparation for a release.
import os
import sys
#Replace version strings
if len(sys.argv)>1:
oldVersion = sys.argv[1]
newVersion = sys.argv[2]
query = raw_input("Replace %s with %s?: " % (oldVersion, newVersion))
if query == "y":
#First, scan through and make sure the replacement is possible
for filename in ("setup.py", "tlslite\\__init__.py", "scripts\\tls.py", "scripts\\tlsdb.py"):
s = open(filename, "rU").read()
x = s.count(oldVersion)
if filename.endswith("__init__.py"):
if x != 2:
print "Error, old version appears in %s %s times" % (filename, x)
sys.exit()
else:
if x != 1:
print "Error, old version appears in %s %s times" % (filename, x)
sys.exit()
#Then perform it
for filename in ("setup.py", "tlslite\\__init__.py", "scripts\\tls.py", "scripts\\tlsdb.py"):
os.system("copy %s .." % filename) #save a backup copy in case something goes awry
s = open(filename, "r").read()
f = open(filename, "w")
f.write(s.replace(oldVersion, newVersion))
f.close()
#Make windows installers
os.system("del installers\*.exe")
#Python 2.3
os.system("rmdir build /s /q")
os.system("python23 setup.py bdist_wininst -o")
os.system("copy dist\* installers")
#Python 2.4
os.system("rmdir build /s /q")
os.system("python24 setup.py bdist_wininst -o")
os.system("copy dist\* installers")
#Make documentation
os.system("python23 c:\\devtools\\python23\\scripts\\epydoc.py --html -o docs tlslite")
#Delete excess files
os.system("del tlslite\\*.pyc")
os.system("del tlslite\\utils\\*.pyc")
os.system("del tlslite\\integration\\*.pyc")
os.system("rmdir build /s /q")
os.system("rmdir dist /s /q")
|
(function webpackUniversalModuleDefinition(root, factory) {
if(typeof exports === 'object' && typeof module === 'object')
module.exports = factory(require("babylonjs"));
else if(typeof define === 'function' && define.amd)
define("babylonjs-gui", ["babylonjs"], factory);
else if(typeof exports === 'object')
exports["babylonjs-gui"] = factory(require("babylonjs"));
else
root["BABYLON"] = root["BABYLON"] || {}, root["BABYLON"]["GUI"] = factory(root["BABYLON"]);
})((typeof self !== "undefined" ? self : typeof global !== "undefined" ? global : this), function(__WEBPACK_EXTERNAL_MODULE_babylonjs_Misc_observable__) {
return /******/ (function(modules) { // webpackBootstrap
/******/ // The module cache
/******/ var installedModules = {};
/******/
/******/ // The require function
/******/ function __webpack_require__(moduleId) {
/******/
/******/ // Check if module is in cache
/******/ if(installedModules[moduleId]) {
/******/ return installedModules[moduleId].exports;
/******/ }
/******/ // Create a new module (and put it into the cache)
/******/ var module = installedModules[moduleId] = {
/******/ i: moduleId,
/******/ l: false,
/******/ exports: {}
/******/ };
/******/
/******/ // Execute the module function
/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
/******/
/******/ // Flag the module as loaded
/******/ module.l = true;
/******/
/******/ // Return the exports of the module
/******/ return module.exports;
/******/ }
/******/
/******/
/******/ // expose the modules object (__webpack_modules__)
/******/ __webpack_require__.m = modules;
/******/
/******/ // expose the module cache
/******/ __webpack_require__.c = installedModules;
/******/
/******/ // define getter function for harmony exports
/******/ __webpack_require__.d = function(exports, name, getter) {
/******/ if(!__webpack_require__.o(exports, name)) {
/******/ Object.defineProperty(exports, name, { enumerable: true, get: getter });
/******/ }
/******/ };
/******/
/******/ // define __esModule on exports
/******/ __webpack_require__.r = function(exports) {
/******/ if(typeof Symbol !== 'undefined' && Symbol.toStringTag) {
/******/ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
/******/ }
/******/ Object.defineProperty(exports, '__esModule', { value: true });
/******/ };
/******/
/******/ // create a fake namespace object
/******/ // mode & 1: value is a module id, require it
/******/ // mode & 2: merge all properties of value into the ns
/******/ // mode & 4: return value when already ns object
/******/ // mode & 8|1: behave like require
/******/ __webpack_require__.t = function(value, mode) {
/******/ if(mode & 1) value = __webpack_require__(value);
/******/ if(mode & 8) return value;
/******/ if((mode & 4) && typeof value === 'object' && value && value.__esModule) return value;
/******/ var ns = Object.create(null);
/******/ __webpack_require__.r(ns);
/******/ Object.defineProperty(ns, 'default', { enumerable: true, value: value });
/******/ if(mode & 2 && typeof value != 'string') for(var key in value) __webpack_require__.d(ns, key, function(key) { return value[key]; }.bind(null, key));
/******/ return ns;
/******/ };
/******/
/******/ // getDefaultExport function for compatibility with non-harmony modules
/******/ __webpack_require__.n = function(module) {
/******/ var getter = module && module.__esModule ?
/******/ function getDefault() { return module['default']; } :
/******/ function getModuleExports() { return module; };
/******/ __webpack_require__.d(getter, 'a', getter);
/******/ return getter;
/******/ };
/******/
/******/ // Object.prototype.hasOwnProperty.call
/******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };
/******/
/******/ // __webpack_public_path__
/******/ __webpack_require__.p = "";
/******/
/******/
/******/ // Load entry module and return exports
/******/ return __webpack_require__(__webpack_require__.s = "./legacy/legacy.ts");
/******/ })
/************************************************************************/
/******/ ({
/***/ "../../node_modules/tslib/tslib.es6.js":
/*!***********************************************************!*\
!*** D:/Repos/Babylon.js/node_modules/tslib/tslib.es6.js ***!
\***********************************************************/
/*! exports provided: __extends, __assign, __rest, __decorate, __param, __metadata, __awaiter, __generator, __exportStar, __values, __read, __spread, __await, __asyncGenerator, __asyncDelegator, __asyncValues, __makeTemplateObject, __importStar, __importDefault */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "__extends", function() { return __extends; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "__assign", function() { return __assign; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "__rest", function() { return __rest; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "__decorate", function() { return __decorate; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "__param", function() { return __param; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "__metadata", function() { return __metadata; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "__awaiter", function() { return __awaiter; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "__generator", function() { return __generator; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "__exportStar", function() { return __exportStar; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "__values", function() { return __values; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "__read", function() { return __read; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "__spread", function() { return __spread; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "__await", function() { return __await; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "__asyncGenerator", function() { return __asyncGenerator; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "__asyncDelegator", function() { return __asyncDelegator; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "__asyncValues", function() { return __asyncValues; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "__makeTemplateObject", function() { return __makeTemplateObject; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "__importStar", function() { return __importStar; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "__importDefault", function() { return __importDefault; });
/*! *****************************************************************************
Copyright (c) Microsoft Corporation. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License"); you may not use
this file except in compliance with the License. You may obtain a copy of the
License at http://www.apache.org/licenses/LICENSE-2.0
THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
MERCHANTABLITY OR NON-INFRINGEMENT.
See the Apache Version 2.0 License for specific language governing permissions
and limitations under the License.
***************************************************************************** */
/* global Reflect, Promise */
var extendStatics = function(d, b) {
extendStatics = Object.setPrototypeOf ||
({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
return extendStatics(d, b);
};
function __extends(d, b) {
extendStatics(d, b);
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
}
var __assign = function() {
__assign = Object.assign || function __assign(t) {
for (var s, i = 1, n = arguments.length; i < n; i++) {
s = arguments[i];
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];
}
return t;
}
return __assign.apply(this, arguments);
}
function __rest(s, e) {
var t = {};
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
t[p] = s[p];
if (s != null && typeof Object.getOwnPropertySymbols === "function")
for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) if (e.indexOf(p[i]) < 0)
t[p[i]] = s[p[i]];
return t;
}
function __decorate(decorators, target, key, desc) {
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
return c > 3 && r && Object.defineProperty(target, key, r), r;
}
function __param(paramIndex, decorator) {
return function (target, key) { decorator(target, key, paramIndex); }
}
function __metadata(metadataKey, metadataValue) {
if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(metadataKey, metadataValue);
}
function __awaiter(thisArg, _arguments, P, generator) {
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
}
function __generator(thisArg, body) {
var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
function verb(n) { return function (v) { return step([n, v]); }; }
function step(op) {
if (f) throw new TypeError("Generator is already executing.");
while (_) try {
if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
if (y = 0, t) op = [op[0] & 2, t.value];
switch (op[0]) {
case 0: case 1: t = op; break;
case 4: _.label++; return { value: op[1], done: false };
case 5: _.label++; y = op[1]; op = [0]; continue;
case 7: op = _.ops.pop(); _.trys.pop(); continue;
default:
if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
if (t[2]) _.ops.pop();
_.trys.pop(); continue;
}
op = body.call(thisArg, _);
} catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
}
}
function __exportStar(m, exports) {
for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p];
}
function __values(o) {
var m = typeof Symbol === "function" && o[Symbol.iterator], i = 0;
if (m) return m.call(o);
return {
next: function () {
if (o && i >= o.length) o = void 0;
return { value: o && o[i++], done: !o };
}
};
}
function __read(o, n) {
var m = typeof Symbol === "function" && o[Symbol.iterator];
if (!m) return o;
var i = m.call(o), r, ar = [], e;
try {
while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
}
catch (error) { e = { error: error }; }
finally {
try {
if (r && !r.done && (m = i["return"])) m.call(i);
}
finally { if (e) throw e.error; }
}
return ar;
}
function __spread() {
for (var ar = [], i = 0; i < arguments.length; i++)
ar = ar.concat(__read(arguments[i]));
return ar;
}
function __await(v) {
return this instanceof __await ? (this.v = v, this) : new __await(v);
}
function __asyncGenerator(thisArg, _arguments, generator) {
if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
var g = generator.apply(thisArg, _arguments || []), i, q = [];
return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i;
function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; }
function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } }
function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); }
function fulfill(value) { resume("next", value); }
function reject(value) { resume("throw", value); }
function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); }
}
function __asyncDelegator(o) {
var i, p;
return i = {}, verb("next"), verb("throw", function (e) { throw e; }), verb("return"), i[Symbol.iterator] = function () { return this; }, i;
function verb(n, f) { i[n] = o[n] ? function (v) { return (p = !p) ? { value: __await(o[n](v)), done: n === "return" } : f ? f(v) : v; } : f; }
}
function __asyncValues(o) {
if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
var m = o[Symbol.asyncIterator], i;
return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i);
function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; }
function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); }
}
function __makeTemplateObject(cooked, raw) {
if (Object.defineProperty) { Object.defineProperty(cooked, "raw", { value: raw }); } else { cooked.raw = raw; }
return cooked;
};
function __importStar(mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];
result.default = mod;
return result;
}
function __importDefault(mod) {
return (mod && mod.__esModule) ? mod : { default: mod };
}
/***/ }),
/***/ "../../node_modules/webpack/buildin/global.js":
/*!***********************************!*\
!*** (webpack)/buildin/global.js ***!
\***********************************/
/*! no static exports found */
/***/ (function(module, exports) {
var g;
// This works in non-strict mode
g = (function() {
return this;
})();
try {
// This works if eval is allowed (see CSP)
g = g || new Function("return this")();
} catch (e) {
// This works if the window reference is available
if (typeof window === "object") g = window;
}
// g can still be undefined, but nothing to do about it...
// We return undefined, instead of nothing here, so it's
// easier to handle this case. if(!global) { ...}
module.exports = g;
/***/ }),
/***/ "./2D/adtInstrumentation.ts":
/*!**********************************!*\
!*** ./2D/adtInstrumentation.ts ***!
\**********************************/
/*! exports provided: AdvancedDynamicTextureInstrumentation */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "AdvancedDynamicTextureInstrumentation", function() { return AdvancedDynamicTextureInstrumentation; });
/* harmony import */ var babylonjs_Misc_tools__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! babylonjs/Misc/tools */ "babylonjs/Misc/observable");
/* harmony import */ var babylonjs_Misc_tools__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(babylonjs_Misc_tools__WEBPACK_IMPORTED_MODULE_0__);
/**
* This class can be used to get instrumentation data from a AdvancedDynamicTexture object
*/
var AdvancedDynamicTextureInstrumentation = /** @class */ (function () {
/**
* Instantiates a new advanced dynamic texture instrumentation.
* This class can be used to get instrumentation data from an AdvancedDynamicTexture object
* @param texture Defines the AdvancedDynamicTexture to instrument
*/
function AdvancedDynamicTextureInstrumentation(
/**
* Define the instrumented AdvancedDynamicTexture.
*/
texture) {
this.texture = texture;
this._captureRenderTime = false;
this._renderTime = new babylonjs_Misc_tools__WEBPACK_IMPORTED_MODULE_0__["PerfCounter"]();
this._captureLayoutTime = false;
this._layoutTime = new babylonjs_Misc_tools__WEBPACK_IMPORTED_MODULE_0__["PerfCounter"]();
// Observers
this._onBeginRenderObserver = null;
this._onEndRenderObserver = null;
this._onBeginLayoutObserver = null;
this._onEndLayoutObserver = null;
}
Object.defineProperty(AdvancedDynamicTextureInstrumentation.prototype, "renderTimeCounter", {
// Properties
/**
* Gets the perf counter used to capture render time
*/
get: function () {
return this._renderTime;
},
enumerable: true,
configurable: true
});
Object.defineProperty(AdvancedDynamicTextureInstrumentation.prototype, "layoutTimeCounter", {
/**
* Gets the perf counter used to capture layout time
*/
get: function () {
return this._layoutTime;
},
enumerable: true,
configurable: true
});
Object.defineProperty(AdvancedDynamicTextureInstrumentation.prototype, "captureRenderTime", {
/**
* Enable or disable the render time capture
*/
get: function () {
return this._captureRenderTime;
},
set: function (value) {
var _this = this;
if (value === this._captureRenderTime) {
return;
}
this._captureRenderTime = value;
if (value) {
this._onBeginRenderObserver = this.texture.onBeginRenderObservable.add(function () {
_this._renderTime.beginMonitoring();
});
this._onEndRenderObserver = this.texture.onEndRenderObservable.add(function () {
_this._renderTime.endMonitoring(true);
});
}
else {
this.texture.onBeginRenderObservable.remove(this._onBeginRenderObserver);
this._onBeginRenderObserver = null;
this.texture.onEndRenderObservable.remove(this._onEndRenderObserver);
this._onEndRenderObserver = null;
}
},
enumerable: true,
configurable: true
});
Object.defineProperty(AdvancedDynamicTextureInstrumentation.prototype, "captureLayoutTime", {
/**
* Enable or disable the layout time capture
*/
get: function () {
return this._captureLayoutTime;
},
set: function (value) {
var _this = this;
if (value === this._captureLayoutTime) {
return;
}
this._captureLayoutTime = value;
if (value) {
this._onBeginLayoutObserver = this.texture.onBeginLayoutObservable.add(function () {
_this._layoutTime.beginMonitoring();
});
this._onEndLayoutObserver = this.texture.onEndLayoutObservable.add(function () {
_this._layoutTime.endMonitoring(true);
});
}
else {
this.texture.onBeginLayoutObservable.remove(this._onBeginLayoutObserver);
this._onBeginLayoutObserver = null;
this.texture.onEndLayoutObservable.remove(this._onEndLayoutObserver);
this._onEndLayoutObserver = null;
}
},
enumerable: true,
configurable: true
});
/**
* Dispose and release associated resources.
*/
AdvancedDynamicTextureInstrumentation.prototype.dispose = function () {
this.texture.onBeginRenderObservable.remove(this._onBeginRenderObserver);
this._onBeginRenderObserver = null;
this.texture.onEndRenderObservable.remove(this._onEndRenderObserver);
this._onEndRenderObserver = null;
this.texture.onBeginLayoutObservable.remove(this._onBeginLayoutObserver);
this._onBeginLayoutObserver = null;
this.texture.onEndLayoutObservable.remove(this._onEndLayoutObserver);
this._onEndLayoutObserver = null;
this.texture = null;
};
return AdvancedDynamicTextureInstrumentation;
}());
/***/ }),
/***/ "./2D/advancedDynamicTexture.ts":
/*!**************************************!*\
!*** ./2D/advancedDynamicTexture.ts ***!
\**************************************/
/*! exports provided: AdvancedDynamicTexture */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "AdvancedDynamicTexture", function() { return AdvancedDynamicTexture; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../../node_modules/tslib/tslib.es6.js");
/* harmony import */ var babylonjs_Misc_observable__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! babylonjs/Misc/observable */ "babylonjs/Misc/observable");
/* harmony import */ var babylonjs_Misc_observable__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(babylonjs_Misc_observable__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var _controls_container__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./controls/container */ "./2D/controls/container.ts");
/* harmony import */ var _style__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./style */ "./2D/style.ts");
/* harmony import */ var _measure__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./measure */ "./2D/measure.ts");
/**
* Class used to create texture to support 2D GUI elements
* @see http://doc.babylonjs.com/how_to/gui
*/
var AdvancedDynamicTexture = /** @class */ (function (_super) {
tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](AdvancedDynamicTexture, _super);
/**
* Creates a new AdvancedDynamicTexture
* @param name defines the name of the texture
* @param width defines the width of the texture
* @param height defines the height of the texture
* @param scene defines the hosting scene
* @param generateMipMaps defines a boolean indicating if mipmaps must be generated (false by default)
* @param samplingMode defines the texture sampling mode (Texture.NEAREST_SAMPLINGMODE by default)
*/
function AdvancedDynamicTexture(name, width, height, scene, generateMipMaps, samplingMode) {
if (width === void 0) { width = 0; }
if (height === void 0) { height = 0; }
if (generateMipMaps === void 0) { generateMipMaps = false; }
if (samplingMode === void 0) { samplingMode = babylonjs_Misc_observable__WEBPACK_IMPORTED_MODULE_1__["Texture"].NEAREST_SAMPLINGMODE; }
var _this = _super.call(this, name, { width: width, height: height }, scene, generateMipMaps, samplingMode, babylonjs_Misc_observable__WEBPACK_IMPORTED_MODULE_1__["Engine"].TEXTUREFORMAT_RGBA) || this;
_this._isDirty = false;
/** @hidden */
_this._rootContainer = new _controls_container__WEBPACK_IMPORTED_MODULE_2__["Container"]("root");
/** @hidden */
_this._lastControlOver = {};
/** @hidden */
_this._lastControlDown = {};
/** @hidden */
_this._capturingControl = {};
/** @hidden */
_this._linkedControls = new Array();
_this._isFullscreen = false;
_this._fullscreenViewport = new babylonjs_Misc_observable__WEBPACK_IMPORTED_MODULE_1__["Viewport"](0, 0, 1, 1);
_this._idealWidth = 0;
_this._idealHeight = 0;
_this._useSmallestIdeal = false;
_this._renderAtIdealSize = false;
_this._blockNextFocusCheck = false;
_this._renderScale = 1;
_this._cursorChanged = false;
/**
* Define type to string to ensure compatibility across browsers
* Safari doesn't support DataTransfer constructor
*/
_this._clipboardData = "";
/**
* Observable event triggered each time an clipboard event is received from the rendering canvas
*/
_this.onClipboardObservable = new babylonjs_Misc_observable__WEBPACK_IMPORTED_MODULE_1__["Observable"]();
/**
* Observable event triggered each time a pointer down is intercepted by a control
*/
_this.onControlPickedObservable = new babylonjs_Misc_observable__WEBPACK_IMPORTED_MODULE_1__["Observable"]();
/**
* Observable event triggered before layout is evaluated
*/
_this.onBeginLayoutObservable = new babylonjs_Misc_observable__WEBPACK_IMPORTED_MODULE_1__["Observable"]();
/**
* Observable event triggered after the layout was evaluated
*/
_this.onEndLayoutObservable = new babylonjs_Misc_observable__WEBPACK_IMPORTED_MODULE_1__["Observable"]();
/**
* Observable event triggered before the texture is rendered
*/
_this.onBeginRenderObservable = new babylonjs_Misc_observable__WEBPACK_IMPORTED_MODULE_1__["Observable"]();
/**
* Observable event triggered after the texture was rendered
*/
_this.onEndRenderObservable = new babylonjs_Misc_observable__WEBPACK_IMPORTED_MODULE_1__["Observable"]();
/**
* Gets or sets a boolean defining if alpha is stored as premultiplied
*/
_this.premulAlpha = false;
_this._useInvalidateRectOptimization = true;
// Invalidated rectangle which is the combination of all invalidated controls after they have been rotated into absolute position
_this._invalidatedRectangle = null;
_this._clearMeasure = new _measure__WEBPACK_IMPORTED_MODULE_4__["Measure"](0, 0, 0, 0);
/** @hidden */
_this.onClipboardCopy = function (rawEvt) {
var evt = rawEvt;
var ev = new babylonjs_Misc_observable__WEBPACK_IMPORTED_MODULE_1__["ClipboardInfo"](babylonjs_Misc_observable__WEBPACK_IMPORTED_MODULE_1__["ClipboardEventTypes"].COPY, evt);
_this.onClipboardObservable.notifyObservers(ev);
evt.preventDefault();
};
/** @hidden */
_this.onClipboardCut = function (rawEvt) {
var evt = rawEvt;
var ev = new babylonjs_Misc_observable__WEBPACK_IMPORTED_MODULE_1__["ClipboardInfo"](babylonjs_Misc_observable__WEBPACK_IMPORTED_MODULE_1__["ClipboardEventTypes"].CUT, evt);
_this.onClipboardObservable.notifyObservers(ev);
evt.preventDefault();
};
/** @hidden */
_this.onClipboardPaste = function (rawEvt) {
var evt = rawEvt;
var ev = new babylonjs_Misc_observable__WEBPACK_IMPORTED_MODULE_1__["ClipboardInfo"](babylonjs_Misc_observable__WEBPACK_IMPORTED_MODULE_1__["ClipboardEventTypes"].PASTE, evt);
_this.onClipboardObservable.notifyObservers(ev);
evt.preventDefault();
};
scene = _this.getScene();
if (!scene || !_this._texture) {
return _this;
}
_this._rootCanvas = scene.getEngine().getRenderingCanvas();
_this._renderObserver = scene.onBeforeCameraRenderObservable.add(function (camera) { return _this._checkUpdate(camera); });
_this._preKeyboardObserver = scene.onPreKeyboardObservable.add(function (info) {
if (!_this._focusedControl) {
return;
}
if (info.type === babylonjs_Misc_observable__WEBPACK_IMPORTED_MODULE_1__["KeyboardEventTypes"].KEYDOWN) {
_this._focusedControl.processKeyboard(info.event);
}
info.skipOnPointerObservable = true;
});
_this._rootContainer._link(_this);
_this.hasAlpha = true;
if (!width || !height) {
_this._resizeObserver = scene.getEngine().onResizeObservable.add(function () { return _this._onResize(); });
_this._onResize();
}
_this._texture.isReady = true;
return _this;
}
Object.defineProperty(AdvancedDynamicTexture.prototype, "renderScale", {
/**
* Gets or sets a number used to scale rendering size (2 means that the texture will be twice bigger).
* Useful when you want more antialiasing
*/
get: function () {
return this._renderScale;
},
set: function (value) {
if (value === this._renderScale) {
return;
}
this._renderScale = value;
this._onResize();
},
enumerable: true,
configurable: true
});
Object.defineProperty(AdvancedDynamicTexture.prototype, "background", {
/** Gets or sets the background color */
get: function () {
return this._background;
},
set: function (value) {
if (this._background === value) {
return;
}
this._background = value;
this.markAsDirty();
},
enumerable: true,
configurable: true
});
Object.defineProperty(AdvancedDynamicTexture.prototype, "idealWidth", {
/**
* Gets or sets the ideal width used to design controls.
* The GUI will then rescale everything accordingly
* @see http://doc.babylonjs.com/how_to/gui#adaptive-scaling
*/
get: function () {
return this._idealWidth;
},
set: function (value) {
if (this._idealWidth === value) {
return;
}
this._idealWidth = value;
this.markAsDirty();
this._rootContainer._markAllAsDirty();
},
enumerable: true,
configurable: true
});
Object.defineProperty(AdvancedDynamicTexture.prototype, "idealHeight", {
/**
* Gets or sets the ideal height used to design controls.
* The GUI will then rescale everything accordingly
* @see http://doc.babylonjs.com/how_to/gui#adaptive-scaling
*/
get: function () {
return this._idealHeight;
},
set: function (value) {
if (this._idealHeight === value) {
return;
}
this._idealHeight = value;
this.markAsDirty();
this._rootContainer._markAllAsDirty();
},
enumerable: true,
configurable: true
});
Object.defineProperty(AdvancedDynamicTexture.prototype, "useSmallestIdeal", {
/**
* Gets or sets a boolean indicating if the smallest ideal value must be used if idealWidth and idealHeight are both set
* @see http://doc.babylonjs.com/how_to/gui#adaptive-scaling
*/
get: function () {
return this._useSmallestIdeal;
},
set: function (value) {
if (this._useSmallestIdeal === value) {
return;
}
this._useSmallestIdeal = value;
this.markAsDirty();
this._rootContainer._markAllAsDirty();
},
enumerable: true,
configurable: true
});
Object.defineProperty(AdvancedDynamicTexture.prototype, "renderAtIdealSize", {
/**
* Gets or sets a boolean indicating if adaptive scaling must be used
* @see http://doc.babylonjs.com/how_to/gui#adaptive-scaling
*/
get: function () {
return this._renderAtIdealSize;
},
set: function (value) {
if (this._renderAtIdealSize === value) {
return;
}
this._renderAtIdealSize = value;
this._onResize();
},
enumerable: true,
configurable: true
});
Object.defineProperty(AdvancedDynamicTexture.prototype, "layer", {
/**
* Gets the underlying layer used to render the texture when in fullscreen mode
*/
get: function () {
return this._layerToDispose;
},
enumerable: true,
configurable: true
});
Object.defineProperty(AdvancedDynamicTexture.prototype, "rootContainer", {
/**
* Gets the root container control
*/
get: function () {
return this._rootContainer;
},
enumerable: true,
configurable: true
});
/**
* Returns an array containing the root container.
* This is mostly used to let the Inspector introspects the ADT
* @returns an array containing the rootContainer
*/
AdvancedDynamicTexture.prototype.getChildren = function () {
return [this._rootContainer];
};
/**
* Will return all controls that are inside this texture
* @param directDescendantsOnly defines if true only direct descendants of 'this' will be considered, if false direct and also indirect (children of children, an so on in a recursive manner) descendants of 'this' will be considered
* @param predicate defines an optional predicate that will be called on every evaluated child, the predicate must return true for a given child to be part of the result, otherwise it will be ignored
* @return all child controls
*/
AdvancedDynamicTexture.prototype.getDescendants = function (directDescendantsOnly, predicate) {
return this._rootContainer.getDescendants(directDescendantsOnly, predicate);
};
Object.defineProperty(AdvancedDynamicTexture.prototype, "focusedControl", {
/**
* Gets or sets the current focused control
*/
get: function () {
return this._focusedControl;
},
set: function (control) {
if (this._focusedControl == control) {
return;
}
if (this._focusedControl) {
this._focusedControl.onBlur();
}
if (control) {
control.onFocus();
}
this._focusedControl = control;
},
enumerable: true,
configurable: true
});
Object.defineProperty(AdvancedDynamicTexture.prototype, "isForeground", {
/**
* Gets or sets a boolean indicating if the texture must be rendered in background or foreground when in fullscreen mode
*/
get: function () {
if (!this.layer) {
return true;
}
return (!this.layer.isBackground);
},
set: function (value) {
if (!this.layer) {
return;
}
if (this.layer.isBackground === !value) {
return;
}
this.layer.isBackground = !value;
},
enumerable: true,
configurable: true
});
Object.defineProperty(AdvancedDynamicTexture.prototype, "clipboardData", {
/**
* Gets or set information about clipboardData
*/
get: function () {
return this._clipboardData;
},
set: function (value) {
this._clipboardData = value;
},
enumerable: true,
configurable: true
});
/**
* Get the current class name of the texture useful for serialization or dynamic coding.
* @returns "AdvancedDynamicTexture"
*/
AdvancedDynamicTexture.prototype.getClassName = function () {
return "AdvancedDynamicTexture";
};
/**
* Function used to execute a function on all controls
* @param func defines the function to execute
* @param container defines the container where controls belong. If null the root container will be used
*/
AdvancedDynamicTexture.prototype.executeOnAllControls = function (func, container) {
if (!container) {
container = this._rootContainer;
}
func(container);
for (var _i = 0, _a = container.children; _i < _a.length; _i++) {
var child = _a[_i];
if (child.children) {
this.executeOnAllControls(func, child);
continue;
}
func(child);
}
};
Object.defineProperty(AdvancedDynamicTexture.prototype, "useInvalidateRectOptimization", {
/**
* Gets or sets a boolean indicating if the InvalidateRect optimization should be turned on
*/
get: function () {
return this._useInvalidateRectOptimization;
},
set: function (value) {
this._useInvalidateRectOptimization = value;
},
enumerable: true,
configurable: true
});
/**
* Invalidates a rectangle area on the gui texture
* @param invalidMinX left most position of the rectangle to invalidate in the texture
* @param invalidMinY top most position of the rectangle to invalidate in the texture
* @param invalidMaxX right most position of the rectangle to invalidate in the texture
* @param invalidMaxY bottom most position of the rectangle to invalidate in the texture
*/
AdvancedDynamicTexture.prototype.invalidateRect = function (invalidMinX, invalidMinY, invalidMaxX, invalidMaxY) {
if (!this._useInvalidateRectOptimization) {
return;
}
if (!this._invalidatedRectangle) {
this._invalidatedRectangle = new _measure__WEBPACK_IMPORTED_MODULE_4__["Measure"](invalidMinX, invalidMinY, invalidMaxX - invalidMinX + 1, invalidMaxY - invalidMinY + 1);
}
else {
// Compute intersection
var maxX = Math.ceil(Math.max(this._invalidatedRectangle.left + this._invalidatedRectangle.width - 1, invalidMaxX));
var maxY = Math.ceil(Math.max(this._invalidatedRectangle.top + this._invalidatedRectangle.height - 1, invalidMaxY));
this._invalidatedRectangle.left = Math.floor(Math.min(this._invalidatedRectangle.left, invalidMinX));
this._invalidatedRectangle.top = Math.floor(Math.min(this._invalidatedRectangle.top, invalidMinY));
this._invalidatedRectangle.width = maxX - this._invalidatedRectangle.left + 1;
this._invalidatedRectangle.height = maxY - this._invalidatedRectangle.top + 1;
}
};
/**
* Marks the texture as dirty forcing a complete update
*/
AdvancedDynamicTexture.prototype.markAsDirty = function () {
this._isDirty = true;
};
/**
* Helper function used to create a new style
* @returns a new style
* @see http://doc.babylonjs.com/how_to/gui#styles
*/
AdvancedDynamicTexture.prototype.createStyle = function () {
return new _style__WEBPACK_IMPORTED_MODULE_3__["Style"](this);
};
/**
* Adds a new control to the root container
* @param control defines the control to add
* @returns the current texture
*/
AdvancedDynamicTexture.prototype.addControl = function (control) {
this._rootContainer.addControl(control);
return this;
};
/**
* Removes a control from the root container
* @param control defines the control to remove
* @returns the current texture
*/
AdvancedDynamicTexture.prototype.removeControl = function (control) {
this._rootContainer.removeControl(control);
return this;
};
/**
* Release all resources
*/
AdvancedDynamicTexture.prototype.dispose = function () {
var scene = this.getScene();
if (!scene) {
return;
}
this._rootCanvas = null;
scene.onBeforeCameraRenderObservable.remove(this._renderObserver);
if (this._resizeObserver) {
scene.getEngine().onResizeObservable.remove(this._resizeObserver);
}
if (this._pointerMoveObserver) {
scene.onPrePointerObservable.remove(this._pointerMoveObserver);
}
if (this._pointerObserver) {
scene.onPointerObservable.remove(this._pointerObserver);
}
if (this._preKeyboardObserver) {
scene.onPreKeyboardObservable.remove(this._preKeyboardObserver);
}
if (this._canvasPointerOutObserver) {
scene.getEngine().onCanvasPointerOutObservable.remove(this._canvasPointerOutObserver);
}
if (this._layerToDispose) {
this._layerToDispose.texture = null;
this._layerToDispose.dispose();
this._layerToDispose = null;
}
this._rootContainer.dispose();
this.onClipboardObservable.clear();
this.onControlPickedObservable.clear();
this.onBeginRenderObservable.clear();
this.onEndRenderObservable.clear();
this.onBeginLayoutObservable.clear();
this.onEndLayoutObservable.clear();
_super.prototype.dispose.call(this);
};
AdvancedDynamicTexture.prototype._onResize = function () {
var scene = this.getScene();
if (!scene) {
return;
}
// Check size
var engine = scene.getEngine();
var textureSize = this.getSize();
var renderWidth = engine.getRenderWidth() * this._renderScale;
var renderHeight = engine.getRenderHeight() * this._renderScale;
if (this._renderAtIdealSize) {
if (this._idealWidth) {
renderHeight = (renderHeight * this._idealWidth) / renderWidth;
renderWidth = this._idealWidth;
}
else if (this._idealHeight) {
renderWidth = (renderWidth * this._idealHeight) / renderHeight;
renderHeight = this._idealHeight;
}
}
if (textureSize.width !== renderWidth || textureSize.height !== renderHeight) {
this.scaleTo(renderWidth, renderHeight);
this.markAsDirty();
if (this._idealWidth || this._idealHeight) {
this._rootContainer._markAllAsDirty();
}
}
this.invalidateRect(0, 0, textureSize.width - 1, textureSize.height - 1);
};
/** @hidden */
AdvancedDynamicTexture.prototype._getGlobalViewport = function (scene) {
var engine = scene.getEngine();
return this._fullscreenViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
};
/**
* Get screen coordinates for a vector3
* @param position defines the position to project
* @param worldMatrix defines the world matrix to use
* @returns the projected position
*/
AdvancedDynamicTexture.prototype.getProjectedPosition = function (position, worldMatrix) {
var scene = this.getScene();
if (!scene) {
return babylonjs_Misc_observable__WEBPACK_IMPORTED_MODULE_1__["Vector2"].Zero();
}
var globalViewport = this._getGlobalViewport(scene);
var projectedPosition = babylonjs_Misc_observable__WEBPACK_IMPORTED_MODULE_1__["Vector3"].Project(position, worldMatrix, scene.getTransformMatrix(), globalViewport);
projectedPosition.scaleInPlace(this.renderScale);
return new babylonjs_Misc_observable__WEBPACK_IMPORTED_MODULE_1__["Vector2"](projectedPosition.x, projectedPosition.y);
};
AdvancedDynamicTexture.prototype._checkUpdate = function (camera) {
if (this._layerToDispose) {
if ((camera.layerMask & this._layerToDispose.layerMask) === 0) {
return;
}
}
if (this._isFullscreen && this._linkedControls.length) {
var scene = this.getScene();
if (!scene) {
return;
}
var globalViewport = this._getGlobalViewport(scene);
for (var _i = 0, _a = this._linkedControls; _i < _a.length; _i++) {
var control = _a[_i];
if (!control.isVisible) {
continue;
}
var mesh = control._linkedMesh;
if (!mesh || mesh.isDisposed()) {
babylonjs_Misc_observable__WEBPACK_IMPORTED_MODULE_1__["Tools"].SetImmediate(function () {
control.linkWithMesh(null);
});
continue;
}
var position = mesh.getBoundingInfo ? mesh.getBoundingInfo().boundingSphere.center : mesh.getAbsolutePosition();
var projectedPosition = babylonjs_Misc_observable__WEBPACK_IMPORTED_MODULE_1__["Vector3"].Project(position, mesh.getWorldMatrix(), scene.getTransformMatrix(), globalViewport);
if (projectedPosition.z < 0 || projectedPosition.z > 1) {
control.notRenderable = true;
continue;
}
control.notRenderable = false;
// Account for RenderScale.
projectedPosition.scaleInPlace(this.renderScale);
control._moveToProjectedPosition(projectedPosition);
}
}
if (!this._isDirty && !this._rootContainer.isDirty) {
return;
}
this._isDirty = false;
this._render();
this.update(true, this.premulAlpha);
};
AdvancedDynamicTexture.prototype._render = function () {
var textureSize = this.getSize();
var renderWidth = textureSize.width;
var renderHeight = textureSize.height;
var context = this.getContext();
context.font = "18px Arial";
context.strokeStyle = "white";
// Layout
this.onBeginLayoutObservable.notifyObservers(this);
var measure = new _measure__WEBPACK_IMPORTED_MODULE_4__["Measure"](0, 0, renderWidth, renderHeight);
this._rootContainer._layout(measure, context);
this.onEndLayoutObservable.notifyObservers(this);
this._isDirty = false; // Restoring the dirty state that could have been set by controls during layout processing
// Clear
if (this._invalidatedRectangle) {
this._clearMeasure.copyFrom(this._invalidatedRectangle);
}
else {
this._clearMeasure.copyFromFloats(0, 0, renderWidth, renderHeight);
}
context.clearRect(this._clearMeasure.left, this._clearMeasure.top, this._clearMeasure.width, this._clearMeasure.height);
if (this._background) {
context.save();
context.fillStyle = this._background;
context.fillRect(this._clearMeasure.left, this._clearMeasure.top, this._clearMeasure.width, this._clearMeasure.height);
context.restore();
}
// Render
this.onBeginRenderObservable.notifyObservers(this);
this._rootContainer._render(context, this._invalidatedRectangle);
this.onEndRenderObservable.notifyObservers(this);
this._invalidatedRectangle = null;
};
/** @hidden */
AdvancedDynamicTexture.prototype._changeCursor = function (cursor) {
if (this._rootCanvas) {
this._rootCanvas.style.cursor = cursor;
this._cursorChanged = true;
}
};
/** @hidden */
AdvancedDynamicTexture.prototype._registerLastControlDown = function (control, pointerId) {
this._lastControlDown[pointerId] = control;
this.onControlPickedObservable.notifyObservers(control);
};
AdvancedDynamicTexture.prototype._doPicking = function (x, y, type, pointerId, buttonIndex) {
var scene = this.getScene();
if (!scene) {
return;
}
var engine = scene.getEngine();
var textureSize = this.getSize();
if (this._isFullscreen) {
var camera = scene.cameraToUseForPointers || scene.activeCamera;
var viewport = camera.viewport;
x = x * (textureSize.width / (engine.getRenderWidth() * viewport.width));
y = y * (textureSize.height / (engine.getRenderHeight() * viewport.height));
}
if (this._capturingControl[pointerId]) {
this._capturingControl[pointerId]._processObservables(type, x, y, pointerId, buttonIndex);
return;
}
this._cursorChanged = false;
if (!this._rootContainer._processPicking(x, y, type, pointerId, buttonIndex)) {
this._changeCursor("");
if (type === babylonjs_Misc_observable__WEBPACK_IMPORTED_MODULE_1__["PointerEventTypes"].POINTERMOVE) {
if (this._lastControlOver[pointerId]) {
this._lastControlOver[pointerId]._onPointerOut(this._lastControlOver[pointerId]);
delete this._lastControlOver[pointerId];
}
}
}
if (!this._cursorChanged) {
this._changeCursor("");
}
this._manageFocus();
};
/** @hidden */
AdvancedDynamicTexture.prototype._cleanControlAfterRemovalFromList = function (list, control) {
for (var pointerId in list) {
if (!list.hasOwnProperty(pointerId)) {
continue;
}
var lastControlOver = list[pointerId];
if (lastControlOver === control) {
delete list[pointerId];
}
}
};
/** @hidden */
AdvancedDynamicTexture.prototype._cleanControlAfterRemoval = function (control) {
this._cleanControlAfterRemovalFromList(this._lastControlDown, control);
this._cleanControlAfterRemovalFromList(this._lastControlOver, control);
};
/** Attach to all scene events required to support pointer events */
AdvancedDynamicTexture.prototype.attach = function () {
var _this = this;
var scene = this.getScene();
if (!scene) {
return;
}
var tempViewport = new babylonjs_Misc_observable__WEBPACK_IMPORTED_MODULE_1__["Viewport"](0, 0, 0, 0);
this._pointerMoveObserver = scene.onPrePointerObservable.add(function (pi, state) {
if (scene.isPointerCaptured((pi.event).pointerId)) {
return;
}
if (pi.type !== babylonjs_Misc_observable__WEBPACK_IMPORTED_MODULE_1__["PointerEventTypes"].POINTERMOVE
&& pi.type !== babylonjs_Misc_observable__WEBPACK_IMPORTED_MODULE_1__["PointerEventTypes"].POINTERUP
&& pi.type !== babylonjs_Misc_observable__WEBPACK_IMPORTED_MODULE_1__["PointerEventTypes"].POINTERDOWN) {
return;
}
if (!scene) {
return;
}
var camera = scene.cameraToUseForPointers || scene.activeCamera;
var engine = scene.getEngine();
if (!camera) {
tempViewport.x = 0;
tempViewport.y = 0;
tempViewport.width = engine.getRenderWidth();
tempViewport.height = engine.getRenderHeight();
}
else {
camera.viewport.toGlobalToRef(engine.getRenderWidth(), engine.getRenderHeight(), tempViewport);
}
var x = scene.pointerX / engine.getHardwareScalingLevel() - tempViewport.x;
var y = scene.pointerY / engine.getHardwareScalingLevel() - (engine.getRenderHeight() - tempViewport.y - tempViewport.height);
_this._shouldBlockPointer = false;
// Do picking modifies _shouldBlockPointer
_this._doPicking(x, y, pi.type, pi.event.pointerId || 0, pi.event.button);
// Avoid overwriting a true skipOnPointerObservable to false
if (_this._shouldBlockPointer) {
pi.skipOnPointerObservable = _this._shouldBlockPointer;
}
});
this._attachToOnPointerOut(scene);
};
/**
* Register the clipboard Events onto the canvas
*/
AdvancedDynamicTexture.prototype.registerClipboardEvents = function () {
self.addEventListener("copy", this.onClipboardCopy, false);
self.addEventListener("cut", this.onClipboardCut, false);
self.addEventListener("paste", this.onClipboardPaste, false);
};
/**
* Unregister the clipboard Events from the canvas
*/
AdvancedDynamicTexture.prototype.unRegisterClipboardEvents = function () {
self.removeEventListener("copy", this.onClipboardCopy);
self.removeEventListener("cut", this.onClipboardCut);
self.removeEventListener("paste", this.onClipboardPaste);
};
/**
* Connect the texture to a hosting mesh to enable interactions
* @param mesh defines the mesh to attach to
* @param supportPointerMove defines a boolean indicating if pointer move events must be catched as well
*/
AdvancedDynamicTexture.prototype.attachToMesh = function (mesh, supportPointerMove) {
var _this = this;
if (supportPointerMove === void 0) { supportPointerMove = true; }
var scene = this.getScene();
if (!scene) {
return;
}
this._pointerObserver = scene.onPointerObservable.add(function (pi, state) {
if (pi.type !== babylonjs_Misc_observable__WEBPACK_IMPORTED_MODULE_1__["PointerEventTypes"].POINTERMOVE
&& pi.type !== babylonjs_Misc_observable__WEBPACK_IMPORTED_MODULE_1__["PointerEventTypes"].POINTERUP
&& pi.type !== babylonjs_Misc_observable__WEBPACK_IMPORTED_MODULE_1__["PointerEventTypes"].POINTERDOWN) {
return;
}
var pointerId = pi.event.pointerId || 0;
if (pi.pickInfo && pi.pickInfo.hit && pi.pickInfo.pickedMesh === mesh) {
var uv = pi.pickInfo.getTextureCoordinates();
if (uv) {
var size = _this.getSize();
_this._doPicking(uv.x * size.width, (1.0 - uv.y) * size.height, pi.type, pointerId, pi.event.button);
}
}
else if (pi.type === babylonjs_Misc_observable__WEBPACK_IMPORTED_MODULE_1__["PointerEventTypes"].POINTERUP) {
if (_this._lastControlDown[pointerId]) {
_this._lastControlDown[pointerId]._forcePointerUp(pointerId);
}
delete _this._lastControlDown[pointerId];
if (_this.focusedControl) {
var friendlyControls = _this.focusedControl.keepsFocusWith();
var canMoveFocus = true;
if (friendlyControls) {
for (var _i = 0, friendlyControls_1 = friendlyControls; _i < friendlyControls_1.length; _i++) {
var control = friendlyControls_1[_i];
// Same host, no need to keep the focus
if (_this === control._host) {
continue;
}
// Different hosts
var otherHost = control._host;
if (otherHost._lastControlOver[pointerId] && otherHost._lastControlOver[pointerId].isAscendant(control)) {
canMoveFocus = false;
break;
}
}
}
if (canMoveFocus) {
_this.focusedControl = null;
}
}
}
else if (pi.type === babylonjs_Misc_observable__WEBPACK_IMPORTED_MODULE_1__["PointerEventTypes"].POINTERMOVE) {
if (_this._lastControlOver[pointerId]) {
_this._lastControlOver[pointerId]._onPointerOut(_this._lastControlOver[pointerId], true);
}
delete _this._lastControlOver[pointerId];
}
});
mesh.enablePointerMoveEvents = supportPointerMove;
this._attachToOnPointerOut(scene);
};
/**
* Move the focus to a specific control
* @param control defines the control which will receive the focus
*/
AdvancedDynamicTexture.prototype.moveFocusToControl = function (control) {
this.focusedControl = control;
this._lastPickedControl = control;
this._blockNextFocusCheck = true;
};
AdvancedDynamicTexture.prototype._manageFocus = function () {
if (this._blockNextFocusCheck) {
this._blockNextFocusCheck = false;
this._lastPickedControl = this._focusedControl;
return;
}
// Focus management
if (this._focusedControl) {
if (this._focusedControl !== this._lastPickedControl) {
if (this._lastPickedControl.isFocusInvisible) {
return;
}
this.focusedControl = null;
}
}
};
AdvancedDynamicTexture.prototype._attachToOnPointerOut = function (scene) {
var _this = this;
this._canvasPointerOutObserver = scene.getEngine().onCanvasPointerOutObservable.add(function (pointerEvent) {
if (_this._lastControlOver[pointerEvent.pointerId]) {
_this._lastControlOver[pointerEvent.pointerId]._onPointerOut(_this._lastControlOver[pointerEvent.pointerId]);
}
delete _this._lastControlOver[pointerEvent.pointerId];
if (_this._lastControlDown[pointerEvent.pointerId] && _this._lastControlDown[pointerEvent.pointerId] !== _this._capturingControl[pointerEvent.pointerId]) {
_this._lastControlDown[pointerEvent.pointerId]._forcePointerUp();
delete _this._lastControlDown[pointerEvent.pointerId];
}
});
};
// Statics
/**
* Creates a new AdvancedDynamicTexture in projected mode (ie. attached to a mesh)
* @param mesh defines the mesh which will receive the texture
* @param width defines the texture width (1024 by default)
* @param height defines the texture height (1024 by default)
* @param supportPointerMove defines a boolean indicating if the texture must capture move events (true by default)
* @param onlyAlphaTesting defines a boolean indicating that alpha blending will not be used (only alpha testing) (false by default)
* @returns a new AdvancedDynamicTexture
*/
AdvancedDynamicTexture.CreateForMesh = function (mesh, width, height, supportPointerMove, onlyAlphaTesting) {
if (width === void 0) { width = 1024; }
if (height === void 0) { height = 1024; }
if (supportPointerMove === void 0) { supportPointerMove = true; }
if (onlyAlphaTesting === void 0) { onlyAlphaTesting = false; }
var result = new AdvancedDynamicTexture(mesh.name + " AdvancedDynamicTexture", width, height, mesh.getScene(), true, babylonjs_Misc_observable__WEBPACK_IMPORTED_MODULE_1__["Texture"].TRILINEAR_SAMPLINGMODE);
var material = new babylonjs_Misc_observable__WEBPACK_IMPORTED_MODULE_1__["StandardMaterial"]("AdvancedDynamicTextureMaterial", mesh.getScene());
material.backFaceCulling = false;
material.diffuseColor = babylonjs_Misc_observable__WEBPACK_IMPORTED_MODULE_1__["Color3"].Black();
material.specularColor = babylonjs_Misc_observable__WEBPACK_IMPORTED_MODULE_1__["Color3"].Black();
if (onlyAlphaTesting) {
material.diffuseTexture = result;
material.emissiveTexture = result;
result.hasAlpha = true;
}
else {
material.emissiveTexture = result;
material.opacityTexture = result;
}
mesh.material = material;
result.attachToMesh(mesh, supportPointerMove);
return result;
};
/**
* Creates a new AdvancedDynamicTexture in fullscreen mode.
* In this mode the texture will rely on a layer for its rendering.
* This allows it to be treated like any other layer.
* As such, if you have a multi camera setup, you can set the layerMask on the GUI as well.
* LayerMask is set through advancedTexture.layer.layerMask
* @param name defines name for the texture
* @param foreground defines a boolean indicating if the texture must be rendered in foreground (default is true)
* @param scene defines the hsoting scene
* @param sampling defines the texture sampling mode (Texture.BILINEAR_SAMPLINGMODE by default)
* @returns a new AdvancedDynamicTexture
*/
AdvancedDynamicTexture.CreateFullscreenUI = function (name, foreground, scene, sampling) {
if (foreground === void 0) { foreground = true; }
if (scene === void 0) { scene = null; }
if (sampling === void 0) { sampling = babylonjs_Misc_observable__WEBPACK_IMPORTED_MODULE_1__["Texture"].BILINEAR_SAMPLINGMODE; }
var result = new AdvancedDynamicTexture(name, 0, 0, scene, false, sampling);
// Display
var layer = new babylonjs_Misc_observable__WEBPACK_IMPORTED_MODULE_1__["Layer"](name + "_layer", null, scene, !foreground);
layer.texture = result;
result._layerToDispose = layer;
result._isFullscreen = true;
// Attach
result.attach();
return result;
};
return AdvancedDynamicTexture;
}(babylonjs_Misc_observable__WEBPACK_IMPORTED_MODULE_1__["DynamicTexture"]));
/***/ }),
/***/ "./2D/controls/button.ts":
/*!*******************************!*\
!*** ./2D/controls/button.ts ***!
\*******************************/
/*! exports provided: Button */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Button", function() { return Button; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../../node_modules/tslib/tslib.es6.js");
/* harmony import */ var _rectangle__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./rectangle */ "./2D/controls/rectangle.ts");
/* harmony import */ var _control__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./control */ "./2D/controls/control.ts");
/* harmony import */ var _textBlock__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./textBlock */ "./2D/controls/textBlock.ts");
/* harmony import */ var _image__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./image */ "./2D/controls/image.ts");
/**
* Class used to create 2D buttons
*/
var Button = /** @class */ (function (_super) {
tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](Button, _super);
/**
* Creates a new Button
* @param name defines the name of the button
*/
function Button(name) {
var _this = _super.call(this, name) || this;
_this.name = name;
_this.thickness = 1;
_this.isPointerBlocker = true;
var alphaStore = null;
_this.pointerEnterAnimation = function () {
alphaStore = _this.alpha;
_this.alpha -= 0.1;
};
_this.pointerOutAnimation = function () {
if (alphaStore !== null) {
_this.alpha = alphaStore;
}
};
_this.pointerDownAnimation = function () {
_this.scaleX -= 0.05;
_this.scaleY -= 0.05;
};
_this.pointerUpAnimation = function () {
_this.scaleX += 0.05;
_this.scaleY += 0.05;
};
return _this;
}
Object.defineProperty(Button.prototype, "image", {
/**
* Returns the image part of the button (if any)
*/
get: function () {
return this._image;
},
enumerable: true,
configurable: true
});
Object.defineProperty(Button.prototype, "textBlock", {
/**
* Returns the image part of the button (if any)
*/
get: function () {
return this._textBlock;
},
enumerable: true,
configurable: true
});
Button.prototype._getTypeName = function () {
return "Button";
};
// While being a container, the button behaves like a control.
/** @hidden */
Button.prototype._processPicking = function (x, y, type, pointerId, buttonIndex) {
if (!this._isEnabled || !this.isHitTestVisible || !this.isVisible || this.notRenderable) {
return false;
}
if (!_super.prototype.contains.call(this, x, y)) {
return false;
}
this._processObservables(type, x, y, pointerId, buttonIndex);
return true;
};
/** @hidden */
Button.prototype._onPointerEnter = function (target) {
if (!_super.prototype._onPointerEnter.call(this, target)) {
return false;
}
if (this.pointerEnterAnimation) {
this.pointerEnterAnimation();
}
return true;
};
/** @hidden */
Button.prototype._onPointerOut = function (target, force) {
if (force === void 0) { force = false; }
if (this.pointerOutAnimation) {
this.pointerOutAnimation();
}
_super.prototype._onPointerOut.call(this, target, force);
};
/** @hidden */
Button.prototype._onPointerDown = function (target, coordinates, pointerId, buttonIndex) {
if (!_super.prototype._onPointerDown.call(this, target, coordinates, pointerId, buttonIndex)) {
return false;
}
if (this.pointerDownAnimation) {
this.pointerDownAnimation();
}
return true;
};
/** @hidden */
Button.prototype._onPointerUp = function (target, coordinates, pointerId, buttonIndex, notifyClick) {
if (this.pointerUpAnimation) {
this.pointerUpAnimation();
}
_super.prototype._onPointerUp.call(this, target, coordinates, pointerId, buttonIndex, notifyClick);
};
// Statics
/**
* Creates a new button made with an image and a text
* @param name defines the name of the button
* @param text defines the text of the button
* @param imageUrl defines the url of the image
* @returns a new Button
*/
Button.CreateImageButton = function (name, text, imageUrl) {
var result = new Button(name);
// Adding text
var textBlock = new _textBlock__WEBPACK_IMPORTED_MODULE_3__["TextBlock"](name + "_button", text);
textBlock.textWrapping = true;
textBlock.textHorizontalAlignment = _control__WEBPACK_IMPORTED_MODULE_2__["Control"].HORIZONTAL_ALIGNMENT_CENTER;
textBlock.paddingLeft = "20%";
result.addControl(textBlock);
// Adding image
var iconImage = new _image__WEBPACK_IMPORTED_MODULE_4__["Image"](name + "_icon", imageUrl);
iconImage.width = "20%";
iconImage.stretch = _image__WEBPACK_IMPORTED_MODULE_4__["Image"].STRETCH_UNIFORM;
iconImage.horizontalAlignment = _control__WEBPACK_IMPORTED_MODULE_2__["Control"].HORIZONTAL_ALIGNMENT_LEFT;
result.addControl(iconImage);
// Store
result._image = iconImage;
result._textBlock = textBlock;
return result;
};
/**
* Creates a new button made with an image
* @param name defines the name of the button
* @param imageUrl defines the url of the image
* @returns a new Button
*/
Button.CreateImageOnlyButton = function (name, imageUrl) {
var result = new Button(name);
// Adding image
var iconImage = new _image__WEBPACK_IMPORTED_MODULE_4__["Image"](name + "_icon", imageUrl);
iconImage.stretch = _image__WEBPACK_IMPORTED_MODULE_4__["Image"].STRETCH_FILL;
iconImage.horizontalAlignment = _control__WEBPACK_IMPORTED_MODULE_2__["Control"].HORIZONTAL_ALIGNMENT_LEFT;
result.addControl(iconImage);
// Store
result._image = iconImage;
return result;
};
/**
* Creates a new button made with a text
* @param name defines the name of the button
* @param text defines the text of the button
* @returns a new Button
*/
Button.CreateSimpleButton = function (name, text) {
var result = new Button(name);
// Adding text
var textBlock = new _textBlock__WEBPACK_IMPORTED_MODULE_3__["TextBlock"](name + "_button", text);
textBlock.textWrapping = true;
textBlock.textHorizontalAlignment = _control__WEBPACK_IMPORTED_MODULE_2__["Control"].HORIZONTAL_ALIGNMENT_CENTER;
result.addControl(textBlock);
// Store
result._textBlock = textBlock;
return result;
};
/**
* Creates a new button made with an image and a centered text
* @param name defines the name of the button
* @param text defines the text of the button
* @param imageUrl defines the url of the image
* @returns a new Button
*/
Button.CreateImageWithCenterTextButton = function (name, text, imageUrl) {
var result = new Button(name);
// Adding image
var iconImage = new _image__WEBPACK_IMPORTED_MODULE_4__["Image"](name + "_icon", imageUrl);
iconImage.stretch = _image__WEBPACK_IMPORTED_MODULE_4__["Image"].STRETCH_FILL;
result.addControl(iconImage);
// Adding text
var textBlock = new _textBlock__WEBPACK_IMPORTED_MODULE_3__["TextBlock"](name + "_button", text);
textBlock.textWrapping = true;
textBlock.textHorizontalAlignment = _control__WEBPACK_IMPORTED_MODULE_2__["Control"].HORIZONTAL_ALIGNMENT_CENTER;
result.addControl(textBlock);
// Store
result._image = iconImage;
result._textBlock = textBlock;
return result;
};
return Button;
}(_rectangle__WEBPACK_IMPORTED_MODULE_1__["Rectangle"]));
/***/ }),
/***/ "./2D/controls/checkbox.ts":
/*!*********************************!*\
!*** ./2D/controls/checkbox.ts ***!
\*********************************/
/*! exports provided: Checkbox */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Checkbox", function() { return Checkbox; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../../node_modules/tslib/tslib.es6.js");
/* harmony import */ var babylonjs_Misc_observable__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! babylonjs/Misc/observable */ "babylonjs/Misc/observable");
/* harmony import */ var babylonjs_Misc_observable__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(babylonjs_Misc_observable__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var _control__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./control */ "./2D/controls/control.ts");
/* harmony import */ var _stackPanel__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./stackPanel */ "./2D/controls/stackPanel.ts");
/* harmony import */ var _textBlock__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./textBlock */ "./2D/controls/textBlock.ts");
/**
* Class used to represent a 2D checkbox
*/
var Checkbox = /** @class */ (function (_super) {
tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](Checkbox, _super);
/**
* Creates a new CheckBox
* @param name defines the control name
*/
function Checkbox(name) {
var _this = _super.call(this, name) || this;
_this.name = name;
_this._isChecked = false;
_this._background = "black";
_this._checkSizeRatio = 0.8;
_this._thickness = 1;
/**
* Observable raised when isChecked property changes
*/
_this.onIsCheckedChangedObservable = new babylonjs_Misc_observable__WEBPACK_IMPORTED_MODULE_1__["Observable"]();
_this.isPointerBlocker = true;
return _this;
}
Object.defineProperty(Checkbox.prototype, "thickness", {
/** Gets or sets border thickness */
get: function () {
return this._thickness;
},
set: function (value) {
if (this._thickness === value) {
return;
}
this._thickness = value;
this._markAsDirty();
},
enumerable: true,
configurable: true
});
Object.defineProperty(Checkbox.prototype, "checkSizeRatio", {
/** Gets or sets a value indicating the ratio between overall size and check size */
get: function () {
return this._checkSizeRatio;
},
set: function (value) {
value = Math.max(Math.min(1, value), 0);
if (this._checkSizeRatio === value) {
return;
}
this._checkSizeRatio = value;
this._markAsDirty();
},
enumerable: true,
configurable: true
});
Object.defineProperty(Checkbox.prototype, "background", {
/** Gets or sets background color */
get: function () {
return this._background;
},
set: function (value) {
if (this._background === value) {
return;
}
this._background = value;
this._markAsDirty();
},
enumerable: true,
configurable: true
});
Object.defineProperty(Checkbox.prototype, "isChecked", {
/** Gets or sets a boolean indicating if the checkbox is checked or not */
get: function () {
return this._isChecked;
},
set: function (value) {
if (this._isChecked === value) {
return;
}
this._isChecked = value;
this._markAsDirty();
this.onIsCheckedChangedObservable.notifyObservers(value);
},
enumerable: true,
configurable: true
});
Checkbox.prototype._getTypeName = function () {
return "Checkbox";
};
/** @hidden */
Checkbox.prototype._draw = function (context) {
context.save();
this._applyStates(context);
var actualWidth = this._currentMeasure.width - this._thickness;
var actualHeight = this._currentMeasure.height - this._thickness;
if (this.shadowBlur || this.shadowOffsetX || this.shadowOffsetY) {
context.shadowColor = this.shadowColor;
context.shadowBlur = this.shadowBlur;
context.shadowOffsetX = this.shadowOffsetX;
context.shadowOffsetY = this.shadowOffsetY;
}
context.fillStyle = this._isEnabled ? this._background : this._disabledColor;
context.fillRect(this._currentMeasure.left + this._thickness / 2, this._currentMeasure.top + this._thickness / 2, actualWidth, actualHeight);
if (this.shadowBlur || this.shadowOffsetX || this.shadowOffsetY) {
context.shadowBlur = 0;
context.shadowOffsetX = 0;
context.shadowOffsetY = 0;
}
if (this._isChecked) {
context.fillStyle = this._isEnabled ? this.color : this._disabledColor;
var offsetWidth = actualWidth * this._checkSizeRatio;
var offseHeight = actualHeight * this._checkSizeRatio;
context.fillRect(this._currentMeasure.left + this._thickness / 2 + (actualWidth - offsetWidth) / 2, this._currentMeasure.top + this._thickness / 2 + (actualHeight - offseHeight) / 2, offsetWidth, offseHeight);
}
context.strokeStyle = this.color;
context.lineWidth = this._thickness;
context.strokeRect(this._currentMeasure.left + this._thickness / 2, this._currentMeasure.top + this._thickness / 2, actualWidth, actualHeight);
context.restore();
};
// Events
/** @hidden */
Checkbox.prototype._onPointerDown = function (target, coordinates, pointerId, buttonIndex) {
if (!_super.prototype._onPointerDown.call(this, target, coordinates, pointerId, buttonIndex)) {
return false;
}
this.isChecked = !this.isChecked;
return true;
};
/**
* Utility function to easily create a checkbox with a header
* @param title defines the label to use for the header
* @param onValueChanged defines the callback to call when value changes
* @returns a StackPanel containing the checkbox and a textBlock
*/
Checkbox.AddCheckBoxWithHeader = function (title, onValueChanged) {
var panel = new _stackPanel__WEBPACK_IMPORTED_MODULE_3__["StackPanel"]();
panel.isVertical = false;
panel.height = "30px";
var checkbox = new Checkbox();
checkbox.width = "20px";
checkbox.height = "20px";
checkbox.isChecked = true;
checkbox.color = "green";
checkbox.onIsCheckedChangedObservable.add(onValueChanged);
panel.addControl(checkbox);
var header = new _textBlock__WEBPACK_IMPORTED_MODULE_4__["TextBlock"]();
header.text = title;
header.width = "180px";
header.paddingLeft = "5px";
header.textHorizontalAlignment = _control__WEBPACK_IMPORTED_MODULE_2__["Control"].HORIZONTAL_ALIGNMENT_LEFT;
header.color = "white";
panel.addControl(header);
return panel;
};
return Checkbox;
}(_control__WEBPACK_IMPORTED_MODULE_2__["Control"]));
/***/ }),
/***/ "./2D/controls/colorpicker.ts":
/*!************************************!*\
!*** ./2D/controls/colorpicker.ts ***!
\************************************/
/*! exports provided: ColorPicker */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ColorPicker", function() { return ColorPicker; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../../node_modules/tslib/tslib.es6.js");
/* harmony import */ var babylonjs_Misc_observable__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! babylonjs/Misc/observable */ "babylonjs/Misc/observable");
/* harmony import */ var babylonjs_Misc_observable__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(babylonjs_Misc_observable__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var _control__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./control */ "./2D/controls/control.ts");
/* harmony import */ var _inputText__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./inputText */ "./2D/controls/inputText.ts");
/* harmony import */ var _rectangle__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./rectangle */ "./2D/controls/rectangle.ts");
/* harmony import */ var _button__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./button */ "./2D/controls/button.ts");
/* harmony import */ var _grid__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ./grid */ "./2D/controls/grid.ts");
/* harmony import */ var _controls_textBlock__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ../controls/textBlock */ "./2D/controls/textBlock.ts");
/** Class used to create color pickers */
var ColorPicker = /** @class */ (function (_super) {
tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](ColorPicker, _super);
/**
* Creates a new ColorPicker
* @param name defines the control name
*/
function ColorPicker(name) {
var _this = _super.call(this, name) || this;
_this.name = name;
_this._value = babylonjs_Misc_observable__WEBPACK_IMPORTED_MODULE_1__["Color3"].Red();
_this._tmpColor = new babylonjs_Misc_observable__WEBPACK_IMPORTED_MODULE_1__["Color3"]();
_this._pointerStartedOnSquare = false;
_this._pointerStartedOnWheel = false;
_this._squareLeft = 0;
_this._squareTop = 0;
_this._squareSize = 0;
_this._h = 360;
_this._s = 1;
_this._v = 1;
_this._lastPointerDownID = -1;
/**
* Observable raised when the value changes
*/
_this.onValueChangedObservable = new babylonjs_Misc_observable__WEBPACK_IMPORTED_MODULE_1__["Observable"]();
// Events
_this._pointerIsDown = false;
_this.value = new babylonjs_Misc_observable__WEBPACK_IMPORTED_MODULE_1__["Color3"](.88, .1, .1);
_this.size = "200px";
_this.isPointerBlocker = true;
return _this;
}
Object.defineProperty(ColorPicker.prototype, "value", {
/** Gets or sets the color of the color picker */
get: function () {
return this._value;
},
set: function (value) {
if (this._value.equals(value)) {
return;
}
this._value.copyFrom(value);
this._RGBtoHSV(this._value, this._tmpColor);
this._h = this._tmpColor.r;
this._s = Math.max(this._tmpColor.g, 0.00001);
this._v = Math.max(this._tmpColor.b, 0.00001);
this._markAsDirty();
if (this._value.r <= ColorPicker._Epsilon) {
this._value.r = 0;
}
if (this._value.g <= ColorPicker._Epsilon) {
this._value.g = 0;
}
if (this._value.b <= ColorPicker._Epsilon) {
this._value.b = 0;
}
if (this._value.r >= 1.0 - ColorPicker._Epsilon) {
this._value.r = 1.0;
}
if (this._value.g >= 1.0 - ColorPicker._Epsilon) {
this._value.g = 1.0;
}
if (this._value.b >= 1.0 - ColorPicker._Epsilon) {
this._value.b = 1.0;
}
this.onValueChangedObservable.notifyObservers(this._value);
},
enumerable: true,
configurable: true
});
Object.defineProperty(ColorPicker.prototype, "width", {
/**
* Gets or sets control width
* @see http://doc.babylonjs.com/how_to/gui#position-and-size
*/
get: function () {
return this._width.toString(this._host);
},
set: function (value) {
if (this._width.toString(this._host) === value) {
return;
}
if (this._width.fromString(value)) {
this._height.fromString(value);
this._markAsDirty();
}
},
enumerable: true,
configurable: true
});
Object.defineProperty(ColorPicker.prototype, "height", {
/**
* Gets or sets control height
* @see http://doc.babylonjs.com/how_to/gui#position-and-size
*/
get: function () {
return this._height.toString(this._host);
},
/** Gets or sets control height */
set: function (value) {
if (this._height.toString(this._host) === value) {
return;
}
if (this._height.fromString(value)) {
this._width.fromString(value);
this._markAsDirty();
}
},
enumerable: true,
configurable: true
});
Object.defineProperty(ColorPicker.prototype, "size", {
/** Gets or sets control size */
get: function () {
return this.width;
},
set: function (value) {
this.width = value;
},
enumerable: true,
configurable: true
});
ColorPicker.prototype._getTypeName = function () {
return "ColorPicker";
};
/** @hidden */
ColorPicker.prototype._preMeasure = function (parentMeasure, context) {
if (parentMeasure.width < parentMeasure.height) {
this._currentMeasure.height = parentMeasure.width;
}
else {
this._currentMeasure.width = parentMeasure.height;
}
};
ColorPicker.prototype._updateSquareProps = function () {
var radius = Math.min(this._currentMeasure.width, this._currentMeasure.height) * .5;
var wheelThickness = radius * .2;
var innerDiameter = (radius - wheelThickness) * 2;
var squareSize = innerDiameter / (Math.sqrt(2));
var offset = radius - squareSize * .5;
this._squareLeft = this._currentMeasure.left + offset;
this._squareTop = this._currentMeasure.top + offset;
this._squareSize = squareSize;
};
ColorPicker.prototype._drawGradientSquare = function (hueValue, left, top, width, height, context) {
var lgh = context.createLinearGradient(left, top, width + left, top);
lgh.addColorStop(0, '#fff');
lgh.addColorStop(1, 'hsl(' + hueValue + ', 100%, 50%)');
context.fillStyle = lgh;
context.fillRect(left, top, width, height);
var lgv = context.createLinearGradient(left, top, left, height + top);
lgv.addColorStop(0, 'rgba(0,0,0,0)');
lgv.addColorStop(1, '#000');
context.fillStyle = lgv;
context.fillRect(left, top, width, height);
};
ColorPicker.prototype._drawCircle = function (centerX, centerY, radius, context) {
context.beginPath();
context.arc(centerX, centerY, radius + 1, 0, 2 * Math.PI, false);
context.lineWidth = 3;
context.strokeStyle = '#333333';
context.stroke();
context.beginPath();
context.arc(centerX, centerY, radius, 0, 2 * Math.PI, false);
context.lineWidth = 3;
context.strokeStyle = '#ffffff';
context.stroke();
};
ColorPicker.prototype._createColorWheelCanvas = function (radius, thickness) {
var canvas = document.createElement("canvas");
canvas.width = radius * 2;
canvas.height = radius * 2;
var context = canvas.getContext("2d");
var image = context.getImageData(0, 0, radius * 2, radius * 2);
var data = image.data;
var color = this._tmpColor;
var maxDistSq = radius * radius;
var innerRadius = radius - thickness;
var minDistSq = innerRadius * innerRadius;
for (var x = -radius; x < radius; x++) {
for (var y = -radius; y < radius; y++) {
var distSq = x * x + y * y;
if (distSq > maxDistSq || distSq < minDistSq) {
continue;
}
var dist = Math.sqrt(distSq);
var ang = Math.atan2(y, x);
this._HSVtoRGB(ang * 180 / Math.PI + 180, dist / radius, 1, color);
var index = ((x + radius) + ((y + radius) * 2 * radius)) * 4;
data[index] = color.r * 255;
data[index + 1] = color.g * 255;
data[index + 2] = color.b * 255;
var alphaRatio = (dist - innerRadius) / (radius - innerRadius);
//apply less alpha to bigger color pickers
var alphaAmount = .2;
var maxAlpha = .2;
var minAlpha = .04;
var lowerRadius = 50;
var upperRadius = 150;
if (radius < lowerRadius) {
alphaAmount = maxAlpha;
}
else if (radius > upperRadius) {
alphaAmount = minAlpha;
}
else {
alphaAmount = (minAlpha - maxAlpha) * (radius - lowerRadius) / (upperRadius - lowerRadius) + maxAlpha;
}
var alphaRatio = (dist - innerRadius) / (radius - innerRadius);
if (alphaRatio < alphaAmount) {
data[index + 3] = 255 * (alphaRatio / alphaAmount);
}
else if (alphaRatio > 1 - alphaAmount) {
data[index + 3] = 255 * (1.0 - ((alphaRatio - (1 - alphaAmount)) / alphaAmount));
}
else {
data[index + 3] = 255;
}
}
}
context.putImageData(image, 0, 0);
return canvas;
};
ColorPicker.prototype._RGBtoHSV = function (color, result) {
var r = color.r;
var g = color.g;
var b = color.b;
var max = Math.max(r, g, b);
var min = Math.min(r, g, b);
var h = 0;
var s = 0;
var v = max;
var dm = max - min;
if (max !== 0) {
s = dm / max;
}
if (max != min) {
if (max == r) {
h = (g - b) / dm;
if (g < b) {
h += 6;
}
}
else if (max == g) {
h = (b - r) / dm + 2;
}
else if (max == b) {
h = (r - g) / dm + 4;
}
h *= 60;
}
result.r = h;
result.g = s;
result.b = v;
};
ColorPicker.prototype._HSVtoRGB = function (hue, saturation, value, result) {
var chroma = value * saturation;
var h = hue / 60;
var x = chroma * (1 - Math.abs((h % 2) - 1));
var r = 0;
var g = 0;
var b = 0;
if (h >= 0 && h <= 1) {
r = chroma;
g = x;
}
else if (h >= 1 && h <= 2) {
r = x;
g = chroma;
}
else if (h >= 2 && h <= 3) {
g = chroma;
b = x;
}
else if (h >= 3 && h <= 4) {
g = x;
b = chroma;
}
else if (h >= 4 && h <= 5) {
r = x;
b = chroma;
}
else if (h >= 5 && h <= 6) {
r = chroma;
b = x;
}
var m = value - chroma;
result.set((r + m), (g + m), (b + m));
};
/** @hidden */
ColorPicker.prototype._draw = function (context) {
context.save();
this._applyStates(context);
var radius = Math.min(this._currentMeasure.width, this._currentMeasure.height) * .5;
var wheelThickness = radius * .2;
var left = this._currentMeasure.left;
var top = this._currentMeasure.top;
if (!this._colorWheelCanvas || this._colorWheelCanvas.width != radius * 2) {
this._colorWheelCanvas = this._createColorWheelCanvas(radius, wheelThickness);
}
this._updateSquareProps();
if (this.shadowBlur || this.shadowOffsetX || this.shadowOffsetY) {
context.shadowColor = this.shadowColor;
context.shadowBlur = this.shadowBlur;
context.shadowOffsetX = this.shadowOffsetX;
context.shadowOffsetY = this.shadowOffsetY;
context.fillRect(this._squareLeft, this._squareTop, this._squareSize, this._squareSize);
}
context.drawImage(this._colorWheelCanvas, left, top);
if (this.shadowBlur || this.shadowOffsetX || this.shadowOffsetY) {
context.shadowBlur = 0;
context.shadowOffsetX = 0;
context.shadowOffsetY = 0;
}
this._drawGradientSquare(this._h, this._squareLeft, this._squareTop, this._squareSize, this._squareSize, context);
var cx = this._squareLeft + this._squareSize * this._s;
var cy = this._squareTop + this._squareSize * (1 - this._v);
this._drawCircle(cx, cy, radius * .04, context);
var dist = radius - wheelThickness * .5;
cx = left + radius + Math.cos((this._h - 180) * Math.PI / 180) * dist;
cy = top + radius + Math.sin((this._h - 180) * Math.PI / 180) * dist;
this._drawCircle(cx, cy, wheelThickness * .35, context);
context.restore();
};
ColorPicker.prototype._updateValueFromPointer = function (x, y) {
if (this._pointerStartedOnWheel) {
var radius = Math.min(this._currentMeasure.width, this._currentMeasure.height) * .5;
var centerX = radius + this._currentMeasure.left;
var centerY = radius + this._currentMeasure.top;
this._h = Math.atan2(y - centerY, x - centerX) * 180 / Math.PI + 180;
}
else if (this._pointerStartedOnSquare) {
this._updateSquareProps();
this._s = (x - this._squareLeft) / this._squareSize;
this._v = 1 - (y - this._squareTop) / this._squareSize;
this._s = Math.min(this._s, 1);
this._s = Math.max(this._s, ColorPicker._Epsilon);
this._v = Math.min(this._v, 1);
this._v = Math.max(this._v, ColorPicker._Epsilon);
}
this._HSVtoRGB(this._h, this._s, this._v, this._tmpColor);
this.value = this._tmpColor;
};
ColorPicker.prototype._isPointOnSquare = function (x, y) {
this._updateSquareProps();
var left = this._squareLeft;
var top = this._squareTop;
var size = this._squareSize;
if (x >= left && x <= left + size &&
y >= top && y <= top + size) {
return true;
}
return false;
};
ColorPicker.prototype._isPointOnWheel = function (x, y) {
var radius = Math.min(this._currentMeasure.width, this._currentMeasure.height) * .5;
var centerX = radius + this._currentMeasure.left;
var centerY = radius + this._currentMeasure.top;
var wheelThickness = radius * .2;
var innerRadius = radius - wheelThickness;
var radiusSq = radius * radius;
var innerRadiusSq = innerRadius * innerRadius;
var dx = x - centerX;
var dy = y - centerY;
var distSq = dx * dx + dy * dy;
if (distSq <= radiusSq && distSq >= innerRadiusSq) {
return true;
}
return false;
};
ColorPicker.prototype._onPointerDown = function (target, coordinates, pointerId, buttonIndex) {
if (!_super.prototype._onPointerDown.call(this, target, coordinates, pointerId, buttonIndex)) {
return false;
}
this._pointerIsDown = true;
this._pointerStartedOnSquare = false;
this._pointerStartedOnWheel = false;
// Invert transform
this._invertTransformMatrix.transformCoordinates(coordinates.x, coordinates.y, this._transformedPosition);
var x = this._transformedPosition.x;
var y = this._transformedPosition.y;
if (this._isPointOnSquare(x, y)) {
this._pointerStartedOnSquare = true;
}
else if (this._isPointOnWheel(x, y)) {
this._pointerStartedOnWheel = true;
}
this._updateValueFromPointer(x, y);
this._host._capturingControl[pointerId] = this;
this._lastPointerDownID = pointerId;
return true;
};
ColorPicker.prototype._onPointerMove = function (target, coordinates, pointerId) {
// Only listen to pointer move events coming from the last pointer to click on the element (To support dual vr controller interaction)
if (pointerId != this._lastPointerDownID) {
return;
}
// Invert transform
this._invertTransformMatrix.transformCoordinates(coordinates.x, coordinates.y, this._transformedPosition);
var x = this._transformedPosition.x;
var y = this._transformedPosition.y;
if (this._pointerIsDown) {
this._updateValueFromPointer(x, y);
}
_super.prototype._onPointerMove.call(this, target, coordinates, pointerId);
};
ColorPicker.prototype._onPointerUp = function (target, coordinates, pointerId, buttonIndex, notifyClick) {
this._pointerIsDown = false;
delete this._host._capturingControl[pointerId];
_super.prototype._onPointerUp.call(this, target, coordinates, pointerId, buttonIndex, notifyClick);
};
/**
* This function expands the color picker by creating a color picker dialog with manual
* color value input and the ability to save colors into an array to be used later in
* subsequent launches of the dialogue.
* @param advancedTexture defines the AdvancedDynamicTexture the dialog is assigned to
* @param options defines size for dialog and options for saved colors. Also accepts last color picked as hex string and saved colors array as hex strings.
* @returns picked color as a hex string and the saved colors array as hex strings.
*/
ColorPicker.ShowPickerDialogAsync = function (advancedTexture, options) {
return new Promise(function (resolve, reject) {
// Default options
options.pickerWidth = options.pickerWidth || "640px";
options.pickerHeight = options.pickerHeight || "400px";
options.headerHeight = options.headerHeight || "35px";
options.lastColor = options.lastColor || "#000000";
options.swatchLimit = options.swatchLimit || 20;
options.numSwatchesPerLine = options.numSwatchesPerLine || 10;
// Window size settings
var drawerMaxRows = options.swatchLimit / options.numSwatchesPerLine;
var rawSwatchSize = parseFloat(options.pickerWidth) / options.numSwatchesPerLine;
var gutterSize = Math.floor(rawSwatchSize * 0.25);
var colGutters = gutterSize * (options.numSwatchesPerLine + 1);
var swatchSize = Math.floor((parseFloat(options.pickerWidth) - colGutters) / options.numSwatchesPerLine);
var drawerMaxSize = (swatchSize * drawerMaxRows) + (gutterSize * (drawerMaxRows + 1));
var containerSize = (parseInt(options.pickerHeight) + drawerMaxSize + Math.floor(swatchSize * 0.25)).toString() + "px";
// Button Colors
var buttonColor = "#c0c0c0";
var buttonBackgroundColor = "#535353";
var buttonBackgroundHoverColor = "#414141";
var buttonBackgroundClickColor = "515151";
var buttonDisabledColor = "#555555";
var buttonDisabledBackgroundColor = "#454545";
var currentSwatchesOutlineColor = "#404040";
var luminanceLimitColor = babylonjs_Misc_observable__WEBPACK_IMPORTED_MODULE_1__["Color3"].FromHexString("#dddddd");
var luminanceLimit = luminanceLimitColor.r + luminanceLimitColor.g + luminanceLimitColor.b;
var iconColorDark = "#aaaaaa";
var iconColorLight = "#ffffff";
var closeIconColor;
// Button settings
var buttonFontSize;
var butEdit;
var buttonWidth;
var buttonHeight;
// Input Text Colors
var inputFieldLabels = ["R", "G", "B"];
var inputTextBackgroundColor = "#454545";
var inputTextColor = "#f0f0f0";
// This is the current color as set by either the picker or by entering a value
var currentColor;
// This int is used for naming swatches and serves as the index for calling them from the list
var swatchNumber;
// Menu Panel options. We need to know if the swatchDrawer exists so we can create it if needed.
var swatchDrawer;
var editSwatchMode = false;
// Color InputText fields that will be updated upon value change
var picker;
var rValInt;
var gValInt;
var bValInt;
var rValDec;
var gValDec;
var bValDec;
var hexVal;
var newSwatch;
var lastVal;
var activeField;
/**
* Will update all values for InputText and ColorPicker controls based on the BABYLON.Color3 passed to this function.
* Each InputText control and the ColorPicker control will be tested to see if they are the activeField and if they
* are will receive no update. This is to prevent the input from the user being overwritten.
*/
function updateValues(value, inputField) {
activeField = inputField;
var pickedColor = value.toHexString();
newSwatch.background = pickedColor;
if (rValInt.name != activeField) {
rValInt.text = Math.floor(value.r * 255).toString();
}
if (gValInt.name != activeField) {
gValInt.text = Math.floor(value.g * 255).toString();
}
if (bValInt.name != activeField) {
bValInt.text = Math.floor(value.b * 255).toString();
}
if (rValDec.name != activeField) {
rValDec.text = value.r.toString();
}
if (gValDec.name != activeField) {
gValDec.text = value.g.toString();
}
if (bValDec.name != activeField) {
bValDec.text = value.b.toString();
}
if (hexVal.name != activeField) {
var minusPound = pickedColor.split("#");
hexVal.text = minusPound[1];
}
if (picker.name != activeField) {
picker.value = value;
}
}
// When the user enters an integer for R, G, or B we check to make sure it is a valid number and replace if not.
function updateInt(field, channel) {
var newValue = field.text;
var checkVal = /[^0-9]/g.test(newValue);
if (checkVal) {
field.text = lastVal;
return;
}
else {
if (newValue != "") {
if (Math.floor(parseInt(newValue)) < 0) {
newValue = "0";
}
else if (Math.floor(parseInt(newValue)) > 255) {
newValue = "255";
}
else if (isNaN(parseInt(newValue))) {
newValue = "0";
}
}
if (activeField == field.name) {
lastVal = newValue;
}
}
if (newValue != "") {
newValue = parseInt(newValue).toString();
field.text = newValue;
var newSwatchRGB = babylonjs_Misc_observable__WEBPACK_IMPORTED_MODULE_1__["Color3"].FromHexString(newSwatch.background);
if (activeField == field.name) {
if (channel == "r") {
updateValues(new babylonjs_Misc_observable__WEBPACK_IMPORTED_MODULE_1__["Color3"]((parseInt(newValue)) / 255, newSwatchRGB.g, newSwatchRGB.b), field.name);
}
else if (channel == "g") {
updateValues(new babylonjs_Misc_observable__WEBPACK_IMPORTED_MODULE_1__["Color3"](newSwatchRGB.r, (parseInt(newValue)) / 255, newSwatchRGB.b), field.name);
}
else {
updateValues(new babylonjs_Misc_observable__WEBPACK_IMPORTED_MODULE_1__["Color3"](newSwatchRGB.r, newSwatchRGB.g, (parseInt(newValue)) / 255), field.name);
}
}
}
}
// When the user enters a float for R, G, or B we check to make sure it is a valid number and replace if not.
function updateFloat(field, channel) {
var newValue = field.text;
var checkVal = /[^0-9\.]/g.test(newValue);
if (checkVal) {
field.text = lastVal;
return;
}
else {
if (newValue != "" && newValue != "." && parseFloat(newValue) != 0) {
if (parseFloat(newValue) < 0.0) {
newValue = "0.0";
}
else if (parseFloat(newValue) > 1.0) {
newValue = "1.0";
}
else if (isNaN(parseFloat(newValue))) {
newValue = "0.0";
}
}
if (activeField == field.name) {
lastVal = newValue;
}
}
if (newValue != "" && newValue != "." && parseFloat(newValue) != 0) {
newValue = parseFloat(newValue).toString();
field.text = newValue;
}
else {
newValue = "0.0";
}
var newSwatchRGB = babylonjs_Misc_observable__WEBPACK_IMPORTED_MODULE_1__["Color3"].FromHexString(newSwatch.background);
if (activeField == field.name) {
if (channel == "r") {
updateValues(new babylonjs_Misc_observable__WEBPACK_IMPORTED_MODULE_1__["Color3"](parseFloat(newValue), newSwatchRGB.g, newSwatchRGB.b), field.name);
}
else if (channel == "g") {
updateValues(new babylonjs_Misc_observable__WEBPACK_IMPORTED_MODULE_1__["Color3"](newSwatchRGB.r, parseFloat(newValue), newSwatchRGB.b), field.name);
}
else {
updateValues(new babylonjs_Misc_observable__WEBPACK_IMPORTED_MODULE_1__["Color3"](newSwatchRGB.r, newSwatchRGB.g, parseFloat(newValue)), field.name);
}
}
}
// Removes the current index from the savedColors array. Drawer can then be regenerated.
function deleteSwatch(index) {
if (options.savedColors) {
options.savedColors.splice(index, 1);
}
if (options.savedColors && options.savedColors.length == 0) {
setEditButtonVisibility(false);
editSwatchMode = false;
}
}
// Creates and styles an individual swatch when updateSwatches is called.
function createSwatch() {
if (options.savedColors && options.savedColors[swatchNumber]) {
if (editSwatchMode) {
var icon = "b";
}
else {
var icon = "";
}
var swatch = _button__WEBPACK_IMPORTED_MODULE_5__["Button"].CreateSimpleButton("Swatch_" + swatchNumber, icon);
swatch.fontFamily = "BabylonJSglyphs";
var swatchColor = babylonjs_Misc_observable__WEBPACK_IMPORTED_MODULE_1__["Color3"].FromHexString(options.savedColors[swatchNumber]);
var swatchLuminence = swatchColor.r + swatchColor.g + swatchColor.b;
// Set color of outline and textBlock based on luminance of the color swatch so feedback always visible
if (swatchLuminence > luminanceLimit) {
swatch.color = iconColorDark;
}
else {
swatch.color = iconColorLight;
}
swatch.fontSize = Math.floor(swatchSize * 0.7);
swatch.textBlock.verticalAlignment = _control__WEBPACK_IMPORTED_MODULE_2__["Control"].VERTICAL_ALIGNMENT_CENTER;
swatch.height = swatch.width = (swatchSize).toString() + "px";
swatch.background = options.savedColors[swatchNumber];
swatch.thickness = 2;
var metadata_1 = swatchNumber;
swatch.pointerDownAnimation = function () {
swatch.thickness = 4;
};
swatch.pointerUpAnimation = function () {
swatch.thickness = 3;
};
swatch.pointerEnterAnimation = function () {
swatch.thickness = 3;
};
swatch.pointerOutAnimation = function () {
swatch.thickness = 2;
};
swatch.onPointerClickObservable.add(function () {
if (!editSwatchMode) {
if (options.savedColors) {
updateValues(babylonjs_Misc_observable__WEBPACK_IMPORTED_MODULE_1__["Color3"].FromHexString(options.savedColors[metadata_1]), swatch.name);
}
}
else {
deleteSwatch(metadata_1);
updateSwatches("", butSave);
}
});
return swatch;
}
else {
return null;
}
}
// Mode switch to render button text and close symbols on swatch controls
function editSwatches(mode) {
if (mode !== undefined) {
editSwatchMode = mode;
}
if (editSwatchMode) {
for (var i = 0; i < swatchDrawer.children.length; i++) {
var thisButton = swatchDrawer.children[i];
thisButton.textBlock.text = "b";
}
if (butEdit !== undefined) {
butEdit.textBlock.text = "Done";
}
}
else {
for (var i = 0; i < swatchDrawer.children.length; i++) {
var thisButton = swatchDrawer.children[i];
thisButton.textBlock.text = "";
}
if (butEdit !== undefined) {
butEdit.textBlock.text = "Edit";
}
}
}
/**
* When Save Color button is pressed this function will first create a swatch drawer if one is not already
* made. Then all controls are removed from the drawer and we step through the savedColors array and
* creates one swatch per color. It will also set the height of the drawer control based on how many
* saved colors there are and how many can be stored per row.
*/
function updateSwatches(color, button) {
if (options.savedColors) {
if (color != "") {
options.savedColors.push(color);
}
swatchNumber = 0;
swatchDrawer.clearControls();
var rowCount = Math.ceil(options.savedColors.length / options.numSwatchesPerLine);
if (rowCount == 0) {
var gutterCount = 0;
}
else {
var gutterCount = rowCount + 1;
}
if (swatchDrawer.rowCount != rowCount + gutterCount) {
var currentRows = swatchDrawer.rowCount;
for (var i = 0; i < currentRows; i++) {
swatchDrawer.removeRowDefinition(0);
}
for (var i = 0; i < rowCount + gutterCount; i++) {
if (i % 2) {
swatchDrawer.addRowDefinition(swatchSize, true);
}
else {
swatchDrawer.addRowDefinition(gutterSize, true);
}
}
}
swatchDrawer.height = ((swatchSize * rowCount) + (gutterCount * gutterSize)).toString() + "px";
for (var y = 1, thisRow = 1; y < rowCount + gutterCount; y += 2, thisRow++) {
// Determine number of buttons to create per row based on the button limit per row and number of saved colors
if (options.savedColors.length > thisRow * options.numSwatchesPerLine) {
var totalButtonsThisRow = options.numSwatchesPerLine;
}
else {
var totalButtonsThisRow = options.savedColors.length - ((thisRow - 1) * options.numSwatchesPerLine);
}
var buttonIterations = (Math.min(Math.max(totalButtonsThisRow, 0), options.numSwatchesPerLine));
for (var x = 0, w = 1; x < buttonIterations; x++) {
if (x > options.numSwatchesPerLine) {
continue;
}
var swatch = createSwatch();
if (swatch != null) {
swatchDrawer.addControl(swatch, y, w);
w += 2;
swatchNumber++;
}
else {
continue;
}
}
}
if (options.savedColors.length >= options.swatchLimit) {
disableButton(button, true);
}
else {
disableButton(button, false);
}
}
}
// Shows or hides edit swatches button depending on if there are saved swatches
function setEditButtonVisibility(enableButton) {
if (enableButton) {
butEdit = _button__WEBPACK_IMPORTED_MODULE_5__["Button"].CreateSimpleButton("butEdit", "Edit");
butEdit.width = buttonWidth;
butEdit.height = buttonHeight;
butEdit.left = (Math.floor(parseInt(buttonWidth) * 0.1)).toString() + "px";
butEdit.top = (parseFloat(butEdit.left) * -1).toString() + "px";
butEdit.verticalAlignment = _control__WEBPACK_IMPORTED_MODULE_2__["Control"].VERTICAL_ALIGNMENT_BOTTOM;
butEdit.horizontalAlignment = _control__WEBPACK_IMPORTED_MODULE_2__["Control"].HORIZONTAL_ALIGNMENT_LEFT;
butEdit.thickness = 2;
butEdit.color = buttonColor;
butEdit.fontSize = buttonFontSize;
butEdit.background = buttonBackgroundColor;
butEdit.onPointerEnterObservable.add(function () {
butEdit.background = buttonBackgroundHoverColor;
});
butEdit.onPointerOutObservable.add(function () {
butEdit.background = buttonBackgroundColor;
});
butEdit.pointerDownAnimation = function () {
butEdit.background = buttonBackgroundClickColor;
};
butEdit.pointerUpAnimation = function () {
butEdit.background = buttonBackgroundHoverColor;
};
butEdit.onPointerClickObservable.add(function () {
if (editSwatchMode) {
editSwatchMode = false;
}
else {
editSwatchMode = true;
}
editSwatches();
});
pickerGrid.addControl(butEdit, 1, 0);
}
else {
pickerGrid.removeControl(butEdit);
}
}
// Called when the user hits the limit of saved colors in the drawer.
function disableButton(button, disabled) {
if (disabled) {
button.color = buttonDisabledColor;
button.background = buttonDisabledBackgroundColor;
}
else {
button.color = buttonColor;
button.background = buttonBackgroundColor;
}
}
// Passes last chosen color back to scene and kills dialog by removing from AdvancedDynamicTexture
function closePicker(color) {
if (options.savedColors && options.savedColors.length > 0) {
resolve({
savedColors: options.savedColors,
pickedColor: color
});
}
else {
resolve({
pickedColor: color
});
}
advancedTexture.removeControl(dialogContainer);
}
// Dialogue menu container which will contain both the main dialogue window and the swatch drawer which opens once a color is saved.
var dialogContainer = new _grid__WEBPACK_IMPORTED_MODULE_6__["Grid"]();
dialogContainer.name = "Dialog Container";
dialogContainer.width = options.pickerWidth;
if (options.savedColors) {
dialogContainer.height = containerSize;
var topRow = parseInt(options.pickerHeight) / parseInt(containerSize);
dialogContainer.addRowDefinition(topRow, false);
dialogContainer.addRowDefinition(1.0 - topRow, false);
}
else {
dialogContainer.height = options.pickerHeight;
dialogContainer.addRowDefinition(1.0, false);
}
advancedTexture.addControl(dialogContainer);
// Swatch drawer which contains all saved color buttons
if (options.savedColors) {
swatchDrawer = new _grid__WEBPACK_IMPORTED_MODULE_6__["Grid"]();
swatchDrawer.name = "Swatch Drawer";
swatchDrawer.verticalAlignment = _control__WEBPACK_IMPORTED_MODULE_2__["Control"].VERTICAL_ALIGNMENT_TOP;
swatchDrawer.background = buttonBackgroundColor;
swatchDrawer.width = options.pickerWidth;
var initialRows = options.savedColors.length / options.numSwatchesPerLine;
if (initialRows == 0) {
var gutterCount = 0;
}
else {
var gutterCount = initialRows + 1;
}
swatchDrawer.height = ((swatchSize * initialRows) + (gutterCount * gutterSize)).toString() + "px";
swatchDrawer.top = Math.floor(swatchSize * 0.25).toString() + "px";
for (var i = 0; i < (Math.ceil(options.savedColors.length / options.numSwatchesPerLine) * 2) + 1; i++) {
if (i % 2 != 0) {
swatchDrawer.addRowDefinition(swatchSize, true);
}
else {
swatchDrawer.addRowDefinition(gutterSize, true);
}
}
for (var i = 0; i < options.numSwatchesPerLine * 2 + 1; i++) {
if (i % 2 != 0) {
swatchDrawer.addColumnDefinition(swatchSize, true);
}
else {
swatchDrawer.addColumnDefinition(gutterSize, true);
}
}
dialogContainer.addControl(swatchDrawer, 1, 0);
}
// Picker container
var pickerPanel = new _grid__WEBPACK_IMPORTED_MODULE_6__["Grid"]();
pickerPanel.name = "Picker Panel";
pickerPanel.height = options.pickerHeight;
var panelHead = parseInt(options.headerHeight) / parseInt(options.pickerHeight);
var pickerPanelRows = [panelHead, 1.0 - panelHead];
pickerPanel.addRowDefinition(pickerPanelRows[0], false);
pickerPanel.addRowDefinition(pickerPanelRows[1], false);
dialogContainer.addControl(pickerPanel, 0, 0);
// Picker container header
var header = new _rectangle__WEBPACK_IMPORTED_MODULE_4__["Rectangle"]();
header.name = "Dialogue Header Bar";
header.background = "#cccccc";
header.thickness = 0;
pickerPanel.addControl(header, 0, 0);
// Header close button
var closeButton = _button__WEBPACK_IMPORTED_MODULE_5__["Button"].CreateSimpleButton("closeButton", "a");
closeButton.fontFamily = "BabylonJSglyphs";
var headerColor3 = babylonjs_Misc_observable__WEBPACK_IMPORTED_MODULE_1__["Color3"].FromHexString(header.background);
closeIconColor = new babylonjs_Misc_observable__WEBPACK_IMPORTED_MODULE_1__["Color3"](1.0 - headerColor3.r, 1.0 - headerColor3.g, 1.0 - headerColor3.b);
closeButton.color = closeIconColor.toHexString();
closeButton.fontSize = Math.floor(parseInt(options.headerHeight) * 0.6);
closeButton.textBlock.textVerticalAlignment = _control__WEBPACK_IMPORTED_MODULE_2__["Control"].VERTICAL_ALIGNMENT_CENTER;
closeButton.horizontalAlignment = _control__WEBPACK_IMPORTED_MODULE_2__["Control"].HORIZONTAL_ALIGNMENT_RIGHT;
closeButton.height = closeButton.width = options.headerHeight;
closeButton.background = header.background;
closeButton.thickness = 0;
closeButton.pointerDownAnimation = function () {
};
closeButton.pointerUpAnimation = function () {
closeButton.background = header.background;
};
closeButton.pointerEnterAnimation = function () {
closeButton.color = header.background;
closeButton.background = "red";
};
closeButton.pointerOutAnimation = function () {
closeButton.color = closeIconColor.toHexString();
closeButton.background = header.background;
};
closeButton.onPointerClickObservable.add(function () {
closePicker(currentSwatch.background);
});
pickerPanel.addControl(closeButton, 0, 0);
// Dialog container body
var dialogBody = new _grid__WEBPACK_IMPORTED_MODULE_6__["Grid"]();
dialogBody.name = "Dialogue Body";
dialogBody.background = buttonBackgroundColor;
var dialogBodyCols = [0.4375, 0.5625];
dialogBody.addRowDefinition(1.0, false);
dialogBody.addColumnDefinition(dialogBodyCols[0], false);
dialogBody.addColumnDefinition(dialogBodyCols[1], false);
pickerPanel.addControl(dialogBody, 1, 0);
// Picker grid
var pickerGrid = new _grid__WEBPACK_IMPORTED_MODULE_6__["Grid"]();
pickerGrid.name = "Picker Grid";
pickerGrid.addRowDefinition(0.85, false);
pickerGrid.addRowDefinition(0.15, false);
dialogBody.addControl(pickerGrid, 0, 0);
// Picker control
picker = new ColorPicker();
picker.name = "GUI Color Picker";
if (options.pickerHeight < options.pickerWidth) {
picker.width = 0.89;
}
else {
picker.height = 0.89;
}
picker.value = babylonjs_Misc_observable__WEBPACK_IMPORTED_MODULE_1__["Color3"].FromHexString(options.lastColor);
picker.horizontalAlignment = _control__WEBPACK_IMPORTED_MODULE_2__["Control"].HORIZONTAL_ALIGNMENT_CENTER;
picker.verticalAlignment = _control__WEBPACK_IMPORTED_MODULE_2__["Control"].VERTICAL_ALIGNMENT_CENTER;
picker.onPointerDownObservable.add(function () {
activeField = picker.name;
lastVal = "";
editSwatches(false);
});
picker.onValueChangedObservable.add(function (value) {
if (activeField == picker.name) {
updateValues(value, picker.name);
}
});
pickerGrid.addControl(picker, 0, 0);
// Picker body right quarant
var pickerBodyRight = new _grid__WEBPACK_IMPORTED_MODULE_6__["Grid"]();
pickerBodyRight.name = "Dialogue Right Half";
pickerBodyRight.horizontalAlignment = _control__WEBPACK_IMPORTED_MODULE_2__["Control"].HORIZONTAL_ALIGNMENT_LEFT;
var pickerBodyRightRows = [0.514, 0.486];
pickerBodyRight.addRowDefinition(pickerBodyRightRows[0], false);
pickerBodyRight.addRowDefinition(pickerBodyRightRows[1], false);
dialogBody.addControl(pickerBodyRight, 1, 1);
// Picker container swatches and buttons
var pickerSwatchesButtons = new _grid__WEBPACK_IMPORTED_MODULE_6__["Grid"]();
pickerSwatchesButtons.name = "Swatches and Buttons";
var pickerButtonsCol = [0.417, 0.583];
pickerSwatchesButtons.addRowDefinition(1.0, false);
pickerSwatchesButtons.addColumnDefinition(pickerButtonsCol[0], false);
pickerSwatchesButtons.addColumnDefinition(pickerButtonsCol[1], false);
pickerBodyRight.addControl(pickerSwatchesButtons, 0, 0);
// Picker Swatches quadrant
var pickerSwatches = new _grid__WEBPACK_IMPORTED_MODULE_6__["Grid"]();
pickerSwatches.name = "New and Current Swatches";
var pickeSwatchesRows = [0.04, 0.16, 0.64, 0.16];
pickerSwatches.addRowDefinition(pickeSwatchesRows[0], false);
pickerSwatches.addRowDefinition(pickeSwatchesRows[1], false);
pickerSwatches.addRowDefinition(pickeSwatchesRows[2], false);
pickerSwatches.addRowDefinition(pickeSwatchesRows[3], false);
pickerSwatchesButtons.addControl(pickerSwatches, 0, 0);
// Active swatches
var activeSwatches = new _grid__WEBPACK_IMPORTED_MODULE_6__["Grid"]();
activeSwatches.name = "Active Swatches";
activeSwatches.width = 0.67;
activeSwatches.addRowDefinition(0.5, false);
activeSwatches.addRowDefinition(0.5, false);
pickerSwatches.addControl(activeSwatches, 2, 0);
var labelWidth = (Math.floor(parseInt(options.pickerWidth) * dialogBodyCols[1] * pickerButtonsCol[0] * 0.11));
var labelHeight = (Math.floor(parseInt(options.pickerHeight) * pickerPanelRows[1] * pickerBodyRightRows[0] * pickeSwatchesRows[1] * 0.5));
if (options.pickerWidth > options.pickerHeight) {
var labelTextSize = labelHeight;
}
else {
var labelTextSize = labelWidth;
}
// New color swatch and previous color button
var newText = new _controls_textBlock__WEBPACK_IMPORTED_MODULE_7__["TextBlock"]();
newText.text = "new";
newText.name = "New Color Label";
newText.color = buttonColor;
newText.fontSize = labelTextSize;
pickerSwatches.addControl(newText, 1, 0);
newSwatch = new _rectangle__WEBPACK_IMPORTED_MODULE_4__["Rectangle"]();
newSwatch.name = "New Color Swatch";
newSwatch.background = options.lastColor;
newSwatch.thickness = 0;
activeSwatches.addControl(newSwatch, 0, 0);
var currentSwatch = _button__WEBPACK_IMPORTED_MODULE_5__["Button"].CreateSimpleButton("currentSwatch", "");
currentSwatch.background = options.lastColor;
currentSwatch.thickness = 0;
currentSwatch.onPointerClickObservable.add(function () {
var revertColor = babylonjs_Misc_observable__WEBPACK_IMPORTED_MODULE_1__["Color3"].FromHexString(currentSwatch.background);
updateValues(revertColor, currentSwatch.name);
editSwatches(false);
});
currentSwatch.pointerDownAnimation = function () { };
currentSwatch.pointerUpAnimation = function () { };
currentSwatch.pointerEnterAnimation = function () { };
currentSwatch.pointerOutAnimation = function () { };
activeSwatches.addControl(currentSwatch, 1, 0);
var swatchOutline = new _rectangle__WEBPACK_IMPORTED_MODULE_4__["Rectangle"]();
swatchOutline.name = "Swatch Outline";
swatchOutline.width = 0.67;
swatchOutline.thickness = 2;
swatchOutline.color = currentSwatchesOutlineColor;
swatchOutline.isHitTestVisible = false;
pickerSwatches.addControl(swatchOutline, 2, 0);
var currentText = new _controls_textBlock__WEBPACK_IMPORTED_MODULE_7__["TextBlock"]();
currentText.name = "Current Color Label";
currentText.text = "current";
currentText.color = buttonColor;
currentText.fontSize = labelTextSize;
pickerSwatches.addControl(currentText, 3, 0);
// Buttons grid
var buttonGrid = new _grid__WEBPACK_IMPORTED_MODULE_6__["Grid"]();
buttonGrid.name = "Button Grid";
buttonGrid.height = 0.8;
var buttonGridRows = 1 / 3;
buttonGrid.addRowDefinition(buttonGridRows, false);
buttonGrid.addRowDefinition(buttonGridRows, false);
buttonGrid.addRowDefinition(buttonGridRows, false);
pickerSwatchesButtons.addControl(buttonGrid, 0, 1);
// Determine pixel width and height for all buttons from overall panel dimensions
buttonWidth = (Math.floor(parseInt(options.pickerWidth) * dialogBodyCols[1] * pickerButtonsCol[1] * 0.67)).toString() + "px";
buttonHeight = (Math.floor(parseInt(options.pickerHeight) * pickerPanelRows[1] * pickerBodyRightRows[0] * (parseFloat(buttonGrid.height.toString()) / 100) * buttonGridRows * 0.7)).toString() + "px";
// Determine button type size
if (parseFloat(buttonWidth) > parseFloat(buttonHeight)) {
buttonFontSize = Math.floor(parseFloat(buttonHeight) * 0.45);
}
else {
buttonFontSize = Math.floor(parseFloat(buttonWidth) * 0.11);
}
// Panel Buttons
var butOK = _button__WEBPACK_IMPORTED_MODULE_5__["Button"].CreateSimpleButton("butOK", "OK");
butOK.width = buttonWidth;
butOK.height = buttonHeight;
butOK.verticalAlignment = _control__WEBPACK_IMPORTED_MODULE_2__["Control"].VERTICAL_ALIGNMENT_CENTER;
butOK.thickness = 2;
butOK.color = buttonColor;
butOK.fontSize = buttonFontSize;
butOK.background = buttonBackgroundColor;
butOK.onPointerEnterObservable.add(function () { butOK.background = buttonBackgroundHoverColor; });
butOK.onPointerOutObservable.add(function () { butOK.background = buttonBackgroundColor; });
butOK.pointerDownAnimation = function () {
butOK.background = buttonBackgroundClickColor;
};
butOK.pointerUpAnimation = function () {
butOK.background = buttonBackgroundHoverColor;
};
butOK.onPointerClickObservable.add(function () {
editSwatches(false);
closePicker(newSwatch.background);
});
buttonGrid.addControl(butOK, 0, 0);
var butCancel = _button__WEBPACK_IMPORTED_MODULE_5__["Button"].CreateSimpleButton("butCancel", "Cancel");
butCancel.width = buttonWidth;
butCancel.height = buttonHeight;
butCancel.verticalAlignment = _control__WEBPACK_IMPORTED_MODULE_2__["Control"].VERTICAL_ALIGNMENT_CENTER;
butCancel.thickness = 2;
butCancel.color = buttonColor;
butCancel.fontSize = buttonFontSize;
butCancel.background = buttonBackgroundColor;
butCancel.onPointerEnterObservable.add(function () { butCancel.background = buttonBackgroundHoverColor; });
butCancel.onPointerOutObservable.add(function () { butCancel.background = buttonBackgroundColor; });
butCancel.pointerDownAnimation = function () {
butCancel.background = buttonBackgroundClickColor;
};
butCancel.pointerUpAnimation = function () {
butCancel.background = buttonBackgroundHoverColor;
};
butCancel.onPointerClickObservable.add(function () {
editSwatches(false);
closePicker(currentSwatch.background);
});
buttonGrid.addControl(butCancel, 1, 0);
if (options.savedColors) {
var butSave = _button__WEBPACK_IMPORTED_MODULE_5__["Button"].CreateSimpleButton("butSave", "Save");
butSave.width = buttonWidth;
butSave.height = buttonHeight;
butSave.verticalAlignment = _control__WEBPACK_IMPORTED_MODULE_2__["Control"].VERTICAL_ALIGNMENT_CENTER;
butSave.thickness = 2;
butSave.fontSize = buttonFontSize;
if (options.savedColors.length < options.swatchLimit) {
butSave.color = buttonColor;
butSave.background = buttonBackgroundColor;
}
else {
disableButton(butSave, true);
}
butSave.onPointerEnterObservable.add(function () {
if (options.savedColors) {
if (options.savedColors.length < options.swatchLimit) {
butSave.background = buttonBackgroundHoverColor;
}
}
});
butSave.onPointerOutObservable.add(function () {
if (options.savedColors) {
if (options.savedColors.length < options.swatchLimit) {
butSave.background = buttonBackgroundColor;
}
}
});
butSave.pointerDownAnimation = function () {
if (options.savedColors) {
if (options.savedColors.length < options.swatchLimit) {
butSave.background = buttonBackgroundClickColor;
}
}
};
butSave.pointerUpAnimation = function () {
if (options.savedColors) {
if (options.savedColors.length < options.swatchLimit) {
butSave.background = buttonBackgroundHoverColor;
}
}
};
butSave.onPointerClickObservable.add(function () {
if (options.savedColors) {
if (options.savedColors.length == 0) {
setEditButtonVisibility(true);
}
if (options.savedColors.length < options.swatchLimit) {
updateSwatches(newSwatch.background, butSave);
}
editSwatches(false);
}
});
if (options.savedColors.length > 0) {
setEditButtonVisibility(true);
}
buttonGrid.addControl(butSave, 2, 0);
}
// Picker color values input
var pickerColorValues = new _grid__WEBPACK_IMPORTED_MODULE_6__["Grid"]();
pickerColorValues.name = "Dialog Lower Right";
pickerColorValues.addRowDefinition(0.02, false);
pickerColorValues.addRowDefinition(0.63, false);
pickerColorValues.addRowDefinition(0.21, false);
pickerColorValues.addRowDefinition(0.14, false);
pickerBodyRight.addControl(pickerColorValues, 1, 0);
// RGB values text boxes
currentColor = babylonjs_Misc_observable__WEBPACK_IMPORTED_MODULE_1__["Color3"].FromHexString(options.lastColor);
var rgbValuesQuadrant = new _grid__WEBPACK_IMPORTED_MODULE_6__["Grid"]();
rgbValuesQuadrant.name = "RGB Values";
rgbValuesQuadrant.width = 0.82;
rgbValuesQuadrant.verticalAlignment = _control__WEBPACK_IMPORTED_MODULE_2__["Control"].VERTICAL_ALIGNMENT_CENTER;
rgbValuesQuadrant.addRowDefinition(1 / 3, false);
rgbValuesQuadrant.addRowDefinition(1 / 3, false);
rgbValuesQuadrant.addRowDefinition(1 / 3, false);
rgbValuesQuadrant.addColumnDefinition(0.1, false);
rgbValuesQuadrant.addColumnDefinition(0.2, false);
rgbValuesQuadrant.addColumnDefinition(0.7, false);
pickerColorValues.addControl(rgbValuesQuadrant, 1, 0);
for (var i = 0; i < inputFieldLabels.length; i++) {
var labelText = new _controls_textBlock__WEBPACK_IMPORTED_MODULE_7__["TextBlock"]();
labelText.text = inputFieldLabels[i];
labelText.color = buttonColor;
labelText.fontSize = buttonFontSize;
rgbValuesQuadrant.addControl(labelText, i, 0);
}
// Input fields for RGB values
rValInt = new _inputText__WEBPACK_IMPORTED_MODULE_3__["InputText"]();
rValInt.width = 0.83;
rValInt.height = 0.72;
rValInt.name = "rIntField";
rValInt.fontSize = buttonFontSize;
rValInt.text = (currentColor.r * 255).toString();
rValInt.color = inputTextColor;
rValInt.background = inputTextBackgroundColor;
rValInt.onFocusObservable.add(function () {
activeField = rValInt.name;
lastVal = rValInt.text;
editSwatches(false);
});
rValInt.onBlurObservable.add(function () {
if (rValInt.text == "") {
rValInt.text = "0";
}
updateInt(rValInt, "r");
if (activeField == rValInt.name) {
activeField = "";
}
});
rValInt.onTextChangedObservable.add(function () {
if (activeField == rValInt.name) {
updateInt(rValInt, "r");
}
});
rgbValuesQuadrant.addControl(rValInt, 0, 1);
gValInt = new _inputText__WEBPACK_IMPORTED_MODULE_3__["InputText"]();
gValInt.width = 0.83;
gValInt.height = 0.72;
gValInt.name = "gIntField";
gValInt.fontSize = buttonFontSize;
gValInt.text = (currentColor.g * 255).toString();
gValInt.color = inputTextColor;
gValInt.background = inputTextBackgroundColor;
gValInt.onFocusObservable.add(function () {
activeField = gValInt.name;
lastVal = gValInt.text;
editSwatches(false);
});
gValInt.onBlurObservable.add(function () {
if (gValInt.text == "") {
gValInt.text = "0";
}
updateInt(gValInt, "g");
if (activeField == gValInt.name) {
activeField = "";
}
});
gValInt.onTextChangedObservable.add(function () {
if (activeField == gValInt.name) {
updateInt(gValInt, "g");
}
});
rgbValuesQuadrant.addControl(gValInt, 1, 1);
bValInt = new _inputText__WEBPACK_IMPORTED_MODULE_3__["InputText"]();
bValInt.width = 0.83;
bValInt.height = 0.72;
bValInt.name = "bIntField";
bValInt.fontSize = buttonFontSize;
bValInt.text = (currentColor.b * 255).toString();
bValInt.color = inputTextColor;
bValInt.background = inputTextBackgroundColor;
bValInt.onFocusObservable.add(function () {
activeField = bValInt.name;
lastVal = bValInt.text;
editSwatches(false);
});
bValInt.onBlurObservable.add(function () {
if (bValInt.text == "") {
bValInt.text = "0";
}
updateInt(bValInt, "b");
if (activeField == bValInt.name) {
activeField = "";
}
});
bValInt.onTextChangedObservable.add(function () {
if (activeField == bValInt.name) {
updateInt(bValInt, "b");
}
});
rgbValuesQuadrant.addControl(bValInt, 2, 1);
rValDec = new _inputText__WEBPACK_IMPORTED_MODULE_3__["InputText"]();
rValDec.width = 0.95;
rValDec.height = 0.72;
rValDec.name = "rDecField";
rValDec.fontSize = buttonFontSize;
rValDec.text = currentColor.r.toString();
rValDec.color = inputTextColor;
rValDec.background = inputTextBackgroundColor;
rValDec.onFocusObservable.add(function () {
activeField = rValDec.name;
lastVal = rValDec.text;
editSwatches(false);
});
rValDec.onBlurObservable.add(function () {
if (parseFloat(rValDec.text) == 0 || rValDec.text == "") {
rValDec.text = "0";
updateFloat(rValDec, "r");
}
if (activeField == rValDec.name) {
activeField = "";
}
});
rValDec.onTextChangedObservable.add(function () {
if (activeField == rValDec.name) {
updateFloat(rValDec, "r");
}
});
rgbValuesQuadrant.addControl(rValDec, 0, 2);
gValDec = new _inputText__WEBPACK_IMPORTED_MODULE_3__["InputText"]();
gValDec.width = 0.95;
gValDec.height = 0.72;
gValDec.name = "gDecField";
gValDec.fontSize = buttonFontSize;
gValDec.text = currentColor.g.toString();
gValDec.color = inputTextColor;
gValDec.background = inputTextBackgroundColor;
gValDec.onFocusObservable.add(function () {
activeField = gValDec.name;
lastVal = gValDec.text;
editSwatches(false);
});
gValDec.onBlurObservable.add(function () {
if (parseFloat(gValDec.text) == 0 || gValDec.text == "") {
gValDec.text = "0";
updateFloat(gValDec, "g");
}
if (activeField == gValDec.name) {
activeField = "";
}
});
gValDec.onTextChangedObservable.add(function () {
if (activeField == gValDec.name) {
updateFloat(gValDec, "g");
}
});
rgbValuesQuadrant.addControl(gValDec, 1, 2);
bValDec = new _inputText__WEBPACK_IMPORTED_MODULE_3__["InputText"]();
bValDec.width = 0.95;
bValDec.height = 0.72;
bValDec.name = "bDecField";
bValDec.fontSize = buttonFontSize;
bValDec.text = currentColor.b.toString();
bValDec.color = inputTextColor;
bValDec.background = inputTextBackgroundColor;
bValDec.onFocusObservable.add(function () {
activeField = bValDec.name;
lastVal = bValDec.text;
editSwatches(false);
});
bValDec.onBlurObservable.add(function () {
if (parseFloat(bValDec.text) == 0 || bValDec.text == "") {
bValDec.text = "0";
updateFloat(bValDec, "b");
}
if (activeField == bValDec.name) {
activeField = "";
}
});
bValDec.onTextChangedObservable.add(function () {
if (activeField == bValDec.name) {
updateFloat(bValDec, "b");
}
});
rgbValuesQuadrant.addControl(bValDec, 2, 2);
// Hex value input
var hexValueQuadrant = new _grid__WEBPACK_IMPORTED_MODULE_6__["Grid"]();
hexValueQuadrant.name = "Hex Value";
hexValueQuadrant.width = 0.82;
hexValueQuadrant.addRowDefinition(1.0, false);
hexValueQuadrant.addColumnDefinition(0.1, false);
hexValueQuadrant.addColumnDefinition(0.9, false);
pickerColorValues.addControl(hexValueQuadrant, 2, 0);
var labelText = new _controls_textBlock__WEBPACK_IMPORTED_MODULE_7__["TextBlock"]();
labelText.text = "#";
labelText.color = buttonColor;
labelText.fontSize = buttonFontSize;
hexValueQuadrant.addControl(labelText, 0, 0);
hexVal = new _inputText__WEBPACK_IMPORTED_MODULE_3__["InputText"]();
hexVal.width = 0.96;
hexVal.height = 0.72;
hexVal.name = "hexField";
hexVal.horizontalAlignment = _control__WEBPACK_IMPORTED_MODULE_2__["Control"].HORIZONTAL_ALIGNMENT_CENTER;
hexVal.fontSize = buttonFontSize;
var minusPound = options.lastColor.split("#");
hexVal.text = minusPound[1];
hexVal.color = inputTextColor;
hexVal.background = inputTextBackgroundColor;
hexVal.onFocusObservable.add(function () {
activeField = hexVal.name;
lastVal = hexVal.text;
editSwatches(false);
});
hexVal.onBlurObservable.add(function () {
if (hexVal.text.length == 3) {
var val = hexVal.text.split("");
hexVal.text = val[0] + val[0] + val[1] + val[1] + val[2] + val[2];
}
if (hexVal.text == "") {
hexVal.text = "000000";
updateValues(babylonjs_Misc_observable__WEBPACK_IMPORTED_MODULE_1__["Color3"].FromHexString(hexVal.text), "b");
}
if (activeField == hexVal.name) {
activeField = "";
}
});
hexVal.onTextChangedObservable.add(function () {
var newHexValue = hexVal.text;
var checkHex = /[^0-9A-F]/i.test(newHexValue);
if ((hexVal.text.length > 6 || checkHex) && activeField == hexVal.name) {
hexVal.text = lastVal;
}
else {
if (hexVal.text.length < 6) {
var leadingZero = 6 - hexVal.text.length;
for (var i = 0; i < leadingZero; i++) {
newHexValue = "0" + newHexValue;
}
}
if (hexVal.text.length == 3) {
var val = hexVal.text.split("");
newHexValue = val[0] + val[0] + val[1] + val[1] + val[2] + val[2];
}
newHexValue = "#" + newHexValue;
if (activeField == hexVal.name) {
lastVal = hexVal.text;
updateValues(babylonjs_Misc_observable__WEBPACK_IMPORTED_MODULE_1__["Color3"].FromHexString(newHexValue), hexVal.name);
}
}
});
hexValueQuadrant.addControl(hexVal, 0, 1);
if (options.savedColors && options.savedColors.length > 0) {
updateSwatches("", butSave);
}
});
};
ColorPicker._Epsilon = 0.000001;
return ColorPicker;
}(_control__WEBPACK_IMPORTED_MODULE_2__["Control"]));
/***/ }),
/***/ "./2D/controls/container.ts":
/*!**********************************!*\
!*** ./2D/controls/container.ts ***!
\**********************************/
/*! exports provided: Container */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Container", function() { return Container; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../../node_modules/tslib/tslib.es6.js");
/* harmony import */ var babylonjs_Misc_logger__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! babylonjs/Misc/logger */ "babylonjs/Misc/observable");
/* harmony import */ var babylonjs_Misc_logger__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(babylonjs_Misc_logger__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var _control__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./control */ "./2D/controls/control.ts");
/* harmony import */ var _measure__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../measure */ "./2D/measure.ts");
/**
* Root class for 2D containers
* @see http://doc.babylonjs.com/how_to/gui#containers
*/
var Container = /** @class */ (function (_super) {
tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](Container, _super);
/**
* Creates a new Container
* @param name defines the name of the container
*/
function Container(name) {
var _this = _super.call(this, name) || this;
_this.name = name;
/** @hidden */
_this._children = new Array();
/** @hidden */
_this._measureForChildren = _measure__WEBPACK_IMPORTED_MODULE_3__["Measure"].Empty();
/** @hidden */
_this._background = "";
/** @hidden */
_this._adaptWidthToChildren = false;
/** @hidden */
_this._adaptHeightToChildren = false;
return _this;
}
Object.defineProperty(Container.prototype, "adaptHeightToChildren", {
/** Gets or sets a boolean indicating if the container should try to adapt to its children height */
get: function () {
return this._adaptHeightToChildren;
},
set: function (value) {
if (this._adaptHeightToChildren === value) {
return;
}
this._adaptHeightToChildren = value;
if (value) {
this.height = "100%";
}
this._markAsDirty();
},
enumerable: true,
configurable: true
});
Object.defineProperty(Container.prototype, "adaptWidthToChildren", {
/** Gets or sets a boolean indicating if the container should try to adapt to its children width */
get: function () {
return this._adaptWidthToChildren;
},
set: function (value) {
if (this._adaptWidthToChildren === value) {
return;
}
this._adaptWidthToChildren = value;
if (value) {
this.width = "100%";
}
this._markAsDirty();
},
enumerable: true,
configurable: true
});
Object.defineProperty(Container.prototype, "background", {
/** Gets or sets background color */
get: function () {
return this._background;
},
set: function (value) {
if (this._background === value) {
return;
}
this._background = value;
this._markAsDirty();
},
enumerable: true,
configurable: true
});
Object.defineProperty(Container.prototype, "children", {
/** Gets the list of children */
get: function () {
return this._children;
},
enumerable: true,
configurable: true
});
Container.prototype._getTypeName = function () {
return "Container";
};
Container.prototype._flagDescendantsAsMatrixDirty = function () {
for (var _i = 0, _a = this.children; _i < _a.length; _i++) {
var child = _a[_i];
child._markMatrixAsDirty();
}
};
/**
* Gets a child using its name
* @param name defines the child name to look for
* @returns the child control if found
*/
Container.prototype.getChildByName = function (name) {
for (var _i = 0, _a = this.children; _i < _a.length; _i++) {
var child = _a[_i];
if (child.name === name) {
return child;
}
}
return null;
};
/**
* Gets a child using its type and its name
* @param name defines the child name to look for
* @param type defines the child type to look for
* @returns the child control if found
*/
Container.prototype.getChildByType = function (name, type) {
for (var _i = 0, _a = this.children; _i < _a.length; _i++) {
var child = _a[_i];
if (child.typeName === type) {
return child;
}
}
return null;
};
/**
* Search for a specific control in children
* @param control defines the control to look for
* @returns true if the control is in child list
*/
Container.prototype.containsControl = function (control) {
return this.children.indexOf(control) !== -1;
};
/**
* Adds a new control to the current container
* @param control defines the control to add
* @returns the current container
*/
Container.prototype.addControl = function (control) {
if (!control) {
return this;
}
var index = this._children.indexOf(control);
if (index !== -1) {
return this;
}
control._link(this._host);
control._markAllAsDirty();
this._reOrderControl(control);
this._markAsDirty();
return this;
};
/**
* Removes all controls from the current container
* @returns the current container
*/
Container.prototype.clearControls = function () {
var children = this.children.slice();
for (var _i = 0, children_1 = children; _i < children_1.length; _i++) {
var child = children_1[_i];
this.removeControl(child);
}
return this;
};
/**
* Removes a control from the current container
* @param control defines the control to remove
* @returns the current container
*/
Container.prototype.removeControl = function (control) {
var index = this._children.indexOf(control);
if (index !== -1) {
this._children.splice(index, 1);
control.parent = null;
}
control.linkWithMesh(null);
if (this._host) {
this._host._cleanControlAfterRemoval(control);
}
this._markAsDirty();
return this;
};
/** @hidden */
Container.prototype._reOrderControl = function (control) {
this.removeControl(control);
var wasAdded = false;
for (var index = 0; index < this._children.length; index++) {
if (this._children[index].zIndex > control.zIndex) {
this._children.splice(index, 0, control);
wasAdded = true;
break;
}
}
if (!wasAdded) {
this._children.push(control);
}
control.parent = this;
this._markAsDirty();
};
/** @hidden */
Container.prototype._offsetLeft = function (offset) {
_super.prototype._offsetLeft.call(this, offset);
for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
var child = _a[_i];
child._offsetLeft(offset);
}
};
/** @hidden */
Container.prototype._offsetTop = function (offset) {
_super.prototype._offsetTop.call(this, offset);
for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
var child = _a[_i];
child._offsetTop(offset);
}
};
/** @hidden */
Container.prototype._markAllAsDirty = function () {
_super.prototype._markAllAsDirty.call(this);
for (var index = 0; index < this._children.length; index++) {
this._children[index]._markAllAsDirty();
}
};
/** @hidden */
Container.prototype._localDraw = function (context) {
if (this._background) {
context.save();
if (this.shadowBlur || this.shadowOffsetX || this.shadowOffsetY) {
context.shadowColor = this.shadowColor;
context.shadowBlur = this.shadowBlur;
context.shadowOffsetX = this.shadowOffsetX;
context.shadowOffsetY = this.shadowOffsetY;
}
context.fillStyle = this._background;
context.fillRect(this._currentMeasure.left, this._currentMeasure.top, this._currentMeasure.width, this._currentMeasure.height);
context.restore();
}
};
/** @hidden */
Container.prototype._link = function (host) {
_super.prototype._link.call(this, host);
for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
var child = _a[_i];
child._link(host);
}
};
/** @hidden */
Container.prototype._beforeLayout = function () {
// Do nothing
};
/** @hidden */
Container.prototype._processMeasures = function (parentMeasure, context) {
if (this._isDirty || !this._cachedParentMeasure.isEqualsTo(parentMeasure)) {
_super.prototype._processMeasures.call(this, parentMeasure, context);
this._evaluateClippingState(parentMeasure);
}
};
/** @hidden */
Container.prototype._layout = function (parentMeasure, context) {
if (!this.isDirty && (!this.isVisible || this.notRenderable)) {
return false;
}
if (this._isDirty) {
this._currentMeasure.transformToRef(this._transformMatrix, this._prevCurrentMeasureTransformedIntoGlobalSpace);
}
var rebuildCount = 0;
context.save();
this._applyStates(context);
this._beforeLayout();
do {
var computedWidth = -1;
var computedHeight = -1;
this._rebuildLayout = false;
this._processMeasures(parentMeasure, context);
if (!this._isClipped) {
for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
var child = _a[_i];
child._tempParentMeasure.copyFrom(this._measureForChildren);
if (child._layout(this._measureForChildren, context)) {
if (this.adaptWidthToChildren && child._width.isPixel) {
computedWidth = Math.max(computedWidth, child._currentMeasure.width);
}
if (this.adaptHeightToChildren && child._height.isPixel) {
computedHeight = Math.max(computedHeight, child._currentMeasure.height);
}
}
}
if (this.adaptWidthToChildren && computedWidth >= 0) {
if (this.width !== computedWidth + "px") {
this.width = computedWidth + "px";
this._rebuildLayout = true;
}
}
if (this.adaptHeightToChildren && computedHeight >= 0) {
if (this.height !== computedHeight + "px") {
this.height = computedHeight + "px";
this._rebuildLayout = true;
}
}
this._postMeasure();
}
rebuildCount++;
} while (this._rebuildLayout && rebuildCount < 3);
if (rebuildCount >= 3) {
babylonjs_Misc_logger__WEBPACK_IMPORTED_MODULE_1__["Logger"].Error("Layout cycle detected in GUI (Container name=" + this.name + ", uniqueId=" + this.uniqueId + ")");
}
context.restore();
if (this._isDirty) {
this.invalidateRect();
this._isDirty = false;
}
return true;
};
Container.prototype._postMeasure = function () {
// Do nothing by default
};
/** @hidden */
Container.prototype._draw = function (context, invalidatedRectangle) {
this._localDraw(context);
if (this.clipChildren) {
this._clipForChildren(context);
}
for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
var child = _a[_i];
// Only redraw parts of the screen that are invalidated
if (invalidatedRectangle) {
if (!child._intersectsRect(invalidatedRectangle)) {
continue;
}
}
child._render(context, invalidatedRectangle);
}
};
/** @hidden */
Container.prototype._getDescendants = function (results, directDescendantsOnly, predicate) {
if (directDescendantsOnly === void 0) { directDescendantsOnly = false; }
if (!this.children) {
return;
}
for (var index = 0; index < this.children.length; index++) {
var item = this.children[index];
if (!predicate || predicate(item)) {
results.push(item);
}
if (!directDescendantsOnly) {
item._getDescendants(results, false, predicate);
}
}
};
/** @hidden */
Container.prototype._processPicking = function (x, y, type, pointerId, buttonIndex) {
if (!this._isEnabled || !this.isVisible || this.notRenderable) {
return false;
}
if (!_super.prototype.contains.call(this, x, y)) {
return false;
}
// Checking backwards to pick closest first
for (var index = this._children.length - 1; index >= 0; index--) {
var child = this._children[index];
if (child._processPicking(x, y, type, pointerId, buttonIndex)) {
if (child.hoverCursor) {
this._host._changeCursor(child.hoverCursor);
}
return true;
}
}
if (!this.isHitTestVisible) {
return false;
}
return this._processObservables(type, x, y, pointerId, buttonIndex);
};
/** @hidden */
Container.prototype._additionalProcessing = function (parentMeasure, context) {
_super.prototype._additionalProcessing.call(this, parentMeasure, context);
this._measureForChildren.copyFrom(this._currentMeasure);
};
/** Releases associated resources */
Container.prototype.dispose = function () {
_super.prototype.dispose.call(this);
for (var index = this.children.length - 1; index >= 0; index--) {
this.children[index].dispose();
}
};
return Container;
}(_control__WEBPACK_IMPORTED_MODULE_2__["Control"]));
/***/ }),
/***/ "./2D/controls/control.ts":
/*!********************************!*\
!*** ./2D/controls/control.ts ***!
\********************************/
/*! exports provided: Control */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Control", function() { return Control; });
/* harmony import */ var babylonjs_Misc_observable__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! babylonjs/Misc/observable */ "babylonjs/Misc/observable");
/* harmony import */ var babylonjs_Misc_observable__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(babylonjs_Misc_observable__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _valueAndUnit__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../valueAndUnit */ "./2D/valueAndUnit.ts");
/* harmony import */ var _measure__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../measure */ "./2D/measure.ts");
/* harmony import */ var _math2D__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../math2D */ "./2D/math2D.ts");
/**
* Root class used for all 2D controls
* @see http://doc.babylonjs.com/how_to/gui#controls
*/
var Control = /** @class */ (function () {
// Functions
/**
* Creates a new control
* @param name defines the name of the control
*/
function Control(
/** defines the name of the control */
name) {
this.name = name;
this._alpha = 1;
this._alphaSet = false;
this._zIndex = 0;
/** @hidden */
this._currentMeasure = _measure__WEBPACK_IMPORTED_MODULE_2__["Measure"].Empty();
this._fontFamily = "Arial";
this._fontStyle = "";
this._fontWeight = "";
this._fontSize = new _valueAndUnit__WEBPACK_IMPORTED_MODULE_1__["ValueAndUnit"](18, _valueAndUnit__WEBPACK_IMPORTED_MODULE_1__["ValueAndUnit"].UNITMODE_PIXEL, false);
/** @hidden */
this._width = new _valueAndUnit__WEBPACK_IMPORTED_MODULE_1__["ValueAndUnit"](1, _valueAndUnit__WEBPACK_IMPORTED_MODULE_1__["ValueAndUnit"].UNITMODE_PERCENTAGE, false);
/** @hidden */
this._height = new _valueAndUnit__WEBPACK_IMPORTED_MODULE_1__["ValueAndUnit"](1, _valueAndUnit__WEBPACK_IMPORTED_MODULE_1__["ValueAndUnit"].UNITMODE_PERCENTAGE, false);
this._color = "";
this._style = null;
/** @hidden */
this._horizontalAlignment = Control.HORIZONTAL_ALIGNMENT_CENTER;
/** @hidden */
this._verticalAlignment = Control.VERTICAL_ALIGNMENT_CENTER;
/** @hidden */
this._isDirty = true;
/** @hidden */
this._wasDirty = false;
/** @hidden */
this._tempParentMeasure = _measure__WEBPACK_IMPORTED_MODULE_2__["Measure"].Empty();
/** @hidden */
this._prevCurrentMeasureTransformedIntoGlobalSpace = _measure__WEBPACK_IMPORTED_MODULE_2__["Measure"].Empty();
/** @hidden */
this._cachedParentMeasure = _measure__WEBPACK_IMPORTED_MODULE_2__["Measure"].Empty();
this._paddingLeft = new _valueAndUnit__WEBPACK_IMPORTED_MODULE_1__["ValueAndUnit"](0);
this._paddingRight = new _valueAndUnit__WEBPACK_IMPORTED_MODULE_1__["ValueAndUnit"](0);
this._paddingTop = new _valueAndUnit__WEBPACK_IMPORTED_MODULE_1__["ValueAndUnit"](0);
this._paddingBottom = new _valueAndUnit__WEBPACK_IMPORTED_MODULE_1__["ValueAndUnit"](0);
/** @hidden */
this._left = new _valueAndUnit__WEBPACK_IMPORTED_MODULE_1__["ValueAndUnit"](0);
/** @hidden */
this._top = new _valueAndUnit__WEBPACK_IMPORTED_MODULE_1__["ValueAndUnit"](0);
this._scaleX = 1.0;
this._scaleY = 1.0;
this._rotation = 0;
this._transformCenterX = 0.5;
this._transformCenterY = 0.5;
/** @hidden */
this._transformMatrix = _math2D__WEBPACK_IMPORTED_MODULE_3__["Matrix2D"].Identity();
/** @hidden */
this._invertTransformMatrix = _math2D__WEBPACK_IMPORTED_MODULE_3__["Matrix2D"].Identity();
/** @hidden */
this._transformedPosition = babylonjs_Misc_observable__WEBPACK_IMPORTED_MODULE_0__["Vector2"].Zero();
this._isMatrixDirty = true;
this._isVisible = true;
this._isHighlighted = false;
this._fontSet = false;
this._dummyVector2 = babylonjs_Misc_observable__WEBPACK_IMPORTED_MODULE_0__["Vector2"].Zero();
this._downCount = 0;
this._enterCount = -1;
this._doNotRender = false;
this._downPointerIds = {};
this._isEnabled = true;
this._disabledColor = "#9a9a9a";
/** @hidden */
this._rebuildLayout = false;
/** @hidden */
this._isClipped = false;
/**
* Gets or sets an object used to store user defined information for the node
*/
this.metadata = null;
/** Gets or sets a boolean indicating if the control can be hit with pointer events */
this.isHitTestVisible = true;
/** Gets or sets a boolean indicating if the control can block pointer events */
this.isPointerBlocker = false;
/** Gets or sets a boolean indicating if the control can be focusable */
this.isFocusInvisible = false;
/**
* Gets or sets a boolean indicating if the children are clipped to the current control bounds.
* Please note that not clipping children may generate issues with adt.useInvalidateRectOptimization so it is recommended to turn this optimization off if you want to use unclipped children
*/
this.clipChildren = true;
/**
* Gets or sets a boolean indicating that control content must be clipped
* Please note that not clipping children may generate issues with adt.useInvalidateRectOptimization so it is recommended to turn this optimization off if you want to use unclipped children
*/
this.clipContent = true;
/**
* Gets or sets a boolean indicating that the current control should cache its rendering (useful when the control does not change often)
*/
this.useBitmapCache = false;
this._shadowOffsetX = 0;
this._shadowOffsetY = 0;
this._shadowBlur = 0;
this._shadowColor = 'black';
/** Gets or sets the cursor to use when the control is hovered */
this.hoverCursor = "";
/** @hidden */
this._linkOffsetX = new _valueAndUnit__WEBPACK_IMPORTED_MODULE_1__["ValueAndUnit"](0);
/** @hidden */
this._linkOffsetY = new _valueAndUnit__WEBPACK_IMPORTED_MODULE_1__["ValueAndUnit"](0);
/**
* An event triggered when the pointer move over the control.
*/
this.onPointerMoveObservable = new babylonjs_Misc_observable__WEBPACK_IMPORTED_MODULE_0__["Observable"]();
/**
* An event triggered when the pointer move out of the control.
*/
this.onPointerOutObservable = new babylonjs_Misc_observable__WEBPACK_IMPORTED_MODULE_0__["Observable"]();
/**
* An event triggered when the pointer taps the control
*/
this.onPointerDownObservable = new babylonjs_Misc_observable__WEBPACK_IMPORTED_MODULE_0__["Observable"]();
/**
* An event triggered when pointer up
*/
this.onPointerUpObservable = new babylonjs_Misc_observable__WEBPACK_IMPORTED_MODULE_0__["Observable"]();
/**
* An event triggered when a control is clicked on
*/
this.onPointerClickObservable = new babylonjs_Misc_observable__WEBPACK_IMPORTED_MODULE_0__["Observable"]();
/**
* An event triggered when pointer enters the control
*/
this.onPointerEnterObservable = new babylonjs_Misc_observable__WEBPACK_IMPORTED_MODULE_0__["Observable"]();
/**
* An event triggered when the control is marked as dirty
*/
this.onDirtyObservable = new babylonjs_Misc_observable__WEBPACK_IMPORTED_MODULE_0__["Observable"]();
/**
* An event triggered before drawing the control
*/
this.onBeforeDrawObservable = new babylonjs_Misc_observable__WEBPACK_IMPORTED_MODULE_0__["Observable"]();
/**
* An event triggered after the control was drawn
*/
this.onAfterDrawObservable = new babylonjs_Misc_observable__WEBPACK_IMPORTED_MODULE_0__["Observable"]();
this._tmpMeasureA = new _measure__WEBPACK_IMPORTED_MODULE_2__["Measure"](0, 0, 0, 0);
}
Object.defineProperty(Control.prototype, "shadowOffsetX", {
/** Gets or sets a value indicating the offset to apply on X axis to render the shadow */
get: function () {
return this._shadowOffsetX;
},
set: function (value) {
if (this._shadowOffsetX === value) {
return;
}
this._shadowOffsetX = value;
this._markAsDirty();
},
enumerable: true,
configurable: true
});
Object.defineProperty(Control.prototype, "shadowOffsetY", {
/** Gets or sets a value indicating the offset to apply on Y axis to render the shadow */
get: function () {
return this._shadowOffsetY;
},
set: function (value) {
if (this._shadowOffsetY === value) {
return;
}
this._shadowOffsetY = value;
this._markAsDirty();
},
enumerable: true,
configurable: true
});
Object.defineProperty(Control.prototype, "shadowBlur", {
/** Gets or sets a value indicating the amount of blur to use to render the shadow */
get: function () {
return this._shadowBlur;
},
set: function (value) {
if (this._shadowBlur === value) {
return;
}
this._shadowBlur = value;
this._markAsDirty();
},
enumerable: true,
configurable: true
});
Object.defineProperty(Control.prototype, "shadowColor", {
/** Gets or sets a value indicating the color of the shadow (black by default ie. "#000") */
get: function () {
return this._shadowColor;
},
set: function (value) {
if (this._shadowColor === value) {
return;
}
this._shadowColor = value;
this._markAsDirty();
},
enumerable: true,
configurable: true
});
Object.defineProperty(Control.prototype, "typeName", {
// Properties
/** Gets the control type name */
get: function () {
return this._getTypeName();
},
enumerable: true,
configurable: true
});
/**
* Get the current class name of the control.
* @returns current class name
*/
Control.prototype.getClassName = function () {
return this._getTypeName();
};
Object.defineProperty(Control.prototype, "host", {
/**
* Get the hosting AdvancedDynamicTexture
*/
get: function () {
return this._host;
},
enumerable: true,
configurable: true
});
Object.defineProperty(Control.prototype, "fontOffset", {
/** Gets or set information about font offsets (used to render and align text) */
get: function () {
return this._fontOffset;
},
set: function (offset) {
this._fontOffset = offset;
},
enumerable: true,
configurable: true
});
Object.defineProperty(Control.prototype, "alpha", {
/** Gets or sets alpha value for the control (1 means opaque and 0 means entirely transparent) */
get: function () {
return this._alpha;
},
set: function (value) {
if (this._alpha === value) {
return;
}
this._alphaSet = true;
this._alpha = value;
this._markAsDirty();
},
enumerable: true,
configurable: true
});
Object.defineProperty(Control.prototype, "isHighlighted", {
/**
* Gets or sets a boolean indicating that we want to highlight the control (mostly for debugging purpose)
*/
get: function () {
return this._isHighlighted;
},
set: function (value) {
if (this._isHighlighted === value) {
return;
}
this._isHighlighted = value;
this._markAsDirty();
},
enumerable: true,
configurable: true
});
Object.defineProperty(Control.prototype, "scaleX", {
/** Gets or sets a value indicating the scale factor on X axis (1 by default)
* @see http://doc.babylonjs.com/how_to/gui#rotation-and-scaling
*/
get: function () {
return this._scaleX;
},
set: function (value) {
if (this._scaleX === value) {
return;
}
this._scaleX = value;
this._markAsDirty();
this._markMatrixAsDirty();
},
enumerable: true,
configurable: true
});
Object.defineProperty(Control.prototype, "scaleY", {
/** Gets or sets a value indicating the scale factor on Y axis (1 by default)
* @see http://doc.babylonjs.com/how_to/gui#rotation-and-scaling
*/
get: function () {
return this._scaleY;
},
set: function (value) {
if (this._scaleY === value) {
return;
}
this._scaleY = value;
this._markAsDirty();
this._markMatrixAsDirty();
},
enumerable: true,
configurable: true
});
Object.defineProperty(Control.prototype, "rotation", {
/** Gets or sets the rotation angle (0 by default)
* @see http://doc.babylonjs.com/how_to/gui#rotation-and-scaling
*/
get: function () {
return this._rotation;
},
set: function (value) {
if (this._rotation === value) {
return;
}
this._rotation = value;
this._markAsDirty();
this._markMatrixAsDirty();
},
enumerable: true,
configurable: true
});
Object.defineProperty(Control.prototype, "transformCenterY", {
/** Gets or sets the transformation center on Y axis (0 by default)
* @see http://doc.babylonjs.com/how_to/gui#rotation-and-scaling
*/
get: function () {
return this._transformCenterY;
},
set: function (value) {
if (this._transformCenterY === value) {
return;
}
this._transformCenterY = value;
this._markAsDirty();
this._markMatrixAsDirty();
},
enumerable: true,
configurable: true
});
Object.defineProperty(Control.prototype, "transformCenterX", {
/** Gets or sets the transformation center on X axis (0 by default)
* @see http://doc.babylonjs.com/how_to/gui#rotation-and-scaling
*/
get: function () {
return this._transformCenterX;
},
set: function (value) {
if (this._transformCenterX === value) {
return;
}
this._transformCenterX = value;
this._markAsDirty();
this._markMatrixAsDirty();
},
enumerable: true,
configurable: true
});
Object.defineProperty(Control.prototype, "horizontalAlignment", {
/**
* Gets or sets the horizontal alignment
* @see http://doc.babylonjs.com/how_to/gui#alignments
*/
get: function () {
return this._horizontalAlignment;
},
set: function (value) {
if (this._horizontalAlignment === value) {
return;
}
this._horizontalAlignment = value;
this._markAsDirty();
},
enumerable: true,
configurable: true
});
Object.defineProperty(Control.prototype, "verticalAlignment", {
/**
* Gets or sets the vertical alignment
* @see http://doc.babylonjs.com/how_to/gui#alignments
*/
get: function () {
return this._verticalAlignment;
},
set: function (value) {
if (this._verticalAlignment === value) {
return;
}
this._verticalAlignment = value;
this._markAsDirty();
},
enumerable: true,
configurable: true
});
Object.defineProperty(Control.prototype, "width", {
/**
* Gets or sets control width
* @see http://doc.babylonjs.com/how_to/gui#position-and-size
*/
get: function () {
return this._width.toString(this._host);
},
set: function (value) {
if (this._width.toString(this._host) === value) {
return;
}
if (this._width.fromString(value)) {
this._markAsDirty();
}
},
enumerable: true,
configurable: true
});
Object.defineProperty(Control.prototype, "widthInPixels", {
/**
* Gets or sets the control width in pixel
* @see http://doc.babylonjs.com/how_to/gui#position-and-size
*/
get: function () {
return this._width.getValueInPixel(this._host, this._cachedParentMeasure.width);
},
set: function (value) {
if (isNaN(value)) {
return;
}
this.width = value + "px";
},
enumerable: true,
configurable: true
});
Object.defineProperty(Control.prototype, "height", {
/**
* Gets or sets control height
* @see http://doc.babylonjs.com/how_to/gui#position-and-size
*/
get: function () {
return this._height.toString(this._host);
},
set: function (value) {
if (this._height.toString(this._host) === value) {
return;
}
if (this._height.fromString(value)) {
this._markAsDirty();
}
},
enumerable: true,
configurable: true
});
Object.defineProperty(Control.prototype, "heightInPixels", {
/**
* Gets or sets control height in pixel
* @see http://doc.babylonjs.com/how_to/gui#position-and-size
*/
get: function () {
return this._height.getValueInPixel(this._host, this._cachedParentMeasure.height);
},
set: function (value) {
if (isNaN(value)) {
return;
}
this.height = value + "px";
},
enumerable: true,
configurable: true
});
Object.defineProperty(Control.prototype, "fontFamily", {
/** Gets or set font family */
get: function () {
if (!this._fontSet) {
return "";
}
return this._fontFamily;
},
set: function (value) {
if (this._fontFamily === value) {
return;
}
this._fontFamily = value;
this._resetFontCache();
},
enumerable: true,
configurable: true
});
Object.defineProperty(Control.prototype, "fontStyle", {
/** Gets or sets font style */
get: function () {
return this._fontStyle;
},
set: function (value) {
if (this._fontStyle === value) {
return;
}
this._fontStyle = value;
this._resetFontCache();
},
enumerable: true,
configurable: true
});
Object.defineProperty(Control.prototype, "fontWeight", {
/** Gets or sets font weight */
get: function () {
return this._fontWeight;
},
set: function (value) {
if (this._fontWeight === value) {
return;
}
this._fontWeight = value;
this._resetFontCache();
},
enumerable: true,
configurable: true
});
Object.defineProperty(Control.prototype, "style", {
/**
* Gets or sets style
* @see http://doc.babylonjs.com/how_to/gui#styles
*/
get: function () {
return this._style;
},
set: function (value) {
var _this = this;
if (this._style) {
this._style.onChangedObservable.remove(this._styleObserver);
this._styleObserver = null;
}
this._style = value;
if (this._style) {
this._styleObserver = this._style.onChangedObservable.add(function () {
_this._markAsDirty();
_this._resetFontCache();
});
}
this._markAsDirty();
this._resetFontCache();
},
enumerable: true,
configurable: true
});
Object.defineProperty(Control.prototype, "_isFontSizeInPercentage", {
/** @hidden */
get: function () {
return this._fontSize.isPercentage;
},
enumerable: true,
configurable: true
});
Object.defineProperty(Control.prototype, "fontSizeInPixels", {
/** Gets or sets font size in pixels */
get: function () {
var fontSizeToUse = this._style ? this._style._fontSize : this._fontSize;
if (fontSizeToUse.isPixel) {
return fontSizeToUse.getValue(this._host);
}
return fontSizeToUse.getValueInPixel(this._host, this._tempParentMeasure.height || this._cachedParentMeasure.height);
},
set: function (value) {
if (isNaN(value)) {
return;
}
this.fontSize = value + "px";
},
enumerable: true,
configurable: true
});
Object.defineProperty(Control.prototype, "fontSize", {
/** Gets or sets font size */
get: function () {
return this._fontSize.toString(this._host);
},
set: function (value) {
if (this._fontSize.toString(this._host) === value) {
return;
}
if (this._fontSize.fromString(value)) {
this._markAsDirty();
this._resetFontCache();
}
},
enumerable: true,
configurable: true
});
Object.defineProperty(Control.prototype, "color", {
/** Gets or sets foreground color */
get: function () {
return this._color;
},
set: function (value) {
if (this._color === value) {
return;
}
this._color = value;
this._markAsDirty();
},
enumerable: true,
configurable: true
});
Object.defineProperty(Control.prototype, "zIndex", {
/** Gets or sets z index which is used to reorder controls on the z axis */
get: function () {
return this._zIndex;
},
set: function (value) {
if (this.zIndex === value) {
return;
}
this._zIndex = value;
if (this.parent) {
this.parent._reOrderControl(this);
}
},
enumerable: true,
configurable: true
});
Object.defineProperty(Control.prototype, "notRenderable", {
/** Gets or sets a boolean indicating if the control can be rendered */
get: function () {
return this._doNotRender;
},
set: function (value) {
if (this._doNotRender === value) {
return;
}
this._doNotRender = value;
this._markAsDirty();
},
enumerable: true,
configurable: true
});
Object.defineProperty(Control.prototype, "isVisible", {
/** Gets or sets a boolean indicating if the control is visible */
get: function () {
return this._isVisible;
},
set: function (value) {
if (this._isVisible === value) {
return;
}
this._isVisible = value;
this._markAsDirty(true);
},
enumerable: true,
configurable: true
});
Object.defineProperty(Control.prototype, "isDirty", {
/** Gets a boolean indicating that the control needs to update its rendering */
get: function () {
return this._isDirty;
},
enumerable: true,
configurable: true
});
Object.defineProperty(Control.prototype, "linkedMesh", {
/**
* Gets the current linked mesh (or null if none)
*/
get: function () {
return this._linkedMesh;
},
enumerable: true,
configurable: true
});
Object.defineProperty(Control.prototype, "paddingLeft", {
/**
* Gets or sets a value indicating the padding to use on the left of the control
* @see http://doc.babylonjs.com/how_to/gui#position-and-size
*/
get: function () {
return this._paddingLeft.toString(this._host);
},
set: function (value) {
if (this._paddingLeft.fromString(value)) {
this._markAsDirty();
}
},
enumerable: true,
configurable: true
});
Object.defineProperty(Control.prototype, "paddingLeftInPixels", {
/**
* Gets or sets a value indicating the padding in pixels to use on the left of the control
* @see http://doc.babylonjs.com/how_to/gui#position-and-size
*/
get: function () {
return this._paddingLeft.getValueInPixel(this._host, this._cachedParentMeasure.width);
},
set: function (value) {
if (isNaN(value)) {
return;
}
this.paddingLeft = value + "px";
},
enumerable: true,
configurable: true
});
Object.defineProperty(Control.prototype, "paddingRight", {
/**
* Gets or sets a value indicating the padding to use on the right of the control
* @see http://doc.babylonjs.com/how_to/gui#position-and-size
*/
get: function () {
return this._paddingRight.toString(this._host);
},
set: function (value) {
if (this._paddingRight.fromString(value)) {
this._markAsDirty();
}
},
enumerable: true,
configurable: true
});
Object.defineProperty(Control.prototype, "paddingRightInPixels", {
/**
* Gets or sets a value indicating the padding in pixels to use on the right of the control
* @see http://doc.babylonjs.com/how_to/gui#position-and-size
*/
get: function () {
return this._paddingRight.getValueInPixel(this._host, this._cachedParentMeasure.width);
},
set: function (value) {
if (isNaN(value)) {
return;
}
this.paddingRight = value + "px";
},
enumerable: true,
configurable: true
});
Object.defineProperty(Control.prototype, "paddingTop", {
/**
* Gets or sets a value indicating the padding to use on the top of the control
* @see http://doc.babylonjs.com/how_to/gui#position-and-size
*/
get: function () {
return this._paddingTop.toString(this._host);
},
set: function (value) {
if (this._paddingTop.fromString(value)) {
this._markAsDirty();
}
},
enumerable: true,
configurable: true
});
Object.defineProperty(Control.prototype, "paddingTopInPixels", {
/**
* Gets or sets a value indicating the padding in pixels to use on the top of the control
* @see http://doc.babylonjs.com/how_to/gui#position-and-size
*/
get: function () {
return this._paddingTop.getValueInPixel(this._host, this._cachedParentMeasure.height);
},
set: function (value) {
if (isNaN(value)) {
return;
}
this.paddingTop = value + "px";
},
enumerable: true,
configurable: true
});
Object.defineProperty(Control.prototype, "paddingBottom", {
/**
* Gets or sets a value indicating the padding to use on the bottom of the control
* @see http://doc.babylonjs.com/how_to/gui#position-and-size
*/
get: function () {
return this._paddingBottom.toString(this._host);
},
set: function (value) {
if (this._paddingBottom.fromString(value)) {
this._markAsDirty();
}
},
enumerable: true,
configurable: true
});
Object.defineProperty(Control.prototype, "paddingBottomInPixels", {
/**
* Gets or sets a value indicating the padding in pixels to use on the bottom of the control
* @see http://doc.babylonjs.com/how_to/gui#position-and-size
*/
get: function () {
return this._paddingBottom.getValueInPixel(this._host, this._cachedParentMeasure.height);
},
set: function (value) {
if (isNaN(value)) {
return;
}
this.paddingBottom = value + "px";
},
enumerable: true,
configurable: true
});
Object.defineProperty(Control.prototype, "left", {
/**
* Gets or sets a value indicating the left coordinate of the control
* @see http://doc.babylonjs.com/how_to/gui#position-and-size
*/
get: function () {
return this._left.toString(this._host);
},
set: function (value) {
if (this._left.fromString(value)) {
this._markAsDirty();
}
},
enumerable: true,
configurable: true
});
Object.defineProperty(Control.prototype, "leftInPixels", {
/**
* Gets or sets a value indicating the left coordinate in pixels of the control
* @see http://doc.babylonjs.com/how_to/gui#position-and-size
*/
get: function () {
return this._left.getValueInPixel(this._host, this._cachedParentMeasure.width);
},
set: function (value) {
if (isNaN(value)) {
return;
}
this.left = value + "px";
},
enumerable: true,
configurable: true
});
Object.defineProperty(Control.prototype, "top", {
/**
* Gets or sets a value indicating the top coordinate of the control
* @see http://doc.babylonjs.com/how_to/gui#position-and-size
*/
get: function () {
return this._top.toString(this._host);
},
set: function (value) {
if (this._top.fromString(value)) {
this._markAsDirty();
}
},
enumerable: true,
configurable: true
});
Object.defineProperty(Control.prototype, "topInPixels", {
/**
* Gets or sets a value indicating the top coordinate in pixels of the control
* @see http://doc.babylonjs.com/how_to/gui#position-and-size
*/
get: function () {
return this._top.getValueInPixel(this._host, this._cachedParentMeasure.height);
},
set: function (value) {
if (isNaN(value)) {
return;
}
this.top = value + "px";
},
enumerable: true,
configurable: true
});
Object.defineProperty(Control.prototype, "linkOffsetX", {
/**
* Gets or sets a value indicating the offset on X axis to the linked mesh
* @see http://doc.babylonjs.com/how_to/gui#tracking-positions
*/
get: function () {
return this._linkOffsetX.toString(this._host);
},
set: function (value) {
if (this._linkOffsetX.fromString(value)) {
this._markAsDirty();
}
},
enumerable: true,
configurable: true
});
Object.defineProperty(Control.prototype, "linkOffsetXInPixels", {
/**
* Gets or sets a value indicating the offset in pixels on X axis to the linked mesh
* @see http://doc.babylonjs.com/how_to/gui#tracking-positions
*/
get: function () {
return this._linkOffsetX.getValueInPixel(this._host, this._cachedParentMeasure.width);
},
set: function (value) {
if (isNaN(value)) {
return;
}
this.linkOffsetX = value + "px";
},
enumerable: true,
configurable: true
});
Object.defineProperty(Control.prototype, "linkOffsetY", {
/**
* Gets or sets a value indicating the offset on Y axis to the linked mesh
* @see http://doc.babylonjs.com/how_to/gui#tracking-positions
*/
get: function () {
return this._linkOffsetY.toString(this._host);
},
set: function (value) {
if (this._linkOffsetY.fromString(value)) {
this._markAsDirty();
}
},
enumerable: true,
configurable: true
});
Object.defineProperty(Control.prototype, "linkOffsetYInPixels", {
/**
* Gets or sets a value indicating the offset in pixels on Y axis to the linked mesh
* @see http://doc.babylonjs.com/how_to/gui#tracking-positions
*/
get: function () {
return this._linkOffsetY.getValueInPixel(this._host, this._cachedParentMeasure.height);
},
set: function (value) {
if (isNaN(value)) {
return;
}
this.linkOffsetY = value + "px";
},
enumerable: true,
configurable: true
});
Object.defineProperty(Control.prototype, "centerX", {
/** Gets the center coordinate on X axis */
get: function () {
return this._currentMeasure.left + this._currentMeasure.width / 2;
},
enumerable: true,
configurable: true
});
Object.defineProperty(Control.prototype, "centerY", {
/** Gets the center coordinate on Y axis */
get: function () {
return this._currentMeasure.top + this._currentMeasure.height / 2;
},
enumerable: true,
configurable: true
});
Object.defineProperty(Control.prototype, "isEnabled", {
/** Gets or sets if control is Enabled*/
get: function () {
return this._isEnabled;
},
set: function (value) {
if (this._isEnabled === value) {
return;
}
this._isEnabled = value;
this._markAsDirty();
},
enumerable: true,
configurable: true
});
Object.defineProperty(Control.prototype, "disabledColor", {
/** Gets or sets background color of control if it's disabled*/
get: function () {
return this._disabledColor;
},
set: function (value) {
if (this._disabledColor === value) {
return;
}
this._disabledColor = value;
this._markAsDirty();
},
enumerable: true,
configurable: true
});
/** @hidden */
Control.prototype._getTypeName = function () {
return "Control";
};
/**
* Gets the first ascendant in the hierarchy of the given type
* @param className defines the required type
* @returns the ascendant or null if not found
*/
Control.prototype.getAscendantOfClass = function (className) {
if (!this.parent) {
return null;
}
if (this.parent.getClassName() === className) {
return this.parent;
}
return this.parent.getAscendantOfClass(className);
};
/** @hidden */
Control.prototype._resetFontCache = function () {
this._fontSet = true;
this._markAsDirty();
};
/**
* Determines if a container is an ascendant of the current control
* @param container defines the container to look for
* @returns true if the container is one of the ascendant of the control
*/
Control.prototype.isAscendant = function (container) {
if (!this.parent) {
return false;
}
if (this.parent === container) {
return true;
}
return this.parent.isAscendant(container);
};
/**
* Gets coordinates in local control space
* @param globalCoordinates defines the coordinates to transform
* @returns the new coordinates in local space
*/
Control.prototype.getLocalCoordinates = function (globalCoordinates) {
var result = babylonjs_Misc_observable__WEBPACK_IMPORTED_MODULE_0__["Vector2"].Zero();
this.getLocalCoordinatesToRef(globalCoordinates, result);
return result;
};
/**
* Gets coordinates in local control space
* @param globalCoordinates defines the coordinates to transform
* @param result defines the target vector2 where to store the result
* @returns the current control
*/
Control.prototype.getLocalCoordinatesToRef = function (globalCoordinates, result) {
result.x = globalCoordinates.x - this._currentMeasure.left;
result.y = globalCoordinates.y - this._currentMeasure.top;
return this;
};
/**
* Gets coordinates in parent local control space
* @param globalCoordinates defines the coordinates to transform
* @returns the new coordinates in parent local space
*/
Control.prototype.getParentLocalCoordinates = function (globalCoordinates) {
var result = babylonjs_Misc_observable__WEBPACK_IMPORTED_MODULE_0__["Vector2"].Zero();
result.x = globalCoordinates.x - this._cachedParentMeasure.left;
result.y = globalCoordinates.y - this._cachedParentMeasure.top;
return result;
};
/**
* Move the current control to a vector3 position projected onto the screen.
* @param position defines the target position
* @param scene defines the hosting scene
*/
Control.prototype.moveToVector3 = function (position, scene) {
if (!this._host || this.parent !== this._host._rootContainer) {
babylonjs_Misc_observable__WEBPACK_IMPORTED_MODULE_0__["Tools"].Error("Cannot move a control to a vector3 if the control is not at root level");
return;
}
this.horizontalAlignment = Control.HORIZONTAL_ALIGNMENT_LEFT;
this.verticalAlignment = Control.VERTICAL_ALIGNMENT_TOP;
var globalViewport = this._host._getGlobalViewport(scene);
var projectedPosition = babylonjs_Misc_observable__WEBPACK_IMPORTED_MODULE_0__["Vector3"].Project(position, babylonjs_Misc_observable__WEBPACK_IMPORTED_MODULE_0__["Matrix"].Identity(), scene.getTransformMatrix(), globalViewport);
this._moveToProjectedPosition(projectedPosition);
if (projectedPosition.z < 0 || projectedPosition.z > 1) {
this.notRenderable = true;
return;
}
this.notRenderable = false;
};
/** @hidden */
Control.prototype._getDescendants = function (results, directDescendantsOnly, predicate) {
if (directDescendantsOnly === void 0) { directDescendantsOnly = false; }
// Do nothing by default
};
/**
* Will return all controls that have this control as ascendant
* @param directDescendantsOnly defines if true only direct descendants of 'this' will be considered, if false direct and also indirect (children of children, an so on in a recursive manner) descendants of 'this' will be considered
* @param predicate defines an optional predicate that will be called on every evaluated child, the predicate must return true for a given child to be part of the result, otherwise it will be ignored
* @return all child controls
*/
Control.prototype.getDescendants = function (directDescendantsOnly, predicate) {
var results = new Array();
this._getDescendants(results, directDescendantsOnly, predicate);
return results;
};
/**
* Link current control with a target mesh
* @param mesh defines the mesh to link with
* @see http://doc.babylonjs.com/how_to/gui#tracking-positions
*/
Control.prototype.linkWithMesh = function (mesh) {
if (!this._host || this.parent && this.parent !== this._host._rootContainer) {
if (mesh) {
babylonjs_Misc_observable__WEBPACK_IMPORTED_MODULE_0__["Tools"].Error("Cannot link a control to a mesh if the control is not at root level");
}
return;
}
var index = this._host._linkedControls.indexOf(this);
if (index !== -1) {
this._linkedMesh = mesh;
if (!mesh) {
this._host._linkedControls.splice(index, 1);
}
return;
}
else if (!mesh) {
return;
}
this.horizontalAlignment = Control.HORIZONTAL_ALIGNMENT_LEFT;
this.verticalAlignment = Control.VERTICAL_ALIGNMENT_TOP;
this._linkedMesh = mesh;
this._host._linkedControls.push(this);
};
/** @hidden */
Control.prototype._moveToProjectedPosition = function (projectedPosition) {
var oldLeft = this._left.getValue(this._host);
var oldTop = this._top.getValue(this._host);
var newLeft = ((projectedPosition.x + this._linkOffsetX.getValue(this._host)) - this._currentMeasure.width / 2);
var newTop = ((projectedPosition.y + this._linkOffsetY.getValue(this._host)) - this._currentMeasure.height / 2);
if (this._left.ignoreAdaptiveScaling && this._top.ignoreAdaptiveScaling) {
if (Math.abs(newLeft - oldLeft) < 0.5) {
newLeft = oldLeft;
}
if (Math.abs(newTop - oldTop) < 0.5) {
newTop = oldTop;
}
}
this.left = newLeft + "px";
this.top = newTop + "px";
this._left.ignoreAdaptiveScaling = true;
this._top.ignoreAdaptiveScaling = true;
this._markAsDirty();
};
/** @hidden */
Control.prototype._offsetLeft = function (offset) {
this._isDirty = true;
this._currentMeasure.left += offset;
};
/** @hidden */
Control.prototype._offsetTop = function (offset) {
this._isDirty = true;
this._currentMeasure.top += offset;
};
/** @hidden */
Control.prototype._markMatrixAsDirty = function () {
this._isMatrixDirty = true;
this._flagDescendantsAsMatrixDirty();
};
/** @hidden */
Control.prototype._flagDescendantsAsMatrixDirty = function () {
// No child
};
/** @hidden */
Control.prototype._intersectsRect = function (rect) {
// Rotate the control's current measure into local space and check if it intersects the passed in rectangle
this._currentMeasure.transformToRef(this._transformMatrix, this._tmpMeasureA);
if (this._tmpMeasureA.left >= rect.left + rect.width) {
return false;
}
if (this._tmpMeasureA.top >= rect.top + rect.height) {
return false;
}
if (this._tmpMeasureA.left + this._tmpMeasureA.width <= rect.left) {
return false;
}
if (this._tmpMeasureA.top + this._tmpMeasureA.height <= rect.top) {
return false;
}
return true;
};
/** @hidden */
Control.prototype.invalidateRect = function () {
this._transform();
if (this.host && this.host.useInvalidateRectOptimization) {
// Rotate by transform to get the measure transformed to global space
this._currentMeasure.transformToRef(this._transformMatrix, this._tmpMeasureA);
// get the boudning box of the current measure and last frames measure in global space and invalidate it
// the previous measure is used to properly clear a control that is scaled down
_measure__WEBPACK_IMPORTED_MODULE_2__["Measure"].CombineToRef(this._tmpMeasureA, this._prevCurrentMeasureTransformedIntoGlobalSpace, this._tmpMeasureA);
if (this.shadowBlur || this.shadowOffsetX || this.shadowOffsetY) {
// Expand rect based on shadows
var shadowOffsetX = this.shadowOffsetX;
var shadowOffsetY = this.shadowOffsetY;
var shadowBlur = this.shadowBlur;
var leftShadowOffset = Math.min(Math.min(shadowOffsetX, 0) - shadowBlur * 2, 0);
var rightShadowOffset = Math.max(Math.max(shadowOffsetX, 0) + shadowBlur * 2, 0);
var topShadowOffset = Math.min(Math.min(shadowOffsetY, 0) - shadowBlur * 2, 0);
var bottomShadowOffset = Math.max(Math.max(shadowOffsetY, 0) + shadowBlur * 2, 0);
this.host.invalidateRect(Math.floor(this._tmpMeasureA.left + leftShadowOffset), Math.floor(this._tmpMeasureA.top + topShadowOffset), Math.ceil(this._tmpMeasureA.left + this._tmpMeasureA.width + rightShadowOffset), Math.ceil(this._tmpMeasureA.top + this._tmpMeasureA.height + bottomShadowOffset));
}
else {
this.host.invalidateRect(Math.floor(this._tmpMeasureA.left), Math.floor(this._tmpMeasureA.top), Math.ceil(this._tmpMeasureA.left + this._tmpMeasureA.width), Math.ceil(this._tmpMeasureA.top + this._tmpMeasureA.height));
}
}
};
/** @hidden */
Control.prototype._markAsDirty = function (force) {
if (force === void 0) { force = false; }
if (!this._isVisible && !force) {
return;
}
this._isDirty = true;
// Redraw only this rectangle
if (this._host) {
this._host.markAsDirty();
}
};
/** @hidden */
Control.prototype._markAllAsDirty = function () {
this._markAsDirty();
if (this._font) {
this._prepareFont();
}
};
/** @hidden */
Control.prototype._link = function (host) {
this._host = host;
if (this._host) {
this.uniqueId = this._host.getScene().getUniqueId();
}
};
/** @hidden */
Control.prototype._transform = function (context) {
if (!this._isMatrixDirty && this._scaleX === 1 && this._scaleY === 1 && this._rotation === 0) {
return;
}
// postTranslate
var offsetX = this._currentMeasure.width * this._transformCenterX + this._currentMeasure.left;
var offsetY = this._currentMeasure.height * this._transformCenterY + this._currentMeasure.top;
if (context) {
context.translate(offsetX, offsetY);
// rotate
context.rotate(this._rotation);
// scale
context.scale(this._scaleX, this._scaleY);
// preTranslate
context.translate(-offsetX, -offsetY);
}
// Need to update matrices?
if (this._isMatrixDirty || this._cachedOffsetX !== offsetX || this._cachedOffsetY !== offsetY) {
this._cachedOffsetX = offsetX;
this._cachedOffsetY = offsetY;
this._isMatrixDirty = false;
this._flagDescendantsAsMatrixDirty();
_math2D__WEBPACK_IMPORTED_MODULE_3__["Matrix2D"].ComposeToRef(-offsetX, -offsetY, this._rotation, this._scaleX, this._scaleY, this.parent ? this.parent._transformMatrix : null, this._transformMatrix);
this._transformMatrix.invertToRef(this._invertTransformMatrix);
}
};
/** @hidden */
Control.prototype._renderHighlight = function (context) {
if (!this.isHighlighted) {
return;
}
context.save();
context.strokeStyle = "#4affff";
context.lineWidth = 2;
this._renderHighlightSpecific(context);
context.restore();
};
/** @hidden */
Control.prototype._renderHighlightSpecific = function (context) {
context.strokeRect(this._currentMeasure.left, this._currentMeasure.top, this._currentMeasure.width, this._currentMeasure.height);
};
/** @hidden */
Control.prototype._applyStates = function (context) {
if (this._isFontSizeInPercentage) {
this._fontSet = true;
}
if (this._fontSet) {
this._prepareFont();
this._fontSet = false;
}
if (this._font) {
context.font = this._font;
}
if (this._color) {
context.fillStyle = this._color;
}
if (Control.AllowAlphaInheritance) {
context.globalAlpha *= this._alpha;
}
else if (this._alphaSet) {
context.globalAlpha = this.parent ? this.parent.alpha * this._alpha : this._alpha;
}
};
/** @hidden */
Control.prototype._layout = function (parentMeasure, context) {
if (!this.isDirty && (!this.isVisible || this.notRenderable)) {
return false;
}
if (this._isDirty || !this._cachedParentMeasure.isEqualsTo(parentMeasure)) {
this._currentMeasure.transformToRef(this._transformMatrix, this._prevCurrentMeasureTransformedIntoGlobalSpace);
context.save();
this._applyStates(context);
var rebuildCount = 0;
do {
this._rebuildLayout = false;
this._processMeasures(parentMeasure, context);
rebuildCount++;
} while (this._rebuildLayout && rebuildCount < 3);
if (rebuildCount >= 3) {
babylonjs_Misc_observable__WEBPACK_IMPORTED_MODULE_0__["Logger"].Error("Layout cycle detected in GUI (Control name=" + this.name + ", uniqueId=" + this.uniqueId + ")");
}
context.restore();
this.invalidateRect();
this._evaluateClippingState(parentMeasure);
}
this._wasDirty = this._isDirty;
this._isDirty = false;
return true;
};
/** @hidden */
Control.prototype._processMeasures = function (parentMeasure, context) {
this._currentMeasure.copyFrom(parentMeasure);
// Let children take some pre-measurement actions
this._preMeasure(parentMeasure, context);
this._measure();
this._computeAlignment(parentMeasure, context);
// Convert to int values
this._currentMeasure.left = this._currentMeasure.left | 0;
this._currentMeasure.top = this._currentMeasure.top | 0;
this._currentMeasure.width = this._currentMeasure.width | 0;
this._currentMeasure.height = this._currentMeasure.height | 0;
// Let children add more features
this._additionalProcessing(parentMeasure, context);
this._cachedParentMeasure.copyFrom(parentMeasure);
if (this.onDirtyObservable.hasObservers()) {
this.onDirtyObservable.notifyObservers(this);
}
};
Control.prototype._evaluateClippingState = function (parentMeasure) {
if (this.parent && this.parent.clipChildren) {
// Early clip
if (this._currentMeasure.left > parentMeasure.left + parentMeasure.width) {
this._isClipped = true;
return;
}
if (this._currentMeasure.left + this._currentMeasure.width < parentMeasure.left) {
this._isClipped = true;
return;
}
if (this._currentMeasure.top > parentMeasure.top + parentMeasure.height) {
this._isClipped = true;
return;
}
if (this._currentMeasure.top + this._currentMeasure.height < parentMeasure.top) {
this._isClipped = true;
return;
}
}
this._isClipped = false;
};
/** @hidden */
Control.prototype._measure = function () {
// Width / Height
if (this._width.isPixel) {
this._currentMeasure.width = this._width.getValue(this._host);
}
else {
this._currentMeasure.width *= this._width.getValue(this._host);
}
if (this._height.isPixel) {
this._currentMeasure.height = this._height.getValue(this._host);
}
else {
this._currentMeasure.height *= this._height.getValue(this._host);
}
};
/** @hidden */
Control.prototype._computeAlignment = function (parentMeasure, context) {
var width = this._currentMeasure.width;
var height = this._currentMeasure.height;
var parentWidth = parentMeasure.width;
var parentHeight = parentMeasure.height;
// Left / top
var x = 0;
var y = 0;
switch (this.horizontalAlignment) {
case Control.HORIZONTAL_ALIGNMENT_LEFT:
x = 0;
break;
case Control.HORIZONTAL_ALIGNMENT_RIGHT:
x = parentWidth - width;
break;
case Control.HORIZONTAL_ALIGNMENT_CENTER:
x = (parentWidth - width) / 2;
break;
}
switch (this.verticalAlignment) {
case Control.VERTICAL_ALIGNMENT_TOP:
y = 0;
break;
case Control.VERTICAL_ALIGNMENT_BOTTOM:
y = parentHeight - height;
break;
case Control.VERTICAL_ALIGNMENT_CENTER:
y = (parentHeight - height) / 2;
break;
}
if (this._paddingLeft.isPixel) {
this._currentMeasure.left += this._paddingLeft.getValue(this._host);
this._currentMeasure.width -= this._paddingLeft.getValue(this._host);
}
else {
this._currentMeasure.left += parentWidth * this._paddingLeft.getValue(this._host);
this._currentMeasure.width -= parentWidth * this._paddingLeft.getValue(this._host);
}
if (this._paddingRight.isPixel) {
this._currentMeasure.width -= this._paddingRight.getValue(this._host);
}
else {
this._currentMeasure.width -= parentWidth * this._paddingRight.getValue(this._host);
}
if (this._paddingTop.isPixel) {
this._currentMeasure.top += this._paddingTop.getValue(this._host);
this._currentMeasure.height -= this._paddingTop.getValue(this._host);
}
else {
this._currentMeasure.top += parentHeight * this._paddingTop.getValue(this._host);
this._currentMeasure.height -= parentHeight * this._paddingTop.getValue(this._host);
}
if (this._paddingBottom.isPixel) {
this._currentMeasure.height -= this._paddingBottom.getValue(this._host);
}
else {
this._currentMeasure.height -= parentHeight * this._paddingBottom.getValue(this._host);
}
if (this._left.isPixel) {
this._currentMeasure.left += this._left.getValue(this._host);
}
else {
this._currentMeasure.left += parentWidth * this._left.getValue(this._host);
}
if (this._top.isPixel) {
this._currentMeasure.top += this._top.getValue(this._host);
}
else {
this._currentMeasure.top += parentHeight * this._top.getValue(this._host);
}
this._currentMeasure.left += x;
this._currentMeasure.top += y;
};
/** @hidden */
Control.prototype._preMeasure = function (parentMeasure, context) {
// Do nothing
};
/** @hidden */
Control.prototype._additionalProcessing = function (parentMeasure, context) {
// Do nothing
};
/** @hidden */
Control.prototype._clipForChildren = function (context) {
// DO nothing
};
Control.prototype._clip = function (context, invalidatedRectangle) {
context.beginPath();
Control._ClipMeasure.copyFrom(this._currentMeasure);
if (invalidatedRectangle) {
// Rotate the invalidated rect into the control's space
invalidatedRectangle.transformToRef(this._invertTransformMatrix, this._tmpMeasureA);
// Get the intersection of the rect in context space and the current context
var intersection = new _measure__WEBPACK_IMPORTED_MODULE_2__["Measure"](0, 0, 0, 0);
intersection.left = Math.max(this._tmpMeasureA.left, this._currentMeasure.left);
intersection.top = Math.max(this._tmpMeasureA.top, this._currentMeasure.top);
intersection.width = Math.min(this._tmpMeasureA.left + this._tmpMeasureA.width, this._currentMeasure.left + this._currentMeasure.width) - intersection.left;
intersection.height = Math.min(this._tmpMeasureA.top + this._tmpMeasureA.height, this._currentMeasure.top + this._currentMeasure.height) - intersection.top;
Control._ClipMeasure.copyFrom(intersection);
}
if (this.shadowBlur || this.shadowOffsetX || this.shadowOffsetY) {
var shadowOffsetX = this.shadowOffsetX;
var shadowOffsetY = this.shadowOffsetY;
var shadowBlur = this.shadowBlur;
var leftShadowOffset = Math.min(Math.min(shadowOffsetX, 0) - shadowBlur * 2, 0);
var rightShadowOffset = Math.max(Math.max(shadowOffsetX, 0) + shadowBlur * 2, 0);
var topShadowOffset = Math.min(Math.min(shadowOffsetY, 0) - shadowBlur * 2, 0);
var bottomShadowOffset = Math.max(Math.max(shadowOffsetY, 0) + shadowBlur * 2, 0);
context.rect(Control._ClipMeasure.left + leftShadowOffset, Control._ClipMeasure.top + topShadowOffset, Control._ClipMeasure.width + rightShadowOffset - leftShadowOffset, Control._ClipMeasure.height + bottomShadowOffset - topShadowOffset);
}
else {
context.rect(Control._ClipMeasure.left, Control._ClipMeasure.top, Control._ClipMeasure.width, Control._ClipMeasure.height);
}
context.clip();
};
/** @hidden */
Control.prototype._render = function (context, invalidatedRectangle) {
if (!this.isVisible || this.notRenderable || this._isClipped) {
this._isDirty = false;
return false;
}
context.save();
this._applyStates(context);
// Transform
this._transform(context);
// Clip
if (this.clipContent) {
this._clip(context, invalidatedRectangle);
}
if (this.onBeforeDrawObservable.hasObservers()) {
this.onBeforeDrawObservable.notifyObservers(this);
}
if (this.useBitmapCache && !this._wasDirty && this._cacheData) {
context.putImageData(this._cacheData, this._currentMeasure.left, this._currentMeasure.top);
}
else {
this._draw(context, invalidatedRectangle);
}
if (this.useBitmapCache && this._wasDirty) {
this._cacheData = context.getImageData(this._currentMeasure.left, this._currentMeasure.top, this._currentMeasure.width, this._currentMeasure.height);
}
this._renderHighlight(context);
if (this.onAfterDrawObservable.hasObservers()) {
this.onAfterDrawObservable.notifyObservers(this);
}
context.restore();
return true;
};
/** @hidden */
Control.prototype._draw = function (context, invalidatedRectangle) {
// Do nothing
};
/**
* Tests if a given coordinates belong to the current control
* @param x defines x coordinate to test
* @param y defines y coordinate to test
* @returns true if the coordinates are inside the control
*/
Control.prototype.contains = function (x, y) {
// Invert transform
this._invertTransformMatrix.transformCoordinates(x, y, this._transformedPosition);
x = this._transformedPosition.x;
y = this._transformedPosition.y;
// Check
if (x < this._currentMeasure.left) {
return false;
}
if (x > this._currentMeasure.left + this._currentMeasure.width) {
return false;
}
if (y < this._currentMeasure.top) {
return false;
}
if (y > this._currentMeasure.top + this._currentMeasure.height) {
return false;
}
if (this.isPointerBlocker) {
this._host._shouldBlockPointer = true;
}
return true;
};
/** @hidden */
Control.prototype._processPicking = function (x, y, type, pointerId, buttonIndex) {
if (!this._isEnabled) {
return false;
}
if (!this.isHitTestVisible || !this.isVisible || this._doNotRender) {
return false;
}
if (!this.contains(x, y)) {
return false;
}
this._processObservables(type, x, y, pointerId, buttonIndex);
return true;
};
/** @hidden */
Control.prototype._onPointerMove = function (target, coordinates, pointerId) {
var canNotify = this.onPointerMoveObservable.notifyObservers(coordinates, -1, target, this);
if (canNotify && this.parent != null) {
this.parent._onPointerMove(target, coordinates, pointerId);
}
};
/** @hidden */
Control.prototype._onPointerEnter = function (target) {
if (!this._isEnabled) {
return false;
}
if (this._enterCount > 0) {
return false;
}
if (this._enterCount === -1) { // -1 is for touch input, we are now sure we are with a mouse or pencil
this._enterCount = 0;
}
this._enterCount++;
var canNotify = this.onPointerEnterObservable.notifyObservers(this, -1, target, this);
if (canNotify && this.parent != null) {
this.parent._onPointerEnter(target);
}
return true;
};
/** @hidden */
Control.prototype._onPointerOut = function (target, force) {
if (force === void 0) { force = false; }
if (!force && (!this._isEnabled || target === this)) {
return;
}
this._enterCount = 0;
var canNotify = true;
if (!target.isAscendant(this)) {
canNotify = this.onPointerOutObservable.notifyObservers(this, -1, target, this);
}
if (canNotify && this.parent != null) {
this.parent._onPointerOut(target, force);
}
};
/** @hidden */
Control.prototype._onPointerDown = function (target, coordinates, pointerId, buttonIndex) {
// Prevent pointerout to lose control context.
// Event redundancy is checked inside the function.
this._onPointerEnter(this);
if (this._downCount !== 0) {
return false;
}
this._downCount++;
this._downPointerIds[pointerId] = true;
var canNotify = this.onPointerDownObservable.notifyObservers(new _math2D__WEBPACK_IMPORTED_MODULE_3__["Vector2WithInfo"](coordinates, buttonIndex), -1, target, this);
if (canNotify && this.parent != null) {
this.parent._onPointerDown(target, coordinates, pointerId, buttonIndex);
}
return true;
};
/** @hidden */
Control.prototype._onPointerUp = function (target, coordinates, pointerId, buttonIndex, notifyClick) {
if (!this._isEnabled) {
return;
}
this._downCount = 0;
delete this._downPointerIds[pointerId];
var canNotifyClick = notifyClick;
if (notifyClick && (this._enterCount > 0 || this._enterCount === -1)) {
canNotifyClick = this.onPointerClickObservable.notifyObservers(new _math2D__WEBPACK_IMPORTED_MODULE_3__["Vector2WithInfo"](coordinates, buttonIndex), -1, target, this);
}
var canNotify = this.onPointerUpObservable.notifyObservers(new _math2D__WEBPACK_IMPORTED_MODULE_3__["Vector2WithInfo"](coordinates, buttonIndex), -1, target, this);
if (canNotify && this.parent != null) {
this.parent._onPointerUp(target, coordinates, pointerId, buttonIndex, canNotifyClick);
}
};
/** @hidden */
Control.prototype._forcePointerUp = function (pointerId) {
if (pointerId === void 0) { pointerId = null; }
if (pointerId !== null) {
this._onPointerUp(this, babylonjs_Misc_observable__WEBPACK_IMPORTED_MODULE_0__["Vector2"].Zero(), pointerId, 0, true);
}
else {
for (var key in this._downPointerIds) {
this._onPointerUp(this, babylonjs_Misc_observable__WEBPACK_IMPORTED_MODULE_0__["Vector2"].Zero(), +key, 0, true);
}
}
};
/** @hidden */
Control.prototype._processObservables = function (type, x, y, pointerId, buttonIndex) {
if (!this._isEnabled) {
return false;
}
this._dummyVector2.copyFromFloats(x, y);
if (type === babylonjs_Misc_observable__WEBPACK_IMPORTED_MODULE_0__["PointerEventTypes"].POINTERMOVE) {
this._onPointerMove(this, this._dummyVector2, pointerId);
var previousControlOver = this._host._lastControlOver[pointerId];
if (previousControlOver && previousControlOver !== this) {
previousControlOver._onPointerOut(this);
}
if (previousControlOver !== this) {
this._onPointerEnter(this);
}
this._host._lastControlOver[pointerId] = this;
return true;
}
if (type === babylonjs_Misc_observable__WEBPACK_IMPORTED_MODULE_0__["PointerEventTypes"].POINTERDOWN) {
this._onPointerDown(this, this._dummyVector2, pointerId, buttonIndex);
this._host._registerLastControlDown(this, pointerId);
this._host._lastPickedControl = this;
return true;
}
if (type === babylonjs_Misc_observable__WEBPACK_IMPORTED_MODULE_0__["PointerEventTypes"].POINTERUP) {
if (this._host._lastControlDown[pointerId]) {
this._host._lastControlDown[pointerId]._onPointerUp(this, this._dummyVector2, pointerId, buttonIndex, true);
}
delete this._host._lastControlDown[pointerId];
return true;
}
return false;
};
Control.prototype._prepareFont = function () {
if (!this._font && !this._fontSet) {
return;
}
if (this._style) {
this._font = this._style.fontStyle + " " + this._style.fontWeight + " " + this.fontSizeInPixels + "px " + this._style.fontFamily;
}
else {
this._font = this._fontStyle + " " + this._fontWeight + " " + this.fontSizeInPixels + "px " + this._fontFamily;
}
this._fontOffset = Control._GetFontOffset(this._font);
};
/** Releases associated resources */
Control.prototype.dispose = function () {
this.onDirtyObservable.clear();
this.onBeforeDrawObservable.clear();
this.onAfterDrawObservable.clear();
this.onPointerDownObservable.clear();
this.onPointerEnterObservable.clear();
this.onPointerMoveObservable.clear();
this.onPointerOutObservable.clear();
this.onPointerUpObservable.clear();
this.onPointerClickObservable.clear();
if (this._styleObserver && this._style) {
this._style.onChangedObservable.remove(this._styleObserver);
this._styleObserver = null;
}
if (this.parent) {
this.parent.removeControl(this);
this.parent = null;
}
if (this._host) {
var index = this._host._linkedControls.indexOf(this);
if (index > -1) {
this.linkWithMesh(null);
}
}
};
Object.defineProperty(Control, "HORIZONTAL_ALIGNMENT_LEFT", {
/** HORIZONTAL_ALIGNMENT_LEFT */
get: function () {
return Control._HORIZONTAL_ALIGNMENT_LEFT;
},
enumerable: true,
configurable: true
});
Object.defineProperty(Control, "HORIZONTAL_ALIGNMENT_RIGHT", {
/** HORIZONTAL_ALIGNMENT_RIGHT */
get: function () {
return Control._HORIZONTAL_ALIGNMENT_RIGHT;
},
enumerable: true,
configurable: true
});
Object.defineProperty(Control, "HORIZONTAL_ALIGNMENT_CENTER", {
/** HORIZONTAL_ALIGNMENT_CENTER */
get: function () {
return Control._HORIZONTAL_ALIGNMENT_CENTER;
},
enumerable: true,
configurable: true
});
Object.defineProperty(Control, "VERTICAL_ALIGNMENT_TOP", {
/** VERTICAL_ALIGNMENT_TOP */
get: function () {
return Control._VERTICAL_ALIGNMENT_TOP;
},
enumerable: true,
configurable: true
});
Object.defineProperty(Control, "VERTICAL_ALIGNMENT_BOTTOM", {
/** VERTICAL_ALIGNMENT_BOTTOM */
get: function () {
return Control._VERTICAL_ALIGNMENT_BOTTOM;
},
enumerable: true,
configurable: true
});
Object.defineProperty(Control, "VERTICAL_ALIGNMENT_CENTER", {
/** VERTICAL_ALIGNMENT_CENTER */
get: function () {
return Control._VERTICAL_ALIGNMENT_CENTER;
},
enumerable: true,
configurable: true
});
/** @hidden */
Control._GetFontOffset = function (font) {
if (Control._FontHeightSizes[font]) {
return Control._FontHeightSizes[font];
}
var text = document.createElement("span");
text.innerHTML = "Hg";
text.style.font = font;
var block = document.createElement("div");
block.style.display = "inline-block";
block.style.width = "1px";
block.style.height = "0px";
block.style.verticalAlign = "bottom";
var div = document.createElement("div");
div.appendChild(text);
div.appendChild(block);
document.body.appendChild(div);
var fontAscent = 0;
var fontHeight = 0;
try {
fontHeight = block.getBoundingClientRect().top - text.getBoundingClientRect().top;
block.style.verticalAlign = "baseline";
fontAscent = block.getBoundingClientRect().top - text.getBoundingClientRect().top;
}
finally {
document.body.removeChild(div);
}
var result = { ascent: fontAscent, height: fontHeight, descent: fontHeight - fontAscent };
Control._FontHeightSizes[font] = result;
return result;
};
/** @hidden */
Control.drawEllipse = function (x, y, width, height, context) {
context.translate(x, y);
context.scale(width, height);
context.beginPath();
context.arc(0, 0, 1, 0, 2 * Math.PI);
context.closePath();
context.scale(1 / width, 1 / height);
context.translate(-x, -y);
};
/**
* Gets or sets a boolean indicating if alpha must be an inherited value (false by default)
*/
Control.AllowAlphaInheritance = false;
Control._ClipMeasure = new _measure__WEBPACK_IMPORTED_MODULE_2__["Measure"](0, 0, 0, 0);
// Statics
Control._HORIZONTAL_ALIGNMENT_LEFT = 0;
Control._HORIZONTAL_ALIGNMENT_RIGHT = 1;
Control._HORIZONTAL_ALIGNMENT_CENTER = 2;
Control._VERTICAL_ALIGNMENT_TOP = 0;
Control._VERTICAL_ALIGNMENT_BOTTOM = 1;
Control._VERTICAL_ALIGNMENT_CENTER = 2;
Control._FontHeightSizes = {};
/**
* Creates a stack panel that can be used to render headers
* @param control defines the control to associate with the header
* @param text defines the text of the header
* @param size defines the size of the header
* @param options defines options used to configure the header
* @returns a new StackPanel
* @ignore
* @hidden
*/
Control.AddHeader = function () { };
return Control;
}());
/***/ }),
/***/ "./2D/controls/displayGrid.ts":
/*!************************************!*\
!*** ./2D/controls/displayGrid.ts ***!
\************************************/
/*! exports provided: DisplayGrid */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "DisplayGrid", function() { return DisplayGrid; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../../node_modules/tslib/tslib.es6.js");
/* harmony import */ var _control__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./control */ "./2D/controls/control.ts");
/** Class used to render a grid */
var DisplayGrid = /** @class */ (function (_super) {
tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](DisplayGrid, _super);
/**
* Creates a new GridDisplayRectangle
* @param name defines the control name
*/
function DisplayGrid(name) {
var _this = _super.call(this, name) || this;
_this.name = name;
_this._cellWidth = 20;
_this._cellHeight = 20;
_this._minorLineTickness = 1;
_this._minorLineColor = "DarkGray";
_this._majorLineTickness = 2;
_this._majorLineColor = "White";
_this._majorLineFrequency = 5;
_this._background = "Black";
_this._displayMajorLines = true;
_this._displayMinorLines = true;
return _this;
}
Object.defineProperty(DisplayGrid.prototype, "displayMinorLines", {
/** Gets or sets a boolean indicating if minor lines must be rendered (true by default)) */
get: function () {
return this._displayMinorLines;
},
set: function (value) {
if (this._displayMinorLines === value) {
return;
}
this._displayMinorLines = value;
this._markAsDirty();
},
enumerable: true,
configurable: true
});
Object.defineProperty(DisplayGrid.prototype, "displayMajorLines", {
/** Gets or sets a boolean indicating if major lines must be rendered (true by default)) */
get: function () {
return this._displayMajorLines;
},
set: function (value) {
if (this._displayMajorLines === value) {
return;
}
this._displayMajorLines = value;
this._markAsDirty();
},
enumerable: true,
configurable: true
});
Object.defineProperty(DisplayGrid.prototype, "background", {
/** Gets or sets background color (Black by default) */
get: function () {
return this._background;
},
set: function (value) {
if (this._background === value) {
return;
}
this._background = value;
this._markAsDirty();
},
enumerable: true,
configurable: true
});
Object.defineProperty(DisplayGrid.prototype, "cellWidth", {
/** Gets or sets the width of each cell (20 by default) */
get: function () {
return this._cellWidth;
},
set: function (value) {
this._cellWidth = value;
this._markAsDirty();
},
enumerable: true,
configurable: true
});
Object.defineProperty(DisplayGrid.prototype, "cellHeight", {
/** Gets or sets the height of each cell (20 by default) */
get: function () {
return this._cellHeight;
},
set: function (value) {
this._cellHeight = value;
this._markAsDirty();
},
enumerable: true,
configurable: true
});
Object.defineProperty(DisplayGrid.prototype, "minorLineTickness", {
/** Gets or sets the tickness of minor lines (1 by default) */
get: function () {
return this._minorLineTickness;
},
set: function (value) {
this._minorLineTickness = value;
this._markAsDirty();
},
enumerable: true,
configurable: true
});
Object.defineProperty(DisplayGrid.prototype, "minorLineColor", {
/** Gets or sets the color of minor lines (DarkGray by default) */
get: function () {
return this._minorLineColor;
},
set: function (value) {
this._minorLineColor = value;
this._markAsDirty();
},
enumerable: true,
configurable: true
});
Object.defineProperty(DisplayGrid.prototype, "majorLineTickness", {
/** Gets or sets the tickness of major lines (2 by default) */
get: function () {
return this._majorLineTickness;
},
set: function (value) {
this._majorLineTickness = value;
this._markAsDirty();
},
enumerable: true,
configurable: true
});
Object.defineProperty(DisplayGrid.prototype, "majorLineColor", {
/** Gets or sets the color of major lines (White by default) */
get: function () {
return this._majorLineColor;
},
set: function (value) {
this._majorLineColor = value;
this._markAsDirty();
},
enumerable: true,
configurable: true
});
Object.defineProperty(DisplayGrid.prototype, "majorLineFrequency", {
/** Gets or sets the frequency of major lines (default is 1 every 5 minor lines)*/
get: function () {
return this._majorLineFrequency;
},
set: function (value) {
this._majorLineFrequency = value;
this._markAsDirty();
},
enumerable: true,
configurable: true
});
DisplayGrid.prototype._draw = function (context) {
context.save();
this._applyStates(context);
if (this._isEnabled) {
if (this._background) {
context.fillStyle = this._background;
context.fillRect(this._currentMeasure.left, this._currentMeasure.top, this._currentMeasure.width, this._currentMeasure.height);
}
var cellCountX = this._currentMeasure.width / this._cellWidth;
var cellCountY = this._currentMeasure.height / this._cellHeight;
// Minor lines
var left = this._currentMeasure.left + this._currentMeasure.width / 2;
var top_1 = this._currentMeasure.top + this._currentMeasure.height / 2;
if (this._displayMinorLines) {
context.strokeStyle = this._minorLineColor;
context.lineWidth = this._minorLineTickness;
for (var x = -cellCountX / 2; x < cellCountX / 2; x++) {
var cellX = left + x * this.cellWidth;
context.beginPath();
context.moveTo(cellX, this._currentMeasure.top);
context.lineTo(cellX, this._currentMeasure.top + this._currentMeasure.height);
context.stroke();
}
for (var y = -cellCountY / 2; y < cellCountY / 2; y++) {
var cellY = top_1 + y * this.cellHeight;
context.beginPath();
context.moveTo(this._currentMeasure.left, cellY);
context.lineTo(this._currentMeasure.left + this._currentMeasure.width, cellY);
context.stroke();
}
}
// Major lines
if (this._displayMajorLines) {
context.strokeStyle = this._majorLineColor;
context.lineWidth = this._majorLineTickness;
for (var x = -cellCountX / 2 + this._majorLineFrequency; x < cellCountX / 2; x += this._majorLineFrequency) {
var cellX = left + x * this.cellWidth;
context.beginPath();
context.moveTo(cellX, this._currentMeasure.top);
context.lineTo(cellX, this._currentMeasure.top + this._currentMeasure.height);
context.stroke();
}
for (var y = -cellCountY / 2 + this._majorLineFrequency; y < cellCountY / 2; y += this._majorLineFrequency) {
var cellY = top_1 + y * this.cellHeight;
context.moveTo(this._currentMeasure.left, cellY);
context.lineTo(this._currentMeasure.left + this._currentMeasure.width, cellY);
context.closePath();
context.stroke();
}
}
}
context.restore();
};
DisplayGrid.prototype._getTypeName = function () {
return "DisplayGrid";
};
return DisplayGrid;
}(_control__WEBPACK_IMPORTED_MODULE_1__["Control"]));
/***/ }),
/***/ "./2D/controls/ellipse.ts":
/*!********************************!*\
!*** ./2D/controls/ellipse.ts ***!
\********************************/
/*! exports provided: Ellipse */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Ellipse", function() { return Ellipse; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../../node_modules/tslib/tslib.es6.js");
/* harmony import */ var _container__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./container */ "./2D/controls/container.ts");
/* harmony import */ var _control__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./control */ "./2D/controls/control.ts");
/** Class used to create 2D ellipse containers */
var Ellipse = /** @class */ (function (_super) {
tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](Ellipse, _super);
/**
* Creates a new Ellipse
* @param name defines the control name
*/
function Ellipse(name) {
var _this = _super.call(this, name) || this;
_this.name = name;
_this._thickness = 1;
return _this;
}
Object.defineProperty(Ellipse.prototype, "thickness", {
/** Gets or sets border thickness */
get: function () {
return this._thickness;
},
set: function (value) {
if (this._thickness === value) {
return;
}
this._thickness = value;
this._markAsDirty();
},
enumerable: true,
configurable: true
});
Ellipse.prototype._getTypeName = function () {
return "Ellipse";
};
Ellipse.prototype._localDraw = function (context) {
context.save();
if (this.shadowBlur || this.shadowOffsetX || this.shadowOffsetY) {
context.shadowColor = this.shadowColor;
context.shadowBlur = this.shadowBlur;
context.shadowOffsetX = this.shadowOffsetX;
context.shadowOffsetY = this.shadowOffsetY;
}
_control__WEBPACK_IMPORTED_MODULE_2__["Control"].drawEllipse(this._currentMeasure.left + this._currentMeasure.width / 2, this._currentMeasure.top + this._currentMeasure.height / 2, this._currentMeasure.width / 2 - this._thickness / 2, this._currentMeasure.height / 2 - this._thickness / 2, context);
if (this._background) {
context.fillStyle = this._background;
context.fill();
}
if (this.shadowBlur || this.shadowOffsetX || this.shadowOffsetY) {
context.shadowBlur = 0;
context.shadowOffsetX = 0;
context.shadowOffsetY = 0;
}
if (this._thickness) {
if (this.color) {
context.strokeStyle = this.color;
}
context.lineWidth = this._thickness;
context.stroke();
}
context.restore();
};
Ellipse.prototype._additionalProcessing = function (parentMeasure, context) {
_super.prototype._additionalProcessing.call(this, parentMeasure, context);
this._measureForChildren.width -= 2 * this._thickness;
this._measureForChildren.height -= 2 * this._thickness;
this._measureForChildren.left += this._thickness;
this._measureForChildren.top += this._thickness;
};
Ellipse.prototype._clipForChildren = function (context) {
_control__WEBPACK_IMPORTED_MODULE_2__["Control"].drawEllipse(this._currentMeasure.left + this._currentMeasure.width / 2, this._currentMeasure.top + this._currentMeasure.height / 2, this._currentMeasure.width / 2, this._currentMeasure.height / 2, context);
context.clip();
};
return Ellipse;
}(_container__WEBPACK_IMPORTED_MODULE_1__["Container"]));
/***/ }),
/***/ "./2D/controls/grid.ts":
/*!*****************************!*\
!*** ./2D/controls/grid.ts ***!
\*****************************/
/*! exports provided: Grid */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Grid", function() { return Grid; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../../node_modules/tslib/tslib.es6.js");
/* harmony import */ var _container__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./container */ "./2D/controls/container.ts");
/* harmony import */ var _valueAndUnit__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../valueAndUnit */ "./2D/valueAndUnit.ts");
/* harmony import */ var _control__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./control */ "./2D/controls/control.ts");
/* harmony import */ var babylonjs_Misc_tools__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! babylonjs/Misc/tools */ "babylonjs/Misc/observable");
/* harmony import */ var babylonjs_Misc_tools__WEBPACK_IMPORTED_MODULE_4___default = /*#__PURE__*/__webpack_require__.n(babylonjs_Misc_tools__WEBPACK_IMPORTED_MODULE_4__);
/**
* Class used to create a 2D grid container
*/
var Grid = /** @class */ (function (_super) {
tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](Grid, _super);
/**
* Creates a new Grid
* @param name defines control name
*/
function Grid(name) {
var _this = _super.call(this, name) || this;
_this.name = name;
_this._rowDefinitions = new Array();
_this._columnDefinitions = new Array();
_this._cells = {};
_this._childControls = new Array();
return _this;
}
Object.defineProperty(Grid.prototype, "columnCount", {
/**
* Gets the number of columns
*/
get: function () {
return this._columnDefinitions.length;
},
enumerable: true,
configurable: true
});
Object.defineProperty(Grid.prototype, "rowCount", {
/**
* Gets the number of rows
*/
get: function () {
return this._rowDefinitions.length;
},
enumerable: true,
configurable: true
});
Object.defineProperty(Grid.prototype, "children", {
/** Gets the list of children */
get: function () {
return this._childControls;
},
enumerable: true,
configurable: true
});
Object.defineProperty(Grid.prototype, "cells", {
/** Gets the list of cells (e.g. the containers) */
get: function () {
return this._cells;
},
enumerable: true,
configurable: true
});
/**
* Gets the definition of a specific row
* @param index defines the index of the row
* @returns the row definition
*/
Grid.prototype.getRowDefinition = function (index) {
if (index < 0 || index >= this._rowDefinitions.length) {
return null;
}
return this._rowDefinitions[index];
};
/**
* Gets the definition of a specific column
* @param index defines the index of the column
* @returns the column definition
*/
Grid.prototype.getColumnDefinition = function (index) {
if (index < 0 || index >= this._columnDefinitions.length) {
return null;
}
return this._columnDefinitions[index];
};
/**
* Adds a new row to the grid
* @param height defines the height of the row (either in pixel or a value between 0 and 1)
* @param isPixel defines if the height is expressed in pixel (or in percentage)
* @returns the current grid
*/
Grid.prototype.addRowDefinition = function (height, isPixel) {
if (isPixel === void 0) { isPixel = false; }
this._rowDefinitions.push(new _valueAndUnit__WEBPACK_IMPORTED_MODULE_2__["ValueAndUnit"](height, isPixel ? _valueAndUnit__WEBPACK_IMPORTED_MODULE_2__["ValueAndUnit"].UNITMODE_PIXEL : _valueAndUnit__WEBPACK_IMPORTED_MODULE_2__["ValueAndUnit"].UNITMODE_PERCENTAGE));
this._markAsDirty();
return this;
};
/**
* Adds a new column to the grid
* @param width defines the width of the column (either in pixel or a value between 0 and 1)
* @param isPixel defines if the width is expressed in pixel (or in percentage)
* @returns the current grid
*/
Grid.prototype.addColumnDefinition = function (width, isPixel) {
if (isPixel === void 0) { isPixel = false; }
this._columnDefinitions.push(new _valueAndUnit__WEBPACK_IMPORTED_MODULE_2__["ValueAndUnit"](width, isPixel ? _valueAndUnit__WEBPACK_IMPORTED_MODULE_2__["ValueAndUnit"].UNITMODE_PIXEL : _valueAndUnit__WEBPACK_IMPORTED_MODULE_2__["ValueAndUnit"].UNITMODE_PERCENTAGE));
this._markAsDirty();
return this;
};
/**
* Update a row definition
* @param index defines the index of the row to update
* @param height defines the height of the row (either in pixel or a value between 0 and 1)
* @param isPixel defines if the weight is expressed in pixel (or in percentage)
* @returns the current grid
*/
Grid.prototype.setRowDefinition = function (index, height, isPixel) {
if (isPixel === void 0) { isPixel = false; }
if (index < 0 || index >= this._rowDefinitions.length) {
return this;
}
var current = this._rowDefinitions[index];
if (current && current.isPixel === isPixel && current.internalValue === height) {
return this;
}
this._rowDefinitions[index] = new _valueAndUnit__WEBPACK_IMPORTED_MODULE_2__["ValueAndUnit"](height, isPixel ? _valueAndUnit__WEBPACK_IMPORTED_MODULE_2__["ValueAndUnit"].UNITMODE_PIXEL : _valueAndUnit__WEBPACK_IMPORTED_MODULE_2__["ValueAndUnit"].UNITMODE_PERCENTAGE);
this._markAsDirty();
return this;
};
/**
* Update a column definition
* @param index defines the index of the column to update
* @param width defines the width of the column (either in pixel or a value between 0 and 1)
* @param isPixel defines if the width is expressed in pixel (or in percentage)
* @returns the current grid
*/
Grid.prototype.setColumnDefinition = function (index, width, isPixel) {
if (isPixel === void 0) { isPixel = false; }
if (index < 0 || index >= this._columnDefinitions.length) {
return this;
}
var current = this._columnDefinitions[index];
if (current && current.isPixel === isPixel && current.internalValue === width) {
return this;
}
this._columnDefinitions[index] = new _valueAndUnit__WEBPACK_IMPORTED_MODULE_2__["ValueAndUnit"](width, isPixel ? _valueAndUnit__WEBPACK_IMPORTED_MODULE_2__["ValueAndUnit"].UNITMODE_PIXEL : _valueAndUnit__WEBPACK_IMPORTED_MODULE_2__["ValueAndUnit"].UNITMODE_PERCENTAGE);
this._markAsDirty();
return this;
};
/**
* Gets the list of children stored in a specific cell
* @param row defines the row to check
* @param column defines the column to check
* @returns the list of controls
*/
Grid.prototype.getChildrenAt = function (row, column) {
var cell = this._cells[row + ":" + column];
if (!cell) {
return null;
}
return cell.children;
};
/**
* Gets a string representing the child cell info (row x column)
* @param child defines the control to get info from
* @returns a string containing the child cell info (row x column)
*/
Grid.prototype.getChildCellInfo = function (child) {
return child._tag;
};
Grid.prototype._removeCell = function (cell, key) {
if (!cell) {
return;
}
_super.prototype.removeControl.call(this, cell);
for (var _i = 0, _a = cell.children; _i < _a.length; _i++) {
var control = _a[_i];
var childIndex = this._childControls.indexOf(control);
if (childIndex !== -1) {
this._childControls.splice(childIndex, 1);
}
}
delete this._cells[key];
};
Grid.prototype._offsetCell = function (previousKey, key) {
if (!this._cells[key]) {
return;
}
this._cells[previousKey] = this._cells[key];
for (var _i = 0, _a = this._cells[previousKey].children; _i < _a.length; _i++) {
var control = _a[_i];
control._tag = previousKey;
}
delete this._cells[key];
};
/**
* Remove a column definition at specified index
* @param index defines the index of the column to remove
* @returns the current grid
*/
Grid.prototype.removeColumnDefinition = function (index) {
if (index < 0 || index >= this._columnDefinitions.length) {
return this;
}
for (var x = 0; x < this._rowDefinitions.length; x++) {
var key = x + ":" + index;
var cell = this._cells[key];
this._removeCell(cell, key);
}
for (var x = 0; x < this._rowDefinitions.length; x++) {
for (var y = index + 1; y < this._columnDefinitions.length; y++) {
var previousKey = x + ":" + (y - 1);
var key = x + ":" + y;
this._offsetCell(previousKey, key);
}
}
this._columnDefinitions.splice(index, 1);
this._markAsDirty();
return this;
};
/**
* Remove a row definition at specified index
* @param index defines the index of the row to remove
* @returns the current grid
*/
Grid.prototype.removeRowDefinition = function (index) {
if (index < 0 || index >= this._rowDefinitions.length) {
return this;
}
for (var y = 0; y < this._columnDefinitions.length; y++) {
var key = index + ":" + y;
var cell = this._cells[key];
this._removeCell(cell, key);
}
for (var y = 0; y < this._columnDefinitions.length; y++) {
for (var x = index + 1; x < this._rowDefinitions.length; x++) {
var previousKey = x - 1 + ":" + y;
var key = x + ":" + y;
this._offsetCell(previousKey, key);
}
}
this._rowDefinitions.splice(index, 1);
this._markAsDirty();
return this;
};
/**
* Adds a new control to the current grid
* @param control defines the control to add
* @param row defines the row where to add the control (0 by default)
* @param column defines the column where to add the control (0 by default)
* @returns the current grid
*/
Grid.prototype.addControl = function (control, row, column) {
if (row === void 0) { row = 0; }
if (column === void 0) { column = 0; }
if (this._rowDefinitions.length === 0) {
// Add default row definition
this.addRowDefinition(1, false);
}
if (this._columnDefinitions.length === 0) {
// Add default column definition
this.addColumnDefinition(1, false);
}
if (this._childControls.indexOf(control) !== -1) {
babylonjs_Misc_tools__WEBPACK_IMPORTED_MODULE_4__["Tools"].Warn("Control (Name:" + control.name + ", UniqueId:" + control.uniqueId + ") is already associated with this grid. You must remove it before reattaching it");
return this;
}
var x = Math.min(row, this._rowDefinitions.length - 1);
var y = Math.min(column, this._columnDefinitions.length - 1);
var key = x + ":" + y;
var goodContainer = this._cells[key];
if (!goodContainer) {
goodContainer = new _container__WEBPACK_IMPORTED_MODULE_1__["Container"](key);
this._cells[key] = goodContainer;
goodContainer.horizontalAlignment = _control__WEBPACK_IMPORTED_MODULE_3__["Control"].HORIZONTAL_ALIGNMENT_LEFT;
goodContainer.verticalAlignment = _control__WEBPACK_IMPORTED_MODULE_3__["Control"].VERTICAL_ALIGNMENT_TOP;
_super.prototype.addControl.call(this, goodContainer);
}
goodContainer.addControl(control);
this._childControls.push(control);
control._tag = key;
control.parent = this;
this._markAsDirty();
return this;
};
/**
* Removes a control from the current container
* @param control defines the control to remove
* @returns the current container
*/
Grid.prototype.removeControl = function (control) {
var index = this._childControls.indexOf(control);
if (index !== -1) {
this._childControls.splice(index, 1);
}
var cell = this._cells[control._tag];
if (cell) {
cell.removeControl(control);
control._tag = null;
}
this._markAsDirty();
return this;
};
Grid.prototype._getTypeName = function () {
return "Grid";
};
Grid.prototype._getGridDefinitions = function (definitionCallback) {
var widths = [];
var heights = [];
var lefts = [];
var tops = [];
var availableWidth = this._currentMeasure.width;
var globalWidthPercentage = 0;
var availableHeight = this._currentMeasure.height;
var globalHeightPercentage = 0;
// Heights
var index = 0;
for (var _i = 0, _a = this._rowDefinitions; _i < _a.length; _i++) {
var value = _a[_i];
if (value.isPixel) {
var height = value.getValue(this._host);
availableHeight -= height;
heights[index] = height;
}
else {
globalHeightPercentage += value.internalValue;
}
index++;
}
var top = 0;
index = 0;
for (var _b = 0, _c = this._rowDefinitions; _b < _c.length; _b++) {
var value = _c[_b];
tops.push(top);
if (!value.isPixel) {
var height = (value.internalValue / globalHeightPercentage) * availableHeight;
top += height;
heights[index] = height;
}
else {
top += value.getValue(this._host);
}
index++;
}
// Widths
index = 0;
for (var _d = 0, _e = this._columnDefinitions; _d < _e.length; _d++) {
var value = _e[_d];
if (value.isPixel) {
var width = value.getValue(this._host);
availableWidth -= width;
widths[index] = width;
}
else {
globalWidthPercentage += value.internalValue;
}
index++;
}
var left = 0;
index = 0;
for (var _f = 0, _g = this._columnDefinitions; _f < _g.length; _f++) {
var value = _g[_f];
lefts.push(left);
if (!value.isPixel) {
var width = (value.internalValue / globalWidthPercentage) * availableWidth;
left += width;
widths[index] = width;
}
else {
left += value.getValue(this._host);
}
index++;
}
definitionCallback(lefts, tops, widths, heights);
};
Grid.prototype._additionalProcessing = function (parentMeasure, context) {
var _this = this;
this._getGridDefinitions(function (lefts, tops, widths, heights) {
// Setting child sizes
for (var key in _this._cells) {
if (!_this._cells.hasOwnProperty(key)) {
continue;
}
var split = key.split(":");
var x = parseInt(split[0]);
var y = parseInt(split[1]);
var cell = _this._cells[key];
cell.left = lefts[y] + "px";
cell.top = tops[x] + "px";
cell.width = widths[y] + "px";
cell.height = heights[x] + "px";
cell._left.ignoreAdaptiveScaling = true;
cell._top.ignoreAdaptiveScaling = true;
cell._width.ignoreAdaptiveScaling = true;
cell._height.ignoreAdaptiveScaling = true;
}
});
_super.prototype._additionalProcessing.call(this, parentMeasure, context);
};
Grid.prototype._flagDescendantsAsMatrixDirty = function () {
for (var key in this._cells) {
if (!this._cells.hasOwnProperty(key)) {
continue;
}
var child = this._cells[key];
child._markMatrixAsDirty();
}
};
Grid.prototype._renderHighlightSpecific = function (context) {
var _this = this;
_super.prototype._renderHighlightSpecific.call(this, context);
this._getGridDefinitions(function (lefts, tops, widths, heights) {
// Columns
for (var index = 0; index < lefts.length; index++) {
var left = _this._currentMeasure.left + lefts[index] + widths[index];
context.beginPath();
context.moveTo(left, _this._currentMeasure.top);
context.lineTo(left, _this._currentMeasure.top + _this._currentMeasure.height);
context.stroke();
}
// Rows
for (var index = 0; index < tops.length; index++) {
var top_1 = _this._currentMeasure.top + tops[index] + heights[index];
context.beginPath();
context.moveTo(_this._currentMeasure.left, top_1);
context.lineTo(_this._currentMeasure.left + _this._currentMeasure.width, top_1);
context.stroke();
}
});
context.restore();
};
/** Releases associated resources */
Grid.prototype.dispose = function () {
_super.prototype.dispose.call(this);
for (var _i = 0, _a = this._childControls; _i < _a.length; _i++) {
var control = _a[_i];
control.dispose();
}
this._childControls = [];
};
return Grid;
}(_container__WEBPACK_IMPORTED_MODULE_1__["Container"]));
/***/ }),
/***/ "./2D/controls/image.ts":
/*!******************************!*\
!*** ./2D/controls/image.ts ***!
\******************************/
/*! exports provided: Image */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Image", function() { return Image; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../../node_modules/tslib/tslib.es6.js");
/* harmony import */ var babylonjs_Misc_observable__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! babylonjs/Misc/observable */ "babylonjs/Misc/observable");
/* harmony import */ var babylonjs_Misc_observable__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(babylonjs_Misc_observable__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var _control__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./control */ "./2D/controls/control.ts");
/**
* Class used to create 2D images
*/
var Image = /** @class */ (function (_super) {
tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](Image, _super);
/**
* Creates a new Image
* @param name defines the control name
* @param url defines the image url
*/
function Image(name, url) {
if (url === void 0) { url = null; }
var _this = _super.call(this, name) || this;
_this.name = name;
_this._loaded = false;
_this._stretch = Image.STRETCH_FILL;
_this._autoScale = false;
_this._sourceLeft = 0;
_this._sourceTop = 0;
_this._sourceWidth = 0;
_this._sourceHeight = 0;
_this._cellWidth = 0;
_this._cellHeight = 0;
_this._cellId = -1;
_this._populateNinePatchSlicesFromImage = false;
/**
* Observable notified when the content is loaded
*/
_this.onImageLoadedObservable = new babylonjs_Misc_observable__WEBPACK_IMPORTED_MODULE_1__["Observable"]();
_this.source = url;
return _this;
}
Object.defineProperty(Image.prototype, "isLoaded", {
/**
* Gets a boolean indicating that the content is loaded
*/
get: function () {
return this._loaded;
},
enumerable: true,
configurable: true
});
Object.defineProperty(Image.prototype, "populateNinePatchSlicesFromImage", {
/**
* Gets or sets a boolean indicating if nine patch slices (left, top, right, bottom) should be read from image data
*/
get: function () {
return this._populateNinePatchSlicesFromImage;
},
set: function (value) {
if (this._populateNinePatchSlicesFromImage === value) {
return;
}
this._populateNinePatchSlicesFromImage = value;
if (this._populateNinePatchSlicesFromImage && this._loaded) {
this._extractNinePatchSliceDataFromImage();
}
},
enumerable: true,
configurable: true
});
Object.defineProperty(Image.prototype, "detectPointerOnOpaqueOnly", {
/**
* Gets or sets a boolean indicating if pointers should only be validated on pixels with alpha > 0.
* Beware using this as this will comsume more memory as the image has to be stored twice
*/
get: function () {
return this._detectPointerOnOpaqueOnly;
},
set: function (value) {
if (this._detectPointerOnOpaqueOnly === value) {
return;
}
this._detectPointerOnOpaqueOnly = value;
},
enumerable: true,
configurable: true
});
Object.defineProperty(Image.prototype, "sliceLeft", {
/**
* Gets or sets the left value for slicing (9-patch)
*/
get: function () {
return this._sliceLeft;
},
set: function (value) {
if (this._sliceLeft === value) {
return;
}
this._sliceLeft = value;
this._markAsDirty();
},
enumerable: true,
configurable: true
});
Object.defineProperty(Image.prototype, "sliceRight", {
/**
* Gets or sets the right value for slicing (9-patch)
*/
get: function () {
return this._sliceRight;
},
set: function (value) {
if (this._sliceRight === value) {
return;
}
this._sliceRight = value;
this._markAsDirty();
},
enumerable: true,
configurable: true
});
Object.defineProperty(Image.prototype, "sliceTop", {
/**
* Gets or sets the top value for slicing (9-patch)
*/
get: function () {
return this._sliceTop;
},
set: function (value) {
if (this._sliceTop === value) {
return;
}
this._sliceTop = value;
this._markAsDirty();
},
enumerable: true,
configurable: true
});
Object.defineProperty(Image.prototype, "sliceBottom", {
/**
* Gets or sets the bottom value for slicing (9-patch)
*/
get: function () {
return this._sliceBottom;
},
set: function (value) {
if (this._sliceBottom === value) {
return;
}
this._sliceBottom = value;
this._markAsDirty();
},
enumerable: true,
configurable: true
});
Object.defineProperty(Image.prototype, "sourceLeft", {
/**
* Gets or sets the left coordinate in the source image
*/
get: function () {
return this._sourceLeft;
},
set: function (value) {
if (this._sourceLeft === value) {
return;
}
this._sourceLeft = value;
this._markAsDirty();
},
enumerable: true,
configurable: true
});
Object.defineProperty(Image.prototype, "sourceTop", {
/**
* Gets or sets the top coordinate in the source image
*/
get: function () {
return this._sourceTop;
},
set: function (value) {
if (this._sourceTop === value) {
return;
}
this._sourceTop = value;
this._markAsDirty();
},
enumerable: true,
configurable: true
});
Object.defineProperty(Image.prototype, "sourceWidth", {
/**
* Gets or sets the width to capture in the source image
*/
get: function () {
return this._sourceWidth;
},
set: function (value) {
if (this._sourceWidth === value) {
return;
}
this._sourceWidth = value;
this._markAsDirty();
},
enumerable: true,
configurable: true
});
Object.defineProperty(Image.prototype, "sourceHeight", {
/**
* Gets or sets the height to capture in the source image
*/
get: function () {
return this._sourceHeight;
},
set: function (value) {
if (this._sourceHeight === value) {
return;
}
this._sourceHeight = value;
this._markAsDirty();
},
enumerable: true,
configurable: true
});
Object.defineProperty(Image.prototype, "autoScale", {
/**
* Gets or sets a boolean indicating if the image can force its container to adapt its size
* @see http://doc.babylonjs.com/how_to/gui#image
*/
get: function () {
return this._autoScale;
},
set: function (value) {
if (this._autoScale === value) {
return;
}
this._autoScale = value;
if (value && this._loaded) {
this.synchronizeSizeWithContent();
}
},
enumerable: true,
configurable: true
});
Object.defineProperty(Image.prototype, "stretch", {
/** Gets or sets the streching mode used by the image */
get: function () {
return this._stretch;
},
set: function (value) {
if (this._stretch === value) {
return;
}
this._stretch = value;
this._markAsDirty();
},
enumerable: true,
configurable: true
});
Object.defineProperty(Image.prototype, "domImage", {
get: function () {
return this._domImage;
},
/**
* Gets or sets the internal DOM image used to render the control
*/
set: function (value) {
var _this = this;
this._domImage = value;
this._loaded = false;
if (this._domImage.width) {
this._onImageLoaded();
}
else {
this._domImage.onload = function () {
_this._onImageLoaded();
};
}
},
enumerable: true,
configurable: true
});
Image.prototype._onImageLoaded = function () {
this._imageWidth = this._domImage.width;
this._imageHeight = this._domImage.height;
this._loaded = true;
if (this._populateNinePatchSlicesFromImage) {
this._extractNinePatchSliceDataFromImage();
}
if (this._autoScale) {
this.synchronizeSizeWithContent();
}
this.onImageLoadedObservable.notifyObservers(this);
this._markAsDirty();
};
Image.prototype._extractNinePatchSliceDataFromImage = function () {
if (!Image._WorkingCanvas) {
Image._WorkingCanvas = document.createElement('canvas');
}
var canvas = Image._WorkingCanvas;
var context = canvas.getContext('2d');
var width = this._domImage.width;
var height = this._domImage.height;
canvas.width = width;
canvas.height = height;
context.drawImage(this._domImage, 0, 0, width, height);
var imageData = context.getImageData(0, 0, width, height);
// Left and right
this._sliceLeft = -1;
this._sliceRight = -1;
for (var x = 0; x < width; x++) {
var alpha = imageData.data[x * 4 + 3];
if (alpha > 127 && this._sliceLeft === -1) {
this._sliceLeft = x;
continue;
}
if (alpha < 127 && this._sliceLeft > -1) {
this._sliceRight = x;
break;
}
}
// top and bottom
this._sliceTop = -1;
this._sliceBottom = -1;
for (var y = 0; y < height; y++) {
var alpha = imageData.data[y * width * 4 + 3];
if (alpha > 127 && this._sliceTop === -1) {
this._sliceTop = y;
continue;
}
if (alpha < 127 && this._sliceTop > -1) {
this._sliceBottom = y;
break;
}
}
};
Object.defineProperty(Image.prototype, "source", {
/**
* Gets or sets image source url
*/
set: function (value) {
var _this = this;
if (this._source === value) {
return;
}
this._loaded = false;
this._source = value;
this._domImage = document.createElement("img");
this._domImage.onload = function () {
_this._onImageLoaded();
};
if (value) {
babylonjs_Misc_observable__WEBPACK_IMPORTED_MODULE_1__["Tools"].SetCorsBehavior(value, this._domImage);
this._domImage.src = value;
}
},
enumerable: true,
configurable: true
});
Object.defineProperty(Image.prototype, "cellWidth", {
/**
* Gets or sets the cell width to use when animation sheet is enabled
* @see http://doc.babylonjs.com/how_to/gui#image
*/
get: function () {
return this._cellWidth;
},
set: function (value) {
if (this._cellWidth === value) {
return;
}
this._cellWidth = value;
this._markAsDirty();
},
enumerable: true,
configurable: true
});
Object.defineProperty(Image.prototype, "cellHeight", {
/**
* Gets or sets the cell height to use when animation sheet is enabled
* @see http://doc.babylonjs.com/how_to/gui#image
*/
get: function () {
return this._cellHeight;
},
set: function (value) {
if (this._cellHeight === value) {
return;
}
this._cellHeight = value;
this._markAsDirty();
},
enumerable: true,
configurable: true
});
Object.defineProperty(Image.prototype, "cellId", {
/**
* Gets or sets the cell id to use (this will turn on the animation sheet mode)
* @see http://doc.babylonjs.com/how_to/gui#image
*/
get: function () {
return this._cellId;
},
set: function (value) {
if (this._cellId === value) {
return;
}
this._cellId = value;
this._markAsDirty();
},
enumerable: true,
configurable: true
});
/**
* Tests if a given coordinates belong to the current control
* @param x defines x coordinate to test
* @param y defines y coordinate to test
* @returns true if the coordinates are inside the control
*/
Image.prototype.contains = function (x, y) {
if (!_super.prototype.contains.call(this, x, y)) {
return false;
}
if (!this._detectPointerOnOpaqueOnly || !Image._WorkingCanvas) {
return true;
}
var canvas = Image._WorkingCanvas;
var context = canvas.getContext("2d");
var width = this._currentMeasure.width | 0;
var height = this._currentMeasure.height | 0;
var imageData = context.getImageData(0, 0, width, height).data;
x = (x - this._currentMeasure.left) | 0;
y = (y - this._currentMeasure.top) | 0;
var pickedPixel = imageData[(x + y * this._currentMeasure.width) * 4 + 3];
return pickedPixel > 0;
};
Image.prototype._getTypeName = function () {
return "Image";
};
/** Force the control to synchronize with its content */
Image.prototype.synchronizeSizeWithContent = function () {
if (!this._loaded) {
return;
}
this.width = this._domImage.width + "px";
this.height = this._domImage.height + "px";
};
Image.prototype._processMeasures = function (parentMeasure, context) {
if (this._loaded) {
switch (this._stretch) {
case Image.STRETCH_NONE:
break;
case Image.STRETCH_FILL:
break;
case Image.STRETCH_UNIFORM:
break;
case Image.STRETCH_NINE_PATCH:
break;
case Image.STRETCH_EXTEND:
if (this._autoScale) {
this.synchronizeSizeWithContent();
}
if (this.parent && this.parent.parent) { // Will update root size if root is not the top root
this.parent.adaptWidthToChildren = true;
this.parent.adaptHeightToChildren = true;
}
break;
}
}
_super.prototype._processMeasures.call(this, parentMeasure, context);
};
Image.prototype._prepareWorkingCanvasForOpaqueDetection = function () {
if (!this._detectPointerOnOpaqueOnly) {
return;
}
if (!Image._WorkingCanvas) {
Image._WorkingCanvas = document.createElement('canvas');
}
var canvas = Image._WorkingCanvas;
var width = this._currentMeasure.width;
var height = this._currentMeasure.height;
var context = canvas.getContext("2d");
canvas.width = width;
canvas.height = height;
context.clearRect(0, 0, width, height);
};
Image.prototype._drawImage = function (context, sx, sy, sw, sh, tx, ty, tw, th) {
context.drawImage(this._domImage, sx, sy, sw, sh, tx, ty, tw, th);
if (!this._detectPointerOnOpaqueOnly) {
return;
}
var canvas = Image._WorkingCanvas;
context = canvas.getContext("2d");
context.drawImage(this._domImage, sx, sy, sw, sh, tx - this._currentMeasure.left, ty - this._currentMeasure.top, tw, th);
};
Image.prototype._draw = function (context) {
context.save();
if (this.shadowBlur || this.shadowOffsetX || this.shadowOffsetY) {
context.shadowColor = this.shadowColor;
context.shadowBlur = this.shadowBlur;
context.shadowOffsetX = this.shadowOffsetX;
context.shadowOffsetY = this.shadowOffsetY;
}
var x, y, width, height;
if (this.cellId == -1) {
x = this._sourceLeft;
y = this._sourceTop;
width = this._sourceWidth ? this._sourceWidth : this._imageWidth;
height = this._sourceHeight ? this._sourceHeight : this._imageHeight;
}
else {
var rowCount = this._domImage.naturalWidth / this.cellWidth;
var column = (this.cellId / rowCount) >> 0;
var row = this.cellId % rowCount;
x = this.cellWidth * row;
y = this.cellHeight * column;
width = this.cellWidth;
height = this.cellHeight;
}
this._prepareWorkingCanvasForOpaqueDetection();
this._applyStates(context);
if (this._loaded) {
switch (this._stretch) {
case Image.STRETCH_NONE:
this._drawImage(context, x, y, width, height, this._currentMeasure.left, this._currentMeasure.top, this._currentMeasure.width, this._currentMeasure.height);
break;
case Image.STRETCH_FILL:
this._drawImage(context, x, y, width, height, this._currentMeasure.left, this._currentMeasure.top, this._currentMeasure.width, this._currentMeasure.height);
break;
case Image.STRETCH_UNIFORM:
var hRatio = this._currentMeasure.width / width;
var vRatio = this._currentMeasure.height / height;
var ratio = Math.min(hRatio, vRatio);
var centerX = (this._currentMeasure.width - width * ratio) / 2;
var centerY = (this._currentMeasure.height - height * ratio) / 2;
this._drawImage(context, x, y, width, height, this._currentMeasure.left + centerX, this._currentMeasure.top + centerY, width * ratio, height * ratio);
break;
case Image.STRETCH_EXTEND:
this._drawImage(context, x, y, width, height, this._currentMeasure.left, this._currentMeasure.top, this._currentMeasure.width, this._currentMeasure.height);
break;
case Image.STRETCH_NINE_PATCH:
this._renderNinePatch(context);
break;
}
}
context.restore();
};
Image.prototype._renderCornerPatch = function (context, x, y, width, height, targetX, targetY) {
this._drawImage(context, x, y, width, height, this._currentMeasure.left + targetX, this._currentMeasure.top + targetY, width, height);
};
Image.prototype._renderNinePatch = function (context) {
var height = this._imageHeight;
var leftWidth = this._sliceLeft;
var topHeight = this._sliceTop;
var bottomHeight = this._imageHeight - this._sliceBottom;
var rightWidth = this._imageWidth - this._sliceRight;
var left = 0;
var top = 0;
if (this._populateNinePatchSlicesFromImage) {
left = 1;
top = 1;
height -= 2;
leftWidth -= 1;
topHeight -= 1;
bottomHeight -= 1;
rightWidth -= 1;
}
var centerWidth = this._sliceRight - this._sliceLeft + 1;
var targetCenterWidth = this._currentMeasure.width - rightWidth - this.sliceLeft + 1;
var targetTopHeight = this._currentMeasure.height - height + this._sliceBottom;
// Corners
this._renderCornerPatch(context, left, top, leftWidth, topHeight, 0, 0);
this._renderCornerPatch(context, left, this._sliceBottom, leftWidth, height - this._sliceBottom, 0, targetTopHeight);
this._renderCornerPatch(context, this._sliceRight, top, rightWidth, topHeight, this._currentMeasure.width - rightWidth, 0);
this._renderCornerPatch(context, this._sliceRight, this._sliceBottom, rightWidth, height - this._sliceBottom, this._currentMeasure.width - rightWidth, targetTopHeight);
// Center
this._drawImage(context, this._sliceLeft, this._sliceTop, centerWidth, this._sliceBottom - this._sliceTop + 1, this._currentMeasure.left + leftWidth, this._currentMeasure.top + topHeight, targetCenterWidth, targetTopHeight - topHeight + 1);
// Borders
this._drawImage(context, left, this._sliceTop, leftWidth, this._sliceBottom - this._sliceTop, this._currentMeasure.left, this._currentMeasure.top + topHeight, leftWidth, targetTopHeight - topHeight);
this._drawImage(context, this._sliceRight, this._sliceTop, leftWidth, this._sliceBottom - this._sliceTop, this._currentMeasure.left + this._currentMeasure.width - rightWidth, this._currentMeasure.top + topHeight, leftWidth, targetTopHeight - topHeight);
this._drawImage(context, this._sliceLeft, top, centerWidth, topHeight, this._currentMeasure.left + leftWidth, this._currentMeasure.top, targetCenterWidth, topHeight);
this._drawImage(context, this._sliceLeft, this._sliceBottom, centerWidth, bottomHeight, this._currentMeasure.left + leftWidth, this._currentMeasure.top + targetTopHeight, targetCenterWidth, bottomHeight);
};
Image.prototype.dispose = function () {
_super.prototype.dispose.call(this);
this.onImageLoadedObservable.clear();
};
Image._WorkingCanvas = null;
// Static
/** STRETCH_NONE */
Image.STRETCH_NONE = 0;
/** STRETCH_FILL */
Image.STRETCH_FILL = 1;
/** STRETCH_UNIFORM */
Image.STRETCH_UNIFORM = 2;
/** STRETCH_EXTEND */
Image.STRETCH_EXTEND = 3;
/** NINE_PATCH */
Image.STRETCH_NINE_PATCH = 4;
return Image;
}(_control__WEBPACK_IMPORTED_MODULE_2__["Control"]));
/***/ }),
/***/ "./2D/controls/index.ts":
/*!******************************!*\
!*** ./2D/controls/index.ts ***!
\******************************/
/*! exports provided: Button, Checkbox, ColorPicker, Container, Control, Ellipse, Grid, Image, InputText, InputPassword, Line, MultiLine, RadioButton, StackPanel, SelectorGroup, CheckboxGroup, RadioGroup, SliderGroup, SelectionPanel, ScrollViewer, TextWrapping, TextBlock, KeyPropertySet, VirtualKeyboard, Rectangle, DisplayGrid, BaseSlider, Slider, ImageBasedSlider, ScrollBar, name */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var _button__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./button */ "./2D/controls/button.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Button", function() { return _button__WEBPACK_IMPORTED_MODULE_0__["Button"]; });
/* harmony import */ var _checkbox__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./checkbox */ "./2D/controls/checkbox.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Checkbox", function() { return _checkbox__WEBPACK_IMPORTED_MODULE_1__["Checkbox"]; });
/* harmony import */ var _colorpicker__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./colorpicker */ "./2D/controls/colorpicker.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ColorPicker", function() { return _colorpicker__WEBPACK_IMPORTED_MODULE_2__["ColorPicker"]; });
/* harmony import */ var _container__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./container */ "./2D/controls/container.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Container", function() { return _container__WEBPACK_IMPORTED_MODULE_3__["Container"]; });
/* harmony import */ var _control__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./control */ "./2D/controls/control.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Control", function() { return _control__WEBPACK_IMPORTED_MODULE_4__["Control"]; });
/* harmony import */ var _ellipse__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./ellipse */ "./2D/controls/ellipse.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Ellipse", function() { return _ellipse__WEBPACK_IMPORTED_MODULE_5__["Ellipse"]; });
/* harmony import */ var _grid__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ./grid */ "./2D/controls/grid.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Grid", function() { return _grid__WEBPACK_IMPORTED_MODULE_6__["Grid"]; });
/* harmony import */ var _image__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ./image */ "./2D/controls/image.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Image", function() { return _image__WEBPACK_IMPORTED_MODULE_7__["Image"]; });
/* harmony import */ var _inputText__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ./inputText */ "./2D/controls/inputText.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "InputText", function() { return _inputText__WEBPACK_IMPORTED_MODULE_8__["InputText"]; });
/* harmony import */ var _inputPassword__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ./inputPassword */ "./2D/controls/inputPassword.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "InputPassword", function() { return _inputPassword__WEBPACK_IMPORTED_MODULE_9__["InputPassword"]; });
/* harmony import */ var _line__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! ./line */ "./2D/controls/line.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Line", function() { return _line__WEBPACK_IMPORTED_MODULE_10__["Line"]; });
/* harmony import */ var _multiLine__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(/*! ./multiLine */ "./2D/controls/multiLine.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "MultiLine", function() { return _multiLine__WEBPACK_IMPORTED_MODULE_11__["MultiLine"]; });
/* harmony import */ var _radioButton__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(/*! ./radioButton */ "./2D/controls/radioButton.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "RadioButton", function() { return _radioButton__WEBPACK_IMPORTED_MODULE_12__["RadioButton"]; });
/* harmony import */ var _stackPanel__WEBPACK_IMPORTED_MODULE_13__ = __webpack_require__(/*! ./stackPanel */ "./2D/controls/stackPanel.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "StackPanel", function() { return _stackPanel__WEBPACK_IMPORTED_MODULE_13__["StackPanel"]; });
/* harmony import */ var _selector__WEBPACK_IMPORTED_MODULE_14__ = __webpack_require__(/*! ./selector */ "./2D/controls/selector.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "SelectorGroup", function() { return _selector__WEBPACK_IMPORTED_MODULE_14__["SelectorGroup"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "CheckboxGroup", function() { return _selector__WEBPACK_IMPORTED_MODULE_14__["CheckboxGroup"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "RadioGroup", function() { return _selector__WEBPACK_IMPORTED_MODULE_14__["RadioGroup"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "SliderGroup", function() { return _selector__WEBPACK_IMPORTED_MODULE_14__["SliderGroup"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "SelectionPanel", function() { return _selector__WEBPACK_IMPORTED_MODULE_14__["SelectionPanel"]; });
/* harmony import */ var _scrollViewers_scrollViewer__WEBPACK_IMPORTED_MODULE_15__ = __webpack_require__(/*! ./scrollViewers/scrollViewer */ "./2D/controls/scrollViewers/scrollViewer.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ScrollViewer", function() { return _scrollViewers_scrollViewer__WEBPACK_IMPORTED_MODULE_15__["ScrollViewer"]; });
/* harmony import */ var _textBlock__WEBPACK_IMPORTED_MODULE_16__ = __webpack_require__(/*! ./textBlock */ "./2D/controls/textBlock.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "TextWrapping", function() { return _textBlock__WEBPACK_IMPORTED_MODULE_16__["TextWrapping"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "TextBlock", function() { return _textBlock__WEBPACK_IMPORTED_MODULE_16__["TextBlock"]; });
/* harmony import */ var _virtualKeyboard__WEBPACK_IMPORTED_MODULE_17__ = __webpack_require__(/*! ./virtualKeyboard */ "./2D/controls/virtualKeyboard.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "KeyPropertySet", function() { return _virtualKeyboard__WEBPACK_IMPORTED_MODULE_17__["KeyPropertySet"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "VirtualKeyboard", function() { return _virtualKeyboard__WEBPACK_IMPORTED_MODULE_17__["VirtualKeyboard"]; });
/* harmony import */ var _rectangle__WEBPACK_IMPORTED_MODULE_18__ = __webpack_require__(/*! ./rectangle */ "./2D/controls/rectangle.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Rectangle", function() { return _rectangle__WEBPACK_IMPORTED_MODULE_18__["Rectangle"]; });
/* harmony import */ var _displayGrid__WEBPACK_IMPORTED_MODULE_19__ = __webpack_require__(/*! ./displayGrid */ "./2D/controls/displayGrid.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "DisplayGrid", function() { return _displayGrid__WEBPACK_IMPORTED_MODULE_19__["DisplayGrid"]; });
/* harmony import */ var _sliders_baseSlider__WEBPACK_IMPORTED_MODULE_20__ = __webpack_require__(/*! ./sliders/baseSlider */ "./2D/controls/sliders/baseSlider.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "BaseSlider", function() { return _sliders_baseSlider__WEBPACK_IMPORTED_MODULE_20__["BaseSlider"]; });
/* harmony import */ var _sliders_slider__WEBPACK_IMPORTED_MODULE_21__ = __webpack_require__(/*! ./sliders/slider */ "./2D/controls/sliders/slider.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Slider", function() { return _sliders_slider__WEBPACK_IMPORTED_MODULE_21__["Slider"]; });
/* harmony import */ var _sliders_imageBasedSlider__WEBPACK_IMPORTED_MODULE_22__ = __webpack_require__(/*! ./sliders/imageBasedSlider */ "./2D/controls/sliders/imageBasedSlider.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ImageBasedSlider", function() { return _sliders_imageBasedSlider__WEBPACK_IMPORTED_MODULE_22__["ImageBasedSlider"]; });
/* harmony import */ var _sliders_scrollBar__WEBPACK_IMPORTED_MODULE_23__ = __webpack_require__(/*! ./sliders/scrollBar */ "./2D/controls/sliders/scrollBar.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ScrollBar", function() { return _sliders_scrollBar__WEBPACK_IMPORTED_MODULE_23__["ScrollBar"]; });
/* harmony import */ var _statics__WEBPACK_IMPORTED_MODULE_24__ = __webpack_require__(/*! ./statics */ "./2D/controls/statics.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "name", function() { return _statics__WEBPACK_IMPORTED_MODULE_24__["name"]; });
/***/ }),
/***/ "./2D/controls/inputPassword.ts":
/*!**************************************!*\
!*** ./2D/controls/inputPassword.ts ***!
\**************************************/
/*! exports provided: InputPassword */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "InputPassword", function() { return InputPassword; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../../node_modules/tslib/tslib.es6.js");
/* harmony import */ var _inputText__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./inputText */ "./2D/controls/inputText.ts");
/**
* Class used to create a password control
*/
var InputPassword = /** @class */ (function (_super) {
tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](InputPassword, _super);
function InputPassword() {
return _super !== null && _super.apply(this, arguments) || this;
}
InputPassword.prototype._beforeRenderText = function (text) {
var txt = "";
for (var i = 0; i < text.length; i++) {
txt += "\u2022";
}
return txt;
};
return InputPassword;
}(_inputText__WEBPACK_IMPORTED_MODULE_1__["InputText"]));
/***/ }),
/***/ "./2D/controls/inputText.ts":
/*!**********************************!*\
!*** ./2D/controls/inputText.ts ***!
\**********************************/
/*! exports provided: InputText */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "InputText", function() { return InputText; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../../node_modules/tslib/tslib.es6.js");
/* harmony import */ var babylonjs_Misc_observable__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! babylonjs/Misc/observable */ "babylonjs/Misc/observable");
/* harmony import */ var babylonjs_Misc_observable__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(babylonjs_Misc_observable__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var _control__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./control */ "./2D/controls/control.ts");
/* harmony import */ var _valueAndUnit__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../valueAndUnit */ "./2D/valueAndUnit.ts");
/**
* Class used to create input text control
*/
var InputText = /** @class */ (function (_super) {
tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](InputText, _super);
/**
* Creates a new InputText
* @param name defines the control name
* @param text defines the text of the control
*/
function InputText(name, text) {
if (text === void 0) { text = ""; }
var _this = _super.call(this, name) || this;
_this.name = name;
_this._text = "";
_this._placeholderText = "";
_this._background = "#222222";
_this._focusedBackground = "#000000";
_this._focusedColor = "white";
_this._placeholderColor = "gray";
_this._thickness = 1;
_this._margin = new _valueAndUnit__WEBPACK_IMPORTED_MODULE_3__["ValueAndUnit"](10, _valueAndUnit__WEBPACK_IMPORTED_MODULE_3__["ValueAndUnit"].UNITMODE_PIXEL);
_this._autoStretchWidth = true;
_this._maxWidth = new _valueAndUnit__WEBPACK_IMPORTED_MODULE_3__["ValueAndUnit"](1, _valueAndUnit__WEBPACK_IMPORTED_MODULE_3__["ValueAndUnit"].UNITMODE_PERCENTAGE, false);
_this._isFocused = false;
_this._blinkIsEven = false;
_this._cursorOffset = 0;
_this._deadKey = false;
_this._addKey = true;
_this._currentKey = "";
_this._isTextHighlightOn = false;
_this._textHighlightColor = "#d5e0ff";
_this._highligherOpacity = 0.4;
_this._highlightedText = "";
_this._startHighlightIndex = 0;
_this._endHighlightIndex = 0;
_this._cursorIndex = -1;
_this._onFocusSelectAll = false;
_this._isPointerDown = false;
/** Gets or sets a string representing the message displayed on mobile when the control gets the focus */
_this.promptMessage = "Please enter text:";
/** Observable raised when the text changes */
_this.onTextChangedObservable = new babylonjs_Misc_observable__WEBPACK_IMPORTED_MODULE_1__["Observable"]();
/** Observable raised just before an entered character is to be added */
_this.onBeforeKeyAddObservable = new babylonjs_Misc_observable__WEBPACK_IMPORTED_MODULE_1__["Observable"]();
/** Observable raised when the control gets the focus */
_this.onFocusObservable = new babylonjs_Misc_observable__WEBPACK_IMPORTED_MODULE_1__["Observable"]();
/** Observable raised when the control loses the focus */
_this.onBlurObservable = new babylonjs_Misc_observable__WEBPACK_IMPORTED_MODULE_1__["Observable"]();
/**Observable raised when the text is highlighted */
_this.onTextHighlightObservable = new babylonjs_Misc_observable__WEBPACK_IMPORTED_MODULE_1__["Observable"]();
/**Observable raised when copy event is triggered */
_this.onTextCopyObservable = new babylonjs_Misc_observable__WEBPACK_IMPORTED_MODULE_1__["Observable"]();
/** Observable raised when cut event is triggered */
_this.onTextCutObservable = new babylonjs_Misc_observable__WEBPACK_IMPORTED_MODULE_1__["Observable"]();
/** Observable raised when paste event is triggered */
_this.onTextPasteObservable = new babylonjs_Misc_observable__WEBPACK_IMPORTED_MODULE_1__["Observable"]();
/** Observable raised when a key event was processed */
_this.onKeyboardEventProcessedObservable = new babylonjs_Misc_observable__WEBPACK_IMPORTED_MODULE_1__["Observable"]();
_this.text = text;
_this.isPointerBlocker = true;
return _this;
}
Object.defineProperty(InputText.prototype, "maxWidth", {
/** Gets or sets the maximum width allowed by the control */
get: function () {
return this._maxWidth.toString(this._host);
},
set: function (value) {
if (this._maxWidth.toString(this._host) === value) {
return;
}
if (this._maxWidth.fromString(value)) {
this._markAsDirty();
}
},
enumerable: true,
configurable: true
});
Object.defineProperty(InputText.prototype, "maxWidthInPixels", {
/** Gets the maximum width allowed by the control in pixels */
get: function () {
return this._maxWidth.getValueInPixel(this._host, this._cachedParentMeasure.width);
},
enumerable: true,
configurable: true
});
Object.defineProperty(InputText.prototype, "highligherOpacity", {
/** Gets or sets the text highlighter transparency; default: 0.4 */
get: function () {
return this._highligherOpacity;
},
set: function (value) {
if (this._highligherOpacity === value) {
return;
}
this._highligherOpacity = value;
this._markAsDirty();
},
enumerable: true,
configurable: true
});
Object.defineProperty(InputText.prototype, "onFocusSelectAll", {
/** Gets or sets a boolean indicating whether to select complete text by default on input focus */
get: function () {
return this._onFocusSelectAll;
},
set: function (value) {
if (this._onFocusSelectAll === value) {
return;
}
this._onFocusSelectAll = value;
this._markAsDirty();
},
enumerable: true,
configurable: true
});
Object.defineProperty(InputText.prototype, "textHighlightColor", {
/** Gets or sets the text hightlight color */
get: function () {
return this._textHighlightColor;
},
set: function (value) {
if (this._textHighlightColor === value) {
return;
}
this._textHighlightColor = value;
this._markAsDirty();
},
enumerable: true,
configurable: true
});
Object.defineProperty(InputText.prototype, "margin", {
/** Gets or sets control margin */
get: function () {
return this._margin.toString(this._host);
},
set: function (value) {
if (this._margin.toString(this._host) === value) {
return;
}
if (this._margin.fromString(value)) {
this._markAsDirty();
}
},
enumerable: true,
configurable: true
});
Object.defineProperty(InputText.prototype, "marginInPixels", {
/** Gets control margin in pixels */
get: function () {
return this._margin.getValueInPixel(this._host, this._cachedParentMeasure.width);
},
enumerable: true,
configurable: true
});
Object.defineProperty(InputText.prototype, "autoStretchWidth", {
/** Gets or sets a boolean indicating if the control can auto stretch its width to adapt to the text */
get: function () {
return this._autoStretchWidth;
},
set: function (value) {
if (this._autoStretchWidth === value) {
return;
}
this._autoStretchWidth = value;
this._markAsDirty();
},
enumerable: true,
configurable: true
});
Object.defineProperty(InputText.prototype, "thickness", {
/** Gets or sets border thickness */
get: function () {
return this._thickness;
},
set: function (value) {
if (this._thickness === value) {
return;
}
this._thickness = value;
this._markAsDirty();
},
enumerable: true,
configurable: true
});
Object.defineProperty(InputText.prototype, "focusedBackground", {
/** Gets or sets the background color when focused */
get: function () {
return this._focusedBackground;
},
set: function (value) {
if (this._focusedBackground === value) {
return;
}
this._focusedBackground = value;
this._markAsDirty();
},
enumerable: true,
configurable: true
});
Object.defineProperty(InputText.prototype, "focusedColor", {
/** Gets or sets the background color when focused */
get: function () {
return this._focusedColor;
},
set: function (value) {
if (this._focusedColor === value) {
return;
}
this._focusedColor = value;
this._markAsDirty();
},
enumerable: true,
configurable: true
});
Object.defineProperty(InputText.prototype, "background", {
/** Gets or sets the background color */
get: function () {
return this._background;
},
set: function (value) {
if (this._background === value) {
return;
}
this._background = value;
this._markAsDirty();
},
enumerable: true,
configurable: true
});
Object.defineProperty(InputText.prototype, "placeholderColor", {
/** Gets or sets the placeholder color */
get: function () {
return this._placeholderColor;
},
set: function (value) {
if (this._placeholderColor === value) {
return;
}
this._placeholderColor = value;
this._markAsDirty();
},
enumerable: true,
configurable: true
});
Object.defineProperty(InputText.prototype, "placeholderText", {
/** Gets or sets the text displayed when the control is empty */
get: function () {
return this._placeholderText;
},
set: function (value) {
if (this._placeholderText === value) {
return;
}
this._placeholderText = value;
this._markAsDirty();
},
enumerable: true,
configurable: true
});
Object.defineProperty(InputText.prototype, "deadKey", {
/** Gets or sets the dead key flag */
get: function () {
return this._deadKey;
},
set: function (flag) {
this._deadKey = flag;
},
enumerable: true,
configurable: true
});
Object.defineProperty(InputText.prototype, "highlightedText", {
/** Gets or sets the highlight text */
get: function () {
return this._highlightedText;
},
set: function (text) {
if (this._highlightedText === text) {
return;
}
this._highlightedText = text;
this._markAsDirty();
},
enumerable: true,
configurable: true
});
Object.defineProperty(InputText.prototype, "addKey", {
/** Gets or sets if the current key should be added */
get: function () {
return this._addKey;
},
set: function (flag) {
this._addKey = flag;
},
enumerable: true,
configurable: true
});
Object.defineProperty(InputText.prototype, "currentKey", {
/** Gets or sets the value of the current key being entered */
get: function () {
return this._currentKey;
},
set: function (key) {
this._currentKey = key;
},
enumerable: true,
configurable: true
});
Object.defineProperty(InputText.prototype, "text", {
/** Gets or sets the text displayed in the control */
get: function () {
return this._text;
},
set: function (value) {
var valueAsString = value.toString(); // Forcing convertion
if (this._text === valueAsString) {
return;
}
this._text = valueAsString;
this._markAsDirty();
this.onTextChangedObservable.notifyObservers(this);
},
enumerable: true,
configurable: true
});
Object.defineProperty(InputText.prototype, "width", {
/** Gets or sets control width */
get: function () {
return this._width.toString(this._host);
},
set: function (value) {
if (this._width.toString(this._host) === value) {
return;
}
if (this._width.fromString(value)) {
this._markAsDirty();
}
this.autoStretchWidth = false;
},
enumerable: true,
configurable: true
});
/** @hidden */
InputText.prototype.onBlur = function () {
this._isFocused = false;
this._scrollLeft = null;
this._cursorOffset = 0;
clearTimeout(this._blinkTimeout);
this._markAsDirty();
this.onBlurObservable.notifyObservers(this);
this._host.unRegisterClipboardEvents();
if (this._onClipboardObserver) {
this._host.onClipboardObservable.remove(this._onClipboardObserver);
}
var scene = this._host.getScene();
if (this._onPointerDblTapObserver && scene) {
scene.onPointerObservable.remove(this._onPointerDblTapObserver);
}
};
/** @hidden */
InputText.prototype.onFocus = function () {
var _this = this;
if (!this._isEnabled) {
return;
}
this._scrollLeft = null;
this._isFocused = true;
this._blinkIsEven = false;
this._cursorOffset = 0;
this._markAsDirty();
this.onFocusObservable.notifyObservers(this);
if (navigator.userAgent.indexOf("Mobile") !== -1) {
var value = prompt(this.promptMessage);
if (value !== null) {
this.text = value;
}
this._host.focusedControl = null;
return;
}
this._host.registerClipboardEvents();
this._onClipboardObserver = this._host.onClipboardObservable.add(function (clipboardInfo) {
// process clipboard event, can be configured.
switch (clipboardInfo.type) {
case babylonjs_Misc_observable__WEBPACK_IMPORTED_MODULE_1__["ClipboardEventTypes"].COPY:
_this._onCopyText(clipboardInfo.event);
_this.onTextCopyObservable.notifyObservers(_this);
break;
case babylonjs_Misc_observable__WEBPACK_IMPORTED_MODULE_1__["ClipboardEventTypes"].CUT:
_this._onCutText(clipboardInfo.event);
_this.onTextCutObservable.notifyObservers(_this);
break;
case babylonjs_Misc_observable__WEBPACK_IMPORTED_MODULE_1__["ClipboardEventTypes"].PASTE:
_this._onPasteText(clipboardInfo.event);
_this.onTextPasteObservable.notifyObservers(_this);
break;
default: return;
}
});
var scene = this._host.getScene();
if (scene) {
//register the pointer double tap event
this._onPointerDblTapObserver = scene.onPointerObservable.add(function (pointerInfo) {
if (!_this._isFocused) {
return;
}
if (pointerInfo.type === babylonjs_Misc_observable__WEBPACK_IMPORTED_MODULE_1__["PointerEventTypes"].POINTERDOUBLETAP) {
_this._processDblClick(pointerInfo);
}
});
}
if (this._onFocusSelectAll) {
this._selectAllText();
}
};
InputText.prototype._getTypeName = function () {
return "InputText";
};
/**
* Function called to get the list of controls that should not steal the focus from this control
* @returns an array of controls
*/
InputText.prototype.keepsFocusWith = function () {
if (!this._connectedVirtualKeyboard) {
return null;
}
return [this._connectedVirtualKeyboard];
};
/** @hidden */
InputText.prototype.processKey = function (keyCode, key, evt) {
//return if clipboard event keys (i.e -ctr/cmd + c,v,x)
if (evt && (evt.ctrlKey || evt.metaKey) && (keyCode === 67 || keyCode === 86 || keyCode === 88)) {
return;
}
//select all
if (evt && (evt.ctrlKey || evt.metaKey) && keyCode === 65) {
this._selectAllText();
evt.preventDefault();
return;
}
// Specific cases
switch (keyCode) {
case 32: //SPACE
key = " "; //ie11 key for space is "Spacebar"
break;
case 191: //SLASH
if (evt) {
evt.preventDefault();
}
break;
case 8: // BACKSPACE
if (this._text && this._text.length > 0) {
//delete the highlighted text
if (this._isTextHighlightOn) {
this.text = this._text.slice(0, this._startHighlightIndex) + this._text.slice(this._endHighlightIndex);
this._isTextHighlightOn = false;
this._cursorOffset = this.text.length - this._startHighlightIndex;
this._blinkIsEven = false;
if (evt) {
evt.preventDefault();
}
return;
}
//delete single character
if (this._cursorOffset === 0) {
this.text = this._text.substr(0, this._text.length - 1);
}
else {
var deletePosition = this._text.length - this._cursorOffset;
if (deletePosition > 0) {
this.text = this._text.slice(0, deletePosition - 1) + this._text.slice(deletePosition);
}
}
}
if (evt) {
evt.preventDefault();
}
return;
case 46: // DELETE
if (this._isTextHighlightOn) {
this.text = this._text.slice(0, this._startHighlightIndex) + this._text.slice(this._endHighlightIndex);
var decrementor = (this._endHighlightIndex - this._startHighlightIndex);
while (decrementor > 0 && this._cursorOffset > 0) {
this._cursorOffset--;
}
this._isTextHighlightOn = false;
this._cursorOffset = this.text.length - this._startHighlightIndex;
if (evt) {
evt.preventDefault();
}
return;
}
if (this._text && this._text.length > 0 && this._cursorOffset > 0) {
var deletePosition = this._text.length - this._cursorOffset;
this.text = this._text.slice(0, deletePosition) + this._text.slice(deletePosition + 1);
this._cursorOffset--;
}
if (evt) {
evt.preventDefault();
}
return;
case 13: // RETURN
this._host.focusedControl = null;
this._isTextHighlightOn = false;
return;
case 35: // END
this._cursorOffset = 0;
this._blinkIsEven = false;
this._isTextHighlightOn = false;
this._markAsDirty();
return;
case 36: // HOME
this._cursorOffset = this._text.length;
this._blinkIsEven = false;
this._isTextHighlightOn = false;
this._markAsDirty();
return;
case 37: // LEFT
this._cursorOffset++;
if (this._cursorOffset > this._text.length) {
this._cursorOffset = this._text.length;
}
if (evt && evt.shiftKey) {
// update the cursor
this._blinkIsEven = false;
// shift + ctrl/cmd + <-
if (evt.ctrlKey || evt.metaKey) {
if (!this._isTextHighlightOn) {
if (this._text.length === this._cursorOffset) {
return;
}
else {
this._endHighlightIndex = this._text.length - this._cursorOffset + 1;
}
}
this._startHighlightIndex = 0;
this._cursorIndex = this._text.length - this._endHighlightIndex;
this._cursorOffset = this._text.length;
this._isTextHighlightOn = true;
this._markAsDirty();
return;
}
//store the starting point
if (!this._isTextHighlightOn) {
this._isTextHighlightOn = true;
this._cursorIndex = (this._cursorOffset >= this._text.length) ? this._text.length : this._cursorOffset - 1;
}
//if text is already highlighted
else if (this._cursorIndex === -1) {
this._cursorIndex = this._text.length - this._endHighlightIndex;
this._cursorOffset = (this._startHighlightIndex === 0) ? this._text.length : this._text.length - this._startHighlightIndex + 1;
}
//set the highlight indexes
if (this._cursorIndex < this._cursorOffset) {
this._endHighlightIndex = this._text.length - this._cursorIndex;
this._startHighlightIndex = this._text.length - this._cursorOffset;
}
else if (this._cursorIndex > this._cursorOffset) {
this._endHighlightIndex = this._text.length - this._cursorOffset;
this._startHighlightIndex = this._text.length - this._cursorIndex;
}
else {
this._isTextHighlightOn = false;
}
this._markAsDirty();
return;
}
if (this._isTextHighlightOn) {
this._cursorOffset = this._text.length - this._startHighlightIndex;
this._isTextHighlightOn = false;
}
if (evt && (evt.ctrlKey || evt.metaKey)) {
this._cursorOffset = this.text.length;
evt.preventDefault();
}
this._blinkIsEven = false;
this._isTextHighlightOn = false;
this._cursorIndex = -1;
this._markAsDirty();
return;
case 39: // RIGHT
this._cursorOffset--;
if (this._cursorOffset < 0) {
this._cursorOffset = 0;
}
if (evt && evt.shiftKey) {
//update the cursor
this._blinkIsEven = false;
//shift + ctrl/cmd + ->
if (evt.ctrlKey || evt.metaKey) {
if (!this._isTextHighlightOn) {
if (this._cursorOffset === 0) {
return;
}
else {
this._startHighlightIndex = this._text.length - this._cursorOffset - 1;
}
}
this._endHighlightIndex = this._text.length;
this._isTextHighlightOn = true;
this._cursorIndex = this._text.length - this._startHighlightIndex;
this._cursorOffset = 0;
this._markAsDirty();
return;
}
if (!this._isTextHighlightOn) {
this._isTextHighlightOn = true;
this._cursorIndex = (this._cursorOffset <= 0) ? 0 : this._cursorOffset + 1;
}
//if text is already highlighted
else if (this._cursorIndex === -1) {
this._cursorIndex = this._text.length - this._startHighlightIndex;
this._cursorOffset = (this._text.length === this._endHighlightIndex) ? 0 : this._text.length - this._endHighlightIndex - 1;
}
//set the highlight indexes
if (this._cursorIndex < this._cursorOffset) {
this._endHighlightIndex = this._text.length - this._cursorIndex;
this._startHighlightIndex = this._text.length - this._cursorOffset;
}
else if (this._cursorIndex > this._cursorOffset) {
this._endHighlightIndex = this._text.length - this._cursorOffset;
this._startHighlightIndex = this._text.length - this._cursorIndex;
}
else {
this._isTextHighlightOn = false;
}
this._markAsDirty();
return;
}
if (this._isTextHighlightOn) {
this._cursorOffset = this._text.length - this._endHighlightIndex;
this._isTextHighlightOn = false;
}
//ctr + ->
if (evt && (evt.ctrlKey || evt.metaKey)) {
this._cursorOffset = 0;
evt.preventDefault();
}
this._blinkIsEven = false;
this._isTextHighlightOn = false;
this._cursorIndex = -1;
this._markAsDirty();
return;
case 222: // Dead
if (evt) {
evt.preventDefault();
}
this._cursorIndex = -1;
this.deadKey = true;
break;
}
// Printable characters
if (key &&
((keyCode === -1) || // Direct access
(keyCode === 32) || // Space
(keyCode > 47 && keyCode < 64) || // Numbers
(keyCode > 64 && keyCode < 91) || // Letters
(keyCode > 159 && keyCode < 193) || // Special characters
(keyCode > 218 && keyCode < 223) || // Special characters
(keyCode > 95 && keyCode < 112))) { // Numpad
this._currentKey = key;
this.onBeforeKeyAddObservable.notifyObservers(this);
key = this._currentKey;
if (this._addKey) {
if (this._isTextHighlightOn) {
this.text = this._text.slice(0, this._startHighlightIndex) + key + this._text.slice(this._endHighlightIndex);
this._cursorOffset = this.text.length - (this._startHighlightIndex + 1);
this._isTextHighlightOn = false;
this._blinkIsEven = false;
this._markAsDirty();
}
else if (this._cursorOffset === 0) {
this.text += key;
}
else {
var insertPosition = this._text.length - this._cursorOffset;
this.text = this._text.slice(0, insertPosition) + key + this._text.slice(insertPosition);
}
}
}
};
/** @hidden */
InputText.prototype._updateValueFromCursorIndex = function (offset) {
//update the cursor
this._blinkIsEven = false;
if (this._cursorIndex === -1) {
this._cursorIndex = offset;
}
else {
if (this._cursorIndex < this._cursorOffset) {
this._endHighlightIndex = this._text.length - this._cursorIndex;
this._startHighlightIndex = this._text.length - this._cursorOffset;
}
else if (this._cursorIndex > this._cursorOffset) {
this._endHighlightIndex = this._text.length - this._cursorOffset;
this._startHighlightIndex = this._text.length - this._cursorIndex;
}
else {
this._isTextHighlightOn = false;
this._markAsDirty();
return;
}
}
this._isTextHighlightOn = true;
this._markAsDirty();
};
/** @hidden */
InputText.prototype._processDblClick = function (evt) {
//pre-find the start and end index of the word under cursor, speeds up the rendering
this._startHighlightIndex = this._text.length - this._cursorOffset;
this._endHighlightIndex = this._startHighlightIndex;
var rWord = /\w+/g, moveLeft, moveRight;
do {
moveRight = this._endHighlightIndex < this._text.length && (this._text[this._endHighlightIndex].search(rWord) !== -1) ? ++this._endHighlightIndex : 0;
moveLeft = this._startHighlightIndex > 0 && (this._text[this._startHighlightIndex - 1].search(rWord) !== -1) ? --this._startHighlightIndex : 0;
} while (moveLeft || moveRight);
this._cursorOffset = this.text.length - this._startHighlightIndex;
this.onTextHighlightObservable.notifyObservers(this);
this._isTextHighlightOn = true;
this._clickedCoordinate = null;
this._blinkIsEven = true;
this._cursorIndex = -1;
this._markAsDirty();
};
/** @hidden */
InputText.prototype._selectAllText = function () {
this._blinkIsEven = true;
this._isTextHighlightOn = true;
this._startHighlightIndex = 0;
this._endHighlightIndex = this._text.length;
this._cursorOffset = this._text.length;
this._cursorIndex = -1;
this._markAsDirty();
};
/**
* Handles the keyboard event
* @param evt Defines the KeyboardEvent
*/
InputText.prototype.processKeyboard = function (evt) {
// process pressed key
this.processKey(evt.keyCode, evt.key, evt);
this.onKeyboardEventProcessedObservable.notifyObservers(evt);
};
/** @hidden */
InputText.prototype._onCopyText = function (ev) {
this._isTextHighlightOn = false;
//when write permission to clipbaord data is denied
try {
ev.clipboardData && ev.clipboardData.setData("text/plain", this._highlightedText);
}
catch (_a) { } //pass
this._host.clipboardData = this._highlightedText;
};
/** @hidden */
InputText.prototype._onCutText = function (ev) {
if (!this._highlightedText) {
return;
}
this.text = this._text.slice(0, this._startHighlightIndex) + this._text.slice(this._endHighlightIndex);
this._isTextHighlightOn = false;
this._cursorOffset = this.text.length - this._startHighlightIndex;
//when write permission to clipbaord data is denied
try {
ev.clipboardData && ev.clipboardData.setData("text/plain", this._highlightedText);
}
catch (_a) { } //pass
this._host.clipboardData = this._highlightedText;
this._highlightedText = "";
};
/** @hidden */
InputText.prototype._onPasteText = function (ev) {
var data = "";
if (ev.clipboardData && ev.clipboardData.types.indexOf("text/plain") !== -1) {
data = ev.clipboardData.getData("text/plain");
}
else {
//get the cached data; returns blank string by default
data = this._host.clipboardData;
}
var insertPosition = this._text.length - this._cursorOffset;
this.text = this._text.slice(0, insertPosition) + data + this._text.slice(insertPosition);
};
InputText.prototype._draw = function (context) {
var _this = this;
context.save();
this._applyStates(context);
if (this.shadowBlur || this.shadowOffsetX || this.shadowOffsetY) {
context.shadowColor = this.shadowColor;
context.shadowBlur = this.shadowBlur;
context.shadowOffsetX = this.shadowOffsetX;
context.shadowOffsetY = this.shadowOffsetY;
}
// Background
if (this._isFocused) {
if (this._focusedBackground) {
context.fillStyle = this._isEnabled ? this._focusedBackground : this._disabledColor;
context.fillRect(this._currentMeasure.left, this._currentMeasure.top, this._currentMeasure.width, this._currentMeasure.height);
}
}
else if (this._background) {
context.fillStyle = this._isEnabled ? this._background : this._disabledColor;
context.fillRect(this._currentMeasure.left, this._currentMeasure.top, this._currentMeasure.width, this._currentMeasure.height);
}
if (this.shadowBlur || this.shadowOffsetX || this.shadowOffsetY) {
context.shadowBlur = 0;
context.shadowOffsetX = 0;
context.shadowOffsetY = 0;
}
if (!this._fontOffset) {
this._fontOffset = _control__WEBPACK_IMPORTED_MODULE_2__["Control"]._GetFontOffset(context.font);
}
// Text
var clipTextLeft = this._currentMeasure.left + this._margin.getValueInPixel(this._host, this._tempParentMeasure.width);
if (this.color) {
context.fillStyle = this.color;
}
var text = this._beforeRenderText(this._text);
if (!this._isFocused && !this._text && this._placeholderText) {
text = this._placeholderText;
if (this._placeholderColor) {
context.fillStyle = this._placeholderColor;
}
}
this._textWidth = context.measureText(text).width;
var marginWidth = this._margin.getValueInPixel(this._host, this._tempParentMeasure.width) * 2;
if (this._autoStretchWidth) {
this.width = Math.min(this._maxWidth.getValueInPixel(this._host, this._tempParentMeasure.width), this._textWidth + marginWidth) + "px";
}
var rootY = this._fontOffset.ascent + (this._currentMeasure.height - this._fontOffset.height) / 2;
var availableWidth = this._width.getValueInPixel(this._host, this._tempParentMeasure.width) - marginWidth;
context.save();
context.beginPath();
context.rect(clipTextLeft, this._currentMeasure.top + (this._currentMeasure.height - this._fontOffset.height) / 2, availableWidth + 2, this._currentMeasure.height);
context.clip();
if (this._isFocused && this._textWidth > availableWidth) {
var textLeft = clipTextLeft - this._textWidth + availableWidth;
if (!this._scrollLeft) {
this._scrollLeft = textLeft;
}
}
else {
this._scrollLeft = clipTextLeft;
}
context.fillText(text, this._scrollLeft, this._currentMeasure.top + rootY);
// Cursor
if (this._isFocused) {
// Need to move cursor
if (this._clickedCoordinate) {
var rightPosition = this._scrollLeft + this._textWidth;
var absoluteCursorPosition = rightPosition - this._clickedCoordinate;
var currentSize = 0;
this._cursorOffset = 0;
var previousDist = 0;
do {
if (this._cursorOffset) {
previousDist = Math.abs(absoluteCursorPosition - currentSize);
}
this._cursorOffset++;
currentSize = context.measureText(text.substr(text.length - this._cursorOffset, this._cursorOffset)).width;
} while (currentSize < absoluteCursorPosition && (text.length >= this._cursorOffset));
// Find closest move
if (Math.abs(absoluteCursorPosition - currentSize) > previousDist) {
this._cursorOffset--;
}
this._blinkIsEven = false;
this._clickedCoordinate = null;
}
// Render cursor
if (!this._blinkIsEven) {
var cursorOffsetText = this.text.substr(this._text.length - this._cursorOffset);
var cursorOffsetWidth = context.measureText(cursorOffsetText).width;
var cursorLeft = this._scrollLeft + this._textWidth - cursorOffsetWidth;
if (cursorLeft < clipTextLeft) {
this._scrollLeft += (clipTextLeft - cursorLeft);
cursorLeft = clipTextLeft;
this._markAsDirty();
}
else if (cursorLeft > clipTextLeft + availableWidth) {
this._scrollLeft += (clipTextLeft + availableWidth - cursorLeft);
cursorLeft = clipTextLeft + availableWidth;
this._markAsDirty();
}
if (!this._isTextHighlightOn) {
context.fillRect(cursorLeft, this._currentMeasure.top + (this._currentMeasure.height - this._fontOffset.height) / 2, 2, this._fontOffset.height);
}
}
clearTimeout(this._blinkTimeout);
this._blinkTimeout = setTimeout(function () {
_this._blinkIsEven = !_this._blinkIsEven;
_this._markAsDirty();
}, 500);
//show the highlighted text
if (this._isTextHighlightOn) {
clearTimeout(this._blinkTimeout);
var highlightCursorOffsetWidth = context.measureText(this.text.substring(this._startHighlightIndex)).width;
var highlightCursorLeft = this._scrollLeft + this._textWidth - highlightCursorOffsetWidth;
this._highlightedText = this.text.substring(this._startHighlightIndex, this._endHighlightIndex);
var width = context.measureText(this.text.substring(this._startHighlightIndex, this._endHighlightIndex)).width;
if (highlightCursorLeft < clipTextLeft) {
width = width - (clipTextLeft - highlightCursorLeft);
if (!width) {
// when using left arrow on text.length > availableWidth;
// assigns the width of the first letter after clipTextLeft
width = context.measureText(this.text.charAt(this.text.length - this._cursorOffset)).width;
}
highlightCursorLeft = clipTextLeft;
}
//for transparancy
context.globalAlpha = this._highligherOpacity;
context.fillStyle = this._textHighlightColor;
context.fillRect(highlightCursorLeft, this._currentMeasure.top + (this._currentMeasure.height - this._fontOffset.height) / 2, width, this._fontOffset.height);
context.globalAlpha = 1.0;
}
}
context.restore();
// Border
if (this._thickness) {
if (this._isFocused) {
if (this.focusedColor) {
context.strokeStyle = this.focusedColor;
}
}
else {
if (this.color) {
context.strokeStyle = this.color;
}
}
context.lineWidth = this._thickness;
context.strokeRect(this._currentMeasure.left + this._thickness / 2, this._currentMeasure.top + this._thickness / 2, this._currentMeasure.width - this._thickness, this._currentMeasure.height - this._thickness);
}
context.restore();
};
InputText.prototype._onPointerDown = function (target, coordinates, pointerId, buttonIndex) {
if (!_super.prototype._onPointerDown.call(this, target, coordinates, pointerId, buttonIndex)) {
return false;
}
this._clickedCoordinate = coordinates.x;
this._isTextHighlightOn = false;
this._highlightedText = "";
this._cursorIndex = -1;
this._isPointerDown = true;
this._host._capturingControl[pointerId] = this;
if (this._host.focusedControl === this) {
// Move cursor
clearTimeout(this._blinkTimeout);
this._markAsDirty();
return true;
}
if (!this._isEnabled) {
return false;
}
this._host.focusedControl = this;
return true;
};
InputText.prototype._onPointerMove = function (target, coordinates, pointerId) {
if (this._host.focusedControl === this && this._isPointerDown) {
this._clickedCoordinate = coordinates.x;
this._markAsDirty();
this._updateValueFromCursorIndex(this._cursorOffset);
}
_super.prototype._onPointerMove.call(this, target, coordinates, pointerId);
};
InputText.prototype._onPointerUp = function (target, coordinates, pointerId, buttonIndex, notifyClick) {
this._isPointerDown = false;
delete this._host._capturingControl[pointerId];
_super.prototype._onPointerUp.call(this, target, coordinates, pointerId, buttonIndex, notifyClick);
};
InputText.prototype._beforeRenderText = function (text) {
return text;
};
InputText.prototype.dispose = function () {
_super.prototype.dispose.call(this);
this.onBlurObservable.clear();
this.onFocusObservable.clear();
this.onTextChangedObservable.clear();
this.onTextCopyObservable.clear();
this.onTextCutObservable.clear();
this.onTextPasteObservable.clear();
this.onTextHighlightObservable.clear();
this.onKeyboardEventProcessedObservable.clear();
};
return InputText;
}(_control__WEBPACK_IMPORTED_MODULE_2__["Control"]));
/***/ }),
/***/ "./2D/controls/line.ts":
/*!*****************************!*\
!*** ./2D/controls/line.ts ***!
\*****************************/
/*! exports provided: Line */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Line", function() { return Line; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../../node_modules/tslib/tslib.es6.js");
/* harmony import */ var babylonjs_Maths_math__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! babylonjs/Maths/math */ "babylonjs/Misc/observable");
/* harmony import */ var babylonjs_Maths_math__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(babylonjs_Maths_math__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var _control__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./control */ "./2D/controls/control.ts");
/* harmony import */ var _valueAndUnit__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../valueAndUnit */ "./2D/valueAndUnit.ts");
/** Class used to render 2D lines */
var Line = /** @class */ (function (_super) {
tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](Line, _super);
/**
* Creates a new Line
* @param name defines the control name
*/
function Line(name) {
var _this = _super.call(this, name) || this;
_this.name = name;
_this._lineWidth = 1;
_this._x1 = new _valueAndUnit__WEBPACK_IMPORTED_MODULE_3__["ValueAndUnit"](0);
_this._y1 = new _valueAndUnit__WEBPACK_IMPORTED_MODULE_3__["ValueAndUnit"](0);
_this._x2 = new _valueAndUnit__WEBPACK_IMPORTED_MODULE_3__["ValueAndUnit"](0);
_this._y2 = new _valueAndUnit__WEBPACK_IMPORTED_MODULE_3__["ValueAndUnit"](0);
_this._dash = new Array();
_this.isHitTestVisible = false;
_this._horizontalAlignment = _control__WEBPACK_IMPORTED_MODULE_2__["Control"].HORIZONTAL_ALIGNMENT_LEFT;
_this._verticalAlignment = _control__WEBPACK_IMPORTED_MODULE_2__["Control"].VERTICAL_ALIGNMENT_TOP;
return _this;
}
Object.defineProperty(Line.prototype, "dash", {
/** Gets or sets the dash pattern */
get: function () {
return this._dash;
},
set: function (value) {
if (this._dash === value) {
return;
}
this._dash = value;
this._markAsDirty();
},
enumerable: true,
configurable: true
});
Object.defineProperty(Line.prototype, "connectedControl", {
/** Gets or sets the control connected with the line end */
get: function () {
return this._connectedControl;
},
set: function (value) {
var _this = this;
if (this._connectedControl === value) {
return;
}
if (this._connectedControlDirtyObserver && this._connectedControl) {
this._connectedControl.onDirtyObservable.remove(this._connectedControlDirtyObserver);
this._connectedControlDirtyObserver = null;
}
if (value) {
this._connectedControlDirtyObserver = value.onDirtyObservable.add(function () { return _this._markAsDirty(); });
}
this._connectedControl = value;
this._markAsDirty();
},
enumerable: true,
configurable: true
});
Object.defineProperty(Line.prototype, "x1", {
/** Gets or sets start coordinates on X axis */
get: function () {
return this._x1.toString(this._host);
},
set: function (value) {
if (this._x1.toString(this._host) === value) {
return;
}
if (this._x1.fromString(value)) {
this._markAsDirty();
}
},
enumerable: true,
configurable: true
});
Object.defineProperty(Line.prototype, "y1", {
/** Gets or sets start coordinates on Y axis */
get: function () {
return this._y1.toString(this._host);
},
set: function (value) {
if (this._y1.toString(this._host) === value) {
return;
}
if (this._y1.fromString(value)) {
this._markAsDirty();
}
},
enumerable: true,
configurable: true
});
Object.defineProperty(Line.prototype, "x2", {
/** Gets or sets end coordinates on X axis */
get: function () {
return this._x2.toString(this._host);
},
set: function (value) {
if (this._x2.toString(this._host) === value) {
return;
}
if (this._x2.fromString(value)) {
this._markAsDirty();
}
},
enumerable: true,
configurable: true
});
Object.defineProperty(Line.prototype, "y2", {
/** Gets or sets end coordinates on Y axis */
get: function () {
return this._y2.toString(this._host);
},
set: function (value) {
if (this._y2.toString(this._host) === value) {
return;
}
if (this._y2.fromString(value)) {
this._markAsDirty();
}
},
enumerable: true,
configurable: true
});
Object.defineProperty(Line.prototype, "lineWidth", {
/** Gets or sets line width */
get: function () {
return this._lineWidth;
},
set: function (value) {
if (this._lineWidth === value) {
return;
}
this._lineWidth = value;
this._markAsDirty();
},
enumerable: true,
configurable: true
});
Object.defineProperty(Line.prototype, "horizontalAlignment", {
/** Gets or sets horizontal alignment */
set: function (value) {
return;
},
enumerable: true,
configurable: true
});
Object.defineProperty(Line.prototype, "verticalAlignment", {
/** Gets or sets vertical alignment */
set: function (value) {
return;
},
enumerable: true,
configurable: true
});
Object.defineProperty(Line.prototype, "_effectiveX2", {
get: function () {
return (this._connectedControl ? this._connectedControl.centerX : 0) + this._x2.getValue(this._host);
},
enumerable: true,
configurable: true
});
Object.defineProperty(Line.prototype, "_effectiveY2", {
get: function () {
return (this._connectedControl ? this._connectedControl.centerY : 0) + this._y2.getValue(this._host);
},
enumerable: true,
configurable: true
});
Line.prototype._getTypeName = function () {
return "Line";
};
Line.prototype._draw = function (context) {
context.save();
if (this.shadowBlur || this.shadowOffsetX || this.shadowOffsetY) {
context.shadowColor = this.shadowColor;
context.shadowBlur = this.shadowBlur;
context.shadowOffsetX = this.shadowOffsetX;
context.shadowOffsetY = this.shadowOffsetY;
}
this._applyStates(context);
context.strokeStyle = this.color;
context.lineWidth = this._lineWidth;
context.setLineDash(this._dash);
context.beginPath();
context.moveTo(this._cachedParentMeasure.left + this._x1.getValue(this._host), this._cachedParentMeasure.left + this._y1.getValue(this._host));
context.lineTo(this._cachedParentMeasure.left + this._effectiveX2, this._cachedParentMeasure.left + this._effectiveY2);
context.stroke();
context.restore();
};
Line.prototype._measure = function () {
// Width / Height
this._currentMeasure.width = Math.abs(this._x1.getValue(this._host) - this._effectiveX2) + this._lineWidth;
this._currentMeasure.height = Math.abs(this._y1.getValue(this._host) - this._effectiveY2) + this._lineWidth;
};
Line.prototype._computeAlignment = function (parentMeasure, context) {
this._currentMeasure.left = parentMeasure.left + Math.min(this._x1.getValue(this._host), this._effectiveX2) - this._lineWidth / 2;
this._currentMeasure.top = parentMeasure.top + Math.min(this._y1.getValue(this._host), this._effectiveY2) - this._lineWidth / 2;
};
/**
* Move one end of the line given 3D cartesian coordinates.
* @param position Targeted world position
* @param scene Scene
* @param end (opt) Set to true to assign x2 and y2 coordinates of the line. Default assign to x1 and y1.
*/
Line.prototype.moveToVector3 = function (position, scene, end) {
if (end === void 0) { end = false; }
if (!this._host || this.parent !== this._host._rootContainer) {
babylonjs_Maths_math__WEBPACK_IMPORTED_MODULE_1__["Tools"].Error("Cannot move a control to a vector3 if the control is not at root level");
return;
}
var globalViewport = this._host._getGlobalViewport(scene);
var projectedPosition = babylonjs_Maths_math__WEBPACK_IMPORTED_MODULE_1__["Vector3"].Project(position, babylonjs_Maths_math__WEBPACK_IMPORTED_MODULE_1__["Matrix"].Identity(), scene.getTransformMatrix(), globalViewport);
this._moveToProjectedPosition(projectedPosition, end);
if (projectedPosition.z < 0 || projectedPosition.z > 1) {
this.notRenderable = true;
return;
}
this.notRenderable = false;
};
/**
* Move one end of the line to a position in screen absolute space.
* @param projectedPosition Position in screen absolute space (X, Y)
* @param end (opt) Set to true to assign x2 and y2 coordinates of the line. Default assign to x1 and y1.
*/
Line.prototype._moveToProjectedPosition = function (projectedPosition, end) {
if (end === void 0) { end = false; }
var x = (projectedPosition.x + this._linkOffsetX.getValue(this._host)) + "px";
var y = (projectedPosition.y + this._linkOffsetY.getValue(this._host)) + "px";
if (end) {
this.x2 = x;
this.y2 = y;
this._x2.ignoreAdaptiveScaling = true;
this._y2.ignoreAdaptiveScaling = true;
}
else {
this.x1 = x;
this.y1 = y;
this._x1.ignoreAdaptiveScaling = true;
this._y1.ignoreAdaptiveScaling = true;
}
};
return Line;
}(_control__WEBPACK_IMPORTED_MODULE_2__["Control"]));
/***/ }),
/***/ "./2D/controls/multiLine.ts":
/*!**********************************!*\
!*** ./2D/controls/multiLine.ts ***!
\**********************************/
/*! exports provided: MultiLine */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "MultiLine", function() { return MultiLine; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../../node_modules/tslib/tslib.es6.js");
/* harmony import */ var babylonjs_Meshes_abstractMesh__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! babylonjs/Meshes/abstractMesh */ "babylonjs/Misc/observable");
/* harmony import */ var babylonjs_Meshes_abstractMesh__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(babylonjs_Meshes_abstractMesh__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var _control__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./control */ "./2D/controls/control.ts");
/* harmony import */ var _multiLinePoint__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../multiLinePoint */ "./2D/multiLinePoint.ts");
/**
* Class used to create multi line control
*/
var MultiLine = /** @class */ (function (_super) {
tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](MultiLine, _super);
/**
* Creates a new MultiLine
* @param name defines the control name
*/
function MultiLine(name) {
var _this = _super.call(this, name) || this;
_this.name = name;
_this._lineWidth = 1;
/** Function called when a point is updated */
_this.onPointUpdate = function () {
_this._markAsDirty();
};
_this.isHitTestVisible = false;
_this._horizontalAlignment = _control__WEBPACK_IMPORTED_MODULE_2__["Control"].HORIZONTAL_ALIGNMENT_LEFT;
_this._verticalAlignment = _control__WEBPACK_IMPORTED_MODULE_2__["Control"].VERTICAL_ALIGNMENT_TOP;
_this._dash = [];
_this._points = [];
return _this;
}
Object.defineProperty(MultiLine.prototype, "dash", {
/** Gets or sets dash pattern */
get: function () {
return this._dash;
},
set: function (value) {
if (this._dash === value) {
return;
}
this._dash = value;
this._markAsDirty();
},
enumerable: true,
configurable: true
});
/**
* Gets point stored at specified index
* @param index defines the index to look for
* @returns the requested point if found
*/
MultiLine.prototype.getAt = function (index) {
if (!this._points[index]) {
this._points[index] = new _multiLinePoint__WEBPACK_IMPORTED_MODULE_3__["MultiLinePoint"](this);
}
return this._points[index];
};
/**
* Adds new points to the point collection
* @param items defines the list of items (mesh, control or 2d coordiantes) to add
* @returns the list of created MultiLinePoint
*/
MultiLine.prototype.add = function () {
var _this = this;
var items = [];
for (var _i = 0; _i < arguments.length; _i++) {
items[_i] = arguments[_i];
}
return items.map(function (item) { return _this.push(item); });
};
/**
* Adds a new point to the point collection
* @param item defines the item (mesh, control or 2d coordiantes) to add
* @returns the created MultiLinePoint
*/
MultiLine.prototype.push = function (item) {
var point = this.getAt(this._points.length);
if (item == null) {
return point;
}
if (item instanceof babylonjs_Meshes_abstractMesh__WEBPACK_IMPORTED_MODULE_1__["AbstractMesh"]) {
point.mesh = item;
}
else if (item instanceof _control__WEBPACK_IMPORTED_MODULE_2__["Control"]) {
point.control = item;
}
else if (item.x != null && item.y != null) {
point.x = item.x;
point.y = item.y;
}
return point;
};
/**
* Remove a specific value or point from the active point collection
* @param value defines the value or point to remove
*/
MultiLine.prototype.remove = function (value) {
var index;
if (value instanceof _multiLinePoint__WEBPACK_IMPORTED_MODULE_3__["MultiLinePoint"]) {
index = this._points.indexOf(value);
if (index === -1) {
return;
}
}
else {
index = value;
}
var point = this._points[index];
if (!point) {
return;
}
point.dispose();
this._points.splice(index, 1);
};
/**
* Resets this object to initial state (no point)
*/
MultiLine.prototype.reset = function () {
while (this._points.length > 0) {
this.remove(this._points.length - 1);
}
};
/**
* Resets all links
*/
MultiLine.prototype.resetLinks = function () {
this._points.forEach(function (point) {
if (point != null) {
point.resetLinks();
}
});
};
Object.defineProperty(MultiLine.prototype, "lineWidth", {
/** Gets or sets line width */
get: function () {
return this._lineWidth;
},
set: function (value) {
if (this._lineWidth === value) {
return;
}
this._lineWidth = value;
this._markAsDirty();
},
enumerable: true,
configurable: true
});
Object.defineProperty(MultiLine.prototype, "horizontalAlignment", {
set: function (value) {
return;
},
enumerable: true,
configurable: true
});
Object.defineProperty(MultiLine.prototype, "verticalAlignment", {
set: function (value) {
return;
},
enumerable: true,
configurable: true
});
MultiLine.prototype._getTypeName = function () {
return "MultiLine";
};
MultiLine.prototype._draw = function (context) {
context.save();
if (this.shadowBlur || this.shadowOffsetX || this.shadowOffsetY) {
context.shadowColor = this.shadowColor;
context.shadowBlur = this.shadowBlur;
context.shadowOffsetX = this.shadowOffsetX;
context.shadowOffsetY = this.shadowOffsetY;
}
this._applyStates(context);
context.strokeStyle = this.color;
context.lineWidth = this._lineWidth;
context.setLineDash(this._dash);
context.beginPath();
var first = true; //first index is not necessarily 0
this._points.forEach(function (point) {
if (!point) {
return;
}
if (first) {
context.moveTo(point._point.x, point._point.y);
first = false;
}
else {
context.lineTo(point._point.x, point._point.y);
}
});
context.stroke();
context.restore();
};
MultiLine.prototype._additionalProcessing = function (parentMeasure, context) {
var _this = this;
this._minX = null;
this._minY = null;
this._maxX = null;
this._maxY = null;
this._points.forEach(function (point, index) {
if (!point) {
return;
}
point.translate();
if (_this._minX == null || point._point.x < _this._minX) {
_this._minX = point._point.x;
}
if (_this._minY == null || point._point.y < _this._minY) {
_this._minY = point._point.y;
}
if (_this._maxX == null || point._point.x > _this._maxX) {
_this._maxX = point._point.x;
}
if (_this._maxY == null || point._point.y > _this._maxY) {
_this._maxY = point._point.y;
}
});
if (this._minX == null) {
this._minX = 0;
}
if (this._minY == null) {
this._minY = 0;
}
if (this._maxX == null) {
this._maxX = 0;
}
if (this._maxY == null) {
this._maxY = 0;
}
};
MultiLine.prototype._measure = function () {
if (this._minX == null || this._maxX == null || this._minY == null || this._maxY == null) {
return;
}
this._currentMeasure.width = Math.abs(this._maxX - this._minX) + this._lineWidth;
this._currentMeasure.height = Math.abs(this._maxY - this._minY) + this._lineWidth;
};
MultiLine.prototype._computeAlignment = function (parentMeasure, context) {
if (this._minX == null || this._minY == null) {
return;
}
this._currentMeasure.left = this._minX - this._lineWidth / 2;
this._currentMeasure.top = this._minY - this._lineWidth / 2;
};
MultiLine.prototype.dispose = function () {
this.reset();
_super.prototype.dispose.call(this);
};
return MultiLine;
}(_control__WEBPACK_IMPORTED_MODULE_2__["Control"]));
/***/ }),
/***/ "./2D/controls/radioButton.ts":
/*!************************************!*\
!*** ./2D/controls/radioButton.ts ***!
\************************************/
/*! exports provided: RadioButton */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "RadioButton", function() { return RadioButton; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../../node_modules/tslib/tslib.es6.js");
/* harmony import */ var babylonjs_Misc_observable__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! babylonjs/Misc/observable */ "babylonjs/Misc/observable");
/* harmony import */ var babylonjs_Misc_observable__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(babylonjs_Misc_observable__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var _control__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./control */ "./2D/controls/control.ts");
/* harmony import */ var _stackPanel__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./stackPanel */ "./2D/controls/stackPanel.ts");
/* harmony import */ var _textBlock__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./textBlock */ "./2D/controls/textBlock.ts");
/**
* Class used to create radio button controls
*/
var RadioButton = /** @class */ (function (_super) {
tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](RadioButton, _super);
/**
* Creates a new RadioButton
* @param name defines the control name
*/
function RadioButton(name) {
var _this = _super.call(this, name) || this;
_this.name = name;
_this._isChecked = false;
_this._background = "black";
_this._checkSizeRatio = 0.8;
_this._thickness = 1;
/** Gets or sets group name */
_this.group = "";
/** Observable raised when isChecked is changed */
_this.onIsCheckedChangedObservable = new babylonjs_Misc_observable__WEBPACK_IMPORTED_MODULE_1__["Observable"]();
_this.isPointerBlocker = true;
return _this;
}
Object.defineProperty(RadioButton.prototype, "thickness", {
/** Gets or sets border thickness */
get: function () {
return this._thickness;
},
set: function (value) {
if (this._thickness === value) {
return;
}
this._thickness = value;
this._markAsDirty();
},
enumerable: true,
configurable: true
});
Object.defineProperty(RadioButton.prototype, "checkSizeRatio", {
/** Gets or sets a value indicating the ratio between overall size and check size */
get: function () {
return this._checkSizeRatio;
},
set: function (value) {
value = Math.max(Math.min(1, value), 0);
if (this._checkSizeRatio === value) {
return;
}
this._checkSizeRatio = value;
this._markAsDirty();
},
enumerable: true,
configurable: true
});
Object.defineProperty(RadioButton.prototype, "background", {
/** Gets or sets background color */
get: function () {
return this._background;
},
set: function (value) {
if (this._background === value) {
return;
}
this._background = value;
this._markAsDirty();
},
enumerable: true,
configurable: true
});
Object.defineProperty(RadioButton.prototype, "isChecked", {
/** Gets or sets a boolean indicating if the checkbox is checked or not */
get: function () {
return this._isChecked;
},
set: function (value) {
var _this = this;
if (this._isChecked === value) {
return;
}
this._isChecked = value;
this._markAsDirty();
this.onIsCheckedChangedObservable.notifyObservers(value);
if (this._isChecked && this._host) {
// Update all controls from same group
this._host.executeOnAllControls(function (control) {
if (control === _this) {
return;
}
if (control.group === undefined) {
return;
}
var childRadio = control;
if (childRadio.group === _this.group) {
childRadio.isChecked = false;
}
});
}
},
enumerable: true,
configurable: true
});
RadioButton.prototype._getTypeName = function () {
return "RadioButton";
};
RadioButton.prototype._draw = function (context) {
context.save();
this._applyStates(context);
var actualWidth = this._currentMeasure.width - this._thickness;
var actualHeight = this._currentMeasure.height - this._thickness;
if (this.shadowBlur || this.shadowOffsetX || this.shadowOffsetY) {
context.shadowColor = this.shadowColor;
context.shadowBlur = this.shadowBlur;
context.shadowOffsetX = this.shadowOffsetX;
context.shadowOffsetY = this.shadowOffsetY;
}
// Outer
_control__WEBPACK_IMPORTED_MODULE_2__["Control"].drawEllipse(this._currentMeasure.left + this._currentMeasure.width / 2, this._currentMeasure.top + this._currentMeasure.height / 2, this._currentMeasure.width / 2 - this._thickness / 2, this._currentMeasure.height / 2 - this._thickness / 2, context);
context.fillStyle = this._isEnabled ? this._background : this._disabledColor;
context.fill();
if (this.shadowBlur || this.shadowOffsetX || this.shadowOffsetY) {
context.shadowBlur = 0;
context.shadowOffsetX = 0;
context.shadowOffsetY = 0;
}
context.strokeStyle = this.color;
context.lineWidth = this._thickness;
context.stroke();
// Inner
if (this._isChecked) {
context.fillStyle = this._isEnabled ? this.color : this._disabledColor;
var offsetWidth = actualWidth * this._checkSizeRatio;
var offseHeight = actualHeight * this._checkSizeRatio;
_control__WEBPACK_IMPORTED_MODULE_2__["Control"].drawEllipse(this._currentMeasure.left + this._currentMeasure.width / 2, this._currentMeasure.top + this._currentMeasure.height / 2, offsetWidth / 2 - this._thickness / 2, offseHeight / 2 - this._thickness / 2, context);
context.fill();
}
context.restore();
};
// Events
RadioButton.prototype._onPointerDown = function (target, coordinates, pointerId, buttonIndex) {
if (!_super.prototype._onPointerDown.call(this, target, coordinates, pointerId, buttonIndex)) {
return false;
}
if (!this.isChecked) {
this.isChecked = true;
}
return true;
};
/**
* Utility function to easily create a radio button with a header
* @param title defines the label to use for the header
* @param group defines the group to use for the radio button
* @param isChecked defines the initial state of the radio button
* @param onValueChanged defines the callback to call when value changes
* @returns a StackPanel containing the radio button and a textBlock
*/
RadioButton.AddRadioButtonWithHeader = function (title, group, isChecked, onValueChanged) {
var panel = new _stackPanel__WEBPACK_IMPORTED_MODULE_3__["StackPanel"]();
panel.isVertical = false;
panel.height = "30px";
var radio = new RadioButton();
radio.width = "20px";
radio.height = "20px";
radio.isChecked = isChecked;
radio.color = "green";
radio.group = group;
radio.onIsCheckedChangedObservable.add(function (value) { return onValueChanged(radio, value); });
panel.addControl(radio);
var header = new _textBlock__WEBPACK_IMPORTED_MODULE_4__["TextBlock"]();
header.text = title;
header.width = "180px";
header.paddingLeft = "5px";
header.textHorizontalAlignment = _control__WEBPACK_IMPORTED_MODULE_2__["Control"].HORIZONTAL_ALIGNMENT_LEFT;
header.color = "white";
panel.addControl(header);
return panel;
};
return RadioButton;
}(_control__WEBPACK_IMPORTED_MODULE_2__["Control"]));
/***/ }),
/***/ "./2D/controls/rectangle.ts":
/*!**********************************!*\
!*** ./2D/controls/rectangle.ts ***!
\**********************************/
/*! exports provided: Rectangle */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Rectangle", function() { return Rectangle; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../../node_modules/tslib/tslib.es6.js");
/* harmony import */ var _container__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./container */ "./2D/controls/container.ts");
/** Class used to create rectangle container */
var Rectangle = /** @class */ (function (_super) {
tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](Rectangle, _super);
/**
* Creates a new Rectangle
* @param name defines the control name
*/
function Rectangle(name) {
var _this = _super.call(this, name) || this;
_this.name = name;
_this._thickness = 1;
_this._cornerRadius = 0;
return _this;
}
Object.defineProperty(Rectangle.prototype, "thickness", {
/** Gets or sets border thickness */
get: function () {
return this._thickness;
},
set: function (value) {
if (this._thickness === value) {
return;
}
this._thickness = value;
this._markAsDirty();
},
enumerable: true,
configurable: true
});
Object.defineProperty(Rectangle.prototype, "cornerRadius", {
/** Gets or sets the corner radius angle */
get: function () {
return this._cornerRadius;
},
set: function (value) {
if (value < 0) {
value = 0;
}
if (this._cornerRadius === value) {
return;
}
this._cornerRadius = value;
this._markAsDirty();
},
enumerable: true,
configurable: true
});
Rectangle.prototype._getTypeName = function () {
return "Rectangle";
};
Rectangle.prototype._localDraw = function (context) {
context.save();
if (this.shadowBlur || this.shadowOffsetX || this.shadowOffsetY) {
context.shadowColor = this.shadowColor;
context.shadowBlur = this.shadowBlur;
context.shadowOffsetX = this.shadowOffsetX;
context.shadowOffsetY = this.shadowOffsetY;
}
if (this._background) {
context.fillStyle = this._background;
if (this._cornerRadius) {
this._drawRoundedRect(context, this._thickness / 2);
context.fill();
}
else {
context.fillRect(this._currentMeasure.left, this._currentMeasure.top, this._currentMeasure.width, this._currentMeasure.height);
}
}
if (this._thickness) {
if (this.shadowBlur || this.shadowOffsetX || this.shadowOffsetY) {
context.shadowBlur = 0;
context.shadowOffsetX = 0;
context.shadowOffsetY = 0;
}
if (this.color) {
context.strokeStyle = this.color;
}
context.lineWidth = this._thickness;
if (this._cornerRadius) {
this._drawRoundedRect(context, this._thickness / 2);
context.stroke();
}
else {
context.strokeRect(this._currentMeasure.left + this._thickness / 2, this._currentMeasure.top + this._thickness / 2, this._currentMeasure.width - this._thickness, this._currentMeasure.height - this._thickness);
}
}
context.restore();
};
Rectangle.prototype._additionalProcessing = function (parentMeasure, context) {
_super.prototype._additionalProcessing.call(this, parentMeasure, context);
this._measureForChildren.width -= 2 * this._thickness;
this._measureForChildren.height -= 2 * this._thickness;
this._measureForChildren.left += this._thickness;
this._measureForChildren.top += this._thickness;
};
Rectangle.prototype._drawRoundedRect = function (context, offset) {
if (offset === void 0) { offset = 0; }
var x = this._currentMeasure.left + offset;
var y = this._currentMeasure.top + offset;
var width = this._currentMeasure.width - offset * 2;
var height = this._currentMeasure.height - offset * 2;
var radius = Math.min(height / 2 - 2, Math.min(width / 2 - 2, this._cornerRadius));
context.beginPath();
context.moveTo(x + radius, y);
context.lineTo(x + width - radius, y);
context.quadraticCurveTo(x + width, y, x + width, y + radius);
context.lineTo(x + width, y + height - radius);
context.quadraticCurveTo(x + width, y + height, x + width - radius, y + height);
context.lineTo(x + radius, y + height);
context.quadraticCurveTo(x, y + height, x, y + height - radius);
context.lineTo(x, y + radius);
context.quadraticCurveTo(x, y, x + radius, y);
context.closePath();
};
Rectangle.prototype._clipForChildren = function (context) {
if (this._cornerRadius) {
this._drawRoundedRect(context, this._thickness);
context.clip();
}
};
return Rectangle;
}(_container__WEBPACK_IMPORTED_MODULE_1__["Container"]));
/***/ }),
/***/ "./2D/controls/scrollViewers/scrollViewer.ts":
/*!***************************************************!*\
!*** ./2D/controls/scrollViewers/scrollViewer.ts ***!
\***************************************************/
/*! exports provided: ScrollViewer */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ScrollViewer", function() { return ScrollViewer; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../../node_modules/tslib/tslib.es6.js");
/* harmony import */ var babylonjs_Events_pointerEvents__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! babylonjs/Events/pointerEvents */ "babylonjs/Misc/observable");
/* harmony import */ var babylonjs_Events_pointerEvents__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(babylonjs_Events_pointerEvents__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var _rectangle__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../rectangle */ "./2D/controls/rectangle.ts");
/* harmony import */ var _grid__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../grid */ "./2D/controls/grid.ts");
/* harmony import */ var _control__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../control */ "./2D/controls/control.ts");
/* harmony import */ var _scrollViewerWindow__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./scrollViewerWindow */ "./2D/controls/scrollViewers/scrollViewerWindow.ts");
/* harmony import */ var _sliders_scrollBar__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../sliders/scrollBar */ "./2D/controls/sliders/scrollBar.ts");
/**
* Class used to hold a viewer window and sliders in a grid
*/
var ScrollViewer = /** @class */ (function (_super) {
tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](ScrollViewer, _super);
/**
* Creates a new ScrollViewer
* @param name of ScrollViewer
*/
function ScrollViewer(name) {
var _this = _super.call(this, name) || this;
_this._barSize = 20;
_this._pointerIsOver = false;
_this._wheelPrecision = 0.05;
_this.onDirtyObservable.add(function () {
_this._horizontalBarSpace.color = _this.color;
_this._verticalBarSpace.color = _this.color;
_this._dragSpace.color = _this.color;
});
_this.onPointerEnterObservable.add(function () {
_this._pointerIsOver = true;
});
_this.onPointerOutObservable.add(function () {
_this._pointerIsOver = false;
});
_this._grid = new _grid__WEBPACK_IMPORTED_MODULE_3__["Grid"]();
_this._horizontalBar = new _sliders_scrollBar__WEBPACK_IMPORTED_MODULE_6__["ScrollBar"]();
_this._verticalBar = new _sliders_scrollBar__WEBPACK_IMPORTED_MODULE_6__["ScrollBar"]();
_this._window = new _scrollViewerWindow__WEBPACK_IMPORTED_MODULE_5__["_ScrollViewerWindow"]();
_this._window.horizontalAlignment = _control__WEBPACK_IMPORTED_MODULE_4__["Control"].HORIZONTAL_ALIGNMENT_LEFT;
_this._window.verticalAlignment = _control__WEBPACK_IMPORTED_MODULE_4__["Control"].VERTICAL_ALIGNMENT_TOP;
_this._grid.addColumnDefinition(1);
_this._grid.addColumnDefinition(0, true);
_this._grid.addRowDefinition(1);
_this._grid.addRowDefinition(0, true);
_super.prototype.addControl.call(_this, _this._grid);
_this._grid.addControl(_this._window, 0, 0);
_this._verticalBar.paddingLeft = 0;
_this._verticalBar.width = "100%";
_this._verticalBar.height = "100%";
_this._verticalBar.barOffset = 0;
_this._verticalBar.value = 0;
_this._verticalBar.maximum = 1;
_this._verticalBar.horizontalAlignment = _control__WEBPACK_IMPORTED_MODULE_4__["Control"].HORIZONTAL_ALIGNMENT_CENTER;
_this._verticalBar.verticalAlignment = _control__WEBPACK_IMPORTED_MODULE_4__["Control"].VERTICAL_ALIGNMENT_CENTER;
_this._verticalBar.isVertical = true;
_this._verticalBar.rotation = Math.PI;
_this._verticalBar.isVisible = false;
_this._verticalBarSpace = new _rectangle__WEBPACK_IMPORTED_MODULE_2__["Rectangle"]();
_this._verticalBarSpace.horizontalAlignment = _control__WEBPACK_IMPORTED_MODULE_4__["Control"].HORIZONTAL_ALIGNMENT_LEFT;
_this._verticalBarSpace.verticalAlignment = _control__WEBPACK_IMPORTED_MODULE_4__["Control"].VERTICAL_ALIGNMENT_TOP;
_this._verticalBarSpace.thickness = 1;
_this._grid.addControl(_this._verticalBarSpace, 0, 1);
_this._verticalBarSpace.addControl(_this._verticalBar);
_this._verticalBar.onValueChangedObservable.add(function (value) {
_this._window.top = value * _this._endTop + "px";
});
_this._horizontalBar.paddingLeft = 0;
_this._horizontalBar.width = "100%";
_this._horizontalBar.height = "100%";
_this._horizontalBar.barOffset = 0;
_this._horizontalBar.value = 0;
_this._horizontalBar.maximum = 1;
_this._horizontalBar.horizontalAlignment = _control__WEBPACK_IMPORTED_MODULE_4__["Control"].HORIZONTAL_ALIGNMENT_CENTER;
_this._horizontalBar.verticalAlignment = _control__WEBPACK_IMPORTED_MODULE_4__["Control"].VERTICAL_ALIGNMENT_CENTER;
_this._horizontalBar.isVisible = false;
_this._horizontalBarSpace = new _rectangle__WEBPACK_IMPORTED_MODULE_2__["Rectangle"]();
_this._horizontalBarSpace.horizontalAlignment = _control__WEBPACK_IMPORTED_MODULE_4__["Control"].HORIZONTAL_ALIGNMENT_LEFT;
_this._horizontalBarSpace.verticalAlignment = _control__WEBPACK_IMPORTED_MODULE_4__["Control"].VERTICAL_ALIGNMENT_TOP;
_this._horizontalBarSpace.thickness = 1;
_this._grid.addControl(_this._horizontalBarSpace, 1, 0);
_this._horizontalBarSpace.addControl(_this._horizontalBar);
_this._horizontalBar.onValueChangedObservable.add(function (value) {
_this._window.left = value * _this._endLeft + "px";
});
_this._dragSpace = new _rectangle__WEBPACK_IMPORTED_MODULE_2__["Rectangle"]();
_this._dragSpace.thickness = 1;
_this._grid.addControl(_this._dragSpace, 1, 1);
// Colors
_this.barColor = "grey";
_this.barBackground = "transparent";
return _this;
}
Object.defineProperty(ScrollViewer.prototype, "horizontalBar", {
/**
* Gets the horizontal scrollbar
*/
get: function () {
return this._horizontalBar;
},
enumerable: true,
configurable: true
});
Object.defineProperty(ScrollViewer.prototype, "verticalBar", {
/**
* Gets the vertical scrollbar
*/
get: function () {
return this._verticalBar;
},
enumerable: true,
configurable: true
});
/**
* Adds a new control to the current container
* @param control defines the control to add
* @returns the current container
*/
ScrollViewer.prototype.addControl = function (control) {
if (!control) {
return this;
}
this._window.addControl(control);
return this;
};
/**
* Removes a control from the current container
* @param control defines the control to remove
* @returns the current container
*/
ScrollViewer.prototype.removeControl = function (control) {
this._window.removeControl(control);
return this;
};
Object.defineProperty(ScrollViewer.prototype, "children", {
/** Gets the list of children */
get: function () {
return this._window.children;
},
enumerable: true,
configurable: true
});
ScrollViewer.prototype._flagDescendantsAsMatrixDirty = function () {
for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
var child = _a[_i];
child._markMatrixAsDirty();
}
};
/** Reset the scroll viewer window to initial size */
ScrollViewer.prototype.resetWindow = function () {
this._window.width = "100%";
this._window.height = "100%";
};
ScrollViewer.prototype._getTypeName = function () {
return "ScrollViewer";
};
ScrollViewer.prototype._buildClientSizes = function () {
this._window.parentClientWidth = this._currentMeasure.width - (this._verticalBar.isVisible ? this._barSize : 0) - 2 * this.thickness;
this._window.parentClientHeight = this._currentMeasure.height - (this._horizontalBar.isVisible ? this._barSize : 0) - 2 * this.thickness;
this._clientWidth = this._window.parentClientWidth;
this._clientHeight = this._window.parentClientHeight;
};
ScrollViewer.prototype._additionalProcessing = function (parentMeasure, context) {
_super.prototype._additionalProcessing.call(this, parentMeasure, context);
this._buildClientSizes();
};
ScrollViewer.prototype._postMeasure = function () {
_super.prototype._postMeasure.call(this);
this._updateScroller();
};
Object.defineProperty(ScrollViewer.prototype, "wheelPrecision", {
/**
* Gets or sets the mouse wheel precision
* from 0 to 1 with a default value of 0.05
* */
get: function () {
return this._wheelPrecision;
},
set: function (value) {
if (this._wheelPrecision === value) {
return;
}
if (value < 0) {
value = 0;
}
if (value > 1) {
value = 1;
}
this._wheelPrecision = value;
},
enumerable: true,
configurable: true
});
Object.defineProperty(ScrollViewer.prototype, "barColor", {
/** Gets or sets the bar color */
get: function () {
return this._barColor;
},
set: function (color) {
if (this._barColor === color) {
return;
}
this._barColor = color;
this._horizontalBar.color = color;
this._verticalBar.color = color;
},
enumerable: true,
configurable: true
});
Object.defineProperty(ScrollViewer.prototype, "barSize", {
/** Gets or sets the size of the bar */
get: function () {
return this._barSize;
},
set: function (value) {
if (this._barSize === value) {
return;
}
this._barSize = value;
this._markAsDirty();
if (this._horizontalBar.isVisible) {
this._grid.setRowDefinition(1, this._barSize, true);
}
if (this._verticalBar.isVisible) {
this._grid.setColumnDefinition(1, this._barSize, true);
}
},
enumerable: true,
configurable: true
});
Object.defineProperty(ScrollViewer.prototype, "barBackground", {
/** Gets or sets the bar background */
get: function () {
return this._barBackground;
},
set: function (color) {
if (this._barBackground === color) {
return;
}
this._barBackground = color;
this._horizontalBar.background = color;
this._verticalBar.background = color;
this._dragSpace.background = color;
},
enumerable: true,
configurable: true
});
/** @hidden */
ScrollViewer.prototype._updateScroller = function () {
var windowContentsWidth = this._window._currentMeasure.width;
var windowContentsHeight = this._window._currentMeasure.height;
if (this._horizontalBar.isVisible && windowContentsWidth <= this._clientWidth) {
this._grid.setRowDefinition(1, 0, true);
this._horizontalBar.isVisible = false;
this._horizontalBar.value = 0;
this._rebuildLayout = true;
}
else if (!this._horizontalBar.isVisible && windowContentsWidth > this._clientWidth) {
this._grid.setRowDefinition(1, this._barSize, true);
this._horizontalBar.isVisible = true;
this._rebuildLayout = true;
}
if (this._verticalBar.isVisible && windowContentsHeight <= this._clientHeight) {
this._grid.setColumnDefinition(1, 0, true);
this._verticalBar.isVisible = false;
this._verticalBar.value = 0;
this._rebuildLayout = true;
}
else if (!this._verticalBar.isVisible && windowContentsHeight > this._clientHeight) {
this._grid.setColumnDefinition(1, this._barSize, true);
this._verticalBar.isVisible = true;
this._rebuildLayout = true;
}
this._buildClientSizes();
this._endLeft = this._clientWidth - windowContentsWidth;
this._endTop = this._clientHeight - windowContentsHeight;
var newLeft = this._horizontalBar.value * this._endLeft + "px";
var newTop = this._verticalBar.value * this._endTop + "px";
if (newLeft !== this._window.left) {
this._window.left = newLeft;
this._rebuildLayout = true;
}
if (newTop !== this._window.top) {
this._window.top = newTop;
this._rebuildLayout = true;
}
var horizontalMultiplicator = this._clientWidth / windowContentsWidth;
var verticalMultiplicator = this._clientHeight / windowContentsHeight;
this._horizontalBar.thumbWidth = (this._clientWidth * horizontalMultiplicator) + "px";
this._verticalBar.thumbWidth = (this._clientHeight * verticalMultiplicator) + "px";
};
ScrollViewer.prototype._link = function (host) {
_super.prototype._link.call(this, host);
this._attachWheel();
};
/** @hidden */
ScrollViewer.prototype._attachWheel = function () {
var _this = this;
if (!this._host || this._onPointerObserver) {
return;
}
var scene = this._host.getScene();
this._onPointerObserver = scene.onPointerObservable.add(function (pi, state) {
if (!_this._pointerIsOver || pi.type !== babylonjs_Events_pointerEvents__WEBPACK_IMPORTED_MODULE_1__["PointerEventTypes"].POINTERWHEEL) {
return;
}
if (_this._verticalBar.isVisible == true) {
if (pi.event.deltaY < 0 && _this._verticalBar.value > 0) {
_this._verticalBar.value -= _this._wheelPrecision;
}
else if (pi.event.deltaY > 0 && _this._verticalBar.value < _this._verticalBar.maximum) {
_this._verticalBar.value += _this._wheelPrecision;
}
}
if (_this._horizontalBar.isVisible == true) {
if (pi.event.deltaX < 0 && _this._horizontalBar.value < _this._horizontalBar.maximum) {
_this._horizontalBar.value += _this._wheelPrecision;
}
else if (pi.event.deltaX > 0 && _this._horizontalBar.value > 0) {
_this._horizontalBar.value -= _this._wheelPrecision;
}
}
});
};
ScrollViewer.prototype._renderHighlightSpecific = function (context) {
if (!this.isHighlighted) {
return;
}
_super.prototype._renderHighlightSpecific.call(this, context);
this._grid._renderHighlightSpecific(context);
context.restore();
};
/** Releases associated resources */
ScrollViewer.prototype.dispose = function () {
var scene = this._host.getScene();
if (scene && this._onPointerObserver) {
scene.onPointerObservable.remove(this._onPointerObserver);
this._onPointerObserver = null;
}
_super.prototype.dispose.call(this);
};
return ScrollViewer;
}(_rectangle__WEBPACK_IMPORTED_MODULE_2__["Rectangle"]));
/***/ }),
/***/ "./2D/controls/scrollViewers/scrollViewerWindow.ts":
/*!*********************************************************!*\
!*** ./2D/controls/scrollViewers/scrollViewerWindow.ts ***!
\*********************************************************/
/*! exports provided: _ScrollViewerWindow */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "_ScrollViewerWindow", function() { return _ScrollViewerWindow; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../../node_modules/tslib/tslib.es6.js");
/* harmony import */ var _container__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../container */ "./2D/controls/container.ts");
/* harmony import */ var _valueAndUnit__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../../valueAndUnit */ "./2D/valueAndUnit.ts");
/* harmony import */ var _control__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../control */ "./2D/controls/control.ts");
/**
* Class used to hold a the container for ScrollViewer
* @hidden
*/
var _ScrollViewerWindow = /** @class */ (function (_super) {
tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](_ScrollViewerWindow, _super);
/**
* Creates a new ScrollViewerWindow
* @param name of ScrollViewerWindow
*/
function _ScrollViewerWindow(name) {
return _super.call(this, name) || this;
}
_ScrollViewerWindow.prototype._getTypeName = function () {
return "ScrollViewerWindow";
};
/** @hidden */
_ScrollViewerWindow.prototype._additionalProcessing = function (parentMeasure, context) {
_super.prototype._additionalProcessing.call(this, parentMeasure, context);
this._measureForChildren.left = this._currentMeasure.left;
this._measureForChildren.top = this._currentMeasure.top;
this._measureForChildren.width = parentMeasure.width;
this._measureForChildren.height = parentMeasure.height;
};
_ScrollViewerWindow.prototype._postMeasure = function () {
var maxWidth = this.parentClientWidth;
var maxHeight = this.parentClientHeight;
for (var _i = 0, _a = this.children; _i < _a.length; _i++) {
var child = _a[_i];
if (!child.isVisible || child.notRenderable) {
continue;
}
if (child.horizontalAlignment === _control__WEBPACK_IMPORTED_MODULE_3__["Control"].HORIZONTAL_ALIGNMENT_CENTER) {
child._offsetLeft(this._currentMeasure.left - child._currentMeasure.left);
}
if (child.verticalAlignment === _control__WEBPACK_IMPORTED_MODULE_3__["Control"].VERTICAL_ALIGNMENT_CENTER) {
child._offsetTop(this._currentMeasure.top - child._currentMeasure.top);
}
maxWidth = Math.max(maxWidth, child._currentMeasure.left - this._currentMeasure.left + child._currentMeasure.width);
maxHeight = Math.max(maxHeight, child._currentMeasure.top - this._currentMeasure.top + child._currentMeasure.height);
}
if (this._currentMeasure.width !== maxWidth) {
this._width.updateInPlace(maxWidth, _valueAndUnit__WEBPACK_IMPORTED_MODULE_2__["ValueAndUnit"].UNITMODE_PIXEL);
this._currentMeasure.width = maxWidth;
this._rebuildLayout = true;
this._isDirty = true;
}
if (this._currentMeasure.height !== maxHeight) {
this._height.updateInPlace(maxHeight, _valueAndUnit__WEBPACK_IMPORTED_MODULE_2__["ValueAndUnit"].UNITMODE_PIXEL);
this._currentMeasure.height = maxHeight;
this._rebuildLayout = true;
this._isDirty = true;
}
_super.prototype._postMeasure.call(this);
};
return _ScrollViewerWindow;
}(_container__WEBPACK_IMPORTED_MODULE_1__["Container"]));
/***/ }),
/***/ "./2D/controls/selector.ts":
/*!*********************************!*\
!*** ./2D/controls/selector.ts ***!
\*********************************/
/*! exports provided: SelectorGroup, CheckboxGroup, RadioGroup, SliderGroup, SelectionPanel */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "SelectorGroup", function() { return SelectorGroup; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "CheckboxGroup", function() { return CheckboxGroup; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "RadioGroup", function() { return RadioGroup; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "SliderGroup", function() { return SliderGroup; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "SelectionPanel", function() { return SelectionPanel; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../../node_modules/tslib/tslib.es6.js");
/* harmony import */ var _rectangle__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./rectangle */ "./2D/controls/rectangle.ts");
/* harmony import */ var _stackPanel__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./stackPanel */ "./2D/controls/stackPanel.ts");
/* harmony import */ var _control__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./control */ "./2D/controls/control.ts");
/* harmony import */ var _textBlock__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./textBlock */ "./2D/controls/textBlock.ts");
/* harmony import */ var _checkbox__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./checkbox */ "./2D/controls/checkbox.ts");
/* harmony import */ var _radioButton__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ./radioButton */ "./2D/controls/radioButton.ts");
/* harmony import */ var _sliders_slider__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ./sliders/slider */ "./2D/controls/sliders/slider.ts");
/* harmony import */ var _container__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ./container */ "./2D/controls/container.ts");
/** Class used to create a RadioGroup
* which contains groups of radio buttons
*/
var SelectorGroup = /** @class */ (function () {
/**
* Creates a new SelectorGroup
* @param name of group, used as a group heading
*/
function SelectorGroup(
/** name of SelectorGroup */
name) {
this.name = name;
this._groupPanel = new _stackPanel__WEBPACK_IMPORTED_MODULE_2__["StackPanel"]();
this._selectors = new Array();
this._groupPanel.verticalAlignment = _control__WEBPACK_IMPORTED_MODULE_3__["Control"].VERTICAL_ALIGNMENT_TOP;
this._groupPanel.horizontalAlignment = _control__WEBPACK_IMPORTED_MODULE_3__["Control"].HORIZONTAL_ALIGNMENT_LEFT;
this._groupHeader = this._addGroupHeader(name);
}
Object.defineProperty(SelectorGroup.prototype, "groupPanel", {
/** Gets the groupPanel of the SelectorGroup */
get: function () {
return this._groupPanel;
},
enumerable: true,
configurable: true
});
Object.defineProperty(SelectorGroup.prototype, "selectors", {
/** Gets the selectors array */
get: function () {
return this._selectors;
},
enumerable: true,
configurable: true
});
Object.defineProperty(SelectorGroup.prototype, "header", {
/** Gets and sets the group header */
get: function () {
return this._groupHeader.text;
},
set: function (label) {
if (this._groupHeader.text === "label") {
return;
}
this._groupHeader.text = label;
},
enumerable: true,
configurable: true
});
/** @hidden */
SelectorGroup.prototype._addGroupHeader = function (text) {
var groupHeading = new _textBlock__WEBPACK_IMPORTED_MODULE_4__["TextBlock"]("groupHead", text);
groupHeading.width = 0.9;
groupHeading.height = "30px";
groupHeading.textWrapping = true;
groupHeading.color = "black";
groupHeading.horizontalAlignment = _control__WEBPACK_IMPORTED_MODULE_3__["Control"].HORIZONTAL_ALIGNMENT_LEFT;
groupHeading.textHorizontalAlignment = _control__WEBPACK_IMPORTED_MODULE_3__["Control"].HORIZONTAL_ALIGNMENT_LEFT;
groupHeading.left = "2px";
this._groupPanel.addControl(groupHeading);
return groupHeading;
};
/** @hidden*/
SelectorGroup.prototype._getSelector = function (selectorNb) {
if (selectorNb < 0 || selectorNb >= this._selectors.length) {
return;
}
return this._selectors[selectorNb];
};
/** Removes the selector at the given position
* @param selectorNb the position of the selector within the group
*/
SelectorGroup.prototype.removeSelector = function (selectorNb) {
if (selectorNb < 0 || selectorNb >= this._selectors.length) {
return;
}
this._groupPanel.removeControl(this._selectors[selectorNb]);
this._selectors.splice(selectorNb, 1);
};
return SelectorGroup;
}());
/** Class used to create a CheckboxGroup
* which contains groups of checkbox buttons
*/
var CheckboxGroup = /** @class */ (function (_super) {
tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](CheckboxGroup, _super);
function CheckboxGroup() {
return _super !== null && _super.apply(this, arguments) || this;
}
/** Adds a checkbox as a control
* @param text is the label for the selector
* @param func is the function called when the Selector is checked
* @param checked is true when Selector is checked
*/
CheckboxGroup.prototype.addCheckbox = function (text, func, checked) {
if (func === void 0) { func = function (s) { }; }
if (checked === void 0) { checked = false; }
var checked = checked || false;
var button = new _checkbox__WEBPACK_IMPORTED_MODULE_5__["Checkbox"]();
button.width = "20px";
button.height = "20px";
button.color = "#364249";
button.background = "#CCCCCC";
button.horizontalAlignment = _control__WEBPACK_IMPORTED_MODULE_3__["Control"].HORIZONTAL_ALIGNMENT_LEFT;
button.onIsCheckedChangedObservable.add(function (state) {
func(state);
});
var _selector = _control__WEBPACK_IMPORTED_MODULE_3__["Control"].AddHeader(button, text, "200px", { isHorizontal: true, controlFirst: true });
_selector.height = "30px";
_selector.horizontalAlignment = _control__WEBPACK_IMPORTED_MODULE_3__["Control"].HORIZONTAL_ALIGNMENT_LEFT;
_selector.left = "4px";
this.groupPanel.addControl(_selector);
this.selectors.push(_selector);
button.isChecked = checked;
if (this.groupPanel.parent && this.groupPanel.parent.parent) {
button.color = this.groupPanel.parent.parent.buttonColor;
button.background = this.groupPanel.parent.parent.buttonBackground;
}
};
/** @hidden */
CheckboxGroup.prototype._setSelectorLabel = function (selectorNb, label) {
this.selectors[selectorNb].children[1].text = label;
};
/** @hidden */
CheckboxGroup.prototype._setSelectorLabelColor = function (selectorNb, color) {
this.selectors[selectorNb].children[1].color = color;
};
/** @hidden */
CheckboxGroup.prototype._setSelectorButtonColor = function (selectorNb, color) {
this.selectors[selectorNb].children[0].color = color;
};
/** @hidden */
CheckboxGroup.prototype._setSelectorButtonBackground = function (selectorNb, color) {
this.selectors[selectorNb].children[0].background = color;
};
return CheckboxGroup;
}(SelectorGroup));
/** Class used to create a RadioGroup
* which contains groups of radio buttons
*/
var RadioGroup = /** @class */ (function (_super) {
tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](RadioGroup, _super);
function RadioGroup() {
var _this = _super !== null && _super.apply(this, arguments) || this;
_this._selectNb = 0;
return _this;
}
/** Adds a radio button as a control
* @param label is the label for the selector
* @param func is the function called when the Selector is checked
* @param checked is true when Selector is checked
*/
RadioGroup.prototype.addRadio = function (label, func, checked) {
if (func === void 0) { func = function (n) { }; }
if (checked === void 0) { checked = false; }
var nb = this._selectNb++;
var button = new _radioButton__WEBPACK_IMPORTED_MODULE_6__["RadioButton"]();
button.name = label;
button.width = "20px";
button.height = "20px";
button.color = "#364249";
button.background = "#CCCCCC";
button.group = this.name;
button.horizontalAlignment = _control__WEBPACK_IMPORTED_MODULE_3__["Control"].HORIZONTAL_ALIGNMENT_LEFT;
button.onIsCheckedChangedObservable.add(function (state) {
if (state) {
func(nb);
}
});
var _selector = _control__WEBPACK_IMPORTED_MODULE_3__["Control"].AddHeader(button, label, "200px", { isHorizontal: true, controlFirst: true });
_selector.height = "30px";
_selector.horizontalAlignment = _control__WEBPACK_IMPORTED_MODULE_3__["Control"].HORIZONTAL_ALIGNMENT_LEFT;
_selector.left = "4px";
this.groupPanel.addControl(_selector);
this.selectors.push(_selector);
button.isChecked = checked;
if (this.groupPanel.parent && this.groupPanel.parent.parent) {
button.color = this.groupPanel.parent.parent.buttonColor;
button.background = this.groupPanel.parent.parent.buttonBackground;
}
};
/** @hidden */
RadioGroup.prototype._setSelectorLabel = function (selectorNb, label) {
this.selectors[selectorNb].children[1].text = label;
};
/** @hidden */
RadioGroup.prototype._setSelectorLabelColor = function (selectorNb, color) {
this.selectors[selectorNb].children[1].color = color;
};
/** @hidden */
RadioGroup.prototype._setSelectorButtonColor = function (selectorNb, color) {
this.selectors[selectorNb].children[0].color = color;
};
/** @hidden */
RadioGroup.prototype._setSelectorButtonBackground = function (selectorNb, color) {
this.selectors[selectorNb].children[0].background = color;
};
return RadioGroup;
}(SelectorGroup));
/** Class used to create a SliderGroup
* which contains groups of slider buttons
*/
var SliderGroup = /** @class */ (function (_super) {
tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](SliderGroup, _super);
function SliderGroup() {
return _super !== null && _super.apply(this, arguments) || this;
}
/**
* Adds a slider to the SelectorGroup
* @param label is the label for the SliderBar
* @param func is the function called when the Slider moves
* @param unit is a string describing the units used, eg degrees or metres
* @param min is the minimum value for the Slider
* @param max is the maximum value for the Slider
* @param value is the start value for the Slider between min and max
* @param onValueChange is the function used to format the value displayed, eg radians to degrees
*/
SliderGroup.prototype.addSlider = function (label, func, unit, min, max, value, onValueChange) {
if (func === void 0) { func = function (v) { }; }
if (unit === void 0) { unit = "Units"; }
if (min === void 0) { min = 0; }
if (max === void 0) { max = 0; }
if (value === void 0) { value = 0; }
if (onValueChange === void 0) { onValueChange = function (v) { return v | 0; }; }
var button = new _sliders_slider__WEBPACK_IMPORTED_MODULE_7__["Slider"]();
button.name = unit;
button.value = value;
button.minimum = min;
button.maximum = max;
button.width = 0.9;
button.height = "20px";
button.color = "#364249";
button.background = "#CCCCCC";
button.borderColor = "black";
button.horizontalAlignment = _control__WEBPACK_IMPORTED_MODULE_3__["Control"].HORIZONTAL_ALIGNMENT_LEFT;
button.left = "4px";
button.paddingBottom = "4px";
button.onValueChangedObservable.add(function (value) {
button.parent.children[0].text = button.parent.children[0].name + ": " + onValueChange(value) + " " + button.name;
func(value);
});
var _selector = _control__WEBPACK_IMPORTED_MODULE_3__["Control"].AddHeader(button, label + ": " + onValueChange(value) + " " + unit, "30px", { isHorizontal: false, controlFirst: false });
_selector.height = "60px";
_selector.horizontalAlignment = _control__WEBPACK_IMPORTED_MODULE_3__["Control"].HORIZONTAL_ALIGNMENT_LEFT;
_selector.left = "4px";
_selector.children[0].name = label;
this.groupPanel.addControl(_selector);
this.selectors.push(_selector);
if (this.groupPanel.parent && this.groupPanel.parent.parent) {
button.color = this.groupPanel.parent.parent.buttonColor;
button.background = this.groupPanel.parent.parent.buttonBackground;
}
};
/** @hidden */
SliderGroup.prototype._setSelectorLabel = function (selectorNb, label) {
this.selectors[selectorNb].children[0].name = label;
this.selectors[selectorNb].children[0].text = label + ": " + this.selectors[selectorNb].children[1].value + " " + this.selectors[selectorNb].children[1].name;
};
/** @hidden */
SliderGroup.prototype._setSelectorLabelColor = function (selectorNb, color) {
this.selectors[selectorNb].children[0].color = color;
};
/** @hidden */
SliderGroup.prototype._setSelectorButtonColor = function (selectorNb, color) {
this.selectors[selectorNb].children[1].color = color;
};
/** @hidden */
SliderGroup.prototype._setSelectorButtonBackground = function (selectorNb, color) {
this.selectors[selectorNb].children[1].background = color;
};
return SliderGroup;
}(SelectorGroup));
/** Class used to hold the controls for the checkboxes, radio buttons and sliders
* @see http://doc.babylonjs.com/how_to/selector
*/
var SelectionPanel = /** @class */ (function (_super) {
tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](SelectionPanel, _super);
/**
* Creates a new SelectionPanel
* @param name of SelectionPanel
* @param groups is an array of SelectionGroups
*/
function SelectionPanel(
/** name of SelectionPanel */
name,
/** an array of SelectionGroups */
groups) {
if (groups === void 0) { groups = []; }
var _this = _super.call(this, name) || this;
_this.name = name;
_this.groups = groups;
_this._buttonColor = "#364249";
_this._buttonBackground = "#CCCCCC";
_this._headerColor = "black";
_this._barColor = "white";
_this._barHeight = "2px";
_this._spacerHeight = "20px";
_this._bars = new Array();
_this._groups = groups;
_this.thickness = 2;
_this._panel = new _stackPanel__WEBPACK_IMPORTED_MODULE_2__["StackPanel"]();
_this._panel.verticalAlignment = _control__WEBPACK_IMPORTED_MODULE_3__["Control"].VERTICAL_ALIGNMENT_TOP;
_this._panel.horizontalAlignment = _control__WEBPACK_IMPORTED_MODULE_3__["Control"].HORIZONTAL_ALIGNMENT_LEFT;
_this._panel.top = 5;
_this._panel.left = 5;
_this._panel.width = 0.95;
if (groups.length > 0) {
for (var i = 0; i < groups.length - 1; i++) {
_this._panel.addControl(groups[i].groupPanel);
_this._addSpacer();
}
_this._panel.addControl(groups[groups.length - 1].groupPanel);
}
_this.addControl(_this._panel);
return _this;
}
SelectionPanel.prototype._getTypeName = function () {
return "SelectionPanel";
};
Object.defineProperty(SelectionPanel.prototype, "headerColor", {
/** Gets or sets the headerColor */
get: function () {
return this._headerColor;
},
set: function (color) {
if (this._headerColor === color) {
return;
}
this._headerColor = color;
this._setHeaderColor();
},
enumerable: true,
configurable: true
});
SelectionPanel.prototype._setHeaderColor = function () {
for (var i = 0; i < this._groups.length; i++) {
this._groups[i].groupPanel.children[0].color = this._headerColor;
}
};
Object.defineProperty(SelectionPanel.prototype, "buttonColor", {
/** Gets or sets the button color */
get: function () {
return this._buttonColor;
},
set: function (color) {
if (this._buttonColor === color) {
return;
}
this._buttonColor = color;
this._setbuttonColor();
},
enumerable: true,
configurable: true
});
SelectionPanel.prototype._setbuttonColor = function () {
for (var i = 0; i < this._groups.length; i++) {
for (var j = 0; j < this._groups[i].selectors.length; j++) {
this._groups[i]._setSelectorButtonColor(j, this._buttonColor);
}
}
};
Object.defineProperty(SelectionPanel.prototype, "labelColor", {
/** Gets or sets the label color */
get: function () {
return this._labelColor;
},
set: function (color) {
if (this._labelColor === color) {
return;
}
this._labelColor = color;
this._setLabelColor();
},
enumerable: true,
configurable: true
});
SelectionPanel.prototype._setLabelColor = function () {
for (var i = 0; i < this._groups.length; i++) {
for (var j = 0; j < this._groups[i].selectors.length; j++) {
this._groups[i]._setSelectorLabelColor(j, this._labelColor);
}
}
};
Object.defineProperty(SelectionPanel.prototype, "buttonBackground", {
/** Gets or sets the button background */
get: function () {
return this._buttonBackground;
},
set: function (color) {
if (this._buttonBackground === color) {
return;
}
this._buttonBackground = color;
this._setButtonBackground();
},
enumerable: true,
configurable: true
});
SelectionPanel.prototype._setButtonBackground = function () {
for (var i = 0; i < this._groups.length; i++) {
for (var j = 0; j < this._groups[i].selectors.length; j++) {
this._groups[i]._setSelectorButtonBackground(j, this._buttonBackground);
}
}
};
Object.defineProperty(SelectionPanel.prototype, "barColor", {
/** Gets or sets the color of separator bar */
get: function () {
return this._barColor;
},
set: function (color) {
if (this._barColor === color) {
return;
}
this._barColor = color;
this._setBarColor();
},
enumerable: true,
configurable: true
});
SelectionPanel.prototype._setBarColor = function () {
for (var i = 0; i < this._bars.length; i++) {
this._bars[i].children[0].background = this._barColor;
}
};
Object.defineProperty(SelectionPanel.prototype, "barHeight", {
/** Gets or sets the height of separator bar */
get: function () {
return this._barHeight;
},
set: function (value) {
if (this._barHeight === value) {
return;
}
this._barHeight = value;
this._setBarHeight();
},
enumerable: true,
configurable: true
});
SelectionPanel.prototype._setBarHeight = function () {
for (var i = 0; i < this._bars.length; i++) {
this._bars[i].children[0].height = this._barHeight;
}
};
Object.defineProperty(SelectionPanel.prototype, "spacerHeight", {
/** Gets or sets the height of spacers*/
get: function () {
return this._spacerHeight;
},
set: function (value) {
if (this._spacerHeight === value) {
return;
}
this._spacerHeight = value;
this._setSpacerHeight();
},
enumerable: true,
configurable: true
});
SelectionPanel.prototype._setSpacerHeight = function () {
for (var i = 0; i < this._bars.length; i++) {
this._bars[i].height = this._spacerHeight;
}
};
/** Adds a bar between groups */
SelectionPanel.prototype._addSpacer = function () {
var separator = new _container__WEBPACK_IMPORTED_MODULE_8__["Container"]();
separator.width = 1;
separator.height = this._spacerHeight;
separator.horizontalAlignment = _control__WEBPACK_IMPORTED_MODULE_3__["Control"].HORIZONTAL_ALIGNMENT_LEFT;
var bar = new _rectangle__WEBPACK_IMPORTED_MODULE_1__["Rectangle"]();
bar.width = 1;
bar.height = this._barHeight;
bar.horizontalAlignment = _control__WEBPACK_IMPORTED_MODULE_3__["Control"].HORIZONTAL_ALIGNMENT_LEFT;
bar.verticalAlignment = _control__WEBPACK_IMPORTED_MODULE_3__["Control"].VERTICAL_ALIGNMENT_CENTER;
bar.background = this._barColor;
bar.color = "transparent";
separator.addControl(bar);
this._panel.addControl(separator);
this._bars.push(separator);
};
/** Add a group to the selection panel
* @param group is the selector group to add
*/
SelectionPanel.prototype.addGroup = function (group) {
if (this._groups.length > 0) {
this._addSpacer();
}
this._panel.addControl(group.groupPanel);
this._groups.push(group);
group.groupPanel.children[0].color = this._headerColor;
for (var j = 0; j < group.selectors.length; j++) {
group._setSelectorButtonColor(j, this._buttonColor);
group._setSelectorButtonBackground(j, this._buttonBackground);
}
};
/** Remove the group from the given position
* @param groupNb is the position of the group in the list
*/
SelectionPanel.prototype.removeGroup = function (groupNb) {
if (groupNb < 0 || groupNb >= this._groups.length) {
return;
}
var group = this._groups[groupNb];
this._panel.removeControl(group.groupPanel);
this._groups.splice(groupNb, 1);
if (groupNb < this._bars.length) {
this._panel.removeControl(this._bars[groupNb]);
this._bars.splice(groupNb, 1);
}
};
/** Change a group header label
* @param label is the new group header label
* @param groupNb is the number of the group to relabel
* */
SelectionPanel.prototype.setHeaderName = function (label, groupNb) {
if (groupNb < 0 || groupNb >= this._groups.length) {
return;
}
var group = this._groups[groupNb];
group.groupPanel.children[0].text = label;
};
/** Change selector label to the one given
* @param label is the new selector label
* @param groupNb is the number of the groupcontaining the selector
* @param selectorNb is the number of the selector within a group to relabel
* */
SelectionPanel.prototype.relabel = function (label, groupNb, selectorNb) {
if (groupNb < 0 || groupNb >= this._groups.length) {
return;
}
var group = this._groups[groupNb];
if (selectorNb < 0 || selectorNb >= group.selectors.length) {
return;
}
group._setSelectorLabel(selectorNb, label);
};
/** For a given group position remove the selector at the given position
* @param groupNb is the number of the group to remove the selector from
* @param selectorNb is the number of the selector within the group
*/
SelectionPanel.prototype.removeFromGroupSelector = function (groupNb, selectorNb) {
if (groupNb < 0 || groupNb >= this._groups.length) {
return;
}
var group = this._groups[groupNb];
if (selectorNb < 0 || selectorNb >= group.selectors.length) {
return;
}
group.removeSelector(selectorNb);
};
/** For a given group position of correct type add a checkbox button
* @param groupNb is the number of the group to remove the selector from
* @param label is the label for the selector
* @param func is the function called when the Selector is checked
* @param checked is true when Selector is checked
*/
SelectionPanel.prototype.addToGroupCheckbox = function (groupNb, label, func, checked) {
if (func === void 0) { func = function () { }; }
if (checked === void 0) { checked = false; }
if (groupNb < 0 || groupNb >= this._groups.length) {
return;
}
var group = this._groups[groupNb];
group.addCheckbox(label, func, checked);
};
/** For a given group position of correct type add a radio button
* @param groupNb is the number of the group to remove the selector from
* @param label is the label for the selector
* @param func is the function called when the Selector is checked
* @param checked is true when Selector is checked
*/
SelectionPanel.prototype.addToGroupRadio = function (groupNb, label, func, checked) {
if (func === void 0) { func = function () { }; }
if (checked === void 0) { checked = false; }
if (groupNb < 0 || groupNb >= this._groups.length) {
return;
}
var group = this._groups[groupNb];
group.addRadio(label, func, checked);
};
/**
* For a given slider group add a slider
* @param groupNb is the number of the group to add the slider to
* @param label is the label for the Slider
* @param func is the function called when the Slider moves
* @param unit is a string describing the units used, eg degrees or metres
* @param min is the minimum value for the Slider
* @param max is the maximum value for the Slider
* @param value is the start value for the Slider between min and max
* @param onVal is the function used to format the value displayed, eg radians to degrees
*/
SelectionPanel.prototype.addToGroupSlider = function (groupNb, label, func, unit, min, max, value, onVal) {
if (func === void 0) { func = function () { }; }
if (unit === void 0) { unit = "Units"; }
if (min === void 0) { min = 0; }
if (max === void 0) { max = 0; }
if (value === void 0) { value = 0; }
if (onVal === void 0) { onVal = function (v) { return v | 0; }; }
if (groupNb < 0 || groupNb >= this._groups.length) {
return;
}
var group = this._groups[groupNb];
group.addSlider(label, func, unit, min, max, value, onVal);
};
return SelectionPanel;
}(_rectangle__WEBPACK_IMPORTED_MODULE_1__["Rectangle"]));
/***/ }),
/***/ "./2D/controls/sliders/baseSlider.ts":
/*!*******************************************!*\
!*** ./2D/controls/sliders/baseSlider.ts ***!
\*******************************************/
/*! exports provided: BaseSlider */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "BaseSlider", function() { return BaseSlider; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../../node_modules/tslib/tslib.es6.js");
/* harmony import */ var babylonjs_Misc_observable__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! babylonjs/Misc/observable */ "babylonjs/Misc/observable");
/* harmony import */ var babylonjs_Misc_observable__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(babylonjs_Misc_observable__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var _control__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../control */ "./2D/controls/control.ts");
/* harmony import */ var _valueAndUnit__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../../valueAndUnit */ "./2D/valueAndUnit.ts");
/**
* Class used to create slider controls
*/
var BaseSlider = /** @class */ (function (_super) {
tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](BaseSlider, _super);
/**
* Creates a new BaseSlider
* @param name defines the control name
*/
function BaseSlider(name) {
var _this = _super.call(this, name) || this;
_this.name = name;
_this._thumbWidth = new _valueAndUnit__WEBPACK_IMPORTED_MODULE_3__["ValueAndUnit"](20, _valueAndUnit__WEBPACK_IMPORTED_MODULE_3__["ValueAndUnit"].UNITMODE_PIXEL, false);
_this._minimum = 0;
_this._maximum = 100;
_this._value = 50;
_this._isVertical = false;
_this._barOffset = new _valueAndUnit__WEBPACK_IMPORTED_MODULE_3__["ValueAndUnit"](5, _valueAndUnit__WEBPACK_IMPORTED_MODULE_3__["ValueAndUnit"].UNITMODE_PIXEL, false);
_this._isThumbClamped = false;
_this._displayThumb = true;
_this._step = 0;
_this._lastPointerDownID = -1;
// Shared rendering info
_this._effectiveBarOffset = 0;
/** Observable raised when the sldier value changes */
_this.onValueChangedObservable = new babylonjs_Misc_observable__WEBPACK_IMPORTED_MODULE_1__["Observable"]();
// Events
_this._pointerIsDown = false;
_this.isPointerBlocker = true;
return _this;
}
Object.defineProperty(BaseSlider.prototype, "displayThumb", {
/** Gets or sets a boolean indicating if the thumb must be rendered */
get: function () {
return this._displayThumb;
},
set: function (value) {
if (this._displayThumb === value) {
return;
}
this._displayThumb = value;
this._markAsDirty();
},
enumerable: true,
configurable: true
});
Object.defineProperty(BaseSlider.prototype, "step", {
/** Gets or sets a step to apply to values (0 by default) */
get: function () {
return this._step;
},
set: function (value) {
if (this._step === value) {
return;
}
this._step = value;
this._markAsDirty();
},
enumerable: true,
configurable: true
});
Object.defineProperty(BaseSlider.prototype, "barOffset", {
/** Gets or sets main bar offset (ie. the margin applied to the value bar) */
get: function () {
return this._barOffset.toString(this._host);
},
set: function (value) {
if (this._barOffset.toString(this._host) === value) {
return;
}
if (this._barOffset.fromString(value)) {
this._markAsDirty();
}
},
enumerable: true,
configurable: true
});
Object.defineProperty(BaseSlider.prototype, "barOffsetInPixels", {
/** Gets main bar offset in pixels*/
get: function () {
return this._barOffset.getValueInPixel(this._host, this._cachedParentMeasure.width);
},
enumerable: true,
configurable: true
});
Object.defineProperty(BaseSlider.prototype, "thumbWidth", {
/** Gets or sets thumb width */
get: function () {
return this._thumbWidth.toString(this._host);
},
set: function (value) {
if (this._thumbWidth.toString(this._host) === value) {
return;
}
if (this._thumbWidth.fromString(value)) {
this._markAsDirty();
}
},
enumerable: true,
configurable: true
});
Object.defineProperty(BaseSlider.prototype, "thumbWidthInPixels", {
/** Gets thumb width in pixels */
get: function () {
return this._thumbWidth.getValueInPixel(this._host, this._cachedParentMeasure.width);
},
enumerable: true,
configurable: true
});
Object.defineProperty(BaseSlider.prototype, "minimum", {
/** Gets or sets minimum value */
get: function () {
return this._minimum;
},
set: function (value) {
if (this._minimum === value) {
return;
}
this._minimum = value;
this._markAsDirty();
this.value = Math.max(Math.min(this.value, this._maximum), this._minimum);
},
enumerable: true,
configurable: true
});
Object.defineProperty(BaseSlider.prototype, "maximum", {
/** Gets or sets maximum value */
get: function () {
return this._maximum;
},
set: function (value) {
if (this._maximum === value) {
return;
}
this._maximum = value;
this._markAsDirty();
this.value = Math.max(Math.min(this.value, this._maximum), this._minimum);
},
enumerable: true,
configurable: true
});
Object.defineProperty(BaseSlider.prototype, "value", {
/** Gets or sets current value */
get: function () {
return this._value;
},
set: function (value) {
value = Math.max(Math.min(value, this._maximum), this._minimum);
if (this._value === value) {
return;
}
this._value = value;
this._markAsDirty();
this.onValueChangedObservable.notifyObservers(this._value);
},
enumerable: true,
configurable: true
});
Object.defineProperty(BaseSlider.prototype, "isVertical", {
/**Gets or sets a boolean indicating if the slider should be vertical or horizontal */
get: function () {
return this._isVertical;
},
set: function (value) {
if (this._isVertical === value) {
return;
}
this._isVertical = value;
this._markAsDirty();
},
enumerable: true,
configurable: true
});
Object.defineProperty(BaseSlider.prototype, "isThumbClamped", {
/** Gets or sets a value indicating if the thumb can go over main bar extends */
get: function () {
return this._isThumbClamped;
},
set: function (value) {
if (this._isThumbClamped === value) {
return;
}
this._isThumbClamped = value;
this._markAsDirty();
},
enumerable: true,
configurable: true
});
BaseSlider.prototype._getTypeName = function () {
return "BaseSlider";
};
BaseSlider.prototype._getThumbPosition = function () {
if (this.isVertical) {
return ((this.maximum - this.value) / (this.maximum - this.minimum)) * this._backgroundBoxLength;
}
return ((this.value - this.minimum) / (this.maximum - this.minimum)) * this._backgroundBoxLength;
};
BaseSlider.prototype._getThumbThickness = function (type) {
var thumbThickness = 0;
switch (type) {
case "circle":
if (this._thumbWidth.isPixel) {
thumbThickness = Math.max(this._thumbWidth.getValue(this._host), this._backgroundBoxThickness);
}
else {
thumbThickness = this._backgroundBoxThickness * this._thumbWidth.getValue(this._host);
}
break;
case "rectangle":
if (this._thumbWidth.isPixel) {
thumbThickness = Math.min(this._thumbWidth.getValue(this._host), this._backgroundBoxThickness);
}
else {
thumbThickness = this._backgroundBoxThickness * this._thumbWidth.getValue(this._host);
}
}
return thumbThickness;
};
BaseSlider.prototype._prepareRenderingData = function (type) {
// Main bar
this._effectiveBarOffset = 0;
this._renderLeft = this._currentMeasure.left;
this._renderTop = this._currentMeasure.top;
this._renderWidth = this._currentMeasure.width;
this._renderHeight = this._currentMeasure.height;
this._backgroundBoxLength = Math.max(this._currentMeasure.width, this._currentMeasure.height);
this._backgroundBoxThickness = Math.min(this._currentMeasure.width, this._currentMeasure.height);
this._effectiveThumbThickness = this._getThumbThickness(type);
if (this.displayThumb) {
this._backgroundBoxLength -= this._effectiveThumbThickness;
}
//throw error when height is less than width for vertical slider
if ((this.isVertical && this._currentMeasure.height < this._currentMeasure.width)) {
console.error("Height should be greater than width");
return;
}
if (this._barOffset.isPixel) {
this._effectiveBarOffset = Math.min(this._barOffset.getValue(this._host), this._backgroundBoxThickness);
}
else {
this._effectiveBarOffset = this._backgroundBoxThickness * this._barOffset.getValue(this._host);
}
this._backgroundBoxThickness -= (this._effectiveBarOffset * 2);
if (this.isVertical) {
this._renderLeft += this._effectiveBarOffset;
if (!this.isThumbClamped && this.displayThumb) {
this._renderTop += (this._effectiveThumbThickness / 2);
}
this._renderHeight = this._backgroundBoxLength;
this._renderWidth = this._backgroundBoxThickness;
}
else {
this._renderTop += this._effectiveBarOffset;
if (!this.isThumbClamped && this.displayThumb) {
this._renderLeft += (this._effectiveThumbThickness / 2);
}
this._renderHeight = this._backgroundBoxThickness;
this._renderWidth = this._backgroundBoxLength;
}
};
/** @hidden */
BaseSlider.prototype._updateValueFromPointer = function (x, y) {
if (this.rotation != 0) {
this._invertTransformMatrix.transformCoordinates(x, y, this._transformedPosition);
x = this._transformedPosition.x;
y = this._transformedPosition.y;
}
var value;
if (this._isVertical) {
value = this._minimum + (1 - ((y - this._currentMeasure.top) / this._currentMeasure.height)) * (this._maximum - this._minimum);
}
else {
value = this._minimum + ((x - this._currentMeasure.left) / this._currentMeasure.width) * (this._maximum - this._minimum);
}
var mult = (1 / this._step) | 0;
this.value = this._step ? ((value * mult) | 0) / mult : value;
};
BaseSlider.prototype._onPointerDown = function (target, coordinates, pointerId, buttonIndex) {
if (!_super.prototype._onPointerDown.call(this, target, coordinates, pointerId, buttonIndex)) {
return false;
}
this._pointerIsDown = true;
this._updateValueFromPointer(coordinates.x, coordinates.y);
this._host._capturingControl[pointerId] = this;
this._lastPointerDownID = pointerId;
return true;
};
BaseSlider.prototype._onPointerMove = function (target, coordinates, pointerId) {
// Only listen to pointer move events coming from the last pointer to click on the element (To support dual vr controller interaction)
if (pointerId != this._lastPointerDownID) {
return;
}
if (this._pointerIsDown) {
this._updateValueFromPointer(coordinates.x, coordinates.y);
}
_super.prototype._onPointerMove.call(this, target, coordinates, pointerId);
};
BaseSlider.prototype._onPointerUp = function (target, coordinates, pointerId, buttonIndex, notifyClick) {
this._pointerIsDown = false;
delete this._host._capturingControl[pointerId];
_super.prototype._onPointerUp.call(this, target, coordinates, pointerId, buttonIndex, notifyClick);
};
return BaseSlider;
}(_control__WEBPACK_IMPORTED_MODULE_2__["Control"]));
/***/ }),
/***/ "./2D/controls/sliders/imageBasedSlider.ts":
/*!*************************************************!*\
!*** ./2D/controls/sliders/imageBasedSlider.ts ***!
\*************************************************/
/*! exports provided: ImageBasedSlider */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ImageBasedSlider", function() { return ImageBasedSlider; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../../node_modules/tslib/tslib.es6.js");
/* harmony import */ var _baseSlider__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./baseSlider */ "./2D/controls/sliders/baseSlider.ts");
/* harmony import */ var _measure__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../../measure */ "./2D/measure.ts");
/**
* Class used to create slider controls based on images
*/
var ImageBasedSlider = /** @class */ (function (_super) {
tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](ImageBasedSlider, _super);
/**
* Creates a new ImageBasedSlider
* @param name defines the control name
*/
function ImageBasedSlider(name) {
var _this = _super.call(this, name) || this;
_this.name = name;
_this._tempMeasure = new _measure__WEBPACK_IMPORTED_MODULE_2__["Measure"](0, 0, 0, 0);
return _this;
}
Object.defineProperty(ImageBasedSlider.prototype, "displayThumb", {
get: function () {
return this._displayThumb && this.thumbImage != null;
},
set: function (value) {
if (this._displayThumb === value) {
return;
}
this._displayThumb = value;
this._markAsDirty();
},
enumerable: true,
configurable: true
});
Object.defineProperty(ImageBasedSlider.prototype, "backgroundImage", {
/**
* Gets or sets the image used to render the background
*/
get: function () {
return this._backgroundImage;
},
set: function (value) {
var _this = this;
if (this._backgroundImage === value) {
return;
}
this._backgroundImage = value;
if (value && !value.isLoaded) {
value.onImageLoadedObservable.addOnce(function () { return _this._markAsDirty(); });
}
this._markAsDirty();
},
enumerable: true,
configurable: true
});
Object.defineProperty(ImageBasedSlider.prototype, "valueBarImage", {
/**
* Gets or sets the image used to render the value bar
*/
get: function () {
return this._valueBarImage;
},
set: function (value) {
var _this = this;
if (this._valueBarImage === value) {
return;
}
this._valueBarImage = value;
if (value && !value.isLoaded) {
value.onImageLoadedObservable.addOnce(function () { return _this._markAsDirty(); });
}
this._markAsDirty();
},
enumerable: true,
configurable: true
});
Object.defineProperty(ImageBasedSlider.prototype, "thumbImage", {
/**
* Gets or sets the image used to render the thumb
*/
get: function () {
return this._thumbImage;
},
set: function (value) {
var _this = this;
if (this._thumbImage === value) {
return;
}
this._thumbImage = value;
if (value && !value.isLoaded) {
value.onImageLoadedObservable.addOnce(function () { return _this._markAsDirty(); });
}
this._markAsDirty();
},
enumerable: true,
configurable: true
});
ImageBasedSlider.prototype._getTypeName = function () {
return "ImageBasedSlider";
};
ImageBasedSlider.prototype._draw = function (context) {
context.save();
this._applyStates(context);
this._prepareRenderingData("rectangle");
var thumbPosition = this._getThumbPosition();
var left = this._renderLeft;
var top = this._renderTop;
var width = this._renderWidth;
var height = this._renderHeight;
// Background
if (this._backgroundImage) {
this._tempMeasure.copyFromFloats(left, top, width, height);
if (this.isThumbClamped && this.displayThumb) {
if (this.isVertical) {
this._tempMeasure.height += this._effectiveThumbThickness;
}
else {
this._tempMeasure.width += this._effectiveThumbThickness;
}
}
this._backgroundImage._currentMeasure.copyFrom(this._tempMeasure);
this._backgroundImage._draw(context);
}
// Bar
if (this._valueBarImage) {
if (this.isVertical) {
if (this.isThumbClamped && this.displayThumb) {
this._tempMeasure.copyFromFloats(left, top + thumbPosition, width, height - thumbPosition + this._effectiveThumbThickness);
}
else {
this._tempMeasure.copyFromFloats(left, top + thumbPosition, width, height - thumbPosition);
}
}
else {
if (this.isThumbClamped && this.displayThumb) {
this._tempMeasure.copyFromFloats(left, top, thumbPosition + this._effectiveThumbThickness / 2, height);
}
else {
this._tempMeasure.copyFromFloats(left, top, thumbPosition, height);
}
}
this._valueBarImage._currentMeasure.copyFrom(this._tempMeasure);
this._valueBarImage._draw(context);
}
// Thumb
if (this.displayThumb) {
if (this.isVertical) {
this._tempMeasure.copyFromFloats(left - this._effectiveBarOffset, this._currentMeasure.top + thumbPosition, this._currentMeasure.width, this._effectiveThumbThickness);
}
else {
this._tempMeasure.copyFromFloats(this._currentMeasure.left + thumbPosition, this._currentMeasure.top, this._effectiveThumbThickness, this._currentMeasure.height);
}
this._thumbImage._currentMeasure.copyFrom(this._tempMeasure);
this._thumbImage._draw(context);
}
context.restore();
};
return ImageBasedSlider;
}(_baseSlider__WEBPACK_IMPORTED_MODULE_1__["BaseSlider"]));
/***/ }),
/***/ "./2D/controls/sliders/scrollBar.ts":
/*!******************************************!*\
!*** ./2D/controls/sliders/scrollBar.ts ***!
\******************************************/
/*! exports provided: ScrollBar */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ScrollBar", function() { return ScrollBar; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../../node_modules/tslib/tslib.es6.js");
/* harmony import */ var _baseSlider__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./baseSlider */ "./2D/controls/sliders/baseSlider.ts");
/* harmony import */ var _measure__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../../measure */ "./2D/measure.ts");
/**
* Class used to create slider controls
*/
var ScrollBar = /** @class */ (function (_super) {
tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](ScrollBar, _super);
/**
* Creates a new Slider
* @param name defines the control name
*/
function ScrollBar(name) {
var _this = _super.call(this, name) || this;
_this.name = name;
_this._background = "black";
_this._borderColor = "white";
_this._thumbMeasure = new _measure__WEBPACK_IMPORTED_MODULE_2__["Measure"](0, 0, 0, 0);
return _this;
}
Object.defineProperty(ScrollBar.prototype, "borderColor", {
/** Gets or sets border color */
get: function () {
return this._borderColor;
},
set: function (value) {
if (this._borderColor === value) {
return;
}
this._borderColor = value;
this._markAsDirty();
},
enumerable: true,
configurable: true
});
Object.defineProperty(ScrollBar.prototype, "background", {
/** Gets or sets background color */
get: function () {
return this._background;
},
set: function (value) {
if (this._background === value) {
return;
}
this._background = value;
this._markAsDirty();
},
enumerable: true,
configurable: true
});
ScrollBar.prototype._getTypeName = function () {
return "Scrollbar";
};
ScrollBar.prototype._getThumbThickness = function () {
var thumbThickness = 0;
if (this._thumbWidth.isPixel) {
thumbThickness = this._thumbWidth.getValue(this._host);
}
else {
thumbThickness = this._backgroundBoxThickness * this._thumbWidth.getValue(this._host);
}
return thumbThickness;
};
ScrollBar.prototype._draw = function (context) {
context.save();
this._applyStates(context);
this._prepareRenderingData("rectangle");
var left = this._renderLeft;
var thumbPosition = this._getThumbPosition();
context.fillStyle = this._background;
context.fillRect(this._currentMeasure.left, this._currentMeasure.top, this._currentMeasure.width, this._currentMeasure.height);
// Value bar
context.fillStyle = this.color;
// Thumb
if (this.isVertical) {
this._thumbMeasure.left = left - this._effectiveBarOffset;
this._thumbMeasure.top = this._currentMeasure.top + thumbPosition;
this._thumbMeasure.width = this._currentMeasure.width;
this._thumbMeasure.height = this._effectiveThumbThickness;
}
else {
this._thumbMeasure.left = this._currentMeasure.left + thumbPosition;
this._thumbMeasure.top = this._currentMeasure.top;
this._thumbMeasure.width = this._effectiveThumbThickness;
this._thumbMeasure.height = this._currentMeasure.height;
}
context.fillRect(this._thumbMeasure.left, this._thumbMeasure.top, this._thumbMeasure.width, this._thumbMeasure.height);
context.restore();
};
/** @hidden */
ScrollBar.prototype._updateValueFromPointer = function (x, y) {
if (this.rotation != 0) {
this._invertTransformMatrix.transformCoordinates(x, y, this._transformedPosition);
x = this._transformedPosition.x;
y = this._transformedPosition.y;
}
if (this._first) {
this._first = false;
this._originX = x;
this._originY = y;
// Check if move is required
if (x < this._thumbMeasure.left || x > this._thumbMeasure.left + this._thumbMeasure.width || y < this._thumbMeasure.top || y > this._thumbMeasure.top + this._thumbMeasure.height) {
if (this.isVertical) {
this.value = this.minimum + (1 - ((y - this._currentMeasure.top) / this._currentMeasure.height)) * (this.maximum - this.minimum);
}
else {
this.value = this.minimum + ((x - this._currentMeasure.left) / this._currentMeasure.width) * (this.maximum - this.minimum);
}
}
}
// Delta mode
var delta = 0;
if (this.isVertical) {
delta = -((y - this._originY) / (this._currentMeasure.height - this._effectiveThumbThickness));
}
else {
delta = (x - this._originX) / (this._currentMeasure.width - this._effectiveThumbThickness);
}
this.value += delta * (this.maximum - this.minimum);
this._originX = x;
this._originY = y;
};
ScrollBar.prototype._onPointerDown = function (target, coordinates, pointerId, buttonIndex) {
this._first = true;
return _super.prototype._onPointerDown.call(this, target, coordinates, pointerId, buttonIndex);
};
return ScrollBar;
}(_baseSlider__WEBPACK_IMPORTED_MODULE_1__["BaseSlider"]));
/***/ }),
/***/ "./2D/controls/sliders/slider.ts":
/*!***************************************!*\
!*** ./2D/controls/sliders/slider.ts ***!
\***************************************/
/*! exports provided: Slider */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Slider", function() { return Slider; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../../node_modules/tslib/tslib.es6.js");
/* harmony import */ var _baseSlider__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./baseSlider */ "./2D/controls/sliders/baseSlider.ts");
/**
* Class used to create slider controls
*/
var Slider = /** @class */ (function (_super) {
tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](Slider, _super);
/**
* Creates a new Slider
* @param name defines the control name
*/
function Slider(name) {
var _this = _super.call(this, name) || this;
_this.name = name;
_this._background = "black";
_this._borderColor = "white";
_this._isThumbCircle = false;
_this._displayValueBar = true;
return _this;
}
Object.defineProperty(Slider.prototype, "displayValueBar", {
/** Gets or sets a boolean indicating if the value bar must be rendered */
get: function () {
return this._displayValueBar;
},
set: function (value) {
if (this._displayValueBar === value) {
return;
}
this._displayValueBar = value;
this._markAsDirty();
},
enumerable: true,
configurable: true
});
Object.defineProperty(Slider.prototype, "borderColor", {
/** Gets or sets border color */
get: function () {
return this._borderColor;
},
set: function (value) {
if (this._borderColor === value) {
return;
}
this._borderColor = value;
this._markAsDirty();
},
enumerable: true,
configurable: true
});
Object.defineProperty(Slider.prototype, "background", {
/** Gets or sets background color */
get: function () {
return this._background;
},
set: function (value) {
if (this._background === value) {
return;
}
this._background = value;
this._markAsDirty();
},
enumerable: true,
configurable: true
});
Object.defineProperty(Slider.prototype, "isThumbCircle", {
/** Gets or sets a boolean indicating if the thumb should be round or square */
get: function () {
return this._isThumbCircle;
},
set: function (value) {
if (this._isThumbCircle === value) {
return;
}
this._isThumbCircle = value;
this._markAsDirty();
},
enumerable: true,
configurable: true
});
Slider.prototype._getTypeName = function () {
return "Slider";
};
Slider.prototype._draw = function (context) {
context.save();
this._applyStates(context);
this._prepareRenderingData(this.isThumbCircle ? "circle" : "rectangle");
var left = this._renderLeft;
var top = this._renderTop;
var width = this._renderWidth;
var height = this._renderHeight;
var radius = 0;
if (this.isThumbClamped && this.isThumbCircle) {
if (this.isVertical) {
top += (this._effectiveThumbThickness / 2);
}
else {
left += (this._effectiveThumbThickness / 2);
}
radius = this._backgroundBoxThickness / 2;
}
else {
radius = (this._effectiveThumbThickness - this._effectiveBarOffset) / 2;
}
if (this.shadowBlur || this.shadowOffsetX || this.shadowOffsetY) {
context.shadowColor = this.shadowColor;
context.shadowBlur = this.shadowBlur;
context.shadowOffsetX = this.shadowOffsetX;
context.shadowOffsetY = this.shadowOffsetY;
}
var thumbPosition = this._getThumbPosition();
context.fillStyle = this._background;
if (this.isVertical) {
if (this.isThumbClamped) {
if (this.isThumbCircle) {
context.beginPath();
context.arc(left + this._backgroundBoxThickness / 2, top, radius, Math.PI, 2 * Math.PI);
context.fill();
context.fillRect(left, top, width, height);
}
else {
context.fillRect(left, top, width, height + this._effectiveThumbThickness);
}
}
else {
context.fillRect(left, top, width, height);
}
}
else {
if (this.isThumbClamped) {
if (this.isThumbCircle) {
context.beginPath();
context.arc(left + this._backgroundBoxLength, top + (this._backgroundBoxThickness / 2), radius, 0, 2 * Math.PI);
context.fill();
context.fillRect(left, top, width, height);
}
else {
context.fillRect(left, top, width + this._effectiveThumbThickness, height);
}
}
else {
context.fillRect(left, top, width, height);
}
}
if (this.shadowBlur || this.shadowOffsetX || this.shadowOffsetY) {
context.shadowBlur = 0;
context.shadowOffsetX = 0;
context.shadowOffsetY = 0;
}
// Value bar
context.fillStyle = this.color;
if (this._displayValueBar) {
if (this.isVertical) {
if (this.isThumbClamped) {
if (this.isThumbCircle) {
context.beginPath();
context.arc(left + this._backgroundBoxThickness / 2, top + this._backgroundBoxLength, radius, 0, 2 * Math.PI);
context.fill();
context.fillRect(left, top + thumbPosition, width, height - thumbPosition);
}
else {
context.fillRect(left, top + thumbPosition, width, height - thumbPosition + this._effectiveThumbThickness);
}
}
else {
context.fillRect(left, top + thumbPosition, width, height - thumbPosition);
}
}
else {
if (this.isThumbClamped) {
if (this.isThumbCircle) {
context.beginPath();
context.arc(left, top + this._backgroundBoxThickness / 2, radius, 0, 2 * Math.PI);
context.fill();
context.fillRect(left, top, thumbPosition, height);
}
else {
context.fillRect(left, top, thumbPosition, height);
}
}
else {
context.fillRect(left, top, thumbPosition, height);
}
}
}
// Thumb
if (this.displayThumb) {
if (this.shadowBlur || this.shadowOffsetX || this.shadowOffsetY) {
context.shadowColor = this.shadowColor;
context.shadowBlur = this.shadowBlur;
context.shadowOffsetX = this.shadowOffsetX;
context.shadowOffsetY = this.shadowOffsetY;
}
if (this._isThumbCircle) {
context.beginPath();
if (this.isVertical) {
context.arc(left + this._backgroundBoxThickness / 2, top + thumbPosition, radius, 0, 2 * Math.PI);
}
else {
context.arc(left + thumbPosition, top + (this._backgroundBoxThickness / 2), radius, 0, 2 * Math.PI);
}
context.fill();
if (this.shadowBlur || this.shadowOffsetX || this.shadowOffsetY) {
context.shadowBlur = 0;
context.shadowOffsetX = 0;
context.shadowOffsetY = 0;
}
context.strokeStyle = this._borderColor;
context.stroke();
}
else {
if (this.isVertical) {
context.fillRect(left - this._effectiveBarOffset, this._currentMeasure.top + thumbPosition, this._currentMeasure.width, this._effectiveThumbThickness);
}
else {
context.fillRect(this._currentMeasure.left + thumbPosition, this._currentMeasure.top, this._effectiveThumbThickness, this._currentMeasure.height);
}
if (this.shadowBlur || this.shadowOffsetX || this.shadowOffsetY) {
context.shadowBlur = 0;
context.shadowOffsetX = 0;
context.shadowOffsetY = 0;
}
context.strokeStyle = this._borderColor;
if (this.isVertical) {
context.strokeRect(left - this._effectiveBarOffset, this._currentMeasure.top + thumbPosition, this._currentMeasure.width, this._effectiveThumbThickness);
}
else {
context.strokeRect(this._currentMeasure.left + thumbPosition, this._currentMeasure.top, this._effectiveThumbThickness, this._currentMeasure.height);
}
}
}
context.restore();
};
return Slider;
}(_baseSlider__WEBPACK_IMPORTED_MODULE_1__["BaseSlider"]));
/***/ }),
/***/ "./2D/controls/stackPanel.ts":
/*!***********************************!*\
!*** ./2D/controls/stackPanel.ts ***!
\***********************************/
/*! exports provided: StackPanel */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "StackPanel", function() { return StackPanel; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../../node_modules/tslib/tslib.es6.js");
/* harmony import */ var babylonjs_Misc_tools__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! babylonjs/Misc/tools */ "babylonjs/Misc/observable");
/* harmony import */ var babylonjs_Misc_tools__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(babylonjs_Misc_tools__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var _container__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./container */ "./2D/controls/container.ts");
/* harmony import */ var _control__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./control */ "./2D/controls/control.ts");
/**
* Class used to create a 2D stack panel container
*/
var StackPanel = /** @class */ (function (_super) {
tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](StackPanel, _super);
/**
* Creates a new StackPanel
* @param name defines control name
*/
function StackPanel(name) {
var _this = _super.call(this, name) || this;
_this.name = name;
_this._isVertical = true;
_this._manualWidth = false;
_this._manualHeight = false;
_this._doNotTrackManualChanges = false;
return _this;
}
Object.defineProperty(StackPanel.prototype, "isVertical", {
/** Gets or sets a boolean indicating if the stack panel is vertical or horizontal*/
get: function () {
return this._isVertical;
},
set: function (value) {
if (this._isVertical === value) {
return;
}
this._isVertical = value;
this._markAsDirty();
},
enumerable: true,
configurable: true
});
Object.defineProperty(StackPanel.prototype, "width", {
get: function () {
return this._width.toString(this._host);
},
/**
* Gets or sets panel width.
* This value should not be set when in horizontal mode as it will be computed automatically
*/
set: function (value) {
if (!this._doNotTrackManualChanges) {
this._manualWidth = true;
}
if (this._width.toString(this._host) === value) {
return;
}
if (this._width.fromString(value)) {
this._markAsDirty();
}
},
enumerable: true,
configurable: true
});
Object.defineProperty(StackPanel.prototype, "height", {
get: function () {
return this._height.toString(this._host);
},
/**
* Gets or sets panel height.
* This value should not be set when in vertical mode as it will be computed automatically
*/
set: function (value) {
if (!this._doNotTrackManualChanges) {
this._manualHeight = true;
}
if (this._height.toString(this._host) === value) {
return;
}
if (this._height.fromString(value)) {
this._markAsDirty();
}
},
enumerable: true,
configurable: true
});
StackPanel.prototype._getTypeName = function () {
return "StackPanel";
};
/** @hidden */
StackPanel.prototype._preMeasure = function (parentMeasure, context) {
for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
var child = _a[_i];
if (this._isVertical) {
child.verticalAlignment = _control__WEBPACK_IMPORTED_MODULE_3__["Control"].VERTICAL_ALIGNMENT_TOP;
}
else {
child.horizontalAlignment = _control__WEBPACK_IMPORTED_MODULE_3__["Control"].HORIZONTAL_ALIGNMENT_LEFT;
}
}
_super.prototype._preMeasure.call(this, parentMeasure, context);
};
StackPanel.prototype._additionalProcessing = function (parentMeasure, context) {
_super.prototype._additionalProcessing.call(this, parentMeasure, context);
this._measureForChildren.copyFrom(parentMeasure);
this._measureForChildren.left = this._currentMeasure.left;
this._measureForChildren.top = this._currentMeasure.top;
if (!this.isVertical || this._manualWidth) {
this._measureForChildren.width = this._currentMeasure.width;
}
if (this.isVertical || this._manualHeight) {
this._measureForChildren.height = this._currentMeasure.height;
}
};
StackPanel.prototype._postMeasure = function () {
var stackWidth = 0;
var stackHeight = 0;
for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
var child = _a[_i];
if (!child.isVisible || child.notRenderable) {
continue;
}
if (this._isVertical) {
if (child.top !== stackHeight + "px") {
child.top = stackHeight + "px";
this._rebuildLayout = true;
child._top.ignoreAdaptiveScaling = true;
}
if (child._height.isPercentage) {
babylonjs_Misc_tools__WEBPACK_IMPORTED_MODULE_1__["Tools"].Warn("Control (Name:" + child.name + ", UniqueId:" + child.uniqueId + ") is using height in percentage mode inside a vertical StackPanel");
}
else {
stackHeight += child._currentMeasure.height + child.paddingTopInPixels + child.paddingBottomInPixels;
}
}
else {
if (child.left !== stackWidth + "px") {
child.left = stackWidth + "px";
this._rebuildLayout = true;
child._left.ignoreAdaptiveScaling = true;
}
if (child._width.isPercentage) {
babylonjs_Misc_tools__WEBPACK_IMPORTED_MODULE_1__["Tools"].Warn("Control (Name:" + child.name + ", UniqueId:" + child.uniqueId + ") is using width in percentage mode inside a horizontal StackPanel");
}
else {
stackWidth += child._currentMeasure.width + child.paddingLeftInPixels + child.paddingRightInPixels;
}
}
}
this._doNotTrackManualChanges = true;
// Let stack panel width or height default to stackHeight and stackWidth if dimensions are not specified.
// User can now define their own height and width for stack panel.
var panelWidthChanged = false;
var panelHeightChanged = false;
if (!this._manualHeight && this._isVertical) { // do not specify height if strictly defined by user
var previousHeight = this.height;
this.height = stackHeight + "px";
panelHeightChanged = previousHeight !== this.height || !this._height.ignoreAdaptiveScaling;
}
if (!this._manualWidth && !this._isVertical) { // do not specify width if strictly defined by user
var previousWidth = this.width;
this.width = stackWidth + "px";
panelWidthChanged = previousWidth !== this.width || !this._width.ignoreAdaptiveScaling;
}
if (panelHeightChanged) {
this._height.ignoreAdaptiveScaling = true;
}
if (panelWidthChanged) {
this._width.ignoreAdaptiveScaling = true;
}
this._doNotTrackManualChanges = false;
if (panelWidthChanged || panelHeightChanged) {
this._rebuildLayout = true;
}
_super.prototype._postMeasure.call(this);
};
return StackPanel;
}(_container__WEBPACK_IMPORTED_MODULE_2__["Container"]));
/***/ }),
/***/ "./2D/controls/statics.ts":
/*!********************************!*\
!*** ./2D/controls/statics.ts ***!
\********************************/
/*! exports provided: name */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "name", function() { return name; });
/* harmony import */ var _control__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./control */ "./2D/controls/control.ts");
/* harmony import */ var _stackPanel__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./stackPanel */ "./2D/controls/stackPanel.ts");
/* harmony import */ var _textBlock__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./textBlock */ "./2D/controls/textBlock.ts");
/**
* Forcing an export so that this code will execute
* @hidden
*/
var name = "Statics";
/**
* Creates a stack panel that can be used to render headers
* @param control defines the control to associate with the header
* @param text defines the text of the header
* @param size defines the size of the header
* @param options defines options used to configure the header
* @returns a new StackPanel
*/
_control__WEBPACK_IMPORTED_MODULE_0__["Control"].AddHeader = function (control, text, size, options) {
var panel = new _stackPanel__WEBPACK_IMPORTED_MODULE_1__["StackPanel"]("panel");
var isHorizontal = options ? options.isHorizontal : true;
var controlFirst = options ? options.controlFirst : true;
panel.isVertical = !isHorizontal;
var header = new _textBlock__WEBPACK_IMPORTED_MODULE_2__["TextBlock"]("header");
header.text = text;
header.textHorizontalAlignment = _control__WEBPACK_IMPORTED_MODULE_0__["Control"].HORIZONTAL_ALIGNMENT_LEFT;
if (isHorizontal) {
header.width = size;
}
else {
header.height = size;
}
if (controlFirst) {
panel.addControl(control);
panel.addControl(header);
header.paddingLeft = "5px";
}
else {
panel.addControl(header);
panel.addControl(control);
header.paddingRight = "5px";
}
header.shadowBlur = control.shadowBlur;
header.shadowColor = control.shadowColor;
header.shadowOffsetX = control.shadowOffsetX;
header.shadowOffsetY = control.shadowOffsetY;
return panel;
};
/***/ }),
/***/ "./2D/controls/textBlock.ts":
/*!**********************************!*\
!*** ./2D/controls/textBlock.ts ***!
\**********************************/
/*! exports provided: TextWrapping, TextBlock */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "TextWrapping", function() { return TextWrapping; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "TextBlock", function() { return TextBlock; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../../node_modules/tslib/tslib.es6.js");
/* harmony import */ var babylonjs_Misc_observable__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! babylonjs/Misc/observable */ "babylonjs/Misc/observable");
/* harmony import */ var babylonjs_Misc_observable__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(babylonjs_Misc_observable__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var _valueAndUnit__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../valueAndUnit */ "./2D/valueAndUnit.ts");
/* harmony import */ var _control__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./control */ "./2D/controls/control.ts");
/**
* Enum that determines the text-wrapping mode to use.
*/
var TextWrapping;
(function (TextWrapping) {
/**
* Clip the text when it's larger than Control.width; this is the default mode.
*/
TextWrapping[TextWrapping["Clip"] = 0] = "Clip";
/**
* Wrap the text word-wise, i.e. try to add line-breaks at word boundary to fit within Control.width.
*/
TextWrapping[TextWrapping["WordWrap"] = 1] = "WordWrap";
/**
* Ellipsize the text, i.e. shrink with trailing … when text is larger than Control.width.
*/
TextWrapping[TextWrapping["Ellipsis"] = 2] = "Ellipsis";
})(TextWrapping || (TextWrapping = {}));
/**
* Class used to create text block control
*/
var TextBlock = /** @class */ (function (_super) {
tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](TextBlock, _super);
/**
* Creates a new TextBlock object
* @param name defines the name of the control
* @param text defines the text to display (emptry string by default)
*/
function TextBlock(
/**
* Defines the name of the control
*/
name, text) {
if (text === void 0) { text = ""; }
var _this = _super.call(this, name) || this;
_this.name = name;
_this._text = "";
_this._textWrapping = TextWrapping.Clip;
_this._textHorizontalAlignment = _control__WEBPACK_IMPORTED_MODULE_3__["Control"].HORIZONTAL_ALIGNMENT_CENTER;
_this._textVerticalAlignment = _control__WEBPACK_IMPORTED_MODULE_3__["Control"].VERTICAL_ALIGNMENT_CENTER;
_this._resizeToFit = false;
_this._lineSpacing = new _valueAndUnit__WEBPACK_IMPORTED_MODULE_2__["ValueAndUnit"](0);
_this._outlineWidth = 0;
_this._outlineColor = "white";
/**
* An event triggered after the text is changed
*/
_this.onTextChangedObservable = new babylonjs_Misc_observable__WEBPACK_IMPORTED_MODULE_1__["Observable"]();
/**
* An event triggered after the text was broken up into lines
*/
_this.onLinesReadyObservable = new babylonjs_Misc_observable__WEBPACK_IMPORTED_MODULE_1__["Observable"]();
_this.text = text;
return _this;
}
Object.defineProperty(TextBlock.prototype, "lines", {
/**
* Return the line list (you may need to use the onLinesReadyObservable to make sure the list is ready)
*/
get: function () {
return this._lines;
},
enumerable: true,
configurable: true
});
Object.defineProperty(TextBlock.prototype, "resizeToFit", {
/**
* Gets or sets an boolean indicating that the TextBlock will be resized to fit container
*/
get: function () {
return this._resizeToFit;
},
/**
* Gets or sets an boolean indicating that the TextBlock will be resized to fit container
*/
set: function (value) {
if (this._resizeToFit === value) {
return;
}
this._resizeToFit = value;
if (this._resizeToFit) {
this._width.ignoreAdaptiveScaling = true;
this._height.ignoreAdaptiveScaling = true;
}
this._markAsDirty();
},
enumerable: true,
configurable: true
});
Object.defineProperty(TextBlock.prototype, "textWrapping", {
/**
* Gets or sets a boolean indicating if text must be wrapped
*/
get: function () {
return this._textWrapping;
},
/**
* Gets or sets a boolean indicating if text must be wrapped
*/
set: function (value) {
if (this._textWrapping === value) {
return;
}
this._textWrapping = +value;
this._markAsDirty();
},
enumerable: true,
configurable: true
});
Object.defineProperty(TextBlock.prototype, "text", {
/**
* Gets or sets text to display
*/
get: function () {
return this._text;
},
/**
* Gets or sets text to display
*/
set: function (value) {
if (this._text === value) {
return;
}
this._text = value;
this._markAsDirty();
this.onTextChangedObservable.notifyObservers(this);
},
enumerable: true,
configurable: true
});
Object.defineProperty(TextBlock.prototype, "textHorizontalAlignment", {
/**
* Gets or sets text horizontal alignment (BABYLON.GUI.Control.HORIZONTAL_ALIGNMENT_CENTER by default)
*/
get: function () {
return this._textHorizontalAlignment;
},
/**
* Gets or sets text horizontal alignment (BABYLON.GUI.Control.HORIZONTAL_ALIGNMENT_CENTER by default)
*/
set: function (value) {
if (this._textHorizontalAlignment === value) {
return;
}
this._textHorizontalAlignment = value;
this._markAsDirty();
},
enumerable: true,
configurable: true
});
Object.defineProperty(TextBlock.prototype, "textVerticalAlignment", {
/**
* Gets or sets text vertical alignment (BABYLON.GUI.Control.VERTICAL_ALIGNMENT_CENTER by default)
*/
get: function () {
return this._textVerticalAlignment;
},
/**
* Gets or sets text vertical alignment (BABYLON.GUI.Control.VERTICAL_ALIGNMENT_CENTER by default)
*/
set: function (value) {
if (this._textVerticalAlignment === value) {
return;
}
this._textVerticalAlignment = value;
this._markAsDirty();
},
enumerable: true,
configurable: true
});
Object.defineProperty(TextBlock.prototype, "lineSpacing", {
/**
* Gets or sets line spacing value
*/
get: function () {
return this._lineSpacing.toString(this._host);
},
/**
* Gets or sets line spacing value
*/
set: function (value) {
if (this._lineSpacing.fromString(value)) {
this._markAsDirty();
}
},
enumerable: true,
configurable: true
});
Object.defineProperty(TextBlock.prototype, "outlineWidth", {
/**
* Gets or sets outlineWidth of the text to display
*/
get: function () {
return this._outlineWidth;
},
/**
* Gets or sets outlineWidth of the text to display
*/
set: function (value) {
if (this._outlineWidth === value) {
return;
}
this._outlineWidth = value;
this._markAsDirty();
},
enumerable: true,
configurable: true
});
Object.defineProperty(TextBlock.prototype, "outlineColor", {
/**
* Gets or sets outlineColor of the text to display
*/
get: function () {
return this._outlineColor;
},
/**
* Gets or sets outlineColor of the text to display
*/
set: function (value) {
if (this._outlineColor === value) {
return;
}
this._outlineColor = value;
this._markAsDirty();
},
enumerable: true,
configurable: true
});
TextBlock.prototype._getTypeName = function () {
return "TextBlock";
};
TextBlock.prototype._processMeasures = function (parentMeasure, context) {
if (!this._fontOffset) {
this._fontOffset = _control__WEBPACK_IMPORTED_MODULE_3__["Control"]._GetFontOffset(context.font);
}
_super.prototype._processMeasures.call(this, parentMeasure, context);
// Prepare lines
this._lines = this._breakLines(this._currentMeasure.width, context);
this.onLinesReadyObservable.notifyObservers(this);
var maxLineWidth = 0;
for (var i = 0; i < this._lines.length; i++) {
var line = this._lines[i];
if (line.width > maxLineWidth) {
maxLineWidth = line.width;
}
}
if (this._resizeToFit) {
if (this._textWrapping === TextWrapping.Clip) {
var newWidth = this.paddingLeftInPixels + this.paddingRightInPixels + maxLineWidth;
if (newWidth !== this._width.internalValue) {
this._width.updateInPlace(newWidth, _valueAndUnit__WEBPACK_IMPORTED_MODULE_2__["ValueAndUnit"].UNITMODE_PIXEL);
this._rebuildLayout = true;
}
}
var newHeight = this.paddingTopInPixels + this.paddingBottomInPixels + this._fontOffset.height * this._lines.length;
if (newHeight !== this._height.internalValue) {
this._height.updateInPlace(newHeight, _valueAndUnit__WEBPACK_IMPORTED_MODULE_2__["ValueAndUnit"].UNITMODE_PIXEL);
this._rebuildLayout = true;
}
}
};
TextBlock.prototype._drawText = function (text, textWidth, y, context) {
var width = this._currentMeasure.width;
var x = 0;
switch (this._textHorizontalAlignment) {
case _control__WEBPACK_IMPORTED_MODULE_3__["Control"].HORIZONTAL_ALIGNMENT_LEFT:
x = 0;
break;
case _control__WEBPACK_IMPORTED_MODULE_3__["Control"].HORIZONTAL_ALIGNMENT_RIGHT:
x = width - textWidth;
break;
case _control__WEBPACK_IMPORTED_MODULE_3__["Control"].HORIZONTAL_ALIGNMENT_CENTER:
x = (width - textWidth) / 2;
break;
}
if (this.shadowBlur || this.shadowOffsetX || this.shadowOffsetY) {
context.shadowColor = this.shadowColor;
context.shadowBlur = this.shadowBlur;
context.shadowOffsetX = this.shadowOffsetX;
context.shadowOffsetY = this.shadowOffsetY;
}
if (this.outlineWidth) {
context.strokeText(text, this._currentMeasure.left + x, y);
}
context.fillText(text, this._currentMeasure.left + x, y);
};
/** @hidden */
TextBlock.prototype._draw = function (context) {
context.save();
this._applyStates(context);
// Render lines
this._renderLines(context);
context.restore();
};
TextBlock.prototype._applyStates = function (context) {
_super.prototype._applyStates.call(this, context);
if (this.outlineWidth) {
context.lineWidth = this.outlineWidth;
context.strokeStyle = this.outlineColor;
}
};
TextBlock.prototype._breakLines = function (refWidth, context) {
var lines = [];
var _lines = this.text.split("\n");
if (this._textWrapping === TextWrapping.Ellipsis) {
for (var _i = 0, _lines_1 = _lines; _i < _lines_1.length; _i++) {
var _line = _lines_1[_i];
lines.push(this._parseLineEllipsis(_line, refWidth, context));
}
}
else if (this._textWrapping === TextWrapping.WordWrap) {
for (var _a = 0, _lines_2 = _lines; _a < _lines_2.length; _a++) {
var _line = _lines_2[_a];
lines.push.apply(lines, this._parseLineWordWrap(_line, refWidth, context));
}
}
else {
for (var _b = 0, _lines_3 = _lines; _b < _lines_3.length; _b++) {
var _line = _lines_3[_b];
lines.push(this._parseLine(_line, context));
}
}
return lines;
};
TextBlock.prototype._parseLine = function (line, context) {
if (line === void 0) { line = ''; }
return { text: line, width: context.measureText(line).width };
};
TextBlock.prototype._parseLineEllipsis = function (line, width, context) {
if (line === void 0) { line = ''; }
var lineWidth = context.measureText(line).width;
if (lineWidth > width) {
line += '…';
}
while (line.length > 2 && lineWidth > width) {
line = line.slice(0, -2) + '…';
lineWidth = context.measureText(line).width;
}
return { text: line, width: lineWidth };
};
TextBlock.prototype._parseLineWordWrap = function (line, width, context) {
if (line === void 0) { line = ''; }
var lines = [];
var words = line.split(' ');
var lineWidth = 0;
for (var n = 0; n < words.length; n++) {
var testLine = n > 0 ? line + " " + words[n] : words[0];
var metrics = context.measureText(testLine);
var testWidth = metrics.width;
if (testWidth > width && n > 0) {
lines.push({ text: line, width: lineWidth });
line = words[n];
lineWidth = context.measureText(line).width;
}
else {
lineWidth = testWidth;
line = testLine;
}
}
lines.push({ text: line, width: lineWidth });
return lines;
};
TextBlock.prototype._renderLines = function (context) {
var height = this._currentMeasure.height;
var rootY = 0;
switch (this._textVerticalAlignment) {
case _control__WEBPACK_IMPORTED_MODULE_3__["Control"].VERTICAL_ALIGNMENT_TOP:
rootY = this._fontOffset.ascent;
break;
case _control__WEBPACK_IMPORTED_MODULE_3__["Control"].VERTICAL_ALIGNMENT_BOTTOM:
rootY = height - this._fontOffset.height * (this._lines.length - 1) - this._fontOffset.descent;
break;
case _control__WEBPACK_IMPORTED_MODULE_3__["Control"].VERTICAL_ALIGNMENT_CENTER:
rootY = this._fontOffset.ascent + (height - this._fontOffset.height * this._lines.length) / 2;
break;
}
rootY += this._currentMeasure.top;
for (var i = 0; i < this._lines.length; i++) {
var line = this._lines[i];
if (i !== 0 && this._lineSpacing.internalValue !== 0) {
if (this._lineSpacing.isPixel) {
rootY += this._lineSpacing.getValue(this._host);
}
else {
rootY = rootY + (this._lineSpacing.getValue(this._host) * this._height.getValueInPixel(this._host, this._cachedParentMeasure.height));
}
}
this._drawText(line.text, line.width, rootY, context);
rootY += this._fontOffset.height;
}
};
/**
* Given a width constraint applied on the text block, find the expected height
* @returns expected height
*/
TextBlock.prototype.computeExpectedHeight = function () {
if (this.text && this.widthInPixels) {
var context_1 = document.createElement('canvas').getContext('2d');
if (context_1) {
this._applyStates(context_1);
if (!this._fontOffset) {
this._fontOffset = _control__WEBPACK_IMPORTED_MODULE_3__["Control"]._GetFontOffset(context_1.font);
}
var lines = this._lines ? this._lines : this._breakLines(this.widthInPixels - this.paddingLeftInPixels - this.paddingRightInPixels, context_1);
return this.paddingTopInPixels + this.paddingBottomInPixels + this._fontOffset.height * lines.length;
}
}
return 0;
};
TextBlock.prototype.dispose = function () {
_super.prototype.dispose.call(this);
this.onTextChangedObservable.clear();
};
return TextBlock;
}(_control__WEBPACK_IMPORTED_MODULE_3__["Control"]));
/***/ }),
/***/ "./2D/controls/virtualKeyboard.ts":
/*!****************************************!*\
!*** ./2D/controls/virtualKeyboard.ts ***!
\****************************************/
/*! exports provided: KeyPropertySet, VirtualKeyboard */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "KeyPropertySet", function() { return KeyPropertySet; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "VirtualKeyboard", function() { return VirtualKeyboard; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../../node_modules/tslib/tslib.es6.js");
/* harmony import */ var babylonjs_Misc_observable__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! babylonjs/Misc/observable */ "babylonjs/Misc/observable");
/* harmony import */ var babylonjs_Misc_observable__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(babylonjs_Misc_observable__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var _stackPanel__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./stackPanel */ "./2D/controls/stackPanel.ts");
/* harmony import */ var _button__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./button */ "./2D/controls/button.ts");
/**
* Class used to store key control properties
*/
var KeyPropertySet = /** @class */ (function () {
function KeyPropertySet() {
}
return KeyPropertySet;
}());
/**
* Class used to create virtual keyboard
*/
var VirtualKeyboard = /** @class */ (function (_super) {
tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](VirtualKeyboard, _super);
function VirtualKeyboard() {
var _this = _super !== null && _super.apply(this, arguments) || this;
/** Observable raised when a key is pressed */
_this.onKeyPressObservable = new babylonjs_Misc_observable__WEBPACK_IMPORTED_MODULE_1__["Observable"]();
/** Gets or sets default key button width */
_this.defaultButtonWidth = "40px";
/** Gets or sets default key button height */
_this.defaultButtonHeight = "40px";
/** Gets or sets default key button left padding */
_this.defaultButtonPaddingLeft = "2px";
/** Gets or sets default key button right padding */
_this.defaultButtonPaddingRight = "2px";
/** Gets or sets default key button top padding */
_this.defaultButtonPaddingTop = "2px";
/** Gets or sets default key button bottom padding */
_this.defaultButtonPaddingBottom = "2px";
/** Gets or sets default key button foreground color */
_this.defaultButtonColor = "#DDD";
/** Gets or sets default key button background color */
_this.defaultButtonBackground = "#070707";
/** Gets or sets shift button foreground color */
_this.shiftButtonColor = "#7799FF";
/** Gets or sets shift button thickness*/
_this.selectedShiftThickness = 1;
/** Gets shift key state */
_this.shiftState = 0;
_this._currentlyConnectedInputText = null;
_this._connectedInputTexts = [];
_this._onKeyPressObserver = null;
return _this;
}
VirtualKeyboard.prototype._getTypeName = function () {
return "VirtualKeyboard";
};
VirtualKeyboard.prototype._createKey = function (key, propertySet) {
var _this = this;
var button = _button__WEBPACK_IMPORTED_MODULE_3__["Button"].CreateSimpleButton(key, key);
button.width = propertySet && propertySet.width ? propertySet.width : this.defaultButtonWidth;
button.height = propertySet && propertySet.height ? propertySet.height : this.defaultButtonHeight;
button.color = propertySet && propertySet.color ? propertySet.color : this.defaultButtonColor;
button.background = propertySet && propertySet.background ? propertySet.background : this.defaultButtonBackground;
button.paddingLeft = propertySet && propertySet.paddingLeft ? propertySet.paddingLeft : this.defaultButtonPaddingLeft;
button.paddingRight = propertySet && propertySet.paddingRight ? propertySet.paddingRight : this.defaultButtonPaddingRight;
button.paddingTop = propertySet && propertySet.paddingTop ? propertySet.paddingTop : this.defaultButtonPaddingTop;
button.paddingBottom = propertySet && propertySet.paddingBottom ? propertySet.paddingBottom : this.defaultButtonPaddingBottom;
button.thickness = 0;
button.isFocusInvisible = true;
button.shadowColor = this.shadowColor;
button.shadowBlur = this.shadowBlur;
button.shadowOffsetX = this.shadowOffsetX;
button.shadowOffsetY = this.shadowOffsetY;
button.onPointerUpObservable.add(function () {
_this.onKeyPressObservable.notifyObservers(key);
});
return button;
};
/**
* Adds a new row of keys
* @param keys defines the list of keys to add
* @param propertySets defines the associated property sets
*/
VirtualKeyboard.prototype.addKeysRow = function (keys, propertySets) {
var panel = new _stackPanel__WEBPACK_IMPORTED_MODULE_2__["StackPanel"]();
panel.isVertical = false;
panel.isFocusInvisible = true;
var maxKey = null;
for (var i = 0; i < keys.length; i++) {
var properties = null;
if (propertySets && propertySets.length === keys.length) {
properties = propertySets[i];
}
var key = this._createKey(keys[i], properties);
if (!maxKey || key.heightInPixels > maxKey.heightInPixels) {
maxKey = key;
}
panel.addControl(key);
}
panel.height = maxKey ? maxKey.height : this.defaultButtonHeight;
this.addControl(panel);
};
/**
* Set the shift key to a specific state
* @param shiftState defines the new shift state
*/
VirtualKeyboard.prototype.applyShiftState = function (shiftState) {
if (!this.children) {
return;
}
for (var i = 0; i < this.children.length; i++) {
var row = this.children[i];
if (!row || !row.children) {
continue;
}
var rowContainer = row;
for (var j = 0; j < rowContainer.children.length; j++) {
var button = rowContainer.children[j];
if (!button || !button.children[0]) {
continue;
}
var button_tblock = button.children[0];
if (button_tblock.text === "\u21E7") {
button.color = (shiftState ? this.shiftButtonColor : this.defaultButtonColor);
button.thickness = (shiftState > 1 ? this.selectedShiftThickness : 0);
}
button_tblock.text = (shiftState > 0 ? button_tblock.text.toUpperCase() : button_tblock.text.toLowerCase());
}
}
};
Object.defineProperty(VirtualKeyboard.prototype, "connectedInputText", {
/** Gets the input text control currently attached to the keyboard */
get: function () {
return this._currentlyConnectedInputText;
},
enumerable: true,
configurable: true
});
/**
* Connects the keyboard with an input text control
*
* @param input defines the target control
*/
VirtualKeyboard.prototype.connect = function (input) {
var _this = this;
var inputTextAlreadyConnected = this._connectedInputTexts.some(function (a) { return a.input === input; });
if (inputTextAlreadyConnected) {
return;
}
if (this._onKeyPressObserver === null) {
this._onKeyPressObserver = this.onKeyPressObservable.add(function (key) {
if (!_this._currentlyConnectedInputText) {
return;
}
_this._currentlyConnectedInputText._host.focusedControl = _this._currentlyConnectedInputText;
switch (key) {
case "\u21E7":
_this.shiftState++;
if (_this.shiftState > 2) {
_this.shiftState = 0;
}
_this.applyShiftState(_this.shiftState);
return;
case "\u2190":
_this._currentlyConnectedInputText.processKey(8);
return;
case "\u21B5":
_this._currentlyConnectedInputText.processKey(13);
return;
}
_this._currentlyConnectedInputText.processKey(-1, (_this.shiftState ? key.toUpperCase() : key));
if (_this.shiftState === 1) {
_this.shiftState = 0;
_this.applyShiftState(_this.shiftState);
}
});
}
this.isVisible = false;
this._currentlyConnectedInputText = input;
input._connectedVirtualKeyboard = this;
// Events hooking
var onFocusObserver = input.onFocusObservable.add(function () {
_this._currentlyConnectedInputText = input;
input._connectedVirtualKeyboard = _this;
_this.isVisible = true;
});
var onBlurObserver = input.onBlurObservable.add(function () {
input._connectedVirtualKeyboard = null;
_this._currentlyConnectedInputText = null;
_this.isVisible = false;
});
this._connectedInputTexts.push({
input: input,
onBlurObserver: onBlurObserver,
onFocusObserver: onFocusObserver
});
};
/**
* Disconnects the keyboard from connected InputText controls
*
* @param input optionally defines a target control, otherwise all are disconnected
*/
VirtualKeyboard.prototype.disconnect = function (input) {
var _this = this;
if (input) {
// .find not available on IE
var filtered = this._connectedInputTexts.filter(function (a) { return a.input === input; });
if (filtered.length === 1) {
this._removeConnectedInputObservables(filtered[0]);
this._connectedInputTexts = this._connectedInputTexts.filter(function (a) { return a.input !== input; });
if (this._currentlyConnectedInputText === input) {
this._currentlyConnectedInputText = null;
}
}
}
else {
this._connectedInputTexts.forEach(function (connectedInputText) {
_this._removeConnectedInputObservables(connectedInputText);
});
this._connectedInputTexts = [];
}
if (this._connectedInputTexts.length === 0) {
this._currentlyConnectedInputText = null;
this.onKeyPressObservable.remove(this._onKeyPressObserver);
this._onKeyPressObserver = null;
}
};
VirtualKeyboard.prototype._removeConnectedInputObservables = function (connectedInputText) {
connectedInputText.input._connectedVirtualKeyboard = null;
connectedInputText.input.onFocusObservable.remove(connectedInputText.onFocusObserver);
connectedInputText.input.onBlurObservable.remove(connectedInputText.onBlurObserver);
};
/**
* Release all resources
*/
VirtualKeyboard.prototype.dispose = function () {
_super.prototype.dispose.call(this);
this.disconnect();
};
// Statics
/**
* Creates a new keyboard using a default layout
*
* @param name defines control name
* @returns a new VirtualKeyboard
*/
VirtualKeyboard.CreateDefaultLayout = function (name) {
var returnValue = new VirtualKeyboard(name);
returnValue.addKeysRow(["1", "2", "3", "4", "5", "6", "7", "8", "9", "0", "\u2190"]);
returnValue.addKeysRow(["q", "w", "e", "r", "t", "y", "u", "i", "o", "p"]);
returnValue.addKeysRow(["a", "s", "d", "f", "g", "h", "j", "k", "l", ";", "'", "\u21B5"]);
returnValue.addKeysRow(["\u21E7", "z", "x", "c", "v", "b", "n", "m", ",", ".", "/"]);
returnValue.addKeysRow([" "], [{ width: "200px" }]);
return returnValue;
};
return VirtualKeyboard;
}(_stackPanel__WEBPACK_IMPORTED_MODULE_2__["StackPanel"]));
/***/ }),
/***/ "./2D/index.ts":
/*!*********************!*\
!*** ./2D/index.ts ***!
\*********************/
/*! exports provided: AdvancedDynamicTexture, AdvancedDynamicTextureInstrumentation, Vector2WithInfo, Matrix2D, Measure, MultiLinePoint, Style, ValueAndUnit, Button, Checkbox, ColorPicker, Container, Control, Ellipse, Grid, Image, InputText, InputPassword, Line, MultiLine, RadioButton, StackPanel, SelectorGroup, CheckboxGroup, RadioGroup, SliderGroup, SelectionPanel, ScrollViewer, TextWrapping, TextBlock, KeyPropertySet, VirtualKeyboard, Rectangle, DisplayGrid, BaseSlider, Slider, ImageBasedSlider, ScrollBar, name */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var _controls__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./controls */ "./2D/controls/index.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Button", function() { return _controls__WEBPACK_IMPORTED_MODULE_0__["Button"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Checkbox", function() { return _controls__WEBPACK_IMPORTED_MODULE_0__["Checkbox"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ColorPicker", function() { return _controls__WEBPACK_IMPORTED_MODULE_0__["ColorPicker"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Container", function() { return _controls__WEBPACK_IMPORTED_MODULE_0__["Container"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Control", function() { return _controls__WEBPACK_IMPORTED_MODULE_0__["Control"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Ellipse", function() { return _controls__WEBPACK_IMPORTED_MODULE_0__["Ellipse"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Grid", function() { return _controls__WEBPACK_IMPORTED_MODULE_0__["Grid"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Image", function() { return _controls__WEBPACK_IMPORTED_MODULE_0__["Image"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "InputText", function() { return _controls__WEBPACK_IMPORTED_MODULE_0__["InputText"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "InputPassword", function() { return _controls__WEBPACK_IMPORTED_MODULE_0__["InputPassword"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Line", function() { return _controls__WEBPACK_IMPORTED_MODULE_0__["Line"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "MultiLine", function() { return _controls__WEBPACK_IMPORTED_MODULE_0__["MultiLine"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "RadioButton", function() { return _controls__WEBPACK_IMPORTED_MODULE_0__["RadioButton"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "StackPanel", function() { return _controls__WEBPACK_IMPORTED_MODULE_0__["StackPanel"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "SelectorGroup", function() { return _controls__WEBPACK_IMPORTED_MODULE_0__["SelectorGroup"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "CheckboxGroup", function() { return _controls__WEBPACK_IMPORTED_MODULE_0__["CheckboxGroup"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "RadioGroup", function() { return _controls__WEBPACK_IMPORTED_MODULE_0__["RadioGroup"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "SliderGroup", function() { return _controls__WEBPACK_IMPORTED_MODULE_0__["SliderGroup"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "SelectionPanel", function() { return _controls__WEBPACK_IMPORTED_MODULE_0__["SelectionPanel"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ScrollViewer", function() { return _controls__WEBPACK_IMPORTED_MODULE_0__["ScrollViewer"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "TextWrapping", function() { return _controls__WEBPACK_IMPORTED_MODULE_0__["TextWrapping"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "TextBlock", function() { return _controls__WEBPACK_IMPORTED_MODULE_0__["TextBlock"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "KeyPropertySet", function() { return _controls__WEBPACK_IMPORTED_MODULE_0__["KeyPropertySet"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "VirtualKeyboard", function() { return _controls__WEBPACK_IMPORTED_MODULE_0__["VirtualKeyboard"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Rectangle", function() { return _controls__WEBPACK_IMPORTED_MODULE_0__["Rectangle"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "DisplayGrid", function() { return _controls__WEBPACK_IMPORTED_MODULE_0__["DisplayGrid"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "BaseSlider", function() { return _controls__WEBPACK_IMPORTED_MODULE_0__["BaseSlider"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Slider", function() { return _controls__WEBPACK_IMPORTED_MODULE_0__["Slider"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ImageBasedSlider", function() { return _controls__WEBPACK_IMPORTED_MODULE_0__["ImageBasedSlider"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ScrollBar", function() { return _controls__WEBPACK_IMPORTED_MODULE_0__["ScrollBar"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "name", function() { return _controls__WEBPACK_IMPORTED_MODULE_0__["name"]; });
/* harmony import */ var _advancedDynamicTexture__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./advancedDynamicTexture */ "./2D/advancedDynamicTexture.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "AdvancedDynamicTexture", function() { return _advancedDynamicTexture__WEBPACK_IMPORTED_MODULE_1__["AdvancedDynamicTexture"]; });
/* harmony import */ var _adtInstrumentation__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./adtInstrumentation */ "./2D/adtInstrumentation.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "AdvancedDynamicTextureInstrumentation", function() { return _adtInstrumentation__WEBPACK_IMPORTED_MODULE_2__["AdvancedDynamicTextureInstrumentation"]; });
/* harmony import */ var _math2D__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./math2D */ "./2D/math2D.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Vector2WithInfo", function() { return _math2D__WEBPACK_IMPORTED_MODULE_3__["Vector2WithInfo"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Matrix2D", function() { return _math2D__WEBPACK_IMPORTED_MODULE_3__["Matrix2D"]; });
/* harmony import */ var _measure__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./measure */ "./2D/measure.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Measure", function() { return _measure__WEBPACK_IMPORTED_MODULE_4__["Measure"]; });
/* harmony import */ var _multiLinePoint__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./multiLinePoint */ "./2D/multiLinePoint.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "MultiLinePoint", function() { return _multiLinePoint__WEBPACK_IMPORTED_MODULE_5__["MultiLinePoint"]; });
/* harmony import */ var _style__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ./style */ "./2D/style.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Style", function() { return _style__WEBPACK_IMPORTED_MODULE_6__["Style"]; });
/* harmony import */ var _valueAndUnit__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ./valueAndUnit */ "./2D/valueAndUnit.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ValueAndUnit", function() { return _valueAndUnit__WEBPACK_IMPORTED_MODULE_7__["ValueAndUnit"]; });
/***/ }),
/***/ "./2D/math2D.ts":
/*!**********************!*\
!*** ./2D/math2D.ts ***!
\**********************/
/*! exports provided: Vector2WithInfo, Matrix2D */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Vector2WithInfo", function() { return Vector2WithInfo; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Matrix2D", function() { return Matrix2D; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../../node_modules/tslib/tslib.es6.js");
/* harmony import */ var babylonjs_Maths_math__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! babylonjs/Maths/math */ "babylonjs/Misc/observable");
/* harmony import */ var babylonjs_Maths_math__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(babylonjs_Maths_math__WEBPACK_IMPORTED_MODULE_1__);
/**
* Class used to transport Vector2 information for pointer events
*/
var Vector2WithInfo = /** @class */ (function (_super) {
tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](Vector2WithInfo, _super);
/**
* Creates a new Vector2WithInfo
* @param source defines the vector2 data to transport
* @param buttonIndex defines the current mouse button index
*/
function Vector2WithInfo(source,
/** defines the current mouse button index */
buttonIndex) {
if (buttonIndex === void 0) { buttonIndex = 0; }
var _this = _super.call(this, source.x, source.y) || this;
_this.buttonIndex = buttonIndex;
return _this;
}
return Vector2WithInfo;
}(babylonjs_Maths_math__WEBPACK_IMPORTED_MODULE_1__["Vector2"]));
/** Class used to provide 2D matrix features */
var Matrix2D = /** @class */ (function () {
/**
* Creates a new matrix
* @param m00 defines value for (0, 0)
* @param m01 defines value for (0, 1)
* @param m10 defines value for (1, 0)
* @param m11 defines value for (1, 1)
* @param m20 defines value for (2, 0)
* @param m21 defines value for (2, 1)
*/
function Matrix2D(m00, m01, m10, m11, m20, m21) {
/** Gets the internal array of 6 floats used to store matrix data */
this.m = new Float32Array(6);
this.fromValues(m00, m01, m10, m11, m20, m21);
}
/**
* Fills the matrix from direct values
* @param m00 defines value for (0, 0)
* @param m01 defines value for (0, 1)
* @param m10 defines value for (1, 0)
* @param m11 defines value for (1, 1)
* @param m20 defines value for (2, 0)
* @param m21 defines value for (2, 1)
* @returns the current modified matrix
*/
Matrix2D.prototype.fromValues = function (m00, m01, m10, m11, m20, m21) {
this.m[0] = m00;
this.m[1] = m01;
this.m[2] = m10;
this.m[3] = m11;
this.m[4] = m20;
this.m[5] = m21;
return this;
};
/**
* Gets matrix determinant
* @returns the determinant
*/
Matrix2D.prototype.determinant = function () {
return this.m[0] * this.m[3] - this.m[1] * this.m[2];
};
/**
* Inverses the matrix and stores it in a target matrix
* @param result defines the target matrix
* @returns the current matrix
*/
Matrix2D.prototype.invertToRef = function (result) {
var l0 = this.m[0];
var l1 = this.m[1];
var l2 = this.m[2];
var l3 = this.m[3];
var l4 = this.m[4];
var l5 = this.m[5];
var det = this.determinant();
if (det < (babylonjs_Maths_math__WEBPACK_IMPORTED_MODULE_1__["Epsilon"] * babylonjs_Maths_math__WEBPACK_IMPORTED_MODULE_1__["Epsilon"])) {
result.m[0] = 0;
result.m[1] = 0;
result.m[2] = 0;
result.m[3] = 0;
result.m[4] = 0;
result.m[5] = 0;
return this;
}
var detDiv = 1 / det;
var det4 = l2 * l5 - l3 * l4;
var det5 = l1 * l4 - l0 * l5;
result.m[0] = l3 * detDiv;
result.m[1] = -l1 * detDiv;
result.m[2] = -l2 * detDiv;
result.m[3] = l0 * detDiv;
result.m[4] = det4 * detDiv;
result.m[5] = det5 * detDiv;
return this;
};
/**
* Multiplies the current matrix with another one
* @param other defines the second operand
* @param result defines the target matrix
* @returns the current matrix
*/
Matrix2D.prototype.multiplyToRef = function (other, result) {
var l0 = this.m[0];
var l1 = this.m[1];
var l2 = this.m[2];
var l3 = this.m[3];
var l4 = this.m[4];
var l5 = this.m[5];
var r0 = other.m[0];
var r1 = other.m[1];
var r2 = other.m[2];
var r3 = other.m[3];
var r4 = other.m[4];
var r5 = other.m[5];
result.m[0] = l0 * r0 + l1 * r2;
result.m[1] = l0 * r1 + l1 * r3;
result.m[2] = l2 * r0 + l3 * r2;
result.m[3] = l2 * r1 + l3 * r3;
result.m[4] = l4 * r0 + l5 * r2 + r4;
result.m[5] = l4 * r1 + l5 * r3 + r5;
return this;
};
/**
* Applies the current matrix to a set of 2 floats and stores the result in a vector2
* @param x defines the x coordinate to transform
* @param y defines the x coordinate to transform
* @param result defines the target vector2
* @returns the current matrix
*/
Matrix2D.prototype.transformCoordinates = function (x, y, result) {
result.x = x * this.m[0] + y * this.m[2] + this.m[4];
result.y = x * this.m[1] + y * this.m[3] + this.m[5];
return this;
};
// Statics
/**
* Creates an identity matrix
* @returns a new matrix
*/
Matrix2D.Identity = function () {
return new Matrix2D(1, 0, 0, 1, 0, 0);
};
/**
* Creates a translation matrix and stores it in a target matrix
* @param x defines the x coordinate of the translation
* @param y defines the y coordinate of the translation
* @param result defines the target matrix
*/
Matrix2D.TranslationToRef = function (x, y, result) {
result.fromValues(1, 0, 0, 1, x, y);
};
/**
* Creates a scaling matrix and stores it in a target matrix
* @param x defines the x coordinate of the scaling
* @param y defines the y coordinate of the scaling
* @param result defines the target matrix
*/
Matrix2D.ScalingToRef = function (x, y, result) {
result.fromValues(x, 0, 0, y, 0, 0);
};
/**
* Creates a rotation matrix and stores it in a target matrix
* @param angle defines the rotation angle
* @param result defines the target matrix
*/
Matrix2D.RotationToRef = function (angle, result) {
var s = Math.sin(angle);
var c = Math.cos(angle);
result.fromValues(c, s, -s, c, 0, 0);
};
/**
* Composes a matrix from translation, rotation, scaling and parent matrix and stores it in a target matrix
* @param tx defines the x coordinate of the translation
* @param ty defines the y coordinate of the translation
* @param angle defines the rotation angle
* @param scaleX defines the x coordinate of the scaling
* @param scaleY defines the y coordinate of the scaling
* @param parentMatrix defines the parent matrix to multiply by (can be null)
* @param result defines the target matrix
*/
Matrix2D.ComposeToRef = function (tx, ty, angle, scaleX, scaleY, parentMatrix, result) {
Matrix2D.TranslationToRef(tx, ty, Matrix2D._TempPreTranslationMatrix);
Matrix2D.ScalingToRef(scaleX, scaleY, Matrix2D._TempScalingMatrix);
Matrix2D.RotationToRef(angle, Matrix2D._TempRotationMatrix);
Matrix2D.TranslationToRef(-tx, -ty, Matrix2D._TempPostTranslationMatrix);
Matrix2D._TempPreTranslationMatrix.multiplyToRef(Matrix2D._TempScalingMatrix, Matrix2D._TempCompose0);
Matrix2D._TempCompose0.multiplyToRef(Matrix2D._TempRotationMatrix, Matrix2D._TempCompose1);
if (parentMatrix) {
Matrix2D._TempCompose1.multiplyToRef(Matrix2D._TempPostTranslationMatrix, Matrix2D._TempCompose2);
Matrix2D._TempCompose2.multiplyToRef(parentMatrix, result);
}
else {
Matrix2D._TempCompose1.multiplyToRef(Matrix2D._TempPostTranslationMatrix, result);
}
};
Matrix2D._TempPreTranslationMatrix = Matrix2D.Identity();
Matrix2D._TempPostTranslationMatrix = Matrix2D.Identity();
Matrix2D._TempRotationMatrix = Matrix2D.Identity();
Matrix2D._TempScalingMatrix = Matrix2D.Identity();
Matrix2D._TempCompose0 = Matrix2D.Identity();
Matrix2D._TempCompose1 = Matrix2D.Identity();
Matrix2D._TempCompose2 = Matrix2D.Identity();
return Matrix2D;
}());
/***/ }),
/***/ "./2D/measure.ts":
/*!***********************!*\
!*** ./2D/measure.ts ***!
\***********************/
/*! exports provided: Measure */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Measure", function() { return Measure; });
/* harmony import */ var babylonjs_Maths_math__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! babylonjs/Maths/math */ "babylonjs/Misc/observable");
/* harmony import */ var babylonjs_Maths_math__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(babylonjs_Maths_math__WEBPACK_IMPORTED_MODULE_0__);
/**
* Class used to store 2D control sizes
*/
var Measure = /** @class */ (function () {
/**
* Creates a new measure
* @param left defines left coordinate
* @param top defines top coordinate
* @param width defines width dimension
* @param height defines height dimension
*/
function Measure(
/** defines left coordinate */
left,
/** defines top coordinate */
top,
/** defines width dimension */
width,
/** defines height dimension */
height) {
this.left = left;
this.top = top;
this.width = width;
this.height = height;
}
/**
* Copy from another measure
* @param other defines the other measure to copy from
*/
Measure.prototype.copyFrom = function (other) {
this.left = other.left;
this.top = other.top;
this.width = other.width;
this.height = other.height;
};
/**
* Copy from a group of 4 floats
* @param left defines left coordinate
* @param top defines top coordinate
* @param width defines width dimension
* @param height defines height dimension
*/
Measure.prototype.copyFromFloats = function (left, top, width, height) {
this.left = left;
this.top = top;
this.width = width;
this.height = height;
};
/**
* Computes the axis aligned bounding box measure for two given measures
* @param a Input measure
* @param b Input measure
* @param result the resulting bounding measure
*/
Measure.CombineToRef = function (a, b, result) {
var left = Math.min(a.left, b.left);
var top = Math.min(a.top, b.top);
var right = Math.max(a.left + a.width, b.left + b.width);
var bottom = Math.max(a.top + a.height, b.top + b.height);
result.left = left;
result.top = top;
result.width = right - left;
result.height = bottom - top;
};
/**
* Computes the axis aligned bounding box of the measure after it is modified by a given transform
* @param transform the matrix to transform the measure before computing the AABB
* @param result the resulting AABB
*/
Measure.prototype.transformToRef = function (transform, result) {
var rectanglePoints = babylonjs_Maths_math__WEBPACK_IMPORTED_MODULE_0__["Polygon"].Rectangle(this.left, this.top, this.left + this.width, this.top + this.height);
var min = new babylonjs_Maths_math__WEBPACK_IMPORTED_MODULE_0__["Vector2"](Number.MAX_VALUE, Number.MAX_VALUE);
var max = new babylonjs_Maths_math__WEBPACK_IMPORTED_MODULE_0__["Vector2"](0, 0);
for (var i = 0; i < 4; i++) {
transform.transformCoordinates(rectanglePoints[i].x, rectanglePoints[i].y, rectanglePoints[i]);
min.x = Math.floor(Math.min(min.x, rectanglePoints[i].x));
min.y = Math.floor(Math.min(min.y, rectanglePoints[i].y));
max.x = Math.ceil(Math.max(max.x, rectanglePoints[i].x));
max.y = Math.ceil(Math.max(max.y, rectanglePoints[i].y));
}
result.left = min.x;
result.top = min.y;
result.width = max.x - min.x;
result.height = max.y - min.y;
};
/**
* Check equality between this measure and another one
* @param other defines the other measures
* @returns true if both measures are equals
*/
Measure.prototype.isEqualsTo = function (other) {
if (this.left !== other.left) {
return false;
}
if (this.top !== other.top) {
return false;
}
if (this.width !== other.width) {
return false;
}
if (this.height !== other.height) {
return false;
}
return true;
};
/**
* Creates an empty measure
* @returns a new measure
*/
Measure.Empty = function () {
return new Measure(0, 0, 0, 0);
};
return Measure;
}());
/***/ }),
/***/ "./2D/multiLinePoint.ts":
/*!******************************!*\
!*** ./2D/multiLinePoint.ts ***!
\******************************/
/*! exports provided: MultiLinePoint */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "MultiLinePoint", function() { return MultiLinePoint; });
/* harmony import */ var babylonjs_Maths_math__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! babylonjs/Maths/math */ "babylonjs/Misc/observable");
/* harmony import */ var babylonjs_Maths_math__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(babylonjs_Maths_math__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _valueAndUnit__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./valueAndUnit */ "./2D/valueAndUnit.ts");
/**
* Class used to store a point for a MultiLine object.
* The point can be pure 2D coordinates, a mesh or a control
*/
var MultiLinePoint = /** @class */ (function () {
/**
* Creates a new MultiLinePoint
* @param multiLine defines the source MultiLine object
*/
function MultiLinePoint(multiLine) {
this._multiLine = multiLine;
this._x = new _valueAndUnit__WEBPACK_IMPORTED_MODULE_1__["ValueAndUnit"](0);
this._y = new _valueAndUnit__WEBPACK_IMPORTED_MODULE_1__["ValueAndUnit"](0);
this._point = new babylonjs_Maths_math__WEBPACK_IMPORTED_MODULE_0__["Vector2"](0, 0);
}
Object.defineProperty(MultiLinePoint.prototype, "x", {
/** Gets or sets x coordinate */
get: function () {
return this._x.toString(this._multiLine._host);
},
set: function (value) {
if (this._x.toString(this._multiLine._host) === value) {
return;
}
if (this._x.fromString(value)) {
this._multiLine._markAsDirty();
}
},
enumerable: true,
configurable: true
});
Object.defineProperty(MultiLinePoint.prototype, "y", {
/** Gets or sets y coordinate */
get: function () {
return this._y.toString(this._multiLine._host);
},
set: function (value) {
if (this._y.toString(this._multiLine._host) === value) {
return;
}
if (this._y.fromString(value)) {
this._multiLine._markAsDirty();
}
},
enumerable: true,
configurable: true
});
Object.defineProperty(MultiLinePoint.prototype, "control", {
/** Gets or sets the control associated with this point */
get: function () {
return this._control;
},
set: function (value) {
if (this._control === value) {
return;
}
if (this._control && this._controlObserver) {
this._control.onDirtyObservable.remove(this._controlObserver);
this._controlObserver = null;
}
this._control = value;
if (this._control) {
this._controlObserver = this._control.onDirtyObservable.add(this._multiLine.onPointUpdate);
}
this._multiLine._markAsDirty();
},
enumerable: true,
configurable: true
});
Object.defineProperty(MultiLinePoint.prototype, "mesh", {
/** Gets or sets the mesh associated with this point */
get: function () {
return this._mesh;
},
set: function (value) {
if (this._mesh === value) {
return;
}
if (this._mesh && this._meshObserver) {
this._mesh.getScene().onAfterCameraRenderObservable.remove(this._meshObserver);
}
this._mesh = value;
if (this._mesh) {
this._meshObserver = this._mesh.getScene().onAfterCameraRenderObservable.add(this._multiLine.onPointUpdate);
}
this._multiLine._markAsDirty();
},
enumerable: true,
configurable: true
});
/** Resets links */
MultiLinePoint.prototype.resetLinks = function () {
this.control = null;
this.mesh = null;
};
/**
* Gets a translation vector
* @returns the translation vector
*/
MultiLinePoint.prototype.translate = function () {
this._point = this._translatePoint();
return this._point;
};
MultiLinePoint.prototype._translatePoint = function () {
if (this._mesh != null) {
return this._multiLine._host.getProjectedPosition(this._mesh.getBoundingInfo().boundingSphere.center, this._mesh.getWorldMatrix());
}
else if (this._control != null) {
return new babylonjs_Maths_math__WEBPACK_IMPORTED_MODULE_0__["Vector2"](this._control.centerX, this._control.centerY);
}
else {
var host = this._multiLine._host;
var xValue = this._x.getValueInPixel(host, Number(host._canvas.width));
var yValue = this._y.getValueInPixel(host, Number(host._canvas.height));
return new babylonjs_Maths_math__WEBPACK_IMPORTED_MODULE_0__["Vector2"](xValue, yValue);
}
};
/** Release associated resources */
MultiLinePoint.prototype.dispose = function () {
this.resetLinks();
};
return MultiLinePoint;
}());
/***/ }),
/***/ "./2D/style.ts":
/*!*********************!*\
!*** ./2D/style.ts ***!
\*********************/
/*! exports provided: Style */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Style", function() { return Style; });
/* harmony import */ var babylonjs_Misc_observable__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! babylonjs/Misc/observable */ "babylonjs/Misc/observable");
/* harmony import */ var babylonjs_Misc_observable__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(babylonjs_Misc_observable__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _valueAndUnit__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./valueAndUnit */ "./2D/valueAndUnit.ts");
/**
* Define a style used by control to automatically setup properties based on a template.
* Only support font related properties so far
*/
var Style = /** @class */ (function () {
/**
* Creates a new style object
* @param host defines the AdvancedDynamicTexture which hosts this style
*/
function Style(host) {
this._fontFamily = "Arial";
this._fontStyle = "";
this._fontWeight = "";
/** @hidden */
this._fontSize = new _valueAndUnit__WEBPACK_IMPORTED_MODULE_1__["ValueAndUnit"](18, _valueAndUnit__WEBPACK_IMPORTED_MODULE_1__["ValueAndUnit"].UNITMODE_PIXEL, false);
/**
* Observable raised when the style values are changed
*/
this.onChangedObservable = new babylonjs_Misc_observable__WEBPACK_IMPORTED_MODULE_0__["Observable"]();
this._host = host;
}
Object.defineProperty(Style.prototype, "fontSize", {
/**
* Gets or sets the font size
*/
get: function () {
return this._fontSize.toString(this._host);
},
set: function (value) {
if (this._fontSize.toString(this._host) === value) {
return;
}
if (this._fontSize.fromString(value)) {
this.onChangedObservable.notifyObservers(this);
}
},
enumerable: true,
configurable: true
});
Object.defineProperty(Style.prototype, "fontFamily", {
/**
* Gets or sets the font family
*/
get: function () {
return this._fontFamily;
},
set: function (value) {
if (this._fontFamily === value) {
return;
}
this._fontFamily = value;
this.onChangedObservable.notifyObservers(this);
},
enumerable: true,
configurable: true
});
Object.defineProperty(Style.prototype, "fontStyle", {
/**
* Gets or sets the font style
*/
get: function () {
return this._fontStyle;
},
set: function (value) {
if (this._fontStyle === value) {
return;
}
this._fontStyle = value;
this.onChangedObservable.notifyObservers(this);
},
enumerable: true,
configurable: true
});
Object.defineProperty(Style.prototype, "fontWeight", {
/** Gets or sets font weight */
get: function () {
return this._fontWeight;
},
set: function (value) {
if (this._fontWeight === value) {
return;
}
this._fontWeight = value;
this.onChangedObservable.notifyObservers(this);
},
enumerable: true,
configurable: true
});
/** Dispose all associated resources */
Style.prototype.dispose = function () {
this.onChangedObservable.clear();
};
return Style;
}());
/***/ }),
/***/ "./2D/valueAndUnit.ts":
/*!****************************!*\
!*** ./2D/valueAndUnit.ts ***!
\****************************/
/*! exports provided: ValueAndUnit */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ValueAndUnit", function() { return ValueAndUnit; });
/**
* Class used to specific a value and its associated unit
*/
var ValueAndUnit = /** @class */ (function () {
/**
* Creates a new ValueAndUnit
* @param value defines the value to store
* @param unit defines the unit to store
* @param negativeValueAllowed defines a boolean indicating if the value can be negative
*/
function ValueAndUnit(value,
/** defines the unit to store */
unit,
/** defines a boolean indicating if the value can be negative */
negativeValueAllowed) {
if (unit === void 0) { unit = ValueAndUnit.UNITMODE_PIXEL; }
if (negativeValueAllowed === void 0) { negativeValueAllowed = true; }
this.unit = unit;
this.negativeValueAllowed = negativeValueAllowed;
this._value = 1;
/**
* Gets or sets a value indicating that this value will not scale accordingly with adaptive scaling property
* @see http://doc.babylonjs.com/how_to/gui#adaptive-scaling
*/
this.ignoreAdaptiveScaling = false;
this._value = value;
this._originalUnit = unit;
}
Object.defineProperty(ValueAndUnit.prototype, "isPercentage", {
/** Gets a boolean indicating if the value is a percentage */
get: function () {
return this.unit === ValueAndUnit.UNITMODE_PERCENTAGE;
},
enumerable: true,
configurable: true
});
Object.defineProperty(ValueAndUnit.prototype, "isPixel", {
/** Gets a boolean indicating if the value is store as pixel */
get: function () {
return this.unit === ValueAndUnit.UNITMODE_PIXEL;
},
enumerable: true,
configurable: true
});
Object.defineProperty(ValueAndUnit.prototype, "internalValue", {
/** Gets direct internal value */
get: function () {
return this._value;
},
enumerable: true,
configurable: true
});
/**
* Gets value as pixel
* @param host defines the root host
* @param refValue defines the reference value for percentages
* @returns the value as pixel
*/
ValueAndUnit.prototype.getValueInPixel = function (host, refValue) {
if (this.isPixel) {
return this.getValue(host);
}
return this.getValue(host) * refValue;
};
/**
* Update the current value and unit. This should be done cautiously as the GUi won't be marked as dirty with this function.
* @param value defines the value to store
* @param unit defines the unit to store
* @returns the current ValueAndUnit
*/
ValueAndUnit.prototype.updateInPlace = function (value, unit) {
if (unit === void 0) { unit = ValueAndUnit.UNITMODE_PIXEL; }
this._value = value;
this.unit = unit;
return this;
};
/**
* Gets the value accordingly to its unit
* @param host defines the root host
* @returns the value
*/
ValueAndUnit.prototype.getValue = function (host) {
if (host && !this.ignoreAdaptiveScaling && this.unit !== ValueAndUnit.UNITMODE_PERCENTAGE) {
var width = 0;
var height = 0;
if (host.idealWidth) {
width = (this._value * host.getSize().width) / host.idealWidth;
}
if (host.idealHeight) {
height = (this._value * host.getSize().height) / host.idealHeight;
}
if (host.useSmallestIdeal && host.idealWidth && host.idealHeight) {
return window.innerWidth < window.innerHeight ? width : height;
}
if (host.idealWidth) { // horizontal
return width;
}
if (host.idealHeight) { // vertical
return height;
}
}
return this._value;
};
/**
* Gets a string representation of the value
* @param host defines the root host
* @param decimals defines an optional number of decimals to display
* @returns a string
*/
ValueAndUnit.prototype.toString = function (host, decimals) {
switch (this.unit) {
case ValueAndUnit.UNITMODE_PERCENTAGE:
var percentage = this.getValue(host) * 100;
return (decimals ? percentage.toFixed(decimals) : percentage) + "%";
case ValueAndUnit.UNITMODE_PIXEL:
var pixels = this.getValue(host);
return (decimals ? pixels.toFixed(decimals) : pixels) + "px";
}
return this.unit.toString();
};
/**
* Store a value parsed from a string
* @param source defines the source string
* @returns true if the value was successfully parsed
*/
ValueAndUnit.prototype.fromString = function (source) {
var match = ValueAndUnit._Regex.exec(source.toString());
if (!match || match.length === 0) {
return false;
}
var sourceValue = parseFloat(match[1]);
var sourceUnit = this._originalUnit;
if (!this.negativeValueAllowed) {
if (sourceValue < 0) {
sourceValue = 0;
}
}
if (match.length === 4) {
switch (match[3]) {
case "px":
sourceUnit = ValueAndUnit.UNITMODE_PIXEL;
break;
case "%":
sourceUnit = ValueAndUnit.UNITMODE_PERCENTAGE;
sourceValue /= 100.0;
break;
}
}
if (sourceValue === this._value && sourceUnit === this.unit) {
return false;
}
this._value = sourceValue;
this.unit = sourceUnit;
return true;
};
Object.defineProperty(ValueAndUnit, "UNITMODE_PERCENTAGE", {
/** UNITMODE_PERCENTAGE */
get: function () {
return ValueAndUnit._UNITMODE_PERCENTAGE;
},
enumerable: true,
configurable: true
});
Object.defineProperty(ValueAndUnit, "UNITMODE_PIXEL", {
/** UNITMODE_PIXEL */
get: function () {
return ValueAndUnit._UNITMODE_PIXEL;
},
enumerable: true,
configurable: true
});
// Static
ValueAndUnit._Regex = /(^-?\d*(\.\d+)?)(%|px)?/;
ValueAndUnit._UNITMODE_PERCENTAGE = 0;
ValueAndUnit._UNITMODE_PIXEL = 1;
return ValueAndUnit;
}());
/***/ }),
/***/ "./3D/controls/abstractButton3D.ts":
/*!*****************************************!*\
!*** ./3D/controls/abstractButton3D.ts ***!
\*****************************************/
/*! exports provided: AbstractButton3D */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "AbstractButton3D", function() { return AbstractButton3D; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../../node_modules/tslib/tslib.es6.js");
/* harmony import */ var babylonjs_Meshes_transformNode__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! babylonjs/Meshes/transformNode */ "babylonjs/Misc/observable");
/* harmony import */ var babylonjs_Meshes_transformNode__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(babylonjs_Meshes_transformNode__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var _control3D__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./control3D */ "./3D/controls/control3D.ts");
/**
* Class used as a root to all buttons
*/
var AbstractButton3D = /** @class */ (function (_super) {
tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](AbstractButton3D, _super);
/**
* Creates a new button
* @param name defines the control name
*/
function AbstractButton3D(name) {
return _super.call(this, name) || this;
}
AbstractButton3D.prototype._getTypeName = function () {
return "AbstractButton3D";
};
// Mesh association
AbstractButton3D.prototype._createNode = function (scene) {
return new babylonjs_Meshes_transformNode__WEBPACK_IMPORTED_MODULE_1__["TransformNode"]("button" + this.name);
};
return AbstractButton3D;
}(_control3D__WEBPACK_IMPORTED_MODULE_2__["Control3D"]));
/***/ }),
/***/ "./3D/controls/button3D.ts":
/*!*********************************!*\
!*** ./3D/controls/button3D.ts ***!
\*********************************/
/*! exports provided: Button3D */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Button3D", function() { return Button3D; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../../node_modules/tslib/tslib.es6.js");
/* harmony import */ var babylonjs_Maths_math__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! babylonjs/Maths/math */ "babylonjs/Misc/observable");
/* harmony import */ var babylonjs_Maths_math__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(babylonjs_Maths_math__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var _abstractButton3D__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./abstractButton3D */ "./3D/controls/abstractButton3D.ts");
/* harmony import */ var _2D_advancedDynamicTexture__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../../2D/advancedDynamicTexture */ "./2D/advancedDynamicTexture.ts");
/**
* Class used to create a button in 3D
*/
var Button3D = /** @class */ (function (_super) {
tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](Button3D, _super);
/**
* Creates a new button
* @param name defines the control name
*/
function Button3D(name) {
var _this = _super.call(this, name) || this;
_this._contentResolution = 512;
_this._contentScaleRatio = 2;
// Default animations
_this.pointerEnterAnimation = function () {
if (!_this.mesh) {
return;
}
_this._currentMaterial.emissiveColor = babylonjs_Maths_math__WEBPACK_IMPORTED_MODULE_1__["Color3"].Red();
};
_this.pointerOutAnimation = function () {
_this._currentMaterial.emissiveColor = babylonjs_Maths_math__WEBPACK_IMPORTED_MODULE_1__["Color3"].Black();
};
_this.pointerDownAnimation = function () {
if (!_this.mesh) {
return;
}
_this.mesh.scaling.scaleInPlace(0.95);
};
_this.pointerUpAnimation = function () {
if (!_this.mesh) {
return;
}
_this.mesh.scaling.scaleInPlace(1.0 / 0.95);
};
return _this;
}
Object.defineProperty(Button3D.prototype, "contentResolution", {
/**
* Gets or sets the texture resolution used to render content (512 by default)
*/
get: function () {
return this._contentResolution;
},
set: function (value) {
if (this._contentResolution === value) {
return;
}
this._contentResolution = value;
this._resetContent();
},
enumerable: true,
configurable: true
});
Object.defineProperty(Button3D.prototype, "contentScaleRatio", {
/**
* Gets or sets the texture scale ratio used to render content (2 by default)
*/
get: function () {
return this._contentScaleRatio;
},
set: function (value) {
if (this._contentScaleRatio === value) {
return;
}
this._contentScaleRatio = value;
this._resetContent();
},
enumerable: true,
configurable: true
});
Button3D.prototype._disposeFacadeTexture = function () {
if (this._facadeTexture) {
this._facadeTexture.dispose();
this._facadeTexture = null;
}
};
Button3D.prototype._resetContent = function () {
this._disposeFacadeTexture();
this.content = this._content;
};
Object.defineProperty(Button3D.prototype, "content", {
/**
* Gets or sets the GUI 2D content used to display the button's facade
*/
get: function () {
return this._content;
},
set: function (value) {
this._content = value;
if (!this._host || !this._host.utilityLayer) {
return;
}
if (!this._facadeTexture) {
this._facadeTexture = new _2D_advancedDynamicTexture__WEBPACK_IMPORTED_MODULE_3__["AdvancedDynamicTexture"]("Facade", this._contentResolution, this._contentResolution, this._host.utilityLayer.utilityLayerScene, true, babylonjs_Maths_math__WEBPACK_IMPORTED_MODULE_1__["Texture"].TRILINEAR_SAMPLINGMODE);
this._facadeTexture.rootContainer.scaleX = this._contentScaleRatio;
this._facadeTexture.rootContainer.scaleY = this._contentScaleRatio;
this._facadeTexture.premulAlpha = true;
}
this._facadeTexture.addControl(value);
this._applyFacade(this._facadeTexture);
},
enumerable: true,
configurable: true
});
/**
* Apply the facade texture (created from the content property).
* This function can be overloaded by child classes
* @param facadeTexture defines the AdvancedDynamicTexture to use
*/
Button3D.prototype._applyFacade = function (facadeTexture) {
this._currentMaterial.emissiveTexture = facadeTexture;
};
Button3D.prototype._getTypeName = function () {
return "Button3D";
};
// Mesh association
Button3D.prototype._createNode = function (scene) {
var faceUV = new Array(6);
for (var i = 0; i < 6; i++) {
faceUV[i] = new babylonjs_Maths_math__WEBPACK_IMPORTED_MODULE_1__["Vector4"](0, 0, 0, 0);
}
faceUV[1] = new babylonjs_Maths_math__WEBPACK_IMPORTED_MODULE_1__["Vector4"](0, 0, 1, 1);
var mesh = babylonjs_Maths_math__WEBPACK_IMPORTED_MODULE_1__["BoxBuilder"].CreateBox(this.name + "_rootMesh", {
width: 1.0,
height: 1.0,
depth: 0.08,
faceUV: faceUV
}, scene);
return mesh;
};
Button3D.prototype._affectMaterial = function (mesh) {
var material = new babylonjs_Maths_math__WEBPACK_IMPORTED_MODULE_1__["StandardMaterial"](this.name + "Material", mesh.getScene());
material.specularColor = babylonjs_Maths_math__WEBPACK_IMPORTED_MODULE_1__["Color3"].Black();
mesh.material = material;
this._currentMaterial = material;
this._resetContent();
};
/**
* Releases all associated resources
*/
Button3D.prototype.dispose = function () {
_super.prototype.dispose.call(this);
this._disposeFacadeTexture();
if (this._currentMaterial) {
this._currentMaterial.dispose();
}
};
return Button3D;
}(_abstractButton3D__WEBPACK_IMPORTED_MODULE_2__["AbstractButton3D"]));
/***/ }),
/***/ "./3D/controls/container3D.ts":
/*!************************************!*\
!*** ./3D/controls/container3D.ts ***!
\************************************/
/*! exports provided: Container3D */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Container3D", function() { return Container3D; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../../node_modules/tslib/tslib.es6.js");
/* harmony import */ var babylonjs_Meshes_transformNode__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! babylonjs/Meshes/transformNode */ "babylonjs/Misc/observable");
/* harmony import */ var babylonjs_Meshes_transformNode__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(babylonjs_Meshes_transformNode__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var _control3D__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./control3D */ "./3D/controls/control3D.ts");
/**
* Class used to create containers for controls
*/
var Container3D = /** @class */ (function (_super) {
tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](Container3D, _super);
/**
* Creates a new container
* @param name defines the container name
*/
function Container3D(name) {
var _this = _super.call(this, name) || this;
_this._blockLayout = false;
/**
* Gets the list of child controls
*/
_this._children = new Array();
return _this;
}
Object.defineProperty(Container3D.prototype, "children", {
/**
* Gets the list of child controls
*/
get: function () {
return this._children;
},
enumerable: true,
configurable: true
});
Object.defineProperty(Container3D.prototype, "blockLayout", {
/**
* Gets or sets a boolean indicating if the layout must be blocked (default is false).
* This is helpful to optimize layout operation when adding multiple children in a row
*/
get: function () {
return this._blockLayout;
},
set: function (value) {
if (this._blockLayout === value) {
return;
}
this._blockLayout = value;
if (!this._blockLayout) {
this._arrangeChildren();
}
},
enumerable: true,
configurable: true
});
/**
* Force the container to update the layout. Please note that it will not take blockLayout property in account
* @returns the current container
*/
Container3D.prototype.updateLayout = function () {
this._arrangeChildren();
return this;
};
/**
* Gets a boolean indicating if the given control is in the children of this control
* @param control defines the control to check
* @returns true if the control is in the child list
*/
Container3D.prototype.containsControl = function (control) {
return this._children.indexOf(control) !== -1;
};
/**
* Adds a control to the children of this control
* @param control defines the control to add
* @returns the current container
*/
Container3D.prototype.addControl = function (control) {
var index = this._children.indexOf(control);
if (index !== -1) {
return this;
}
control.parent = this;
control._host = this._host;
this._children.push(control);
if (this._host.utilityLayer) {
control._prepareNode(this._host.utilityLayer.utilityLayerScene);
if (control.node) {
control.node.parent = this.node;
}
if (!this.blockLayout) {
this._arrangeChildren();
}
}
return this;
};
/**
* This function will be called everytime a new control is added
*/
Container3D.prototype._arrangeChildren = function () {
};
Container3D.prototype._createNode = function (scene) {
return new babylonjs_Meshes_transformNode__WEBPACK_IMPORTED_MODULE_1__["TransformNode"]("ContainerNode", scene);
};
/**
* Removes a control from the children of this control
* @param control defines the control to remove
* @returns the current container
*/
Container3D.prototype.removeControl = function (control) {
var index = this._children.indexOf(control);
if (index !== -1) {
this._children.splice(index, 1);
control.parent = null;
control._disposeNode();
}
return this;
};
Container3D.prototype._getTypeName = function () {
return "Container3D";
};
/**
* Releases all associated resources
*/
Container3D.prototype.dispose = function () {
for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
var control = _a[_i];
control.dispose();
}
this._children = [];
_super.prototype.dispose.call(this);
};
/** Control rotation will remain unchanged */
Container3D.UNSET_ORIENTATION = 0;
/** Control will rotate to make it look at sphere central axis */
Container3D.FACEORIGIN_ORIENTATION = 1;
/** Control will rotate to make it look back at sphere central axis */
Container3D.FACEORIGINREVERSED_ORIENTATION = 2;
/** Control will rotate to look at z axis (0, 0, 1) */
Container3D.FACEFORWARD_ORIENTATION = 3;
/** Control will rotate to look at negative z axis (0, 0, -1) */
Container3D.FACEFORWARDREVERSED_ORIENTATION = 4;
return Container3D;
}(_control3D__WEBPACK_IMPORTED_MODULE_2__["Control3D"]));
/***/ }),
/***/ "./3D/controls/control3D.ts":
/*!**********************************!*\
!*** ./3D/controls/control3D.ts ***!
\**********************************/
/*! exports provided: Control3D */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Control3D", function() { return Control3D; });
/* harmony import */ var babylonjs_Misc_observable__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! babylonjs/Misc/observable */ "babylonjs/Misc/observable");
/* harmony import */ var babylonjs_Misc_observable__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(babylonjs_Misc_observable__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _vector3WithInfo__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../vector3WithInfo */ "./3D/vector3WithInfo.ts");
/**
* Class used as base class for controls
*/
var Control3D = /** @class */ (function () {
/**
* Creates a new control
* @param name defines the control name
*/
function Control3D(
/** Defines the control name */
name) {
this.name = name;
this._downCount = 0;
this._enterCount = -1;
this._downPointerIds = {};
this._isVisible = true;
/**
* An event triggered when the pointer move over the control
*/
this.onPointerMoveObservable = new babylonjs_Misc_observable__WEBPACK_IMPORTED_MODULE_0__["Observable"]();
/**
* An event triggered when the pointer move out of the control
*/
this.onPointerOutObservable = new babylonjs_Misc_observable__WEBPACK_IMPORTED_MODULE_0__["Observable"]();
/**
* An event triggered when the pointer taps the control
*/
this.onPointerDownObservable = new babylonjs_Misc_observable__WEBPACK_IMPORTED_MODULE_0__["Observable"]();
/**
* An event triggered when pointer is up
*/
this.onPointerUpObservable = new babylonjs_Misc_observable__WEBPACK_IMPORTED_MODULE_0__["Observable"]();
/**
* An event triggered when a control is clicked on (with a mouse)
*/
this.onPointerClickObservable = new babylonjs_Misc_observable__WEBPACK_IMPORTED_MODULE_0__["Observable"]();
/**
* An event triggered when pointer enters the control
*/
this.onPointerEnterObservable = new babylonjs_Misc_observable__WEBPACK_IMPORTED_MODULE_0__["Observable"]();
// Behaviors
this._behaviors = new Array();
}
Object.defineProperty(Control3D.prototype, "position", {
/** Gets or sets the control position in world space */
get: function () {
if (!this._node) {
return babylonjs_Misc_observable__WEBPACK_IMPORTED_MODULE_0__["Vector3"].Zero();
}
return this._node.position;
},
set: function (value) {
if (!this._node) {
return;
}
this._node.position = value;
},
enumerable: true,
configurable: true
});
Object.defineProperty(Control3D.prototype, "scaling", {
/** Gets or sets the control scaling in world space */
get: function () {
if (!this._node) {
return new babylonjs_Misc_observable__WEBPACK_IMPORTED_MODULE_0__["Vector3"](1, 1, 1);
}
return this._node.scaling;
},
set: function (value) {
if (!this._node) {
return;
}
this._node.scaling = value;
},
enumerable: true,
configurable: true
});
Object.defineProperty(Control3D.prototype, "behaviors", {
/**
* Gets the list of attached behaviors
* @see http://doc.babylonjs.com/features/behaviour
*/
get: function () {
return this._behaviors;
},
enumerable: true,
configurable: true
});
/**
* Attach a behavior to the control
* @see http://doc.babylonjs.com/features/behaviour
* @param behavior defines the behavior to attach
* @returns the current control
*/
Control3D.prototype.addBehavior = function (behavior) {
var _this = this;
var index = this._behaviors.indexOf(behavior);
if (index !== -1) {
return this;
}
behavior.init();
var scene = this._host.scene;
if (scene.isLoading) {
// We defer the attach when the scene will be loaded
scene.onDataLoadedObservable.addOnce(function () {
behavior.attach(_this);
});
}
else {
behavior.attach(this);
}
this._behaviors.push(behavior);
return this;
};
/**
* Remove an attached behavior
* @see http://doc.babylonjs.com/features/behaviour
* @param behavior defines the behavior to attach
* @returns the current control
*/
Control3D.prototype.removeBehavior = function (behavior) {
var index = this._behaviors.indexOf(behavior);
if (index === -1) {
return this;
}
this._behaviors[index].detach();
this._behaviors.splice(index, 1);
return this;
};
/**
* Gets an attached behavior by name
* @param name defines the name of the behavior to look for
* @see http://doc.babylonjs.com/features/behaviour
* @returns null if behavior was not found else the requested behavior
*/
Control3D.prototype.getBehaviorByName = function (name) {
for (var _i = 0, _a = this._behaviors; _i < _a.length; _i++) {
var behavior = _a[_i];
if (behavior.name === name) {
return behavior;
}
}
return null;
};
Object.defineProperty(Control3D.prototype, "isVisible", {
/** Gets or sets a boolean indicating if the control is visible */
get: function () {
return this._isVisible;
},
set: function (value) {
if (this._isVisible === value) {
return;
}
this._isVisible = value;
var mesh = this.mesh;
if (mesh) {
mesh.setEnabled(value);
}
},
enumerable: true,
configurable: true
});
Object.defineProperty(Control3D.prototype, "typeName", {
/**
* Gets a string representing the class name
*/
get: function () {
return this._getTypeName();
},
enumerable: true,
configurable: true
});
/**
* Get the current class name of the control.
* @returns current class name
*/
Control3D.prototype.getClassName = function () {
return this._getTypeName();
};
Control3D.prototype._getTypeName = function () {
return "Control3D";
};
Object.defineProperty(Control3D.prototype, "node", {
/**
* Gets the transform node used by this control
*/
get: function () {
return this._node;
},
enumerable: true,
configurable: true
});
Object.defineProperty(Control3D.prototype, "mesh", {
/**
* Gets the mesh used to render this control
*/
get: function () {
if (this._node instanceof babylonjs_Misc_observable__WEBPACK_IMPORTED_MODULE_0__["AbstractMesh"]) {
return this._node;
}
return null;
},
enumerable: true,
configurable: true
});
/**
* Link the control as child of the given node
* @param node defines the node to link to. Use null to unlink the control
* @returns the current control
*/
Control3D.prototype.linkToTransformNode = function (node) {
if (this._node) {
this._node.parent = node;
}
return this;
};
/** @hidden **/
Control3D.prototype._prepareNode = function (scene) {
if (!this._node) {
this._node = this._createNode(scene);
if (!this.node) {
return;
}
this._node.metadata = this; // Store the control on the metadata field in order to get it when picking
this._node.position = this.position;
this._node.scaling = this.scaling;
var mesh = this.mesh;
if (mesh) {
mesh.isPickable = true;
this._affectMaterial(mesh);
}
}
};
/**
* Node creation.
* Can be overriden by children
* @param scene defines the scene where the node must be attached
* @returns the attached node or null if none. Must return a Mesh or AbstractMesh if there is an atttached visible object
*/
Control3D.prototype._createNode = function (scene) {
// Do nothing by default
return null;
};
/**
* Affect a material to the given mesh
* @param mesh defines the mesh which will represent the control
*/
Control3D.prototype._affectMaterial = function (mesh) {
mesh.material = null;
};
// Pointers
/** @hidden */
Control3D.prototype._onPointerMove = function (target, coordinates) {
this.onPointerMoveObservable.notifyObservers(coordinates, -1, target, this);
};
/** @hidden */
Control3D.prototype._onPointerEnter = function (target) {
if (this._enterCount > 0) {
return false;
}
if (this._enterCount === -1) { // -1 is for touch input, we are now sure we are with a mouse or pencil
this._enterCount = 0;
}
this._enterCount++;
this.onPointerEnterObservable.notifyObservers(this, -1, target, this);
if (this.pointerEnterAnimation) {
this.pointerEnterAnimation();
}
return true;
};
/** @hidden */
Control3D.prototype._onPointerOut = function (target) {
this._enterCount = 0;
this.onPointerOutObservable.notifyObservers(this, -1, target, this);
if (this.pointerOutAnimation) {
this.pointerOutAnimation();
}
};
/** @hidden */
Control3D.prototype._onPointerDown = function (target, coordinates, pointerId, buttonIndex) {
if (this._downCount !== 0) {
this._downCount++;
return false;
}
this._downCount++;
this._downPointerIds[pointerId] = true;
this.onPointerDownObservable.notifyObservers(new _vector3WithInfo__WEBPACK_IMPORTED_MODULE_1__["Vector3WithInfo"](coordinates, buttonIndex), -1, target, this);
if (this.pointerDownAnimation) {
this.pointerDownAnimation();
}
return true;
};
/** @hidden */
Control3D.prototype._onPointerUp = function (target, coordinates, pointerId, buttonIndex, notifyClick) {
this._downCount--;
delete this._downPointerIds[pointerId];
if (this._downCount < 0) {
// Handle if forcePointerUp was called prior to this
this._downCount = 0;
return;
}
if (this._downCount == 0) {
if (notifyClick && (this._enterCount > 0 || this._enterCount === -1)) {
this.onPointerClickObservable.notifyObservers(new _vector3WithInfo__WEBPACK_IMPORTED_MODULE_1__["Vector3WithInfo"](coordinates, buttonIndex), -1, target, this);
}
this.onPointerUpObservable.notifyObservers(new _vector3WithInfo__WEBPACK_IMPORTED_MODULE_1__["Vector3WithInfo"](coordinates, buttonIndex), -1, target, this);
if (this.pointerUpAnimation) {
this.pointerUpAnimation();
}
}
};
/** @hidden */
Control3D.prototype.forcePointerUp = function (pointerId) {
if (pointerId === void 0) { pointerId = null; }
if (pointerId !== null) {
this._onPointerUp(this, babylonjs_Misc_observable__WEBPACK_IMPORTED_MODULE_0__["Vector3"].Zero(), pointerId, 0, true);
}
else {
for (var key in this._downPointerIds) {
this._onPointerUp(this, babylonjs_Misc_observable__WEBPACK_IMPORTED_MODULE_0__["Vector3"].Zero(), +key, 0, true);
}
if (this._downCount > 0) {
this._downCount = 1;
this._onPointerUp(this, babylonjs_Misc_observable__WEBPACK_IMPORTED_MODULE_0__["Vector3"].Zero(), 0, 0, true);
}
}
};
/** @hidden */
Control3D.prototype._processObservables = function (type, pickedPoint, pointerId, buttonIndex) {
if (type === babylonjs_Misc_observable__WEBPACK_IMPORTED_MODULE_0__["PointerEventTypes"].POINTERMOVE) {
this._onPointerMove(this, pickedPoint);
var previousControlOver = this._host._lastControlOver[pointerId];
if (previousControlOver && previousControlOver !== this) {
previousControlOver._onPointerOut(this);
}
if (previousControlOver !== this) {
this._onPointerEnter(this);
}
this._host._lastControlOver[pointerId] = this;
return true;
}
if (type === babylonjs_Misc_observable__WEBPACK_IMPORTED_MODULE_0__["PointerEventTypes"].POINTERDOWN) {
this._onPointerDown(this, pickedPoint, pointerId, buttonIndex);
this._host._lastControlDown[pointerId] = this;
this._host._lastPickedControl = this;
return true;
}
if (type === babylonjs_Misc_observable__WEBPACK_IMPORTED_MODULE_0__["PointerEventTypes"].POINTERUP) {
if (this._host._lastControlDown[pointerId]) {
this._host._lastControlDown[pointerId]._onPointerUp(this, pickedPoint, pointerId, buttonIndex, true);
}
delete this._host._lastControlDown[pointerId];
return true;
}
return false;
};
/** @hidden */
Control3D.prototype._disposeNode = function () {
if (this._node) {
this._node.dispose();
this._node = null;
}
};
/**
* Releases all associated resources
*/
Control3D.prototype.dispose = function () {
this.onPointerDownObservable.clear();
this.onPointerEnterObservable.clear();
this.onPointerMoveObservable.clear();
this.onPointerOutObservable.clear();
this.onPointerUpObservable.clear();
this.onPointerClickObservable.clear();
this._disposeNode();
// Behaviors
for (var _i = 0, _a = this._behaviors; _i < _a.length; _i++) {
var behavior = _a[_i];
behavior.detach();
}
};
return Control3D;
}());
/***/ }),
/***/ "./3D/controls/cylinderPanel.ts":
/*!**************************************!*\
!*** ./3D/controls/cylinderPanel.ts ***!
\**************************************/
/*! exports provided: CylinderPanel */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "CylinderPanel", function() { return CylinderPanel; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../../node_modules/tslib/tslib.es6.js");
/* harmony import */ var babylonjs_Misc_tools__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! babylonjs/Misc/tools */ "babylonjs/Misc/observable");
/* harmony import */ var babylonjs_Misc_tools__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(babylonjs_Misc_tools__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var _volumeBasedPanel__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./volumeBasedPanel */ "./3D/controls/volumeBasedPanel.ts");
/* harmony import */ var _container3D__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./container3D */ "./3D/controls/container3D.ts");
/**
* Class used to create a container panel deployed on the surface of a cylinder
*/
var CylinderPanel = /** @class */ (function (_super) {
tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](CylinderPanel, _super);
function CylinderPanel() {
var _this = _super !== null && _super.apply(this, arguments) || this;
_this._radius = 5.0;
return _this;
}
Object.defineProperty(CylinderPanel.prototype, "radius", {
/**
* Gets or sets the radius of the cylinder where to project controls (5 by default)
*/
get: function () {
return this._radius;
},
set: function (value) {
var _this = this;
if (this._radius === value) {
return;
}
this._radius = value;
babylonjs_Misc_tools__WEBPACK_IMPORTED_MODULE_1__["Tools"].SetImmediate(function () {
_this._arrangeChildren();
});
},
enumerable: true,
configurable: true
});
CylinderPanel.prototype._mapGridNode = function (control, nodePosition) {
var mesh = control.mesh;
if (!mesh) {
return;
}
var newPos = this._cylindricalMapping(nodePosition);
control.position = newPos;
switch (this.orientation) {
case _container3D__WEBPACK_IMPORTED_MODULE_3__["Container3D"].FACEORIGIN_ORIENTATION:
mesh.lookAt(new babylonjs_Misc_tools__WEBPACK_IMPORTED_MODULE_1__["Vector3"](2 * newPos.x, newPos.y, 2 * newPos.z));
break;
case _container3D__WEBPACK_IMPORTED_MODULE_3__["Container3D"].FACEORIGINREVERSED_ORIENTATION:
mesh.lookAt(new babylonjs_Misc_tools__WEBPACK_IMPORTED_MODULE_1__["Vector3"](-newPos.x, newPos.y, -newPos.z));
break;
case _container3D__WEBPACK_IMPORTED_MODULE_3__["Container3D"].FACEFORWARD_ORIENTATION:
break;
case _container3D__WEBPACK_IMPORTED_MODULE_3__["Container3D"].FACEFORWARDREVERSED_ORIENTATION:
mesh.rotate(babylonjs_Misc_tools__WEBPACK_IMPORTED_MODULE_1__["Axis"].Y, Math.PI, babylonjs_Misc_tools__WEBPACK_IMPORTED_MODULE_1__["Space"].LOCAL);
break;
}
};
CylinderPanel.prototype._cylindricalMapping = function (source) {
var newPos = new babylonjs_Misc_tools__WEBPACK_IMPORTED_MODULE_1__["Vector3"](0, source.y, this._radius);
var yAngle = (source.x / this._radius);
babylonjs_Misc_tools__WEBPACK_IMPORTED_MODULE_1__["Matrix"].RotationYawPitchRollToRef(yAngle, 0, 0, babylonjs_Misc_tools__WEBPACK_IMPORTED_MODULE_1__["Tmp"].Matrix[0]);
return babylonjs_Misc_tools__WEBPACK_IMPORTED_MODULE_1__["Vector3"].TransformNormal(newPos, babylonjs_Misc_tools__WEBPACK_IMPORTED_MODULE_1__["Tmp"].Matrix[0]);
};
return CylinderPanel;
}(_volumeBasedPanel__WEBPACK_IMPORTED_MODULE_2__["VolumeBasedPanel"]));
/***/ }),
/***/ "./3D/controls/holographicButton.ts":
/*!******************************************!*\
!*** ./3D/controls/holographicButton.ts ***!
\******************************************/
/*! exports provided: HolographicButton */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "HolographicButton", function() { return HolographicButton; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../../node_modules/tslib/tslib.es6.js");
/* harmony import */ var _button3D__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./button3D */ "./3D/controls/button3D.ts");
/* harmony import */ var babylonjs_Maths_math__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! babylonjs/Maths/math */ "babylonjs/Misc/observable");
/* harmony import */ var babylonjs_Maths_math__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(babylonjs_Maths_math__WEBPACK_IMPORTED_MODULE_2__);
/* harmony import */ var _materials_fluentMaterial__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../materials/fluentMaterial */ "./3D/materials/fluentMaterial.ts");
/* harmony import */ var _2D_controls_stackPanel__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../../2D/controls/stackPanel */ "./2D/controls/stackPanel.ts");
/* harmony import */ var _2D_controls_image__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../../2D/controls/image */ "./2D/controls/image.ts");
/* harmony import */ var _2D_controls_textBlock__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../../2D/controls/textBlock */ "./2D/controls/textBlock.ts");
/* harmony import */ var _2D_advancedDynamicTexture__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ../../2D/advancedDynamicTexture */ "./2D/advancedDynamicTexture.ts");
/**
* Class used to create a holographic button in 3D
*/
var HolographicButton = /** @class */ (function (_super) {
tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](HolographicButton, _super);
/**
* Creates a new button
* @param name defines the control name
*/
function HolographicButton(name, shareMaterials) {
if (shareMaterials === void 0) { shareMaterials = true; }
var _this = _super.call(this, name) || this;
_this._shareMaterials = true;
_this._shareMaterials = shareMaterials;
// Default animations
_this.pointerEnterAnimation = function () {
if (!_this.mesh) {
return;
}
_this._frontPlate.setEnabled(true);
};
_this.pointerOutAnimation = function () {
if (!_this.mesh) {
return;
}
_this._frontPlate.setEnabled(false);
};
return _this;
}
HolographicButton.prototype._disposeTooltip = function () {
this._tooltipFade = null;
if (this._tooltipTextBlock) {
this._tooltipTextBlock.dispose();
}
if (this._tooltipTexture) {
this._tooltipTexture.dispose();
}
if (this._tooltipMesh) {
this._tooltipMesh.dispose();
}
this.onPointerEnterObservable.remove(this._tooltipHoverObserver);
this.onPointerOutObservable.remove(this._tooltipOutObserver);
};
Object.defineProperty(HolographicButton.prototype, "tooltipText", {
get: function () {
if (this._tooltipTextBlock) {
return this._tooltipTextBlock.text;
}
return null;
},
/**
* Text to be displayed on the tooltip shown when hovering on the button. When set to null tooltip is disabled. (Default: null)
*/
set: function (text) {
var _this = this;
if (!text) {
this._disposeTooltip();
return;
}
if (!this._tooltipFade) {
// Create tooltip with mesh and text
this._tooltipMesh = babylonjs_Maths_math__WEBPACK_IMPORTED_MODULE_2__["PlaneBuilder"].CreatePlane("", { size: 1 }, this._backPlate._scene);
var tooltipBackground = babylonjs_Maths_math__WEBPACK_IMPORTED_MODULE_2__["PlaneBuilder"].CreatePlane("", { size: 1, sideOrientation: babylonjs_Maths_math__WEBPACK_IMPORTED_MODULE_2__["Mesh"].DOUBLESIDE }, this._backPlate._scene);
var mat = new babylonjs_Maths_math__WEBPACK_IMPORTED_MODULE_2__["StandardMaterial"]("", this._backPlate._scene);
mat.diffuseColor = babylonjs_Maths_math__WEBPACK_IMPORTED_MODULE_2__["Color3"].FromHexString("#212121");
tooltipBackground.material = mat;
tooltipBackground.isPickable = false;
this._tooltipMesh.addChild(tooltipBackground);
tooltipBackground.position.z = 0.05;
this._tooltipMesh.scaling.y = 1 / 3;
this._tooltipMesh.position.y = 0.7;
this._tooltipMesh.position.z = -0.15;
this._tooltipMesh.isPickable = false;
this._tooltipMesh.parent = this._backPlate;
// Create text texture for the tooltip
this._tooltipTexture = _2D_advancedDynamicTexture__WEBPACK_IMPORTED_MODULE_7__["AdvancedDynamicTexture"].CreateForMesh(this._tooltipMesh);
this._tooltipTextBlock = new _2D_controls_textBlock__WEBPACK_IMPORTED_MODULE_6__["TextBlock"]();
this._tooltipTextBlock.scaleY = 3;
this._tooltipTextBlock.color = "white";
this._tooltipTextBlock.fontSize = 130;
this._tooltipTexture.addControl(this._tooltipTextBlock);
// Add hover action to tooltip
this._tooltipFade = new babylonjs_Maths_math__WEBPACK_IMPORTED_MODULE_2__["FadeInOutBehavior"]();
this._tooltipFade.delay = 500;
this._tooltipMesh.addBehavior(this._tooltipFade);
this._tooltipHoverObserver = this.onPointerEnterObservable.add(function () {
if (_this._tooltipFade) {
_this._tooltipFade.fadeIn(true);
}
});
this._tooltipOutObserver = this.onPointerOutObservable.add(function () {
if (_this._tooltipFade) {
_this._tooltipFade.fadeIn(false);
}
});
}
if (this._tooltipTextBlock) {
this._tooltipTextBlock.text = text;
}
},
enumerable: true,
configurable: true
});
Object.defineProperty(HolographicButton.prototype, "text", {
/**
* Gets or sets text for the button
*/
get: function () {
return this._text;
},
set: function (value) {
if (this._text === value) {
return;
}
this._text = value;
this._rebuildContent();
},
enumerable: true,
configurable: true
});
Object.defineProperty(HolographicButton.prototype, "imageUrl", {
/**
* Gets or sets the image url for the button
*/
get: function () {
return this._imageUrl;
},
set: function (value) {
if (this._imageUrl === value) {
return;
}
this._imageUrl = value;
this._rebuildContent();
},
enumerable: true,
configurable: true
});
Object.defineProperty(HolographicButton.prototype, "backMaterial", {
/**
* Gets the back material used by this button
*/
get: function () {
return this._backMaterial;
},
enumerable: true,
configurable: true
});
Object.defineProperty(HolographicButton.prototype, "frontMaterial", {
/**
* Gets the front material used by this button
*/
get: function () {
return this._frontMaterial;
},
enumerable: true,
configurable: true
});
Object.defineProperty(HolographicButton.prototype, "plateMaterial", {
/**
* Gets the plate material used by this button
*/
get: function () {
return this._plateMaterial;
},
enumerable: true,
configurable: true
});
Object.defineProperty(HolographicButton.prototype, "shareMaterials", {
/**
* Gets a boolean indicating if this button shares its material with other HolographicButtons
*/
get: function () {
return this._shareMaterials;
},
enumerable: true,
configurable: true
});
HolographicButton.prototype._getTypeName = function () {
return "HolographicButton";
};
HolographicButton.prototype._rebuildContent = function () {
this._disposeFacadeTexture();
var panel = new _2D_controls_stackPanel__WEBPACK_IMPORTED_MODULE_4__["StackPanel"]();
panel.isVertical = true;
if (this._imageUrl) {
var image = new _2D_controls_image__WEBPACK_IMPORTED_MODULE_5__["Image"]();
image.source = this._imageUrl;
image.paddingTop = "40px";
image.height = "180px";
image.width = "100px";
image.paddingBottom = "40px";
panel.addControl(image);
}
if (this._text) {
var text = new _2D_controls_textBlock__WEBPACK_IMPORTED_MODULE_6__["TextBlock"]();
text.text = this._text;
text.color = "white";
text.height = "30px";
text.fontSize = 24;
panel.addControl(text);
}
if (this._frontPlate) {
this.content = panel;
}
};
// Mesh association
HolographicButton.prototype._createNode = function (scene) {
this._backPlate = babylonjs_Maths_math__WEBPACK_IMPORTED_MODULE_2__["BoxBuilder"].CreateBox(this.name + "BackMesh", {
width: 1.0,
height: 1.0,
depth: 0.08
}, scene);
this._frontPlate = babylonjs_Maths_math__WEBPACK_IMPORTED_MODULE_2__["BoxBuilder"].CreateBox(this.name + "FrontMesh", {
width: 1.0,
height: 1.0,
depth: 0.08
}, scene);
this._frontPlate.parent = this._backPlate;
this._frontPlate.position.z = -0.08;
this._frontPlate.isPickable = false;
this._frontPlate.setEnabled(false);
this._textPlate = _super.prototype._createNode.call(this, scene);
this._textPlate.parent = this._backPlate;
this._textPlate.position.z = -0.08;
this._textPlate.isPickable = false;
return this._backPlate;
};
HolographicButton.prototype._applyFacade = function (facadeTexture) {
this._plateMaterial.emissiveTexture = facadeTexture;
this._plateMaterial.opacityTexture = facadeTexture;
};
HolographicButton.prototype._createBackMaterial = function (mesh) {
var _this = this;
this._backMaterial = new _materials_fluentMaterial__WEBPACK_IMPORTED_MODULE_3__["FluentMaterial"](this.name + "Back Material", mesh.getScene());
this._backMaterial.renderHoverLight = true;
this._pickedPointObserver = this._host.onPickedPointChangedObservable.add(function (pickedPoint) {
if (pickedPoint) {
_this._backMaterial.hoverPosition = pickedPoint;
_this._backMaterial.hoverColor.a = 1.0;
}
else {
_this._backMaterial.hoverColor.a = 0;
}
});
};
HolographicButton.prototype._createFrontMaterial = function (mesh) {
this._frontMaterial = new _materials_fluentMaterial__WEBPACK_IMPORTED_MODULE_3__["FluentMaterial"](this.name + "Front Material", mesh.getScene());
this._frontMaterial.innerGlowColorIntensity = 0; // No inner glow
this._frontMaterial.alpha = 0.5; // Additive
this._frontMaterial.renderBorders = true;
};
HolographicButton.prototype._createPlateMaterial = function (mesh) {
this._plateMaterial = new babylonjs_Maths_math__WEBPACK_IMPORTED_MODULE_2__["StandardMaterial"](this.name + "Plate Material", mesh.getScene());
this._plateMaterial.specularColor = babylonjs_Maths_math__WEBPACK_IMPORTED_MODULE_2__["Color3"].Black();
};
HolographicButton.prototype._affectMaterial = function (mesh) {
// Back
if (this._shareMaterials) {
if (!this._host._sharedMaterials["backFluentMaterial"]) {
this._createBackMaterial(mesh);
this._host._sharedMaterials["backFluentMaterial"] = this._backMaterial;
}
else {
this._backMaterial = this._host._sharedMaterials["backFluentMaterial"];
}
// Front
if (!this._host._sharedMaterials["frontFluentMaterial"]) {
this._createFrontMaterial(mesh);
this._host._sharedMaterials["frontFluentMaterial"] = this._frontMaterial;
}
else {
this._frontMaterial = this._host._sharedMaterials["frontFluentMaterial"];
}
}
else {
this._createBackMaterial(mesh);
this._createFrontMaterial(mesh);
}
this._createPlateMaterial(mesh);
this._backPlate.material = this._backMaterial;
this._frontPlate.material = this._frontMaterial;
this._textPlate.material = this._plateMaterial;
this._rebuildContent();
};
/**
* Releases all associated resources
*/
HolographicButton.prototype.dispose = function () {
_super.prototype.dispose.call(this); // will dispose main mesh ie. back plate
this._disposeTooltip();
if (!this.shareMaterials) {
this._backMaterial.dispose();
this._frontMaterial.dispose();
this._plateMaterial.dispose();
if (this._pickedPointObserver) {
this._host.onPickedPointChangedObservable.remove(this._pickedPointObserver);
this._pickedPointObserver = null;
}
}
};
return HolographicButton;
}(_button3D__WEBPACK_IMPORTED_MODULE_1__["Button3D"]));
/***/ }),
/***/ "./3D/controls/index.ts":
/*!******************************!*\
!*** ./3D/controls/index.ts ***!
\******************************/
/*! exports provided: AbstractButton3D, Button3D, Container3D, Control3D, CylinderPanel, HolographicButton, MeshButton3D, PlanePanel, ScatterPanel, SpherePanel, StackPanel3D, VolumeBasedPanel */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var _abstractButton3D__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./abstractButton3D */ "./3D/controls/abstractButton3D.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "AbstractButton3D", function() { return _abstractButton3D__WEBPACK_IMPORTED_MODULE_0__["AbstractButton3D"]; });
/* harmony import */ var _button3D__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./button3D */ "./3D/controls/button3D.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Button3D", function() { return _button3D__WEBPACK_IMPORTED_MODULE_1__["Button3D"]; });
/* harmony import */ var _container3D__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./container3D */ "./3D/controls/container3D.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Container3D", function() { return _container3D__WEBPACK_IMPORTED_MODULE_2__["Container3D"]; });
/* harmony import */ var _control3D__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./control3D */ "./3D/controls/control3D.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Control3D", function() { return _control3D__WEBPACK_IMPORTED_MODULE_3__["Control3D"]; });
/* harmony import */ var _cylinderPanel__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./cylinderPanel */ "./3D/controls/cylinderPanel.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "CylinderPanel", function() { return _cylinderPanel__WEBPACK_IMPORTED_MODULE_4__["CylinderPanel"]; });
/* harmony import */ var _holographicButton__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./holographicButton */ "./3D/controls/holographicButton.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "HolographicButton", function() { return _holographicButton__WEBPACK_IMPORTED_MODULE_5__["HolographicButton"]; });
/* harmony import */ var _meshButton3D__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ./meshButton3D */ "./3D/controls/meshButton3D.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "MeshButton3D", function() { return _meshButton3D__WEBPACK_IMPORTED_MODULE_6__["MeshButton3D"]; });
/* harmony import */ var _planePanel__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ./planePanel */ "./3D/controls/planePanel.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "PlanePanel", function() { return _planePanel__WEBPACK_IMPORTED_MODULE_7__["PlanePanel"]; });
/* harmony import */ var _scatterPanel__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ./scatterPanel */ "./3D/controls/scatterPanel.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ScatterPanel", function() { return _scatterPanel__WEBPACK_IMPORTED_MODULE_8__["ScatterPanel"]; });
/* harmony import */ var _spherePanel__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ./spherePanel */ "./3D/controls/spherePanel.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "SpherePanel", function() { return _spherePanel__WEBPACK_IMPORTED_MODULE_9__["SpherePanel"]; });
/* harmony import */ var _stackPanel3D__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! ./stackPanel3D */ "./3D/controls/stackPanel3D.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "StackPanel3D", function() { return _stackPanel3D__WEBPACK_IMPORTED_MODULE_10__["StackPanel3D"]; });
/* harmony import */ var _volumeBasedPanel__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(/*! ./volumeBasedPanel */ "./3D/controls/volumeBasedPanel.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "VolumeBasedPanel", function() { return _volumeBasedPanel__WEBPACK_IMPORTED_MODULE_11__["VolumeBasedPanel"]; });
/***/ }),
/***/ "./3D/controls/meshButton3D.ts":
/*!*************************************!*\
!*** ./3D/controls/meshButton3D.ts ***!
\*************************************/
/*! exports provided: MeshButton3D */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "MeshButton3D", function() { return MeshButton3D; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../../node_modules/tslib/tslib.es6.js");
/* harmony import */ var _button3D__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./button3D */ "./3D/controls/button3D.ts");
/**
* Class used to create an interactable object. It's a 3D button using a mesh coming from the current scene
*/
var MeshButton3D = /** @class */ (function (_super) {
tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](MeshButton3D, _super);
/**
* Creates a new 3D button based on a mesh
* @param mesh mesh to become a 3D button
* @param name defines the control name
*/
function MeshButton3D(mesh, name) {
var _this = _super.call(this, name) || this;
_this._currentMesh = mesh;
/**
* Provides a default behavior on hover/out & up/down
* Override those function to create your own desired behavior specific to your mesh
*/
_this.pointerEnterAnimation = function () {
if (!_this.mesh) {
return;
}
_this.mesh.scaling.scaleInPlace(1.1);
};
_this.pointerOutAnimation = function () {
if (!_this.mesh) {
return;
}
_this.mesh.scaling.scaleInPlace(1.0 / 1.1);
};
_this.pointerDownAnimation = function () {
if (!_this.mesh) {
return;
}
_this.mesh.scaling.scaleInPlace(0.95);
};
_this.pointerUpAnimation = function () {
if (!_this.mesh) {
return;
}
_this.mesh.scaling.scaleInPlace(1.0 / 0.95);
};
return _this;
}
MeshButton3D.prototype._getTypeName = function () {
return "MeshButton3D";
};
// Mesh association
MeshButton3D.prototype._createNode = function (scene) {
var _this = this;
this._currentMesh.getChildMeshes().forEach(function (mesh) {
mesh.metadata = _this;
});
return this._currentMesh;
};
MeshButton3D.prototype._affectMaterial = function (mesh) {
};
return MeshButton3D;
}(_button3D__WEBPACK_IMPORTED_MODULE_1__["Button3D"]));
/***/ }),
/***/ "./3D/controls/planePanel.ts":
/*!***********************************!*\
!*** ./3D/controls/planePanel.ts ***!
\***********************************/
/*! exports provided: PlanePanel */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "PlanePanel", function() { return PlanePanel; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../../node_modules/tslib/tslib.es6.js");
/* harmony import */ var babylonjs_Maths_math__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! babylonjs/Maths/math */ "babylonjs/Misc/observable");
/* harmony import */ var babylonjs_Maths_math__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(babylonjs_Maths_math__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var _container3D__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./container3D */ "./3D/controls/container3D.ts");
/* harmony import */ var _volumeBasedPanel__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./volumeBasedPanel */ "./3D/controls/volumeBasedPanel.ts");
/**
* Class used to create a container panel deployed on the surface of a plane
*/
var PlanePanel = /** @class */ (function (_super) {
tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](PlanePanel, _super);
function PlanePanel() {
return _super !== null && _super.apply(this, arguments) || this;
}
PlanePanel.prototype._mapGridNode = function (control, nodePosition) {
var mesh = control.mesh;
if (!mesh) {
return;
}
control.position = nodePosition.clone();
var target = babylonjs_Maths_math__WEBPACK_IMPORTED_MODULE_1__["Tmp"].Vector3[0];
target.copyFrom(nodePosition);
switch (this.orientation) {
case _container3D__WEBPACK_IMPORTED_MODULE_2__["Container3D"].FACEORIGIN_ORIENTATION:
case _container3D__WEBPACK_IMPORTED_MODULE_2__["Container3D"].FACEFORWARD_ORIENTATION:
target.addInPlace(new babylonjs_Maths_math__WEBPACK_IMPORTED_MODULE_1__["Vector3"](0, 0, 1));
mesh.lookAt(target);
break;
case _container3D__WEBPACK_IMPORTED_MODULE_2__["Container3D"].FACEFORWARDREVERSED_ORIENTATION:
case _container3D__WEBPACK_IMPORTED_MODULE_2__["Container3D"].FACEORIGINREVERSED_ORIENTATION:
target.addInPlace(new babylonjs_Maths_math__WEBPACK_IMPORTED_MODULE_1__["Vector3"](0, 0, -1));
mesh.lookAt(target);
break;
}
};
return PlanePanel;
}(_volumeBasedPanel__WEBPACK_IMPORTED_MODULE_3__["VolumeBasedPanel"]));
/***/ }),
/***/ "./3D/controls/scatterPanel.ts":
/*!*************************************!*\
!*** ./3D/controls/scatterPanel.ts ***!
\*************************************/
/*! exports provided: ScatterPanel */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ScatterPanel", function() { return ScatterPanel; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../../node_modules/tslib/tslib.es6.js");
/* harmony import */ var babylonjs_Misc_tools__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! babylonjs/Misc/tools */ "babylonjs/Misc/observable");
/* harmony import */ var babylonjs_Misc_tools__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(babylonjs_Misc_tools__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var _volumeBasedPanel__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./volumeBasedPanel */ "./3D/controls/volumeBasedPanel.ts");
/* harmony import */ var _container3D__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./container3D */ "./3D/controls/container3D.ts");
/**
* Class used to create a container panel where items get randomized planar mapping
*/
var ScatterPanel = /** @class */ (function (_super) {
tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](ScatterPanel, _super);
function ScatterPanel() {
var _this = _super !== null && _super.apply(this, arguments) || this;
_this._iteration = 100.0;
return _this;
}
Object.defineProperty(ScatterPanel.prototype, "iteration", {
/**
* Gets or sets the number of iteration to use to scatter the controls (100 by default)
*/
get: function () {
return this._iteration;
},
set: function (value) {
var _this = this;
if (this._iteration === value) {
return;
}
this._iteration = value;
babylonjs_Misc_tools__WEBPACK_IMPORTED_MODULE_1__["Tools"].SetImmediate(function () {
_this._arrangeChildren();
});
},
enumerable: true,
configurable: true
});
ScatterPanel.prototype._mapGridNode = function (control, nodePosition) {
var mesh = control.mesh;
var newPos = this._scatterMapping(nodePosition);
if (!mesh) {
return;
}
switch (this.orientation) {
case _container3D__WEBPACK_IMPORTED_MODULE_3__["Container3D"].FACEORIGIN_ORIENTATION:
case _container3D__WEBPACK_IMPORTED_MODULE_3__["Container3D"].FACEFORWARD_ORIENTATION:
mesh.lookAt(new babylonjs_Misc_tools__WEBPACK_IMPORTED_MODULE_1__["Vector3"](0, 0, 1));
break;
case _container3D__WEBPACK_IMPORTED_MODULE_3__["Container3D"].FACEFORWARDREVERSED_ORIENTATION:
case _container3D__WEBPACK_IMPORTED_MODULE_3__["Container3D"].FACEORIGINREVERSED_ORIENTATION:
mesh.lookAt(new babylonjs_Misc_tools__WEBPACK_IMPORTED_MODULE_1__["Vector3"](0, 0, -1));
break;
}
control.position = newPos;
};
ScatterPanel.prototype._scatterMapping = function (source) {
source.x = (1.0 - Math.random() * 2.0) * this._cellWidth;
source.y = (1.0 - Math.random() * 2.0) * this._cellHeight;
return source;
};
ScatterPanel.prototype._finalProcessing = function () {
var meshes = [];
for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
var child = _a[_i];
if (!child.mesh) {
continue;
}
meshes.push(child.mesh);
}
for (var count = 0; count < this._iteration; count++) {
meshes.sort(function (a, b) {
var distance1 = a.position.lengthSquared();
var distance2 = b.position.lengthSquared();
if (distance1 < distance2) {
return 1;
}
else if (distance1 > distance2) {
return -1;
}
return 0;
});
var radiusPaddingSquared = Math.pow(this.margin, 2.0);
var cellSize = Math.max(this._cellWidth, this._cellHeight);
var difference2D = babylonjs_Misc_tools__WEBPACK_IMPORTED_MODULE_1__["Tmp"].Vector2[0];
var difference = babylonjs_Misc_tools__WEBPACK_IMPORTED_MODULE_1__["Tmp"].Vector3[0];
for (var i = 0; i < meshes.length - 1; i++) {
for (var j = i + 1; j < meshes.length; j++) {
if (i != j) {
meshes[j].position.subtractToRef(meshes[i].position, difference);
// Ignore Z axis
difference2D.x = difference.x;
difference2D.y = difference.y;
var combinedRadius = cellSize;
var distance = difference2D.lengthSquared() - radiusPaddingSquared;
var minSeparation = Math.min(distance, radiusPaddingSquared);
distance -= minSeparation;
if (distance < (Math.pow(combinedRadius, 2.0))) {
difference2D.normalize();
difference.scaleInPlace((combinedRadius - Math.sqrt(distance)) * 0.5);
meshes[j].position.addInPlace(difference);
meshes[i].position.subtractInPlace(difference);
}
}
}
}
}
};
return ScatterPanel;
}(_volumeBasedPanel__WEBPACK_IMPORTED_MODULE_2__["VolumeBasedPanel"]));
/***/ }),
/***/ "./3D/controls/spherePanel.ts":
/*!************************************!*\
!*** ./3D/controls/spherePanel.ts ***!
\************************************/
/*! exports provided: SpherePanel */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "SpherePanel", function() { return SpherePanel; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../../node_modules/tslib/tslib.es6.js");
/* harmony import */ var babylonjs_Misc_tools__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! babylonjs/Misc/tools */ "babylonjs/Misc/observable");
/* harmony import */ var babylonjs_Misc_tools__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(babylonjs_Misc_tools__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var _volumeBasedPanel__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./volumeBasedPanel */ "./3D/controls/volumeBasedPanel.ts");
/* harmony import */ var _container3D__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./container3D */ "./3D/controls/container3D.ts");
/**
* Class used to create a container panel deployed on the surface of a sphere
*/
var SpherePanel = /** @class */ (function (_super) {
tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](SpherePanel, _super);
function SpherePanel() {
var _this = _super !== null && _super.apply(this, arguments) || this;
_this._radius = 5.0;
return _this;
}
Object.defineProperty(SpherePanel.prototype, "radius", {
/**
* Gets or sets the radius of the sphere where to project controls (5 by default)
*/
get: function () {
return this._radius;
},
set: function (value) {
var _this = this;
if (this._radius === value) {
return;
}
this._radius = value;
babylonjs_Misc_tools__WEBPACK_IMPORTED_MODULE_1__["Tools"].SetImmediate(function () {
_this._arrangeChildren();
});
},
enumerable: true,
configurable: true
});
SpherePanel.prototype._mapGridNode = function (control, nodePosition) {
var mesh = control.mesh;
if (!mesh) {
return;
}
var newPos = this._sphericalMapping(nodePosition);
control.position = newPos;
switch (this.orientation) {
case _container3D__WEBPACK_IMPORTED_MODULE_3__["Container3D"].FACEORIGIN_ORIENTATION:
mesh.lookAt(new babylonjs_Misc_tools__WEBPACK_IMPORTED_MODULE_1__["Vector3"](2 * newPos.x, 2 * newPos.y, 2 * newPos.z));
break;
case _container3D__WEBPACK_IMPORTED_MODULE_3__["Container3D"].FACEORIGINREVERSED_ORIENTATION:
mesh.lookAt(new babylonjs_Misc_tools__WEBPACK_IMPORTED_MODULE_1__["Vector3"](-newPos.x, -newPos.y, -newPos.z));
break;
case _container3D__WEBPACK_IMPORTED_MODULE_3__["Container3D"].FACEFORWARD_ORIENTATION:
break;
case _container3D__WEBPACK_IMPORTED_MODULE_3__["Container3D"].FACEFORWARDREVERSED_ORIENTATION:
mesh.rotate(babylonjs_Misc_tools__WEBPACK_IMPORTED_MODULE_1__["Axis"].Y, Math.PI, babylonjs_Misc_tools__WEBPACK_IMPORTED_MODULE_1__["Space"].LOCAL);
break;
}
};
SpherePanel.prototype._sphericalMapping = function (source) {
var newPos = new babylonjs_Misc_tools__WEBPACK_IMPORTED_MODULE_1__["Vector3"](0, 0, this._radius);
var xAngle = (source.y / this._radius);
var yAngle = -(source.x / this._radius);
babylonjs_Misc_tools__WEBPACK_IMPORTED_MODULE_1__["Matrix"].RotationYawPitchRollToRef(yAngle, xAngle, 0, babylonjs_Misc_tools__WEBPACK_IMPORTED_MODULE_1__["Tmp"].Matrix[0]);
return babylonjs_Misc_tools__WEBPACK_IMPORTED_MODULE_1__["Vector3"].TransformNormal(newPos, babylonjs_Misc_tools__WEBPACK_IMPORTED_MODULE_1__["Tmp"].Matrix[0]);
};
return SpherePanel;
}(_volumeBasedPanel__WEBPACK_IMPORTED_MODULE_2__["VolumeBasedPanel"]));
/***/ }),
/***/ "./3D/controls/stackPanel3D.ts":
/*!*************************************!*\
!*** ./3D/controls/stackPanel3D.ts ***!
\*************************************/
/*! exports provided: StackPanel3D */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "StackPanel3D", function() { return StackPanel3D; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../../node_modules/tslib/tslib.es6.js");
/* harmony import */ var babylonjs_Misc_tools__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! babylonjs/Misc/tools */ "babylonjs/Misc/observable");
/* harmony import */ var babylonjs_Misc_tools__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(babylonjs_Misc_tools__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var _container3D__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./container3D */ "./3D/controls/container3D.ts");
/**
* Class used to create a stack panel in 3D on XY plane
*/
var StackPanel3D = /** @class */ (function (_super) {
tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](StackPanel3D, _super);
/**
* Creates new StackPanel
* @param isVertical
*/
function StackPanel3D(isVertical) {
if (isVertical === void 0) { isVertical = false; }
var _this = _super.call(this) || this;
_this._isVertical = false;
/**
* Gets or sets the distance between elements
*/
_this.margin = 0.1;
_this._isVertical = isVertical;
return _this;
}
Object.defineProperty(StackPanel3D.prototype, "isVertical", {
/**
* Gets or sets a boolean indicating if the stack panel is vertical or horizontal (horizontal by default)
*/
get: function () {
return this._isVertical;
},
set: function (value) {
var _this = this;
if (this._isVertical === value) {
return;
}
this._isVertical = value;
babylonjs_Misc_tools__WEBPACK_IMPORTED_MODULE_1__["Tools"].SetImmediate(function () {
_this._arrangeChildren();
});
},
enumerable: true,
configurable: true
});
StackPanel3D.prototype._arrangeChildren = function () {
var width = 0;
var height = 0;
var controlCount = 0;
var extendSizes = [];
var currentInverseWorld = babylonjs_Misc_tools__WEBPACK_IMPORTED_MODULE_1__["Matrix"].Invert(this.node.computeWorldMatrix(true));
// Measure
for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
var child = _a[_i];
if (!child.mesh) {
continue;
}
controlCount++;
child.mesh.computeWorldMatrix(true);
child.mesh.getWorldMatrix().multiplyToRef(currentInverseWorld, babylonjs_Misc_tools__WEBPACK_IMPORTED_MODULE_1__["Tmp"].Matrix[0]);
var boundingBox = child.mesh.getBoundingInfo().boundingBox;
var extendSize = babylonjs_Misc_tools__WEBPACK_IMPORTED_MODULE_1__["Vector3"].TransformNormal(boundingBox.extendSize, babylonjs_Misc_tools__WEBPACK_IMPORTED_MODULE_1__["Tmp"].Matrix[0]);
extendSizes.push(extendSize);
if (this._isVertical) {
height += extendSize.y;
}
else {
width += extendSize.x;
}
}
if (this._isVertical) {
height += (controlCount - 1) * this.margin / 2;
}
else {
width += (controlCount - 1) * this.margin / 2;
}
// Arrange
var offset;
if (this._isVertical) {
offset = -height;
}
else {
offset = -width;
}
var index = 0;
for (var _b = 0, _c = this._children; _b < _c.length; _b++) {
var child = _c[_b];
if (!child.mesh) {
continue;
}
controlCount--;
var extendSize = extendSizes[index++];
if (this._isVertical) {
child.position.y = offset + extendSize.y;
child.position.x = 0;
offset += extendSize.y * 2;
}
else {
child.position.x = offset + extendSize.x;
child.position.y = 0;
offset += extendSize.x * 2;
}
offset += (controlCount > 0 ? this.margin : 0);
}
};
return StackPanel3D;
}(_container3D__WEBPACK_IMPORTED_MODULE_2__["Container3D"]));
/***/ }),
/***/ "./3D/controls/volumeBasedPanel.ts":
/*!*****************************************!*\
!*** ./3D/controls/volumeBasedPanel.ts ***!
\*****************************************/
/*! exports provided: VolumeBasedPanel */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "VolumeBasedPanel", function() { return VolumeBasedPanel; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../../node_modules/tslib/tslib.es6.js");
/* harmony import */ var babylonjs_Misc_tools__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! babylonjs/Misc/tools */ "babylonjs/Misc/observable");
/* harmony import */ var babylonjs_Misc_tools__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(babylonjs_Misc_tools__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var _container3D__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./container3D */ "./3D/controls/container3D.ts");
/**
* Abstract class used to create a container panel deployed on the surface of a volume
*/
var VolumeBasedPanel = /** @class */ (function (_super) {
tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](VolumeBasedPanel, _super);
/**
* Creates new VolumeBasedPanel
*/
function VolumeBasedPanel() {
var _this = _super.call(this) || this;
_this._columns = 10;
_this._rows = 0;
_this._rowThenColum = true;
_this._orientation = _container3D__WEBPACK_IMPORTED_MODULE_2__["Container3D"].FACEORIGIN_ORIENTATION;
/**
* Gets or sets the distance between elements
*/
_this.margin = 0;
return _this;
}
Object.defineProperty(VolumeBasedPanel.prototype, "orientation", {
/**
* Gets or sets the orientation to apply to all controls (BABYLON.Container3D.FaceOriginReversedOrientation by default)
* | Value | Type | Description |
* | ----- | ----------------------------------- | ----------- |
* | 0 | UNSET_ORIENTATION | Control rotation will remain unchanged |
* | 1 | FACEORIGIN_ORIENTATION | Control will rotate to make it look at sphere central axis |
* | 2 | FACEORIGINREVERSED_ORIENTATION | Control will rotate to make it look back at sphere central axis |
* | 3 | FACEFORWARD_ORIENTATION | Control will rotate to look at z axis (0, 0, 1) |
* | 4 | FACEFORWARDREVERSED_ORIENTATION | Control will rotate to look at negative z axis (0, 0, -1) |
*/
get: function () {
return this._orientation;
},
set: function (value) {
var _this = this;
if (this._orientation === value) {
return;
}
this._orientation = value;
babylonjs_Misc_tools__WEBPACK_IMPORTED_MODULE_1__["Tools"].SetImmediate(function () {
_this._arrangeChildren();
});
},
enumerable: true,
configurable: true
});
Object.defineProperty(VolumeBasedPanel.prototype, "columns", {
/**
* Gets or sets the number of columns requested (10 by default).
* The panel will automatically compute the number of rows based on number of child controls.
*/
get: function () {
return this._columns;
},
set: function (value) {
var _this = this;
if (this._columns === value) {
return;
}
this._columns = value;
this._rowThenColum = true;
babylonjs_Misc_tools__WEBPACK_IMPORTED_MODULE_1__["Tools"].SetImmediate(function () {
_this._arrangeChildren();
});
},
enumerable: true,
configurable: true
});
Object.defineProperty(VolumeBasedPanel.prototype, "rows", {
/**
* Gets or sets a the number of rows requested.
* The panel will automatically compute the number of columns based on number of child controls.
*/
get: function () {
return this._rows;
},
set: function (value) {
var _this = this;
if (this._rows === value) {
return;
}
this._rows = value;
this._rowThenColum = false;
babylonjs_Misc_tools__WEBPACK_IMPORTED_MODULE_1__["Tools"].SetImmediate(function () {
_this._arrangeChildren();
});
},
enumerable: true,
configurable: true
});
VolumeBasedPanel.prototype._arrangeChildren = function () {
this._cellWidth = 0;
this._cellHeight = 0;
var rows = 0;
var columns = 0;
var controlCount = 0;
var currentInverseWorld = babylonjs_Misc_tools__WEBPACK_IMPORTED_MODULE_1__["Matrix"].Invert(this.node.computeWorldMatrix(true));
// Measure
for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
var child = _a[_i];
if (!child.mesh) {
continue;
}
controlCount++;
child.mesh.computeWorldMatrix(true);
// child.mesh.getWorldMatrix().multiplyToRef(currentInverseWorld, Tmp.Matrix[0]);
var boundingBox = child.mesh.getHierarchyBoundingVectors();
var extendSize = babylonjs_Misc_tools__WEBPACK_IMPORTED_MODULE_1__["Tmp"].Vector3[0];
var diff = babylonjs_Misc_tools__WEBPACK_IMPORTED_MODULE_1__["Tmp"].Vector3[1];
boundingBox.max.subtractToRef(boundingBox.min, diff);
diff.scaleInPlace(0.5);
babylonjs_Misc_tools__WEBPACK_IMPORTED_MODULE_1__["Vector3"].TransformNormalToRef(diff, currentInverseWorld, extendSize);
this._cellWidth = Math.max(this._cellWidth, extendSize.x * 2);
this._cellHeight = Math.max(this._cellHeight, extendSize.y * 2);
}
this._cellWidth += this.margin * 2;
this._cellHeight += this.margin * 2;
// Arrange
if (this._rowThenColum) {
columns = this._columns;
rows = Math.ceil(controlCount / this._columns);
}
else {
rows = this._rows;
columns = Math.ceil(controlCount / this._rows);
}
var startOffsetX = (columns * 0.5) * this._cellWidth;
var startOffsetY = (rows * 0.5) * this._cellHeight;
var nodeGrid = [];
var cellCounter = 0;
if (this._rowThenColum) {
for (var r = 0; r < rows; r++) {
for (var c = 0; c < columns; c++) {
nodeGrid.push(new babylonjs_Misc_tools__WEBPACK_IMPORTED_MODULE_1__["Vector3"]((c * this._cellWidth) - startOffsetX + this._cellWidth / 2, (r * this._cellHeight) - startOffsetY + this._cellHeight / 2, 0));
cellCounter++;
if (cellCounter > controlCount) {
break;
}
}
}
}
else {
for (var c = 0; c < columns; c++) {
for (var r = 0; r < rows; r++) {
nodeGrid.push(new babylonjs_Misc_tools__WEBPACK_IMPORTED_MODULE_1__["Vector3"]((c * this._cellWidth) - startOffsetX + this._cellWidth / 2, (r * this._cellHeight) - startOffsetY + this._cellHeight / 2, 0));
cellCounter++;
if (cellCounter > controlCount) {
break;
}
}
}
}
cellCounter = 0;
for (var _b = 0, _c = this._children; _b < _c.length; _b++) {
var child = _c[_b];
if (!child.mesh) {
continue;
}
this._mapGridNode(child, nodeGrid[cellCounter]);
cellCounter++;
}
this._finalProcessing();
};
/** Child classes can implement this function to provide additional processing */
VolumeBasedPanel.prototype._finalProcessing = function () {
};
return VolumeBasedPanel;
}(_container3D__WEBPACK_IMPORTED_MODULE_2__["Container3D"]));
/***/ }),
/***/ "./3D/gui3DManager.ts":
/*!****************************!*\
!*** ./3D/gui3DManager.ts ***!
\****************************/
/*! exports provided: GUI3DManager */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "GUI3DManager", function() { return GUI3DManager; });
/* harmony import */ var babylonjs_Misc_observable__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! babylonjs/Misc/observable */ "babylonjs/Misc/observable");
/* harmony import */ var babylonjs_Misc_observable__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(babylonjs_Misc_observable__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _controls_container3D__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./controls/container3D */ "./3D/controls/container3D.ts");
/**
* Class used to manage 3D user interface
* @see http://doc.babylonjs.com/how_to/gui3d
*/
var GUI3DManager = /** @class */ (function () {
/**
* Creates a new GUI3DManager
* @param scene
*/
function GUI3DManager(scene) {
var _this = this;
/** @hidden */
this._lastControlOver = {};
/** @hidden */
this._lastControlDown = {};
/**
* Observable raised when the point picked by the pointer events changed
*/
this.onPickedPointChangedObservable = new babylonjs_Misc_observable__WEBPACK_IMPORTED_MODULE_0__["Observable"]();
// Shared resources
/** @hidden */
this._sharedMaterials = {};
this._scene = scene || babylonjs_Misc_observable__WEBPACK_IMPORTED_MODULE_0__["EngineStore"].LastCreatedScene;
this._sceneDisposeObserver = this._scene.onDisposeObservable.add(function () {
_this._sceneDisposeObserver = null;
_this._utilityLayer = null;
_this.dispose();
});
this._utilityLayer = new babylonjs_Misc_observable__WEBPACK_IMPORTED_MODULE_0__["UtilityLayerRenderer"](this._scene);
this._utilityLayer.onlyCheckPointerDownEvents = false;
this._utilityLayer.pickUtilitySceneFirst = false;
this._utilityLayer.mainSceneTrackerPredicate = function (mesh) {
return mesh && mesh.metadata && mesh.metadata._node;
};
// Root
this._rootContainer = new _controls_container3D__WEBPACK_IMPORTED_MODULE_1__["Container3D"]("RootContainer");
this._rootContainer._host = this;
var utilityLayerScene = this._utilityLayer.utilityLayerScene;
// Events
this._pointerOutObserver = this._utilityLayer.onPointerOutObservable.add(function (pointerId) {
_this._handlePointerOut(pointerId, true);
});
this._pointerObserver = utilityLayerScene.onPointerObservable.add(function (pi, state) {
_this._doPicking(pi);
});
// Scene
this._utilityLayer.utilityLayerScene.autoClear = false;
this._utilityLayer.utilityLayerScene.autoClearDepthAndStencil = false;
new babylonjs_Misc_observable__WEBPACK_IMPORTED_MODULE_0__["HemisphericLight"]("hemi", babylonjs_Misc_observable__WEBPACK_IMPORTED_MODULE_0__["Vector3"].Up(), this._utilityLayer.utilityLayerScene);
}
Object.defineProperty(GUI3DManager.prototype, "scene", {
/** Gets the hosting scene */
get: function () {
return this._scene;
},
enumerable: true,
configurable: true
});
Object.defineProperty(GUI3DManager.prototype, "utilityLayer", {
/** Gets associated utility layer */
get: function () {
return this._utilityLayer;
},
enumerable: true,
configurable: true
});
GUI3DManager.prototype._handlePointerOut = function (pointerId, isPointerUp) {
var previousControlOver = this._lastControlOver[pointerId];
if (previousControlOver) {
previousControlOver._onPointerOut(previousControlOver);
delete this._lastControlOver[pointerId];
}
if (isPointerUp) {
if (this._lastControlDown[pointerId]) {
this._lastControlDown[pointerId].forcePointerUp();
delete this._lastControlDown[pointerId];
}
}
this.onPickedPointChangedObservable.notifyObservers(null);
};
GUI3DManager.prototype._doPicking = function (pi) {
if (!this._utilityLayer || !this._utilityLayer.utilityLayerScene.activeCamera) {
return false;
}
var pointerEvent = (pi.event);
var pointerId = pointerEvent.pointerId || 0;
var buttonIndex = pointerEvent.button;
var pickingInfo = pi.pickInfo;
if (!pickingInfo || !pickingInfo.hit) {
this._handlePointerOut(pointerId, pi.type === babylonjs_Misc_observable__WEBPACK_IMPORTED_MODULE_0__["PointerEventTypes"].POINTERUP);
return false;
}
var control = (pickingInfo.pickedMesh.metadata);
if (pickingInfo.pickedPoint) {
this.onPickedPointChangedObservable.notifyObservers(pickingInfo.pickedPoint);
}
if (!control._processObservables(pi.type, pickingInfo.pickedPoint, pointerId, buttonIndex)) {
if (pi.type === babylonjs_Misc_observable__WEBPACK_IMPORTED_MODULE_0__["PointerEventTypes"].POINTERMOVE) {
if (this._lastControlOver[pointerId]) {
this._lastControlOver[pointerId]._onPointerOut(this._lastControlOver[pointerId]);
}
delete this._lastControlOver[pointerId];
}
}
if (pi.type === babylonjs_Misc_observable__WEBPACK_IMPORTED_MODULE_0__["PointerEventTypes"].POINTERUP) {
if (this._lastControlDown[pointerEvent.pointerId]) {
this._lastControlDown[pointerEvent.pointerId].forcePointerUp();
delete this._lastControlDown[pointerEvent.pointerId];
}
if (pointerEvent.pointerType === "touch") {
this._handlePointerOut(pointerId, false);
}
}
return true;
};
Object.defineProperty(GUI3DManager.prototype, "rootContainer", {
/**
* Gets the root container
*/
get: function () {
return this._rootContainer;
},
enumerable: true,
configurable: true
});
/**
* Gets a boolean indicating if the given control is in the root child list
* @param control defines the control to check
* @returns true if the control is in the root child list
*/
GUI3DManager.prototype.containsControl = function (control) {
return this._rootContainer.containsControl(control);
};
/**
* Adds a control to the root child list
* @param control defines the control to add
* @returns the current manager
*/
GUI3DManager.prototype.addControl = function (control) {
this._rootContainer.addControl(control);
return this;
};
/**
* Removes a control from the root child list
* @param control defines the control to remove
* @returns the current container
*/
GUI3DManager.prototype.removeControl = function (control) {
this._rootContainer.removeControl(control);
return this;
};
/**
* Releases all associated resources
*/
GUI3DManager.prototype.dispose = function () {
this._rootContainer.dispose();
for (var materialName in this._sharedMaterials) {
if (!this._sharedMaterials.hasOwnProperty(materialName)) {
continue;
}
this._sharedMaterials[materialName].dispose();
}
this._sharedMaterials = {};
if (this._pointerOutObserver && this._utilityLayer) {
this._utilityLayer.onPointerOutObservable.remove(this._pointerOutObserver);
this._pointerOutObserver = null;
}
this.onPickedPointChangedObservable.clear();
var utilityLayerScene = this._utilityLayer ? this._utilityLayer.utilityLayerScene : null;
if (utilityLayerScene) {
if (this._pointerObserver) {
utilityLayerScene.onPointerObservable.remove(this._pointerObserver);
this._pointerObserver = null;
}
}
if (this._scene) {
if (this._sceneDisposeObserver) {
this._scene.onDisposeObservable.remove(this._sceneDisposeObserver);
this._sceneDisposeObserver = null;
}
}
if (this._utilityLayer) {
this._utilityLayer.dispose();
}
};
return GUI3DManager;
}());
/***/ }),
/***/ "./3D/index.ts":
/*!*********************!*\
!*** ./3D/index.ts ***!
\*********************/
/*! exports provided: GUI3DManager, Vector3WithInfo, AbstractButton3D, Button3D, Container3D, Control3D, CylinderPanel, HolographicButton, MeshButton3D, PlanePanel, ScatterPanel, SpherePanel, StackPanel3D, VolumeBasedPanel, FluentMaterialDefines, FluentMaterial */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var _controls__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./controls */ "./3D/controls/index.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "AbstractButton3D", function() { return _controls__WEBPACK_IMPORTED_MODULE_0__["AbstractButton3D"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Button3D", function() { return _controls__WEBPACK_IMPORTED_MODULE_0__["Button3D"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Container3D", function() { return _controls__WEBPACK_IMPORTED_MODULE_0__["Container3D"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Control3D", function() { return _controls__WEBPACK_IMPORTED_MODULE_0__["Control3D"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "CylinderPanel", function() { return _controls__WEBPACK_IMPORTED_MODULE_0__["CylinderPanel"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "HolographicButton", function() { return _controls__WEBPACK_IMPORTED_MODULE_0__["HolographicButton"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "MeshButton3D", function() { return _controls__WEBPACK_IMPORTED_MODULE_0__["MeshButton3D"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "PlanePanel", function() { return _controls__WEBPACK_IMPORTED_MODULE_0__["PlanePanel"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ScatterPanel", function() { return _controls__WEBPACK_IMPORTED_MODULE_0__["ScatterPanel"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "SpherePanel", function() { return _controls__WEBPACK_IMPORTED_MODULE_0__["SpherePanel"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "StackPanel3D", function() { return _controls__WEBPACK_IMPORTED_MODULE_0__["StackPanel3D"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "VolumeBasedPanel", function() { return _controls__WEBPACK_IMPORTED_MODULE_0__["VolumeBasedPanel"]; });
/* harmony import */ var _materials__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./materials */ "./3D/materials/index.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "FluentMaterialDefines", function() { return _materials__WEBPACK_IMPORTED_MODULE_1__["FluentMaterialDefines"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "FluentMaterial", function() { return _materials__WEBPACK_IMPORTED_MODULE_1__["FluentMaterial"]; });
/* harmony import */ var _gui3DManager__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./gui3DManager */ "./3D/gui3DManager.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "GUI3DManager", function() { return _gui3DManager__WEBPACK_IMPORTED_MODULE_2__["GUI3DManager"]; });
/* harmony import */ var _vector3WithInfo__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./vector3WithInfo */ "./3D/vector3WithInfo.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Vector3WithInfo", function() { return _vector3WithInfo__WEBPACK_IMPORTED_MODULE_3__["Vector3WithInfo"]; });
/***/ }),
/***/ "./3D/materials/fluentMaterial.ts":
/*!****************************************!*\
!*** ./3D/materials/fluentMaterial.ts ***!
\****************************************/
/*! exports provided: FluentMaterialDefines, FluentMaterial */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "FluentMaterialDefines", function() { return FluentMaterialDefines; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "FluentMaterial", function() { return FluentMaterial; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../../node_modules/tslib/tslib.es6.js");
/* harmony import */ var babylonjs_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! babylonjs/Misc/decorators */ "babylonjs/Misc/observable");
/* harmony import */ var babylonjs_Misc_decorators__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(babylonjs_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var _shaders_fluent_vertex__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./shaders/fluent.vertex */ "./3D/materials/shaders/fluent.vertex.ts");
/* harmony import */ var _shaders_fluent_fragment__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./shaders/fluent.fragment */ "./3D/materials/shaders/fluent.fragment.ts");
/** @hidden */
var FluentMaterialDefines = /** @class */ (function (_super) {
tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](FluentMaterialDefines, _super);
function FluentMaterialDefines() {
var _this = _super.call(this) || this;
_this.INNERGLOW = false;
_this.BORDER = false;
_this.HOVERLIGHT = false;
_this.TEXTURE = false;
_this.rebuild();
return _this;
}
return FluentMaterialDefines;
}(babylonjs_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["MaterialDefines"]));
/**
* Class used to render controls with fluent desgin
*/
var FluentMaterial = /** @class */ (function (_super) {
tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](FluentMaterial, _super);
/**
* Creates a new Fluent material
* @param name defines the name of the material
* @param scene defines the hosting scene
*/
function FluentMaterial(name, scene) {
var _this = _super.call(this, name, scene) || this;
/**
* Gets or sets inner glow intensity. A value of 0 means no glow (default is 0.5)
*/
_this.innerGlowColorIntensity = 0.5;
/**
* Gets or sets the inner glow color (white by default)
*/
_this.innerGlowColor = new babylonjs_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["Color3"](1.0, 1.0, 1.0);
/**
* Gets or sets alpha value (default is 1.0)
*/
_this.alpha = 1.0;
/**
* Gets or sets the albedo color (Default is Color3(0.3, 0.35, 0.4))
*/
_this.albedoColor = new babylonjs_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["Color3"](0.3, 0.35, 0.4);
/**
* Gets or sets a boolean indicating if borders must be rendered (default is false)
*/
_this.renderBorders = false;
/**
* Gets or sets border width (default is 0.5)
*/
_this.borderWidth = 0.5;
/**
* Gets or sets a value indicating the smoothing value applied to border edges (0.02 by default)
*/
_this.edgeSmoothingValue = 0.02;
/**
* Gets or sets the minimum value that can be applied to border width (default is 0.1)
*/
_this.borderMinValue = 0.1;
/**
* Gets or sets a boolean indicating if hover light must be rendered (default is false)
*/
_this.renderHoverLight = false;
/**
* Gets or sets the radius used to render the hover light (default is 1.0)
*/
_this.hoverRadius = 1.0;
/**
* Gets or sets the color used to render the hover light (default is Color4(0.3, 0.3, 0.3, 1.0))
*/
_this.hoverColor = new babylonjs_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["Color4"](0.3, 0.3, 0.3, 1.0);
/**
* Gets or sets the hover light position in world space (default is Vector3.Zero())
*/
_this.hoverPosition = babylonjs_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["Vector3"].Zero();
return _this;
}
FluentMaterial.prototype.needAlphaBlending = function () {
return this.alpha !== 1.0;
};
FluentMaterial.prototype.needAlphaTesting = function () {
return false;
};
FluentMaterial.prototype.getAlphaTestTexture = function () {
return null;
};
FluentMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
if (this.isFrozen) {
if (this._wasPreviouslyReady && subMesh.effect) {
return true;
}
}
if (!subMesh._materialDefines) {
subMesh._materialDefines = new FluentMaterialDefines();
}
var scene = this.getScene();
var defines = subMesh._materialDefines;
if (!this.checkReadyOnEveryCall && subMesh.effect) {
if (defines._renderId === scene.getRenderId()) {
return true;
}
}
if (defines._areTexturesDirty) {
defines.INNERGLOW = this.innerGlowColorIntensity > 0;
defines.BORDER = this.renderBorders;
defines.HOVERLIGHT = this.renderHoverLight;
if (this._albedoTexture) {
if (!this._albedoTexture.isReadyOrNotBlocking()) {
return false;
}
else {
defines.TEXTURE = true;
}
}
else {
defines.TEXTURE = false;
}
}
var engine = scene.getEngine();
// Get correct effect
if (defines.isDirty) {
defines.markAsProcessed();
scene.resetCachedMaterial();
//Attributes
var attribs = [babylonjs_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["VertexBuffer"].PositionKind];
attribs.push(babylonjs_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["VertexBuffer"].NormalKind);
attribs.push(babylonjs_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["VertexBuffer"].UVKind);
var shaderName = "fluent";
var uniforms = ["world", "viewProjection", "innerGlowColor", "albedoColor", "borderWidth", "edgeSmoothingValue", "scaleFactor", "borderMinValue",
"hoverColor", "hoverPosition", "hoverRadius"
];
var samplers = ["albedoSampler"];
var uniformBuffers = new Array();
babylonjs_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["MaterialHelper"].PrepareUniformsAndSamplersList({
uniformsNames: uniforms,
uniformBuffersNames: uniformBuffers,
samplers: samplers,
defines: defines,
maxSimultaneousLights: 4
});
var join = defines.toString();
subMesh.setEffect(scene.getEngine().createEffect(shaderName, {
attributes: attribs,
uniformsNames: uniforms,
uniformBuffersNames: uniformBuffers,
samplers: samplers,
defines: join,
fallbacks: null,
onCompiled: this.onCompiled,
onError: this.onError,
indexParameters: { maxSimultaneousLights: 4 }
}, engine));
}
if (!subMesh.effect || !subMesh.effect.isReady()) {
return false;
}
defines._renderId = scene.getRenderId();
this._wasPreviouslyReady = true;
return true;
};
FluentMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
var scene = this.getScene();
var defines = subMesh._materialDefines;
if (!defines) {
return;
}
var effect = subMesh.effect;
if (!effect) {
return;
}
this._activeEffect = effect;
// Matrices
this.bindOnlyWorldMatrix(world);
this._activeEffect.setMatrix("viewProjection", scene.getTransformMatrix());
if (this._mustRebind(scene, effect)) {
this._activeEffect.setColor4("albedoColor", this.albedoColor, this.alpha);
if (defines.INNERGLOW) {
this._activeEffect.setColor4("innerGlowColor", this.innerGlowColor, this.innerGlowColorIntensity);
}
if (defines.BORDER) {
this._activeEffect.setFloat("borderWidth", this.borderWidth);
this._activeEffect.setFloat("edgeSmoothingValue", this.edgeSmoothingValue);
this._activeEffect.setFloat("borderMinValue", this.borderMinValue);
mesh.getBoundingInfo().boundingBox.extendSize.multiplyToRef(mesh.scaling, babylonjs_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["Tmp"].Vector3[0]);
this._activeEffect.setVector3("scaleFactor", babylonjs_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["Tmp"].Vector3[0]);
}
if (defines.HOVERLIGHT) {
this._activeEffect.setDirectColor4("hoverColor", this.hoverColor);
this._activeEffect.setFloat("hoverRadius", this.hoverRadius);
this._activeEffect.setVector3("hoverPosition", this.hoverPosition);
}
if (defines.TEXTURE) {
this._activeEffect.setTexture("albedoSampler", this._albedoTexture);
}
}
this._afterBind(mesh, this._activeEffect);
};
FluentMaterial.prototype.getActiveTextures = function () {
var activeTextures = _super.prototype.getActiveTextures.call(this);
return activeTextures;
};
FluentMaterial.prototype.hasTexture = function (texture) {
if (_super.prototype.hasTexture.call(this, texture)) {
return true;
}
return false;
};
FluentMaterial.prototype.dispose = function (forceDisposeEffect) {
_super.prototype.dispose.call(this, forceDisposeEffect);
};
FluentMaterial.prototype.clone = function (name) {
var _this = this;
return babylonjs_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["SerializationHelper"].Clone(function () { return new FluentMaterial(name, _this.getScene()); }, this);
};
FluentMaterial.prototype.serialize = function () {
var serializationObject = babylonjs_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["SerializationHelper"].Serialize(this);
serializationObject.customType = "BABYLON.GUI.FluentMaterial";
return serializationObject;
};
FluentMaterial.prototype.getClassName = function () {
return "FluentMaterial";
};
// Statics
FluentMaterial.Parse = function (source, scene, rootUrl) {
return babylonjs_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["SerializationHelper"].Parse(function () { return new FluentMaterial(source.name, scene); }, source, scene, rootUrl);
};
tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([
Object(babylonjs_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])(),
Object(babylonjs_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["expandToProperty"])("_markAllSubMeshesAsTexturesDirty")
], FluentMaterial.prototype, "innerGlowColorIntensity", void 0);
tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([
Object(babylonjs_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serializeAsColor3"])()
], FluentMaterial.prototype, "innerGlowColor", void 0);
tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([
Object(babylonjs_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])()
], FluentMaterial.prototype, "alpha", void 0);
tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([
Object(babylonjs_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serializeAsColor3"])()
], FluentMaterial.prototype, "albedoColor", void 0);
tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([
Object(babylonjs_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])(),
Object(babylonjs_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["expandToProperty"])("_markAllSubMeshesAsTexturesDirty")
], FluentMaterial.prototype, "renderBorders", void 0);
tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([
Object(babylonjs_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])()
], FluentMaterial.prototype, "borderWidth", void 0);
tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([
Object(babylonjs_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])()
], FluentMaterial.prototype, "edgeSmoothingValue", void 0);
tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([
Object(babylonjs_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])()
], FluentMaterial.prototype, "borderMinValue", void 0);
tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([
Object(babylonjs_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])(),
Object(babylonjs_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["expandToProperty"])("_markAllSubMeshesAsTexturesDirty")
], FluentMaterial.prototype, "renderHoverLight", void 0);
tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([
Object(babylonjs_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])()
], FluentMaterial.prototype, "hoverRadius", void 0);
tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([
Object(babylonjs_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serializeAsColor4"])()
], FluentMaterial.prototype, "hoverColor", void 0);
tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([
Object(babylonjs_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serializeAsVector3"])()
], FluentMaterial.prototype, "hoverPosition", void 0);
tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([
Object(babylonjs_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serializeAsTexture"])("albedoTexture")
], FluentMaterial.prototype, "_albedoTexture", void 0);
tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([
Object(babylonjs_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["expandToProperty"])("_markAllSubMeshesAsTexturesAndMiscDirty")
], FluentMaterial.prototype, "albedoTexture", void 0);
return FluentMaterial;
}(babylonjs_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["PushMaterial"]));
babylonjs_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["_TypeStore"].RegisteredTypes["BABYLON.GUI.FluentMaterial"] = FluentMaterial;
/***/ }),
/***/ "./3D/materials/index.ts":
/*!*******************************!*\
!*** ./3D/materials/index.ts ***!
\*******************************/
/*! exports provided: FluentMaterialDefines, FluentMaterial */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var _fluentMaterial__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./fluentMaterial */ "./3D/materials/fluentMaterial.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "FluentMaterialDefines", function() { return _fluentMaterial__WEBPACK_IMPORTED_MODULE_0__["FluentMaterialDefines"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "FluentMaterial", function() { return _fluentMaterial__WEBPACK_IMPORTED_MODULE_0__["FluentMaterial"]; });
/***/ }),
/***/ "./3D/materials/shaders/fluent.fragment.ts":
/*!*************************************************!*\
!*** ./3D/materials/shaders/fluent.fragment.ts ***!
\*************************************************/
/*! exports provided: fluentPixelShader */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "fluentPixelShader", function() { return fluentPixelShader; });
/* harmony import */ var babylonjs_Materials_effect__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! babylonjs/Materials/effect */ "babylonjs/Misc/observable");
/* harmony import */ var babylonjs_Materials_effect__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(babylonjs_Materials_effect__WEBPACK_IMPORTED_MODULE_0__);
var name = 'fluentPixelShader';
var shader = "precision highp float;\nvarying vec2 vUV;\nuniform vec4 albedoColor;\n#ifdef INNERGLOW\nuniform vec4 innerGlowColor;\n#endif\n#ifdef BORDER\nvarying vec2 scaleInfo;\nuniform float edgeSmoothingValue;\nuniform float borderMinValue;\n#endif\n#ifdef HOVERLIGHT\nvarying vec3 worldPosition;\nuniform vec3 hoverPosition;\nuniform vec4 hoverColor;\nuniform float hoverRadius;\n#endif\n#ifdef TEXTURE\nuniform sampler2D albedoSampler;\n#endif\nvoid main(void) {\nvec3 albedo=albedoColor.rgb;\nfloat alpha=albedoColor.a;\n#ifdef TEXTURE\nalbedo=texture2D(albedoSampler,vUV).rgb;\n#endif\n#ifdef HOVERLIGHT\nfloat pointToHover=(1.0-clamp(length(hoverPosition-worldPosition)/hoverRadius,0.,1.))*hoverColor.a;\nalbedo=clamp(albedo+hoverColor.rgb*pointToHover,0.,1.);\n#else\nfloat pointToHover=1.0;\n#endif\n#ifdef BORDER\nfloat borderPower=10.0;\nfloat inverseBorderPower=1.0/borderPower;\nvec3 borderColor=albedo*borderPower;\nvec2 distanceToEdge;\ndistanceToEdge.x=abs(vUV.x-0.5)*2.0;\ndistanceToEdge.y=abs(vUV.y-0.5)*2.0;\nfloat borderValue=max(smoothstep(scaleInfo.x-edgeSmoothingValue,scaleInfo.x+edgeSmoothingValue,distanceToEdge.x),\nsmoothstep(scaleInfo.y-edgeSmoothingValue,scaleInfo.y+edgeSmoothingValue,distanceToEdge.y));\nborderColor=borderColor*borderValue*max(borderMinValue*inverseBorderPower,pointToHover);\nalbedo+=borderColor;\nalpha=max(alpha,borderValue);\n#endif\n#ifdef INNERGLOW\n\nvec2 uvGlow=(vUV-vec2(0.5,0.5))*(innerGlowColor.a*2.0);\nuvGlow=uvGlow*uvGlow;\nuvGlow=uvGlow*uvGlow;\nalbedo+=mix(vec3(0.0,0.0,0.0),innerGlowColor.rgb,uvGlow.x+uvGlow.y);\n#endif\ngl_FragColor=vec4(albedo,alpha);\n}";
babylonjs_Materials_effect__WEBPACK_IMPORTED_MODULE_0__["Effect"].ShadersStore[name] = shader;
/** @hidden */
var fluentPixelShader = { name: name, shader: shader };
/***/ }),
/***/ "./3D/materials/shaders/fluent.vertex.ts":
/*!***********************************************!*\
!*** ./3D/materials/shaders/fluent.vertex.ts ***!
\***********************************************/
/*! exports provided: fluentVertexShader */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "fluentVertexShader", function() { return fluentVertexShader; });
/* harmony import */ var babylonjs_Materials_effect__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! babylonjs/Materials/effect */ "babylonjs/Misc/observable");
/* harmony import */ var babylonjs_Materials_effect__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(babylonjs_Materials_effect__WEBPACK_IMPORTED_MODULE_0__);
var name = 'fluentVertexShader';
var shader = "precision highp float;\n\nattribute vec3 position;\nattribute vec3 normal;\nattribute vec2 uv;\n\nuniform mat4 world;\nuniform mat4 viewProjection;\nvarying vec2 vUV;\n#ifdef BORDER\nvarying vec2 scaleInfo;\nuniform float borderWidth;\nuniform vec3 scaleFactor;\n#endif\n#ifdef HOVERLIGHT\nvarying vec3 worldPosition;\n#endif\nvoid main(void) {\nvUV=uv;\n#ifdef BORDER\nvec3 scale=scaleFactor;\nfloat minScale=min(min(scale.x,scale.y),scale.z);\nfloat maxScale=max(max(scale.x,scale.y),scale.z);\nfloat minOverMiddleScale=minScale/(scale.x+scale.y+scale.z-minScale-maxScale);\nfloat areaYZ=scale.y*scale.z;\nfloat areaXZ=scale.x*scale.z;\nfloat areaXY=scale.x*scale.y;\nfloat scaledBorderWidth=borderWidth;\nif (abs(normal.x) == 1.0)\n{\nscale.x=scale.y;\nscale.y=scale.z;\nif (areaYZ>areaXZ && areaYZ>areaXY)\n{\nscaledBorderWidth*=minOverMiddleScale;\n}\n}\nelse if (abs(normal.y) == 1.0)\n{\nscale.x=scale.z;\nif (areaXZ>areaXY && areaXZ>areaYZ)\n{\nscaledBorderWidth*=minOverMiddleScale;\n}\n}\nelse\n{\nif (areaXY>areaYZ && areaXY>areaXZ)\n{\nscaledBorderWidth*=minOverMiddleScale;\n}\n}\nfloat scaleRatio=min(scale.x,scale.y)/max(scale.x,scale.y);\nif (scale.x>scale.y)\n{\nscaleInfo.x=1.0-(scaledBorderWidth*scaleRatio);\nscaleInfo.y=1.0-scaledBorderWidth;\n}\nelse\n{\nscaleInfo.x=1.0-scaledBorderWidth;\nscaleInfo.y=1.0-(scaledBorderWidth*scaleRatio);\n}\n#endif\nvec4 worldPos=world*vec4(position,1.0);\n#ifdef HOVERLIGHT\nworldPosition=worldPos.xyz;\n#endif\ngl_Position=viewProjection*worldPos;\n}\n";
babylonjs_Materials_effect__WEBPACK_IMPORTED_MODULE_0__["Effect"].ShadersStore[name] = shader;
/** @hidden */
var fluentVertexShader = { name: name, shader: shader };
/***/ }),
/***/ "./3D/vector3WithInfo.ts":
/*!*******************************!*\
!*** ./3D/vector3WithInfo.ts ***!
\*******************************/
/*! exports provided: Vector3WithInfo */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Vector3WithInfo", function() { return Vector3WithInfo; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../../node_modules/tslib/tslib.es6.js");
/* harmony import */ var babylonjs_Maths_math__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! babylonjs/Maths/math */ "babylonjs/Misc/observable");
/* harmony import */ var babylonjs_Maths_math__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(babylonjs_Maths_math__WEBPACK_IMPORTED_MODULE_1__);
/**
* Class used to transport Vector3 information for pointer events
*/
var Vector3WithInfo = /** @class */ (function (_super) {
tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](Vector3WithInfo, _super);
/**
* Creates a new Vector3WithInfo
* @param source defines the vector3 data to transport
* @param buttonIndex defines the current mouse button index
*/
function Vector3WithInfo(source,
/** defines the current mouse button index */
buttonIndex) {
if (buttonIndex === void 0) { buttonIndex = 0; }
var _this = _super.call(this, source.x, source.y, source.z) || this;
_this.buttonIndex = buttonIndex;
return _this;
}
return Vector3WithInfo;
}(babylonjs_Maths_math__WEBPACK_IMPORTED_MODULE_1__["Vector3"]));
/***/ }),
/***/ "./index.ts":
/*!******************!*\
!*** ./index.ts ***!
\******************/
/*! exports provided: AdvancedDynamicTexture, AdvancedDynamicTextureInstrumentation, Vector2WithInfo, Matrix2D, Measure, MultiLinePoint, Style, ValueAndUnit, GUI3DManager, Vector3WithInfo, Button, Checkbox, ColorPicker, Container, Control, Ellipse, Grid, Image, InputText, InputPassword, Line, MultiLine, RadioButton, StackPanel, SelectorGroup, CheckboxGroup, RadioGroup, SliderGroup, SelectionPanel, ScrollViewer, TextWrapping, TextBlock, KeyPropertySet, VirtualKeyboard, Rectangle, DisplayGrid, BaseSlider, Slider, ImageBasedSlider, ScrollBar, name, AbstractButton3D, Button3D, Container3D, Control3D, CylinderPanel, HolographicButton, MeshButton3D, PlanePanel, ScatterPanel, SpherePanel, StackPanel3D, VolumeBasedPanel, FluentMaterialDefines, FluentMaterial */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var _2D__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./2D */ "./2D/index.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "AdvancedDynamicTexture", function() { return _2D__WEBPACK_IMPORTED_MODULE_0__["AdvancedDynamicTexture"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "AdvancedDynamicTextureInstrumentation", function() { return _2D__WEBPACK_IMPORTED_MODULE_0__["AdvancedDynamicTextureInstrumentation"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Vector2WithInfo", function() { return _2D__WEBPACK_IMPORTED_MODULE_0__["Vector2WithInfo"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Matrix2D", function() { return _2D__WEBPACK_IMPORTED_MODULE_0__["Matrix2D"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Measure", function() { return _2D__WEBPACK_IMPORTED_MODULE_0__["Measure"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "MultiLinePoint", function() { return _2D__WEBPACK_IMPORTED_MODULE_0__["MultiLinePoint"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Style", function() { return _2D__WEBPACK_IMPORTED_MODULE_0__["Style"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ValueAndUnit", function() { return _2D__WEBPACK_IMPORTED_MODULE_0__["ValueAndUnit"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Button", function() { return _2D__WEBPACK_IMPORTED_MODULE_0__["Button"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Checkbox", function() { return _2D__WEBPACK_IMPORTED_MODULE_0__["Checkbox"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ColorPicker", function() { return _2D__WEBPACK_IMPORTED_MODULE_0__["ColorPicker"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Container", function() { return _2D__WEBPACK_IMPORTED_MODULE_0__["Container"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Control", function() { return _2D__WEBPACK_IMPORTED_MODULE_0__["Control"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Ellipse", function() { return _2D__WEBPACK_IMPORTED_MODULE_0__["Ellipse"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Grid", function() { return _2D__WEBPACK_IMPORTED_MODULE_0__["Grid"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Image", function() { return _2D__WEBPACK_IMPORTED_MODULE_0__["Image"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "InputText", function() { return _2D__WEBPACK_IMPORTED_MODULE_0__["InputText"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "InputPassword", function() { return _2D__WEBPACK_IMPORTED_MODULE_0__["InputPassword"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Line", function() { return _2D__WEBPACK_IMPORTED_MODULE_0__["Line"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "MultiLine", function() { return _2D__WEBPACK_IMPORTED_MODULE_0__["MultiLine"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "RadioButton", function() { return _2D__WEBPACK_IMPORTED_MODULE_0__["RadioButton"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "StackPanel", function() { return _2D__WEBPACK_IMPORTED_MODULE_0__["StackPanel"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "SelectorGroup", function() { return _2D__WEBPACK_IMPORTED_MODULE_0__["SelectorGroup"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "CheckboxGroup", function() { return _2D__WEBPACK_IMPORTED_MODULE_0__["CheckboxGroup"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "RadioGroup", function() { return _2D__WEBPACK_IMPORTED_MODULE_0__["RadioGroup"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "SliderGroup", function() { return _2D__WEBPACK_IMPORTED_MODULE_0__["SliderGroup"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "SelectionPanel", function() { return _2D__WEBPACK_IMPORTED_MODULE_0__["SelectionPanel"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ScrollViewer", function() { return _2D__WEBPACK_IMPORTED_MODULE_0__["ScrollViewer"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "TextWrapping", function() { return _2D__WEBPACK_IMPORTED_MODULE_0__["TextWrapping"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "TextBlock", function() { return _2D__WEBPACK_IMPORTED_MODULE_0__["TextBlock"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "KeyPropertySet", function() { return _2D__WEBPACK_IMPORTED_MODULE_0__["KeyPropertySet"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "VirtualKeyboard", function() { return _2D__WEBPACK_IMPORTED_MODULE_0__["VirtualKeyboard"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Rectangle", function() { return _2D__WEBPACK_IMPORTED_MODULE_0__["Rectangle"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "DisplayGrid", function() { return _2D__WEBPACK_IMPORTED_MODULE_0__["DisplayGrid"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "BaseSlider", function() { return _2D__WEBPACK_IMPORTED_MODULE_0__["BaseSlider"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Slider", function() { return _2D__WEBPACK_IMPORTED_MODULE_0__["Slider"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ImageBasedSlider", function() { return _2D__WEBPACK_IMPORTED_MODULE_0__["ImageBasedSlider"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ScrollBar", function() { return _2D__WEBPACK_IMPORTED_MODULE_0__["ScrollBar"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "name", function() { return _2D__WEBPACK_IMPORTED_MODULE_0__["name"]; });
/* harmony import */ var _3D__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./3D */ "./3D/index.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "GUI3DManager", function() { return _3D__WEBPACK_IMPORTED_MODULE_1__["GUI3DManager"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Vector3WithInfo", function() { return _3D__WEBPACK_IMPORTED_MODULE_1__["Vector3WithInfo"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "AbstractButton3D", function() { return _3D__WEBPACK_IMPORTED_MODULE_1__["AbstractButton3D"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Button3D", function() { return _3D__WEBPACK_IMPORTED_MODULE_1__["Button3D"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Container3D", function() { return _3D__WEBPACK_IMPORTED_MODULE_1__["Container3D"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Control3D", function() { return _3D__WEBPACK_IMPORTED_MODULE_1__["Control3D"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "CylinderPanel", function() { return _3D__WEBPACK_IMPORTED_MODULE_1__["CylinderPanel"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "HolographicButton", function() { return _3D__WEBPACK_IMPORTED_MODULE_1__["HolographicButton"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "MeshButton3D", function() { return _3D__WEBPACK_IMPORTED_MODULE_1__["MeshButton3D"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "PlanePanel", function() { return _3D__WEBPACK_IMPORTED_MODULE_1__["PlanePanel"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ScatterPanel", function() { return _3D__WEBPACK_IMPORTED_MODULE_1__["ScatterPanel"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "SpherePanel", function() { return _3D__WEBPACK_IMPORTED_MODULE_1__["SpherePanel"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "StackPanel3D", function() { return _3D__WEBPACK_IMPORTED_MODULE_1__["StackPanel3D"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "VolumeBasedPanel", function() { return _3D__WEBPACK_IMPORTED_MODULE_1__["VolumeBasedPanel"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "FluentMaterialDefines", function() { return _3D__WEBPACK_IMPORTED_MODULE_1__["FluentMaterialDefines"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "FluentMaterial", function() { return _3D__WEBPACK_IMPORTED_MODULE_1__["FluentMaterial"]; });
/***/ }),
/***/ "./legacy/legacy.ts":
/*!**************************!*\
!*** ./legacy/legacy.ts ***!
\**************************/
/*! exports provided: AdvancedDynamicTexture, AdvancedDynamicTextureInstrumentation, Vector2WithInfo, Matrix2D, Measure, MultiLinePoint, Style, ValueAndUnit, GUI3DManager, Vector3WithInfo, Button, Checkbox, ColorPicker, Container, Control, Ellipse, Grid, Image, InputText, InputPassword, Line, MultiLine, RadioButton, StackPanel, SelectorGroup, CheckboxGroup, RadioGroup, SliderGroup, SelectionPanel, ScrollViewer, TextWrapping, TextBlock, KeyPropertySet, VirtualKeyboard, Rectangle, DisplayGrid, BaseSlider, Slider, ImageBasedSlider, ScrollBar, name, AbstractButton3D, Button3D, Container3D, Control3D, CylinderPanel, HolographicButton, MeshButton3D, PlanePanel, ScatterPanel, SpherePanel, StackPanel3D, VolumeBasedPanel, FluentMaterialDefines, FluentMaterial */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* WEBPACK VAR INJECTION */(function(global) {/* harmony import */ var _index__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../index */ "./index.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "AdvancedDynamicTexture", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["AdvancedDynamicTexture"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "AdvancedDynamicTextureInstrumentation", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["AdvancedDynamicTextureInstrumentation"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Vector2WithInfo", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["Vector2WithInfo"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Matrix2D", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["Matrix2D"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Measure", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["Measure"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "MultiLinePoint", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["MultiLinePoint"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Style", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["Style"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ValueAndUnit", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["ValueAndUnit"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "GUI3DManager", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["GUI3DManager"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Vector3WithInfo", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["Vector3WithInfo"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Button", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["Button"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Checkbox", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["Checkbox"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ColorPicker", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["ColorPicker"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Container", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["Container"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Control", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["Control"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Ellipse", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["Ellipse"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Grid", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["Grid"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Image", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["Image"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "InputText", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["InputText"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "InputPassword", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["InputPassword"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Line", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["Line"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "MultiLine", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["MultiLine"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "RadioButton", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["RadioButton"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "StackPanel", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["StackPanel"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "SelectorGroup", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["SelectorGroup"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "CheckboxGroup", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["CheckboxGroup"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "RadioGroup", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["RadioGroup"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "SliderGroup", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["SliderGroup"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "SelectionPanel", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["SelectionPanel"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ScrollViewer", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["ScrollViewer"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "TextWrapping", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["TextWrapping"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "TextBlock", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["TextBlock"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "KeyPropertySet", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["KeyPropertySet"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "VirtualKeyboard", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["VirtualKeyboard"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Rectangle", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["Rectangle"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "DisplayGrid", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["DisplayGrid"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "BaseSlider", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["BaseSlider"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Slider", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["Slider"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ImageBasedSlider", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["ImageBasedSlider"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ScrollBar", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["ScrollBar"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "name", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["name"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "AbstractButton3D", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["AbstractButton3D"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Button3D", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["Button3D"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Container3D", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["Container3D"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Control3D", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["Control3D"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "CylinderPanel", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["CylinderPanel"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "HolographicButton", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["HolographicButton"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "MeshButton3D", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["MeshButton3D"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "PlanePanel", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["PlanePanel"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ScatterPanel", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["ScatterPanel"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "SpherePanel", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["SpherePanel"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "StackPanel3D", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["StackPanel3D"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "VolumeBasedPanel", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["VolumeBasedPanel"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "FluentMaterialDefines", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["FluentMaterialDefines"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "FluentMaterial", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["FluentMaterial"]; });
/**
* Legacy support, defining window.BABYLON.GUI (global variable).
*
* This is the entry point for the UMD module.
* The entry point for a future ESM package should be index.ts
*/
var globalObject = (typeof global !== 'undefined') ? global : ((typeof window !== 'undefined') ? window : undefined);
if (typeof globalObject !== "undefined") {
globalObject.BABYLON = globalObject.BABYLON || {};
globalObject.BABYLON.GUI = _index__WEBPACK_IMPORTED_MODULE_0__;
}
/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(/*! ./../../../node_modules/webpack/buildin/global.js */ "../../node_modules/webpack/buildin/global.js")))
/***/ }),
/***/ "babylonjs/Misc/observable":
/*!****************************************************************************************************!*\
!*** external {"root":"BABYLON","commonjs":"babylonjs","commonjs2":"babylonjs","amd":"babylonjs"} ***!
\****************************************************************************************************/
/*! no static exports found */
/***/ (function(module, exports) {
module.exports = __WEBPACK_EXTERNAL_MODULE_babylonjs_Misc_observable__;
/***/ })
/******/ });
});
//# sourceMappingURL=babylon.gui.js.map |
module.exports = {
siteMetadata: {
title: `Koray Ece`,
description: `Kick off your next, great Gatsby project with this default starter. This barebones starter ships with the main Gatsby configuration files you might need.`,
author: `@gatsbyjs`,
},
plugins: [
`gatsby-plugin-react-helmet`,
{
resolve: `gatsby-source-filesystem`,
options: {
name: `images`,
path: `${__dirname}/src/images`,
},
},
`gatsby-transformer-sharp`,
`gatsby-plugin-sharp`,
{
resolve: `gatsby-plugin-manifest`,
options: {
name: `gatsby-starter-default`,
short_name: `starter`,
start_url: `/`,
background_color: `#663399`,
theme_color: `#663399`,
display: `minimal-ui`,
icon: `src/images/gatsby-icon.png`, // This path is relative to the root of the site.
},
},
// this (optional) plugin enables Progressive Web App + Offline functionality
// To learn more, visit: https://gatsby.dev/offline
// 'gatsby-plugin-offline',
],
}
|
import React from "react";
import ResetPassword from "../Auths/ResetPassword";
import { MemoryRouter } from "react-router-dom";
describe("ResetPassword component", () => {
it("should render the form", () => {
const wrapper = mount(
<MemoryRouter>
<ResetPassword />
</MemoryRouter>
);
expect(wrapper.exists("[className=\"field\"]")).to.equal(true);
});
it("should be able to click submit", () => {
const wrapper = mount(
<MemoryRouter>
<ResetPassword />
</MemoryRouter>
);
const button = wrapper.find("button");
button.simulate("click");
});
}); |
'use strict'
const http = require('http')
const { proxy: forward } = require('fast-proxy')({
base: 'http://127.0.0.1:3000/',
undici: {
connections: 100,
pipelining: 10
}
})
const proxy = http.createServer((req, res) => {
forward(req, res, req.url, {
rewriteRequestHeaders (req, headers) {
delete headers.connection
return headers
}
})
})
proxy.listen(8080)
|
# Names scores
# Problem 22
# Using names.txt (right click and 'Save Link/Target As...'), a 46K text file containing over five-thousand first
# names, begin by sorting it into alphabetical order. Then working out the alphabetical value for each name,
# multiply this value by its alphabetical position in the list to obtain a name score.
#
# For example, when the list is sorted into alphabetical order, COLIN, which is worth 3 + 15 + 12 + 9 + 14 = 53,
# is the 938th name in the list. So, COLIN would obtain a score of 938 × 53 = 49714.
#
# What is the total of all the name scores in the file?
import string
with open('p022_names.txt', 'r') as f:
INPUT = f.readline()
NAME_LIST = INPUT.replace('"', '').split(',')
NAME_LIST.sort()
alphabetical_pos = ((string.ascii_uppercase.index(c) + 1 for c in name) for name in NAME_LIST)
sums = map(sum, alphabetical_pos)
sums_x_pos = ((index + 1) * value for index, value in enumerate(sums))
print(sum(sums_x_pos))
|
# Copyright 2013-2022 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)
from spack.package import *
class Comd(MakefilePackage):
"""CoMD is a reference implementation of classical molecular dynamics
algorithms and workloads as used in materials science. It is created and
maintained by The Exascale Co-Design Center for Materials in Extreme
Environments (ExMatEx). The code is intended to serve as a vehicle for
co-design by allowing others to extend and/or reimplement it as needed to
test performance of new architectures, programming models, etc. New
versions of CoMD will be released to incorporate the lessons learned from
the co-design process."""
tags = ['proxy-app']
homepage = "http://www.exmatex.org/comd.html"
url = "https://github.com/ECP-copa/CoMD/archive/v1.1.tar.gz"
git = "https://github.com/ECP-copa/CoMD.git"
version('develop', branch='master')
version('1.1', sha256='4e85f86f043681a1ef72940fc24a4c71356a36afa45446f7cfe776abad6aa252')
variant('mpi', default=True, description='Build with MPI support')
variant('openmp', default=False, description='Build with OpenMP support')
variant('precision', default=True, description='Toggle Precesion Options')
variant('graphs', default=False, description='Enable graph visuals')
depends_on('mpi', when='+mpi')
depends_on('graphviz', when='+graphs')
conflicts('+openmp', when='+mpi')
def edit(self, spec, prefix):
with working_dir('src-mpi') or working_dir('src-openmp'):
copy('Makefile.vanilla', 'Makefile')
@property
def build_targets(self):
targets = []
cflags = ' -std=c99 '
optflags = ' -g -O5 '
clib = ' -lm '
comd_variant = 'CoMD'
cc = spack_cc
if '+openmp' in self.spec:
targets.append('--directory=src-openmp')
comd_variant += '-openmp'
cflags += ' -fopenmp '
if '+mpi' in self.spec:
comd_variant += '-mpi'
targets.append('CC = {0}'.format(self.spec['mpi'].mpicc))
else:
targets.append('CC = {0}'.format('spack_cc'))
else:
targets.append('--directory=src-mpi')
if '~mpi' in self.spec:
comd_variant += '-serial'
targets.append('CC = {0}'.format(cc))
else:
comd_variant += '-mpi'
targets.append('CC = {0}'.format(self.spec['mpi'].mpicc))
if '+mpi' in self.spec:
cflags += '-DDO_MPI'
targets.append(
'INCLUDES = {0}'.format(self.spec['mpi'].prefix.include))
if '+precision' in self.spec:
cflags += ' -DDOUBLE '
else:
cflags += ' -DSINGLE '
targets.append('CoMD_VARIANT = {0}'.format(comd_variant))
targets.append('CFLAGS = {0}'.format(cflags))
targets.append('OPTFLAGS = {0}'.format(optflags))
targets.append('C_LIB = {0}'.format(clib))
return targets
def install(self, spec, prefix):
install_tree('bin', prefix.bin)
install_tree('examples', prefix.examples)
install_tree('pots', prefix.pots)
mkdirp(prefix.doc)
install('README.md', prefix.doc)
install('LICENSE.md', prefix.doc)
|
function toggle(div_id) {
var el = document.getElementById(div_id);
if ( el.style.display == 'none' ) { el.style.display = 'block';}
else {el.style.display = 'none';}
}
function blanket_size(popUpDivVar) {
if (typeof window.innerWidth != 'undefined') {
viewportheight = window.innerHeight;
} else {
viewportheight = document.documentElement.clientHeight;
}
if ((viewportheight > document.body.parentNode.scrollHeight) && (viewportheight > document.body.parentNode.clientHeight)) {
blanket_height = viewportheight;
} else {
if (document.body.parentNode.clientHeight > document.body.parentNode.scrollHeight) {
blanket_height = document.body.parentNode.clientHeight;
} else {
blanket_height = document.body.parentNode.scrollHeight;
}
}
var blanket = document.getElementById('blanket');
blanket.style.height = blanket_height + 'px';
var popUpDiv = document.getElementById(popUpDivVar);
popUpDiv_height=blanket_height/2-300;//100 is half popup's height
popUpDiv.style.top = popUpDiv_height + 'px';
}
function window_pos(popUpDivVar) {
if (typeof window.innerWidth != 'undefined') {
viewportwidth = window.innerHeight;
} else {
viewportwidth = document.documentElement.clientHeight;
}
if ((viewportwidth > document.body.parentNode.scrollWidth) && (viewportwidth > document.body.parentNode.clientWidth)) {
window_width = viewportwidth;
} else {
if (document.body.parentNode.clientWidth > document.body.parentNode.scrollWidth) {
window_width = document.body.parentNode.clientWidth;
} else {
window_width = document.body.parentNode.scrollWidth;
}
}
var popUpDiv = document.getElementById(popUpDivVar);
window_width=window_width/2-200;//200 is half popup's width
popUpDiv.style.left = window_width + 'px';
}
function popup(windowname) {
blanket_size(windowname);
window_pos(windowname);
toggle('blanket');
toggle(windowname);
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.